Clang Project

clang_source_code/lib/Sema/SemaOverload.cpp
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/Overload.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeOrdering.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/Optional.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include <algorithm>
36#include <cstdlib>
37
38using namespace clang;
39using namespace sema;
40
41static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42  return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43    return P->hasAttr<PassObjectSizeAttr>();
44  });
45}
46
47/// A convenience routine for creating a decayed reference to a function.
48static ExprResult
49CreateFunctionRefExpr(Sema &SFunctionDecl *FnNamedDecl *FoundDecl,
50                      const Expr *Basebool HadMultipleCandidates,
51                      SourceLocation Loc = SourceLocation(),
52                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53  if (S.DiagnoseUseOfDecl(FoundDeclLoc))
54    return ExprError();
55  // If FoundDecl is different from Fn (such as if one is a template
56  // and the other a specialization), make sure DiagnoseUseOfDecl is
57  // called on both.
58  // FIXME: This would be more comprehensively addressed by modifying
59  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60  // being used.
61  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(FnLoc))
62    return ExprError();
63  if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64    S.ResolveExceptionSpec(Loc, FPT);
65  DeclRefExpr *DRE = new (S.Context)
66      DeclRefExpr(S.ContextFnfalseFn->getType(), VK_LValueLocLocInfo);
67  if (HadMultipleCandidates)
68    DRE->setHadMultipleCandidates(true);
69
70  S.MarkDeclRefReferenced(DREBase);
71  return S.ImpCastExprToType(DRES.Context.getPointerType(DRE->getType()),
72                             CK_FunctionToPointerDecay);
73}
74
75static bool IsStandardConversion(Sema &SExprFromQualType ToType,
76                                 bool InOverloadResolution,
77                                 StandardConversionSequence &SCS,
78                                 bool CStyle,
79                                 bool AllowObjCWritebackConversion);
80
81static bool IsTransparentUnionStandardConversion(Sema &SExprFrom,
82                                                 QualType &ToType,
83                                                 bool InOverloadResolution,
84                                                 StandardConversionSequence &SCS,
85                                                 bool CStyle);
86static OverloadingResult
87IsUserDefinedConversion(Sema &SExpr *FromQualType ToType,
88                        UserDefinedConversionSequenceUser,
89                        OverloadCandidateSetConversions,
90                        bool AllowExplicit,
91                        bool AllowObjCConversionOnExplicit);
92
93
94static ImplicitConversionSequence::CompareKind
95CompareStandardConversionSequences(Sema &SSourceLocation Loc,
96                                   const StandardConversionSequenceSCS1,
97                                   const StandardConversionSequenceSCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareQualificationConversions(Sema &S,
101                                const StandardConversionSequenceSCS1,
102                                const StandardConversionSequenceSCS2);
103
104static ImplicitConversionSequence::CompareKind
105CompareDerivedToBaseConversions(Sema &SSourceLocation Loc,
106                                const StandardConversionSequenceSCS1,
107                                const StandardConversionSequenceSCS2);
108
109/// GetConversionRank - Retrieve the implicit conversion rank
110/// corresponding to the given implicit conversion kind.
111ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112  static const ImplicitConversionRank
113    Rank[(int)ICK_Num_Conversion_Kinds] = {
114    ICR_Exact_Match,
115    ICR_Exact_Match,
116    ICR_Exact_Match,
117    ICR_Exact_Match,
118    ICR_Exact_Match,
119    ICR_Exact_Match,
120    ICR_Promotion,
121    ICR_Promotion,
122    ICR_Promotion,
123    ICR_Conversion,
124    ICR_Conversion,
125    ICR_Conversion,
126    ICR_Conversion,
127    ICR_Conversion,
128    ICR_Conversion,
129    ICR_Conversion,
130    ICR_Conversion,
131    ICR_Conversion,
132    ICR_Conversion,
133    ICR_OCL_Scalar_Widening,
134    ICR_Complex_Real_Conversion,
135    ICR_Conversion,
136    ICR_Conversion,
137    ICR_Writeback_Conversion,
138    ICR_Exact_Match// NOTE(gbiv): This may not be completely right --
139                     // it was omitted by the patch that added
140                     // ICK_Zero_Event_Conversion
141    ICR_C_Conversion,
142    ICR_C_Conversion_Extension
143  };
144  return Rank[(int)Kind];
145}
146
147/// GetImplicitConversionName - Return the name of this kind of
148/// implicit conversion.
149static const charGetImplicitConversionName(ImplicitConversionKind Kind) {
150  static const charconst Name[(int)ICK_Num_Conversion_Kinds] = {
151    "No conversion",
152    "Lvalue-to-rvalue",
153    "Array-to-pointer",
154    "Function-to-pointer",
155    "Function pointer conversion",
156    "Qualification",
157    "Integral promotion",
158    "Floating point promotion",
159    "Complex promotion",
160    "Integral conversion",
161    "Floating conversion",
162    "Complex conversion",
163    "Floating-integral conversion",
164    "Pointer conversion",
165    "Pointer-to-member conversion",
166    "Boolean conversion",
167    "Compatible-types conversion",
168    "Derived-to-base conversion",
169    "Vector conversion",
170    "Vector splat",
171    "Complex-real conversion",
172    "Block Pointer conversion",
173    "Transparent Union Conversion",
174    "Writeback conversion",
175    "OpenCL Zero Event Conversion",
176    "C specific type conversion",
177    "Incompatible pointer conversion"
178  };
179  return Name[Kind];
180}
181
182/// StandardConversionSequence - Set the standard conversion
183/// sequence to the identity conversion.
184void StandardConversionSequence::setAsIdentityConversion() {
185  First = ICK_Identity;
186  Second = ICK_Identity;
187  Third = ICK_Identity;
188  DeprecatedStringLiteralToCharPtr = false;
189  QualificationIncludesObjCLifetime = false;
190  ReferenceBinding = false;
191  DirectBinding = false;
192  IsLvalueReference = true;
193  BindsToFunctionLvalue = false;
194  BindsToRvalue = false;
195  BindsImplicitObjectArgumentWithoutRefQualifier = false;
196  ObjCLifetimeConversionBinding = false;
197  CopyConstructor = nullptr;
198}
199
200/// getRank - Retrieve the rank of this standard conversion sequence
201/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202/// implicit conversions.
203ImplicitConversionRank StandardConversionSequence::getRank() const {
204  ImplicitConversionRank Rank = ICR_Exact_Match;
205  if  (GetConversionRank(First) > Rank)
206    Rank = GetConversionRank(First);
207  if  (GetConversionRank(Second) > Rank)
208    Rank = GetConversionRank(Second);
209  if  (GetConversionRank(Third) > Rank)
210    Rank = GetConversionRank(Third);
211  return Rank;
212}
213
214/// isPointerConversionToBool - Determines whether this conversion is
215/// a conversion of a pointer or pointer-to-member to bool. This is
216/// used as part of the ranking of standard conversion sequences
217/// (C++ 13.3.3.2p4).
218bool StandardConversionSequence::isPointerConversionToBool() const {
219  // Note that FromType has not necessarily been transformed by the
220  // array-to-pointer or function-to-pointer implicit conversions, so
221  // check for their presence as well as checking whether FromType is
222  // a pointer.
223  if (getToType(1)->isBooleanType() &&
224      (getFromType()->isPointerType() ||
225       getFromType()->isMemberPointerType() ||
226       getFromType()->isObjCObjectPointerType() ||
227       getFromType()->isBlockPointerType() ||
228       getFromType()->isNullPtrType() ||
229       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230    return true;
231
232  return false;
233}
234
235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
239bool
240StandardConversionSequence::
241isPointerConversionToVoidPointer(ASTContextContextconst {
242  QualType FromType = getFromType();
243  QualType ToType = getToType(1);
244
245  // Note that FromType has not necessarily been transformed by the
246  // array-to-pointer implicit conversion, so check for its presence
247  // and redo the conversion to get a pointer.
248  if (First == ICK_Array_To_Pointer)
249    FromType = Context.getArrayDecayedType(FromType);
250
251  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252    if (const PointerTypeToPtrType = ToType->getAs<PointerType>())
253      return ToPtrType->getPointeeType()->isVoidType();
254
255  return false;
256}
257
258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262    switch (ICE->getCastKind()) {
263    case CK_NoOp:
264    case CK_IntegralCast:
265    case CK_IntegralToBoolean:
266    case CK_IntegralToFloating:
267    case CK_BooleanToSignedIntegral:
268    case CK_FloatingToIntegral:
269    case CK_FloatingToBoolean:
270    case CK_FloatingCast:
271      Converted = ICE->getSubExpr();
272      continue;
273
274    default:
275      return Converted;
276    }
277  }
278
279  return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx  The AST context.
286/// \param Converted  The result of applying this standard conversion sequence.
287/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288///        value of the expression prior to the narrowing conversion.
289/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290///        type of the expression prior to the narrowing conversion.
291/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292///        from floating point types to integral types should be ignored.
293NarrowingKind StandardConversionSequence::getNarrowingKind(
294    ASTContext &Ctxconst Expr *ConvertedAPValue &ConstantValue,
295    QualType &ConstantTypebool IgnoreFloatToIntegralConversionconst {
296   (0) . __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 296, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297
298  // C++11 [dcl.init.list]p7:
299  //   A narrowing conversion is an implicit conversion ...
300  QualType FromType = getToType(0);
301  QualType ToType = getToType(1);
302
303  // A conversion to an enumeration type is narrowing if the conversion to
304  // the underlying type is narrowing. This only arises for expressions of
305  // the form 'Enum{init}'.
306  if (auto *ET = ToType->getAs<EnumType>())
307    ToType = ET->getDecl()->getIntegerType();
308
309  switch (Second) {
310  // 'bool' is an integral type; dispatch to the right place to handle it.
311  case ICK_Boolean_Conversion:
312    if (FromType->isRealFloatingType())
313      goto FloatingIntegralConversion;
314    if (FromType->isIntegralOrUnscopedEnumerationType())
315      goto IntegralConversion;
316    // Boolean conversions can be from pointers and pointers to members
317    // [conv.bool], and those aren't considered narrowing conversions.
318    return NK_Not_Narrowing;
319
320  // -- from a floating-point type to an integer type, or
321  //
322  // -- from an integer type or unscoped enumeration type to a floating-point
323  //    type, except where the source is a constant expression and the actual
324  //    value after conversion will fit into the target type and will produce
325  //    the original value when converted back to the original type, or
326  case ICK_Floating_Integral:
327  FloatingIntegralConversion:
328    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329      return NK_Type_Narrowing;
330    } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331               ToType->isRealFloatingType()) {
332      if (IgnoreFloatToIntegralConversion)
333        return NK_Not_Narrowing;
334      llvm::APSInt IntConstantValue;
335      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       (0) . __assert_fail ("Initializer && \"Unknown conversion expression\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 336, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Initializer && "Unknown conversion expression");
337
338      // If it's value-dependent, we can't tell whether it's narrowing.
339      if (Initializer->isValueDependent())
340        return NK_Dependent_Narrowing;
341
342      if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343        // Convert the integer to the floating type.
344        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                llvm::APFloat::rmNearestTiesToEven);
347        // And back.
348        llvm::APSInt ConvertedValue = IntConstantValue;
349        bool ignored;
350        Result.convertToInteger(ConvertedValue,
351                                llvm::APFloat::rmTowardZero, &ignored);
352        // If the resulting value is different, this was a narrowing conversion.
353        if (IntConstantValue != ConvertedValue) {
354          ConstantValue = APValue(IntConstantValue);
355          ConstantType = Initializer->getType();
356          return NK_Constant_Narrowing;
357        }
358      } else {
359        // Variables are always narrowings.
360        return NK_Variable_Narrowing;
361      }
362    }
363    return NK_Not_Narrowing;
364
365  // -- from long double to double or float, or from double to float, except
366  //    where the source is a constant expression and the actual value after
367  //    conversion is within the range of values that can be represented (even
368  //    if it cannot be represented exactly), or
369  case ICK_Floating_Conversion:
370    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371        Ctx.getFloatingTypeOrder(FromTypeToType) == 1) {
372      // FromType is larger than ToType.
373      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374
375      // If it's value-dependent, we can't tell whether it's narrowing.
376      if (Initializer->isValueDependent())
377        return NK_Dependent_Narrowing;
378
379      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380        // Constant!
381        assert(ConstantValue.isFloat());
382        llvm::APFloat FloatVal = ConstantValue.getFloat();
383        // Convert the source value into the target type.
384        bool ignored;
385        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386          Ctx.getFloatTypeSemantics(ToType),
387          llvm::APFloat::rmNearestTiesToEven, &ignored);
388        // If there was no overflow, the source value is within the range of
389        // values that can be represented.
390        if (ConvertStatus & llvm::APFloat::opOverflow) {
391          ConstantType = Initializer->getType();
392          return NK_Constant_Narrowing;
393        }
394      } else {
395        return NK_Variable_Narrowing;
396      }
397    }
398    return NK_Not_Narrowing;
399
400  // -- from an integer type or unscoped enumeration type to an integer type
401  //    that cannot represent all the values of the original type, except where
402  //    the source is a constant expression and the actual value after
403  //    conversion will fit into the target type and will produce the original
404  //    value when converted back to the original type.
405  case ICK_Integral_Conversion:
406  IntegralConversion: {
407    isIntegralOrUnscopedEnumerationType()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 407, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FromType->isIntegralOrUnscopedEnumerationType());
408    isIntegralOrUnscopedEnumerationType()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 408, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ToType->isIntegralOrUnscopedEnumerationType());
409    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410    const unsigned FromWidth = Ctx.getIntWidth(FromType);
411    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412    const unsigned ToWidth = Ctx.getIntWidth(ToType);
413
414    if (FromWidth > ToWidth ||
415        (FromWidth == ToWidth && FromSigned != ToSigned) ||
416        (FromSigned && !ToSigned)) {
417      // Not all values of FromType can be represented in ToType.
418      llvm::APSInt InitializerValue;
419      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420
421      // If it's value-dependent, we can't tell whether it's narrowing.
422      if (Initializer->isValueDependent())
423        return NK_Dependent_Narrowing;
424
425      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426        // Such conversions on variables are always narrowing.
427        return NK_Variable_Narrowing;
428      }
429      bool Narrowing = false;
430      if (FromWidth < ToWidth) {
431        // Negative -> unsigned is narrowing. Otherwise, more bits is never
432        // narrowing.
433        if (InitializerValue.isSigned() && InitializerValue.isNegative())
434          Narrowing = true;
435      } else {
436        // Add a bit to the InitializerValue so we don't have to worry about
437        // signed vs. unsigned comparisons.
438        InitializerValue = InitializerValue.extend(
439          InitializerValue.getBitWidth() + 1);
440        // Convert the initializer to and from the target width and signed-ness.
441        llvm::APSInt ConvertedValue = InitializerValue;
442        ConvertedValue = ConvertedValue.trunc(ToWidth);
443        ConvertedValue.setIsSigned(ToSigned);
444        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445        ConvertedValue.setIsSigned(InitializerValue.isSigned());
446        // If the result is different, this was a narrowing conversion.
447        if (ConvertedValue != InitializerValue)
448          Narrowing = true;
449      }
450      if (Narrowing) {
451        ConstantType = Initializer->getType();
452        ConstantValue = APValue(InitializerValue);
453        return NK_Constant_Narrowing;
454      }
455    }
456    return NK_Not_Narrowing;
457  }
458
459  default:
460    // Other kinds of conversions are not narrowings.
461    return NK_Not_Narrowing;
462  }
463}
464
465/// dump - Print this standard conversion sequence to standard
466/// error. Useful for debugging overloading issues.
467LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468  raw_ostream &OS = llvm::errs();
469  bool PrintedSomething = false;
470  if (First != ICK_Identity) {
471    OS << GetImplicitConversionName(First);
472    PrintedSomething = true;
473  }
474
475  if (Second != ICK_Identity) {
476    if (PrintedSomething) {
477      OS << " -> ";
478    }
479    OS << GetImplicitConversionName(Second);
480
481    if (CopyConstructor) {
482      OS << " (by copy constructor)";
483    } else if (DirectBinding) {
484      OS << " (direct reference binding)";
485    } else if (ReferenceBinding) {
486      OS << " (reference binding)";
487    }
488    PrintedSomething = true;
489  }
490
491  if (Third != ICK_Identity) {
492    if (PrintedSomething) {
493      OS << " -> ";
494    }
495    OS << GetImplicitConversionName(Third);
496    PrintedSomething = true;
497  }
498
499  if (!PrintedSomething) {
500    OS << "No conversions required";
501  }
502}
503
504/// dump - Print this user-defined conversion sequence to standard
505/// error. Useful for debugging overloading issues.
506void UserDefinedConversionSequence::dump() const {
507  raw_ostream &OS = llvm::errs();
508  if (Before.First || Before.Second || Before.Third) {
509    Before.dump();
510    OS << " -> ";
511  }
512  if (ConversionFunction)
513    OS << '\'' << *ConversionFunction << '\'';
514  else
515    OS << "aggregate initialization";
516  if (After.First || After.Second || After.Third) {
517    OS << " -> ";
518    After.dump();
519  }
520}
521
522/// dump - Print this implicit conversion sequence to standard
523/// error. Useful for debugging overloading issues.
524void ImplicitConversionSequence::dump() const {
525  raw_ostream &OS = llvm::errs();
526  if (isStdInitializerListElement())
527    OS << "Worst std::initializer_list element conversion: ";
528  switch (ConversionKind) {
529  case StandardConversion:
530    OS << "Standard conversion: ";
531    Standard.dump();
532    break;
533  case UserDefinedConversion:
534    OS << "User-defined conversion: ";
535    UserDefined.dump();
536    break;
537  case EllipsisConversion:
538    OS << "Ellipsis conversion";
539    break;
540  case AmbiguousConversion:
541    OS << "Ambiguous conversion";
542    break;
543  case BadConversion:
544    OS << "Bad conversion";
545    break;
546  }
547
548  OS << "\n";
549}
550
551void AmbiguousConversionSequence::construct() {
552  new (&conversions()) ConversionSet();
553}
554
555void AmbiguousConversionSequence::destruct() {
556  conversions().~ConversionSet();
557}
558
559void
560AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561  FromTypePtr = O.FromTypePtr;
562  ToTypePtr = O.ToTypePtr;
563  new (&conversions()) ConversionSet(O.conversions());
564}
565
566namespace {
567  // Structure used by DeductionFailureInfo to store
568  // template argument information.
569  struct DFIArguments {
570    TemplateArgument FirstArg;
571    TemplateArgument SecondArg;
572  };
573  // Structure used by DeductionFailureInfo to store
574  // template parameter and template argument information.
575  struct DFIParamWithArguments : DFIArguments {
576    TemplateParameter Param;
577  };
578  // Structure used by DeductionFailureInfo to store template argument
579  // information and the index of the problematic call argument.
580  struct DFIDeducedMismatchArgs : DFIArguments {
581    TemplateArgumentList *TemplateArgs;
582    unsigned CallArgIndex;
583  };
584}
585
586/// Convert from Sema's representation of template deduction information
587/// to the form used in overload-candidate information.
588DeductionFailureInfo
589clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                Sema::TemplateDeductionResult TDK,
591                                TemplateDeductionInfo &Info) {
592  DeductionFailureInfo Result;
593  Result.Result = static_cast<unsigned>(TDK);
594  Result.HasDiagnostic = false;
595  switch (TDK) {
596  case Sema::TDK_Invalid:
597  case Sema::TDK_InstantiationDepth:
598  case Sema::TDK_TooManyArguments:
599  case Sema::TDK_TooFewArguments:
600  case Sema::TDK_MiscellaneousDeductionFailure:
601  case Sema::TDK_CUDATargetMismatch:
602    Result.Data = nullptr;
603    break;
604
605  case Sema::TDK_Incomplete:
606  case Sema::TDK_InvalidExplicitArguments:
607    Result.Data = Info.Param.getOpaqueValue();
608    break;
609
610  case Sema::TDK_DeducedMismatch:
611  case Sema::TDK_DeducedMismatchNested: {
612    // FIXME: Should allocate from normal heap so that we can free this later.
613    auto *Saved = new (Context) DFIDeducedMismatchArgs;
614    Saved->FirstArg = Info.FirstArg;
615    Saved->SecondArg = Info.SecondArg;
616    Saved->TemplateArgs = Info.take();
617    Saved->CallArgIndex = Info.CallArgIndex;
618    Result.Data = Saved;
619    break;
620  }
621
622  case Sema::TDK_NonDeducedMismatch: {
623    // FIXME: Should allocate from normal heap so that we can free this later.
624    DFIArguments *Saved = new (Context) DFIArguments;
625    Saved->FirstArg = Info.FirstArg;
626    Saved->SecondArg = Info.SecondArg;
627    Result.Data = Saved;
628    break;
629  }
630
631  case Sema::TDK_IncompletePack:
632    // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
633  case Sema::TDK_Inconsistent:
634  case Sema::TDK_Underqualified: {
635    // FIXME: Should allocate from normal heap so that we can free this later.
636    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
637    Saved->Param = Info.Param;
638    Saved->FirstArg = Info.FirstArg;
639    Saved->SecondArg = Info.SecondArg;
640    Result.Data = Saved;
641    break;
642  }
643
644  case Sema::TDK_SubstitutionFailure:
645    Result.Data = Info.take();
646    if (Info.hasSFINAEDiagnostic()) {
647      PartialDiagnosticAt *Diag = new (Result.DiagnosticPartialDiagnosticAt(
648          SourceLocation(), PartialDiagnostic::NullDiagnostic());
649      Info.takeSFINAEDiagnostic(*Diag);
650      Result.HasDiagnostic = true;
651    }
652    break;
653
654  case Sema::TDK_Success:
655  case Sema::TDK_NonDependentConversionFailure:
656    llvm_unreachable("not a deduction failure");
657  }
658
659  return Result;
660}
661
662void DeductionFailureInfo::Destroy() {
663  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
664  case Sema::TDK_Success:
665  case Sema::TDK_Invalid:
666  case Sema::TDK_InstantiationDepth:
667  case Sema::TDK_Incomplete:
668  case Sema::TDK_TooManyArguments:
669  case Sema::TDK_TooFewArguments:
670  case Sema::TDK_InvalidExplicitArguments:
671  case Sema::TDK_CUDATargetMismatch:
672  case Sema::TDK_NonDependentConversionFailure:
673    break;
674
675  case Sema::TDK_IncompletePack:
676  case Sema::TDK_Inconsistent:
677  case Sema::TDK_Underqualified:
678  case Sema::TDK_DeducedMismatch:
679  case Sema::TDK_DeducedMismatchNested:
680  case Sema::TDK_NonDeducedMismatch:
681    // FIXME: Destroy the data?
682    Data = nullptr;
683    break;
684
685  case Sema::TDK_SubstitutionFailure:
686    // FIXME: Destroy the template argument list?
687    Data = nullptr;
688    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
689      Diag->~PartialDiagnosticAt();
690      HasDiagnostic = false;
691    }
692    break;
693
694  // Unhandled
695  case Sema::TDK_MiscellaneousDeductionFailure:
696    break;
697  }
698}
699
700PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
701  if (HasDiagnostic)
702    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
703  return nullptr;
704}
705
706TemplateParameter DeductionFailureInfo::getTemplateParameter() {
707  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708  case Sema::TDK_Success:
709  case Sema::TDK_Invalid:
710  case Sema::TDK_InstantiationDepth:
711  case Sema::TDK_TooManyArguments:
712  case Sema::TDK_TooFewArguments:
713  case Sema::TDK_SubstitutionFailure:
714  case Sema::TDK_DeducedMismatch:
715  case Sema::TDK_DeducedMismatchNested:
716  case Sema::TDK_NonDeducedMismatch:
717  case Sema::TDK_CUDATargetMismatch:
718  case Sema::TDK_NonDependentConversionFailure:
719    return TemplateParameter();
720
721  case Sema::TDK_Incomplete:
722  case Sema::TDK_InvalidExplicitArguments:
723    return TemplateParameter::getFromOpaqueValue(Data);
724
725  case Sema::TDK_IncompletePack:
726  case Sema::TDK_Inconsistent:
727  case Sema::TDK_Underqualified:
728    return static_cast<DFIParamWithArguments*>(Data)->Param;
729
730  // Unhandled
731  case Sema::TDK_MiscellaneousDeductionFailure:
732    break;
733  }
734
735  return TemplateParameter();
736}
737
738TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
739  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
740  case Sema::TDK_Success:
741  case Sema::TDK_Invalid:
742  case Sema::TDK_InstantiationDepth:
743  case Sema::TDK_TooManyArguments:
744  case Sema::TDK_TooFewArguments:
745  case Sema::TDK_Incomplete:
746  case Sema::TDK_IncompletePack:
747  case Sema::TDK_InvalidExplicitArguments:
748  case Sema::TDK_Inconsistent:
749  case Sema::TDK_Underqualified:
750  case Sema::TDK_NonDeducedMismatch:
751  case Sema::TDK_CUDATargetMismatch:
752  case Sema::TDK_NonDependentConversionFailure:
753    return nullptr;
754
755  case Sema::TDK_DeducedMismatch:
756  case Sema::TDK_DeducedMismatchNested:
757    return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
758
759  case Sema::TDK_SubstitutionFailure:
760    return static_cast<TemplateArgumentList*>(Data);
761
762  // Unhandled
763  case Sema::TDK_MiscellaneousDeductionFailure:
764    break;
765  }
766
767  return nullptr;
768}
769
770const TemplateArgument *DeductionFailureInfo::getFirstArg() {
771  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
772  case Sema::TDK_Success:
773  case Sema::TDK_Invalid:
774  case Sema::TDK_InstantiationDepth:
775  case Sema::TDK_Incomplete:
776  case Sema::TDK_TooManyArguments:
777  case Sema::TDK_TooFewArguments:
778  case Sema::TDK_InvalidExplicitArguments:
779  case Sema::TDK_SubstitutionFailure:
780  case Sema::TDK_CUDATargetMismatch:
781  case Sema::TDK_NonDependentConversionFailure:
782    return nullptr;
783
784  case Sema::TDK_IncompletePack:
785  case Sema::TDK_Inconsistent:
786  case Sema::TDK_Underqualified:
787  case Sema::TDK_DeducedMismatch:
788  case Sema::TDK_DeducedMismatchNested:
789  case Sema::TDK_NonDeducedMismatch:
790    return &static_cast<DFIArguments*>(Data)->FirstArg;
791
792  // Unhandled
793  case Sema::TDK_MiscellaneousDeductionFailure:
794    break;
795  }
796
797  return nullptr;
798}
799
800const TemplateArgument *DeductionFailureInfo::getSecondArg() {
801  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802  case Sema::TDK_Success:
803  case Sema::TDK_Invalid:
804  case Sema::TDK_InstantiationDepth:
805  case Sema::TDK_Incomplete:
806  case Sema::TDK_IncompletePack:
807  case Sema::TDK_TooManyArguments:
808  case Sema::TDK_TooFewArguments:
809  case Sema::TDK_InvalidExplicitArguments:
810  case Sema::TDK_SubstitutionFailure:
811  case Sema::TDK_CUDATargetMismatch:
812  case Sema::TDK_NonDependentConversionFailure:
813    return nullptr;
814
815  case Sema::TDK_Inconsistent:
816  case Sema::TDK_Underqualified:
817  case Sema::TDK_DeducedMismatch:
818  case Sema::TDK_DeducedMismatchNested:
819  case Sema::TDK_NonDeducedMismatch:
820    return &static_cast<DFIArguments*>(Data)->SecondArg;
821
822  // Unhandled
823  case Sema::TDK_MiscellaneousDeductionFailure:
824    break;
825  }
826
827  return nullptr;
828}
829
830llvm::Optional<unsignedDeductionFailureInfo::getCallArgIndex() {
831  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
832  case Sema::TDK_DeducedMismatch:
833  case Sema::TDK_DeducedMismatchNested:
834    return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
835
836  default:
837    return llvm::None;
838  }
839}
840
841void OverloadCandidateSet::destroyCandidates() {
842  for (iterator i = begin(), e = end(); i != e; ++i) {
843    for (auto &C : i->Conversions)
844      C.~ImplicitConversionSequence();
845    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
846      i->DeductionFailure.Destroy();
847  }
848}
849
850void OverloadCandidateSet::clear(CandidateSetKind CSK) {
851  destroyCandidates();
852  SlabAllocator.Reset();
853  NumInlineBytesUsed = 0;
854  Candidates.clear();
855  Functions.clear();
856  Kind = CSK;
857}
858
859namespace {
860  class UnbridgedCastsSet {
861    struct Entry {
862      Expr **Addr;
863      Expr *Saved;
864    };
865    SmallVector<Entry2Entries;
866
867  public:
868    void save(Sema &SExpr *&E) {
869      hasPlaceholderType(BuiltinType..ARCUnbridgedCast)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 869, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
870      Entry entry = { &EE };
871      Entries.push_back(entry);
872      E = S.stripARCUnbridgedCast(E);
873    }
874
875    void restore() {
876      for (SmallVectorImpl<Entry>::iterator
877             i = Entries.begin(), e = Entries.end(); i != e; ++i)
878        *i->Addr = i->Saved;
879    }
880  };
881}
882
883/// checkPlaceholderForOverload - Do any interesting placeholder-like
884/// preprocessing on the given expression.
885///
886/// \param unbridgedCasts a collection to which to add unbridged casts;
887///   without this, they will be immediately diagnosed as errors
888///
889/// Return true on unrecoverable error.
890static bool
891checkPlaceholderForOverload(Sema &SExpr *&E,
892                            UnbridgedCastsSet *unbridgedCasts = nullptr) {
893  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
894    // We can't handle overloaded expressions here because overload
895    // resolution might reasonably tweak them.
896    if (placeholder->getKind() == BuiltinType::Overloadreturn false;
897
898    // If the context potentially accepts unbridged ARC casts, strip
899    // the unbridged cast and add it to the collection for later restoration.
900    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
901        unbridgedCasts) {
902      unbridgedCasts->save(SE);
903      return false;
904    }
905
906    // Go ahead and check everything else.
907    ExprResult result = S.CheckPlaceholderExpr(E);
908    if (result.isInvalid())
909      return true;
910
911    E = result.get();
912    return false;
913  }
914
915  // Nothing to do.
916  return false;
917}
918
919/// checkArgPlaceholdersForOverload - Check a set of call operands for
920/// placeholders.
921static bool checkArgPlaceholdersForOverload(Sema &S,
922                                            MultiExprArg Args,
923                                            UnbridgedCastsSet &unbridged) {
924  for (unsigned i = 0e = Args.size(); i != e; ++i)
925    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
926      return true;
927
928  return false;
929}
930
931/// Determine whether the given New declaration is an overload of the
932/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
933/// New and Old cannot be overloaded, e.g., if New has the same signature as
934/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
935/// functions (or function templates) at all. When it does return Ovl_Match or
936/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
937/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
938/// declaration.
939///
940/// Example: Given the following input:
941///
942///   void f(int, float); // #1
943///   void f(int, int); // #2
944///   int f(int, int); // #3
945///
946/// When we process #1, there is no previous declaration of "f", so IsOverload
947/// will not be used.
948///
949/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
950/// the parameter types, we see that #1 and #2 are overloaded (since they have
951/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
952/// unchanged.
953///
954/// When we process #3, Old is an overload set containing #1 and #2. We compare
955/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
956/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
957/// functions are not part of the signature), IsOverload returns Ovl_Match and
958/// MatchedDecl will be set to point to the FunctionDecl for #2.
959///
960/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
961/// by a using declaration. The rules for whether to hide shadow declarations
962/// ignore some properties which otherwise figure into a function template's
963/// signature.
964Sema::OverloadKind
965Sema::CheckOverload(Scope *SFunctionDecl *Newconst LookupResult &Old,
966                    NamedDecl *&Matchbool NewIsUsingDecl) {
967  for (LookupResult::iterator I = Old.begin(), E = Old.end();
968         I != E; ++I) {
969    NamedDecl *OldD = *I;
970
971    bool OldIsUsingDecl = false;
972    if (isa<UsingShadowDecl>(OldD)) {
973      OldIsUsingDecl = true;
974
975      // We can always introduce two using declarations into the same
976      // context, even if they have identical signatures.
977      if (NewIsUsingDeclcontinue;
978
979      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980    }
981
982    // A using-declaration does not conflict with another declaration
983    // if one of them is hidden.
984    if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
985      continue;
986
987    // If either declaration was introduced by a using declaration,
988    // we'll need to use slightly different rules for matching.
989    // Essentially, these rules are the normal rules, except that
990    // function templates hide function templates with different
991    // return types or template parameter lists.
992    bool UseMemberUsingDeclRules =
993      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
994      !New->getFriendObjectKind();
995
996    if (FunctionDecl *OldF = OldD->getAsFunction()) {
997      if (!IsOverload(NewOldFUseMemberUsingDeclRules)) {
998        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
999          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1000          continue;
1001        }
1002
1003        if (!isa<FunctionTemplateDecl>(OldD) &&
1004            !shouldLinkPossiblyHiddenDecl(*I, New))
1005          continue;
1006
1007        Match = *I;
1008        return Ovl_Match;
1009      }
1010
1011      // Builtins that have custom typechecking or have a reference should
1012      // not be overloadable or redeclarable.
1013      if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1014        Match = *I;
1015        return Ovl_NonFunction;
1016      }
1017    } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1018      // We can overload with these, which can show up when doing
1019      // redeclaration checks for UsingDecls.
1020      assert(Old.getLookupKind() == LookupUsingDeclName);
1021    } else if (isa<TagDecl>(OldD)) {
1022      // We can always overload with tags by hiding them.
1023    } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1024      // Optimistically assume that an unresolved using decl will
1025      // overload; if it doesn't, we'll have to diagnose during
1026      // template instantiation.
1027      //
1028      // Exception: if the scope is dependent and this is not a class
1029      // member, the using declaration can only introduce an enumerator.
1030      if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1031        Match = *I;
1032        return Ovl_NonFunction;
1033      }
1034    } else {
1035      // (C++ 13p1):
1036      //   Only function declarations can be overloaded; object and type
1037      //   declarations cannot be overloaded.
1038      Match = *I;
1039      return Ovl_NonFunction;
1040    }
1041  }
1042
1043  // C++ [temp.friend]p1:
1044  //   For a friend function declaration that is not a template declaration:
1045  //    -- if the name of the friend is a qualified or unqualified template-id,
1046  //       [...], otherwise
1047  //    -- if the name of the friend is a qualified-id and a matching
1048  //       non-template function is found in the specified class or namespace,
1049  //       the friend declaration refers to that function, otherwise,
1050  //    -- if the name of the friend is a qualified-id and a matching function
1051  //       template is found in the specified class or namespace, the friend
1052  //       declaration refers to the deduced specialization of that function
1053  //       template, otherwise
1054  //    -- the name shall be an unqualified-id [...]
1055  // If we get here for a qualified friend declaration, we've just reached the
1056  // third bullet. If the type of the friend is dependent, skip this lookup
1057  // until instantiation.
1058  if (New->getFriendObjectKind() && New->getQualifier() &&
1059      !New->getDependentSpecializationInfo() &&
1060      !New->getType()->isDependentType()) {
1061    LookupResult TemplateSpecResult(LookupResult::TemporaryOld);
1062    TemplateSpecResult.addAllDecls(Old);
1063    if (CheckFunctionTemplateSpecialization(NewnullptrTemplateSpecResult,
1064                                            /*QualifiedFriend*/true)) {
1065      New->setInvalidDecl();
1066      return Ovl_Overload;
1067    }
1068
1069    Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1070    return Ovl_Match;
1071  }
1072
1073  return Ovl_Overload;
1074}
1075
1076bool Sema::IsOverload(FunctionDecl *NewFunctionDecl *Old,
1077                      bool UseMemberUsingDeclRulesbool ConsiderCudaAttrs) {
1078  // C++ [basic.start.main]p2: This function shall not be overloaded.
1079  if (New->isMain())
1080    return false;
1081
1082  // MSVCRT user defined entry points cannot be overloaded.
1083  if (New->isMSVCRTEntryPoint())
1084    return false;
1085
1086  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1087  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1088
1089  // C++ [temp.fct]p2:
1090  //   A function template can be overloaded with other function templates
1091  //   and with normal (non-template) functions.
1092  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1093    return true;
1094
1095  // Is the function New an overload of the function Old?
1096  QualType OldQType = Context.getCanonicalType(Old->getType());
1097  QualType NewQType = Context.getCanonicalType(New->getType());
1098
1099  // Compare the signatures (C++ 1.3.10) of the two functions to
1100  // determine whether they are overloads. If we find any mismatch
1101  // in the signature, they are overloads.
1102
1103  // If either of these functions is a K&R-style function (no
1104  // prototype), then we consider them to have matching signatures.
1105  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1106      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1107    return false;
1108
1109  const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1110  const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1111
1112  // The signature of a function includes the types of its
1113  // parameters (C++ 1.3.10), which includes the presence or absence
1114  // of the ellipsis; see C++ DR 357).
1115  if (OldQType != NewQType &&
1116      (OldType->getNumParams() != NewType->getNumParams() ||
1117       OldType->isVariadic() != NewType->isVariadic() ||
1118       !FunctionParamTypesAreEqual(OldTypeNewType)))
1119    return true;
1120
1121  // C++ [temp.over.link]p4:
1122  //   The signature of a function template consists of its function
1123  //   signature, its return type and its template parameter list. The names
1124  //   of the template parameters are significant only for establishing the
1125  //   relationship between the template parameters and the rest of the
1126  //   signature.
1127  //
1128  // We check the return type and template parameter lists for function
1129  // templates first; the remaining checks follow.
1130  //
1131  // However, we don't consider either of these when deciding whether
1132  // a member introduced by a shadow declaration is hidden.
1133  if (!UseMemberUsingDeclRules && NewTemplate &&
1134      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1135                                       OldTemplate->getTemplateParameters(),
1136                                       falseTPL_TemplateMatch) ||
1137       !Context.hasSameType(Old->getDeclaredReturnType(),
1138                            New->getDeclaredReturnType())))
1139    return true;
1140
1141  // If the function is a class member, its signature includes the
1142  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1143  //
1144  // As part of this, also check whether one of the member functions
1145  // is static, in which case they are not overloads (C++
1146  // 13.1p2). While not part of the definition of the signature,
1147  // this check is important to determine whether these functions
1148  // can be overloaded.
1149  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1150  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1151  if (OldMethod && NewMethod &&
1152      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1153    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1154      if (!UseMemberUsingDeclRules &&
1155          (OldMethod->getRefQualifier() == RQ_None ||
1156           NewMethod->getRefQualifier() == RQ_None)) {
1157        // C++0x [over.load]p2:
1158        //   - Member function declarations with the same name and the same
1159        //     parameter-type-list as well as member function template
1160        //     declarations with the same name, the same parameter-type-list, and
1161        //     the same template parameter lists cannot be overloaded if any of
1162        //     them, but not all, have a ref-qualifier (8.3.5).
1163        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1164          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1165        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1166      }
1167      return true;
1168    }
1169
1170    // We may not have applied the implicit const for a constexpr member
1171    // function yet (because we haven't yet resolved whether this is a static
1172    // or non-static member function). Add it now, on the assumption that this
1173    // is a redeclaration of OldMethod.
1174    auto OldQuals = OldMethod->getMethodQualifiers();
1175    auto NewQuals = NewMethod->getMethodQualifiers();
1176    if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1177        !isa<CXXConstructorDecl>(NewMethod))
1178      NewQuals.addConst();
1179    // We do not allow overloading based off of '__restrict'.
1180    OldQuals.removeRestrict();
1181    NewQuals.removeRestrict();
1182    if (OldQuals != NewQuals)
1183      return true;
1184  }
1185
1186  // Though pass_object_size is placed on parameters and takes an argument, we
1187  // consider it to be a function-level modifier for the sake of function
1188  // identity. Either the function has one or more parameters with
1189  // pass_object_size or it doesn't.
1190  if (functionHasPassObjectSizeParams(New) !=
1191      functionHasPassObjectSizeParams(Old))
1192    return true;
1193
1194  // enable_if attributes are an order-sensitive part of the signature.
1195  for (specific_attr_iterator<EnableIfAttr>
1196         NewI = New->specific_attr_begin<EnableIfAttr>(),
1197         NewE = New->specific_attr_end<EnableIfAttr>(),
1198         OldI = Old->specific_attr_begin<EnableIfAttr>(),
1199         OldE = Old->specific_attr_end<EnableIfAttr>();
1200       NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1201    if (NewI == NewE || OldI == OldE)
1202      return true;
1203    llvm::FoldingSetNodeID NewID, OldID;
1204    NewI->getCond()->Profile(NewID, Context, true);
1205    OldI->getCond()->Profile(OldID, Context, true);
1206    if (NewID != OldID)
1207      return true;
1208  }
1209
1210  if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1211    // Don't allow overloading of destructors.  (In theory we could, but it
1212    // would be a giant change to clang.)
1213    if (isa<CXXDestructorDecl>(New))
1214      return false;
1215
1216    CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1217                       OldTarget = IdentifyCUDATarget(Old);
1218    if (NewTarget == CFT_InvalidTarget)
1219      return false;
1220
1221     (0) . __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1221, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1222
1223    // Allow overloading of functions with same signature and different CUDA
1224    // target attributes.
1225    return NewTarget != OldTarget;
1226  }
1227
1228  // The signatures match; this is not an overload.
1229  return false;
1230}
1231
1232/// Tries a user-defined conversion from From to ToType.
1233///
1234/// Produces an implicit conversion sequence for when a standard conversion
1235/// is not an option. See TryImplicitConversion for more information.
1236static ImplicitConversionSequence
1237TryUserDefinedConversion(Sema &SExpr *FromQualType ToType,
1238                         bool SuppressUserConversions,
1239                         bool AllowExplicit,
1240                         bool InOverloadResolution,
1241                         bool CStyle,
1242                         bool AllowObjCWritebackConversion,
1243                         bool AllowObjCConversionOnExplicit) {
1244  ImplicitConversionSequence ICS;
1245
1246  if (SuppressUserConversions) {
1247    // We're not in the case above, so there is no conversion that
1248    // we can perform.
1249    ICS.setBad(BadConversionSequence::no_conversionFromToType);
1250    return ICS;
1251  }
1252
1253  // Attempt user-defined conversion.
1254  OverloadCandidateSet Conversions(From->getExprLoc(),
1255                                   OverloadCandidateSet::CSK_Normal);
1256  switch (IsUserDefinedConversion(SFromToTypeICS.UserDefined,
1257                                  ConversionsAllowExplicit,
1258                                  AllowObjCConversionOnExplicit)) {
1259  case OR_Success:
1260  case OR_Deleted:
1261    ICS.setUserDefined();
1262    // C++ [over.ics.user]p4:
1263    //   A conversion of an expression of class type to the same class
1264    //   type is given Exact Match rank, and a conversion of an
1265    //   expression of class type to a base class of that type is
1266    //   given Conversion rank, in spite of the fact that a copy
1267    //   constructor (i.e., a user-defined conversion function) is
1268    //   called for those cases.
1269    if (CXXConstructorDecl *Constructor
1270          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1271      QualType FromCanon
1272        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1273      QualType ToCanon
1274        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1275      if (Constructor->isCopyConstructor() &&
1276          (FromCanon == ToCanon ||
1277           S.IsDerivedFrom(From->getBeginLoc(), FromCanonToCanon))) {
1278        // Turn this into a "standard" conversion sequence, so that it
1279        // gets ranked with standard conversion sequences.
1280        DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1281        ICS.setStandard();
1282        ICS.Standard.setAsIdentityConversion();
1283        ICS.Standard.setFromType(From->getType());
1284        ICS.Standard.setAllToTypes(ToType);
1285        ICS.Standard.CopyConstructor = Constructor;
1286        ICS.Standard.FoundCopyConstructor = Found;
1287        if (ToCanon != FromCanon)
1288          ICS.Standard.Second = ICK_Derived_To_Base;
1289      }
1290    }
1291    break;
1292
1293  case OR_Ambiguous:
1294    ICS.setAmbiguous();
1295    ICS.Ambiguous.setFromType(From->getType());
1296    ICS.Ambiguous.setToType(ToType);
1297    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1298         Cand != Conversions.end(); ++Cand)
1299      if (Cand->Viable)
1300        ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1301    break;
1302
1303    // Fall through.
1304  case OR_No_Viable_Function:
1305    ICS.setBad(BadConversionSequence::no_conversionFromToType);
1306    break;
1307  }
1308
1309  return ICS;
1310}
1311
1312/// TryImplicitConversion - Attempt to perform an implicit conversion
1313/// from the given expression (Expr) to the given type (ToType). This
1314/// function returns an implicit conversion sequence that can be used
1315/// to perform the initialization. Given
1316///
1317///   void f(float f);
1318///   void g(int i) { f(i); }
1319///
1320/// this routine would produce an implicit conversion sequence to
1321/// describe the initialization of f from i, which will be a standard
1322/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1323/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1324//
1325/// Note that this routine only determines how the conversion can be
1326/// performed; it does not actually perform the conversion. As such,
1327/// it will not produce any diagnostics if no conversion is available,
1328/// but will instead return an implicit conversion sequence of kind
1329/// "BadConversion".
1330///
1331/// If @p SuppressUserConversions, then user-defined conversions are
1332/// not permitted.
1333/// If @p AllowExplicit, then explicit user-defined conversions are
1334/// permitted.
1335///
1336/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1337/// writeback conversion, which allows __autoreleasing id* parameters to
1338/// be initialized with __strong id* or __weak id* arguments.
1339static ImplicitConversionSequence
1340TryImplicitConversion(Sema &SExpr *FromQualType ToType,
1341                      bool SuppressUserConversions,
1342                      bool AllowExplicit,
1343                      bool InOverloadResolution,
1344                      bool CStyle,
1345                      bool AllowObjCWritebackConversion,
1346                      bool AllowObjCConversionOnExplicit) {
1347  ImplicitConversionSequence ICS;
1348  if (IsStandardConversion(SFromToTypeInOverloadResolution,
1349                           ICS.Standard, CStyleAllowObjCWritebackConversion)){
1350    ICS.setStandard();
1351    return ICS;
1352  }
1353
1354  if (!S.getLangOpts().CPlusPlus) {
1355    ICS.setBad(BadConversionSequence::no_conversionFromToType);
1356    return ICS;
1357  }
1358
1359  // C++ [over.ics.user]p4:
1360  //   A conversion of an expression of class type to the same class
1361  //   type is given Exact Match rank, and a conversion of an
1362  //   expression of class type to a base class of that type is
1363  //   given Conversion rank, in spite of the fact that a copy/move
1364  //   constructor (i.e., a user-defined conversion function) is
1365  //   called for those cases.
1366  QualType FromType = From->getType();
1367  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1368      (S.Context.hasSameUnqualifiedType(FromTypeToType) ||
1369       S.IsDerivedFrom(From->getBeginLoc(), FromTypeToType))) {
1370    ICS.setStandard();
1371    ICS.Standard.setAsIdentityConversion();
1372    ICS.Standard.setFromType(FromType);
1373    ICS.Standard.setAllToTypes(ToType);
1374
1375    // We don't actually check at this point whether there is a valid
1376    // copy/move constructor, since overloading just assumes that it
1377    // exists. When we actually perform initialization, we'll find the
1378    // appropriate constructor to copy the returned object, if needed.
1379    ICS.Standard.CopyConstructor = nullptr;
1380
1381    // Determine whether this is considered a derived-to-base conversion.
1382    if (!S.Context.hasSameUnqualifiedType(FromTypeToType))
1383      ICS.Standard.Second = ICK_Derived_To_Base;
1384
1385    return ICS;
1386  }
1387
1388  return TryUserDefinedConversion(SFromToTypeSuppressUserConversions,
1389                                  AllowExplicitInOverloadResolutionCStyle,
1390                                  AllowObjCWritebackConversion,
1391                                  AllowObjCConversionOnExplicit);
1392}
1393
1394ImplicitConversionSequence
1395Sema::TryImplicitConversion(Expr *FromQualType ToType,
1396                            bool SuppressUserConversions,
1397                            bool AllowExplicit,
1398                            bool InOverloadResolution,
1399                            bool CStyle,
1400                            bool AllowObjCWritebackConversion) {
1401  return ::TryImplicitConversion(*thisFromToType,
1402                                 SuppressUserConversionsAllowExplicit,
1403                                 InOverloadResolutionCStyle,
1404                                 AllowObjCWritebackConversion,
1405                                 /*AllowObjCConversionOnExplicit=*/false);
1406}
1407
1408/// PerformImplicitConversion - Perform an implicit conversion of the
1409/// expression From to the type ToType. Returns the
1410/// converted expression. Flavor is the kind of conversion we're
1411/// performing, used in the error message. If @p AllowExplicit,
1412/// explicit user-defined conversions are permitted.
1413ExprResult
1414Sema::PerformImplicitConversion(Expr *FromQualType ToType,
1415                                AssignmentAction Actionbool AllowExplicit) {
1416  ImplicitConversionSequence ICS;
1417  return PerformImplicitConversion(FromToTypeActionAllowExplicitICS);
1418}
1419
1420ExprResult
1421Sema::PerformImplicitConversion(Expr *FromQualType ToType,
1422                                AssignmentAction Actionbool AllowExplicit,
1423                                ImplicitConversionSequenceICS) {
1424  if (checkPlaceholderForOverload(*thisFrom))
1425    return ExprError();
1426
1427  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1428  bool AllowObjCWritebackConversion
1429    = getLangOpts().ObjCAutoRefCount &&
1430      (Action == AA_Passing || Action == AA_Sending);
1431  if (getLangOpts().ObjC)
1432    CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1433                                      From->getType(), From);
1434  ICS = ::TryImplicitConversion(*thisFromToType,
1435                                /*SuppressUserConversions=*/false,
1436                                AllowExplicit,
1437                                /*InOverloadResolution=*/false,
1438                                /*CStyle=*/false,
1439                                AllowObjCWritebackConversion,
1440                                /*AllowObjCConversionOnExplicit=*/false);
1441  return PerformImplicitConversion(FromToTypeICSAction);
1442}
1443
1444/// Determine whether the conversion from FromType to ToType is a valid
1445/// conversion that strips "noexcept" or "noreturn" off the nested function
1446/// type.
1447bool Sema::IsFunctionConversion(QualType FromTypeQualType ToType,
1448                                QualType &ResultTy) {
1449  if (Context.hasSameUnqualifiedType(FromTypeToType))
1450    return false;
1451
1452  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1453  //                    or F(t noexcept) -> F(t)
1454  // where F adds one of the following at most once:
1455  //   - a pointer
1456  //   - a member pointer
1457  //   - a block pointer
1458  // Changes here need matching changes in FindCompositePointerType.
1459  CanQualType CanTo = Context.getCanonicalType(ToType);
1460  CanQualType CanFrom = Context.getCanonicalType(FromType);
1461  Type::TypeClass TyClass = CanTo->getTypeClass();
1462  if (TyClass != CanFrom->getTypeClass()) return false;
1463  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1464    if (TyClass == Type::Pointer) {
1465      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1466      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1467    } else if (TyClass == Type::BlockPointer) {
1468      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1469      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1470    } else if (TyClass == Type::MemberPointer) {
1471      auto ToMPT = CanTo.getAs<MemberPointerType>();
1472      auto FromMPT = CanFrom.getAs<MemberPointerType>();
1473      // A function pointer conversion cannot change the class of the function.
1474      if (ToMPT->getClass() != FromMPT->getClass())
1475        return false;
1476      CanTo = ToMPT->getPointeeType();
1477      CanFrom = FromMPT->getPointeeType();
1478    } else {
1479      return false;
1480    }
1481
1482    TyClass = CanTo->getTypeClass();
1483    if (TyClass != CanFrom->getTypeClass()) return false;
1484    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1485      return false;
1486  }
1487
1488  const auto *FromFn = cast<FunctionType>(CanFrom);
1489  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1490
1491  const auto *ToFn = cast<FunctionType>(CanTo);
1492  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1493
1494  bool Changed = false;
1495
1496  // Drop 'noreturn' if not present in target type.
1497  if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1498    FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1499    Changed = true;
1500  }
1501
1502  // Drop 'noexcept' if not present in target type.
1503  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1504    const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1505    if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1506      FromFn = cast<FunctionType>(
1507          Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1508                                                   EST_None)
1509                 .getTypePtr());
1510      Changed = true;
1511    }
1512
1513    // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1514    // only if the ExtParameterInfo lists of the two function prototypes can be
1515    // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1516    SmallVector<FunctionProtoType::ExtParameterInfo4NewParamInfos;
1517    bool CanUseToFPTCanUseFromFPT;
1518    if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1519                                      CanUseFromFPT, NewParamInfos) &&
1520        CanUseToFPT && !CanUseFromFPT) {
1521      FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1522      ExtInfo.ExtParameterInfos =
1523          NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1524      QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1525                                            FromFPT->getParamTypes(), ExtInfo);
1526      FromFn = QT->getAs<FunctionType>();
1527      Changed = true;
1528    }
1529  }
1530
1531  if (!Changed)
1532    return false;
1533
1534  assert(QualType(FromFn, 0).isCanonical());
1535  if (QualType(FromFn, 0) != CanTo) return false;
1536
1537  ResultTy = ToType;
1538  return true;
1539}
1540
1541/// Determine whether the conversion from FromType to ToType is a valid
1542/// vector conversion.
1543///
1544/// \param ICK Will be set to the vector conversion kind, if this is a vector
1545/// conversion.
1546static bool IsVectorConversion(Sema &SQualType FromType,
1547                               QualType ToTypeImplicitConversionKind &ICK) {
1548  // We need at least one of these types to be a vector type to have a vector
1549  // conversion.
1550  if (!ToType->isVectorType() && !FromType->isVectorType())
1551    return false;
1552
1553  // Identical types require no conversions.
1554  if (S.Context.hasSameUnqualifiedType(FromTypeToType))
1555    return false;
1556
1557  // There are no conversions between extended vector types, only identity.
1558  if (ToType->isExtVectorType()) {
1559    // There are no conversions between extended vector types other than the
1560    // identity conversion.
1561    if (FromType->isExtVectorType())
1562      return false;
1563
1564    // Vector splat from any arithmetic type to a vector.
1565    if (FromType->isArithmeticType()) {
1566      ICK = ICK_Vector_Splat;
1567      return true;
1568    }
1569  }
1570
1571  // We can perform the conversion between vector types in the following cases:
1572  // 1)vector types are equivalent AltiVec and GCC vector types
1573  // 2)lax vector conversions are permitted and the vector types are of the
1574  //   same size
1575  if (ToType->isVectorType() && FromType->isVectorType()) {
1576    if (S.Context.areCompatibleVectorTypes(FromTypeToType) ||
1577        S.isLaxVectorConversion(FromTypeToType)) {
1578      ICK = ICK_Vector_Conversion;
1579      return true;
1580    }
1581  }
1582
1583  return false;
1584}
1585
1586static bool tryAtomicConversion(Sema &SExpr *FromQualType ToType,
1587                                bool InOverloadResolution,
1588                                StandardConversionSequence &SCS,
1589                                bool CStyle);
1590
1591/// IsStandardConversion - Determines whether there is a standard
1592/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1593/// expression From to the type ToType. Standard conversion sequences
1594/// only consider non-class types; for conversions that involve class
1595/// types, use TryImplicitConversion. If a conversion exists, SCS will
1596/// contain the standard conversion sequence required to perform this
1597/// conversion and this routine will return true. Otherwise, this
1598/// routine will return false and the value of SCS is unspecified.
1599static bool IsStandardConversion(Sema &SExprFromQualType ToType,
1600                                 bool InOverloadResolution,
1601                                 StandardConversionSequence &SCS,
1602                                 bool CStyle,
1603                                 bool AllowObjCWritebackConversion) {
1604  QualType FromType = From->getType();
1605
1606  // Standard conversions (C++ [conv])
1607  SCS.setAsIdentityConversion();
1608  SCS.IncompatibleObjC = false;
1609  SCS.setFromType(FromType);
1610  SCS.CopyConstructor = nullptr;
1611
1612  // There are no standard conversions for class types in C++, so
1613  // abort early. When overloading in C, however, we do permit them.
1614  if (S.getLangOpts().CPlusPlus &&
1615      (FromType->isRecordType() || ToType->isRecordType()))
1616    return false;
1617
1618  // The first conversion can be an lvalue-to-rvalue conversion,
1619  // array-to-pointer conversion, or function-to-pointer conversion
1620  // (C++ 4p1).
1621
1622  if (FromType == S.Context.OverloadTy) {
1623    DeclAccessPair AccessPair;
1624    if (FunctionDecl *Fn
1625          = S.ResolveAddressOfOverloadedFunction(FromToTypefalse,
1626                                                 AccessPair)) {
1627      // We were able to resolve the address of the overloaded function,
1628      // so we can convert to the type of that function.
1629      FromType = Fn->getType();
1630      SCS.setFromType(FromType);
1631
1632      // we can sometimes resolve &foo<int> regardless of ToType, so check
1633      // if the type matches (identity) or we are converting to bool
1634      if (!S.Context.hasSameUnqualifiedType(
1635                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1636        QualType resultTy;
1637        // if the function type matches except for [[noreturn]], it's ok
1638        if (!S.IsFunctionConversion(FromType,
1639              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1640          // otherwise, only a boolean conversion is standard
1641          if (!ToType->isBooleanType())
1642            return false;
1643      }
1644
1645      // Check if the "from" expression is taking the address of an overloaded
1646      // function and recompute the FromType accordingly. Take advantage of the
1647      // fact that non-static member functions *must* have such an address-of
1648      // expression.
1649      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1650      if (Method && !Method->isStatic()) {
1651         (0) . __assert_fail ("isa(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1652, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1652 (0) . __assert_fail ("isa(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1652, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               "Non-unary operator on non-static member address");
1653         (0) . __assert_fail ("cast(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1655, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1654 (0) . __assert_fail ("cast(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1655, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               == UO_AddrOf &&
1655 (0) . __assert_fail ("cast(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1655, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               "Non-address-of operator on non-static member address");
1656        const Type *ClassType
1657          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1658        FromType = S.Context.getMemberPointerType(FromTypeClassType);
1659      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1660         (0) . __assert_fail ("cast(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1662, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1661 (0) . __assert_fail ("cast(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1662, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               UO_AddrOf &&
1662 (0) . __assert_fail ("cast(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1662, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               "Non-address-of operator for overloaded function expression");
1663        FromType = S.Context.getPointerType(FromType);
1664      }
1665
1666      // Check that we've computed the proper type after overload resolution.
1667      // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1668      // be calling it from within an NDEBUG block.
1669      getType())", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1671, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S.Context.hasSameType(
1670getType())", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1671, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">        FromType,
1671getType())", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 1671, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1672    } else {
1673      return false;
1674    }
1675  }
1676  // Lvalue-to-rvalue conversion (C++11 4.1):
1677  //   A glvalue (3.10) of a non-function, non-array type T can
1678  //   be converted to a prvalue.
1679  bool argIsLValue = From->isGLValue();
1680  if (argIsLValue &&
1681      !FromType->isFunctionType() && !FromType->isArrayType() &&
1682      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1683    SCS.First = ICK_Lvalue_To_Rvalue;
1684
1685    // C11 6.3.2.1p2:
1686    //   ... if the lvalue has atomic type, the value has the non-atomic version
1687    //   of the type of the lvalue ...
1688    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1689      FromType = Atomic->getValueType();
1690
1691    // If T is a non-class type, the type of the rvalue is the
1692    // cv-unqualified version of T. Otherwise, the type of the rvalue
1693    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1694    // just strip the qualifiers because they don't matter.
1695    FromType = FromType.getUnqualifiedType();
1696  } else if (FromType->isArrayType()) {
1697    // Array-to-pointer conversion (C++ 4.2)
1698    SCS.First = ICK_Array_To_Pointer;
1699
1700    // An lvalue or rvalue of type "array of N T" or "array of unknown
1701    // bound of T" can be converted to an rvalue of type "pointer to
1702    // T" (C++ 4.2p1).
1703    FromType = S.Context.getArrayDecayedType(FromType);
1704
1705    if (S.IsStringLiteralToNonConstPointerConversion(FromToType)) {
1706      // This conversion is deprecated in C++03 (D.4)
1707      SCS.DeprecatedStringLiteralToCharPtr = true;
1708
1709      // For the purpose of ranking in overload resolution
1710      // (13.3.3.1.1), this conversion is considered an
1711      // array-to-pointer conversion followed by a qualification
1712      // conversion (4.4). (C++ 4.2p2)
1713      SCS.Second = ICK_Identity;
1714      SCS.Third = ICK_Qualification;
1715      SCS.QualificationIncludesObjCLifetime = false;
1716      SCS.setAllToTypes(FromType);
1717      return true;
1718    }
1719  } else if (FromType->isFunctionType() && argIsLValue) {
1720    // Function-to-pointer conversion (C++ 4.3).
1721    SCS.First = ICK_Function_To_Pointer;
1722
1723    if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1724      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1725        if (!S.checkAddressOfFunctionIsAvailable(FD))
1726          return false;
1727
1728    // An lvalue of function type T can be converted to an rvalue of
1729    // type "pointer to T." The result is a pointer to the
1730    // function. (C++ 4.3p1).
1731    FromType = S.Context.getPointerType(FromType);
1732  } else {
1733    // We don't require any conversions for the first step.
1734    SCS.First = ICK_Identity;
1735  }
1736  SCS.setToType(0FromType);
1737
1738  // The second conversion can be an integral promotion, floating
1739  // point promotion, integral conversion, floating point conversion,
1740  // floating-integral conversion, pointer conversion,
1741  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1742  // For overloading in C, this can also be a "compatible-type"
1743  // conversion.
1744  bool IncompatibleObjC = false;
1745  ImplicitConversionKind SecondICK = ICK_Identity;
1746  if (S.Context.hasSameUnqualifiedType(FromTypeToType)) {
1747    // The unqualified versions of the types are the same: there's no
1748    // conversion to do.
1749    SCS.Second = ICK_Identity;
1750  } else if (S.IsIntegralPromotion(FromFromTypeToType)) {
1751    // Integral promotion (C++ 4.5).
1752    SCS.Second = ICK_Integral_Promotion;
1753    FromType = ToType.getUnqualifiedType();
1754  } else if (S.IsFloatingPointPromotion(FromTypeToType)) {
1755    // Floating point promotion (C++ 4.6).
1756    SCS.Second = ICK_Floating_Promotion;
1757    FromType = ToType.getUnqualifiedType();
1758  } else if (S.IsComplexPromotion(FromTypeToType)) {
1759    // Complex promotion (Clang extension)
1760    SCS.Second = ICK_Complex_Promotion;
1761    FromType = ToType.getUnqualifiedType();
1762  } else if (ToType->isBooleanType() &&
1763             (FromType->isArithmeticType() ||
1764              FromType->isAnyPointerType() ||
1765              FromType->isBlockPointerType() ||
1766              FromType->isMemberPointerType() ||
1767              FromType->isNullPtrType())) {
1768    // Boolean conversions (C++ 4.12).
1769    SCS.Second = ICK_Boolean_Conversion;
1770    FromType = S.Context.BoolTy;
1771  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1772             ToType->isIntegralType(S.Context)) {
1773    // Integral conversions (C++ 4.7).
1774    SCS.Second = ICK_Integral_Conversion;
1775    FromType = ToType.getUnqualifiedType();
1776  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1777    // Complex conversions (C99 6.3.1.6)
1778    SCS.Second = ICK_Complex_Conversion;
1779    FromType = ToType.getUnqualifiedType();
1780  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1781             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1782    // Complex-real conversions (C99 6.3.1.7)
1783    SCS.Second = ICK_Complex_Real;
1784    FromType = ToType.getUnqualifiedType();
1785  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1786    // FIXME: disable conversions between long double and __float128 if
1787    // their representation is different until there is back end support
1788    // We of course allow this conversion if long double is really double.
1789    if (&S.Context.getFloatTypeSemantics(FromType) !=
1790        &S.Context.getFloatTypeSemantics(ToType)) {
1791      bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1792                                    ToType == S.Context.LongDoubleTy) ||
1793                                   (FromType == S.Context.LongDoubleTy &&
1794                                    ToType == S.Context.Float128Ty));
1795      if (Float128AndLongDouble &&
1796          (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1797           &llvm::APFloat::PPCDoubleDouble()))
1798        return false;
1799    }
1800    // Floating point conversions (C++ 4.8).
1801    SCS.Second = ICK_Floating_Conversion;
1802    FromType = ToType.getUnqualifiedType();
1803  } else if ((FromType->isRealFloatingType() &&
1804              ToType->isIntegralType(S.Context)) ||
1805             (FromType->isIntegralOrUnscopedEnumerationType() &&
1806              ToType->isRealFloatingType())) {
1807    // Floating-integral conversions (C++ 4.9).
1808    SCS.Second = ICK_Floating_Integral;
1809    FromType = ToType.getUnqualifiedType();
1810  } else if (S.IsBlockPointerConversion(FromTypeToTypeFromType)) {
1811    SCS.Second = ICK_Block_Pointer_Conversion;
1812  } else if (AllowObjCWritebackConversion &&
1813             S.isObjCWritebackConversion(FromTypeToTypeFromType)) {
1814    SCS.Second = ICK_Writeback_Conversion;
1815  } else if (S.IsPointerConversion(FromFromTypeToTypeInOverloadResolution,
1816                                   FromTypeIncompatibleObjC)) {
1817    // Pointer conversions (C++ 4.10).
1818    SCS.Second = ICK_Pointer_Conversion;
1819    SCS.IncompatibleObjC = IncompatibleObjC;
1820    FromType = FromType.getUnqualifiedType();
1821  } else if (S.IsMemberPointerConversion(FromFromTypeToType,
1822                                         InOverloadResolutionFromType)) {
1823    // Pointer to member conversions (4.11).
1824    SCS.Second = ICK_Pointer_Member;
1825  } else if (IsVectorConversion(SFromTypeToTypeSecondICK)) {
1826    SCS.Second = SecondICK;
1827    FromType = ToType.getUnqualifiedType();
1828  } else if (!S.getLangOpts().CPlusPlus &&
1829             S.Context.typesAreCompatible(ToTypeFromType)) {
1830    // Compatible conversions (Clang extension for C function overloading)
1831    SCS.Second = ICK_Compatible_Conversion;
1832    FromType = ToType.getUnqualifiedType();
1833  } else if (IsTransparentUnionStandardConversion(SFromToType,
1834                                             InOverloadResolution,
1835                                             SCSCStyle)) {
1836    SCS.Second = ICK_TransparentUnionConversion;
1837    FromType = ToType;
1838  } else if (tryAtomicConversion(SFromToTypeInOverloadResolutionSCS,
1839                                 CStyle)) {
1840    // tryAtomicConversion has updated the standard conversion sequence
1841    // appropriately.
1842    return true;
1843  } else if (ToType->isEventT() &&
1844             From->isIntegerConstantExpr(S.getASTContext()) &&
1845             From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1846    SCS.Second = ICK_Zero_Event_Conversion;
1847    FromType = ToType;
1848  } else if (ToType->isQueueT() &&
1849             From->isIntegerConstantExpr(S.getASTContext()) &&
1850             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1851    SCS.Second = ICK_Zero_Queue_Conversion;
1852    FromType = ToType;
1853  } else {
1854    // No second conversion required.
1855    SCS.Second = ICK_Identity;
1856  }
1857  SCS.setToType(1FromType);
1858
1859  // The third conversion can be a function pointer conversion or a
1860  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1861  bool ObjCLifetimeConversion;
1862  if (S.IsFunctionConversion(FromTypeToTypeFromType)) {
1863    // Function pointer conversions (removing 'noexcept') including removal of
1864    // 'noreturn' (Clang extension).
1865    SCS.Third = ICK_Function_Conversion;
1866  } else if (S.IsQualificationConversion(FromTypeToTypeCStyle,
1867                                         ObjCLifetimeConversion)) {
1868    SCS.Third = ICK_Qualification;
1869    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1870    FromType = ToType;
1871  } else {
1872    // No conversion required
1873    SCS.Third = ICK_Identity;
1874  }
1875
1876  // C++ [over.best.ics]p6:
1877  //   [...] Any difference in top-level cv-qualification is
1878  //   subsumed by the initialization itself and does not constitute
1879  //   a conversion. [...]
1880  QualType CanonFrom = S.Context.getCanonicalType(FromType);
1881  QualType CanonTo = S.Context.getCanonicalType(ToType);
1882  if (CanonFrom.getLocalUnqualifiedType()
1883                                     == CanonTo.getLocalUnqualifiedType() &&
1884      CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1885    FromType = ToType;
1886    CanonFrom = CanonTo;
1887  }
1888
1889  SCS.setToType(2FromType);
1890
1891  if (CanonFrom == CanonTo)
1892    return true;
1893
1894  // If we have not converted the argument type to the parameter type,
1895  // this is a bad conversion sequence, unless we're resolving an overload in C.
1896  if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1897    return false;
1898
1899  ExprResult ER = ExprResult{From};
1900  Sema::AssignConvertType Conv =
1901      S.CheckSingleAssignmentConstraints(ToTypeER,
1902                                         /*Diagnose=*/false,
1903                                         /*DiagnoseCFAudited=*/false,
1904                                         /*ConvertRHS=*/false);
1905  ImplicitConversionKind SecondConv;
1906  switch (Conv) {
1907  case Sema::Compatible:
1908    SecondConv = ICK_C_Only_Conversion;
1909    break;
1910  // For our purposes, discarding qualifiers is just as bad as using an
1911  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1912  // qualifiers, as well.
1913  case Sema::CompatiblePointerDiscardsQualifiers:
1914  case Sema::IncompatiblePointer:
1915  case Sema::IncompatiblePointerSign:
1916    SecondConv = ICK_Incompatible_Pointer_Conversion;
1917    break;
1918  default:
1919    return false;
1920  }
1921
1922  // First can only be an lvalue conversion, so we pretend that this was the
1923  // second conversion. First should already be valid from earlier in the
1924  // function.
1925  SCS.Second = SecondConv;
1926  SCS.setToType(1ToType);
1927
1928  // Third is Identity, because Second should rank us worse than any other
1929  // conversion. This could also be ICK_Qualification, but it's simpler to just
1930  // lump everything in with the second conversion, and we don't gain anything
1931  // from making this ICK_Qualification.
1932  SCS.Third = ICK_Identity;
1933  SCS.setToType(2ToType);
1934  return true;
1935}
1936
1937static bool
1938IsTransparentUnionStandardConversion(Sema &SExprFrom,
1939                                     QualType &ToType,
1940                                     bool InOverloadResolution,
1941                                     StandardConversionSequence &SCS,
1942                                     bool CStyle) {
1943
1944  const RecordType *UT = ToType->getAsUnionType();
1945  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1946    return false;
1947  // The field to initialize within the transparent union.
1948  RecordDecl *UD = UT->getDecl();
1949  // It's compatible if the expression matches any of the fields.
1950  for (const auto *it : UD->fields()) {
1951    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1952                             CStyle, /*ObjCWritebackConversion=*/false)) {
1953      ToType = it->getType();
1954      return true;
1955    }
1956  }
1957  return false;
1958}
1959
1960/// IsIntegralPromotion - Determines whether the conversion from the
1961/// expression From (whose potentially-adjusted type is FromType) to
1962/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1963/// sets PromotedType to the promoted type.
1964bool Sema::IsIntegralPromotion(Expr *FromQualType FromTypeQualType ToType) {
1965  const BuiltinType *To = ToType->getAs<BuiltinType>();
1966  // All integers are built-in.
1967  if (!To) {
1968    return false;
1969  }
1970
1971  // An rvalue of type char, signed char, unsigned char, short int, or
1972  // unsigned short int can be converted to an rvalue of type int if
1973  // int can represent all the values of the source type; otherwise,
1974  // the source rvalue can be converted to an rvalue of type unsigned
1975  // int (C++ 4.5p1).
1976  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1977      !FromType->isEnumeralType()) {
1978    if (// We can promote any signed, promotable integer type to an int
1979        (FromType->isSignedIntegerType() ||
1980         // We can promote any unsigned integer type whose size is
1981         // less than int to an int.
1982         Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1983      return To->getKind() == BuiltinType::Int;
1984    }
1985
1986    return To->getKind() == BuiltinType::UInt;
1987  }
1988
1989  // C++11 [conv.prom]p3:
1990  //   A prvalue of an unscoped enumeration type whose underlying type is not
1991  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1992  //   following types that can represent all the values of the enumeration
1993  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1994  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1995  //   long long int. If none of the types in that list can represent all the
1996  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1997  //   type can be converted to an rvalue a prvalue of the extended integer type
1998  //   with lowest integer conversion rank (4.13) greater than the rank of long
1999  //   long in which all the values of the enumeration can be represented. If
2000  //   there are two such extended types, the signed one is chosen.
2001  // C++11 [conv.prom]p4:
2002  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2003  //   can be converted to a prvalue of its underlying type. Moreover, if
2004  //   integral promotion can be applied to its underlying type, a prvalue of an
2005  //   unscoped enumeration type whose underlying type is fixed can also be
2006  //   converted to a prvalue of the promoted underlying type.
2007  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2008    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2009    // provided for a scoped enumeration.
2010    if (FromEnumType->getDecl()->isScoped())
2011      return false;
2012
2013    // We can perform an integral promotion to the underlying type of the enum,
2014    // even if that's not the promoted type. Note that the check for promoting
2015    // the underlying type is based on the type alone, and does not consider
2016    // the bitfield-ness of the actual source expression.
2017    if (FromEnumType->getDecl()->isFixed()) {
2018      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2019      return Context.hasSameUnqualifiedType(UnderlyingToType) ||
2020             IsIntegralPromotion(nullptrUnderlyingToType);
2021    }
2022
2023    // We have already pre-calculated the promotion type, so this is trivial.
2024    if (ToType->isIntegerType() &&
2025        isCompleteType(From->getBeginLoc(), FromType))
2026      return Context.hasSameUnqualifiedType(
2027          ToTypeFromEnumType->getDecl()->getPromotionType());
2028
2029    // C++ [conv.prom]p5:
2030    //   If the bit-field has an enumerated type, it is treated as any other
2031    //   value of that type for promotion purposes.
2032    //
2033    // ... so do not fall through into the bit-field checks below in C++.
2034    if (getLangOpts().CPlusPlus)
2035      return false;
2036  }
2037
2038  // C++0x [conv.prom]p2:
2039  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2040  //   to an rvalue a prvalue of the first of the following types that can
2041  //   represent all the values of its underlying type: int, unsigned int,
2042  //   long int, unsigned long int, long long int, or unsigned long long int.
2043  //   If none of the types in that list can represent all the values of its
2044  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2045  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2046  //   type.
2047  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2048      ToType->isIntegerType()) {
2049    // Determine whether the type we're converting from is signed or
2050    // unsigned.
2051    bool FromIsSigned = FromType->isSignedIntegerType();
2052    uint64_t FromSize = Context.getTypeSize(FromType);
2053
2054    // The types we'll try to promote to, in the appropriate
2055    // order. Try each of these types.
2056    QualType PromoteTypes[6] = {
2057      Context.IntTyContext.UnsignedIntTy,
2058      Context.LongTyContext.UnsignedLongTy ,
2059      Context.LongLongTyContext.UnsignedLongLongTy
2060    };
2061    for (int Idx = 0Idx < 6; ++Idx) {
2062      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2063      if (FromSize < ToSize ||
2064          (FromSize == ToSize &&
2065           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2066        // We found the type that we can promote to. If this is the
2067        // type we wanted, we have a promotion. Otherwise, no
2068        // promotion.
2069        return Context.hasSameUnqualifiedType(ToTypePromoteTypes[Idx]);
2070      }
2071    }
2072  }
2073
2074  // An rvalue for an integral bit-field (9.6) can be converted to an
2075  // rvalue of type int if int can represent all the values of the
2076  // bit-field; otherwise, it can be converted to unsigned int if
2077  // unsigned int can represent all the values of the bit-field. If
2078  // the bit-field is larger yet, no integral promotion applies to
2079  // it. If the bit-field has an enumerated type, it is treated as any
2080  // other value of that type for promotion purposes (C++ 4.5p3).
2081  // FIXME: We should delay checking of bit-fields until we actually perform the
2082  // conversion.
2083  //
2084  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2085  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2086  // bit-fields and those whose underlying type is larger than int) for GCC
2087  // compatibility.
2088  if (From) {
2089    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2090      llvm::APSInt BitWidth;
2091      if (FromType->isIntegralType(Context) &&
2092          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2093        llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2094        ToSize = Context.getTypeSize(ToType);
2095
2096        // Are we promoting to an int from a bitfield that fits in an int?
2097        if (BitWidth < ToSize ||
2098            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2099          return To->getKind() == BuiltinType::Int;
2100        }
2101
2102        // Are we promoting to an unsigned int from an unsigned bitfield
2103        // that fits into an unsigned int?
2104        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2105          return To->getKind() == BuiltinType::UInt;
2106        }
2107
2108        return false;
2109      }
2110    }
2111  }
2112
2113  // An rvalue of type bool can be converted to an rvalue of type int,
2114  // with false becoming zero and true becoming one (C++ 4.5p4).
2115  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2116    return true;
2117  }
2118
2119  return false;
2120}
2121
2122/// IsFloatingPointPromotion - Determines whether the conversion from
2123/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2124/// returns true and sets PromotedType to the promoted type.
2125bool Sema::IsFloatingPointPromotion(QualType FromTypeQualType ToType) {
2126  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2127    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2128      /// An rvalue of type float can be converted to an rvalue of type
2129      /// double. (C++ 4.6p1).
2130      if (FromBuiltin->getKind() == BuiltinType::Float &&
2131          ToBuiltin->getKind() == BuiltinType::Double)
2132        return true;
2133
2134      // C99 6.3.1.5p1:
2135      //   When a float is promoted to double or long double, or a
2136      //   double is promoted to long double [...].
2137      if (!getLangOpts().CPlusPlus &&
2138          (FromBuiltin->getKind() == BuiltinType::Float ||
2139           FromBuiltin->getKind() == BuiltinType::Double) &&
2140          (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2141           ToBuiltin->getKind() == BuiltinType::Float128))
2142        return true;
2143
2144      // Half can be promoted to float.
2145      if (!getLangOpts().NativeHalfType &&
2146           FromBuiltin->getKind() == BuiltinType::Half &&
2147          ToBuiltin->getKind() == BuiltinType::Float)
2148        return true;
2149    }
2150
2151  return false;
2152}
2153
2154/// Determine if a conversion is a complex promotion.
2155///
2156/// A complex promotion is defined as a complex -> complex conversion
2157/// where the conversion between the underlying real types is a
2158/// floating-point or integral promotion.
2159bool Sema::IsComplexPromotion(QualType FromTypeQualType ToType) {
2160  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2161  if (!FromComplex)
2162    return false;
2163
2164  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2165  if (!ToComplex)
2166    return false;
2167
2168  return IsFloatingPointPromotion(FromComplex->getElementType(),
2169                                  ToComplex->getElementType()) ||
2170    IsIntegralPromotion(nullptrFromComplex->getElementType(),
2171                        ToComplex->getElementType());
2172}
2173
2174/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2175/// the pointer type FromPtr to a pointer to type ToPointee, with the
2176/// same type qualifiers as FromPtr has on its pointee type. ToType,
2177/// if non-empty, will be a pointer to ToType that may or may not have
2178/// the right set of qualifiers on its pointee.
2179///
2180static QualType
2181BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2182                                   QualType ToPointeeQualType ToType,
2183                                   ASTContext &Context,
2184                                   bool StripObjCLifetime = false) {
2185   (0) . __assert_fail ("(FromPtr->getTypeClass() == Type..Pointer || FromPtr->getTypeClass() == Type..ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 2187, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((FromPtr->getTypeClass() == Type::Pointer ||
2186 (0) . __assert_fail ("(FromPtr->getTypeClass() == Type..Pointer || FromPtr->getTypeClass() == Type..ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 2187, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2187 (0) . __assert_fail ("(FromPtr->getTypeClass() == Type..Pointer || FromPtr->getTypeClass() == Type..ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 2187, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Invalid similarly-qualified pointer type");
2188
2189  /// Conversions to 'id' subsume cv-qualifier conversions.
2190  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2191    return ToType.getUnqualifiedType();
2192
2193  QualType CanonFromPointee
2194    = Context.getCanonicalType(FromPtr->getPointeeType());
2195  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2196  Qualifiers Quals = CanonFromPointee.getQualifiers();
2197
2198  if (StripObjCLifetime)
2199    Quals.removeObjCLifetime();
2200
2201  // Exact qualifier match -> return the pointer type we're converting to.
2202  if (CanonToPointee.getLocalQualifiers() == Quals) {
2203    // ToType is exactly what we need. Return it.
2204    if (!ToType.isNull())
2205      return ToType.getUnqualifiedType();
2206
2207    // Build a pointer to ToPointee. It has the right qualifiers
2208    // already.
2209    if (isa<ObjCObjectPointerType>(ToType))
2210      return Context.getObjCObjectPointerType(ToPointee);
2211    return Context.getPointerType(ToPointee);
2212  }
2213
2214  // Just build a canonical type that has the right qualifiers.
2215  QualType QualifiedCanonToPointee
2216    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2217
2218  if (isa<ObjCObjectPointerType>(ToType))
2219    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2220  return Context.getPointerType(QualifiedCanonToPointee);
2221}
2222
2223static bool isNullPointerConstantForConversion(Expr *Expr,
2224                                               bool InOverloadResolution,
2225                                               ASTContext &Context) {
2226  // Handle value-dependent integral null pointer constants correctly.
2227  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2228  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2229      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2230    return !InOverloadResolution;
2231
2232  return Expr->isNullPointerConstant(Context,
2233                    InOverloadResolutionExpr::NPC_ValueDependentIsNotNull
2234                                        : Expr::NPC_ValueDependentIsNull);
2235}
2236
2237/// IsPointerConversion - Determines whether the conversion of the
2238/// expression From, which has the (possibly adjusted) type FromType,
2239/// can be converted to the type ToType via a pointer conversion (C++
2240/// 4.10). If so, returns true and places the converted type (that
2241/// might differ from ToType in its cv-qualifiers at some level) into
2242/// ConvertedType.
2243///
2244/// This routine also supports conversions to and from block pointers
2245/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2246/// pointers to interfaces. FIXME: Once we've determined the
2247/// appropriate overloading rules for Objective-C, we may want to
2248/// split the Objective-C checks into a different routine; however,
2249/// GCC seems to consider all of these conversions to be pointer
2250/// conversions, so for now they live here. IncompatibleObjC will be
2251/// set if the conversion is an allowed Objective-C conversion that
2252/// should result in a warning.
2253bool Sema::IsPointerConversion(Expr *FromQualType FromTypeQualType ToType,
2254                               bool InOverloadResolution,
2255                               QualTypeConvertedType,
2256                               bool &IncompatibleObjC) {
2257  IncompatibleObjC = false;
2258  if (isObjCPointerConversion(FromTypeToTypeConvertedType,
2259                              IncompatibleObjC))
2260    return true;
2261
2262  // Conversion from a null pointer constant to any Objective-C pointer type.
2263  if (ToType->isObjCObjectPointerType() &&
2264      isNullPointerConstantForConversion(FromInOverloadResolutionContext)) {
2265    ConvertedType = ToType;
2266    return true;
2267  }
2268
2269  // Blocks: Block pointers can be converted to void*.
2270  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2271      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2272    ConvertedType = ToType;
2273    return true;
2274  }
2275  // Blocks: A null pointer constant can be converted to a block
2276  // pointer type.
2277  if (ToType->isBlockPointerType() &&
2278      isNullPointerConstantForConversion(FromInOverloadResolutionContext)) {
2279    ConvertedType = ToType;
2280    return true;
2281  }
2282
2283  // If the left-hand-side is nullptr_t, the right side can be a null
2284  // pointer constant.
2285  if (ToType->isNullPtrType() &&
2286      isNullPointerConstantForConversion(FromInOverloadResolutionContext)) {
2287    ConvertedType = ToType;
2288    return true;
2289  }
2290
2291  const PointerTypeToTypePtr = ToType->getAs<PointerType>();
2292  if (!ToTypePtr)
2293    return false;
2294
2295  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2296  if (isNullPointerConstantForConversion(FromInOverloadResolutionContext)) {
2297    ConvertedType = ToType;
2298    return true;
2299  }
2300
2301  // Beyond this point, both types need to be pointers
2302  // , including objective-c pointers.
2303  QualType ToPointeeType = ToTypePtr->getPointeeType();
2304  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2305      !getLangOpts().ObjCAutoRefCount) {
2306    ConvertedType = BuildSimilarlyQualifiedPointerType(
2307                                      FromType->getAs<ObjCObjectPointerType>(),
2308                                                       ToPointeeType,
2309                                                       ToTypeContext);
2310    return true;
2311  }
2312  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2313  if (!FromTypePtr)
2314    return false;
2315
2316  QualType FromPointeeType = FromTypePtr->getPointeeType();
2317
2318  // If the unqualified pointee types are the same, this can't be a
2319  // pointer conversion, so don't do all of the work below.
2320  if (Context.hasSameUnqualifiedType(FromPointeeTypeToPointeeType))
2321    return false;
2322
2323  // An rvalue of type "pointer to cv T," where T is an object type,
2324  // can be converted to an rvalue of type "pointer to cv void" (C++
2325  // 4.10p2).
2326  if (FromPointeeType->isIncompleteOrObjectType() &&
2327      ToPointeeType->isVoidType()) {
2328    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2329                                                       ToPointeeType,
2330                                                       ToTypeContext,
2331                                                   /*StripObjCLifetime=*/true);
2332    return true;
2333  }
2334
2335  // MSVC allows implicit function to void* type conversion.
2336  if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2337      ToPointeeType->isVoidType()) {
2338    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                       ToPointeeType,
2340                                                       ToTypeContext);
2341    return true;
2342  }
2343
2344  // When we're overloading in C, we allow a special kind of pointer
2345  // conversion for compatible-but-not-identical pointee types.
2346  if (!getLangOpts().CPlusPlus &&
2347      Context.typesAreCompatible(FromPointeeTypeToPointeeType)) {
2348    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2349                                                       ToPointeeType,
2350                                                       ToTypeContext);
2351    return true;
2352  }
2353
2354  // C++ [conv.ptr]p3:
2355  //
2356  //   An rvalue of type "pointer to cv D," where D is a class type,
2357  //   can be converted to an rvalue of type "pointer to cv B," where
2358  //   B is a base class (clause 10) of D. If B is an inaccessible
2359  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2360  //   necessitates this conversion is ill-formed. The result of the
2361  //   conversion is a pointer to the base class sub-object of the
2362  //   derived class object. The null pointer value is converted to
2363  //   the null pointer value of the destination type.
2364  //
2365  // Note that we do not check for ambiguity or inaccessibility
2366  // here. That is handled by CheckPointerConversion.
2367  if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2368      ToPointeeType->isRecordType() &&
2369      !Context.hasSameUnqualifiedType(FromPointeeTypeToPointeeType) &&
2370      IsDerivedFrom(From->getBeginLoc(), FromPointeeTypeToPointeeType)) {
2371    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2372                                                       ToPointeeType,
2373                                                       ToTypeContext);
2374    return true;
2375  }
2376
2377  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2378      Context.areCompatibleVectorTypes(FromPointeeTypeToPointeeType)) {
2379    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2380                                                       ToPointeeType,
2381                                                       ToTypeContext);
2382    return true;
2383  }
2384
2385  return false;
2386}
2387
2388/// Adopt the given qualifiers for the given type.
2389static QualType AdoptQualifiers(ASTContext &ContextQualType TQualifiers Qs){
2390  Qualifiers TQs = T.getQualifiers();
2391
2392  // Check whether qualifiers already match.
2393  if (TQs == Qs)
2394    return T;
2395
2396  if (Qs.compatiblyIncludes(TQs))
2397    return Context.getQualifiedType(TQs);
2398
2399  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2400}
2401
2402/// isObjCPointerConversion - Determines whether this is an
2403/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2404/// with the same arguments and return values.
2405bool Sema::isObjCPointerConversion(QualType FromTypeQualType ToType,
2406                                   QualTypeConvertedType,
2407                                   bool &IncompatibleObjC) {
2408  if (!getLangOpts().ObjC)
2409    return false;
2410
2411  // The set of qualifiers on the type we're converting from.
2412  Qualifiers FromQualifiers = FromType.getQualifiers();
2413
2414  // First, we handle all conversions on ObjC object pointer types.
2415  const ObjCObjectPointerTypeToObjCPtr =
2416    ToType->getAs<ObjCObjectPointerType>();
2417  const ObjCObjectPointerType *FromObjCPtr =
2418    FromType->getAs<ObjCObjectPointerType>();
2419
2420  if (ToObjCPtr && FromObjCPtr) {
2421    // If the pointee types are the same (ignoring qualifications),
2422    // then this is not a pointer conversion.
2423    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2424                                       FromObjCPtr->getPointeeType()))
2425      return false;
2426
2427    // Conversion between Objective-C pointers.
2428    if (Context.canAssignObjCInterfaces(ToObjCPtrFromObjCPtr)) {
2429      const ObjCInterfaceTypeLHS = ToObjCPtr->getInterfaceType();
2430      const ObjCInterfaceTypeRHS = FromObjCPtr->getInterfaceType();
2431      if (getLangOpts().CPlusPlus && LHS && RHS &&
2432          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2433                                                FromObjCPtr->getPointeeType()))
2434        return false;
2435      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2436                                                   ToObjCPtr->getPointeeType(),
2437                                                         ToTypeContext);
2438      ConvertedType = AdoptQualifiers(ContextConvertedTypeFromQualifiers);
2439      return true;
2440    }
2441
2442    if (Context.canAssignObjCInterfaces(FromObjCPtrToObjCPtr)) {
2443      // Okay: this is some kind of implicit downcast of Objective-C
2444      // interfaces, which is permitted. However, we're going to
2445      // complain about it.
2446      IncompatibleObjC = true;
2447      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2448                                                   ToObjCPtr->getPointeeType(),
2449                                                         ToTypeContext);
2450      ConvertedType = AdoptQualifiers(ContextConvertedTypeFromQualifiers);
2451      return true;
2452    }
2453  }
2454  // Beyond this point, both types need to be C pointers or block pointers.
2455  QualType ToPointeeType;
2456  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2457    ToPointeeType = ToCPtr->getPointeeType();
2458  else if (const BlockPointerType *ToBlockPtr =
2459            ToType->getAs<BlockPointerType>()) {
2460    // Objective C++: We're able to convert from a pointer to any object
2461    // to a block pointer type.
2462    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2463      ConvertedType = AdoptQualifiers(ContextToTypeFromQualifiers);
2464      return true;
2465    }
2466    ToPointeeType = ToBlockPtr->getPointeeType();
2467  }
2468  else if (FromType->getAs<BlockPointerType>() &&
2469           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2470    // Objective C++: We're able to convert from a block pointer type to a
2471    // pointer to any object.
2472    ConvertedType = AdoptQualifiers(ContextToTypeFromQualifiers);
2473    return true;
2474  }
2475  else
2476    return false;
2477
2478  QualType FromPointeeType;
2479  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2480    FromPointeeType = FromCPtr->getPointeeType();
2481  else if (const BlockPointerType *FromBlockPtr =
2482           FromType->getAs<BlockPointerType>())
2483    FromPointeeType = FromBlockPtr->getPointeeType();
2484  else
2485    return false;
2486
2487  // If we have pointers to pointers, recursively check whether this
2488  // is an Objective-C conversion.
2489  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2490      isObjCPointerConversion(FromPointeeTypeToPointeeTypeConvertedType,
2491                              IncompatibleObjC)) {
2492    // We always complain about this conversion.
2493    IncompatibleObjC = true;
2494    ConvertedType = Context.getPointerType(ConvertedType);
2495    ConvertedType = AdoptQualifiers(ContextConvertedTypeFromQualifiers);
2496    return true;
2497  }
2498  // Allow conversion of pointee being objective-c pointer to another one;
2499  // as in I* to id.
2500  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2501      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2502      isObjCPointerConversion(FromPointeeTypeToPointeeTypeConvertedType,
2503                              IncompatibleObjC)) {
2504
2505    ConvertedType = Context.getPointerType(ConvertedType);
2506    ConvertedType = AdoptQualifiers(ContextConvertedTypeFromQualifiers);
2507    return true;
2508  }
2509
2510  // If we have pointers to functions or blocks, check whether the only
2511  // differences in the argument and result types are in Objective-C
2512  // pointer conversions. If so, we permit the conversion (but
2513  // complain about it).
2514  const FunctionProtoType *FromFunctionType
2515    = FromPointeeType->getAs<FunctionProtoType>();
2516  const FunctionProtoType *ToFunctionType
2517    = ToPointeeType->getAs<FunctionProtoType>();
2518  if (FromFunctionType && ToFunctionType) {
2519    // If the function types are exactly the same, this isn't an
2520    // Objective-C pointer conversion.
2521    if (Context.getCanonicalType(FromPointeeType)
2522          == Context.getCanonicalType(ToPointeeType))
2523      return false;
2524
2525    // Perform the quick checks that will tell us whether these
2526    // function types are obviously different.
2527    if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2528        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2529        FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2530      return false;
2531
2532    bool HasObjCConversion = false;
2533    if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2534        Context.getCanonicalType(ToFunctionType->getReturnType())) {
2535      // Okay, the types match exactly. Nothing to do.
2536    } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2537                                       ToFunctionType->getReturnType(),
2538                                       ConvertedTypeIncompatibleObjC)) {
2539      // Okay, we have an Objective-C pointer conversion.
2540      HasObjCConversion = true;
2541    } else {
2542      // Function types are too different. Abort.
2543      return false;
2544    }
2545
2546    // Check argument types.
2547    for (unsigned ArgIdx = 0NumArgs = FromFunctionType->getNumParams();
2548         ArgIdx != NumArgs; ++ArgIdx) {
2549      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2550      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2551      if (Context.getCanonicalType(FromArgType)
2552            == Context.getCanonicalType(ToArgType)) {
2553        // Okay, the types match exactly. Nothing to do.
2554      } else if (isObjCPointerConversion(FromArgTypeToArgType,
2555                                         ConvertedTypeIncompatibleObjC)) {
2556        // Okay, we have an Objective-C pointer conversion.
2557        HasObjCConversion = true;
2558      } else {
2559        // Argument types are too different. Abort.
2560        return false;
2561      }
2562    }
2563
2564    if (HasObjCConversion) {
2565      // We had an Objective-C conversion. Allow this pointer
2566      // conversion, but complain about it.
2567      ConvertedType = AdoptQualifiers(ContextToTypeFromQualifiers);
2568      IncompatibleObjC = true;
2569      return true;
2570    }
2571  }
2572
2573  return false;
2574}
2575
2576/// Determine whether this is an Objective-C writeback conversion,
2577/// used for parameter passing when performing automatic reference counting.
2578///
2579/// \param FromType The type we're converting form.
2580///
2581/// \param ToType The type we're converting to.
2582///
2583/// \param ConvertedType The type that will be produced after applying
2584/// this conversion.
2585bool Sema::isObjCWritebackConversion(QualType FromTypeQualType ToType,
2586                                     QualType &ConvertedType) {
2587  if (!getLangOpts().ObjCAutoRefCount ||
2588      Context.hasSameUnqualifiedType(FromTypeToType))
2589    return false;
2590
2591  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2592  QualType ToPointee;
2593  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2594    ToPointee = ToPointer->getPointeeType();
2595  else
2596    return false;
2597
2598  Qualifiers ToQuals = ToPointee.getQualifiers();
2599  if (!ToPointee->isObjCLifetimeType() ||
2600      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2601      !ToQuals.withoutObjCLifetime().empty())
2602    return false;
2603
2604  // Argument must be a pointer to __strong to __weak.
2605  QualType FromPointee;
2606  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2607    FromPointee = FromPointer->getPointeeType();
2608  else
2609    return false;
2610
2611  Qualifiers FromQuals = FromPointee.getQualifiers();
2612  if (!FromPointee->isObjCLifetimeType() ||
2613      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2614       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2615    return false;
2616
2617  // Make sure that we have compatible qualifiers.
2618  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2619  if (!ToQuals.compatiblyIncludes(FromQuals))
2620    return false;
2621
2622  // Remove qualifiers from the pointee type we're converting from; they
2623  // aren't used in the compatibility check belong, and we'll be adding back
2624  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2625  FromPointee = FromPointee.getUnqualifiedType();
2626
2627  // The unqualified form of the pointee types must be compatible.
2628  ToPointee = ToPointee.getUnqualifiedType();
2629  bool IncompatibleObjC;
2630  if (Context.typesAreCompatible(FromPointeeToPointee))
2631    FromPointee = ToPointee;
2632  else if (!isObjCPointerConversion(FromPointeeToPointeeFromPointee,
2633                                    IncompatibleObjC))
2634    return false;
2635
2636  /// Construct the type we're converting to, which is a pointer to
2637  /// __autoreleasing pointee.
2638  FromPointee = Context.getQualifiedType(FromPointeeFromQuals);
2639  ConvertedType = Context.getPointerType(FromPointee);
2640  return true;
2641}
2642
2643bool Sema::IsBlockPointerConversion(QualType FromTypeQualType ToType,
2644                                    QualTypeConvertedType) {
2645  QualType ToPointeeType;
2646  if (const BlockPointerType *ToBlockPtr =
2647        ToType->getAs<BlockPointerType>())
2648    ToPointeeType = ToBlockPtr->getPointeeType();
2649  else
2650    return false;
2651
2652  QualType FromPointeeType;
2653  if (const BlockPointerType *FromBlockPtr =
2654      FromType->getAs<BlockPointerType>())
2655    FromPointeeType = FromBlockPtr->getPointeeType();
2656  else
2657    return false;
2658  // We have pointer to blocks, check whether the only
2659  // differences in the argument and result types are in Objective-C
2660  // pointer conversions. If so, we permit the conversion.
2661
2662  const FunctionProtoType *FromFunctionType
2663    = FromPointeeType->getAs<FunctionProtoType>();
2664  const FunctionProtoType *ToFunctionType
2665    = ToPointeeType->getAs<FunctionProtoType>();
2666
2667  if (!FromFunctionType || !ToFunctionType)
2668    return false;
2669
2670  if (Context.hasSameType(FromPointeeTypeToPointeeType))
2671    return true;
2672
2673  // Perform the quick checks that will tell us whether these
2674  // function types are obviously different.
2675  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2676      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2677    return false;
2678
2679  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2680  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2681  if (FromEInfo != ToEInfo)
2682    return false;
2683
2684  bool IncompatibleObjC = false;
2685  if (Context.hasSameType(FromFunctionType->getReturnType(),
2686                          ToFunctionType->getReturnType())) {
2687    // Okay, the types match exactly. Nothing to do.
2688  } else {
2689    QualType RHS = FromFunctionType->getReturnType();
2690    QualType LHS = ToFunctionType->getReturnType();
2691    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2692        !RHS.hasQualifiers() && LHS.hasQualifiers())
2693       LHS = LHS.getUnqualifiedType();
2694
2695     if (Context.hasSameType(RHS,LHS)) {
2696       // OK exact match.
2697     } else if (isObjCPointerConversion(RHSLHS,
2698                                        ConvertedTypeIncompatibleObjC)) {
2699     if (IncompatibleObjC)
2700       return false;
2701     // Okay, we have an Objective-C pointer conversion.
2702     }
2703     else
2704       return false;
2705   }
2706
2707   // Check argument types.
2708   for (unsigned ArgIdx = 0NumArgs = FromFunctionType->getNumParams();
2709        ArgIdx != NumArgs; ++ArgIdx) {
2710     IncompatibleObjC = false;
2711     QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2712     QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2713     if (Context.hasSameType(FromArgTypeToArgType)) {
2714       // Okay, the types match exactly. Nothing to do.
2715     } else if (isObjCPointerConversion(ToArgTypeFromArgType,
2716                                        ConvertedTypeIncompatibleObjC)) {
2717       if (IncompatibleObjC)
2718         return false;
2719       // Okay, we have an Objective-C pointer conversion.
2720     } else
2721       // Argument types are too different. Abort.
2722       return false;
2723   }
2724
2725   SmallVector<FunctionProtoType::ExtParameterInfo4NewParamInfos;
2726   bool CanUseToFPTCanUseFromFPT;
2727   if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2728                                      CanUseToFPT, CanUseFromFPT,
2729                                      NewParamInfos))
2730     return false;
2731
2732   ConvertedType = ToType;
2733   return true;
2734}
2735
2736enum {
2737  ft_default,
2738  ft_different_class,
2739  ft_parameter_arity,
2740  ft_parameter_mismatch,
2741  ft_return_type,
2742  ft_qualifer_mismatch,
2743  ft_noexcept
2744};
2745
2746/// Attempts to get the FunctionProtoType from a Type. Handles
2747/// MemberFunctionPointers properly.
2748static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2749  if (auto *FPT = FromType->getAs<FunctionProtoType>())
2750    return FPT;
2751
2752  if (auto *MPT = FromType->getAs<MemberPointerType>())
2753    return MPT->getPointeeType()->getAs<FunctionProtoType>();
2754
2755  return nullptr;
2756}
2757
2758/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2759/// function types.  Catches different number of parameter, mismatch in
2760/// parameter types, and different return types.
2761void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2762                                      QualType FromTypeQualType ToType) {
2763  // If either type is not valid, include no extra info.
2764  if (FromType.isNull() || ToType.isNull()) {
2765    PDiag << ft_default;
2766    return;
2767  }
2768
2769  // Get the function type from the pointers.
2770  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2771    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2772                            *ToMember = ToType->getAs<MemberPointerType>();
2773    if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2774      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2775            << QualType(FromMember->getClass(), 0);
2776      return;
2777    }
2778    FromType = FromMember->getPointeeType();
2779    ToType = ToMember->getPointeeType();
2780  }
2781
2782  if (FromType->isPointerType())
2783    FromType = FromType->getPointeeType();
2784  if (ToType->isPointerType())
2785    ToType = ToType->getPointeeType();
2786
2787  // Remove references.
2788  FromType = FromType.getNonReferenceType();
2789  ToType = ToType.getNonReferenceType();
2790
2791  // Don't print extra info for non-specialized template functions.
2792  if (FromType->isInstantiationDependentType() &&
2793      !FromType->getAs<TemplateSpecializationType>()) {
2794    PDiag << ft_default;
2795    return;
2796  }
2797
2798  // No extra info for same types.
2799  if (Context.hasSameType(FromTypeToType)) {
2800    PDiag << ft_default;
2801    return;
2802  }
2803
2804  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2805                          *ToFunction = tryGetFunctionProtoType(ToType);
2806
2807  // Both types need to be function types.
2808  if (!FromFunction || !ToFunction) {
2809    PDiag << ft_default;
2810    return;
2811  }
2812
2813  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2814    PDiag << ft_parameter_arity << ToFunction->getNumParams()
2815          << FromFunction->getNumParams();
2816    return;
2817  }
2818
2819  // Handle different parameter types.
2820  unsigned ArgPos;
2821  if (!FunctionParamTypesAreEqual(FromFunctionToFunction, &ArgPos)) {
2822    PDiag << ft_parameter_mismatch << ArgPos + 1
2823          << ToFunction->getParamType(ArgPos)
2824          << FromFunction->getParamType(ArgPos);
2825    return;
2826  }
2827
2828  // Handle different return type.
2829  if (!Context.hasSameType(FromFunction->getReturnType(),
2830                           ToFunction->getReturnType())) {
2831    PDiag << ft_return_type << ToFunction->getReturnType()
2832          << FromFunction->getReturnType();
2833    return;
2834  }
2835
2836  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2837    PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2838          << FromFunction->getMethodQuals();
2839    return;
2840  }
2841
2842  // Handle exception specification differences on canonical type (in C++17
2843  // onwards).
2844  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2845          ->isNothrow() !=
2846      cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2847          ->isNothrow()) {
2848    PDiag << ft_noexcept;
2849    return;
2850  }
2851
2852  // Unable to find a difference, so add no extra info.
2853  PDiag << ft_default;
2854}
2855
2856/// FunctionParamTypesAreEqual - This routine checks two function proto types
2857/// for equality of their argument types. Caller has already checked that
2858/// they have same number of arguments.  If the parameters are different,
2859/// ArgPos will have the parameter index of the first different parameter.
2860bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2861                                      const FunctionProtoType *NewType,
2862                                      unsigned *ArgPos) {
2863  for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2864                                              N = NewType->param_type_begin(),
2865                                              E = OldType->param_type_end();
2866       O && (O != E); ++O, ++N) {
2867    if (!Context.hasSameType(O->getUnqualifiedType(),
2868                             N->getUnqualifiedType())) {
2869      if (ArgPos)
2870        *ArgPos = O - OldType->param_type_begin();
2871      return false;
2872    }
2873  }
2874  return true;
2875}
2876
2877/// CheckPointerConversion - Check the pointer conversion from the
2878/// expression From to the type ToType. This routine checks for
2879/// ambiguous or inaccessible derived-to-base pointer
2880/// conversions for which IsPointerConversion has already returned
2881/// true. It returns true and produces a diagnostic if there was an
2882/// error, or returns false otherwise.
2883bool Sema::CheckPointerConversion(Expr *FromQualType ToType,
2884                                  CastKind &Kind,
2885                                  CXXCastPathBasePath,
2886                                  bool IgnoreBaseAccess,
2887                                  bool Diagnose) {
2888  QualType FromType = From->getType();
2889  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2890
2891  Kind = CK_BitCast;
2892
2893  if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2894      From->isNullPointerConstant(ContextExpr::NPC_ValueDependentIsNotNull) ==
2895          Expr::NPCK_ZeroExpression) {
2896    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2897      DiagRuntimeBehavior(From->getExprLoc(), From,
2898                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2899                            << ToType << From->getSourceRange());
2900    else if (!isUnevaluatedContext())
2901      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2902        << ToType << From->getSourceRange();
2903  }
2904  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2905    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2906      QualType FromPointeeType = FromPtrType->getPointeeType(),
2907               ToPointeeType   = ToPtrType->getPointeeType();
2908
2909      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2910          !Context.hasSameUnqualifiedType(FromPointeeTypeToPointeeType)) {
2911        // We must have a derived-to-base conversion. Check an
2912        // ambiguous or inaccessible conversion.
2913        unsigned InaccessibleID = 0;
2914        unsigned AmbigiousID = 0;
2915        if (Diagnose) {
2916          InaccessibleID = diag::err_upcast_to_inaccessible_base;
2917          AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2918        }
2919        if (CheckDerivedToBaseConversion(
2920                FromPointeeTypeToPointeeTypeInaccessibleIDAmbigiousID,
2921                From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2922                &BasePathIgnoreBaseAccess))
2923          return true;
2924
2925        // The conversion was successful.
2926        Kind = CK_DerivedToBase;
2927      }
2928
2929      if (Diagnose && !IsCStyleOrFunctionalCast &&
2930          FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2931         (0) . __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 2932, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getLangOpts().MSVCCompat &&
2932 (0) . __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 2932, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               "this should only be possible with MSVCCompat!");
2933        Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2934            << From->getSourceRange();
2935      }
2936    }
2937  } else if (const ObjCObjectPointerType *ToPtrType =
2938               ToType->getAs<ObjCObjectPointerType>()) {
2939    if (const ObjCObjectPointerType *FromPtrType =
2940          FromType->getAs<ObjCObjectPointerType>()) {
2941      // Objective-C++ conversions are always okay.
2942      // FIXME: We should have a different class of conversions for the
2943      // Objective-C++ implicit conversions.
2944      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2945        return false;
2946    } else if (FromType->isBlockPointerType()) {
2947      Kind = CK_BlockPointerToObjCPointerCast;
2948    } else {
2949      Kind = CK_CPointerToObjCPointerCast;
2950    }
2951  } else if (ToType->isBlockPointerType()) {
2952    if (!FromType->isBlockPointerType())
2953      Kind = CK_AnyPointerToBlockPointerCast;
2954  }
2955
2956  // We shouldn't fall into this case unless it's valid for other
2957  // reasons.
2958  if (From->isNullPointerConstant(ContextExpr::NPC_ValueDependentIsNull))
2959    Kind = CK_NullToPointer;
2960
2961  return false;
2962}
2963
2964/// IsMemberPointerConversion - Determines whether the conversion of the
2965/// expression From, which has the (possibly adjusted) type FromType, can be
2966/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2967/// If so, returns true and places the converted type (that might differ from
2968/// ToType in its cv-qualifiers at some level) into ConvertedType.
2969bool Sema::IsMemberPointerConversion(Expr *FromQualType FromType,
2970                                     QualType ToType,
2971                                     bool InOverloadResolution,
2972                                     QualType &ConvertedType) {
2973  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2974  if (!ToTypePtr)
2975    return false;
2976
2977  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2978  if (From->isNullPointerConstant(Context,
2979                    InOverloadResolutionExpr::NPC_ValueDependentIsNotNull
2980                                        : Expr::NPC_ValueDependentIsNull)) {
2981    ConvertedType = ToType;
2982    return true;
2983  }
2984
2985  // Otherwise, both types have to be member pointers.
2986  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2987  if (!FromTypePtr)
2988    return false;
2989
2990  // A pointer to member of B can be converted to a pointer to member of D,
2991  // where D is derived from B (C++ 4.11p2).
2992  QualType FromClass(FromTypePtr->getClass(), 0);
2993  QualType ToClass(ToTypePtr->getClass(), 0);
2994
2995  if (!Context.hasSameUnqualifiedType(FromClassToClass) &&
2996      IsDerivedFrom(From->getBeginLoc(), ToClassFromClass)) {
2997    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2998                                                 ToClass.getTypePtr());
2999    return true;
3000  }
3001
3002  return false;
3003}
3004
3005/// CheckMemberPointerConversion - Check the member pointer conversion from the
3006/// expression From to the type ToType. This routine checks for ambiguous or
3007/// virtual or inaccessible base-to-derived member pointer conversions
3008/// for which IsMemberPointerConversion has already returned true. It returns
3009/// true and produces a diagnostic if there was an error, or returns false
3010/// otherwise.
3011bool Sema::CheckMemberPointerConversion(Expr *FromQualType ToType,
3012                                        CastKind &Kind,
3013                                        CXXCastPath &BasePath,
3014                                        bool IgnoreBaseAccess) {
3015  QualType FromType = From->getType();
3016  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3017  if (!FromPtrType) {
3018    // This must be a null pointer to member pointer conversion
3019     (0) . __assert_fail ("From->isNullPointerConstant(Context, Expr..NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3021, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(From->isNullPointerConstant(Context,
3020 (0) . __assert_fail ("From->isNullPointerConstant(Context, Expr..NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3021, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                                       Expr::NPC_ValueDependentIsNull) &&
3021 (0) . __assert_fail ("From->isNullPointerConstant(Context, Expr..NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3021, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Expr must be null pointer constant!");
3022    Kind = CK_NullToMemberPointer;
3023    return false;
3024  }
3025
3026  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3027   (0) . __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3028, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ToPtrType && "No member pointer cast has a target type "
3028 (0) . __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3028, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                      "that is not a member pointer.");
3029
3030  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3031  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3032
3033  // FIXME: What about dependent types?
3034   (0) . __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3034, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FromClass->isRecordType() && "Pointer into non-class.");
3035   (0) . __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3035, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ToClass->isRecordType() && "Pointer into non-class.");
3036
3037  CXXBasePaths Paths(/*FindAmbiguities=*/true/*RecordPaths=*/true,
3038                     /*DetectVirtual=*/true);
3039  bool DerivationOkay =
3040      IsDerivedFrom(From->getBeginLoc(), ToClassFromClassPaths);
3041   (0) . __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3042, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(DerivationOkay &&
3042 (0) . __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 3042, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Should not have been called if derivation isn't OK.");
3043  (void)DerivationOkay;
3044
3045  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3046                                  getUnqualifiedType())) {
3047    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3048    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3049      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3050    return true;
3051  }
3052
3053  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3054    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3055      << FromClass << ToClass << QualType(VBase, 0)
3056      << From->getSourceRange();
3057    return true;
3058  }
3059
3060  if (!IgnoreBaseAccess)
3061    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3062                         Paths.front(),
3063                         diag::err_downcast_from_inaccessible_base);
3064
3065  // Must be a base to derived member conversion.
3066  BuildBasePathArray(PathsBasePath);
3067  Kind = CK_BaseToDerivedMemberPointer;
3068  return false;
3069}
3070
3071/// Determine whether the lifetime conversion between the two given
3072/// qualifiers sets is nontrivial.
3073static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3074                                               Qualifiers ToQuals) {
3075  // Converting anything to const __unsafe_unretained is trivial.
3076  if (ToQuals.hasConst() &&
3077      ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3078    return false;
3079
3080  return true;
3081}
3082
3083/// IsQualificationConversion - Determines whether the conversion from
3084/// an rvalue of type FromType to ToType is a qualification conversion
3085/// (C++ 4.4).
3086///
3087/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3088/// when the qualification conversion involves a change in the Objective-C
3089/// object lifetime.
3090bool
3091Sema::IsQualificationConversion(QualType FromTypeQualType ToType,
3092                                bool CStylebool &ObjCLifetimeConversion) {
3093  FromType = Context.getCanonicalType(FromType);
3094  ToType = Context.getCanonicalType(ToType);
3095  ObjCLifetimeConversion = false;
3096
3097  // If FromType and ToType are the same type, this is not a
3098  // qualification conversion.
3099  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3100    return false;
3101
3102  // (C++ 4.4p4):
3103  //   A conversion can add cv-qualifiers at levels other than the first
3104  //   in multi-level pointers, subject to the following rules: [...]
3105  bool PreviousToQualsIncludeConst = true;
3106  bool UnwrappedAnyPointer = false;
3107  while (Context.UnwrapSimilarTypes(FromTypeToType)) {
3108    // Within each iteration of the loop, we check the qualifiers to
3109    // determine if this still looks like a qualification
3110    // conversion. Then, if all is well, we unwrap one more level of
3111    // pointers or pointers-to-members and do it all again
3112    // until there are no more pointers or pointers-to-members left to
3113    // unwrap.
3114    UnwrappedAnyPointer = true;
3115
3116    Qualifiers FromQuals = FromType.getQualifiers();
3117    Qualifiers ToQuals = ToType.getQualifiers();
3118
3119    // Ignore __unaligned qualifier if this type is void.
3120    if (ToType.getUnqualifiedType()->isVoidType())
3121      FromQuals.removeUnaligned();
3122
3123    // Objective-C ARC:
3124    //   Check Objective-C lifetime conversions.
3125    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3126        UnwrappedAnyPointer) {
3127      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3128        if (isNonTrivialObjCLifetimeConversion(FromQualsToQuals))
3129          ObjCLifetimeConversion = true;
3130        FromQuals.removeObjCLifetime();
3131        ToQuals.removeObjCLifetime();
3132      } else {
3133        // Qualification conversions cannot cast between different
3134        // Objective-C lifetime qualifiers.
3135        return false;
3136      }
3137    }
3138
3139    // Allow addition/removal of GC attributes but not changing GC attributes.
3140    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3141        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3142      FromQuals.removeObjCGCAttr();
3143      ToQuals.removeObjCGCAttr();
3144    }
3145
3146    //   -- for every j > 0, if const is in cv 1,j then const is in cv
3147    //      2,j, and similarly for volatile.
3148    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3149      return false;
3150
3151    //   -- if the cv 1,j and cv 2,j are different, then const is in
3152    //      every cv for 0 < k < j.
3153    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3154        && !PreviousToQualsIncludeConst)
3155      return false;
3156
3157    // Keep track of whether all prior cv-qualifiers in the "to" type
3158    // include const.
3159    PreviousToQualsIncludeConst
3160      = PreviousToQualsIncludeConst && ToQuals.hasConst();
3161  }
3162
3163  // Allows address space promotion by language rules implemented in
3164  // Type::Qualifiers::isAddressSpaceSupersetOf.
3165  Qualifiers FromQuals = FromType.getQualifiers();
3166  Qualifiers ToQuals = ToType.getQualifiers();
3167  if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3168      !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3169    return false;
3170  }
3171
3172  // We are left with FromType and ToType being the pointee types
3173  // after unwrapping the original FromType and ToType the same number
3174  // of types. If we unwrapped any pointers, and if FromType and
3175  // ToType have the same unqualified type (since we checked
3176  // qualifiers above), then this is a qualification conversion.
3177  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3178}
3179
3180/// - Determine whether this is a conversion from a scalar type to an
3181/// atomic type.
3182///
3183/// If successful, updates \c SCS's second and third steps in the conversion
3184/// sequence to finish the conversion.
3185static bool tryAtomicConversion(Sema &SExpr *FromQualType ToType,
3186                                bool InOverloadResolution,
3187                                StandardConversionSequence &SCS,
3188                                bool CStyle) {
3189  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3190  if (!ToAtomic)
3191    return false;
3192
3193  StandardConversionSequence InnerSCS;
3194  if (!IsStandardConversion(SFromToAtomic->getValueType(),
3195                            InOverloadResolutionInnerSCS,
3196                            CStyle/*AllowObjCWritebackConversion=*/false))
3197    return false;
3198
3199  SCS.Second = InnerSCS.Second;
3200  SCS.setToType(1InnerSCS.getToType(1));
3201  SCS.Third = InnerSCS.Third;
3202  SCS.QualificationIncludesObjCLifetime
3203    = InnerSCS.QualificationIncludesObjCLifetime;
3204  SCS.setToType(2InnerSCS.getToType(2));
3205  return true;
3206}
3207
3208static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3209                                              CXXConstructorDecl *Constructor,
3210                                              QualType Type) {
3211  const FunctionProtoType *CtorType =
3212      Constructor->getType()->getAs<FunctionProtoType>();
3213  if (CtorType->getNumParams() > 0) {
3214    QualType FirstArg = CtorType->getParamType(0);
3215    if (Context.hasSameUnqualifiedType(TypeFirstArg.getNonReferenceType()))
3216      return true;
3217  }
3218  return false;
3219}
3220
3221static OverloadingResult
3222IsInitializerListConstructorConversion(Sema &SExpr *FromQualType ToType,
3223                                       CXXRecordDecl *To,
3224                                       UserDefinedConversionSequence &User,
3225                                       OverloadCandidateSet &CandidateSet,
3226                                       bool AllowExplicit) {
3227  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3228  for (auto *D : S.LookupConstructors(To)) {
3229    auto Info = getConstructorInfo(D);
3230    if (!Info)
3231      continue;
3232
3233    bool Usable = !Info.Constructor->isInvalidDecl() &&
3234                  S.isInitListConstructor(Info.Constructor) &&
3235                  (AllowExplicit || !Info.Constructor->isExplicit());
3236    if (Usable) {
3237      // If the first argument is (a reference to) the target type,
3238      // suppress conversions.
3239      bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3240          S.Context, Info.Constructor, ToType);
3241      if (Info.ConstructorTmpl)
3242        S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3243                                       /*ExplicitArgs*/ nullptr, From,
3244                                       CandidateSet, SuppressUserConversions);
3245      else
3246        S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3247                               CandidateSet, SuppressUserConversions);
3248    }
3249  }
3250
3251  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3252
3253  OverloadCandidateSet::iterator Best;
3254  switch (auto Result =
3255              CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3256  case OR_Deleted:
3257  case OR_Success: {
3258    // Record the standard conversion we used and the conversion function.
3259    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3260    QualType ThisType = Constructor->getThisType();
3261    // Initializer lists don't have conversions as such.
3262    User.Before.setAsIdentityConversion();
3263    User.HadMultipleCandidates = HadMultipleCandidates;
3264    User.ConversionFunction = Constructor;
3265    User.FoundConversionFunction = Best->FoundDecl;
3266    User.After.setAsIdentityConversion();
3267    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3268    User.After.setAllToTypes(ToType);
3269    return Result;
3270  }
3271
3272  case OR_No_Viable_Function:
3273    return OR_No_Viable_Function;
3274  case OR_Ambiguous:
3275    return OR_Ambiguous;
3276  }
3277
3278  llvm_unreachable("Invalid OverloadResult!");
3279}
3280
3281/// Determines whether there is a user-defined conversion sequence
3282/// (C++ [over.ics.user]) that converts expression From to the type
3283/// ToType. If such a conversion exists, User will contain the
3284/// user-defined conversion sequence that performs such a conversion
3285/// and this routine will return true. Otherwise, this routine returns
3286/// false and User is unspecified.
3287///
3288/// \param AllowExplicit  true if the conversion should consider C++0x
3289/// "explicit" conversion functions as well as non-explicit conversion
3290/// functions (C++0x [class.conv.fct]p2).
3291///
3292/// \param AllowObjCConversionOnExplicit true if the conversion should
3293/// allow an extra Objective-C pointer conversion on uses of explicit
3294/// constructors. Requires \c AllowExplicit to also be set.
3295static OverloadingResult
3296IsUserDefinedConversion(Sema &SExpr *FromQualType ToType,
3297                        UserDefinedConversionSequence &User,
3298                        OverloadCandidateSet &CandidateSet,
3299                        bool AllowExplicit,
3300                        bool AllowObjCConversionOnExplicit) {
3301  assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3302  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3303
3304  // Whether we will only visit constructors.
3305  bool ConstructorsOnly = false;
3306
3307  // If the type we are conversion to is a class type, enumerate its
3308  // constructors.
3309  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3310    // C++ [over.match.ctor]p1:
3311    //   When objects of class type are direct-initialized (8.5), or
3312    //   copy-initialized from an expression of the same or a
3313    //   derived class type (8.5), overload resolution selects the
3314    //   constructor. [...] For copy-initialization, the candidate
3315    //   functions are all the converting constructors (12.3.1) of
3316    //   that class. The argument list is the expression-list within
3317    //   the parentheses of the initializer.
3318    if (S.Context.hasSameUnqualifiedType(ToTypeFrom->getType()) ||
3319        (From->getType()->getAs<RecordType>() &&
3320         S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3321      ConstructorsOnly = true;
3322
3323    if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3324      // We're not going to find any constructors.
3325    } else if (CXXRecordDecl *ToRecordDecl
3326                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3327
3328      Expr **Args = &From;
3329      unsigned NumArgs = 1;
3330      bool ListInitializing = false;
3331      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3332        // But first, see if there is an init-list-constructor that will work.
3333        OverloadingResult Result = IsInitializerListConstructorConversion(
3334            SFromToTypeToRecordDeclUserCandidateSetAllowExplicit);
3335        if (Result != OR_No_Viable_Function)
3336          return Result;
3337        // Never mind.
3338        CandidateSet.clear(
3339            OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3340
3341        // If we're list-initializing, we pass the individual elements as
3342        // arguments, not the entire list.
3343        Args = InitList->getInits();
3344        NumArgs = InitList->getNumInits();
3345        ListInitializing = true;
3346      }
3347
3348      for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3349        auto Info = getConstructorInfo(D);
3350        if (!Info)
3351          continue;
3352
3353        bool Usable = !Info.Constructor->isInvalidDecl();
3354        if (ListInitializing)
3355          Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3356        else
3357          Usable = Usable &&
3358                   Info.Constructor->isConvertingConstructor(AllowExplicit);
3359        if (Usable) {
3360          bool SuppressUserConversions = !ConstructorsOnly;
3361          if (SuppressUserConversions && ListInitializing) {
3362            SuppressUserConversions = false;
3363            if (NumArgs == 1) {
3364              // If the first argument is (a reference to) the target type,
3365              // suppress conversions.
3366              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3367                  S.Context, Info.Constructor, ToType);
3368            }
3369          }
3370          if (Info.ConstructorTmpl)
3371            S.AddTemplateOverloadCandidate(
3372                Info.ConstructorTmpl, Info.FoundDecl,
3373                /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3374                CandidateSet, SuppressUserConversions);
3375          else
3376            // Allow one user-defined conversion when user specifies a
3377            // From->ToType conversion via an static cast (c-style, etc).
3378            S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3379                                   llvm::makeArrayRef(Args, NumArgs),
3380                                   CandidateSet, SuppressUserConversions);
3381        }
3382      }
3383    }
3384  }
3385
3386  // Enumerate conversion functions, if we're allowed to.
3387  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3388  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3389    // No conversion functions from incomplete types.
3390  } else if (const RecordType *FromRecordType =
3391                 From->getType()->getAs<RecordType>()) {
3392    if (CXXRecordDecl *FromRecordDecl
3393         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3394      // Add all of the conversion functions as candidates.
3395      const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3396      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3397        DeclAccessPair FoundDecl = I.getPair();
3398        NamedDecl *D = FoundDecl.getDecl();
3399        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3400        if (isa<UsingShadowDecl>(D))
3401          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3402
3403        CXXConversionDecl *Conv;
3404        FunctionTemplateDecl *ConvTemplate;
3405        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3406          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3407        else
3408          Conv = cast<CXXConversionDecl>(D);
3409
3410        if (AllowExplicit || !Conv->isExplicit()) {
3411          if (ConvTemplate)
3412            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3413                                             ActingContext, From, ToType,
3414                                             CandidateSet,
3415                                             AllowObjCConversionOnExplicit);
3416          else
3417            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3418                                     From, ToType, CandidateSet,
3419                                     AllowObjCConversionOnExplicit);
3420        }
3421      }
3422    }
3423  }
3424
3425  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3426
3427  OverloadCandidateSet::iterator Best;
3428  switch (auto Result =
3429              CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3430  case OR_Success:
3431  case OR_Deleted:
3432    // Record the standard conversion we used and the conversion function.
3433    if (CXXConstructorDecl *Constructor
3434          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3435      // C++ [over.ics.user]p1:
3436      //   If the user-defined conversion is specified by a
3437      //   constructor (12.3.1), the initial standard conversion
3438      //   sequence converts the source type to the type required by
3439      //   the argument of the constructor.
3440      //
3441      QualType ThisType = Constructor->getThisType();
3442      if (isa<InitListExpr>(From)) {
3443        // Initializer lists don't have conversions as such.
3444        User.Before.setAsIdentityConversion();
3445      } else {
3446        if (Best->Conversions[0].isEllipsis())
3447          User.EllipsisConversion = true;
3448        else {
3449          User.Before = Best->Conversions[0].Standard;
3450          User.EllipsisConversion = false;
3451        }
3452      }
3453      User.HadMultipleCandidates = HadMultipleCandidates;
3454      User.ConversionFunction = Constructor;
3455      User.FoundConversionFunction = Best->FoundDecl;
3456      User.After.setAsIdentityConversion();
3457      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3458      User.After.setAllToTypes(ToType);
3459      return Result;
3460    }
3461    if (CXXConversionDecl *Conversion
3462                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3463      // C++ [over.ics.user]p1:
3464      //
3465      //   [...] If the user-defined conversion is specified by a
3466      //   conversion function (12.3.2), the initial standard
3467      //   conversion sequence converts the source type to the
3468      //   implicit object parameter of the conversion function.
3469      User.Before = Best->Conversions[0].Standard;
3470      User.HadMultipleCandidates = HadMultipleCandidates;
3471      User.ConversionFunction = Conversion;
3472      User.FoundConversionFunction = Best->FoundDecl;
3473      User.EllipsisConversion = false;
3474
3475      // C++ [over.ics.user]p2:
3476      //   The second standard conversion sequence converts the
3477      //   result of the user-defined conversion to the target type
3478      //   for the sequence. Since an implicit conversion sequence
3479      //   is an initialization, the special rules for
3480      //   initialization by user-defined conversion apply when
3481      //   selecting the best user-defined conversion for a
3482      //   user-defined conversion sequence (see 13.3.3 and
3483      //   13.3.3.1).
3484      User.After = Best->FinalConversion;
3485      return Result;
3486    }
3487    llvm_unreachable("Not a constructor or conversion function?");
3488
3489  case OR_No_Viable_Function:
3490    return OR_No_Viable_Function;
3491
3492  case OR_Ambiguous:
3493    return OR_Ambiguous;
3494  }
3495
3496  llvm_unreachable("Invalid OverloadResult!");
3497}
3498
3499bool
3500Sema::DiagnoseMultipleUserDefinedConversion(Expr *FromQualType ToType) {
3501  ImplicitConversionSequence ICS;
3502  OverloadCandidateSet CandidateSet(From->getExprLoc(),
3503                                    OverloadCandidateSet::CSK_Normal);
3504  OverloadingResult OvResult =
3505    IsUserDefinedConversion(*thisFromToTypeICS.UserDefined,
3506                            CandidateSetfalsefalse);
3507  if (OvResult == OR_Ambiguous)
3508    Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3509        << From->getType() << ToType << From->getSourceRange();
3510  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3511    if (!RequireCompleteType(From->getBeginLoc(), ToType,
3512                             diag::err_typecheck_nonviable_condition_incomplete,
3513                             From->getType(), From->getSourceRange()))
3514      Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3515          << false << From->getType() << From->getSourceRange() << ToType;
3516  } else
3517    return false;
3518  CandidateSet.NoteCandidates(*thisOCD_AllCandidatesFrom);
3519  return true;
3520}
3521
3522/// Compare the user-defined conversion functions or constructors
3523/// of two user-defined conversion sequences to determine whether any ordering
3524/// is possible.
3525static ImplicitConversionSequence::CompareKind
3526compareConversionFunctions(Sema &SFunctionDecl *Function1,
3527                           FunctionDecl *Function2) {
3528  if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3529    return ImplicitConversionSequence::Indistinguishable;
3530
3531  // Objective-C++:
3532  //   If both conversion functions are implicitly-declared conversions from
3533  //   a lambda closure type to a function pointer and a block pointer,
3534  //   respectively, always prefer the conversion to a function pointer,
3535  //   because the function pointer is more lightweight and is more likely
3536  //   to keep code working.
3537  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3538  if (!Conv1)
3539    return ImplicitConversionSequence::Indistinguishable;
3540
3541  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3542  if (!Conv2)
3543    return ImplicitConversionSequence::Indistinguishable;
3544
3545  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3546    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3547    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3548    if (Block1 != Block2)
3549      return Block1 ? ImplicitConversionSequence::Worse
3550                    : ImplicitConversionSequence::Better;
3551  }
3552
3553  return ImplicitConversionSequence::Indistinguishable;
3554}
3555
3556static bool hasDeprecatedStringLiteralToCharPtrConversion(
3557    const ImplicitConversionSequence &ICS) {
3558  return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3559         (ICS.isUserDefined() &&
3560          ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3561}
3562
3563/// CompareImplicitConversionSequences - Compare two implicit
3564/// conversion sequences to determine whether one is better than the
3565/// other or if they are indistinguishable (C++ 13.3.3.2).
3566static ImplicitConversionSequence::CompareKind
3567CompareImplicitConversionSequences(Sema &SSourceLocation Loc,
3568                                   const ImplicitConversionSequenceICS1,
3569                                   const ImplicitConversionSequenceICS2)
3570{
3571  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3572  // conversion sequences (as defined in 13.3.3.1)
3573  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3574  //      conversion sequence than a user-defined conversion sequence or
3575  //      an ellipsis conversion sequence, and
3576  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3577  //      conversion sequence than an ellipsis conversion sequence
3578  //      (13.3.3.1.3).
3579  //
3580  // C++0x [over.best.ics]p10:
3581  //   For the purpose of ranking implicit conversion sequences as
3582  //   described in 13.3.3.2, the ambiguous conversion sequence is
3583  //   treated as a user-defined sequence that is indistinguishable
3584  //   from any other user-defined conversion sequence.
3585
3586  // String literal to 'char *' conversion has been deprecated in C++03. It has
3587  // been removed from C++11. We still accept this conversion, if it happens at
3588  // the best viable function. Otherwise, this conversion is considered worse
3589  // than ellipsis conversion. Consider this as an extension; this is not in the
3590  // standard. For example:
3591  //
3592  // int &f(...);    // #1
3593  // void f(char*);  // #2
3594  // void g() { int &r = f("foo"); }
3595  //
3596  // In C++03, we pick #2 as the best viable function.
3597  // In C++11, we pick #1 as the best viable function, because ellipsis
3598  // conversion is better than string-literal to char* conversion (since there
3599  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3600  // convert arguments, #2 would be the best viable function in C++11.
3601  // If the best viable function has this conversion, a warning will be issued
3602  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3603
3604  if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3605      hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3606      hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3607    return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3608               ? ImplicitConversionSequence::Worse
3609               : ImplicitConversionSequence::Better;
3610
3611  if (ICS1.getKindRank() < ICS2.getKindRank())
3612    return ImplicitConversionSequence::Better;
3613  if (ICS2.getKindRank() < ICS1.getKindRank())
3614    return ImplicitConversionSequence::Worse;
3615
3616  // The following checks require both conversion sequences to be of
3617  // the same kind.
3618  if (ICS1.getKind() != ICS2.getKind())
3619    return ImplicitConversionSequence::Indistinguishable;
3620
3621  ImplicitConversionSequence::CompareKind Result =
3622      ImplicitConversionSequence::Indistinguishable;
3623
3624  // Two implicit conversion sequences of the same form are
3625  // indistinguishable conversion sequences unless one of the
3626  // following rules apply: (C++ 13.3.3.2p3):
3627
3628  // List-initialization sequence L1 is a better conversion sequence than
3629  // list-initialization sequence L2 if:
3630  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3631  //   if not that,
3632  // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3633  //   and N1 is smaller than N2.,
3634  // even if one of the other rules in this paragraph would otherwise apply.
3635  if (!ICS1.isBad()) {
3636    if (ICS1.isStdInitializerListElement() &&
3637        !ICS2.isStdInitializerListElement())
3638      return ImplicitConversionSequence::Better;
3639    if (!ICS1.isStdInitializerListElement() &&
3640        ICS2.isStdInitializerListElement())
3641      return ImplicitConversionSequence::Worse;
3642  }
3643
3644  if (ICS1.isStandard())
3645    // Standard conversion sequence S1 is a better conversion sequence than
3646    // standard conversion sequence S2 if [...]
3647    Result = CompareStandardConversionSequences(SLoc,
3648                                                ICS1.Standard, ICS2.Standard);
3649  else if (ICS1.isUserDefined()) {
3650    // User-defined conversion sequence U1 is a better conversion
3651    // sequence than another user-defined conversion sequence U2 if
3652    // they contain the same user-defined conversion function or
3653    // constructor and if the second standard conversion sequence of
3654    // U1 is better than the second standard conversion sequence of
3655    // U2 (C++ 13.3.3.2p3).
3656    if (ICS1.UserDefined.ConversionFunction ==
3657          ICS2.UserDefined.ConversionFunction)
3658      Result = CompareStandardConversionSequences(SLoc,
3659                                                  ICS1.UserDefined.After,
3660                                                  ICS2.UserDefined.After);
3661    else
3662      Result = compareConversionFunctions(S,
3663                                          ICS1.UserDefined.ConversionFunction,
3664                                          ICS2.UserDefined.ConversionFunction);
3665  }
3666
3667  return Result;
3668}
3669
3670// Per 13.3.3.2p3, compare the given standard conversion sequences to
3671// determine if one is a proper subset of the other.
3672static ImplicitConversionSequence::CompareKind
3673compareStandardConversionSubsets(ASTContext &Context,
3674                                 const StandardConversionSequenceSCS1,
3675                                 const StandardConversionSequenceSCS2) {
3676  ImplicitConversionSequence::CompareKind Result
3677    = ImplicitConversionSequence::Indistinguishable;
3678
3679  // the identity conversion sequence is considered to be a subsequence of
3680  // any non-identity conversion sequence
3681  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3682    return ImplicitConversionSequence::Better;
3683  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3684    return ImplicitConversionSequence::Worse;
3685
3686  if (SCS1.Second != SCS2.Second) {
3687    if (SCS1.Second == ICK_Identity)
3688      Result = ImplicitConversionSequence::Better;
3689    else if (SCS2.Second == ICK_Identity)
3690      Result = ImplicitConversionSequence::Worse;
3691    else
3692      return ImplicitConversionSequence::Indistinguishable;
3693  } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3694    return ImplicitConversionSequence::Indistinguishable;
3695
3696  if (SCS1.Third == SCS2.Third) {
3697    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3698                             : ImplicitConversionSequence::Indistinguishable;
3699  }
3700
3701  if (SCS1.Third == ICK_Identity)
3702    return Result == ImplicitConversionSequence::Worse
3703             ? ImplicitConversionSequence::Indistinguishable
3704             : ImplicitConversionSequence::Better;
3705
3706  if (SCS2.Third == ICK_Identity)
3707    return Result == ImplicitConversionSequence::Better
3708             ? ImplicitConversionSequence::Indistinguishable
3709             : ImplicitConversionSequence::Worse;
3710
3711  return ImplicitConversionSequence::Indistinguishable;
3712}
3713
3714/// Determine whether one of the given reference bindings is better
3715/// than the other based on what kind of bindings they are.
3716static bool
3717isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3718                             const StandardConversionSequence &SCS2) {
3719  // C++0x [over.ics.rank]p3b4:
3720  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3721  //      implicit object parameter of a non-static member function declared
3722  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3723  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3724  //      lvalue reference to a function lvalue and S2 binds an rvalue
3725  //      reference*.
3726  //
3727  // FIXME: Rvalue references. We're going rogue with the above edits,
3728  // because the semantics in the current C++0x working paper (N3225 at the
3729  // time of this writing) break the standard definition of std::forward
3730  // and std::reference_wrapper when dealing with references to functions.
3731  // Proposed wording changes submitted to CWG for consideration.
3732  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3733      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3734    return false;
3735
3736  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3737          SCS2.IsLvalueReference) ||
3738         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3739          !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3740}
3741
3742/// CompareStandardConversionSequences - Compare two standard
3743/// conversion sequences to determine whether one is better than the
3744/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3745static ImplicitConversionSequence::CompareKind
3746CompareStandardConversionSequences(Sema &SSourceLocation Loc,
3747                                   const StandardConversionSequenceSCS1,
3748                                   const StandardConversionSequenceSCS2)
3749{
3750  // Standard conversion sequence S1 is a better conversion sequence
3751  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3752
3753  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3754  //     sequences in the canonical form defined by 13.3.3.1.1,
3755  //     excluding any Lvalue Transformation; the identity conversion
3756  //     sequence is considered to be a subsequence of any
3757  //     non-identity conversion sequence) or, if not that,
3758  if (ImplicitConversionSequence::CompareKind CK
3759        = compareStandardConversionSubsets(S.ContextSCS1SCS2))
3760    return CK;
3761
3762  //  -- the rank of S1 is better than the rank of S2 (by the rules
3763  //     defined below), or, if not that,
3764  ImplicitConversionRank Rank1 = SCS1.getRank();
3765  ImplicitConversionRank Rank2 = SCS2.getRank();
3766  if (Rank1 < Rank2)
3767    return ImplicitConversionSequence::Better;
3768  else if (Rank2 < Rank1)
3769    return ImplicitConversionSequence::Worse;
3770
3771  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3772  // are indistinguishable unless one of the following rules
3773  // applies:
3774
3775  //   A conversion that is not a conversion of a pointer, or
3776  //   pointer to member, to bool is better than another conversion
3777  //   that is such a conversion.
3778  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3779    return SCS2.isPointerConversionToBool()
3780             ? ImplicitConversionSequence::Better
3781             : ImplicitConversionSequence::Worse;
3782
3783  // C++ [over.ics.rank]p4b2:
3784  //
3785  //   If class B is derived directly or indirectly from class A,
3786  //   conversion of B* to A* is better than conversion of B* to
3787  //   void*, and conversion of A* to void* is better than conversion
3788  //   of B* to void*.
3789  bool SCS1ConvertsToVoid
3790    = SCS1.isPointerConversionToVoidPointer(S.Context);
3791  bool SCS2ConvertsToVoid
3792    = SCS2.isPointerConversionToVoidPointer(S.Context);
3793  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3794    // Exactly one of the conversion sequences is a conversion to
3795    // a void pointer; it's the worse conversion.
3796    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3797                              : ImplicitConversionSequence::Worse;
3798  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3799    // Neither conversion sequence converts to a void pointer; compare
3800    // their derived-to-base conversions.
3801    if (ImplicitConversionSequence::CompareKind DerivedCK
3802          = CompareDerivedToBaseConversions(SLocSCS1SCS2))
3803      return DerivedCK;
3804  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3805             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3806    // Both conversion sequences are conversions to void
3807    // pointers. Compare the source types to determine if there's an
3808    // inheritance relationship in their sources.
3809    QualType FromType1 = SCS1.getFromType();
3810    QualType FromType2 = SCS2.getFromType();
3811
3812    // Adjust the types we're converting from via the array-to-pointer
3813    // conversion, if we need to.
3814    if (SCS1.First == ICK_Array_To_Pointer)
3815      FromType1 = S.Context.getArrayDecayedType(FromType1);
3816    if (SCS2.First == ICK_Array_To_Pointer)
3817      FromType2 = S.Context.getArrayDecayedType(FromType2);
3818
3819    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3820    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3821
3822    if (S.IsDerivedFrom(LocFromPointee2FromPointee1))
3823      return ImplicitConversionSequence::Better;
3824    else if (S.IsDerivedFrom(LocFromPointee1FromPointee2))
3825      return ImplicitConversionSequence::Worse;
3826
3827    // Objective-C++: If one interface is more specific than the
3828    // other, it is the better one.
3829    const ObjCObjectPointerTypeFromObjCPtr1
3830      = FromType1->getAs<ObjCObjectPointerType>();
3831    const ObjCObjectPointerTypeFromObjCPtr2
3832      = FromType2->getAs<ObjCObjectPointerType>();
3833    if (FromObjCPtr1 && FromObjCPtr2) {
3834      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3835                                                          FromObjCPtr2);
3836      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3837                                                           FromObjCPtr1);
3838      if (AssignLeft != AssignRight) {
3839        return AssignLeftImplicitConversionSequence::Better
3840                         : ImplicitConversionSequence::Worse;
3841      }
3842    }
3843  }
3844
3845  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3846  // bullet 3).
3847  if (ImplicitConversionSequence::CompareKind QualCK
3848        = CompareQualificationConversions(SSCS1SCS2))
3849    return QualCK;
3850
3851  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3852    // Check for a better reference binding based on the kind of bindings.
3853    if (isBetterReferenceBindingKind(SCS1SCS2))
3854      return ImplicitConversionSequence::Better;
3855    else if (isBetterReferenceBindingKind(SCS2SCS1))
3856      return ImplicitConversionSequence::Worse;
3857
3858    // C++ [over.ics.rank]p3b4:
3859    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3860    //      which the references refer are the same type except for
3861    //      top-level cv-qualifiers, and the type to which the reference
3862    //      initialized by S2 refers is more cv-qualified than the type
3863    //      to which the reference initialized by S1 refers.
3864    QualType T1 = SCS1.getToType(2);
3865    QualType T2 = SCS2.getToType(2);
3866    T1 = S.Context.getCanonicalType(T1);
3867    T2 = S.Context.getCanonicalType(T2);
3868    Qualifiers T1QualsT2Quals;
3869    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1T1Quals);
3870    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2T2Quals);
3871    if (UnqualT1 == UnqualT2) {
3872      // Objective-C++ ARC: If the references refer to objects with different
3873      // lifetimes, prefer bindings that don't change lifetime.
3874      if (SCS1.ObjCLifetimeConversionBinding !=
3875                                          SCS2.ObjCLifetimeConversionBinding) {
3876        return SCS1.ObjCLifetimeConversionBinding
3877                                           ? ImplicitConversionSequence::Worse
3878                                           : ImplicitConversionSequence::Better;
3879      }
3880
3881      // If the type is an array type, promote the element qualifiers to the
3882      // type for comparison.
3883      if (isa<ArrayType>(T1) && T1Quals)
3884        T1 = S.Context.getQualifiedType(UnqualT1T1Quals);
3885      if (isa<ArrayType>(T2) && T2Quals)
3886        T2 = S.Context.getQualifiedType(UnqualT2T2Quals);
3887      if (T2.isMoreQualifiedThan(T1))
3888        return ImplicitConversionSequence::Better;
3889      else if (T1.isMoreQualifiedThan(T2))
3890        return ImplicitConversionSequence::Worse;
3891    }
3892  }
3893
3894  // In Microsoft mode, prefer an integral conversion to a
3895  // floating-to-integral conversion if the integral conversion
3896  // is between types of the same size.
3897  // For example:
3898  // void f(float);
3899  // void f(int);
3900  // int main {
3901  //    long a;
3902  //    f(a);
3903  // }
3904  // Here, MSVC will call f(int) instead of generating a compile error
3905  // as clang will do in standard mode.
3906  if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3907      SCS2.Second == ICK_Floating_Integral &&
3908      S.Context.getTypeSize(SCS1.getFromType()) ==
3909          S.Context.getTypeSize(SCS1.getToType(2)))
3910    return ImplicitConversionSequence::Better;
3911
3912  // Prefer a compatible vector conversion over a lax vector conversion
3913  // For example:
3914  //
3915  // typedef float __v4sf __attribute__((__vector_size__(16)));
3916  // void f(vector float);
3917  // void f(vector signed int);
3918  // int main() {
3919  //   __v4sf a;
3920  //   f(a);
3921  // }
3922  // Here, we'd like to choose f(vector float) and not
3923  // report an ambiguous call error
3924  if (SCS1.Second == ICK_Vector_Conversion &&
3925      SCS2.Second == ICK_Vector_Conversion) {
3926    bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3927        SCS1.getFromType(), SCS1.getToType(2));
3928    bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3929        SCS2.getFromType(), SCS2.getToType(2));
3930
3931    if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3932      return SCS1IsCompatibleVectorConversion
3933                 ? ImplicitConversionSequence::Better
3934                 : ImplicitConversionSequence::Worse;
3935  }
3936
3937  return ImplicitConversionSequence::Indistinguishable;
3938}
3939
3940/// CompareQualificationConversions - Compares two standard conversion
3941/// sequences to determine whether they can be ranked based on their
3942/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3943static ImplicitConversionSequence::CompareKind
3944CompareQualificationConversions(Sema &S,
3945                                const StandardConversionSequenceSCS1,
3946                                const StandardConversionSequenceSCS2) {
3947  // C++ 13.3.3.2p3:
3948  //  -- S1 and S2 differ only in their qualification conversion and
3949  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3950  //     cv-qualification signature of type T1 is a proper subset of
3951  //     the cv-qualification signature of type T2, and S1 is not the
3952  //     deprecated string literal array-to-pointer conversion (4.2).
3953  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3954      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3955    return ImplicitConversionSequence::Indistinguishable;
3956
3957  // FIXME: the example in the standard doesn't use a qualification
3958  // conversion (!)
3959  QualType T1 = SCS1.getToType(2);
3960  QualType T2 = SCS2.getToType(2);
3961  T1 = S.Context.getCanonicalType(T1);
3962  T2 = S.Context.getCanonicalType(T2);
3963  Qualifiers T1QualsT2Quals;
3964  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1T1Quals);
3965  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2T2Quals);
3966
3967  // If the types are the same, we won't learn anything by unwrapped
3968  // them.
3969  if (UnqualT1 == UnqualT2)
3970    return ImplicitConversionSequence::Indistinguishable;
3971
3972  // If the type is an array type, promote the element qualifiers to the type
3973  // for comparison.
3974  if (isa<ArrayType>(T1) && T1Quals)
3975    T1 = S.Context.getQualifiedType(UnqualT1T1Quals);
3976  if (isa<ArrayType>(T2) && T2Quals)
3977    T2 = S.Context.getQualifiedType(UnqualT2T2Quals);
3978
3979  ImplicitConversionSequence::CompareKind Result
3980    = ImplicitConversionSequence::Indistinguishable;
3981
3982  // Objective-C++ ARC:
3983  //   Prefer qualification conversions not involving a change in lifetime
3984  //   to qualification conversions that do not change lifetime.
3985  if (SCS1.QualificationIncludesObjCLifetime !=
3986                                      SCS2.QualificationIncludesObjCLifetime) {
3987    Result = SCS1.QualificationIncludesObjCLifetime
3988               ? ImplicitConversionSequence::Worse
3989               : ImplicitConversionSequence::Better;
3990  }
3991
3992  while (S.Context.UnwrapSimilarTypes(T1T2)) {
3993    // Within each iteration of the loop, we check the qualifiers to
3994    // determine if this still looks like a qualification
3995    // conversion. Then, if all is well, we unwrap one more level of
3996    // pointers or pointers-to-members and do it all again
3997    // until there are no more pointers or pointers-to-members left
3998    // to unwrap. This essentially mimics what
3999    // IsQualificationConversion does, but here we're checking for a
4000    // strict subset of qualifiers.
4001    if (T1.getQualifiers().withoutObjCLifetime() ==
4002        T2.getQualifiers().withoutObjCLifetime())
4003      // The qualifiers are the same, so this doesn't tell us anything
4004      // about how the sequences rank.
4005      // ObjC ownership quals are omitted above as they interfere with
4006      // the ARC overload rule.
4007      ;
4008    else if (T2.isMoreQualifiedThan(T1)) {
4009      // T1 has fewer qualifiers, so it could be the better sequence.
4010      if (Result == ImplicitConversionSequence::Worse)
4011        // Neither has qualifiers that are a subset of the other's
4012        // qualifiers.
4013        return ImplicitConversionSequence::Indistinguishable;
4014
4015      Result = ImplicitConversionSequence::Better;
4016    } else if (T1.isMoreQualifiedThan(T2)) {
4017      // T2 has fewer qualifiers, so it could be the better sequence.
4018      if (Result == ImplicitConversionSequence::Better)
4019        // Neither has qualifiers that are a subset of the other's
4020        // qualifiers.
4021        return ImplicitConversionSequence::Indistinguishable;
4022
4023      Result = ImplicitConversionSequence::Worse;
4024    } else {
4025      // Qualifiers are disjoint.
4026      return ImplicitConversionSequence::Indistinguishable;
4027    }
4028
4029    // If the types after this point are equivalent, we're done.
4030    if (S.Context.hasSameUnqualifiedType(T1T2))
4031      break;
4032  }
4033
4034  // Check that the winning standard conversion sequence isn't using
4035  // the deprecated string literal array to pointer conversion.
4036  switch (Result) {
4037  case ImplicitConversionSequence::Better:
4038    if (SCS1.DeprecatedStringLiteralToCharPtr)
4039      Result = ImplicitConversionSequence::Indistinguishable;
4040    break;
4041
4042  case ImplicitConversionSequence::Indistinguishable:
4043    break;
4044
4045  case ImplicitConversionSequence::Worse:
4046    if (SCS2.DeprecatedStringLiteralToCharPtr)
4047      Result = ImplicitConversionSequence::Indistinguishable;
4048    break;
4049  }
4050
4051  return Result;
4052}
4053
4054/// CompareDerivedToBaseConversions - Compares two standard conversion
4055/// sequences to determine whether they can be ranked based on their
4056/// various kinds of derived-to-base conversions (C++
4057/// [over.ics.rank]p4b3).  As part of these checks, we also look at
4058/// conversions between Objective-C interface types.
4059static ImplicitConversionSequence::CompareKind
4060CompareDerivedToBaseConversions(Sema &SSourceLocation Loc,
4061                                const StandardConversionSequenceSCS1,
4062                                const StandardConversionSequenceSCS2) {
4063  QualType FromType1 = SCS1.getFromType();
4064  QualType ToType1 = SCS1.getToType(1);
4065  QualType FromType2 = SCS2.getFromType();
4066  QualType ToType2 = SCS2.getToType(1);
4067
4068  // Adjust the types we're converting from via the array-to-pointer
4069  // conversion, if we need to.
4070  if (SCS1.First == ICK_Array_To_Pointer)
4071    FromType1 = S.Context.getArrayDecayedType(FromType1);
4072  if (SCS2.First == ICK_Array_To_Pointer)
4073    FromType2 = S.Context.getArrayDecayedType(FromType2);
4074
4075  // Canonicalize all of the types.
4076  FromType1 = S.Context.getCanonicalType(FromType1);
4077  ToType1 = S.Context.getCanonicalType(ToType1);
4078  FromType2 = S.Context.getCanonicalType(FromType2);
4079  ToType2 = S.Context.getCanonicalType(ToType2);
4080
4081  // C++ [over.ics.rank]p4b3:
4082  //
4083  //   If class B is derived directly or indirectly from class A and
4084  //   class C is derived directly or indirectly from B,
4085  //
4086  // Compare based on pointer conversions.
4087  if (SCS1.Second == ICK_Pointer_Conversion &&
4088      SCS2.Second == ICK_Pointer_Conversion &&
4089      /*FIXME: Remove if Objective-C id conversions get their own rank*/
4090      FromType1->isPointerType() && FromType2->isPointerType() &&
4091      ToType1->isPointerType() && ToType2->isPointerType()) {
4092    QualType FromPointee1
4093      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4094    QualType ToPointee1
4095      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4096    QualType FromPointee2
4097      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4098    QualType ToPointee2
4099      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4100
4101    //   -- conversion of C* to B* is better than conversion of C* to A*,
4102    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4103      if (S.IsDerivedFrom(LocToPointee1ToPointee2))
4104        return ImplicitConversionSequence::Better;
4105      else if (S.IsDerivedFrom(LocToPointee2ToPointee1))
4106        return ImplicitConversionSequence::Worse;
4107    }
4108
4109    //   -- conversion of B* to A* is better than conversion of C* to A*,
4110    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4111      if (S.IsDerivedFrom(LocFromPointee2FromPointee1))
4112        return ImplicitConversionSequence::Better;
4113      else if (S.IsDerivedFrom(LocFromPointee1FromPointee2))
4114        return ImplicitConversionSequence::Worse;
4115    }
4116  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4117             SCS2.Second == ICK_Pointer_Conversion) {
4118    const ObjCObjectPointerType *FromPtr1
4119      = FromType1->getAs<ObjCObjectPointerType>();
4120    const ObjCObjectPointerType *FromPtr2
4121      = FromType2->getAs<ObjCObjectPointerType>();
4122    const ObjCObjectPointerType *ToPtr1
4123      = ToType1->getAs<ObjCObjectPointerType>();
4124    const ObjCObjectPointerType *ToPtr2
4125      = ToType2->getAs<ObjCObjectPointerType>();
4126
4127    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4128      // Apply the same conversion ranking rules for Objective-C pointer types
4129      // that we do for C++ pointers to class types. However, we employ the
4130      // Objective-C pseudo-subtyping relationship used for assignment of
4131      // Objective-C pointer types.
4132      bool FromAssignLeft
4133        = S.Context.canAssignObjCInterfaces(FromPtr1FromPtr2);
4134      bool FromAssignRight
4135        = S.Context.canAssignObjCInterfaces(FromPtr2FromPtr1);
4136      bool ToAssignLeft
4137        = S.Context.canAssignObjCInterfaces(ToPtr1ToPtr2);
4138      bool ToAssignRight
4139        = S.Context.canAssignObjCInterfaces(ToPtr2ToPtr1);
4140
4141      // A conversion to an a non-id object pointer type or qualified 'id'
4142      // type is better than a conversion to 'id'.
4143      if (ToPtr1->isObjCIdType() &&
4144          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4145        return ImplicitConversionSequence::Worse;
4146      if (ToPtr2->isObjCIdType() &&
4147          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4148        return ImplicitConversionSequence::Better;
4149
4150      // A conversion to a non-id object pointer type is better than a
4151      // conversion to a qualified 'id' type
4152      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4153        return ImplicitConversionSequence::Worse;
4154      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4155        return ImplicitConversionSequence::Better;
4156
4157      // A conversion to an a non-Class object pointer type or qualified 'Class'
4158      // type is better than a conversion to 'Class'.
4159      if (ToPtr1->isObjCClassType() &&
4160          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4161        return ImplicitConversionSequence::Worse;
4162      if (ToPtr2->isObjCClassType() &&
4163          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4164        return ImplicitConversionSequence::Better;
4165
4166      // A conversion to a non-Class object pointer type is better than a
4167      // conversion to a qualified 'Class' type.
4168      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4169        return ImplicitConversionSequence::Worse;
4170      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4171        return ImplicitConversionSequence::Better;
4172
4173      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4174      if (S.Context.hasSameType(FromType1FromType2) &&
4175          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4176          (ToAssignLeft != ToAssignRight)) {
4177        if (FromPtr1->isSpecialized()) {
4178          // "conversion of B<A> * to B * is better than conversion of B * to
4179          // C *.
4180          bool IsFirstSame =
4181              FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4182          bool IsSecondSame =
4183              FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4184          if (IsFirstSame) {
4185            if (!IsSecondSame)
4186              return ImplicitConversionSequence::Better;
4187          } else if (IsSecondSame)
4188            return ImplicitConversionSequence::Worse;
4189        }
4190        return ToAssignLeftImplicitConversionSequence::Worse
4191                           : ImplicitConversionSequence::Better;
4192      }
4193
4194      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4195      if (S.Context.hasSameUnqualifiedType(ToType1ToType2) &&
4196          (FromAssignLeft != FromAssignRight))
4197        return FromAssignLeftImplicitConversionSequence::Better
4198        : ImplicitConversionSequence::Worse;
4199    }
4200  }
4201
4202  // Ranking of member-pointer types.
4203  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4204      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4205      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4206    const MemberPointerType * FromMemPointer1 =
4207                                        FromType1->getAs<MemberPointerType>();
4208    const MemberPointerType * ToMemPointer1 =
4209                                          ToType1->getAs<MemberPointerType>();
4210    const MemberPointerType * FromMemPointer2 =
4211                                          FromType2->getAs<MemberPointerType>();
4212    const MemberPointerType * ToMemPointer2 =
4213                                          ToType2->getAs<MemberPointerType>();
4214    const Type *FromPointeeType1 = FromMemPointer1->getClass();
4215    const Type *ToPointeeType1 = ToMemPointer1->getClass();
4216    const Type *FromPointeeType2 = FromMemPointer2->getClass();
4217    const Type *ToPointeeType2 = ToMemPointer2->getClass();
4218    QualType FromPointee1 = QualType(FromPointeeType10).getUnqualifiedType();
4219    QualType ToPointee1 = QualType(ToPointeeType10).getUnqualifiedType();
4220    QualType FromPointee2 = QualType(FromPointeeType20).getUnqualifiedType();
4221    QualType ToPointee2 = QualType(ToPointeeType20).getUnqualifiedType();
4222    // conversion of A::* to B::* is better than conversion of A::* to C::*,
4223    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4224      if (S.IsDerivedFrom(LocToPointee1ToPointee2))
4225        return ImplicitConversionSequence::Worse;
4226      else if (S.IsDerivedFrom(LocToPointee2ToPointee1))
4227        return ImplicitConversionSequence::Better;
4228    }
4229    // conversion of B::* to C::* is better than conversion of A::* to C::*
4230    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4231      if (S.IsDerivedFrom(LocFromPointee1FromPointee2))
4232        return ImplicitConversionSequence::Better;
4233      else if (S.IsDerivedFrom(LocFromPointee2FromPointee1))
4234        return ImplicitConversionSequence::Worse;
4235    }
4236  }
4237
4238  if (SCS1.Second == ICK_Derived_To_Base) {
4239    //   -- conversion of C to B is better than conversion of C to A,
4240    //   -- binding of an expression of type C to a reference of type
4241    //      B& is better than binding an expression of type C to a
4242    //      reference of type A&,
4243    if (S.Context.hasSameUnqualifiedType(FromType1FromType2) &&
4244        !S.Context.hasSameUnqualifiedType(ToType1ToType2)) {
4245      if (S.IsDerivedFrom(LocToType1ToType2))
4246        return ImplicitConversionSequence::Better;
4247      else if (S.IsDerivedFrom(LocToType2ToType1))
4248        return ImplicitConversionSequence::Worse;
4249    }
4250
4251    //   -- conversion of B to A is better than conversion of C to A.
4252    //   -- binding of an expression of type B to a reference of type
4253    //      A& is better than binding an expression of type C to a
4254    //      reference of type A&,
4255    if (!S.Context.hasSameUnqualifiedType(FromType1FromType2) &&
4256        S.Context.hasSameUnqualifiedType(ToType1ToType2)) {
4257      if (S.IsDerivedFrom(LocFromType2FromType1))
4258        return ImplicitConversionSequence::Better;
4259      else if (S.IsDerivedFrom(LocFromType1FromType2))
4260        return ImplicitConversionSequence::Worse;
4261    }
4262  }
4263
4264  return ImplicitConversionSequence::Indistinguishable;
4265}
4266
4267/// Determine whether the given type is valid, e.g., it is not an invalid
4268/// C++ class.
4269static bool isTypeValid(QualType T) {
4270  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4271    return !Record->isInvalidDecl();
4272
4273  return true;
4274}
4275
4276/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4277/// determine whether they are reference-related,
4278/// reference-compatible, reference-compatible with added
4279/// qualification, or incompatible, for use in C++ initialization by
4280/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4281/// type, and the first type (T1) is the pointee type of the reference
4282/// type being initialized.
4283Sema::ReferenceCompareResult
4284Sema::CompareReferenceRelationship(SourceLocation Loc,
4285                                   QualType OrigT1QualType OrigT2,
4286                                   bool &DerivedToBase,
4287                                   bool &ObjCConversion,
4288                                   bool &ObjCLifetimeConversion) {
4289   (0) . __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4290, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!OrigT1->isReferenceType() &&
4290 (0) . __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4290, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">    "T1 must be the pointee type of the reference type");
4291   (0) . __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4291, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4292
4293  QualType T1 = Context.getCanonicalType(OrigT1);
4294  QualType T2 = Context.getCanonicalType(OrigT2);
4295  Qualifiers T1QualsT2Quals;
4296  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1T1Quals);
4297  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2T2Quals);
4298
4299  // C++ [dcl.init.ref]p4:
4300  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4301  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4302  //   T1 is a base class of T2.
4303  DerivedToBase = false;
4304  ObjCConversion = false;
4305  ObjCLifetimeConversion = false;
4306  QualType ConvertedT2;
4307  if (UnqualT1 == UnqualT2) {
4308    // Nothing to do.
4309  } else if (isCompleteType(LocOrigT2) &&
4310             isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4311             IsDerivedFrom(LocUnqualT2UnqualT1))
4312    DerivedToBase = true;
4313  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4314           UnqualT2->isObjCObjectOrInterfaceType() &&
4315           Context.canBindObjCObjectType(UnqualT1UnqualT2))
4316    ObjCConversion = true;
4317  else if (UnqualT2->isFunctionType() &&
4318           IsFunctionConversion(UnqualT2UnqualT1ConvertedT2))
4319    // C++1z [dcl.init.ref]p4:
4320    //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4321    //   function" and T1 is "function"
4322    //
4323    // We extend this to also apply to 'noreturn', so allow any function
4324    // conversion between function types.
4325    return Ref_Compatible;
4326  else
4327    return Ref_Incompatible;
4328
4329  // At this point, we know that T1 and T2 are reference-related (at
4330  // least).
4331
4332  // If the type is an array type, promote the element qualifiers to the type
4333  // for comparison.
4334  if (isa<ArrayType>(T1) && T1Quals)
4335    T1 = Context.getQualifiedType(UnqualT1T1Quals);
4336  if (isa<ArrayType>(T2) && T2Quals)
4337    T2 = Context.getQualifiedType(UnqualT2T2Quals);
4338
4339  // C++ [dcl.init.ref]p4:
4340  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4341  //   reference-related to T2 and cv1 is the same cv-qualification
4342  //   as, or greater cv-qualification than, cv2. For purposes of
4343  //   overload resolution, cases for which cv1 is greater
4344  //   cv-qualification than cv2 are identified as
4345  //   reference-compatible with added qualification (see 13.3.3.2).
4346  //
4347  // Note that we also require equivalence of Objective-C GC and address-space
4348  // qualifiers when performing these computations, so that e.g., an int in
4349  // address space 1 is not reference-compatible with an int in address
4350  // space 2.
4351  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4352      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4353    if (isNonTrivialObjCLifetimeConversion(T2QualsT1Quals))
4354      ObjCLifetimeConversion = true;
4355
4356    T1Quals.removeObjCLifetime();
4357    T2Quals.removeObjCLifetime();
4358  }
4359
4360  // MS compiler ignores __unaligned qualifier for references; do the same.
4361  T1Quals.removeUnaligned();
4362  T2Quals.removeUnaligned();
4363
4364  if (T1Quals.compatiblyIncludes(T2Quals))
4365    return Ref_Compatible;
4366  else
4367    return Ref_Related;
4368}
4369
4370/// Look for a user-defined conversion to a value reference-compatible
4371///        with DeclType. Return true if something definite is found.
4372static bool
4373FindConversionForRefInit(Sema &SImplicitConversionSequence &ICS,
4374                         QualType DeclTypeSourceLocation DeclLoc,
4375                         Expr *InitQualType T2bool AllowRvalues,
4376                         bool AllowExplicit) {
4377   (0) . __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4377, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(T2->isRecordType() && "Can only find conversions of record types.");
4378  CXXRecordDecl *T2RecordDecl
4379    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4380
4381  OverloadCandidateSet CandidateSet(
4382      DeclLocOverloadCandidateSet::CSK_InitByUserDefinedConversion);
4383  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4384  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4385    NamedDecl *D = *I;
4386    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4387    if (isa<UsingShadowDecl>(D))
4388      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4389
4390    FunctionTemplateDecl *ConvTemplate
4391      = dyn_cast<FunctionTemplateDecl>(D);
4392    CXXConversionDecl *Conv;
4393    if (ConvTemplate)
4394      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4395    else
4396      Conv = cast<CXXConversionDecl>(D);
4397
4398    // If this is an explicit conversion, and we're not allowed to consider
4399    // explicit conversions, skip it.
4400    if (!AllowExplicit && Conv->isExplicit())
4401      continue;
4402
4403    if (AllowRvalues) {
4404      bool DerivedToBase = false;
4405      bool ObjCConversion = false;
4406      bool ObjCLifetimeConversion = false;
4407
4408      // If we are initializing an rvalue reference, don't permit conversion
4409      // functions that return lvalues.
4410      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4411        const ReferenceType *RefType
4412          = Conv->getConversionType()->getAs<LValueReferenceType>();
4413        if (RefType && !RefType->getPointeeType()->isFunctionType())
4414          continue;
4415      }
4416
4417      if (!ConvTemplate &&
4418          S.CompareReferenceRelationship(
4419            DeclLoc,
4420            Conv->getConversionType().getNonReferenceType()
4421              .getUnqualifiedType(),
4422            DeclType.getNonReferenceType().getUnqualifiedType(),
4423            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4424          Sema::Ref_Incompatible)
4425        continue;
4426    } else {
4427      // If the conversion function doesn't return a reference type,
4428      // it can't be considered for this conversion. An rvalue reference
4429      // is only acceptable if its referencee is a function type.
4430
4431      const ReferenceType *RefType =
4432        Conv->getConversionType()->getAs<ReferenceType>();
4433      if (!RefType ||
4434          (!RefType->isLValueReferenceType() &&
4435           !RefType->getPointeeType()->isFunctionType()))
4436        continue;
4437    }
4438
4439    if (ConvTemplate)
4440      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4441                                       Init, DeclType, CandidateSet,
4442                                       /*AllowObjCConversionOnExplicit=*/false);
4443    else
4444      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4445                               DeclType, CandidateSet,
4446                               /*AllowObjCConversionOnExplicit=*/false);
4447  }
4448
4449  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4450
4451  OverloadCandidateSet::iterator Best;
4452  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4453  case OR_Success:
4454    // C++ [over.ics.ref]p1:
4455    //
4456    //   [...] If the parameter binds directly to the result of
4457    //   applying a conversion function to the argument
4458    //   expression, the implicit conversion sequence is a
4459    //   user-defined conversion sequence (13.3.3.1.2), with the
4460    //   second standard conversion sequence either an identity
4461    //   conversion or, if the conversion function returns an
4462    //   entity of a type that is a derived class of the parameter
4463    //   type, a derived-to-base Conversion.
4464    if (!Best->FinalConversion.DirectBinding)
4465      return false;
4466
4467    ICS.setUserDefined();
4468    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4469    ICS.UserDefined.After = Best->FinalConversion;
4470    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4471    ICS.UserDefined.ConversionFunction = Best->Function;
4472    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4473    ICS.UserDefined.EllipsisConversion = false;
4474     (0) . __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4476, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ICS.UserDefined.After.ReferenceBinding &&
4475 (0) . __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4476, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           ICS.UserDefined.After.DirectBinding &&
4476 (0) . __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4476, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Expected a direct reference binding!");
4477    return true;
4478
4479  case OR_Ambiguous:
4480    ICS.setAmbiguous();
4481    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4482         Cand != CandidateSet.end(); ++Cand)
4483      if (Cand->Viable)
4484        ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4485    return true;
4486
4487  case OR_No_Viable_Function:
4488  case OR_Deleted:
4489    // There was no suitable conversion, or we found a deleted
4490    // conversion; continue with other checks.
4491    return false;
4492  }
4493
4494  llvm_unreachable("Invalid OverloadResult!");
4495}
4496
4497/// Compute an implicit conversion sequence for reference
4498/// initialization.
4499static ImplicitConversionSequence
4500TryReferenceInit(Sema &SExpr *InitQualType DeclType,
4501                 SourceLocation DeclLoc,
4502                 bool SuppressUserConversions,
4503                 bool AllowExplicit) {
4504   (0) . __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4504, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(DeclType->isReferenceType() && "Reference init needs a reference");
4505
4506  // Most paths end in a failed conversion.
4507  ImplicitConversionSequence ICS;
4508  ICS.setBad(BadConversionSequence::no_conversionInitDeclType);
4509
4510  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4511  QualType T2 = Init->getType();
4512
4513  // If the initializer is the address of an overloaded function, try
4514  // to resolve the overloaded function. If all goes well, T2 is the
4515  // type of the resulting function.
4516  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4517    DeclAccessPair Found;
4518    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(InitDeclType,
4519                                                                falseFound))
4520      T2 = Fn->getType();
4521  }
4522
4523  // Compute some basic properties of the types and the initializer.
4524  bool isRValRef = DeclType->isRValueReferenceType();
4525  bool DerivedToBase = false;
4526  bool ObjCConversion = false;
4527  bool ObjCLifetimeConversion = false;
4528  Expr::Classification InitCategory = Init->Classify(S.Context);
4529  Sema::ReferenceCompareResult RefRelationship
4530    = S.CompareReferenceRelationship(DeclLocT1T2DerivedToBase,
4531                                     ObjCConversionObjCLifetimeConversion);
4532
4533
4534  // C++0x [dcl.init.ref]p5:
4535  //   A reference to type "cv1 T1" is initialized by an expression
4536  //   of type "cv2 T2" as follows:
4537
4538  //     -- If reference is an lvalue reference and the initializer expression
4539  if (!isRValRef) {
4540    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4541    //        reference-compatible with "cv2 T2," or
4542    //
4543    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4544    if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4545      // C++ [over.ics.ref]p1:
4546      //   When a parameter of reference type binds directly (8.5.3)
4547      //   to an argument expression, the implicit conversion sequence
4548      //   is the identity conversion, unless the argument expression
4549      //   has a type that is a derived class of the parameter type,
4550      //   in which case the implicit conversion sequence is a
4551      //   derived-to-base Conversion (13.3.3.1).
4552      ICS.setStandard();
4553      ICS.Standard.First = ICK_Identity;
4554      ICS.Standard.Second = DerivedToBaseICK_Derived_To_Base
4555                         : ObjCConversionICK_Compatible_Conversion
4556                         : ICK_Identity;
4557      ICS.Standard.Third = ICK_Identity;
4558      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4559      ICS.Standard.setToType(0T2);
4560      ICS.Standard.setToType(1T1);
4561      ICS.Standard.setToType(2T1);
4562      ICS.Standard.ReferenceBinding = true;
4563      ICS.Standard.DirectBinding = true;
4564      ICS.Standard.IsLvalueReference = !isRValRef;
4565      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4566      ICS.Standard.BindsToRvalue = false;
4567      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4568      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4569      ICS.Standard.CopyConstructor = nullptr;
4570      ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4571
4572      // Nothing more to do: the inaccessibility/ambiguity check for
4573      // derived-to-base conversions is suppressed when we're
4574      // computing the implicit conversion sequence (C++
4575      // [over.best.ics]p2).
4576      return ICS;
4577    }
4578
4579    //       -- has a class type (i.e., T2 is a class type), where T1 is
4580    //          not reference-related to T2, and can be implicitly
4581    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4582    //          is reference-compatible with "cv3 T3" 92) (this
4583    //          conversion is selected by enumerating the applicable
4584    //          conversion functions (13.3.1.6) and choosing the best
4585    //          one through overload resolution (13.3)),
4586    if (!SuppressUserConversions && T2->isRecordType() &&
4587        S.isCompleteType(DeclLocT2) &&
4588        RefRelationship == Sema::Ref_Incompatible) {
4589      if (FindConversionForRefInit(SICSDeclTypeDeclLoc,
4590                                   InitT2/*AllowRvalues=*/false,
4591                                   AllowExplicit))
4592        return ICS;
4593    }
4594  }
4595
4596  //     -- Otherwise, the reference shall be an lvalue reference to a
4597  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4598  //        shall be an rvalue reference.
4599  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4600    return ICS;
4601
4602  //       -- If the initializer expression
4603  //
4604  //            -- is an xvalue, class prvalue, array prvalue or function
4605  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4606  if (RefRelationship == Sema::Ref_Compatible &&
4607      (InitCategory.isXValue() ||
4608       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4609       (InitCategory.isLValue() && T2->isFunctionType()))) {
4610    ICS.setStandard();
4611    ICS.Standard.First = ICK_Identity;
4612    ICS.Standard.Second = DerivedToBaseICK_Derived_To_Base
4613                      : ObjCConversionICK_Compatible_Conversion
4614                      : ICK_Identity;
4615    ICS.Standard.Third = ICK_Identity;
4616    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4617    ICS.Standard.setToType(0T2);
4618    ICS.Standard.setToType(1T1);
4619    ICS.Standard.setToType(2T1);
4620    ICS.Standard.ReferenceBinding = true;
4621    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4622    // binding unless we're binding to a class prvalue.
4623    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4624    // allow the use of rvalue references in C++98/03 for the benefit of
4625    // standard library implementors; therefore, we need the xvalue check here.
4626    ICS.Standard.DirectBinding =
4627      S.getLangOpts().CPlusPlus11 ||
4628      !(InitCategory.isPRValue() || T2->isRecordType());
4629    ICS.Standard.IsLvalueReference = !isRValRef;
4630    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4631    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4632    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4633    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4634    ICS.Standard.CopyConstructor = nullptr;
4635    ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4636    return ICS;
4637  }
4638
4639  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4640  //               reference-related to T2, and can be implicitly converted to
4641  //               an xvalue, class prvalue, or function lvalue of type
4642  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4643  //               "cv3 T3",
4644  //
4645  //          then the reference is bound to the value of the initializer
4646  //          expression in the first case and to the result of the conversion
4647  //          in the second case (or, in either case, to an appropriate base
4648  //          class subobject).
4649  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4650      T2->isRecordType() && S.isCompleteType(DeclLocT2) &&
4651      FindConversionForRefInit(SICSDeclTypeDeclLoc,
4652                               InitT2/*AllowRvalues=*/true,
4653                               AllowExplicit)) {
4654    // In the second case, if the reference is an rvalue reference
4655    // and the second standard conversion sequence of the
4656    // user-defined conversion sequence includes an lvalue-to-rvalue
4657    // conversion, the program is ill-formed.
4658    if (ICS.isUserDefined() && isRValRef &&
4659        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4660      ICS.setBad(BadConversionSequence::no_conversionInitDeclType);
4661
4662    return ICS;
4663  }
4664
4665  // A temporary of function type cannot be created; don't even try.
4666  if (T1->isFunctionType())
4667    return ICS;
4668
4669  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4670  //          initialized from the initializer expression using the
4671  //          rules for a non-reference copy initialization (8.5). The
4672  //          reference is then bound to the temporary. If T1 is
4673  //          reference-related to T2, cv1 must be the same
4674  //          cv-qualification as, or greater cv-qualification than,
4675  //          cv2; otherwise, the program is ill-formed.
4676  if (RefRelationship == Sema::Ref_Related) {
4677    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4678    // we would be reference-compatible or reference-compatible with
4679    // added qualification. But that wasn't the case, so the reference
4680    // initialization fails.
4681    //
4682    // Note that we only want to check address spaces and cvr-qualifiers here.
4683    // ObjC GC, lifetime and unaligned qualifiers aren't important.
4684    Qualifiers T1Quals = T1.getQualifiers();
4685    Qualifiers T2Quals = T2.getQualifiers();
4686    T1Quals.removeObjCGCAttr();
4687    T1Quals.removeObjCLifetime();
4688    T2Quals.removeObjCGCAttr();
4689    T2Quals.removeObjCLifetime();
4690    // MS compiler ignores __unaligned qualifier for references; do the same.
4691    T1Quals.removeUnaligned();
4692    T2Quals.removeUnaligned();
4693    if (!T1Quals.compatiblyIncludes(T2Quals))
4694      return ICS;
4695  }
4696
4697  // If at least one of the types is a class type, the types are not
4698  // related, and we aren't allowed any user conversions, the
4699  // reference binding fails. This case is important for breaking
4700  // recursion, since TryImplicitConversion below will attempt to
4701  // create a temporary through the use of a copy constructor.
4702  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4703      (T1->isRecordType() || T2->isRecordType()))
4704    return ICS;
4705
4706  // If T1 is reference-related to T2 and the reference is an rvalue
4707  // reference, the initializer expression shall not be an lvalue.
4708  if (RefRelationship >= Sema::Ref_Related &&
4709      isRValRef && Init->Classify(S.Context).isLValue())
4710    return ICS;
4711
4712  // C++ [over.ics.ref]p2:
4713  //   When a parameter of reference type is not bound directly to
4714  //   an argument expression, the conversion sequence is the one
4715  //   required to convert the argument expression to the
4716  //   underlying type of the reference according to
4717  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4718  //   to copy-initializing a temporary of the underlying type with
4719  //   the argument expression. Any difference in top-level
4720  //   cv-qualification is subsumed by the initialization itself
4721  //   and does not constitute a conversion.
4722  ICS = TryImplicitConversion(SInitT1SuppressUserConversions,
4723                              /*AllowExplicit=*/false,
4724                              /*InOverloadResolution=*/false,
4725                              /*CStyle=*/false,
4726                              /*AllowObjCWritebackConversion=*/false,
4727                              /*AllowObjCConversionOnExplicit=*/false);
4728
4729  // Of course, that's still a reference binding.
4730  if (ICS.isStandard()) {
4731    ICS.Standard.ReferenceBinding = true;
4732    ICS.Standard.IsLvalueReference = !isRValRef;
4733    ICS.Standard.BindsToFunctionLvalue = false;
4734    ICS.Standard.BindsToRvalue = true;
4735    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4736    ICS.Standard.ObjCLifetimeConversionBinding = false;
4737  } else if (ICS.isUserDefined()) {
4738    const ReferenceType *LValRefType =
4739        ICS.UserDefined.ConversionFunction->getReturnType()
4740            ->getAs<LValueReferenceType>();
4741
4742    // C++ [over.ics.ref]p3:
4743    //   Except for an implicit object parameter, for which see 13.3.1, a
4744    //   standard conversion sequence cannot be formed if it requires [...]
4745    //   binding an rvalue reference to an lvalue other than a function
4746    //   lvalue.
4747    // Note that the function case is not possible here.
4748    if (DeclType->isRValueReferenceType() && LValRefType) {
4749      // FIXME: This is the wrong BadConversionSequence. The problem is binding
4750      // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4751      // reference to an rvalue!
4752      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalueInitDeclType);
4753      return ICS;
4754    }
4755
4756    ICS.UserDefined.After.ReferenceBinding = true;
4757    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4758    ICS.UserDefined.After.BindsToFunctionLvalue = false;
4759    ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4760    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4761    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4762  }
4763
4764  return ICS;
4765}
4766
4767static ImplicitConversionSequence
4768TryCopyInitialization(Sema &SExpr *FromQualType ToType,
4769                      bool SuppressUserConversions,
4770                      bool InOverloadResolution,
4771                      bool AllowObjCWritebackConversion,
4772                      bool AllowExplicit = false);
4773
4774/// TryListConversion - Try to copy-initialize a value of type ToType from the
4775/// initializer list From.
4776static ImplicitConversionSequence
4777TryListConversion(Sema &SInitListExpr *FromQualType ToType,
4778                  bool SuppressUserConversions,
4779                  bool InOverloadResolution,
4780                  bool AllowObjCWritebackConversion) {
4781  // C++11 [over.ics.list]p1:
4782  //   When an argument is an initializer list, it is not an expression and
4783  //   special rules apply for converting it to a parameter type.
4784
4785  ImplicitConversionSequence Result;
4786  Result.setBad(BadConversionSequence::no_conversionFromToType);
4787
4788  // We need a complete type for what follows. Incomplete types can never be
4789  // initialized from init lists.
4790  if (!S.isCompleteType(From->getBeginLoc(), ToType))
4791    return Result;
4792
4793  // Per DR1467:
4794  //   If the parameter type is a class X and the initializer list has a single
4795  //   element of type cv U, where U is X or a class derived from X, the
4796  //   implicit conversion sequence is the one required to convert the element
4797  //   to the parameter type.
4798  //
4799  //   Otherwise, if the parameter type is a character array [... ]
4800  //   and the initializer list has a single element that is an
4801  //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4802  //   implicit conversion sequence is the identity conversion.
4803  if (From->getNumInits() == 1) {
4804    if (ToType->isRecordType()) {
4805      QualType InitType = From->getInit(0)->getType();
4806      if (S.Context.hasSameUnqualifiedType(InitTypeToType) ||
4807          S.IsDerivedFrom(From->getBeginLoc(), InitTypeToType))
4808        return TryCopyInitialization(SFrom->getInit(0), ToType,
4809                                     SuppressUserConversions,
4810                                     InOverloadResolution,
4811                                     AllowObjCWritebackConversion);
4812    }
4813    // FIXME: Check the other conditions here: array of character type,
4814    // initializer is a string literal.
4815    if (ToType->isArrayType()) {
4816      InitializedEntity Entity =
4817        InitializedEntity::InitializeParameter(S.ContextToType,
4818                                               /*Consumed=*/false);
4819      if (S.CanPerformCopyInitialization(EntityFrom)) {
4820        Result.setStandard();
4821        Result.Standard.setAsIdentityConversion();
4822        Result.Standard.setFromType(ToType);
4823        Result.Standard.setAllToTypes(ToType);
4824        return Result;
4825      }
4826    }
4827  }
4828
4829  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4830  // C++11 [over.ics.list]p2:
4831  //   If the parameter type is std::initializer_list<X> or "array of X" and
4832  //   all the elements can be implicitly converted to X, the implicit
4833  //   conversion sequence is the worst conversion necessary to convert an
4834  //   element of the list to X.
4835  //
4836  // C++14 [over.ics.list]p3:
4837  //   Otherwise, if the parameter type is "array of N X", if the initializer
4838  //   list has exactly N elements or if it has fewer than N elements and X is
4839  //   default-constructible, and if all the elements of the initializer list
4840  //   can be implicitly converted to X, the implicit conversion sequence is
4841  //   the worst conversion necessary to convert an element of the list to X.
4842  //
4843  // FIXME: We're missing a lot of these checks.
4844  bool toStdInitializerList = false;
4845  QualType X;
4846  if (ToType->isArrayType())
4847    X = S.Context.getAsArrayType(ToType)->getElementType();
4848  else
4849    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4850  if (!X.isNull()) {
4851    for (unsigned i = 0e = From->getNumInits(); i < e; ++i) {
4852      Expr *Init = From->getInit(i);
4853      ImplicitConversionSequence ICS =
4854          TryCopyInitialization(SInitXSuppressUserConversions,
4855                                InOverloadResolution,
4856                                AllowObjCWritebackConversion);
4857      // If a single element isn't convertible, fail.
4858      if (ICS.isBad()) {
4859        Result = ICS;
4860        break;
4861      }
4862      // Otherwise, look for the worst conversion.
4863      if (Result.isBad() || CompareImplicitConversionSequences(
4864                                SFrom->getBeginLoc(), ICSResult) ==
4865                                ImplicitConversionSequence::Worse)
4866        Result = ICS;
4867    }
4868
4869    // For an empty list, we won't have computed any conversion sequence.
4870    // Introduce the identity conversion sequence.
4871    if (From->getNumInits() == 0) {
4872      Result.setStandard();
4873      Result.Standard.setAsIdentityConversion();
4874      Result.Standard.setFromType(ToType);
4875      Result.Standard.setAllToTypes(ToType);
4876    }
4877
4878    Result.setStdInitializerListElement(toStdInitializerList);
4879    return Result;
4880  }
4881
4882  // C++14 [over.ics.list]p4:
4883  // C++11 [over.ics.list]p3:
4884  //   Otherwise, if the parameter is a non-aggregate class X and overload
4885  //   resolution chooses a single best constructor [...] the implicit
4886  //   conversion sequence is a user-defined conversion sequence. If multiple
4887  //   constructors are viable but none is better than the others, the
4888  //   implicit conversion sequence is a user-defined conversion sequence.
4889  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4890    // This function can deal with initializer lists.
4891    return TryUserDefinedConversion(SFromToTypeSuppressUserConversions,
4892                                    /*AllowExplicit=*/false,
4893                                    InOverloadResolution/*CStyle=*/false,
4894                                    AllowObjCWritebackConversion,
4895                                    /*AllowObjCConversionOnExplicit=*/false);
4896  }
4897
4898  // C++14 [over.ics.list]p5:
4899  // C++11 [over.ics.list]p4:
4900  //   Otherwise, if the parameter has an aggregate type which can be
4901  //   initialized from the initializer list [...] the implicit conversion
4902  //   sequence is a user-defined conversion sequence.
4903  if (ToType->isAggregateType()) {
4904    // Type is an aggregate, argument is an init list. At this point it comes
4905    // down to checking whether the initialization works.
4906    // FIXME: Find out whether this parameter is consumed or not.
4907    // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4908    // need to call into the initialization code here; overload resolution
4909    // should not be doing that.
4910    InitializedEntity Entity =
4911        InitializedEntity::InitializeParameter(S.ContextToType,
4912                                               /*Consumed=*/false);
4913    if (S.CanPerformCopyInitialization(EntityFrom)) {
4914      Result.setUserDefined();
4915      Result.UserDefined.Before.setAsIdentityConversion();
4916      // Initializer lists don't have a type.
4917      Result.UserDefined.Before.setFromType(QualType());
4918      Result.UserDefined.Before.setAllToTypes(QualType());
4919
4920      Result.UserDefined.After.setAsIdentityConversion();
4921      Result.UserDefined.After.setFromType(ToType);
4922      Result.UserDefined.After.setAllToTypes(ToType);
4923      Result.UserDefined.ConversionFunction = nullptr;
4924    }
4925    return Result;
4926  }
4927
4928  // C++14 [over.ics.list]p6:
4929  // C++11 [over.ics.list]p5:
4930  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4931  if (ToType->isReferenceType()) {
4932    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4933    // mention initializer lists in any way. So we go by what list-
4934    // initialization would do and try to extrapolate from that.
4935
4936    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4937
4938    // If the initializer list has a single element that is reference-related
4939    // to the parameter type, we initialize the reference from that.
4940    if (From->getNumInits() == 1) {
4941      Expr *Init = From->getInit(0);
4942
4943      QualType T2 = Init->getType();
4944
4945      // If the initializer is the address of an overloaded function, try
4946      // to resolve the overloaded function. If all goes well, T2 is the
4947      // type of the resulting function.
4948      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4949        DeclAccessPair Found;
4950        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4951                                   InitToTypefalseFound))
4952          T2 = Fn->getType();
4953      }
4954
4955      // Compute some basic properties of the types and the initializer.
4956      bool dummy1 = false;
4957      bool dummy2 = false;
4958      bool dummy3 = false;
4959      Sema::ReferenceCompareResult RefRelationship =
4960          S.CompareReferenceRelationship(From->getBeginLoc(), T1T2dummy1,
4961                                         dummy2dummy3);
4962
4963      if (RefRelationship >= Sema::Ref_Related) {
4964        return TryReferenceInit(SInitToType/*FIXME*/ From->getBeginLoc(),
4965                                SuppressUserConversions,
4966                                /*AllowExplicit=*/false);
4967      }
4968    }
4969
4970    // Otherwise, we bind the reference to a temporary created from the
4971    // initializer list.
4972    Result = TryListConversion(SFromT1SuppressUserConversions,
4973                               InOverloadResolution,
4974                               AllowObjCWritebackConversion);
4975    if (Result.isFailure())
4976      return Result;
4977     (0) . __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4978, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Result.isEllipsis() &&
4978 (0) . __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 4978, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Sub-initialization cannot result in ellipsis conversion.");
4979
4980    // Can we even bind to a temporary?
4981    if (ToType->isRValueReferenceType() ||
4982        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4983      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4984                                            Result.UserDefined.After;
4985      SCS.ReferenceBinding = true;
4986      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4987      SCS.BindsToRvalue = true;
4988      SCS.BindsToFunctionLvalue = false;
4989      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4990      SCS.ObjCLifetimeConversionBinding = false;
4991    } else
4992      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4993                    FromToType);
4994    return Result;
4995  }
4996
4997  // C++14 [over.ics.list]p7:
4998  // C++11 [over.ics.list]p6:
4999  //   Otherwise, if the parameter type is not a class:
5000  if (!ToType->isRecordType()) {
5001    //    - if the initializer list has one element that is not itself an
5002    //      initializer list, the implicit conversion sequence is the one
5003    //      required to convert the element to the parameter type.
5004    unsigned NumInits = From->getNumInits();
5005    if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5006      Result = TryCopyInitialization(SFrom->getInit(0), ToType,
5007                                     SuppressUserConversions,
5008                                     InOverloadResolution,
5009                                     AllowObjCWritebackConversion);
5010    //    - if the initializer list has no elements, the implicit conversion
5011    //      sequence is the identity conversion.
5012    else if (NumInits == 0) {
5013      Result.setStandard();
5014      Result.Standard.setAsIdentityConversion();
5015      Result.Standard.setFromType(ToType);
5016      Result.Standard.setAllToTypes(ToType);
5017    }
5018    return Result;
5019  }
5020
5021  // C++14 [over.ics.list]p8:
5022  // C++11 [over.ics.list]p7:
5023  //   In all cases other than those enumerated above, no conversion is possible
5024  return Result;
5025}
5026
5027/// TryCopyInitialization - Try to copy-initialize a value of type
5028/// ToType from the expression From. Return the implicit conversion
5029/// sequence required to pass this argument, which may be a bad
5030/// conversion sequence (meaning that the argument cannot be passed to
5031/// a parameter of this type). If @p SuppressUserConversions, then we
5032/// do not permit any user-defined conversion sequences.
5033static ImplicitConversionSequence
5034TryCopyInitialization(Sema &SExpr *FromQualType ToType,
5035                      bool SuppressUserConversions,
5036                      bool InOverloadResolution,
5037                      bool AllowObjCWritebackConversion,
5038                      bool AllowExplicit) {
5039  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5040    return TryListConversion(SFromInitListToTypeSuppressUserConversions,
5041                             InOverloadResolution,AllowObjCWritebackConversion);
5042
5043  if (ToType->isReferenceType())
5044    return TryReferenceInit(SFromToType,
5045                            /*FIXME:*/ From->getBeginLoc(),
5046                            SuppressUserConversionsAllowExplicit);
5047
5048  return TryImplicitConversion(SFromToType,
5049                               SuppressUserConversions,
5050                               /*AllowExplicit=*/false,
5051                               InOverloadResolution,
5052                               /*CStyle=*/false,
5053                               AllowObjCWritebackConversion,
5054                               /*AllowObjCConversionOnExplicit=*/false);
5055}
5056
5057static bool TryCopyInitialization(const CanQualType FromQTy,
5058                                  const CanQualType ToQTy,
5059                                  Sema &S,
5060                                  SourceLocation Loc,
5061                                  ExprValueKind FromVK) {
5062  OpaqueValueExpr TmpExpr(LocFromQTyFromVK);
5063  ImplicitConversionSequence ICS =
5064    TryCopyInitialization(S, &TmpExprToQTytruetruefalse);
5065
5066  return !ICS.isBad();
5067}
5068
5069/// TryObjectArgumentInitialization - Try to initialize the object
5070/// parameter of the given member function (@c Method) from the
5071/// expression @p From.
5072static ImplicitConversionSequence
5073TryObjectArgumentInitialization(Sema &SSourceLocation LocQualType FromType,
5074                                Expr::Classification FromClassification,
5075                                CXXMethodDecl *Method,
5076                                CXXRecordDecl *ActingContext) {
5077  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5078  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5079  //                 const volatile object.
5080  Qualifiers Quals;
5081  if (isa<CXXDestructorDecl>(Method)) {
5082    Quals.addConst();
5083    Quals.addVolatile();
5084  } else {
5085    Quals = Method->getMethodQualifiers();
5086  }
5087
5088  QualType ImplicitParamType = S.Context.getQualifiedType(ClassTypeQuals);
5089
5090  // Set up the conversion sequence as a "bad" conversion, to allow us
5091  // to exit early.
5092  ImplicitConversionSequence ICS;
5093
5094  // We need to have an object of class type.
5095  if (const PointerType *PT = FromType->getAs<PointerType>()) {
5096    FromType = PT->getPointeeType();
5097
5098    // When we had a pointer, it's implicitly dereferenced, so we
5099    // better have an lvalue.
5100    assert(FromClassification.isLValue());
5101  }
5102
5103  isRecordType()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5103, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FromType->isRecordType());
5104
5105  // C++0x [over.match.funcs]p4:
5106  //   For non-static member functions, the type of the implicit object
5107  //   parameter is
5108  //
5109  //     - "lvalue reference to cv X" for functions declared without a
5110  //        ref-qualifier or with the & ref-qualifier
5111  //     - "rvalue reference to cv X" for functions declared with the &&
5112  //        ref-qualifier
5113  //
5114  // where X is the class of which the function is a member and cv is the
5115  // cv-qualification on the member function declaration.
5116  //
5117  // However, when finding an implicit conversion sequence for the argument, we
5118  // are not allowed to perform user-defined conversions
5119  // (C++ [over.match.funcs]p5). We perform a simplified version of
5120  // reference binding here, that allows class rvalues to bind to
5121  // non-constant references.
5122
5123  // First check the qualifiers.
5124  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5125  if (ImplicitParamType.getCVRQualifiers()
5126                                    != FromTypeCanon.getLocalCVRQualifiers() &&
5127      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5128    ICS.setBad(BadConversionSequence::bad_qualifiers,
5129               FromTypeImplicitParamType);
5130    return ICS;
5131  }
5132
5133  if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5134    Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5135    Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5136    if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5137      ICS.setBad(BadConversionSequence::bad_qualifiers,
5138                 FromTypeImplicitParamType);
5139      return ICS;
5140    }
5141  }
5142
5143  // Check that we have either the same type or a derived type. It
5144  // affects the conversion rank.
5145  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5146  ImplicitConversionKind SecondKind;
5147  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5148    SecondKind = ICK_Identity;
5149  } else if (S.IsDerivedFrom(LocFromTypeClassType))
5150    SecondKind = ICK_Derived_To_Base;
5151  else {
5152    ICS.setBad(BadConversionSequence::unrelated_class,
5153               FromTypeImplicitParamType);
5154    return ICS;
5155  }
5156
5157  // Check the ref-qualifier.
5158  switch (Method->getRefQualifier()) {
5159  case RQ_None:
5160    // Do nothing; we don't care about lvalueness or rvalueness.
5161    break;
5162
5163  case RQ_LValue:
5164    if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5165      // non-const lvalue reference cannot bind to an rvalue
5166      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalueFromType,
5167                 ImplicitParamType);
5168      return ICS;
5169    }
5170    break;
5171
5172  case RQ_RValue:
5173    if (!FromClassification.isRValue()) {
5174      // rvalue reference cannot bind to an lvalue
5175      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalueFromType,
5176                 ImplicitParamType);
5177      return ICS;
5178    }
5179    break;
5180  }
5181
5182  // Success. Mark this as a reference binding.
5183  ICS.setStandard();
5184  ICS.Standard.setAsIdentityConversion();
5185  ICS.Standard.Second = SecondKind;
5186  ICS.Standard.setFromType(FromType);
5187  ICS.Standard.setAllToTypes(ImplicitParamType);
5188  ICS.Standard.ReferenceBinding = true;
5189  ICS.Standard.DirectBinding = true;
5190  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5191  ICS.Standard.BindsToFunctionLvalue = false;
5192  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5193  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5194    = (Method->getRefQualifier() == RQ_None);
5195  return ICS;
5196}
5197
5198/// PerformObjectArgumentInitialization - Perform initialization of
5199/// the implicit object parameter for the given Method with the given
5200/// expression.
5201ExprResult
5202Sema::PerformObjectArgumentInitialization(Expr *From,
5203                                          NestedNameSpecifier *Qualifier,
5204                                          NamedDecl *FoundDecl,
5205                                          CXXMethodDecl *Method) {
5206  QualType FromRecordTypeDestType;
5207  QualType ImplicitParamRecordType  =
5208    Method->getThisType()->getAs<PointerType>()->getPointeeType();
5209
5210  Expr::Classification FromClassification;
5211  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5212    FromRecordType = PT->getPointeeType();
5213    DestType = Method->getThisType();
5214    FromClassification = Expr::Classification::makeSimpleLValue();
5215  } else {
5216    FromRecordType = From->getType();
5217    DestType = ImplicitParamRecordType;
5218    FromClassification = From->Classify(Context);
5219
5220    // When performing member access on an rvalue, materialize a temporary.
5221    if (From->isRValue()) {
5222      From = CreateMaterializeTemporaryExpr(FromRecordTypeFrom,
5223                                            Method->getRefQualifier() !=
5224                                                RefQualifierKind::RQ_RValue);
5225    }
5226  }
5227
5228  // Note that we always use the true parent context when performing
5229  // the actual argument initialization.
5230  ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5231      *thisFrom->getBeginLoc(), From->getType(), FromClassificationMethod,
5232      Method->getParent());
5233  if (ICS.isBad()) {
5234    switch (ICS.Bad.Kind) {
5235    case BadConversionSequence::bad_qualifiers: {
5236      Qualifiers FromQs = FromRecordType.getQualifiers();
5237      Qualifiers ToQs = DestType.getQualifiers();
5238      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5239      if (CVR) {
5240        Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5241            << Method->getDeclName() << FromRecordType << (CVR - 1)
5242            << From->getSourceRange();
5243        Diag(Method->getLocation(), diag::note_previous_decl)
5244          << Method->getDeclName();
5245        return ExprError();
5246      }
5247      break;
5248    }
5249
5250    case BadConversionSequence::lvalue_ref_to_rvalue:
5251    case BadConversionSequence::rvalue_ref_to_lvalue: {
5252      bool IsRValueQualified =
5253        Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5254      Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5255          << Method->getDeclName() << FromClassification.isRValue()
5256          << IsRValueQualified;
5257      Diag(Method->getLocation(), diag::note_previous_decl)
5258        << Method->getDeclName();
5259      return ExprError();
5260    }
5261
5262    case BadConversionSequence::no_conversion:
5263    case BadConversionSequence::unrelated_class:
5264      break;
5265    }
5266
5267    return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5268           << ImplicitParamRecordType << FromRecordType
5269           << From->getSourceRange();
5270  }
5271
5272  if (ICS.Standard.Second == ICK_Derived_To_Base) {
5273    ExprResult FromRes =
5274      PerformObjectMemberConversion(FromQualifierFoundDeclMethod);
5275    if (FromRes.isInvalid())
5276      return ExprError();
5277    From = FromRes.get();
5278  }
5279
5280  if (!Context.hasSameType(From->getType(), DestType)) {
5281    if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5282      From = ImpCastExprToType(FromDestTypeCK_AddressSpaceConversion,
5283                             From->getValueKind()).get();
5284    else
5285      From = ImpCastExprToType(FromDestTypeCK_NoOp,
5286                             From->getValueKind()).get();
5287  }
5288  return From;
5289}
5290
5291/// TryContextuallyConvertToBool - Attempt to contextually convert the
5292/// expression From to bool (C++0x [conv]p3).
5293static ImplicitConversionSequence
5294TryContextuallyConvertToBool(Sema &SExpr *From) {
5295  return TryImplicitConversion(SFromS.Context.BoolTy,
5296                               /*SuppressUserConversions=*/false,
5297                               /*AllowExplicit=*/true,
5298                               /*InOverloadResolution=*/false,
5299                               /*CStyle=*/false,
5300                               /*AllowObjCWritebackConversion=*/false,
5301                               /*AllowObjCConversionOnExplicit=*/false);
5302}
5303
5304/// PerformContextuallyConvertToBool - Perform a contextual conversion
5305/// of the expression From to bool (C++0x [conv]p3).
5306ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5307  if (checkPlaceholderForOverload(*thisFrom))
5308    return ExprError();
5309
5310  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*thisFrom);
5311  if (!ICS.isBad())
5312    return PerformImplicitConversion(FromContext.BoolTyICSAA_Converting);
5313
5314  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5315    return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5316           << From->getType() << From->getSourceRange();
5317  return ExprError();
5318}
5319
5320/// Check that the specified conversion is permitted in a converted constant
5321/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5322/// is acceptable.
5323static bool CheckConvertedConstantConversions(Sema &S,
5324                                              StandardConversionSequence &SCS) {
5325  // Since we know that the target type is an integral or unscoped enumeration
5326  // type, most conversion kinds are impossible. All possible First and Third
5327  // conversions are fine.
5328  switch (SCS.Second) {
5329  case ICK_Identity:
5330  case ICK_Function_Conversion:
5331  case ICK_Integral_Promotion:
5332  case ICK_Integral_Conversion// Narrowing conversions are checked elsewhere.
5333  case ICK_Zero_Queue_Conversion:
5334    return true;
5335
5336  case ICK_Boolean_Conversion:
5337    // Conversion from an integral or unscoped enumeration type to bool is
5338    // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5339    // conversion, so we allow it in a converted constant expression.
5340    //
5341    // FIXME: Per core issue 1407, we should not allow this, but that breaks
5342    // a lot of popular code. We should at least add a warning for this
5343    // (non-conforming) extension.
5344    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5345           SCS.getToType(2)->isBooleanType();
5346
5347  case ICK_Pointer_Conversion:
5348  case ICK_Pointer_Member:
5349    // C++1z: null pointer conversions and null member pointer conversions are
5350    // only permitted if the source type is std::nullptr_t.
5351    return SCS.getFromType()->isNullPtrType();
5352
5353  case ICK_Floating_Promotion:
5354  case ICK_Complex_Promotion:
5355  case ICK_Floating_Conversion:
5356  case ICK_Complex_Conversion:
5357  case ICK_Floating_Integral:
5358  case ICK_Compatible_Conversion:
5359  case ICK_Derived_To_Base:
5360  case ICK_Vector_Conversion:
5361  case ICK_Vector_Splat:
5362  case ICK_Complex_Real:
5363  case ICK_Block_Pointer_Conversion:
5364  case ICK_TransparentUnionConversion:
5365  case ICK_Writeback_Conversion:
5366  case ICK_Zero_Event_Conversion:
5367  case ICK_C_Only_Conversion:
5368  case ICK_Incompatible_Pointer_Conversion:
5369    return false;
5370
5371  case ICK_Lvalue_To_Rvalue:
5372  case ICK_Array_To_Pointer:
5373  case ICK_Function_To_Pointer:
5374    llvm_unreachable("found a first conversion kind in Second");
5375
5376  case ICK_Qualification:
5377    llvm_unreachable("found a third conversion kind in Second");
5378
5379  case ICK_Num_Conversion_Kinds:
5380    break;
5381  }
5382
5383  llvm_unreachable("unknown conversion kind");
5384}
5385
5386/// CheckConvertedConstantExpression - Check that the expression From is a
5387/// converted constant expression of type T, perform the conversion and produce
5388/// the converted expression, per C++11 [expr.const]p3.
5389static ExprResult CheckConvertedConstantExpression(Sema &SExpr *From,
5390                                                   QualType TAPValue &Value,
5391                                                   Sema::CCEKind CCE,
5392                                                   bool RequireInt) {
5393   (0) . __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5394, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S.getLangOpts().CPlusPlus11 &&
5394 (0) . __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5394, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "converted constant expression outside C++11");
5395
5396  if (checkPlaceholderForOverload(SFrom))
5397    return ExprError();
5398
5399  // C++1z [expr.const]p3:
5400  //  A converted constant expression of type T is an expression,
5401  //  implicitly converted to type T, where the converted
5402  //  expression is a constant expression and the implicit conversion
5403  //  sequence contains only [... list of conversions ...].
5404  // C++1z [stmt.if]p2:
5405  //  If the if statement is of the form if constexpr, the value of the
5406  //  condition shall be a contextually converted constant expression of type
5407  //  bool.
5408  ImplicitConversionSequence ICS =
5409      CCE == Sema::CCEK_ConstexprIf
5410          ? TryContextuallyConvertToBool(SFrom)
5411          : TryCopyInitialization(SFromT,
5412                                  /*SuppressUserConversions=*/false,
5413                                  /*InOverloadResolution=*/false,
5414                                  /*AllowObjcWritebackConversion=*/false,
5415                                  /*AllowExplicit=*/false);
5416  StandardConversionSequence *SCS = nullptr;
5417  switch (ICS.getKind()) {
5418  case ImplicitConversionSequence::StandardConversion:
5419    SCS = &ICS.Standard;
5420    break;
5421  case ImplicitConversionSequence::UserDefinedConversion:
5422    // We are converting to a non-class type, so the Before sequence
5423    // must be trivial.
5424    SCS = &ICS.UserDefined.After;
5425    break;
5426  case ImplicitConversionSequence::AmbiguousConversion:
5427  case ImplicitConversionSequence::BadConversion:
5428    if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5429      return S.Diag(From->getBeginLoc(),
5430                    diag::err_typecheck_converted_constant_expression)
5431             << From->getType() << From->getSourceRange() << T;
5432    return ExprError();
5433
5434  case ImplicitConversionSequence::EllipsisConversion:
5435    llvm_unreachable("ellipsis conversion in converted constant expression");
5436  }
5437
5438  // Check that we would only use permitted conversions.
5439  if (!CheckConvertedConstantConversions(S*SCS)) {
5440    return S.Diag(From->getBeginLoc(),
5441                  diag::err_typecheck_converted_constant_expression_disallowed)
5442           << From->getType() << From->getSourceRange() << T;
5443  }
5444  // [...] and where the reference binding (if any) binds directly.
5445  if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5446    return S.Diag(From->getBeginLoc(),
5447                  diag::err_typecheck_converted_constant_expression_indirect)
5448           << From->getType() << From->getSourceRange() << T;
5449  }
5450
5451  ExprResult Result =
5452      S.PerformImplicitConversion(FromTICSSema::AA_Converting);
5453  if (Result.isInvalid())
5454    return Result;
5455
5456  // Check for a narrowing implicit conversion.
5457  APValue PreNarrowingValue;
5458  QualType PreNarrowingType;
5459  switch (SCS->getNarrowingKind(S.ContextResult.get(), PreNarrowingValue,
5460                                PreNarrowingType)) {
5461  case NK_Dependent_Narrowing:
5462    // Implicit conversion to a narrower type, but the expression is
5463    // value-dependent so we can't tell whether it's actually narrowing.
5464  case NK_Variable_Narrowing:
5465    // Implicit conversion to a narrower type, and the value is not a constant
5466    // expression. We'll diagnose this in a moment.
5467  case NK_Not_Narrowing:
5468    break;
5469
5470  case NK_Constant_Narrowing:
5471    S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5472        << CCE << /*Constant*/ 1
5473        << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5474    break;
5475
5476  case NK_Type_Narrowing:
5477    S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5478        << CCE << /*Constant*/ 0 << From->getType() << T;
5479    break;
5480  }
5481
5482  if (Result.get()->isValueDependent()) {
5483    Value = APValue();
5484    return Result;
5485  }
5486
5487  // Check the expression is a constant expression.
5488  SmallVector<PartialDiagnosticAt8Notes;
5489  Expr::EvalResult Eval;
5490  Eval.Diag = &Notes;
5491  Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5492                                   ? Expr::EvaluateForMangling
5493                                   : Expr::EvaluateForCodeGen;
5494
5495  if (!Result.get()->EvaluateAsConstantExpr(EvalUsageS.Context) ||
5496      (RequireInt && !Eval.Val.isInt())) {
5497    // The expression can't be folded, so we can't keep it at this position in
5498    // the AST.
5499    Result = ExprError();
5500  } else {
5501    Value = Eval.Val;
5502
5503    if (Notes.empty()) {
5504      // It's a constant expression.
5505      return ConstantExpr::Create(S.ContextResult.get());
5506    }
5507  }
5508
5509  // It's not a constant expression. Produce an appropriate diagnostic.
5510  if (Notes.size() == 1 &&
5511      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5512    S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5513  else {
5514    S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5515        << CCE << From->getSourceRange();
5516    for (unsigned I = 0; I < Notes.size(); ++I)
5517      S.Diag(Notes[I].first, Notes[I].second);
5518  }
5519  return ExprError();
5520}
5521
5522ExprResult Sema::CheckConvertedConstantExpression(Expr *FromQualType T,
5523                                                  APValue &ValueCCEKind CCE) {
5524  return ::CheckConvertedConstantExpression(*thisFromTValueCCEfalse);
5525}
5526
5527ExprResult Sema::CheckConvertedConstantExpression(Expr *FromQualType T,
5528                                                  llvm::APSInt &Value,
5529                                                  CCEKind CCE) {
5530   (0) . __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5530, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5531
5532  APValue V;
5533  auto R = ::CheckConvertedConstantExpression(*thisFromTVCCEtrue);
5534  if (!R.isInvalid() && !R.get()->isValueDependent())
5535    Value = V.getInt();
5536  return R;
5537}
5538
5539
5540/// dropPointerConversions - If the given standard conversion sequence
5541/// involves any pointer conversions, remove them.  This may change
5542/// the result type of the conversion sequence.
5543static void dropPointerConversion(StandardConversionSequence &SCS) {
5544  if (SCS.Second == ICK_Pointer_Conversion) {
5545    SCS.Second = ICK_Identity;
5546    SCS.Third = ICK_Identity;
5547    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5548  }
5549}
5550
5551/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5552/// convert the expression From to an Objective-C pointer type.
5553static ImplicitConversionSequence
5554TryContextuallyConvertToObjCPointer(Sema &SExpr *From) {
5555  // Do an implicit conversion to 'id'.
5556  QualType Ty = S.Context.getObjCIdType();
5557  ImplicitConversionSequence ICS
5558    = TryImplicitConversion(SFromTy,
5559                            // FIXME: Are these flags correct?
5560                            /*SuppressUserConversions=*/false,
5561                            /*AllowExplicit=*/true,
5562                            /*InOverloadResolution=*/false,
5563                            /*CStyle=*/false,
5564                            /*AllowObjCWritebackConversion=*/false,
5565                            /*AllowObjCConversionOnExplicit=*/true);
5566
5567  // Strip off any final conversions to 'id'.
5568  switch (ICS.getKind()) {
5569  case ImplicitConversionSequence::BadConversion:
5570  case ImplicitConversionSequence::AmbiguousConversion:
5571  case ImplicitConversionSequence::EllipsisConversion:
5572    break;
5573
5574  case ImplicitConversionSequence::UserDefinedConversion:
5575    dropPointerConversion(ICS.UserDefined.After);
5576    break;
5577
5578  case ImplicitConversionSequence::StandardConversion:
5579    dropPointerConversion(ICS.Standard);
5580    break;
5581  }
5582
5583  return ICS;
5584}
5585
5586/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5587/// conversion of the expression From to an Objective-C pointer type.
5588/// Returns a valid but null ExprResult if no conversion sequence exists.
5589ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5590  if (checkPlaceholderForOverload(*thisFrom))
5591    return ExprError();
5592
5593  QualType Ty = Context.getObjCIdType();
5594  ImplicitConversionSequence ICS =
5595    TryContextuallyConvertToObjCPointer(*thisFrom);
5596  if (!ICS.isBad())
5597    return PerformImplicitConversion(FromTyICSAA_Converting);
5598  return ExprResult();
5599}
5600
5601/// Determine whether the provided type is an integral type, or an enumeration
5602/// type of a permitted flavor.
5603bool Sema::ICEConvertDiagnoser::match(QualType T) {
5604  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5605                                 : T->isIntegralOrUnscopedEnumerationType();
5606}
5607
5608static ExprResult
5609diagnoseAmbiguousConversion(Sema &SemaRefSourceLocation LocExpr *From,
5610                            Sema::ContextualImplicitConverter &Converter,
5611                            QualType TUnresolvedSetImpl &ViableConversions) {
5612
5613  if (Converter.Suppress)
5614    return ExprError();
5615
5616  Converter.diagnoseAmbiguous(SemaRefLocT) << From->getSourceRange();
5617  for (unsigned I = 0N = ViableConversions.size(); I != N; ++I) {
5618    CXXConversionDecl *Conv =
5619        cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5620    QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5621    Converter.noteAmbiguous(SemaRefConvConvTy);
5622  }
5623  return From;
5624}
5625
5626static bool
5627diagnoseNoViableConversion(Sema &SemaRefSourceLocation LocExpr *&From,
5628                           Sema::ContextualImplicitConverter &Converter,
5629                           QualType Tbool HadMultipleCandidates,
5630                           UnresolvedSetImpl &ExplicitConversions) {
5631  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5632    DeclAccessPair Found = ExplicitConversions[0];
5633    CXXConversionDecl *Conversion =
5634        cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5635
5636    // The user probably meant to invoke the given explicit
5637    // conversion; use it.
5638    QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5639    std::string TypeStr;
5640    ConvTy.getAsStringInternal(TypeStrSemaRef.getPrintingPolicy());
5641
5642    Converter.diagnoseExplicitConv(SemaRefLocTConvTy)
5643        << FixItHint::CreateInsertion(From->getBeginLoc(),
5644                                      "static_cast<" + TypeStr + ">(")
5645        << FixItHint::CreateInsertion(
5646               SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5647    Converter.noteExplicitConv(SemaRefConversionConvTy);
5648
5649    // If we aren't in a SFINAE context, build a call to the
5650    // explicit conversion function.
5651    if (SemaRef.isSFINAEContext())
5652      return true;
5653
5654    SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), FromnullptrFound);
5655    ExprResult Result = SemaRef.BuildCXXMemberCallExpr(FromFoundConversion,
5656                                                       HadMultipleCandidates);
5657    if (Result.isInvalid())
5658      return true;
5659    // Record usage of conversion in an implicit cast.
5660    From = ImplicitCastExpr::Create(SemaRef.ContextResult.get()->getType(),
5661                                    CK_UserDefinedConversionResult.get(),
5662                                    nullptrResult.get()->getValueKind());
5663  }
5664  return false;
5665}
5666
5667static bool recordConversion(Sema &SemaRefSourceLocation LocExpr *&From,
5668                             Sema::ContextualImplicitConverter &Converter,
5669                             QualType Tbool HadMultipleCandidates,
5670                             DeclAccessPair &Found) {
5671  CXXConversionDecl *Conversion =
5672      cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5673  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), FromnullptrFound);
5674
5675  QualType ToType = Conversion->getConversionType().getNonReferenceType();
5676  if (!Converter.SuppressConversion) {
5677    if (SemaRef.isSFINAEContext())
5678      return true;
5679
5680    Converter.diagnoseConversion(SemaRefLocTToType)
5681        << From->getSourceRange();
5682  }
5683
5684  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(FromFoundConversion,
5685                                                     HadMultipleCandidates);
5686  if (Result.isInvalid())
5687    return true;
5688  // Record usage of conversion in an implicit cast.
5689  From = ImplicitCastExpr::Create(SemaRef.ContextResult.get()->getType(),
5690                                  CK_UserDefinedConversionResult.get(),
5691                                  nullptrResult.get()->getValueKind());
5692  return false;
5693}
5694
5695static ExprResult finishContextualImplicitConversion(
5696    Sema &SemaRefSourceLocation LocExpr *From,
5697    Sema::ContextualImplicitConverter &Converter) {
5698  if (!Converter.match(From->getType()) && !Converter.Suppress)
5699    Converter.diagnoseNoMatch(SemaRefLocFrom->getType())
5700        << From->getSourceRange();
5701
5702  return SemaRef.DefaultLvalueConversion(From);
5703}
5704
5705static void
5706collectViableConversionCandidates(Sema &SemaRefExpr *FromQualType ToType,
5707                                  UnresolvedSetImpl &ViableConversions,
5708                                  OverloadCandidateSet &CandidateSet) {
5709  for (unsigned I = 0N = ViableConversions.size(); I != N; ++I) {
5710    DeclAccessPair FoundDecl = ViableConversions[I];
5711    NamedDecl *D = FoundDecl.getDecl();
5712    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5713    if (isa<UsingShadowDecl>(D))
5714      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5715
5716    CXXConversionDecl *Conv;
5717    FunctionTemplateDecl *ConvTemplate;
5718    if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5719      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5720    else
5721      Conv = cast<CXXConversionDecl>(D);
5722
5723    if (ConvTemplate)
5724      SemaRef.AddTemplateConversionCandidate(
5725        ConvTemplateFoundDeclActingContextFromToTypeCandidateSet,
5726        /*AllowObjCConversionOnExplicit=*/false);
5727    else
5728      SemaRef.AddConversionCandidate(ConvFoundDeclActingContextFrom,
5729                                     ToTypeCandidateSet,
5730                                     /*AllowObjCConversionOnExplicit=*/false);
5731  }
5732}
5733
5734/// Attempt to convert the given expression to a type which is accepted
5735/// by the given converter.
5736///
5737/// This routine will attempt to convert an expression of class type to a
5738/// type accepted by the specified converter. In C++11 and before, the class
5739/// must have a single non-explicit conversion function converting to a matching
5740/// type. In C++1y, there can be multiple such conversion functions, but only
5741/// one target type.
5742///
5743/// \param Loc The source location of the construct that requires the
5744/// conversion.
5745///
5746/// \param From The expression we're converting from.
5747///
5748/// \param Converter Used to control and diagnose the conversion process.
5749///
5750/// \returns The expression, converted to an integral or enumeration type if
5751/// successful.
5752ExprResult Sema::PerformContextualImplicitConversion(
5753    SourceLocation LocExpr *FromContextualImplicitConverter &Converter) {
5754  // We can't perform any more checking for type-dependent expressions.
5755  if (From->isTypeDependent())
5756    return From;
5757
5758  // Process placeholders immediately.
5759  if (From->hasPlaceholderType()) {
5760    ExprResult result = CheckPlaceholderExpr(From);
5761    if (result.isInvalid())
5762      return result;
5763    From = result.get();
5764  }
5765
5766  // If the expression already has a matching type, we're golden.
5767  QualType T = From->getType();
5768  if (Converter.match(T))
5769    return DefaultLvalueConversion(From);
5770
5771  // FIXME: Check for missing '()' if T is a function type?
5772
5773  // We can only perform contextual implicit conversions on objects of class
5774  // type.
5775  const RecordType *RecordTy = T->getAs<RecordType>();
5776  if (!RecordTy || !getLangOpts().CPlusPlus) {
5777    if (!Converter.Suppress)
5778      Converter.diagnoseNoMatch(*thisLocT) << From->getSourceRange();
5779    return From;
5780  }
5781
5782  // We must have a complete class type.
5783  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5784    ContextualImplicitConverter &Converter;
5785    Expr *From;
5786
5787    TypeDiagnoserPartialDiag(ContextualImplicitConverter &ConverterExpr *From)
5788        : Converter(Converter), From(From) {}
5789
5790    void diagnose(Sema &SSourceLocation LocQualType T) override {
5791      Converter.diagnoseIncomplete(SLocT) << From->getSourceRange();
5792    }
5793  } IncompleteDiagnoser(ConverterFrom);
5794
5795  if (Converter.Suppress ? !isCompleteType(LocT)
5796                         : RequireCompleteType(LocTIncompleteDiagnoser))
5797    return From;
5798
5799  // Look for a conversion to an integral or enumeration type.
5800  UnresolvedSet<4>
5801      ViableConversions// These are *potentially* viable in C++1y.
5802  UnresolvedSet<4ExplicitConversions;
5803  const auto &Conversions =
5804      cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5805
5806  bool HadMultipleCandidates =
5807      (std::distance(Conversions.begin(), Conversions.end()) > 1);
5808
5809  // To check that there is only one target type, in C++1y:
5810  QualType ToType;
5811  bool HasUniqueTargetType = true;
5812
5813  // Collect explicit or viable (potentially in C++1y) conversions.
5814  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5815    NamedDecl *D = (*I)->getUnderlyingDecl();
5816    CXXConversionDecl *Conversion;
5817    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5818    if (ConvTemplate) {
5819      if (getLangOpts().CPlusPlus14)
5820        Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5821      else
5822        continue// C++11 does not consider conversion operator templates(?).
5823    } else
5824      Conversion = cast<CXXConversionDecl>(D);
5825
5826     (0) . __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5828, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5827 (0) . __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5828, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Conversion operator templates are considered potentially "
5828 (0) . __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5828, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "viable in C++1y");
5829
5830    QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5831    if (Converter.match(CurToType) || ConvTemplate) {
5832
5833      if (Conversion->isExplicit()) {
5834        // FIXME: For C++1y, do we need this restriction?
5835        // cf. diagnoseNoViableConversion()
5836        if (!ConvTemplate)
5837          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5838      } else {
5839        if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5840          if (ToType.isNull())
5841            ToType = CurToType.getUnqualifiedType();
5842          else if (HasUniqueTargetType &&
5843                   (CurToType.getUnqualifiedType() != ToType))
5844            HasUniqueTargetType = false;
5845        }
5846        ViableConversions.addDecl(I.getDecl(), I.getAccess());
5847      }
5848    }
5849  }
5850
5851  if (getLangOpts().CPlusPlus14) {
5852    // C++1y [conv]p6:
5853    // ... An expression e of class type E appearing in such a context
5854    // is said to be contextually implicitly converted to a specified
5855    // type T and is well-formed if and only if e can be implicitly
5856    // converted to a type T that is determined as follows: E is searched
5857    // for conversion functions whose return type is cv T or reference to
5858    // cv T such that T is allowed by the context. There shall be
5859    // exactly one such T.
5860
5861    // If no unique T is found:
5862    if (ToType.isNull()) {
5863      if (diagnoseNoViableConversion(*thisLocFromConverterT,
5864                                     HadMultipleCandidates,
5865                                     ExplicitConversions))
5866        return ExprError();
5867      return finishContextualImplicitConversion(*thisLocFromConverter);
5868    }
5869
5870    // If more than one unique Ts are found:
5871    if (!HasUniqueTargetType)
5872      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5873                                         ViableConversions);
5874
5875    // If one unique T is found:
5876    // First, build a candidate set from the previously recorded
5877    // potentially viable conversions.
5878    OverloadCandidateSet CandidateSet(LocOverloadCandidateSet::CSK_Normal);
5879    collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5880                                      CandidateSet);
5881
5882    // Then, perform overload resolution over the candidate set.
5883    OverloadCandidateSet::iterator Best;
5884    switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5885    case OR_Success: {
5886      // Apply this conversion.
5887      DeclAccessPair Found =
5888          DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5889      if (recordConversion(*this, Loc, From, Converter, T,
5890                           HadMultipleCandidates, Found))
5891        return ExprError();
5892      break;
5893    }
5894    case OR_Ambiguous:
5895      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5896                                         ViableConversions);
5897    case OR_No_Viable_Function:
5898      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5899                                     HadMultipleCandidates,
5900                                     ExplicitConversions))
5901        return ExprError();
5902      LLVM_FALLTHROUGH;
5903    case OR_Deleted:
5904      // We'll complain below about a non-integral condition type.
5905      break;
5906    }
5907  } else {
5908    switch (ViableConversions.size()) {
5909    case 0: {
5910      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5911                                     HadMultipleCandidates,
5912                                     ExplicitConversions))
5913        return ExprError();
5914
5915      // We'll complain below about a non-integral condition type.
5916      break;
5917    }
5918    case 1: {
5919      // Apply this conversion.
5920      DeclAccessPair Found = ViableConversions[0];
5921      if (recordConversion(*this, Loc, From, Converter, T,
5922                           HadMultipleCandidates, Found))
5923        return ExprError();
5924      break;
5925    }
5926    default:
5927      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5928                                         ViableConversions);
5929    }
5930  }
5931
5932  return finishContextualImplicitConversion(*thisLocFromConverter);
5933}
5934
5935/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5936/// an acceptable non-member overloaded operator for a call whose
5937/// arguments have types T1 (and, if non-empty, T2). This routine
5938/// implements the check in C++ [over.match.oper]p3b2 concerning
5939/// enumeration types.
5940static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5941                                                   FunctionDecl *Fn,
5942                                                   ArrayRef<Expr *> Args) {
5943  QualType T1 = Args[0]->getType();
5944  QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5945
5946  if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5947    return true;
5948
5949  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5950    return true;
5951
5952  const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5953  if (Proto->getNumParams() < 1)
5954    return false;
5955
5956  if (T1->isEnumeralType()) {
5957    QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5958    if (Context.hasSameUnqualifiedType(T1ArgType))
5959      return true;
5960  }
5961
5962  if (Proto->getNumParams() < 2)
5963    return false;
5964
5965  if (!T2.isNull() && T2->isEnumeralType()) {
5966    QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5967    if (Context.hasSameUnqualifiedType(T2ArgType))
5968      return true;
5969  }
5970
5971  return false;
5972}
5973
5974/// AddOverloadCandidate - Adds the given function to the set of
5975/// candidate functions, using the given function call arguments.  If
5976/// @p SuppressUserConversions, then don't allow user-defined
5977/// conversions via constructors or conversion operators.
5978///
5979/// \param PartialOverloading true if we are performing "partial" overloading
5980/// based on an incomplete set of function arguments. This feature is used by
5981/// code completion.
5982void Sema::AddOverloadCandidate(FunctionDecl *Function,
5983                                DeclAccessPair FoundDeclArrayRef<Expr *> Args,
5984                                OverloadCandidateSet &CandidateSet,
5985                                bool SuppressUserConversions,
5986                                bool PartialOverloadingbool AllowExplicit,
5987                                ADLCallKind IsADLCandidate,
5988                                ConversionSequenceList EarlyConversions) {
5989  const FunctionProtoType *Proto
5990    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5991   (0) . __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5991, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Proto && "Functions without a prototype cannot be overloaded");
5992   (0) . __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5993, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Function->getDescribedFunctionTemplate() &&
5993 (0) . __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 5993, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Use AddTemplateOverloadCandidate for function templates");
5994
5995  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5996    if (!isa<CXXConstructorDecl>(Method)) {
5997      // If we get here, it's because we're calling a member function
5998      // that is named without a member access expression (e.g.,
5999      // "this->f") that was either written explicitly or created
6000      // implicitly. This can happen with a qualified call to a member
6001      // function, e.g., X::f(). We use an empty type for the implied
6002      // object argument (C++ [over.call.func]p3), and the acting context
6003      // is irrelevant.
6004      AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6005                         Expr::Classification::makeSimpleLValue(), Args,
6006                         CandidateSet, SuppressUserConversions,
6007                         PartialOverloading, EarlyConversions);
6008      return;
6009    }
6010    // We treat a constructor like a non-member function, since its object
6011    // argument doesn't participate in overload resolution.
6012  }
6013
6014  if (!CandidateSet.isNewCandidate(Function))
6015    return;
6016
6017  // C++ [over.match.oper]p3:
6018  //   if no operand has a class type, only those non-member functions in the
6019  //   lookup set that have a first parameter of type T1 or "reference to
6020  //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6021  //   is a right operand) a second parameter of type T2 or "reference to
6022  //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6023  //   candidate functions.
6024  if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6025      !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6026    return;
6027
6028  // C++11 [class.copy]p11: [DR1402]
6029  //   A defaulted move constructor that is defined as deleted is ignored by
6030  //   overload resolution.
6031  CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6032  if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6033      Constructor->isMoveConstructor())
6034    return;
6035
6036  // Overload resolution is always an unevaluated context.
6037  EnterExpressionEvaluationContext Unevaluated(
6038      *thisSema::ExpressionEvaluationContext::Unevaluated);
6039
6040  // Add this candidate
6041  OverloadCandidate &Candidate =
6042      CandidateSet.addCandidate(Args.size(), EarlyConversions);
6043  Candidate.FoundDecl = FoundDecl;
6044  Candidate.Function = Function;
6045  Candidate.Viable = true;
6046  Candidate.IsSurrogate = false;
6047  Candidate.IsADLCandidate = IsADLCandidate;
6048  Candidate.IgnoreObjectArgument = false;
6049  Candidate.ExplicitCallArguments = Args.size();
6050
6051  if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6052      !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6053    Candidate.Viable = false;
6054    Candidate.FailureKind = ovl_non_default_multiversion_function;
6055    return;
6056  }
6057
6058  if (Constructor) {
6059    // C++ [class.copy]p3:
6060    //   A member function template is never instantiated to perform the copy
6061    //   of a class object to an object of its class type.
6062    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6063    if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6064        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6065         IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6066                       ClassType))) {
6067      Candidate.Viable = false;
6068      Candidate.FailureKind = ovl_fail_illegal_constructor;
6069      return;
6070    }
6071
6072    // C++ [over.match.funcs]p8: (proposed DR resolution)
6073    //   A constructor inherited from class type C that has a first parameter
6074    //   of type "reference to P" (including such a constructor instantiated
6075    //   from a template) is excluded from the set of candidate functions when
6076    //   constructing an object of type cv D if the argument list has exactly
6077    //   one argument and D is reference-related to P and P is reference-related
6078    //   to C.
6079    auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6080    if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6081        Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6082      QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6083      QualType C = Context.getRecordType(Constructor->getParent());
6084      QualType D = Context.getRecordType(Shadow->getParent());
6085      SourceLocation Loc = Args.front()->getExprLoc();
6086      if ((Context.hasSameUnqualifiedType(PC) || IsDerivedFrom(LocPC)) &&
6087          (Context.hasSameUnqualifiedType(DP) || IsDerivedFrom(LocDP))) {
6088        Candidate.Viable = false;
6089        Candidate.FailureKind = ovl_fail_inhctor_slice;
6090        return;
6091      }
6092    }
6093  }
6094
6095  unsigned NumParams = Proto->getNumParams();
6096
6097  // (C++ 13.3.2p2): A candidate function having fewer than m
6098  // parameters is viable only if it has an ellipsis in its parameter
6099  // list (8.3.5).
6100  if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6101      !Proto->isVariadic()) {
6102    Candidate.Viable = false;
6103    Candidate.FailureKind = ovl_fail_too_many_arguments;
6104    return;
6105  }
6106
6107  // (C++ 13.3.2p2): A candidate function having more than m parameters
6108  // is viable only if the (m+1)st parameter has a default argument
6109  // (8.3.6). For the purposes of overload resolution, the
6110  // parameter list is truncated on the right, so that there are
6111  // exactly m parameters.
6112  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6113  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6114    // Not enough arguments.
6115    Candidate.Viable = false;
6116    Candidate.FailureKind = ovl_fail_too_few_arguments;
6117    return;
6118  }
6119
6120  // (CUDA B.1): Check for invalid calls between targets.
6121  if (getLangOpts().CUDA)
6122    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6123      // Skip the check for callers that are implicit members, because in this
6124      // case we may not yet know what the member's target is; the target is
6125      // inferred for the member automatically, based on the bases and fields of
6126      // the class.
6127      if (!Caller->isImplicit() && !IsAllowedCUDACall(CallerFunction)) {
6128        Candidate.Viable = false;
6129        Candidate.FailureKind = ovl_fail_bad_target;
6130        return;
6131      }
6132
6133  // Determine the implicit conversion sequences for each of the
6134  // arguments.
6135  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6136    if (Candidate.Conversions[ArgIdx].isInitialized()) {
6137      // We already formed a conversion sequence for this parameter during
6138      // template argument deduction.
6139    } else if (ArgIdx < NumParams) {
6140      // (C++ 13.3.2p3): for F to be a viable function, there shall
6141      // exist for each argument an implicit conversion sequence
6142      // (13.3.3.1) that converts that argument to the corresponding
6143      // parameter of F.
6144      QualType ParamType = Proto->getParamType(ArgIdx);
6145      Candidate.Conversions[ArgIdx]
6146        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6147                                SuppressUserConversions,
6148                                /*InOverloadResolution=*/true,
6149                                /*AllowObjCWritebackConversion=*/
6150                                  getLangOpts().ObjCAutoRefCount,
6151                                AllowExplicit);
6152      if (Candidate.Conversions[ArgIdx].isBad()) {
6153        Candidate.Viable = false;
6154        Candidate.FailureKind = ovl_fail_bad_conversion;
6155        return;
6156      }
6157    } else {
6158      // (C++ 13.3.2p2): For the purposes of overload resolution, any
6159      // argument for which there is no corresponding parameter is
6160      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6161      Candidate.Conversions[ArgIdx].setEllipsis();
6162    }
6163  }
6164
6165  if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6166    Candidate.Viable = false;
6167    Candidate.FailureKind = ovl_fail_enable_if;
6168    Candidate.DeductionFailure.Data = FailedAttr;
6169    return;
6170  }
6171
6172  if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6173    Candidate.Viable = false;
6174    Candidate.FailureKind = ovl_fail_ext_disabled;
6175    return;
6176  }
6177}
6178
6179ObjCMethodDecl *
6180Sema::SelectBestMethod(Selector SelMultiExprArg Argsbool IsInstance,
6181                       SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6182  if (Methods.size() <= 1)
6183    return nullptr;
6184
6185  for (unsigned b = 0e = Methods.size(); b < eb++) {
6186    bool Match = true;
6187    ObjCMethodDecl *Method = Methods[b];
6188    unsigned NumNamedArgs = Sel.getNumArgs();
6189    // Method might have more arguments than selector indicates. This is due
6190    // to addition of c-style arguments in method.
6191    if (Method->param_size() > NumNamedArgs)
6192      NumNamedArgs = Method->param_size();
6193    if (Args.size() < NumNamedArgs)
6194      continue;
6195
6196    for (unsigned i = 0i < NumNamedArgsi++) {
6197      // We can't do any type-checking on a type-dependent argument.
6198      if (Args[i]->isTypeDependent()) {
6199        Match = false;
6200        break;
6201      }
6202
6203      ParmVarDecl *param = Method->parameters()[i];
6204      Expr *argExpr = Args[i];
6205       (0) . __assert_fail ("argExpr && \"SelectBestMethod(). missing expression\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6205, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(argExpr && "SelectBestMethod(): missing expression");
6206
6207      // Strip the unbridged-cast placeholder expression off unless it's
6208      // a consumed argument.
6209      if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6210          !param->hasAttr<CFConsumedAttr>())
6211        argExpr = stripARCUnbridgedCast(argExpr);
6212
6213      // If the parameter is __unknown_anytype, move on to the next method.
6214      if (param->getType() == Context.UnknownAnyTy) {
6215        Match = false;
6216        break;
6217      }
6218
6219      ImplicitConversionSequence ConversionState
6220        = TryCopyInitialization(*thisargExprparam->getType(),
6221                                /*SuppressUserConversions*/false,
6222                                /*InOverloadResolution=*/true,
6223                                /*AllowObjCWritebackConversion=*/
6224                                getLangOpts().ObjCAutoRefCount,
6225                                /*AllowExplicit*/false);
6226      // This function looks for a reasonably-exact match, so we consider
6227      // incompatible pointer conversions to be a failure here.
6228      if (ConversionState.isBad() ||
6229          (ConversionState.isStandard() &&
6230           ConversionState.Standard.Second ==
6231               ICK_Incompatible_Pointer_Conversion)) {
6232        Match = false;
6233        break;
6234      }
6235    }
6236    // Promote additional arguments to variadic methods.
6237    if (Match && Method->isVariadic()) {
6238      for (unsigned i = NumNamedArgse = Args.size(); i < e; ++i) {
6239        if (Args[i]->isTypeDependent()) {
6240          Match = false;
6241          break;
6242        }
6243        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6244                                                          nullptr);
6245        if (Arg.isInvalid()) {
6246          Match = false;
6247          break;
6248        }
6249      }
6250    } else {
6251      // Check for extra arguments to non-variadic methods.
6252      if (Args.size() != NumNamedArgs)
6253        Match = false;
6254      else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6255        // Special case when selectors have no argument. In this case, select
6256        // one with the most general result type of 'id'.
6257        for (unsigned b = 0e = Methods.size(); b < eb++) {
6258          QualType ReturnT = Methods[b]->getReturnType();
6259          if (ReturnT->isObjCIdType())
6260            return Methods[b];
6261        }
6262      }
6263    }
6264
6265    if (Match)
6266      return Method;
6267  }
6268  return nullptr;
6269}
6270
6271static bool
6272convertArgsForAvailabilityChecks(Sema &SFunctionDecl *FunctionExpr *ThisArg,
6273                                 ArrayRef<Expr *> ArgsSema::SFINAETrap &Trap,
6274                                 bool MissingImplicitThisExpr *&ConvertedThis,
6275                                 SmallVectorImpl<Expr *> &ConvertedArgs) {
6276  if (ThisArg) {
6277    CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6278     (0) . __assert_fail ("!isa(Method) && \"Shouldn't have `this` for ctors!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6279, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isa<CXXConstructorDecl>(Method) &&
6279 (0) . __assert_fail ("!isa(Method) && \"Shouldn't have `this` for ctors!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6279, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Shouldn't have `this` for ctors!");
6280     (0) . __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6280, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6281    ExprResult R = S.PerformObjectArgumentInitialization(
6282        ThisArg/*Qualifier=*/nullptrMethodMethod);
6283    if (R.isInvalid())
6284      return false;
6285    ConvertedThis = R.get();
6286  } else {
6287    if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6288      (void)MD;
6289       (0) . __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa(MD)) && \"Expected `this` for non-ctor instance methods\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6291, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((MissingImplicitThis || MD->isStatic() ||
6290 (0) . __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa(MD)) && \"Expected `this` for non-ctor instance methods\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6291, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">              isa<CXXConstructorDecl>(MD)) &&
6291 (0) . __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa(MD)) && \"Expected `this` for non-ctor instance methods\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6291, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "Expected `this` for non-ctor instance methods");
6292    }
6293    ConvertedThis = nullptr;
6294  }
6295
6296  // Ignore any variadic arguments. Converting them is pointless, since the
6297  // user can't refer to them in the function condition.
6298  unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6299
6300  // Convert the arguments.
6301  for (unsigned I = 0I != ArgSizeNoVarargs; ++I) {
6302    ExprResult R;
6303    R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6304                                        S.Context, Function->getParamDecl(I)),
6305                                    SourceLocation(), Args[I]);
6306
6307    if (R.isInvalid())
6308      return false;
6309
6310    ConvertedArgs.push_back(R.get());
6311  }
6312
6313  if (Trap.hasErrorOccurred())
6314    return false;
6315
6316  // Push default arguments if needed.
6317  if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6318    for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6319      ParmVarDecl *P = Function->getParamDecl(i);
6320      Expr *DefArg = P->hasUninstantiatedDefaultArg()
6321                         ? P->getUninstantiatedDefaultArg()
6322                         : P->getDefaultArg();
6323      // This can only happen in code completion, i.e. when PartialOverloading
6324      // is true.
6325      if (!DefArg)
6326        return false;
6327      ExprResult R =
6328          S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6329                                          S.ContextFunction->getParamDecl(i)),
6330                                      SourceLocation(), DefArg);
6331      if (R.isInvalid())
6332        return false;
6333      ConvertedArgs.push_back(R.get());
6334    }
6335
6336    if (Trap.hasErrorOccurred())
6337      return false;
6338  }
6339  return true;
6340}
6341
6342EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *FunctionArrayRef<Expr *> Args,
6343                                  bool MissingImplicitThis) {
6344  auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6345  if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6346    return nullptr;
6347
6348  SFINAETrap Trap(*this);
6349  SmallVector<Expr *, 16ConvertedArgs;
6350  // FIXME: We should look into making enable_if late-parsed.
6351  Expr *DiscardedThis;
6352  if (!convertArgsForAvailabilityChecks(
6353          *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6354          /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6355    return *EnableIfAttrs.begin();
6356
6357  for (auto *EIA : EnableIfAttrs) {
6358    APValue Result;
6359    // FIXME: This doesn't consider value-dependent cases, because doing so is
6360    // very difficult. Ideally, we should handle them more gracefully.
6361    if (!EIA->getCond()->EvaluateWithSubstitution(
6362            Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6363      return EIA;
6364
6365    if (!Result.isInt() || !Result.getInt().getBoolValue())
6366      return EIA;
6367  }
6368  return nullptr;
6369}
6370
6371template <typename CheckFn>
6372static bool diagnoseDiagnoseIfAttrsWith(Sema &Sconst NamedDecl *ND,
6373                                        bool ArgDependentSourceLocation Loc,
6374                                        CheckFn &&IsSuccessful) {
6375  SmallVector<const DiagnoseIfAttr *, 8Attrs;
6376  for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6377    if (ArgDependent == DIA->getArgDependent())
6378      Attrs.push_back(DIA);
6379  }
6380
6381  // Common case: No diagnose_if attributes, so we can quit early.
6382  if (Attrs.empty())
6383    return false;
6384
6385  auto WarningBegin = std::stable_partition(
6386      Attrs.begin(), Attrs.end(),
6387      [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6388
6389  // Note that diagnose_if attributes are late-parsed, so they appear in the
6390  // correct order (unlike enable_if attributes).
6391  auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6392                               IsSuccessful);
6393  if (ErrAttr != WarningBegin) {
6394    const DiagnoseIfAttr *DIA = *ErrAttr;
6395    S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6396    S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6397        << DIA->getParent() << DIA->getCond()->getSourceRange();
6398    return true;
6399  }
6400
6401  for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6402    if (IsSuccessful(DIA)) {
6403      S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6404      S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6405          << DIA->getParent() << DIA->getCond()->getSourceRange();
6406    }
6407
6408  return false;
6409}
6410
6411bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6412                                               const Expr *ThisArg,
6413                                               ArrayRef<const Expr *> Args,
6414                                               SourceLocation Loc) {
6415  return diagnoseDiagnoseIfAttrsWith(
6416      *thisFunction/*ArgDependent=*/trueLoc,
6417      [&](const DiagnoseIfAttr *DIA) {
6418        APValue Result;
6419        // It's sane to use the same Args for any redecl of this function, since
6420        // EvaluateWithSubstitution only cares about the position of each
6421        // argument in the arg list, not the ParmVarDecl* it maps to.
6422        if (!DIA->getCond()->EvaluateWithSubstitution(
6423                Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6424          return false;
6425        return Result.isInt() && Result.getInt().getBoolValue();
6426      });
6427}
6428
6429bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6430                                                 SourceLocation Loc) {
6431  return diagnoseDiagnoseIfAttrsWith(
6432      *thisND/*ArgDependent=*/falseLoc,
6433      [&](const DiagnoseIfAttr *DIA) {
6434        bool Result;
6435        return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6436               Result;
6437      });
6438}
6439
6440/// Add all of the function declarations in the given function set to
6441/// the overload candidate set.
6442void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6443                                 ArrayRef<Expr *> Args,
6444                                 OverloadCandidateSet &CandidateSet,
6445                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
6446                                 bool SuppressUserConversions,
6447                                 bool PartialOverloading,
6448                                 bool FirstArgumentIsBase) {
6449  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6450    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6451    ArrayRef<Expr *> FunctionArgs = Args;
6452
6453    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6454    FunctionDecl *FD =
6455        FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6456
6457    if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6458      QualType ObjectType;
6459      Expr::Classification ObjectClassification;
6460      if (Args.size() > 0) {
6461        if (Expr *E = Args[0]) {
6462          // Use the explicit base to restrict the lookup:
6463          ObjectType = E->getType();
6464          // Pointers in the object arguments are implicitly dereferenced, so we
6465          // always classify them as l-values.
6466          if (!ObjectType.isNull() && ObjectType->isPointerType())
6467            ObjectClassification = Expr::Classification::makeSimpleLValue();
6468          else
6469            ObjectClassification = E->Classify(Context);
6470        } // .. else there is an implicit base.
6471        FunctionArgs = Args.slice(1);
6472      }
6473      if (FunTmpl) {
6474        AddMethodTemplateCandidate(
6475            FunTmpl, F.getPair(),
6476            cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6477            ExplicitTemplateArgs, ObjectType, ObjectClassification,
6478            FunctionArgs, CandidateSet, SuppressUserConversions,
6479            PartialOverloading);
6480      } else {
6481        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6482                           cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6483                           ObjectClassification, FunctionArgs, CandidateSet,
6484                           SuppressUserConversions, PartialOverloading);
6485      }
6486    } else {
6487      // This branch handles both standalone functions and static methods.
6488
6489      // Slice the first argument (which is the base) when we access
6490      // static method as non-static.
6491      if (Args.size() > 0 &&
6492          (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6493                        !isa<CXXConstructorDecl>(FD)))) {
6494        (FD)->isStatic()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6494, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(cast<CXXMethodDecl>(FD)->isStatic());
6495        FunctionArgs = Args.slice(1);
6496      }
6497      if (FunTmpl) {
6498        AddTemplateOverloadCandidate(
6499            FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6500            CandidateSet, SuppressUserConversions, PartialOverloading);
6501      } else {
6502        AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6503                             SuppressUserConversions, PartialOverloading);
6504      }
6505    }
6506  }
6507}
6508
6509/// AddMethodCandidate - Adds a named decl (which is some kind of
6510/// method) as a method candidate to the given overload set.
6511void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6512                              QualType ObjectType,
6513                              Expr::Classification ObjectClassification,
6514                              ArrayRef<Expr *> Args,
6515                              OverloadCandidateSetCandidateSet,
6516                              bool SuppressUserConversions) {
6517  NamedDecl *Decl = FoundDecl.getDecl();
6518  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6519
6520  if (isa<UsingShadowDecl>(Decl))
6521    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6522
6523  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6524     (0) . __assert_fail ("isa(TD->getTemplatedDecl()) && \"Expected a member function template\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6525, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6525 (0) . __assert_fail ("isa(TD->getTemplatedDecl()) && \"Expected a member function template\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6525, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Expected a member function template");
6526    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6527                               /*ExplicitArgs*/ nullptr, ObjectType,
6528                               ObjectClassification, Args, CandidateSet,
6529                               SuppressUserConversions);
6530  } else {
6531    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6532                       ObjectType, ObjectClassification, Args, CandidateSet,
6533                       SuppressUserConversions);
6534  }
6535}
6536
6537/// AddMethodCandidate - Adds the given C++ member function to the set
6538/// of candidate functions, using the given function call arguments
6539/// and the object argument (@c Object). For example, in a call
6540/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6541/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6542/// allow user-defined conversions via constructors or conversion
6543/// operators.
6544void
6545Sema::AddMethodCandidate(CXXMethodDecl *MethodDeclAccessPair FoundDecl,
6546                         CXXRecordDecl *ActingContextQualType ObjectType,
6547                         Expr::Classification ObjectClassification,
6548                         ArrayRef<Expr *> Args,
6549                         OverloadCandidateSet &CandidateSet,
6550                         bool SuppressUserConversions,
6551                         bool PartialOverloading,
6552                         ConversionSequenceList EarlyConversions) {
6553  const FunctionProtoType *Proto
6554    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6555   (0) . __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6555, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Proto && "Methods without a prototype cannot be overloaded");
6556   (0) . __assert_fail ("!isa(Method) && \"Use AddOverloadCandidate for constructors\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6557, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isa<CXXConstructorDecl>(Method) &&
6557 (0) . __assert_fail ("!isa(Method) && \"Use AddOverloadCandidate for constructors\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6557, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Use AddOverloadCandidate for constructors");
6558
6559  if (!CandidateSet.isNewCandidate(Method))
6560    return;
6561
6562  // C++11 [class.copy]p23: [DR1402]
6563  //   A defaulted move assignment operator that is defined as deleted is
6564  //   ignored by overload resolution.
6565  if (Method->isDefaulted() && Method->isDeleted() &&
6566      Method->isMoveAssignmentOperator())
6567    return;
6568
6569  // Overload resolution is always an unevaluated context.
6570  EnterExpressionEvaluationContext Unevaluated(
6571      *thisSema::ExpressionEvaluationContext::Unevaluated);
6572
6573  // Add this candidate
6574  OverloadCandidate &Candidate =
6575      CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6576  Candidate.FoundDecl = FoundDecl;
6577  Candidate.Function = Method;
6578  Candidate.IsSurrogate = false;
6579  Candidate.IgnoreObjectArgument = false;
6580  Candidate.ExplicitCallArguments = Args.size();
6581
6582  unsigned NumParams = Proto->getNumParams();
6583
6584  // (C++ 13.3.2p2): A candidate function having fewer than m
6585  // parameters is viable only if it has an ellipsis in its parameter
6586  // list (8.3.5).
6587  if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6588      !Proto->isVariadic()) {
6589    Candidate.Viable = false;
6590    Candidate.FailureKind = ovl_fail_too_many_arguments;
6591    return;
6592  }
6593
6594  // (C++ 13.3.2p2): A candidate function having more than m parameters
6595  // is viable only if the (m+1)st parameter has a default argument
6596  // (8.3.6). For the purposes of overload resolution, the
6597  // parameter list is truncated on the right, so that there are
6598  // exactly m parameters.
6599  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6600  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6601    // Not enough arguments.
6602    Candidate.Viable = false;
6603    Candidate.FailureKind = ovl_fail_too_few_arguments;
6604    return;
6605  }
6606
6607  Candidate.Viable = true;
6608
6609  if (Method->isStatic() || ObjectType.isNull())
6610    // The implicit object argument is ignored.
6611    Candidate.IgnoreObjectArgument = true;
6612  else {
6613    // Determine the implicit conversion sequence for the object
6614    // parameter.
6615    Candidate.Conversions[0] = TryObjectArgumentInitialization(
6616        *thisCandidateSet.getLocation(), ObjectTypeObjectClassification,
6617        MethodActingContext);
6618    if (Candidate.Conversions[0].isBad()) {
6619      Candidate.Viable = false;
6620      Candidate.FailureKind = ovl_fail_bad_conversion;
6621      return;
6622    }
6623  }
6624
6625  // (CUDA B.1): Check for invalid calls between targets.
6626  if (getLangOpts().CUDA)
6627    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6628      if (!IsAllowedCUDACall(CallerMethod)) {
6629        Candidate.Viable = false;
6630        Candidate.FailureKind = ovl_fail_bad_target;
6631        return;
6632      }
6633
6634  // Determine the implicit conversion sequences for each of the
6635  // arguments.
6636  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6637    if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6638      // We already formed a conversion sequence for this parameter during
6639      // template argument deduction.
6640    } else if (ArgIdx < NumParams) {
6641      // (C++ 13.3.2p3): for F to be a viable function, there shall
6642      // exist for each argument an implicit conversion sequence
6643      // (13.3.3.1) that converts that argument to the corresponding
6644      // parameter of F.
6645      QualType ParamType = Proto->getParamType(ArgIdx);
6646      Candidate.Conversions[ArgIdx + 1]
6647        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6648                                SuppressUserConversions,
6649                                /*InOverloadResolution=*/true,
6650                                /*AllowObjCWritebackConversion=*/
6651                                  getLangOpts().ObjCAutoRefCount);
6652      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6653        Candidate.Viable = false;
6654        Candidate.FailureKind = ovl_fail_bad_conversion;
6655        return;
6656      }
6657    } else {
6658      // (C++ 13.3.2p2): For the purposes of overload resolution, any
6659      // argument for which there is no corresponding parameter is
6660      // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6661      Candidate.Conversions[ArgIdx + 1].setEllipsis();
6662    }
6663  }
6664
6665  if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6666    Candidate.Viable = false;
6667    Candidate.FailureKind = ovl_fail_enable_if;
6668    Candidate.DeductionFailure.Data = FailedAttr;
6669    return;
6670  }
6671
6672  if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6673      !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6674    Candidate.Viable = false;
6675    Candidate.FailureKind = ovl_non_default_multiversion_function;
6676  }
6677}
6678
6679/// Add a C++ member function template as a candidate to the candidate
6680/// set, using template argument deduction to produce an appropriate member
6681/// function template specialization.
6682void
6683Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6684                                 DeclAccessPair FoundDecl,
6685                                 CXXRecordDecl *ActingContext,
6686                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
6687                                 QualType ObjectType,
6688                                 Expr::Classification ObjectClassification,
6689                                 ArrayRef<Expr *> Args,
6690                                 OverloadCandidateSetCandidateSet,
6691                                 bool SuppressUserConversions,
6692                                 bool PartialOverloading) {
6693  if (!CandidateSet.isNewCandidate(MethodTmpl))
6694    return;
6695
6696  // C++ [over.match.funcs]p7:
6697  //   In each case where a candidate is a function template, candidate
6698  //   function template specializations are generated using template argument
6699  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6700  //   candidate functions in the usual way.113) A given name can refer to one
6701  //   or more function templates and also to a set of overloaded non-template
6702  //   functions. In such a case, the candidate functions generated from each
6703  //   function template are combined with the set of non-template candidate
6704  //   functions.
6705  TemplateDeductionInfo Info(CandidateSet.getLocation());
6706  FunctionDecl *Specialization = nullptr;
6707  ConversionSequenceList Conversions;
6708  if (TemplateDeductionResult Result = DeduceTemplateArguments(
6709          MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6710          PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6711            return CheckNonDependentConversions(
6712                MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6713                SuppressUserConversions, ActingContext, ObjectType,
6714                ObjectClassification);
6715          })) {
6716    OverloadCandidate &Candidate =
6717        CandidateSet.addCandidate(Conversions.size(), Conversions);
6718    Candidate.FoundDecl = FoundDecl;
6719    Candidate.Function = MethodTmpl->getTemplatedDecl();
6720    Candidate.Viable = false;
6721    Candidate.IsSurrogate = false;
6722    Candidate.IgnoreObjectArgument =
6723        cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6724        ObjectType.isNull();
6725    Candidate.ExplicitCallArguments = Args.size();
6726    if (Result == TDK_NonDependentConversionFailure)
6727      Candidate.FailureKind = ovl_fail_bad_conversion;
6728    else {
6729      Candidate.FailureKind = ovl_fail_bad_deduction;
6730      Candidate.DeductionFailure = MakeDeductionFailureInfo(ContextResult,
6731                                                            Info);
6732    }
6733    return;
6734  }
6735
6736  // Add the function template specialization produced by template argument
6737  // deduction as a candidate.
6738   (0) . __assert_fail ("Specialization && \"Missing member function template specialization?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6738, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Specialization && "Missing member function template specialization?");
6739   (0) . __assert_fail ("isa(Specialization) && \"Specialization is not a member function?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6740, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<CXXMethodDecl>(Specialization) &&
6740 (0) . __assert_fail ("isa(Specialization) && \"Specialization is not a member function?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6740, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Specialization is not a member function?");
6741  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6742                     ActingContext, ObjectType, ObjectClassification, Args,
6743                     CandidateSet, SuppressUserConversions, PartialOverloading,
6744                     Conversions);
6745}
6746
6747/// Add a C++ function template specialization as a candidate
6748/// in the candidate set, using template argument deduction to produce
6749/// an appropriate function template specialization.
6750void Sema::AddTemplateOverloadCandidate(
6751    FunctionTemplateDecl *FunctionTemplateDeclAccessPair FoundDecl,
6752    TemplateArgumentListInfo *ExplicitTemplateArgsArrayRef<Expr *> Args,
6753    OverloadCandidateSet &CandidateSetbool SuppressUserConversions,
6754    bool PartialOverloadingADLCallKind IsADLCandidate) {
6755  if (!CandidateSet.isNewCandidate(FunctionTemplate))
6756    return;
6757
6758  // C++ [over.match.funcs]p7:
6759  //   In each case where a candidate is a function template, candidate
6760  //   function template specializations are generated using template argument
6761  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6762  //   candidate functions in the usual way.113) A given name can refer to one
6763  //   or more function templates and also to a set of overloaded non-template
6764  //   functions. In such a case, the candidate functions generated from each
6765  //   function template are combined with the set of non-template candidate
6766  //   functions.
6767  TemplateDeductionInfo Info(CandidateSet.getLocation());
6768  FunctionDecl *Specialization = nullptr;
6769  ConversionSequenceList Conversions;
6770  if (TemplateDeductionResult Result = DeduceTemplateArguments(
6771          FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6772          PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6773            return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6774                                                Args, CandidateSet, Conversions,
6775                                                SuppressUserConversions);
6776          })) {
6777    OverloadCandidate &Candidate =
6778        CandidateSet.addCandidate(Conversions.size(), Conversions);
6779    Candidate.FoundDecl = FoundDecl;
6780    Candidate.Function = FunctionTemplate->getTemplatedDecl();
6781    Candidate.Viable = false;
6782    Candidate.IsSurrogate = false;
6783    Candidate.IsADLCandidate = IsADLCandidate;
6784    // Ignore the object argument if there is one, since we don't have an object
6785    // type.
6786    Candidate.IgnoreObjectArgument =
6787        isa<CXXMethodDecl>(Candidate.Function) &&
6788        !isa<CXXConstructorDecl>(Candidate.Function);
6789    Candidate.ExplicitCallArguments = Args.size();
6790    if (Result == TDK_NonDependentConversionFailure)
6791      Candidate.FailureKind = ovl_fail_bad_conversion;
6792    else {
6793      Candidate.FailureKind = ovl_fail_bad_deduction;
6794      Candidate.DeductionFailure = MakeDeductionFailureInfo(ContextResult,
6795                                                            Info);
6796    }
6797    return;
6798  }
6799
6800  // Add the function template specialization produced by template argument
6801  // deduction as a candidate.
6802   (0) . __assert_fail ("Specialization && \"Missing function template specialization?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6802, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Specialization && "Missing function template specialization?");
6803  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6804                       SuppressUserConversions, PartialOverloading,
6805                       /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6806}
6807
6808/// Check that implicit conversion sequences can be formed for each argument
6809/// whose corresponding parameter has a non-dependent type, per DR1391's
6810/// [temp.deduct.call]p10.
6811bool Sema::CheckNonDependentConversions(
6812    FunctionTemplateDecl *FunctionTemplateArrayRef<QualTypeParamTypes,
6813    ArrayRef<Expr *> ArgsOverloadCandidateSet &CandidateSet,
6814    ConversionSequenceList &Conversionsbool SuppressUserConversions,
6815    CXXRecordDecl *ActingContextQualType ObjectType,
6816    Expr::Classification ObjectClassification) {
6817  // FIXME: The cases in which we allow explicit conversions for constructor
6818  // arguments never consider calling a constructor template. It's not clear
6819  // that is correct.
6820  const bool AllowExplicit = false;
6821
6822  auto *FD = FunctionTemplate->getTemplatedDecl();
6823  auto *Method = dyn_cast<CXXMethodDecl>(FD);
6824  bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6825  unsigned ThisConversions = HasThisConversion ? 1 : 0;
6826
6827  Conversions =
6828      CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6829
6830  // Overload resolution is always an unevaluated context.
6831  EnterExpressionEvaluationContext Unevaluated(
6832      *thisSema::ExpressionEvaluationContext::Unevaluated);
6833
6834  // For a method call, check the 'this' conversion here too. DR1391 doesn't
6835  // require that, but this check should never result in a hard error, and
6836  // overload resolution is permitted to sidestep instantiations.
6837  if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6838      !ObjectType.isNull()) {
6839    Conversions[0] = TryObjectArgumentInitialization(
6840        *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6841        Method, ActingContext);
6842    if (Conversions[0].isBad())
6843      return true;
6844  }
6845
6846  for (unsigned I = 0N = std::min(ParamTypes.size(), Args.size()); I != N;
6847       ++I) {
6848    QualType ParamType = ParamTypes[I];
6849    if (!ParamType->isDependentType()) {
6850      Conversions[ThisConversions + I]
6851        = TryCopyInitialization(*this, Args[I], ParamType,
6852                                SuppressUserConversions,
6853                                /*InOverloadResolution=*/true,
6854                                /*AllowObjCWritebackConversion=*/
6855                                  getLangOpts().ObjCAutoRefCount,
6856                                AllowExplicit);
6857      if (Conversions[ThisConversions + I].isBad())
6858        return true;
6859    }
6860  }
6861
6862  return false;
6863}
6864
6865/// Determine whether this is an allowable conversion from the result
6866/// of an explicit conversion operator to the expected type, per C++
6867/// [over.match.conv]p1 and [over.match.ref]p1.
6868///
6869/// \param ConvType The return type of the conversion function.
6870///
6871/// \param ToType The type we are converting to.
6872///
6873/// \param AllowObjCPointerConversion Allow a conversion from one
6874/// Objective-C pointer to another.
6875///
6876/// \returns true if the conversion is allowable, false otherwise.
6877static bool isAllowableExplicitConversion(Sema &S,
6878                                          QualType ConvTypeQualType ToType,
6879                                          bool AllowObjCPointerConversion) {
6880  QualType ToNonRefType = ToType.getNonReferenceType();
6881
6882  // Easy case: the types are the same.
6883  if (S.Context.hasSameUnqualifiedType(ConvTypeToNonRefType))
6884    return true;
6885
6886  // Allow qualification conversions.
6887  bool ObjCLifetimeConversion;
6888  if (S.IsQualificationConversion(ConvTypeToNonRefType/*CStyle*/false,
6889                                  ObjCLifetimeConversion))
6890    return true;
6891
6892  // If we're not allowed to consider Objective-C pointer conversions,
6893  // we're done.
6894  if (!AllowObjCPointerConversion)
6895    return false;
6896
6897  // Is this an Objective-C pointer conversion?
6898  bool IncompatibleObjC = false;
6899  QualType ConvertedType;
6900  return S.isObjCPointerConversion(ConvTypeToNonRefTypeConvertedType,
6901                                   IncompatibleObjC);
6902}
6903
6904/// AddConversionCandidate - Add a C++ conversion function as a
6905/// candidate in the candidate set (C++ [over.match.conv],
6906/// C++ [over.match.copy]). From is the expression we're converting from,
6907/// and ToType is the type that we're eventually trying to convert to
6908/// (which may or may not be the same type as the type that the
6909/// conversion function produces).
6910void
6911Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6912                             DeclAccessPair FoundDecl,
6913                             CXXRecordDecl *ActingContext,
6914                             Expr *FromQualType ToType,
6915                             OverloadCandidateSetCandidateSet,
6916                             bool AllowObjCConversionOnExplicit,
6917                             bool AllowResultConversion) {
6918   (0) . __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6919, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Conversion->getDescribedFunctionTemplate() &&
6919 (0) . __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 6919, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Conversion function templates use AddTemplateConversionCandidate");
6920  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6921  if (!CandidateSet.isNewCandidate(Conversion))
6922    return;
6923
6924  // If the conversion function has an undeduced return type, trigger its
6925  // deduction now.
6926  if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6927    if (DeduceReturnType(ConversionFrom->getExprLoc()))
6928      return;
6929    ConvType = Conversion->getConversionType().getNonReferenceType();
6930  }
6931
6932  // If we don't allow any conversion of the result type, ignore conversion
6933  // functions that don't convert to exactly (possibly cv-qualified) T.
6934  if (!AllowResultConversion &&
6935      !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6936    return;
6937
6938  // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6939  // operator is only a candidate if its return type is the target type or
6940  // can be converted to the target type with a qualification conversion.
6941  if (Conversion->isExplicit() &&
6942      !isAllowableExplicitConversion(*thisConvTypeToType,
6943                                     AllowObjCConversionOnExplicit))
6944    return;
6945
6946  // Overload resolution is always an unevaluated context.
6947  EnterExpressionEvaluationContext Unevaluated(
6948      *thisSema::ExpressionEvaluationContext::Unevaluated);
6949
6950  // Add this candidate
6951  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6952  Candidate.FoundDecl = FoundDecl;
6953  Candidate.Function = Conversion;
6954  Candidate.IsSurrogate = false;
6955  Candidate.IgnoreObjectArgument = false;
6956  Candidate.FinalConversion.setAsIdentityConversion();
6957  Candidate.FinalConversion.setFromType(ConvType);
6958  Candidate.FinalConversion.setAllToTypes(ToType);
6959  Candidate.Viable = true;
6960  Candidate.ExplicitCallArguments = 1;
6961
6962  // C++ [over.match.funcs]p4:
6963  //   For conversion functions, the function is considered to be a member of
6964  //   the class of the implicit implied object argument for the purpose of
6965  //   defining the type of the implicit object parameter.
6966  //
6967  // Determine the implicit conversion sequence for the implicit
6968  // object parameter.
6969  QualType ImplicitParamType = From->getType();
6970  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6971    ImplicitParamType = FromPtrType->getPointeeType();
6972  CXXRecordDecl *ConversionContext
6973    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6974
6975  Candidate.Conversions[0] = TryObjectArgumentInitialization(
6976      *thisCandidateSet.getLocation(), From->getType(),
6977      From->Classify(Context), ConversionConversionContext);
6978
6979  if (Candidate.Conversions[0].isBad()) {
6980    Candidate.Viable = false;
6981    Candidate.FailureKind = ovl_fail_bad_conversion;
6982    return;
6983  }
6984
6985  // We won't go through a user-defined type conversion function to convert a
6986  // derived to base as such conversions are given Conversion Rank. They only
6987  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6988  QualType FromCanon
6989    = Context.getCanonicalType(From->getType().getUnqualifiedType());
6990  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6991  if (FromCanon == ToCanon ||
6992      IsDerivedFrom(CandidateSet.getLocation(), FromCanonToCanon)) {
6993    Candidate.Viable = false;
6994    Candidate.FailureKind = ovl_fail_trivial_conversion;
6995    return;
6996  }
6997
6998  // To determine what the conversion from the result of calling the
6999  // conversion function to the type we're eventually trying to
7000  // convert to (ToType), we need to synthesize a call to the
7001  // conversion function and attempt copy initialization from it. This
7002  // makes sure that we get the right semantics with respect to
7003  // lvalues/rvalues and the type. Fortunately, we can allocate this
7004  // call on the stack and we don't need its arguments to be
7005  // well-formed.
7006  DeclRefExpr ConversionRef(ContextConversionfalseConversion->getType(),
7007                            VK_LValueFrom->getBeginLoc());
7008  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7009                                Context.getPointerType(Conversion->getType()),
7010                                CK_FunctionToPointerDecay,
7011                                &ConversionRefVK_RValue);
7012
7013  QualType ConversionType = Conversion->getConversionType();
7014  if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7015    Candidate.Viable = false;
7016    Candidate.FailureKind = ovl_fail_bad_final_conversion;
7017    return;
7018  }
7019
7020  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7021
7022  // Note that it is safe to allocate CallExpr on the stack here because
7023  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7024  // allocator).
7025  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7026
7027  llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7028      Buffer;
7029  CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7030      Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7031
7032  ImplicitConversionSequence ICS =
7033      TryCopyInitialization(*thisTheTemporaryCallToType,
7034                            /*SuppressUserConversions=*/true,
7035                            /*InOverloadResolution=*/false,
7036                            /*AllowObjCWritebackConversion=*/false);
7037
7038  switch (ICS.getKind()) {
7039  case ImplicitConversionSequence::StandardConversion:
7040    Candidate.FinalConversion = ICS.Standard;
7041
7042    // C++ [over.ics.user]p3:
7043    //   If the user-defined conversion is specified by a specialization of a
7044    //   conversion function template, the second standard conversion sequence
7045    //   shall have exact match rank.
7046    if (Conversion->getPrimaryTemplate() &&
7047        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7048      Candidate.Viable = false;
7049      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7050      return;
7051    }
7052
7053    // C++0x [dcl.init.ref]p5:
7054    //    In the second case, if the reference is an rvalue reference and
7055    //    the second standard conversion sequence of the user-defined
7056    //    conversion sequence includes an lvalue-to-rvalue conversion, the
7057    //    program is ill-formed.
7058    if (ToType->isRValueReferenceType() &&
7059        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7060      Candidate.Viable = false;
7061      Candidate.FailureKind = ovl_fail_bad_final_conversion;
7062      return;
7063    }
7064    break;
7065
7066  case ImplicitConversionSequence::BadConversion:
7067    Candidate.Viable = false;
7068    Candidate.FailureKind = ovl_fail_bad_final_conversion;
7069    return;
7070
7071  default:
7072    llvm_unreachable(
7073           "Can only end up with a standard conversion sequence or failure");
7074  }
7075
7076  if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7077    Candidate.Viable = false;
7078    Candidate.FailureKind = ovl_fail_enable_if;
7079    Candidate.DeductionFailure.Data = FailedAttr;
7080    return;
7081  }
7082
7083  if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7084      !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7085    Candidate.Viable = false;
7086    Candidate.FailureKind = ovl_non_default_multiversion_function;
7087  }
7088}
7089
7090/// Adds a conversion function template specialization
7091/// candidate to the overload set, using template argument deduction
7092/// to deduce the template arguments of the conversion function
7093/// template from the type that we are converting to (C++
7094/// [temp.deduct.conv]).
7095void
7096Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7097                                     DeclAccessPair FoundDecl,
7098                                     CXXRecordDecl *ActingDC,
7099                                     Expr *FromQualType ToType,
7100                                     OverloadCandidateSet &CandidateSet,
7101                                     bool AllowObjCConversionOnExplicit,
7102                                     bool AllowResultConversion) {
7103   (0) . __assert_fail ("isa(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7104, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7104 (0) . __assert_fail ("isa(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7104, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Only conversion function templates permitted here");
7105
7106  if (!CandidateSet.isNewCandidate(FunctionTemplate))
7107    return;
7108
7109  TemplateDeductionInfo Info(CandidateSet.getLocation());
7110  CXXConversionDecl *Specialization = nullptr;
7111  if (TemplateDeductionResult Result
7112        = DeduceTemplateArguments(FunctionTemplateToType,
7113                                  SpecializationInfo)) {
7114    OverloadCandidate &Candidate = CandidateSet.addCandidate();
7115    Candidate.FoundDecl = FoundDecl;
7116    Candidate.Function = FunctionTemplate->getTemplatedDecl();
7117    Candidate.Viable = false;
7118    Candidate.FailureKind = ovl_fail_bad_deduction;
7119    Candidate.IsSurrogate = false;
7120    Candidate.IgnoreObjectArgument = false;
7121    Candidate.ExplicitCallArguments = 1;
7122    Candidate.DeductionFailure = MakeDeductionFailureInfo(ContextResult,
7123                                                          Info);
7124    return;
7125  }
7126
7127  // Add the conversion function template specialization produced by
7128  // template argument deduction as a candidate.
7129   (0) . __assert_fail ("Specialization && \"Missing function template specialization?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7129, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Specialization && "Missing function template specialization?");
7130  AddConversionCandidate(SpecializationFoundDeclActingDCFromToType,
7131                         CandidateSetAllowObjCConversionOnExplicit,
7132                         AllowResultConversion);
7133}
7134
7135/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7136/// converts the given @c Object to a function pointer via the
7137/// conversion function @c Conversion, and then attempts to call it
7138/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7139/// the type of function that we'll eventually be calling.
7140void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7141                                 DeclAccessPair FoundDecl,
7142                                 CXXRecordDecl *ActingContext,
7143                                 const FunctionProtoType *Proto,
7144                                 Expr *Object,
7145                                 ArrayRef<Expr *> Args,
7146                                 OverloadCandidateSetCandidateSet) {
7147  if (!CandidateSet.isNewCandidate(Conversion))
7148    return;
7149
7150  // Overload resolution is always an unevaluated context.
7151  EnterExpressionEvaluationContext Unevaluated(
7152      *thisSema::ExpressionEvaluationContext::Unevaluated);
7153
7154  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7155  Candidate.FoundDecl = FoundDecl;
7156  Candidate.Function = nullptr;
7157  Candidate.Surrogate = Conversion;
7158  Candidate.Viable = true;
7159  Candidate.IsSurrogate = true;
7160  Candidate.IgnoreObjectArgument = false;
7161  Candidate.ExplicitCallArguments = Args.size();
7162
7163  // Determine the implicit conversion sequence for the implicit
7164  // object parameter.
7165  ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7166      *thisCandidateSet.getLocation(), Object->getType(),
7167      Object->Classify(Context), ConversionActingContext);
7168  if (ObjectInit.isBad()) {
7169    Candidate.Viable = false;
7170    Candidate.FailureKind = ovl_fail_bad_conversion;
7171    Candidate.Conversions[0] = ObjectInit;
7172    return;
7173  }
7174
7175  // The first conversion is actually a user-defined conversion whose
7176  // first conversion is ObjectInit's standard conversion (which is
7177  // effectively a reference binding). Record it as such.
7178  Candidate.Conversions[0].setUserDefined();
7179  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7180  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7181  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7182  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7183  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7184  Candidate.Conversions[0].UserDefined.After
7185    = Candidate.Conversions[0].UserDefined.Before;
7186  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7187
7188  // Find the
7189  unsigned NumParams = Proto->getNumParams();
7190
7191  // (C++ 13.3.2p2): A candidate function having fewer than m
7192  // parameters is viable only if it has an ellipsis in its parameter
7193  // list (8.3.5).
7194  if (Args.size() > NumParams && !Proto->isVariadic()) {
7195    Candidate.Viable = false;
7196    Candidate.FailureKind = ovl_fail_too_many_arguments;
7197    return;
7198  }
7199
7200  // Function types don't have any default arguments, so just check if
7201  // we have enough arguments.
7202  if (Args.size() < NumParams) {
7203    // Not enough arguments.
7204    Candidate.Viable = false;
7205    Candidate.FailureKind = ovl_fail_too_few_arguments;
7206    return;
7207  }
7208
7209  // Determine the implicit conversion sequences for each of the
7210  // arguments.
7211  for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
7212    if (ArgIdx < NumParams) {
7213      // (C++ 13.3.2p3): for F to be a viable function, there shall
7214      // exist for each argument an implicit conversion sequence
7215      // (13.3.3.1) that converts that argument to the corresponding
7216      // parameter of F.
7217      QualType ParamType = Proto->getParamType(ArgIdx);
7218      Candidate.Conversions[ArgIdx + 1]
7219        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7220                                /*SuppressUserConversions=*/false,
7221                                /*InOverloadResolution=*/false,
7222                                /*AllowObjCWritebackConversion=*/
7223                                  getLangOpts().ObjCAutoRefCount);
7224      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7225        Candidate.Viable = false;
7226        Candidate.FailureKind = ovl_fail_bad_conversion;
7227        return;
7228      }
7229    } else {
7230      // (C++ 13.3.2p2): For the purposes of overload resolution, any
7231      // argument for which there is no corresponding parameter is
7232      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7233      Candidate.Conversions[ArgIdx + 1].setEllipsis();
7234    }
7235  }
7236
7237  if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7238    Candidate.Viable = false;
7239    Candidate.FailureKind = ovl_fail_enable_if;
7240    Candidate.DeductionFailure.Data = FailedAttr;
7241    return;
7242  }
7243}
7244
7245/// Add overload candidates for overloaded operators that are
7246/// member functions.
7247///
7248/// Add the overloaded operator candidates that are member functions
7249/// for the operator Op that was used in an operator expression such
7250/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7251/// CandidateSet will store the added overload candidates. (C++
7252/// [over.match.oper]).
7253void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7254                                       SourceLocation OpLoc,
7255                                       ArrayRef<Expr *> Args,
7256                                       OverloadCandidateSetCandidateSet,
7257                                       SourceRange OpRange) {
7258  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7259
7260  // C++ [over.match.oper]p3:
7261  //   For a unary operator @ with an operand of a type whose
7262  //   cv-unqualified version is T1, and for a binary operator @ with
7263  //   a left operand of a type whose cv-unqualified version is T1 and
7264  //   a right operand of a type whose cv-unqualified version is T2,
7265  //   three sets of candidate functions, designated member
7266  //   candidates, non-member candidates and built-in candidates, are
7267  //   constructed as follows:
7268  QualType T1 = Args[0]->getType();
7269
7270  //     -- If T1 is a complete class type or a class currently being
7271  //        defined, the set of member candidates is the result of the
7272  //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7273  //        the set of member candidates is empty.
7274  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7275    // Complete the type if it can be completed.
7276    if (!isCompleteType(OpLocT1) && !T1Rec->isBeingDefined())
7277      return;
7278    // If the type is neither complete nor being defined, bail out now.
7279    if (!T1Rec->getDecl()->getDefinition())
7280      return;
7281
7282    LookupResult Operators(*thisOpNameOpLocLookupOrdinaryName);
7283    LookupQualifiedName(OperatorsT1Rec->getDecl());
7284    Operators.suppressDiagnostics();
7285
7286    for (LookupResult::iterator Oper = Operators.begin(),
7287                             OperEnd = Operators.end();
7288         Oper != OperEnd;
7289         ++Oper)
7290      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7291                         Args[0]->Classify(Context), Args.slice(1),
7292                         CandidateSet, /*SuppressUserConversions=*/false);
7293  }
7294}
7295
7296/// AddBuiltinCandidate - Add a candidate for a built-in
7297/// operator. ResultTy and ParamTys are the result and parameter types
7298/// of the built-in candidate, respectively. Args and NumArgs are the
7299/// arguments being passed to the candidate. IsAssignmentOperator
7300/// should be true when this built-in candidate is an assignment
7301/// operator. NumContextualBoolArguments is the number of arguments
7302/// (at the beginning of the argument list) that will be contextually
7303/// converted to bool.
7304void Sema::AddBuiltinCandidate(QualType *ParamTysArrayRef<Expr *> Args,
7305                               OverloadCandidateSetCandidateSet,
7306                               bool IsAssignmentOperator,
7307                               unsigned NumContextualBoolArguments) {
7308  // Overload resolution is always an unevaluated context.
7309  EnterExpressionEvaluationContext Unevaluated(
7310      *thisSema::ExpressionEvaluationContext::Unevaluated);
7311
7312  // Add this candidate
7313  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7314  Candidate.FoundDecl = DeclAccessPair::make(nullptrAS_none);
7315  Candidate.Function = nullptr;
7316  Candidate.IsSurrogate = false;
7317  Candidate.IgnoreObjectArgument = false;
7318  std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7319
7320  // Determine the implicit conversion sequences for each of the
7321  // arguments.
7322  Candidate.Viable = true;
7323  Candidate.ExplicitCallArguments = Args.size();
7324  for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
7325    // C++ [over.match.oper]p4:
7326    //   For the built-in assignment operators, conversions of the
7327    //   left operand are restricted as follows:
7328    //     -- no temporaries are introduced to hold the left operand, and
7329    //     -- no user-defined conversions are applied to the left
7330    //        operand to achieve a type match with the left-most
7331    //        parameter of a built-in candidate.
7332    //
7333    // We block these conversions by turning off user-defined
7334    // conversions, since that is the only way that initialization of
7335    // a reference to a non-class type can occur from something that
7336    // is not of the same type.
7337    if (ArgIdx < NumContextualBoolArguments) {
7338       (0) . __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7339, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ParamTys[ArgIdx] == Context.BoolTy &&
7339 (0) . __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7339, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "Contextual conversion to bool requires bool type");
7340      Candidate.Conversions[ArgIdx]
7341        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7342    } else {
7343      Candidate.Conversions[ArgIdx]
7344        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7345                                ArgIdx == 0 && IsAssignmentOperator,
7346                                /*InOverloadResolution=*/false,
7347                                /*AllowObjCWritebackConversion=*/
7348                                  getLangOpts().ObjCAutoRefCount);
7349    }
7350    if (Candidate.Conversions[ArgIdx].isBad()) {
7351      Candidate.Viable = false;
7352      Candidate.FailureKind = ovl_fail_bad_conversion;
7353      break;
7354    }
7355  }
7356}
7357
7358namespace {
7359
7360/// BuiltinCandidateTypeSet - A set of types that will be used for the
7361/// candidate operator functions for built-in operators (C++
7362/// [over.built]). The types are separated into pointer types and
7363/// enumeration types.
7364class BuiltinCandidateTypeSet  {
7365  /// TypeSet - A set of types.
7366  typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7367                          llvm::SmallPtrSet<QualType, 8>> TypeSet;
7368
7369  /// PointerTypes - The set of pointer types that will be used in the
7370  /// built-in candidates.
7371  TypeSet PointerTypes;
7372
7373  /// MemberPointerTypes - The set of member pointer types that will be
7374  /// used in the built-in candidates.
7375  TypeSet MemberPointerTypes;
7376
7377  /// EnumerationTypes - The set of enumeration types that will be
7378  /// used in the built-in candidates.
7379  TypeSet EnumerationTypes;
7380
7381  /// The set of vector types that will be used in the built-in
7382  /// candidates.
7383  TypeSet VectorTypes;
7384
7385  /// A flag indicating non-record types are viable candidates
7386  bool HasNonRecordTypes;
7387
7388  /// A flag indicating whether either arithmetic or enumeration types
7389  /// were present in the candidate set.
7390  bool HasArithmeticOrEnumeralTypes;
7391
7392  /// A flag indicating whether the nullptr type was present in the
7393  /// candidate set.
7394  bool HasNullPtrType;
7395
7396  /// Sema - The semantic analysis instance where we are building the
7397  /// candidate type set.
7398  Sema &SemaRef;
7399
7400  /// Context - The AST context in which we will build the type sets.
7401  ASTContext &Context;
7402
7403  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7404                                               const Qualifiers &VisibleQuals);
7405  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7406
7407public:
7408  /// iterator - Iterates through the types that are part of the set.
7409  typedef TypeSet::iterator iterator;
7410
7411  BuiltinCandidateTypeSet(Sema &SemaRef)
7412    : HasNonRecordTypes(false),
7413      HasArithmeticOrEnumeralTypes(false),
7414      HasNullPtrType(false),
7415      SemaRef(SemaRef),
7416      Context(SemaRef.Context) { }
7417
7418  void AddTypesConvertedFrom(QualType Ty,
7419                             SourceLocation Loc,
7420                             bool AllowUserConversions,
7421                             bool AllowExplicitConversions,
7422                             const Qualifiers &VisibleTypeConversionsQuals);
7423
7424  /// pointer_begin - First pointer type found;
7425  iterator pointer_begin() { return PointerTypes.begin(); }
7426
7427  /// pointer_end - Past the last pointer type found;
7428  iterator pointer_end() { return PointerTypes.end(); }
7429
7430  /// member_pointer_begin - First member pointer type found;
7431  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7432
7433  /// member_pointer_end - Past the last member pointer type found;
7434  iterator member_pointer_end() { return MemberPointerTypes.end(); }
7435
7436  /// enumeration_begin - First enumeration type found;
7437  iterator enumeration_begin() { return EnumerationTypes.begin(); }
7438
7439  /// enumeration_end - Past the last enumeration type found;
7440  iterator enumeration_end() { return EnumerationTypes.end(); }
7441
7442  iterator vector_begin() { return VectorTypes.begin(); }
7443  iterator vector_end() { return VectorTypes.end(); }
7444
7445  bool hasNonRecordTypes() { return HasNonRecordTypes; }
7446  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7447  bool hasNullPtrType() const { return HasNullPtrType; }
7448};
7449
7450// end anonymous namespace
7451
7452/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7453/// the set of pointer types along with any more-qualified variants of
7454/// that type. For example, if @p Ty is "int const *", this routine
7455/// will add "int const *", "int const volatile *", "int const
7456/// restrict *", and "int const volatile restrict *" to the set of
7457/// pointer types. Returns true if the add of @p Ty itself succeeded,
7458/// false otherwise.
7459///
7460/// FIXME: what to do about extended qualifiers?
7461bool
7462BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7463                                             const Qualifiers &VisibleQuals) {
7464
7465  // Insert this type.
7466  if (!PointerTypes.insert(Ty))
7467    return false;
7468
7469  QualType PointeeTy;
7470  const PointerType *PointerTy = Ty->getAs<PointerType>();
7471  bool buildObjCPtr = false;
7472  if (!PointerTy) {
7473    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7474    PointeeTy = PTy->getPointeeType();
7475    buildObjCPtr = true;
7476  } else {
7477    PointeeTy = PointerTy->getPointeeType();
7478  }
7479
7480  // Don't add qualified variants of arrays. For one, they're not allowed
7481  // (the qualifier would sink to the element type), and for another, the
7482  // only overload situation where it matters is subscript or pointer +- int,
7483  // and those shouldn't have qualifier variants anyway.
7484  if (PointeeTy->isArrayType())
7485    return true;
7486
7487  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7488  bool hasVolatile = VisibleQuals.hasVolatile();
7489  bool hasRestrict = VisibleQuals.hasRestrict();
7490
7491  // Iterate through all strict supersets of BaseCVR.
7492  for (unsigned CVR = BaseCVR+1CVR <= Qualifiers::CVRMask; ++CVR) {
7493    if ((CVR | BaseCVR) != CVRcontinue;
7494    // Skip over volatile if no volatile found anywhere in the types.
7495    if ((CVR & Qualifiers::Volatile) && !hasVolatilecontinue;
7496
7497    // Skip over restrict if no restrict found anywhere in the types, or if
7498    // the type cannot be restrict-qualified.
7499    if ((CVR & Qualifiers::Restrict) &&
7500        (!hasRestrict ||
7501         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7502      continue;
7503
7504    // Build qualified pointee type.
7505    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTyCVR);
7506
7507    // Build qualified pointer type.
7508    QualType QPointerTy;
7509    if (!buildObjCPtr)
7510      QPointerTy = Context.getPointerType(QPointeeTy);
7511    else
7512      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7513
7514    // Insert qualified pointer type.
7515    PointerTypes.insert(QPointerTy);
7516  }
7517
7518  return true;
7519}
7520
7521/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7522/// to the set of pointer types along with any more-qualified variants of
7523/// that type. For example, if @p Ty is "int const *", this routine
7524/// will add "int const *", "int const volatile *", "int const
7525/// restrict *", and "int const volatile restrict *" to the set of
7526/// pointer types. Returns true if the add of @p Ty itself succeeded,
7527/// false otherwise.
7528///
7529/// FIXME: what to do about extended qualifiers?
7530bool
7531BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7532    QualType Ty) {
7533  // Insert this type.
7534  if (!MemberPointerTypes.insert(Ty))
7535    return false;
7536
7537  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7538   (0) . __assert_fail ("PointerTy && \"type was not a member pointer type!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7538, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(PointerTy && "type was not a member pointer type!");
7539
7540  QualType PointeeTy = PointerTy->getPointeeType();
7541  // Don't add qualified variants of arrays. For one, they're not allowed
7542  // (the qualifier would sink to the element type), and for another, the
7543  // only overload situation where it matters is subscript or pointer +- int,
7544  // and those shouldn't have qualifier variants anyway.
7545  if (PointeeTy->isArrayType())
7546    return true;
7547  const Type *ClassTy = PointerTy->getClass();
7548
7549  // Iterate through all strict supersets of the pointee type's CVR
7550  // qualifiers.
7551  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7552  for (unsigned CVR = BaseCVR+1CVR <= Qualifiers::CVRMask; ++CVR) {
7553    if ((CVR | BaseCVR) != CVRcontinue;
7554
7555    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTyCVR);
7556    MemberPointerTypes.insert(
7557      Context.getMemberPointerType(QPointeeTy, ClassTy));
7558  }
7559
7560  return true;
7561}
7562
7563/// AddTypesConvertedFrom - Add each of the types to which the type @p
7564/// Ty can be implicit converted to the given set of @p Types. We're
7565/// primarily interested in pointer types and enumeration types. We also
7566/// take member pointer types, for the conditional operator.
7567/// AllowUserConversions is true if we should look at the conversion
7568/// functions of a class type, and AllowExplicitConversions if we
7569/// should also include the explicit conversion functions of a class
7570/// type.
7571void
7572BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7573                                               SourceLocation Loc,
7574                                               bool AllowUserConversions,
7575                                               bool AllowExplicitConversions,
7576                                               const Qualifiers &VisibleQuals) {
7577  // Only deal with canonical types.
7578  Ty = Context.getCanonicalType(Ty);
7579
7580  // Look through reference types; they aren't part of the type of an
7581  // expression for the purposes of conversions.
7582  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7583    Ty = RefTy->getPointeeType();
7584
7585  // If we're dealing with an array type, decay to the pointer.
7586  if (Ty->isArrayType())
7587    Ty = SemaRef.Context.getArrayDecayedType(Ty);
7588
7589  // Otherwise, we don't care about qualifiers on the type.
7590  Ty = Ty.getLocalUnqualifiedType();
7591
7592  // Flag if we ever add a non-record type.
7593  const RecordType *TyRec = Ty->getAs<RecordType>();
7594  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7595
7596  // Flag if we encounter an arithmetic type.
7597  HasArithmeticOrEnumeralTypes =
7598    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7599
7600  if (Ty->isObjCIdType() || Ty->isObjCClassType())
7601    PointerTypes.insert(Ty);
7602  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7603    // Insert our type, and its more-qualified variants, into the set
7604    // of types.
7605    if (!AddPointerWithMoreQualifiedTypeVariants(TyVisibleQuals))
7606      return;
7607  } else if (Ty->isMemberPointerType()) {
7608    // Member pointers are far easier, since the pointee can't be converted.
7609    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7610      return;
7611  } else if (Ty->isEnumeralType()) {
7612    HasArithmeticOrEnumeralTypes = true;
7613    EnumerationTypes.insert(Ty);
7614  } else if (Ty->isVectorType()) {
7615    // We treat vector types as arithmetic types in many contexts as an
7616    // extension.
7617    HasArithmeticOrEnumeralTypes = true;
7618    VectorTypes.insert(Ty);
7619  } else if (Ty->isNullPtrType()) {
7620    HasNullPtrType = true;
7621  } else if (AllowUserConversions && TyRec) {
7622    // No conversion functions in incomplete types.
7623    if (!SemaRef.isCompleteType(LocTy))
7624      return;
7625
7626    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7627    for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7628      if (isa<UsingShadowDecl>(D))
7629        D = cast<UsingShadowDecl>(D)->getTargetDecl();
7630
7631      // Skip conversion function templates; they don't tell us anything
7632      // about which builtin types we can convert to.
7633      if (isa<FunctionTemplateDecl>(D))
7634        continue;
7635
7636      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7637      if (AllowExplicitConversions || !Conv->isExplicit()) {
7638        AddTypesConvertedFrom(Conv->getConversionType(), Loc, falsefalse,
7639                              VisibleQuals);
7640      }
7641    }
7642  }
7643}
7644/// Helper function for adjusting address spaces for the pointer or reference
7645/// operands of builtin operators depending on the argument.
7646static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &SQualType T,
7647                                                        Expr *Arg) {
7648  return S.Context.getAddrSpaceQualType(TArg->getType().getAddressSpace());
7649}
7650
7651/// Helper function for AddBuiltinOperatorCandidates() that adds
7652/// the volatile- and non-volatile-qualified assignment operators for the
7653/// given type to the candidate set.
7654static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7655                                                   QualType T,
7656                                                   ArrayRef<Expr *> Args,
7657                                    OverloadCandidateSet &CandidateSet) {
7658  QualType ParamTypes[2];
7659
7660  // T& operator=(T&, T)
7661  ParamTypes[0] = S.Context.getLValueReferenceType(
7662      AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7663  ParamTypes[1] = T;
7664  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7665                        /*IsAssignmentOperator=*/true);
7666
7667  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7668    // volatile T& operator=(volatile T&, T)
7669    ParamTypes[0] = S.Context.getLValueReferenceType(
7670        AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7671                                                Args[0]));
7672    ParamTypes[1] = T;
7673    S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7674                          /*IsAssignmentOperator=*/true);
7675  }
7676}
7677
7678/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7679/// if any, found in visible type conversion functions found in ArgExpr's type.
7680static  Qualifiers CollectVRQualifiers(ASTContext &ContextExprArgExpr) {
7681    Qualifiers VRQuals;
7682    const RecordType *TyRec;
7683    if (const MemberPointerType *RHSMPType =
7684        ArgExpr->getType()->getAs<MemberPointerType>())
7685      TyRec = RHSMPType->getClass()->getAs<RecordType>();
7686    else
7687      TyRec = ArgExpr->getType()->getAs<RecordType>();
7688    if (!TyRec) {
7689      // Just to be safe, assume the worst case.
7690      VRQuals.addVolatile();
7691      VRQuals.addRestrict();
7692      return VRQuals;
7693    }
7694
7695    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7696    if (!ClassDecl->hasDefinition())
7697      return VRQuals;
7698
7699    for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7700      if (isa<UsingShadowDecl>(D))
7701        D = cast<UsingShadowDecl>(D)->getTargetDecl();
7702      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7703        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7704        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7705          CanTy = ResTypeRef->getPointeeType();
7706        // Need to go down the pointer/mempointer chain and add qualifiers
7707        // as see them.
7708        bool done = false;
7709        while (!done) {
7710          if (CanTy.isRestrictQualified())
7711            VRQuals.addRestrict();
7712          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7713            CanTy = ResTypePtr->getPointeeType();
7714          else if (const MemberPointerType *ResTypeMPtr =
7715                CanTy->getAs<MemberPointerType>())
7716            CanTy = ResTypeMPtr->getPointeeType();
7717          else
7718            done = true;
7719          if (CanTy.isVolatileQualified())
7720            VRQuals.addVolatile();
7721          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7722            return VRQuals;
7723        }
7724      }
7725    }
7726    return VRQuals;
7727}
7728
7729namespace {
7730
7731/// Helper class to manage the addition of builtin operator overload
7732/// candidates. It provides shared state and utility methods used throughout
7733/// the process, as well as a helper method to add each group of builtin
7734/// operator overloads from the standard to a candidate set.
7735class BuiltinOperatorOverloadBuilder {
7736  // Common instance state available to all overload candidate addition methods.
7737  Sema &S;
7738  ArrayRef<Expr *> Args;
7739  Qualifiers VisibleTypeConversionsQuals;
7740  bool HasArithmeticOrEnumeralCandidateType;
7741  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7742  OverloadCandidateSet &CandidateSet;
7743
7744  static constexpr int ArithmeticTypesCap = 24;
7745  SmallVector<CanQualTypeArithmeticTypesCapArithmeticTypes;
7746
7747  // Define some indices used to iterate over the arithemetic types in
7748  // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7749  // types are that preserved by promotion (C++ [over.built]p2).
7750  unsigned FirstIntegralType,
7751           LastIntegralType;
7752  unsigned FirstPromotedIntegralType,
7753           LastPromotedIntegralType;
7754  unsigned FirstPromotedArithmeticType,
7755           LastPromotedArithmeticType;
7756  unsigned NumArithmeticTypes;
7757
7758  void InitArithmeticTypes() {
7759    // Start of promoted types.
7760    FirstPromotedArithmeticType = 0;
7761    ArithmeticTypes.push_back(S.Context.FloatTy);
7762    ArithmeticTypes.push_back(S.Context.DoubleTy);
7763    ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7764    if (S.Context.getTargetInfo().hasFloat128Type())
7765      ArithmeticTypes.push_back(S.Context.Float128Ty);
7766
7767    // Start of integral types.
7768    FirstIntegralType = ArithmeticTypes.size();
7769    FirstPromotedIntegralType = ArithmeticTypes.size();
7770    ArithmeticTypes.push_back(S.Context.IntTy);
7771    ArithmeticTypes.push_back(S.Context.LongTy);
7772    ArithmeticTypes.push_back(S.Context.LongLongTy);
7773    if (S.Context.getTargetInfo().hasInt128Type())
7774      ArithmeticTypes.push_back(S.Context.Int128Ty);
7775    ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7776    ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7777    ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7778    if (S.Context.getTargetInfo().hasInt128Type())
7779      ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7780    LastPromotedIntegralType = ArithmeticTypes.size();
7781    LastPromotedArithmeticType = ArithmeticTypes.size();
7782    // End of promoted types.
7783
7784    ArithmeticTypes.push_back(S.Context.BoolTy);
7785    ArithmeticTypes.push_back(S.Context.CharTy);
7786    ArithmeticTypes.push_back(S.Context.WCharTy);
7787    if (S.Context.getLangOpts().Char8)
7788      ArithmeticTypes.push_back(S.Context.Char8Ty);
7789    ArithmeticTypes.push_back(S.Context.Char16Ty);
7790    ArithmeticTypes.push_back(S.Context.Char32Ty);
7791    ArithmeticTypes.push_back(S.Context.SignedCharTy);
7792    ArithmeticTypes.push_back(S.Context.ShortTy);
7793    ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7794    ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7795    LastIntegralType = ArithmeticTypes.size();
7796    NumArithmeticTypes = ArithmeticTypes.size();
7797    // End of integral types.
7798    // FIXME: What about complex? What about half?
7799
7800     (0) . __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7801, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7801 (0) . __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 7801, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Enough inline storage for all arithmetic types.");
7802  }
7803
7804  /// Helper method to factor out the common pattern of adding overloads
7805  /// for '++' and '--' builtin operators.
7806  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7807                                           bool HasVolatile,
7808                                           bool HasRestrict) {
7809    QualType ParamTypes[2] = {
7810      S.Context.getLValueReferenceType(CandidateTy),
7811      S.Context.IntTy
7812    };
7813
7814    // Non-volatile version.
7815    S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7816
7817    // Use a heuristic to reduce number of builtin candidates in the set:
7818    // add volatile version only if there are conversions to a volatile type.
7819    if (HasVolatile) {
7820      ParamTypes[0] =
7821        S.Context.getLValueReferenceType(
7822          S.Context.getVolatileType(CandidateTy));
7823      S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7824    }
7825
7826    // Add restrict version only if there are conversions to a restrict type
7827    // and our candidate type is a non-restrict-qualified pointer.
7828    if (HasRestrict && CandidateTy->isAnyPointerType() &&
7829        !CandidateTy.isRestrictQualified()) {
7830      ParamTypes[0]
7831        = S.Context.getLValueReferenceType(
7832            S.Context.getCVRQualifiedType(CandidateTyQualifiers::Restrict));
7833      S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7834
7835      if (HasVolatile) {
7836        ParamTypes[0]
7837          = S.Context.getLValueReferenceType(
7838              S.Context.getCVRQualifiedType(CandidateTy,
7839                                            (Qualifiers::Volatile |
7840                                             Qualifiers::Restrict)));
7841        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7842      }
7843    }
7844
7845  }
7846
7847public:
7848  BuiltinOperatorOverloadBuilder(
7849    Sema &SArrayRef<Expr *> Args,
7850    Qualifiers VisibleTypeConversionsQuals,
7851    bool HasArithmeticOrEnumeralCandidateType,
7852    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7853    OverloadCandidateSet &CandidateSet)
7854    : S(S), Args(Args),
7855      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7856      HasArithmeticOrEnumeralCandidateType(
7857        HasArithmeticOrEnumeralCandidateType),
7858      CandidateTypes(CandidateTypes),
7859      CandidateSet(CandidateSet) {
7860
7861    InitArithmeticTypes();
7862  }
7863
7864  // Increment is deprecated for bool since C++17.
7865  //
7866  // C++ [over.built]p3:
7867  //
7868  //   For every pair (T, VQ), where T is an arithmetic type other
7869  //   than bool, and VQ is either volatile or empty, there exist
7870  //   candidate operator functions of the form
7871  //
7872  //       VQ T&      operator++(VQ T&);
7873  //       T          operator++(VQ T&, int);
7874  //
7875  // C++ [over.built]p4:
7876  //
7877  //   For every pair (T, VQ), where T is an arithmetic type other
7878  //   than bool, and VQ is either volatile or empty, there exist
7879  //   candidate operator functions of the form
7880  //
7881  //       VQ T&      operator--(VQ T&);
7882  //       T          operator--(VQ T&, int);
7883  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7884    if (!HasArithmeticOrEnumeralCandidateType)
7885      return;
7886
7887    for (unsigned Arith = 0Arith < NumArithmeticTypes; ++Arith) {
7888      const auto TypeOfT = ArithmeticTypes[Arith];
7889      if (TypeOfT == S.Context.BoolTy) {
7890        if (Op == OO_MinusMinus)
7891          continue;
7892        if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7893          continue;
7894      }
7895      addPlusPlusMinusMinusStyleOverloads(
7896        TypeOfT,
7897        VisibleTypeConversionsQuals.hasVolatile(),
7898        VisibleTypeConversionsQuals.hasRestrict());
7899    }
7900  }
7901
7902  // C++ [over.built]p5:
7903  //
7904  //   For every pair (T, VQ), where T is a cv-qualified or
7905  //   cv-unqualified object type, and VQ is either volatile or
7906  //   empty, there exist candidate operator functions of the form
7907  //
7908  //       T*VQ&      operator++(T*VQ&);
7909  //       T*VQ&      operator--(T*VQ&);
7910  //       T*         operator++(T*VQ&, int);
7911  //       T*         operator--(T*VQ&, int);
7912  void addPlusPlusMinusMinusPointerOverloads() {
7913    for (BuiltinCandidateTypeSet::iterator
7914              Ptr = CandidateTypes[0].pointer_begin(),
7915           PtrEnd = CandidateTypes[0].pointer_end();
7916         Ptr != PtrEnd; ++Ptr) {
7917      // Skip pointer types that aren't pointers to object types.
7918      if (!(*Ptr)->getPointeeType()->isObjectType())
7919        continue;
7920
7921      addPlusPlusMinusMinusStyleOverloads(*Ptr,
7922        (!(*Ptr).isVolatileQualified() &&
7923         VisibleTypeConversionsQuals.hasVolatile()),
7924        (!(*Ptr).isRestrictQualified() &&
7925         VisibleTypeConversionsQuals.hasRestrict()));
7926    }
7927  }
7928
7929  // C++ [over.built]p6:
7930  //   For every cv-qualified or cv-unqualified object type T, there
7931  //   exist candidate operator functions of the form
7932  //
7933  //       T&         operator*(T*);
7934  //
7935  // C++ [over.built]p7:
7936  //   For every function type T that does not have cv-qualifiers or a
7937  //   ref-qualifier, there exist candidate operator functions of the form
7938  //       T&         operator*(T*);
7939  void addUnaryStarPointerOverloads() {
7940    for (BuiltinCandidateTypeSet::iterator
7941              Ptr = CandidateTypes[0].pointer_begin(),
7942           PtrEnd = CandidateTypes[0].pointer_end();
7943         Ptr != PtrEnd; ++Ptr) {
7944      QualType ParamTy = *Ptr;
7945      QualType PointeeTy = ParamTy->getPointeeType();
7946      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7947        continue;
7948
7949      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7950        if (Proto->getMethodQuals() || Proto->getRefQualifier())
7951          continue;
7952
7953      S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7954    }
7955  }
7956
7957  // C++ [over.built]p9:
7958  //  For every promoted arithmetic type T, there exist candidate
7959  //  operator functions of the form
7960  //
7961  //       T         operator+(T);
7962  //       T         operator-(T);
7963  void addUnaryPlusOrMinusArithmeticOverloads() {
7964    if (!HasArithmeticOrEnumeralCandidateType)
7965      return;
7966
7967    for (unsigned Arith = FirstPromotedArithmeticType;
7968         Arith < LastPromotedArithmeticType; ++Arith) {
7969      QualType ArithTy = ArithmeticTypes[Arith];
7970      S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7971    }
7972
7973    // Extension: We also add these operators for vector types.
7974    for (BuiltinCandidateTypeSet::iterator
7975              Vec = CandidateTypes[0].vector_begin(),
7976           VecEnd = CandidateTypes[0].vector_end();
7977         Vec != VecEnd; ++Vec) {
7978      QualType VecTy = *Vec;
7979      S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7980    }
7981  }
7982
7983  // C++ [over.built]p8:
7984  //   For every type T, there exist candidate operator functions of
7985  //   the form
7986  //
7987  //       T*         operator+(T*);
7988  void addUnaryPlusPointerOverloads() {
7989    for (BuiltinCandidateTypeSet::iterator
7990              Ptr = CandidateTypes[0].pointer_begin(),
7991           PtrEnd = CandidateTypes[0].pointer_end();
7992         Ptr != PtrEnd; ++Ptr) {
7993      QualType ParamTy = *Ptr;
7994      S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7995    }
7996  }
7997
7998  // C++ [over.built]p10:
7999  //   For every promoted integral type T, there exist candidate
8000  //   operator functions of the form
8001  //
8002  //        T         operator~(T);
8003  void addUnaryTildePromotedIntegralOverloads() {
8004    if (!HasArithmeticOrEnumeralCandidateType)
8005      return;
8006
8007    for (unsigned Int = FirstPromotedIntegralType;
8008         Int < LastPromotedIntegralType; ++Int) {
8009      QualType IntTy = ArithmeticTypes[Int];
8010      S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8011    }
8012
8013    // Extension: We also add this operator for vector types.
8014    for (BuiltinCandidateTypeSet::iterator
8015              Vec = CandidateTypes[0].vector_begin(),
8016           VecEnd = CandidateTypes[0].vector_end();
8017         Vec != VecEnd; ++Vec) {
8018      QualType VecTy = *Vec;
8019      S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8020    }
8021  }
8022
8023  // C++ [over.match.oper]p16:
8024  //   For every pointer to member type T or type std::nullptr_t, there
8025  //   exist candidate operator functions of the form
8026  //
8027  //        bool operator==(T,T);
8028  //        bool operator!=(T,T);
8029  void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8030    /// Set of (canonical) types that we've already handled.
8031    llvm::SmallPtrSet<QualType, 8> AddedTypes;
8032
8033    for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
8034      for (BuiltinCandidateTypeSet::iterator
8035                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8036             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8037           MemPtr != MemPtrEnd;
8038           ++MemPtr) {
8039        // Don't add the same builtin candidate twice.
8040        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8041          continue;
8042
8043        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8044        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8045      }
8046
8047      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8048        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8049        if (AddedTypes.insert(NullPtrTy).second) {
8050          QualType ParamTypes[2] = { NullPtrTyNullPtrTy };
8051          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8052        }
8053      }
8054    }
8055  }
8056
8057  // C++ [over.built]p15:
8058  //
8059  //   For every T, where T is an enumeration type or a pointer type,
8060  //   there exist candidate operator functions of the form
8061  //
8062  //        bool       operator<(T, T);
8063  //        bool       operator>(T, T);
8064  //        bool       operator<=(T, T);
8065  //        bool       operator>=(T, T);
8066  //        bool       operator==(T, T);
8067  //        bool       operator!=(T, T);
8068  //           R       operator<=>(T, T)
8069  void addGenericBinaryPointerOrEnumeralOverloads() {
8070    // C++ [over.match.oper]p3:
8071    //   [...]the built-in candidates include all of the candidate operator
8072    //   functions defined in 13.6 that, compared to the given operator, [...]
8073    //   do not have the same parameter-type-list as any non-template non-member
8074    //   candidate.
8075    //
8076    // Note that in practice, this only affects enumeration types because there
8077    // aren't any built-in candidates of record type, and a user-defined operator
8078    // must have an operand of record or enumeration type. Also, the only other
8079    // overloaded operator with enumeration arguments, operator=,
8080    // cannot be overloaded for enumeration types, so this is the only place
8081    // where we must suppress candidates like this.
8082    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8083      UserDefinedBinaryOperators;
8084
8085    for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
8086      if (CandidateTypes[ArgIdx].enumeration_begin() !=
8087          CandidateTypes[ArgIdx].enumeration_end()) {
8088        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8089                                         CEnd = CandidateSet.end();
8090             C != CEnd; ++C) {
8091          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8092            continue;
8093
8094          if (C->Function->isFunctionTemplateSpecialization())
8095            continue;
8096
8097          QualType FirstParamType =
8098            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8099          QualType SecondParamType =
8100            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8101
8102          // Skip if either parameter isn't of enumeral type.
8103          if (!FirstParamType->isEnumeralType() ||
8104              !SecondParamType->isEnumeralType())
8105            continue;
8106
8107          // Add this operator to the set of known user-defined operators.
8108          UserDefinedBinaryOperators.insert(
8109            std::make_pair(S.Context.getCanonicalType(FirstParamType),
8110                           S.Context.getCanonicalType(SecondParamType)));
8111        }
8112      }
8113    }
8114
8115    /// Set of (canonical) types that we've already handled.
8116    llvm::SmallPtrSet<QualType, 8> AddedTypes;
8117
8118    for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
8119      for (BuiltinCandidateTypeSet::iterator
8120                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8121             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8122           Ptr != PtrEnd; ++Ptr) {
8123        // Don't add the same builtin candidate twice.
8124        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8125          continue;
8126
8127        QualType ParamTypes[2] = { *Ptr, *Ptr };
8128        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129      }
8130      for (BuiltinCandidateTypeSet::iterator
8131                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8132             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8133           Enum != EnumEnd; ++Enum) {
8134        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8135
8136        // Don't add the same builtin candidate twice, or if a user defined
8137        // candidate exists.
8138        if (!AddedTypes.insert(CanonType).second ||
8139            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8140                                                            CanonType)))
8141          continue;
8142        QualType ParamTypes[2] = { *Enum, *Enum };
8143        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8144      }
8145    }
8146  }
8147
8148  // C++ [over.built]p13:
8149  //
8150  //   For every cv-qualified or cv-unqualified object type T
8151  //   there exist candidate operator functions of the form
8152  //
8153  //      T*         operator+(T*, ptrdiff_t);
8154  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8155  //      T*         operator-(T*, ptrdiff_t);
8156  //      T*         operator+(ptrdiff_t, T*);
8157  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8158  //
8159  // C++ [over.built]p14:
8160  //
8161  //   For every T, where T is a pointer to object type, there
8162  //   exist candidate operator functions of the form
8163  //
8164  //      ptrdiff_t  operator-(T, T);
8165  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8166    /// Set of (canonical) types that we've already handled.
8167    llvm::SmallPtrSet<QualType, 8> AddedTypes;
8168
8169    for (int Arg = 0Arg < 2; ++Arg) {
8170      QualType AsymmetricParamTypes[2] = {
8171        S.Context.getPointerDiffType(),
8172        S.Context.getPointerDiffType(),
8173      };
8174      for (BuiltinCandidateTypeSet::iterator
8175                Ptr = CandidateTypes[Arg].pointer_begin(),
8176             PtrEnd = CandidateTypes[Arg].pointer_end();
8177           Ptr != PtrEnd; ++Ptr) {
8178        QualType PointeeTy = (*Ptr)->getPointeeType();
8179        if (!PointeeTy->isObjectType())
8180          continue;
8181
8182        AsymmetricParamTypes[Arg] = *Ptr;
8183        if (Arg == 0 || Op == OO_Plus) {
8184          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8185          // T* operator+(ptrdiff_t, T*);
8186          S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8187        }
8188        if (Op == OO_Minus) {
8189          // ptrdiff_t operator-(T, T);
8190          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8191            continue;
8192
8193          QualType ParamTypes[2] = { *Ptr, *Ptr };
8194          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8195        }
8196      }
8197    }
8198  }
8199
8200  // C++ [over.built]p12:
8201  //
8202  //   For every pair of promoted arithmetic types L and R, there
8203  //   exist candidate operator functions of the form
8204  //
8205  //        LR         operator*(L, R);
8206  //        LR         operator/(L, R);
8207  //        LR         operator+(L, R);
8208  //        LR         operator-(L, R);
8209  //        bool       operator<(L, R);
8210  //        bool       operator>(L, R);
8211  //        bool       operator<=(L, R);
8212  //        bool       operator>=(L, R);
8213  //        bool       operator==(L, R);
8214  //        bool       operator!=(L, R);
8215  //
8216  //   where LR is the result of the usual arithmetic conversions
8217  //   between types L and R.
8218  //
8219  // C++ [over.built]p24:
8220  //
8221  //   For every pair of promoted arithmetic types L and R, there exist
8222  //   candidate operator functions of the form
8223  //
8224  //        LR       operator?(bool, L, R);
8225  //
8226  //   where LR is the result of the usual arithmetic conversions
8227  //   between types L and R.
8228  // Our candidates ignore the first parameter.
8229  void addGenericBinaryArithmeticOverloads() {
8230    if (!HasArithmeticOrEnumeralCandidateType)
8231      return;
8232
8233    for (unsigned Left = FirstPromotedArithmeticType;
8234         Left < LastPromotedArithmeticType; ++Left) {
8235      for (unsigned Right = FirstPromotedArithmeticType;
8236           Right < LastPromotedArithmeticType; ++Right) {
8237        QualType LandR[2] = { ArithmeticTypes[Left],
8238                              ArithmeticTypes[Right] };
8239        S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8240      }
8241    }
8242
8243    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8244    // conditional operator for vector types.
8245    for (BuiltinCandidateTypeSet::iterator
8246              Vec1 = CandidateTypes[0].vector_begin(),
8247           Vec1End = CandidateTypes[0].vector_end();
8248         Vec1 != Vec1End; ++Vec1) {
8249      for (BuiltinCandidateTypeSet::iterator
8250                Vec2 = CandidateTypes[1].vector_begin(),
8251             Vec2End = CandidateTypes[1].vector_end();
8252           Vec2 != Vec2End; ++Vec2) {
8253        QualType LandR[2] = { *Vec1, *Vec2 };
8254        S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8255      }
8256    }
8257  }
8258
8259  // C++2a [over.built]p14:
8260  //
8261  //   For every integral type T there exists a candidate operator function
8262  //   of the form
8263  //
8264  //        std::strong_ordering operator<=>(T, T)
8265  //
8266  // C++2a [over.built]p15:
8267  //
8268  //   For every pair of floating-point types L and R, there exists a candidate
8269  //   operator function of the form
8270  //
8271  //       std::partial_ordering operator<=>(L, R);
8272  //
8273  // FIXME: The current specification for integral types doesn't play nice with
8274  // the direction of p0946r0, which allows mixed integral and unscoped-enum
8275  // comparisons. Under the current spec this can lead to ambiguity during
8276  // overload resolution. For example:
8277  //
8278  //   enum A : int {a};
8279  //   auto x = (a <=> (long)42);
8280  //
8281  //   error: call is ambiguous for arguments 'A' and 'long'.
8282  //   note: candidate operator<=>(int, int)
8283  //   note: candidate operator<=>(long, long)
8284  //
8285  // To avoid this error, this function deviates from the specification and adds
8286  // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8287  // arithmetic types (the same as the generic relational overloads).
8288  //
8289  // For now this function acts as a placeholder.
8290  void addThreeWayArithmeticOverloads() {
8291    addGenericBinaryArithmeticOverloads();
8292  }
8293
8294  // C++ [over.built]p17:
8295  //
8296  //   For every pair of promoted integral types L and R, there
8297  //   exist candidate operator functions of the form
8298  //
8299  //      LR         operator%(L, R);
8300  //      LR         operator&(L, R);
8301  //      LR         operator^(L, R);
8302  //      LR         operator|(L, R);
8303  //      L          operator<<(L, R);
8304  //      L          operator>>(L, R);
8305  //
8306  //   where LR is the result of the usual arithmetic conversions
8307  //   between types L and R.
8308  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8309    if (!HasArithmeticOrEnumeralCandidateType)
8310      return;
8311
8312    for (unsigned Left = FirstPromotedIntegralType;
8313         Left < LastPromotedIntegralType; ++Left) {
8314      for (unsigned Right = FirstPromotedIntegralType;
8315           Right < LastPromotedIntegralType; ++Right) {
8316        QualType LandR[2] = { ArithmeticTypes[Left],
8317                              ArithmeticTypes[Right] };
8318        S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8319      }
8320    }
8321  }
8322
8323  // C++ [over.built]p20:
8324  //
8325  //   For every pair (T, VQ), where T is an enumeration or
8326  //   pointer to member type and VQ is either volatile or
8327  //   empty, there exist candidate operator functions of the form
8328  //
8329  //        VQ T&      operator=(VQ T&, T);
8330  void addAssignmentMemberPointerOrEnumeralOverloads() {
8331    /// Set of (canonical) types that we've already handled.
8332    llvm::SmallPtrSet<QualType, 8> AddedTypes;
8333
8334    for (unsigned ArgIdx = 0ArgIdx < 2; ++ArgIdx) {
8335      for (BuiltinCandidateTypeSet::iterator
8336                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8337             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8338           Enum != EnumEnd; ++Enum) {
8339        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8340          continue;
8341
8342        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8343      }
8344
8345      for (BuiltinCandidateTypeSet::iterator
8346                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8347             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8348           MemPtr != MemPtrEnd; ++MemPtr) {
8349        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8350          continue;
8351
8352        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8353      }
8354    }
8355  }
8356
8357  // C++ [over.built]p19:
8358  //
8359  //   For every pair (T, VQ), where T is any type and VQ is either
8360  //   volatile or empty, there exist candidate operator functions
8361  //   of the form
8362  //
8363  //        T*VQ&      operator=(T*VQ&, T*);
8364  //
8365  // C++ [over.built]p21:
8366  //
8367  //   For every pair (T, VQ), where T is a cv-qualified or
8368  //   cv-unqualified object type and VQ is either volatile or
8369  //   empty, there exist candidate operator functions of the form
8370  //
8371  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8372  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8373  void addAssignmentPointerOverloads(bool isEqualOp) {
8374    /// Set of (canonical) types that we've already handled.
8375    llvm::SmallPtrSet<QualType, 8> AddedTypes;
8376
8377    for (BuiltinCandidateTypeSet::iterator
8378              Ptr = CandidateTypes[0].pointer_begin(),
8379           PtrEnd = CandidateTypes[0].pointer_end();
8380         Ptr != PtrEnd; ++Ptr) {
8381      // If this is operator=, keep track of the builtin candidates we added.
8382      if (isEqualOp)
8383        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8384      else if (!(*Ptr)->getPointeeType()->isObjectType())
8385        continue;
8386
8387      // non-volatile version
8388      QualType ParamTypes[2] = {
8389        S.Context.getLValueReferenceType(*Ptr),
8390        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8391      };
8392      S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8393                            /*IsAssigmentOperator=*/ isEqualOp);
8394
8395      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8396                          VisibleTypeConversionsQuals.hasVolatile();
8397      if (NeedVolatile) {
8398        // volatile version
8399        ParamTypes[0] =
8400          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8401        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8402                              /*IsAssigmentOperator=*/isEqualOp);
8403      }
8404
8405      if (!(*Ptr).isRestrictQualified() &&
8406          VisibleTypeConversionsQuals.hasRestrict()) {
8407        // restrict version
8408        ParamTypes[0]
8409          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8410        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8411                              /*IsAssigmentOperator=*/isEqualOp);
8412
8413        if (NeedVolatile) {
8414          // volatile restrict version
8415          ParamTypes[0]
8416            = S.Context.getLValueReferenceType(
8417                S.Context.getCVRQualifiedType(*Ptr,
8418                                              (Qualifiers::Volatile |
8419                                               Qualifiers::Restrict)));
8420          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8421                                /*IsAssigmentOperator=*/isEqualOp);
8422        }
8423      }
8424    }
8425
8426    if (isEqualOp) {
8427      for (BuiltinCandidateTypeSet::iterator
8428                Ptr = CandidateTypes[1].pointer_begin(),
8429             PtrEnd = CandidateTypes[1].pointer_end();
8430           Ptr != PtrEnd; ++Ptr) {
8431        // Make sure we don't add the same candidate twice.
8432        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8433          continue;
8434
8435        QualType ParamTypes[2] = {
8436          S.Context.getLValueReferenceType(*Ptr),
8437          *Ptr,
8438        };
8439
8440        // non-volatile version
8441        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8442                              /*IsAssigmentOperator=*/true);
8443
8444        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8445                           VisibleTypeConversionsQuals.hasVolatile();
8446        if (NeedVolatile) {
8447          // volatile version
8448          ParamTypes[0] =
8449            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8450          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8451                                /*IsAssigmentOperator=*/true);
8452        }
8453
8454        if (!(*Ptr).isRestrictQualified() &&
8455            VisibleTypeConversionsQuals.hasRestrict()) {
8456          // restrict version
8457          ParamTypes[0]
8458            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8459          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8460                                /*IsAssigmentOperator=*/true);
8461
8462          if (NeedVolatile) {
8463            // volatile restrict version
8464            ParamTypes[0]
8465              = S.Context.getLValueReferenceType(
8466                  S.Context.getCVRQualifiedType(*Ptr,
8467                                                (Qualifiers::Volatile |
8468                                                 Qualifiers::Restrict)));
8469            S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8470                                  /*IsAssigmentOperator=*/true);
8471          }
8472        }
8473      }
8474    }
8475  }
8476
8477  // C++ [over.built]p18:
8478  //
8479  //   For every triple (L, VQ, R), where L is an arithmetic type,
8480  //   VQ is either volatile or empty, and R is a promoted
8481  //   arithmetic type, there exist candidate operator functions of
8482  //   the form
8483  //
8484  //        VQ L&      operator=(VQ L&, R);
8485  //        VQ L&      operator*=(VQ L&, R);
8486  //        VQ L&      operator/=(VQ L&, R);
8487  //        VQ L&      operator+=(VQ L&, R);
8488  //        VQ L&      operator-=(VQ L&, R);
8489  void addAssignmentArithmeticOverloads(bool isEqualOp) {
8490    if (!HasArithmeticOrEnumeralCandidateType)
8491      return;
8492
8493    for (unsigned Left = 0Left < NumArithmeticTypes; ++Left) {
8494      for (unsigned Right = FirstPromotedArithmeticType;
8495           Right < LastPromotedArithmeticType; ++Right) {
8496        QualType ParamTypes[2];
8497        ParamTypes[1] = ArithmeticTypes[Right];
8498        auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8499            S, ArithmeticTypes[Left], Args[0]);
8500        // Add this built-in operator as a candidate (VQ is empty).
8501        ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8502        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8503                              /*IsAssigmentOperator=*/isEqualOp);
8504
8505        // Add this built-in operator as a candidate (VQ is 'volatile').
8506        if (VisibleTypeConversionsQuals.hasVolatile()) {
8507          ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8508          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8509          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8510                                /*IsAssigmentOperator=*/isEqualOp);
8511        }
8512      }
8513    }
8514
8515    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8516    for (BuiltinCandidateTypeSet::iterator
8517              Vec1 = CandidateTypes[0].vector_begin(),
8518           Vec1End = CandidateTypes[0].vector_end();
8519         Vec1 != Vec1End; ++Vec1) {
8520      for (BuiltinCandidateTypeSet::iterator
8521                Vec2 = CandidateTypes[1].vector_begin(),
8522             Vec2End = CandidateTypes[1].vector_end();
8523           Vec2 != Vec2End; ++Vec2) {
8524        QualType ParamTypes[2];
8525        ParamTypes[1] = *Vec2;
8526        // Add this built-in operator as a candidate (VQ is empty).
8527        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8528        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8529                              /*IsAssigmentOperator=*/isEqualOp);
8530
8531        // Add this built-in operator as a candidate (VQ is 'volatile').
8532        if (VisibleTypeConversionsQuals.hasVolatile()) {
8533          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8534          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8535          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8536                                /*IsAssigmentOperator=*/isEqualOp);
8537        }
8538      }
8539    }
8540  }
8541
8542  // C++ [over.built]p22:
8543  //
8544  //   For every triple (L, VQ, R), where L is an integral type, VQ
8545  //   is either volatile or empty, and R is a promoted integral
8546  //   type, there exist candidate operator functions of the form
8547  //
8548  //        VQ L&       operator%=(VQ L&, R);
8549  //        VQ L&       operator<<=(VQ L&, R);
8550  //        VQ L&       operator>>=(VQ L&, R);
8551  //        VQ L&       operator&=(VQ L&, R);
8552  //        VQ L&       operator^=(VQ L&, R);
8553  //        VQ L&       operator|=(VQ L&, R);
8554  void addAssignmentIntegralOverloads() {
8555    if (!HasArithmeticOrEnumeralCandidateType)
8556      return;
8557
8558    for (unsigned Left = FirstIntegralTypeLeft < LastIntegralType; ++Left) {
8559      for (unsigned Right = FirstPromotedIntegralType;
8560           Right < LastPromotedIntegralType; ++Right) {
8561        QualType ParamTypes[2];
8562        ParamTypes[1] = ArithmeticTypes[Right];
8563        auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8564            S, ArithmeticTypes[Left], Args[0]);
8565        // Add this built-in operator as a candidate (VQ is empty).
8566        ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8567        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8568        if (VisibleTypeConversionsQuals.hasVolatile()) {
8569          // Add this built-in operator as a candidate (VQ is 'volatile').
8570          ParamTypes[0] = LeftBaseTy;
8571          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8572          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8573          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8574        }
8575      }
8576    }
8577  }
8578
8579  // C++ [over.operator]p23:
8580  //
8581  //   There also exist candidate operator functions of the form
8582  //
8583  //        bool        operator!(bool);
8584  //        bool        operator&&(bool, bool);
8585  //        bool        operator||(bool, bool);
8586  void addExclaimOverload() {
8587    QualType ParamTy = S.Context.BoolTy;
8588    S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8589                          /*IsAssignmentOperator=*/false,
8590                          /*NumContextualBoolArguments=*/1);
8591  }
8592  void addAmpAmpOrPipePipeOverload() {
8593    QualType ParamTypes[2] = { S.Context.BoolTyS.Context.BoolTy };
8594    S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8595                          /*IsAssignmentOperator=*/false,
8596                          /*NumContextualBoolArguments=*/2);
8597  }
8598
8599  // C++ [over.built]p13:
8600  //
8601  //   For every cv-qualified or cv-unqualified object type T there
8602  //   exist candidate operator functions of the form
8603  //
8604  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8605  //        T&         operator[](T*, ptrdiff_t);
8606  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8607  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8608  //        T&         operator[](ptrdiff_t, T*);
8609  void addSubscriptOverloads() {
8610    for (BuiltinCandidateTypeSet::iterator
8611              Ptr = CandidateTypes[0].pointer_begin(),
8612           PtrEnd = CandidateTypes[0].pointer_end();
8613         Ptr != PtrEnd; ++Ptr) {
8614      QualType ParamTypes[2] = { *PtrS.Context.getPointerDiffType() };
8615      QualType PointeeType = (*Ptr)->getPointeeType();
8616      if (!PointeeType->isObjectType())
8617        continue;
8618
8619      // T& operator[](T*, ptrdiff_t)
8620      S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8621    }
8622
8623    for (BuiltinCandidateTypeSet::iterator
8624              Ptr = CandidateTypes[1].pointer_begin(),
8625           PtrEnd = CandidateTypes[1].pointer_end();
8626         Ptr != PtrEnd; ++Ptr) {
8627      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8628      QualType PointeeType = (*Ptr)->getPointeeType();
8629      if (!PointeeType->isObjectType())
8630        continue;
8631
8632      // T& operator[](ptrdiff_t, T*)
8633      S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8634    }
8635  }
8636
8637  // C++ [over.built]p11:
8638  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8639  //    C1 is the same type as C2 or is a derived class of C2, T is an object
8640  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8641  //    there exist candidate operator functions of the form
8642  //
8643  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8644  //
8645  //    where CV12 is the union of CV1 and CV2.
8646  void addArrowStarOverloads() {
8647    for (BuiltinCandidateTypeSet::iterator
8648             Ptr = CandidateTypes[0].pointer_begin(),
8649           PtrEnd = CandidateTypes[0].pointer_end();
8650         Ptr != PtrEnd; ++Ptr) {
8651      QualType C1Ty = (*Ptr);
8652      QualType C1;
8653      QualifierCollector Q1;
8654      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8655      if (!isa<RecordType>(C1))
8656        continue;
8657      // heuristic to reduce number of builtin candidates in the set.
8658      // Add volatile/restrict version only if there are conversions to a
8659      // volatile/restrict type.
8660      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8661        continue;
8662      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8663        continue;
8664      for (BuiltinCandidateTypeSet::iterator
8665                MemPtr = CandidateTypes[1].member_pointer_begin(),
8666             MemPtrEnd = CandidateTypes[1].member_pointer_end();
8667           MemPtr != MemPtrEnd; ++MemPtr) {
8668        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8669        QualType C2 = QualType(mptr->getClass(), 0);
8670        C2 = C2.getUnqualifiedType();
8671        if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1C2))
8672          break;
8673        QualType ParamTypes[2] = { *Ptr, *MemPtr };
8674        // build CV12 T&
8675        QualType T = mptr->getPointeeType();
8676        if (!VisibleTypeConversionsQuals.hasVolatile() &&
8677            T.isVolatileQualified())
8678          continue;
8679        if (!VisibleTypeConversionsQuals.hasRestrict() &&
8680            T.isRestrictQualified())
8681          continue;
8682        T = Q1.apply(S.ContextT);
8683        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8684      }
8685    }
8686  }
8687
8688  // Note that we don't consider the first argument, since it has been
8689  // contextually converted to bool long ago. The candidates below are
8690  // therefore added as binary.
8691  //
8692  // C++ [over.built]p25:
8693  //   For every type T, where T is a pointer, pointer-to-member, or scoped
8694  //   enumeration type, there exist candidate operator functions of the form
8695  //
8696  //        T        operator?(bool, T, T);
8697  //
8698  void addConditionalOperatorOverloads() {
8699    /// Set of (canonical) types that we've already handled.
8700    llvm::SmallPtrSet<QualType, 8> AddedTypes;
8701
8702    for (unsigned ArgIdx = 0ArgIdx < 2; ++ArgIdx) {
8703      for (BuiltinCandidateTypeSet::iterator
8704                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8705             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8706           Ptr != PtrEnd; ++Ptr) {
8707        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8708          continue;
8709
8710        QualType ParamTypes[2] = { *Ptr, *Ptr };
8711        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8712      }
8713
8714      for (BuiltinCandidateTypeSet::iterator
8715                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8716             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8717           MemPtr != MemPtrEnd; ++MemPtr) {
8718        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8719          continue;
8720
8721        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8722        S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8723      }
8724
8725      if (S.getLangOpts().CPlusPlus11) {
8726        for (BuiltinCandidateTypeSet::iterator
8727                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8728               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8729             Enum != EnumEnd; ++Enum) {
8730          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8731            continue;
8732
8733          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8734            continue;
8735
8736          QualType ParamTypes[2] = { *Enum, *Enum };
8737          S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8738        }
8739      }
8740    }
8741  }
8742};
8743
8744// end anonymous namespace
8745
8746/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8747/// operator overloads to the candidate set (C++ [over.built]), based
8748/// on the operator @p Op and the arguments given. For example, if the
8749/// operator is a binary '+', this routine might add "int
8750/// operator+(int, int)" to cover integer addition.
8751void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8752                                        SourceLocation OpLoc,
8753                                        ArrayRef<Expr *> Args,
8754                                        OverloadCandidateSet &CandidateSet) {
8755  // Find all of the types that the arguments can convert to, but only
8756  // if the operator we're looking at has built-in operator candidates
8757  // that make use of these types. Also record whether we encounter non-record
8758  // candidate types or either arithmetic or enumeral candidate types.
8759  Qualifiers VisibleTypeConversionsQuals;
8760  VisibleTypeConversionsQuals.addConst();
8761  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8762    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8763
8764  bool HasNonRecordCandidateType = false;
8765  bool HasArithmeticOrEnumeralCandidateType = false;
8766  SmallVector<BuiltinCandidateTypeSet2CandidateTypes;
8767  for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
8768    CandidateTypes.emplace_back(*this);
8769    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8770                                                 OpLoc,
8771                                                 true,
8772                                                 (Op == OO_Exclaim ||
8773                                                  Op == OO_AmpAmp ||
8774                                                  Op == OO_PipePipe),
8775                                                 VisibleTypeConversionsQuals);
8776    HasNonRecordCandidateType = HasNonRecordCandidateType ||
8777        CandidateTypes[ArgIdx].hasNonRecordTypes();
8778    HasArithmeticOrEnumeralCandidateType =
8779        HasArithmeticOrEnumeralCandidateType ||
8780        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8781  }
8782
8783  // Exit early when no non-record types have been added to the candidate set
8784  // for any of the arguments to the operator.
8785  //
8786  // We can't exit early for !, ||, or &&, since there we have always have
8787  // 'bool' overloads.
8788  if (!HasNonRecordCandidateType &&
8789      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8790    return;
8791
8792  // Setup an object to manage the common state for building overloads.
8793  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8794                                           VisibleTypeConversionsQuals,
8795                                           HasArithmeticOrEnumeralCandidateType,
8796                                           CandidateTypes, CandidateSet);
8797
8798  // Dispatch over the operation to add in only those overloads which apply.
8799  switch (Op) {
8800  case OO_None:
8801  case NUM_OVERLOADED_OPERATORS:
8802    llvm_unreachable("Expected an overloaded operator");
8803
8804  case OO_New:
8805  case OO_Delete:
8806  case OO_Array_New:
8807  case OO_Array_Delete:
8808  case OO_Call:
8809    llvm_unreachable(
8810                    "Special operators don't use AddBuiltinOperatorCandidates");
8811
8812  case OO_Comma:
8813  case OO_Arrow:
8814  case OO_Coawait:
8815    // C++ [over.match.oper]p3:
8816    //   -- For the operator ',', the unary operator '&', the
8817    //      operator '->', or the operator 'co_await', the
8818    //      built-in candidates set is empty.
8819    break;
8820
8821  case OO_Plus// '+' is either unary or binary
8822    if (Args.size() == 1)
8823      OpBuilder.addUnaryPlusPointerOverloads();
8824    LLVM_FALLTHROUGH;
8825
8826  case OO_Minus// '-' is either unary or binary
8827    if (Args.size() == 1) {
8828      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8829    } else {
8830      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8831      OpBuilder.addGenericBinaryArithmeticOverloads();
8832    }
8833    break;
8834
8835  case OO_Star// '*' is either unary or binary
8836    if (Args.size() == 1)
8837      OpBuilder.addUnaryStarPointerOverloads();
8838    else
8839      OpBuilder.addGenericBinaryArithmeticOverloads();
8840    break;
8841
8842  case OO_Slash:
8843    OpBuilder.addGenericBinaryArithmeticOverloads();
8844    break;
8845
8846  case OO_PlusPlus:
8847  case OO_MinusMinus:
8848    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8849    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8850    break;
8851
8852  case OO_EqualEqual:
8853  case OO_ExclaimEqual:
8854    OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8855    LLVM_FALLTHROUGH;
8856
8857  case OO_Less:
8858  case OO_Greater:
8859  case OO_LessEqual:
8860  case OO_GreaterEqual:
8861    OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8862    OpBuilder.addGenericBinaryArithmeticOverloads();
8863    break;
8864
8865  case OO_Spaceship:
8866    OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8867    OpBuilder.addThreeWayArithmeticOverloads();
8868    break;
8869
8870  case OO_Percent:
8871  case OO_Caret:
8872  case OO_Pipe:
8873  case OO_LessLess:
8874  case OO_GreaterGreater:
8875    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8876    break;
8877
8878  case OO_Amp// '&' is either unary or binary
8879    if (Args.size() == 1)
8880      // C++ [over.match.oper]p3:
8881      //   -- For the operator ',', the unary operator '&', or the
8882      //      operator '->', the built-in candidates set is empty.
8883      break;
8884
8885    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8886    break;
8887
8888  case OO_Tilde:
8889    OpBuilder.addUnaryTildePromotedIntegralOverloads();
8890    break;
8891
8892  case OO_Equal:
8893    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8894    LLVM_FALLTHROUGH;
8895
8896  case OO_PlusEqual:
8897  case OO_MinusEqual:
8898    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8899    LLVM_FALLTHROUGH;
8900
8901  case OO_StarEqual:
8902  case OO_SlashEqual:
8903    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8904    break;
8905
8906  case OO_PercentEqual:
8907  case OO_LessLessEqual:
8908  case OO_GreaterGreaterEqual:
8909  case OO_AmpEqual:
8910  case OO_CaretEqual:
8911  case OO_PipeEqual:
8912    OpBuilder.addAssignmentIntegralOverloads();
8913    break;
8914
8915  case OO_Exclaim:
8916    OpBuilder.addExclaimOverload();
8917    break;
8918
8919  case OO_AmpAmp:
8920  case OO_PipePipe:
8921    OpBuilder.addAmpAmpOrPipePipeOverload();
8922    break;
8923
8924  case OO_Subscript:
8925    OpBuilder.addSubscriptOverloads();
8926    break;
8927
8928  case OO_ArrowStar:
8929    OpBuilder.addArrowStarOverloads();
8930    break;
8931
8932  case OO_Conditional:
8933    OpBuilder.addConditionalOperatorOverloads();
8934    OpBuilder.addGenericBinaryArithmeticOverloads();
8935    break;
8936  }
8937}
8938
8939/// Add function candidates found via argument-dependent lookup
8940/// to the set of overloading candidates.
8941///
8942/// This routine performs argument-dependent name lookup based on the
8943/// given function name (which may also be an operator name) and adds
8944/// all of the overload candidates found by ADL to the overload
8945/// candidate set (C++ [basic.lookup.argdep]).
8946void
8947Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8948                                           SourceLocation Loc,
8949                                           ArrayRef<Expr *> Args,
8950                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
8951                                           OverloadCandidateSetCandidateSet,
8952                                           bool PartialOverloading) {
8953  ADLResult Fns;
8954
8955  // FIXME: This approach for uniquing ADL results (and removing
8956  // redundant candidates from the set) relies on pointer-equality,
8957  // which means we need to key off the canonical decl.  However,
8958  // always going back to the canonical decl might not get us the
8959  // right set of default arguments.  What default arguments are
8960  // we supposed to consider on ADL candidates, anyway?
8961
8962  // FIXME: Pass in the explicit template arguments?
8963  ArgumentDependentLookup(Name, Loc, Args, Fns);
8964
8965  // Erase all of the candidates we already knew about.
8966  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8967                                   CandEnd = CandidateSet.end();
8968       Cand != CandEnd; ++Cand)
8969    if (Cand->Function) {
8970      Fns.erase(Cand->Function);
8971      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8972        Fns.erase(FunTmpl);
8973    }
8974
8975  // For each of the ADL candidates we found, add it to the overload
8976  // set.
8977  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8978    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8979
8980    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8981      if (ExplicitTemplateArgs)
8982        continue;
8983
8984      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8985                           /*SupressUserConversions=*/false, PartialOverloading,
8986                           /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8987    } else {
8988      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
8989                                   ExplicitTemplateArgs, Args, CandidateSet,
8990                                   /*SupressUserConversions=*/false,
8991                                   PartialOverloading, ADLCallKind::UsesADL);
8992    }
8993  }
8994}
8995
8996namespace {
8997enum class Comparison { EqualBetterWorse };
8998}
8999
9000/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9001/// overload resolution.
9002///
9003/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9004/// Cand1's first N enable_if attributes have precisely the same conditions as
9005/// Cand2's first N enable_if attributes (where N = the number of enable_if
9006/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9007///
9008/// Note that you can have a pair of candidates such that Cand1's enable_if
9009/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9010/// worse than Cand1's.
9011static Comparison compareEnableIfAttrs(const Sema &Sconst FunctionDecl *Cand1,
9012                                       const FunctionDecl *Cand2) {
9013  // Common case: One (or both) decls don't have enable_if attrs.
9014  bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9015  bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9016  if (!Cand1Attr || !Cand2Attr) {
9017    if (Cand1Attr == Cand2Attr)
9018      return Comparison::Equal;
9019    return Cand1Attr ? Comparison::Better : Comparison::Worse;
9020  }
9021
9022  auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9023  auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9024
9025  llvm::FoldingSetNodeID Cand1IDCand2ID;
9026  for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9027    Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9028    Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9029
9030    // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9031    // has fewer enable_if attributes than Cand2, and vice versa.
9032    if (!Cand1A)
9033      return Comparison::Worse;
9034    if (!Cand2A)
9035      return Comparison::Better;
9036
9037    Cand1ID.clear();
9038    Cand2ID.clear();
9039
9040    (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9041    (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9042    if (Cand1ID != Cand2ID)
9043      return Comparison::Worse;
9044  }
9045
9046  return Comparison::Equal;
9047}
9048
9049static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9050                                          const OverloadCandidate &Cand2) {
9051  if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9052      !Cand2.Function->isMultiVersion())
9053    return false;
9054
9055  // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9056  // is obviously better.
9057  if (Cand1.Function->isInvalidDecl()) return false;
9058  if (Cand2.Function->isInvalidDecl()) return true;
9059
9060  // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9061  // cpu_dispatch, else arbitrarily based on the identifiers.
9062  bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9063  bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9064  const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9065  const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9066
9067  if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9068    return false;
9069
9070  if (Cand1CPUDisp && !Cand2CPUDisp)
9071    return true;
9072  if (Cand2CPUDisp && !Cand1CPUDisp)
9073    return false;
9074
9075  if (Cand1CPUSpec && Cand2CPUSpec) {
9076    if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9077      return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9078
9079    std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9080        FirstDiff = std::mismatch(
9081            Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9082            Cand2CPUSpec->cpus_begin(),
9083            [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9084              return LHS->getName() == RHS->getName();
9085            });
9086
9087     (0) . __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9089, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9088 (0) . __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9089, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Two different cpu-specific versions should not have the same "
9089 (0) . __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9089, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "identifier list, otherwise they'd be the same decl!");
9090    return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9091  }
9092  llvm_unreachable("No way to get here unless both had cpu_dispatch");
9093}
9094
9095/// isBetterOverloadCandidate - Determines whether the first overload
9096/// candidate is a better candidate than the second (C++ 13.3.3p1).
9097bool clang::isBetterOverloadCandidate(
9098    Sema &Sconst OverloadCandidate &Cand1const OverloadCandidate &Cand2,
9099    SourceLocation LocOverloadCandidateSet::CandidateSetKind Kind) {
9100  // Define viable functions to be better candidates than non-viable
9101  // functions.
9102  if (!Cand2.Viable)
9103    return Cand1.Viable;
9104  else if (!Cand1.Viable)
9105    return false;
9106
9107  // C++ [over.match.best]p1:
9108  //
9109  //   -- if F is a static member function, ICS1(F) is defined such
9110  //      that ICS1(F) is neither better nor worse than ICS1(G) for
9111  //      any function G, and, symmetrically, ICS1(G) is neither
9112  //      better nor worse than ICS1(F).
9113  unsigned StartArg = 0;
9114  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9115    StartArg = 1;
9116
9117  auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9118    // We don't allow incompatible pointer conversions in C++.
9119    if (!S.getLangOpts().CPlusPlus)
9120      return ICS.isStandard() &&
9121             ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9122
9123    // The only ill-formed conversion we allow in C++ is the string literal to
9124    // char* conversion, which is only considered ill-formed after C++11.
9125    return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9126           hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9127  };
9128
9129  // Define functions that don't require ill-formed conversions for a given
9130  // argument to be better candidates than functions that do.
9131  unsigned NumArgs = Cand1.Conversions.size();
9132   (0) . __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9132, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9133  bool HasBetterConversion = false;
9134  for (unsigned ArgIdx = StartArgArgIdx < NumArgs; ++ArgIdx) {
9135    bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9136    bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9137    if (Cand1Bad != Cand2Bad) {
9138      if (Cand1Bad)
9139        return false;
9140      HasBetterConversion = true;
9141    }
9142  }
9143
9144  if (HasBetterConversion)
9145    return true;
9146
9147  // C++ [over.match.best]p1:
9148  //   A viable function F1 is defined to be a better function than another
9149  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9150  //   conversion sequence than ICSi(F2), and then...
9151  for (unsigned ArgIdx = StartArgArgIdx < NumArgs; ++ArgIdx) {
9152    switch (CompareImplicitConversionSequences(SLoc,
9153                                               Cand1.Conversions[ArgIdx],
9154                                               Cand2.Conversions[ArgIdx])) {
9155    case ImplicitConversionSequence::Better:
9156      // Cand1 has a better conversion sequence.
9157      HasBetterConversion = true;
9158      break;
9159
9160    case ImplicitConversionSequence::Worse:
9161      // Cand1 can't be better than Cand2.
9162      return false;
9163
9164    case ImplicitConversionSequence::Indistinguishable:
9165      // Do nothing.
9166      break;
9167    }
9168  }
9169
9170  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9171  //       ICSj(F2), or, if not that,
9172  if (HasBetterConversion)
9173    return true;
9174
9175  //   -- the context is an initialization by user-defined conversion
9176  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9177  //      from the return type of F1 to the destination type (i.e.,
9178  //      the type of the entity being initialized) is a better
9179  //      conversion sequence than the standard conversion sequence
9180  //      from the return type of F2 to the destination type.
9181  if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9182      Cand1.Function && Cand2.Function &&
9183      isa<CXXConversionDecl>(Cand1.Function) &&
9184      isa<CXXConversionDecl>(Cand2.Function)) {
9185    // First check whether we prefer one of the conversion functions over the
9186    // other. This only distinguishes the results in non-standard, extension
9187    // cases such as the conversion from a lambda closure type to a function
9188    // pointer or block.
9189    ImplicitConversionSequence::CompareKind Result =
9190        compareConversionFunctions(SCand1.FunctionCand2.Function);
9191    if (Result == ImplicitConversionSequence::Indistinguishable)
9192      Result = CompareStandardConversionSequences(SLoc,
9193                                                  Cand1.FinalConversion,
9194                                                  Cand2.FinalConversion);
9195
9196    if (Result != ImplicitConversionSequence::Indistinguishable)
9197      return Result == ImplicitConversionSequence::Better;
9198
9199    // FIXME: Compare kind of reference binding if conversion functions
9200    // convert to a reference type used in direct reference binding, per
9201    // C++14 [over.match.best]p1 section 2 bullet 3.
9202  }
9203
9204  // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9205  // as combined with the resolution to CWG issue 243.
9206  //
9207  // When the context is initialization by constructor ([over.match.ctor] or
9208  // either phase of [over.match.list]), a constructor is preferred over
9209  // a conversion function.
9210  if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9211      Cand1.Function && Cand2.Function &&
9212      isa<CXXConstructorDecl>(Cand1.Function) !=
9213          isa<CXXConstructorDecl>(Cand2.Function))
9214    return isa<CXXConstructorDecl>(Cand1.Function);
9215
9216  //    -- F1 is a non-template function and F2 is a function template
9217  //       specialization, or, if not that,
9218  bool Cand1IsSpecialization = Cand1.Function &&
9219                               Cand1.Function->getPrimaryTemplate();
9220  bool Cand2IsSpecialization = Cand2.Function &&
9221                               Cand2.Function->getPrimaryTemplate();
9222  if (Cand1IsSpecialization != Cand2IsSpecialization)
9223    return Cand2IsSpecialization;
9224
9225  //   -- F1 and F2 are function template specializations, and the function
9226  //      template for F1 is more specialized than the template for F2
9227  //      according to the partial ordering rules described in 14.5.5.2, or,
9228  //      if not that,
9229  if (Cand1IsSpecialization && Cand2IsSpecialization) {
9230    if (FunctionTemplateDecl *BetterTemplate
9231          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9232                                         Cand2.Function->getPrimaryTemplate(),
9233                                         Loc,
9234                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9235                                                             : TPOC_Call,
9236                                         Cand1.ExplicitCallArguments,
9237                                         Cand2.ExplicitCallArguments))
9238      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9239  }
9240
9241  // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9242  // A derived-class constructor beats an (inherited) base class constructor.
9243  bool Cand1IsInherited =
9244      dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9245  bool Cand2IsInherited =
9246      dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9247  if (Cand1IsInherited != Cand2IsInherited)
9248    return Cand2IsInherited;
9249  else if (Cand1IsInherited) {
9250    assert(Cand2IsInherited);
9251    auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9252    auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9253    if (Cand1Class->isDerivedFrom(Cand2Class))
9254      return true;
9255    if (Cand2Class->isDerivedFrom(Cand1Class))
9256      return false;
9257    // Inherited from sibling base classes: still ambiguous.
9258  }
9259
9260  // Check C++17 tie-breakers for deduction guides.
9261  {
9262    auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9263    auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9264    if (Guide1 && Guide2) {
9265      //  -- F1 is generated from a deduction-guide and F2 is not
9266      if (Guide1->isImplicit() != Guide2->isImplicit())
9267        return Guide2->isImplicit();
9268
9269      //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9270      if (Guide1->isCopyDeductionCandidate())
9271        return true;
9272    }
9273  }
9274
9275  // Check for enable_if value-based overload resolution.
9276  if (Cand1.Function && Cand2.Function) {
9277    Comparison Cmp = compareEnableIfAttrs(SCand1.FunctionCand2.Function);
9278    if (Cmp != Comparison::Equal)
9279      return Cmp == Comparison::Better;
9280  }
9281
9282  if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9283    FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9284    return S.IdentifyCUDAPreference(CallerCand1.Function) >
9285           S.IdentifyCUDAPreference(CallerCand2.Function);
9286  }
9287
9288  bool HasPS1 = Cand1.Function != nullptr &&
9289                functionHasPassObjectSizeParams(Cand1.Function);
9290  bool HasPS2 = Cand2.Function != nullptr &&
9291                functionHasPassObjectSizeParams(Cand2.Function);
9292  if (HasPS1 != HasPS2 && HasPS1)
9293    return true;
9294
9295  return isBetterMultiversionCandidate(Cand1Cand2);
9296}
9297
9298/// Determine whether two declarations are "equivalent" for the purposes of
9299/// name lookup and overload resolution. This applies when the same internal/no
9300/// linkage entity is defined by two modules (probably by textually including
9301/// the same header). In such a case, we don't consider the declarations to
9302/// declare the same entity, but we also don't want lookups with both
9303/// declarations visible to be ambiguous in some cases (this happens when using
9304/// a modularized libstdc++).
9305bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9306                                                  const NamedDecl *B) {
9307  auto *VA = dyn_cast_or_null<ValueDecl>(A);
9308  auto *VB = dyn_cast_or_null<ValueDecl>(B);
9309  if (!VA || !VB)
9310    return false;
9311
9312  // The declarations must be declaring the same name as an internal linkage
9313  // entity in different modules.
9314  if (!VA->getDeclContext()->getRedeclContext()->Equals(
9315          VB->getDeclContext()->getRedeclContext()) ||
9316      getOwningModule(const_cast<ValueDecl *>(VA)) ==
9317          getOwningModule(const_cast<ValueDecl *>(VB)) ||
9318      VA->isExternallyVisible() || VB->isExternallyVisible())
9319    return false;
9320
9321  // Check that the declarations appear to be equivalent.
9322  //
9323  // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9324  // For constants and functions, we should check the initializer or body is
9325  // the same. For non-constant variables, we shouldn't allow it at all.
9326  if (Context.hasSameType(VA->getType(), VB->getType()))
9327    return true;
9328
9329  // Enum constants within unnamed enumerations will have different types, but
9330  // may still be similar enough to be interchangeable for our purposes.
9331  if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9332    if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9333      // Only handle anonymous enums. If the enumerations were named and
9334      // equivalent, they would have been merged to the same type.
9335      auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9336      auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9337      if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9338          !Context.hasSameType(EnumA->getIntegerType(),
9339                               EnumB->getIntegerType()))
9340        return false;
9341      // Allow this only if the value is the same for both enumerators.
9342      return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9343    }
9344  }
9345
9346  // Nothing else is sufficiently similar.
9347  return false;
9348}
9349
9350void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9351    SourceLocation Locconst NamedDecl *DArrayRef<const NamedDecl *> Equiv) {
9352  Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9353
9354  Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9355  Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9356      << !M << (M ? M->getFullModuleName() : "");
9357
9358  for (auto *E : Equiv) {
9359    Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9360    Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9361        << !M << (M ? M->getFullModuleName() : "");
9362  }
9363}
9364
9365/// Computes the best viable function (C++ 13.3.3)
9366/// within an overload candidate set.
9367///
9368/// \param Loc The location of the function name (or operator symbol) for
9369/// which overload resolution occurs.
9370///
9371/// \param Best If overload resolution was successful or found a deleted
9372/// function, \p Best points to the candidate function found.
9373///
9374/// \returns The result of overload resolution.
9375OverloadingResult
9376OverloadCandidateSet::BestViableFunction(Sema &SSourceLocation Loc,
9377                                         iterator &Best) {
9378  llvm::SmallVector<OverloadCandidate *, 16Candidates;
9379  std::transform(begin(), end(), std::back_inserter(Candidates),
9380                 [](OverloadCandidate &Cand) { return &Cand; });
9381
9382  // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9383  // are accepted by both clang and NVCC. However, during a particular
9384  // compilation mode only one call variant is viable. We need to
9385  // exclude non-viable overload candidates from consideration based
9386  // only on their host/device attributes. Specifically, if one
9387  // candidate call is WrongSide and the other is SameSide, we ignore
9388  // the WrongSide candidate.
9389  if (S.getLangOpts().CUDA) {
9390    const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9391    bool ContainsSameSideCandidate =
9392        llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9393          return Cand->Function &&
9394                 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9395                     Sema::CFP_SameSide;
9396        });
9397    if (ContainsSameSideCandidate) {
9398      auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9399        return Cand->Function &&
9400               S.IdentifyCUDAPreference(CallerCand->Function) ==
9401                   Sema::CFP_WrongSide;
9402      };
9403      llvm::erase_if(Candidates, IsWrongSideCandidate);
9404    }
9405  }
9406
9407  // Find the best viable function.
9408  Best = end();
9409  for (auto *Cand : Candidates)
9410    if (Cand->Viable)
9411      if (Best == end() ||
9412          isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9413        Best = Cand;
9414
9415  // If we didn't find any viable functions, abort.
9416  if (Best == end())
9417    return OR_No_Viable_Function;
9418
9419  llvm::SmallVector<const NamedDecl *, 4EquivalentCands;
9420
9421  // Make sure that this function is better than every other viable
9422  // function. If not, we have an ambiguity.
9423  for (auto *Cand : Candidates) {
9424    if (Cand->Viable && Cand != Best &&
9425        !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9426      if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9427                                                   Cand->Function)) {
9428        EquivalentCands.push_back(Cand->Function);
9429        continue;
9430      }
9431
9432      Best = end();
9433      return OR_Ambiguous;
9434    }
9435  }
9436
9437  // Best is the best viable function.
9438  if (Best->Function && Best->Function->isDeleted())
9439    return OR_Deleted;
9440
9441  if (!EquivalentCands.empty())
9442    S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9443                                                    EquivalentCands);
9444
9445  return OR_Success;
9446}
9447
9448namespace {
9449
9450enum OverloadCandidateKind {
9451  oc_function,
9452  oc_method,
9453  oc_constructor,
9454  oc_implicit_default_constructor,
9455  oc_implicit_copy_constructor,
9456  oc_implicit_move_constructor,
9457  oc_implicit_copy_assignment,
9458  oc_implicit_move_assignment,
9459  oc_inherited_constructor
9460};
9461
9462enum OverloadCandidateSelect {
9463  ocs_non_template,
9464  ocs_template,
9465  ocs_described_template,
9466};
9467
9468static std::pair<OverloadCandidateKindOverloadCandidateSelect>
9469ClassifyOverloadCandidate(Sema &SNamedDecl *FoundFunctionDecl *Fn,
9470                          std::string &Description) {
9471
9472  bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9473  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9474    isTemplate = true;
9475    Description = S.getTemplateArgumentBindingsText(
9476        FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9477  }
9478
9479  OverloadCandidateSelect Select = [&]() {
9480    if (!Description.empty())
9481      return ocs_described_template;
9482    return isTemplate ? ocs_template : ocs_non_template;
9483  }();
9484
9485  OverloadCandidateKind Kind = [&]() {
9486    if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9487      if (!Ctor->isImplicit()) {
9488        if (isa<ConstructorUsingShadowDecl>(Found))
9489          return oc_inherited_constructor;
9490        else
9491          return oc_constructor;
9492      }
9493
9494      if (Ctor->isDefaultConstructor())
9495        return oc_implicit_default_constructor;
9496
9497      if (Ctor->isMoveConstructor())
9498        return oc_implicit_move_constructor;
9499
9500       (0) . __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9501, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Ctor->isCopyConstructor() &&
9501 (0) . __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9501, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "unexpected sort of implicit constructor");
9502      return oc_implicit_copy_constructor;
9503    }
9504
9505    if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9506      // This actually gets spelled 'candidate function' for now, but
9507      // it doesn't hurt to split it out.
9508      if (!Meth->isImplicit())
9509        return oc_method;
9510
9511      if (Meth->isMoveAssignmentOperator())
9512        return oc_implicit_move_assignment;
9513
9514      if (Meth->isCopyAssignmentOperator())
9515        return oc_implicit_copy_assignment;
9516
9517       (0) . __assert_fail ("isa(Meth) && \"expected conversion\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9517, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9518      return oc_method;
9519    }
9520
9521    return oc_function;
9522  }();
9523
9524  return std::make_pair(KindSelect);
9525}
9526
9527void MaybeEmitInheritedConstructorNote(Sema &SDecl *FoundDecl) {
9528  // FIXME: It'd be nice to only emit a note once per using-decl per overload
9529  // set.
9530  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9531    S.Diag(FoundDecl->getLocation(),
9532           diag::note_ovl_candidate_inherited_constructor)
9533      << Shadow->getNominatedBaseClass();
9534}
9535
9536// end anonymous namespace
9537
9538static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9539                                    const FunctionDecl *FD) {
9540  for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9541    bool AlwaysTrue;
9542    if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9543      return false;
9544    if (!AlwaysTrue)
9545      return false;
9546  }
9547  return true;
9548}
9549
9550/// Returns true if we can take the address of the function.
9551///
9552/// \param Complain - If true, we'll emit a diagnostic
9553/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9554///   we in overload resolution?
9555/// \param Loc - The location of the statement we're complaining about. Ignored
9556///   if we're not complaining, or if we're in overload resolution.
9557static bool checkAddressOfFunctionIsAvailable(Sema &Sconst FunctionDecl *FD,
9558                                              bool Complain,
9559                                              bool InOverloadResolution,
9560                                              SourceLocation Loc) {
9561  if (!isFunctionAlwaysEnabled(S.ContextFD)) {
9562    if (Complain) {
9563      if (InOverloadResolution)
9564        S.Diag(FD->getBeginLoc(),
9565               diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9566      else
9567        S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9568    }
9569    return false;
9570  }
9571
9572  auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9573    return P->hasAttr<PassObjectSizeAttr>();
9574  });
9575  if (I == FD->param_end())
9576    return true;
9577
9578  if (Complain) {
9579    // Add one to ParamNo because it's user-facing
9580    unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9581    if (InOverloadResolution)
9582      S.Diag(FD->getLocation(),
9583             diag::note_ovl_candidate_has_pass_object_size_params)
9584          << ParamNo;
9585    else
9586      S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9587          << FD << ParamNo;
9588  }
9589  return false;
9590}
9591
9592static bool checkAddressOfCandidateIsAvailable(Sema &S,
9593                                               const FunctionDecl *FD) {
9594  return checkAddressOfFunctionIsAvailable(SFD/*Complain=*/true,
9595                                           /*InOverloadResolution=*/true,
9596                                           /*Loc=*/SourceLocation());
9597}
9598
9599bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9600                                             bool Complain,
9601                                             SourceLocation Loc) {
9602  return ::checkAddressOfFunctionIsAvailable(*thisFunctionComplain,
9603                                             /*InOverloadResolution=*/false,
9604                                             Loc);
9605}
9606
9607// Notes the location of an overload candidate.
9608void Sema::NoteOverloadCandidate(NamedDecl *FoundFunctionDecl *Fn,
9609                                 QualType DestTypebool TakingAddress) {
9610  if (TakingAddress && !checkAddressOfCandidateIsAvailable(*thisFn))
9611    return;
9612  if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9613      !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9614    return;
9615
9616  std::string FnDesc;
9617  std::pair<OverloadCandidateKindOverloadCandidateSelectKSPair =
9618      ClassifyOverloadCandidate(*thisFoundFnFnDesc);
9619  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9620                         << (unsigned)KSPair.first << (unsigned)KSPair.second
9621                         << Fn << FnDesc;
9622
9623  HandleFunctionTypeMismatch(PDFn->getType(), DestType);
9624  Diag(Fn->getLocation(), PD);
9625  MaybeEmitInheritedConstructorNote(*thisFound);
9626}
9627
9628// Notes the location of all overload candidates designated through
9629// OverloadedExpr
9630void Sema::NoteAllOverloadCandidates(Expr *OverloadedExprQualType DestType,
9631                                     bool TakingAddress) {
9632  getType() == Context.OverloadTy", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9632, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(OverloadedExpr->getType() == Context.OverloadTy);
9633
9634  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9635  OverloadExpr *OvlExpr = Ovl.Expression;
9636
9637  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9638                            IEnd = OvlExpr->decls_end();
9639       I != IEnd; ++I) {
9640    if (FunctionTemplateDecl *FunTmpl =
9641                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9642      NoteOverloadCandidate(*IFunTmpl->getTemplatedDecl(), DestType,
9643                            TakingAddress);
9644    } else if (FunctionDecl *Fun
9645                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9646      NoteOverloadCandidate(*IFunDestTypeTakingAddress);
9647    }
9648  }
9649}
9650
9651/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9652/// "lead" diagnostic; it will be given two arguments, the source and
9653/// target types of the conversion.
9654void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9655                                 Sema &S,
9656                                 SourceLocation CaretLoc,
9657                                 const PartialDiagnostic &PDiagconst {
9658  S.Diag(CaretLoc, PDiag)
9659    << Ambiguous.getFromType() << Ambiguous.getToType();
9660  // FIXME: The note limiting machinery is borrowed from
9661  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9662  // refactoring here.
9663  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9664  unsigned CandsShown = 0;
9665  AmbiguousConversionSequence::const_iterator I, E;
9666  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9667    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9668      break;
9669    ++CandsShown;
9670    S.NoteOverloadCandidate(I->first, I->second);
9671  }
9672  if (I != E)
9673    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9674}
9675
9676static void DiagnoseBadConversion(Sema &SOverloadCandidate *Cand,
9677                                  unsigned Ibool TakingCandidateAddress) {
9678  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9679  assert(Conv.isBad());
9680   (0) . __assert_fail ("Cand->Function && \"for now, candidate must be a function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9680, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Cand->Function && "for now, candidate must be a function");
9681  FunctionDecl *Fn = Cand->Function;
9682
9683  // There's a conversion slot for the object argument if this is a
9684  // non-constructor method.  Note that 'I' corresponds the
9685  // conversion-slot index.
9686  bool isObjectArgument = false;
9687  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9688    if (I == 0)
9689      isObjectArgument = true;
9690    else
9691      I--;
9692  }
9693
9694  std::string FnDesc;
9695  std::pair<OverloadCandidateKindOverloadCandidateSelectFnKindPair =
9696      ClassifyOverloadCandidate(SCand->FoundDeclFnFnDesc);
9697
9698  Expr *FromExpr = Conv.Bad.FromExpr;
9699  QualType FromTy = Conv.Bad.getFromType();
9700  QualType ToTy = Conv.Bad.getToType();
9701
9702  if (FromTy == S.Context.OverloadTy) {
9703     (0) . __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9703, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FromExpr && "overload set argument came from implicit argument?");
9704    Expr *E = FromExpr->IgnoreParens();
9705    if (isa<UnaryOperator>(E))
9706      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9707    DeclarationName Name = cast<OverloadExpr>(E)->getName();
9708
9709    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9710        << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9711        << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9712        << Name << I + 1;
9713    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9714    return;
9715  }
9716
9717  // Do some hand-waving analysis to see if the non-viability is due
9718  // to a qualifier mismatch.
9719  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9720  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9721  if (CanQual<ReferenceTypeRT = CToTy->getAs<ReferenceType>())
9722    CToTy = RT->getPointeeType();
9723  else {
9724    // TODO: detect and diagnose the full richness of const mismatches.
9725    if (CanQual<PointerTypeFromPT = CFromTy->getAs<PointerType>())
9726      if (CanQual<PointerTypeToPT = CToTy->getAs<PointerType>()) {
9727        CFromTy = FromPT->getPointeeType();
9728        CToTy = ToPT->getPointeeType();
9729      }
9730  }
9731
9732  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9733      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9734    Qualifiers FromQs = CFromTy.getQualifiers();
9735    Qualifiers ToQs = CToTy.getQualifiers();
9736
9737    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9738      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9739          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9740          << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9741          << ToTy << (unsigned)isObjectArgument << I + 1;
9742      MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9743      return;
9744    }
9745
9746    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9747      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9748          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9749          << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9750          << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9751          << (unsigned)isObjectArgument << I + 1;
9752      MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9753      return;
9754    }
9755
9756    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9757      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9758          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9759          << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9760          << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9761          << (unsigned)isObjectArgument << I + 1;
9762      MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9763      return;
9764    }
9765
9766    if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9767      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9768          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9769          << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9770          << FromQs.hasUnaligned() << I + 1;
9771      MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9772      return;
9773    }
9774
9775    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9776     (0) . __assert_fail ("CVR && \"unexpected qualifiers mismatch\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9776, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CVR && "unexpected qualifiers mismatch");
9777
9778    if (isObjectArgument) {
9779      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9780          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9781          << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9782          << (CVR - 1);
9783    } else {
9784      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9785          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9786          << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9787          << (CVR - 1) << I + 1;
9788    }
9789    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9790    return;
9791  }
9792
9793  // Special diagnostic for failure to convert an initializer list, since
9794  // telling the user that it has type void is not useful.
9795  if (FromExpr && isa<InitListExpr>(FromExpr)) {
9796    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9797        << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9798        << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9799        << ToTy << (unsigned)isObjectArgument << I + 1;
9800    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9801    return;
9802  }
9803
9804  // Diagnose references or pointers to incomplete types differently,
9805  // since it's far from impossible that the incompleteness triggered
9806  // the failure.
9807  QualType TempFromTy = FromTy.getNonReferenceType();
9808  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9809    TempFromTy = PTy->getPointeeType();
9810  if (TempFromTy->isIncompleteType()) {
9811    // Emit the generic diagnostic and, optionally, add the hints to it.
9812    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9813        << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9814        << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9815        << ToTy << (unsigned)isObjectArgument << I + 1
9816        << (unsigned)(Cand->Fix.Kind);
9817
9818    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9819    return;
9820  }
9821
9822  // Diagnose base -> derived pointer conversions.
9823  unsigned BaseToDerivedConversion = 0;
9824  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9825    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9826      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9827                                               FromPtrTy->getPointeeType()) &&
9828          !FromPtrTy->getPointeeType()->isIncompleteType() &&
9829          !ToPtrTy->getPointeeType()->isIncompleteType() &&
9830          S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9831                          FromPtrTy->getPointeeType()))
9832        BaseToDerivedConversion = 1;
9833    }
9834  } else if (const ObjCObjectPointerType *FromPtrTy
9835                                    = FromTy->getAs<ObjCObjectPointerType>()) {
9836    if (const ObjCObjectPointerType *ToPtrTy
9837                                        = ToTy->getAs<ObjCObjectPointerType>())
9838      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9839        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9840          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9841                                                FromPtrTy->getPointeeType()) &&
9842              FromIface->isSuperClassOf(ToIface))
9843            BaseToDerivedConversion = 2;
9844  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9845    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9846        !FromTy->isIncompleteType() &&
9847        !ToRefTy->getPointeeType()->isIncompleteType() &&
9848        S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9849      BaseToDerivedConversion = 3;
9850    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9851               ToTy.getNonReferenceType().getCanonicalType() ==
9852               FromTy.getNonReferenceType().getCanonicalType()) {
9853      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9854          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9855          << (unsigned)isObjectArgument << I + 1
9856          << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9857      MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9858      return;
9859    }
9860  }
9861
9862  if (BaseToDerivedConversion) {
9863    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9864        << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9865        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9866        << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9867    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9868    return;
9869  }
9870
9871  if (isa<ObjCObjectPointerType>(CFromTy) &&
9872      isa<PointerType>(CToTy)) {
9873      Qualifiers FromQs = CFromTy.getQualifiers();
9874      Qualifiers ToQs = CToTy.getQualifiers();
9875      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9876        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9877            << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9878            << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9879            << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9880        MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9881        return;
9882      }
9883  }
9884
9885  if (TakingCandidateAddress &&
9886      !checkAddressOfCandidateIsAvailable(SCand->Function))
9887    return;
9888
9889  // Emit the generic diagnostic and, optionally, add the hints to it.
9890  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9891  FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9892        << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9893        << ToTy << (unsigned)isObjectArgument << I + 1
9894        << (unsigned)(Cand->Fix.Kind);
9895
9896  // If we can fix the conversion, suggest the FixIts.
9897  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9898       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9899    FDiag << *HI;
9900  S.Diag(Fn->getLocation(), FDiag);
9901
9902  MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
9903}
9904
9905/// Additional arity mismatch diagnosis specific to a function overload
9906/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9907/// over a candidate in any candidate set.
9908static bool CheckArityMismatch(Sema &SOverloadCandidate *Cand,
9909                               unsigned NumArgs) {
9910  FunctionDecl *Fn = Cand->Function;
9911  unsigned MinParams = Fn->getMinRequiredArguments();
9912
9913  // With invalid overloaded operators, it's possible that we think we
9914  // have an arity mismatch when in fact it looks like we have the
9915  // right number of arguments, because only overloaded operators have
9916  // the weird behavior of overloading member and non-member functions.
9917  // Just don't report anything.
9918  if (Fn->isInvalidDecl() &&
9919      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9920    return true;
9921
9922  if (NumArgs < MinParams) {
9923    FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema..TDK_TooFewArguments)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9925, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9924FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema..TDK_TooFewArguments)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9925, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           (Cand->FailureKind == ovl_fail_bad_deduction &&
9925FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema..TDK_TooFewArguments)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9925, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9926  } else {
9927    FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema..TDK_TooManyArguments)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9929, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9928FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema..TDK_TooManyArguments)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9929, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           (Cand->FailureKind == ovl_fail_bad_deduction &&
9929FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema..TDK_TooManyArguments)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9929, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9930  }
9931
9932  return false;
9933}
9934
9935/// General arity mismatch diagnosis over a candidate in a candidate set.
9936static void DiagnoseArityMismatch(Sema &SNamedDecl *FoundDecl *D,
9937                                  unsigned NumFormalArgs) {
9938   (0) . __assert_fail ("isa(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9941, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<FunctionDecl>(D) &&
9939 (0) . __assert_fail ("isa(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9941, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">      "The templated declaration should at least be a function"
9940 (0) . __assert_fail ("isa(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9941, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">      " when diagnosing bad template argument deduction due to too many"
9941 (0) . __assert_fail ("isa(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 9941, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">      " or too few arguments");
9942
9943  FunctionDecl *Fn = cast<FunctionDecl>(D);
9944
9945  // TODO: treat calls to a missing default constructor as a special case
9946  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9947  unsigned MinParams = Fn->getMinRequiredArguments();
9948
9949  // at least / at most / exactly
9950  unsigned modemodeCount;
9951  if (NumFormalArgs < MinParams) {
9952    if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9953        FnTy->isTemplateVariadic())
9954      mode = 0// "at least"
9955    else
9956      mode = 2// "exactly"
9957    modeCount = MinParams;
9958  } else {
9959    if (MinParams != FnTy->getNumParams())
9960      mode = 1// "at most"
9961    else
9962      mode = 2// "exactly"
9963    modeCount = FnTy->getNumParams();
9964  }
9965
9966  std::string Description;
9967  std::pair<OverloadCandidateKindOverloadCandidateSelectFnKindPair =
9968      ClassifyOverloadCandidate(SFoundFnDescription);
9969
9970  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9971    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9972        << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9973        << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9974  else
9975    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9976        << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9977        << Description << mode << modeCount << NumFormalArgs;
9978
9979  MaybeEmitInheritedConstructorNote(SFound);
9980}
9981
9982/// Arity mismatch diagnosis specific to a function overload candidate.
9983static void DiagnoseArityMismatch(Sema &SOverloadCandidate *Cand,
9984                                  unsigned NumFormalArgs) {
9985  if (!CheckArityMismatch(SCandNumFormalArgs))
9986    DiagnoseArityMismatch(SCand->FoundDeclCand->FunctionNumFormalArgs);
9987}
9988
9989static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9990  if (TemplateDecl *TD = Templated->getDescribedTemplate())
9991    return TD;
9992  llvm_unreachable("Unsupported: Getting the described template declaration"
9993                   " for bad deduction diagnosis");
9994}
9995
9996/// Diagnose a failed template-argument deduction.
9997static void DiagnoseBadDeduction(Sema &SNamedDecl *FoundDecl *Templated,
9998                                 DeductionFailureInfo &DeductionFailure,
9999                                 unsigned NumArgs,
10000                                 bool TakingCandidateAddress) {
10001  TemplateParameter Param = DeductionFailure.getTemplateParameter();
10002  NamedDecl *ParamD;
10003  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10004  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10005  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10006  switch (DeductionFailure.Result) {
10007  case Sema::TDK_Success:
10008    llvm_unreachable("TDK_success while diagnosing bad deduction");
10009
10010  case Sema::TDK_Incomplete: {
10011     (0) . __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10011, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ParamD && "no parameter found for incomplete deduction result");
10012    S.Diag(Templated->getLocation(),
10013           diag::note_ovl_candidate_incomplete_deduction)
10014        << ParamD->getDeclName();
10015    MaybeEmitInheritedConstructorNote(SFound);
10016    return;
10017  }
10018
10019  case Sema::TDK_IncompletePack: {
10020     (0) . __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10020, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ParamD && "no parameter found for incomplete deduction result");
10021    S.Diag(Templated->getLocation(),
10022           diag::note_ovl_candidate_incomplete_deduction_pack)
10023        << ParamD->getDeclName()
10024        << (DeductionFailure.getFirstArg()->pack_size() + 1)
10025        << *DeductionFailure.getFirstArg();
10026    MaybeEmitInheritedConstructorNote(SFound);
10027    return;
10028  }
10029
10030  case Sema::TDK_Underqualified: {
10031     (0) . __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10031, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ParamD && "no parameter found for bad qualifiers deduction result");
10032    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10033
10034    QualType Param = DeductionFailure.getFirstArg()->getAsType();
10035
10036    // Param will have been canonicalized, but it should just be a
10037    // qualified version of ParamD, so move the qualifiers to that.
10038    QualifierCollector Qs;
10039    Qs.strip(Param);
10040    QualType NonCanonParam = Qs.apply(S.ContextTParam->getTypeForDecl());
10041    assert(S.Context.hasSameType(Param, NonCanonParam));
10042
10043    // Arg has also been canonicalized, but there's nothing we can do
10044    // about that.  It also doesn't matter as much, because it won't
10045    // have any template parameters in it (because deduction isn't
10046    // done on dependent types).
10047    QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10048
10049    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10050        << ParamD->getDeclName() << Arg << NonCanonParam;
10051    MaybeEmitInheritedConstructorNote(SFound);
10052    return;
10053  }
10054
10055  case Sema::TDK_Inconsistent: {
10056     (0) . __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10056, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ParamD && "no parameter found for inconsistent deduction result");
10057    int which = 0;
10058    if (isa<TemplateTypeParmDecl>(ParamD))
10059      which = 0;
10060    else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10061      // Deduction might have failed because we deduced arguments of two
10062      // different types for a non-type template parameter.
10063      // FIXME: Use a different TDK value for this.
10064      QualType T1 =
10065          DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10066      QualType T2 =
10067          DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10068      if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1T2)) {
10069        S.Diag(Templated->getLocation(),
10070               diag::note_ovl_candidate_inconsistent_deduction_types)
10071          << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10072          << *DeductionFailure.getSecondArg() << T2;
10073        MaybeEmitInheritedConstructorNote(SFound);
10074        return;
10075      }
10076
10077      which = 1;
10078    } else {
10079      which = 2;
10080    }
10081
10082    S.Diag(Templated->getLocation(),
10083           diag::note_ovl_candidate_inconsistent_deduction)
10084        << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10085        << *DeductionFailure.getSecondArg();
10086    MaybeEmitInheritedConstructorNote(SFound);
10087    return;
10088  }
10089
10090  case Sema::TDK_InvalidExplicitArguments:
10091     (0) . __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10091, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ParamD && "no parameter found for invalid explicit arguments");
10092    if (ParamD->getDeclName())
10093      S.Diag(Templated->getLocation(),
10094             diag::note_ovl_candidate_explicit_arg_mismatch_named)
10095          << ParamD->getDeclName();
10096    else {
10097      int index = 0;
10098      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10099        index = TTP->getIndex();
10100      else if (NonTypeTemplateParmDecl *NTTP
10101                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10102        index = NTTP->getIndex();
10103      else
10104        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10105      S.Diag(Templated->getLocation(),
10106             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10107          << (index + 1);
10108    }
10109    MaybeEmitInheritedConstructorNote(SFound);
10110    return;
10111
10112  case Sema::TDK_TooManyArguments:
10113  case Sema::TDK_TooFewArguments:
10114    DiagnoseArityMismatch(SFoundTemplatedNumArgs);
10115    return;
10116
10117  case Sema::TDK_InstantiationDepth:
10118    S.Diag(Templated->getLocation(),
10119           diag::note_ovl_candidate_instantiation_depth);
10120    MaybeEmitInheritedConstructorNote(SFound);
10121    return;
10122
10123  case Sema::TDK_SubstitutionFailure: {
10124    // Format the template argument list into the argument string.
10125    SmallString<128TemplateArgString;
10126    if (TemplateArgumentList *Args =
10127            DeductionFailure.getTemplateArgumentList()) {
10128      TemplateArgString = " ";
10129      TemplateArgString += S.getTemplateArgumentBindingsText(
10130          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10131    }
10132
10133    // If this candidate was disabled by enable_if, say so.
10134    PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10135    if (PDiag && PDiag->second.getDiagID() ==
10136          diag::err_typename_nested_not_found_enable_if) {
10137      // FIXME: Use the source range of the condition, and the fully-qualified
10138      //        name of the enable_if template. These are both present in PDiag.
10139      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10140        << "'enable_if'" << TemplateArgString;
10141      return;
10142    }
10143
10144    // We found a specific requirement that disabled the enable_if.
10145    if (PDiag && PDiag->second.getDiagID() ==
10146        diag::err_typename_nested_not_found_requirement) {
10147      S.Diag(Templated->getLocation(),
10148             diag::note_ovl_candidate_disabled_by_requirement)
10149        << PDiag->second.getStringArg(0) << TemplateArgString;
10150      return;
10151    }
10152
10153    // Format the SFINAE diagnostic into the argument string.
10154    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10155    //        formatted message in another diagnostic.
10156    SmallString<128SFINAEArgString;
10157    SourceRange R;
10158    if (PDiag) {
10159      SFINAEArgString = ": ";
10160      R = SourceRange(PDiag->firstPDiag->first);
10161      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10162    }
10163
10164    S.Diag(Templated->getLocation(),
10165           diag::note_ovl_candidate_substitution_failure)
10166        << TemplateArgString << SFINAEArgString << R;
10167    MaybeEmitInheritedConstructorNote(SFound);
10168    return;
10169  }
10170
10171  case Sema::TDK_DeducedMismatch:
10172  case Sema::TDK_DeducedMismatchNested: {
10173    // Format the template argument list into the argument string.
10174    SmallString<128TemplateArgString;
10175    if (TemplateArgumentList *Args =
10176            DeductionFailure.getTemplateArgumentList()) {
10177      TemplateArgString = " ";
10178      TemplateArgString += S.getTemplateArgumentBindingsText(
10179          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10180    }
10181
10182    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10183        << (*DeductionFailure.getCallArgIndex() + 1)
10184        << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10185        << TemplateArgString
10186        << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10187    break;
10188  }
10189
10190  case Sema::TDK_NonDeducedMismatch: {
10191    // FIXME: Provide a source location to indicate what we couldn't match.
10192    TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10193    TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10194    if (FirstTA.getKind() == TemplateArgument::Template &&
10195        SecondTA.getKind() == TemplateArgument::Template) {
10196      TemplateName FirstTN = FirstTA.getAsTemplate();
10197      TemplateName SecondTN = SecondTA.getAsTemplate();
10198      if (FirstTN.getKind() == TemplateName::Template &&
10199          SecondTN.getKind() == TemplateName::Template) {
10200        if (FirstTN.getAsTemplateDecl()->getName() ==
10201            SecondTN.getAsTemplateDecl()->getName()) {
10202          // FIXME: This fixes a bad diagnostic where both templates are named
10203          // the same.  This particular case is a bit difficult since:
10204          // 1) It is passed as a string to the diagnostic printer.
10205          // 2) The diagnostic printer only attempts to find a better
10206          //    name for types, not decls.
10207          // Ideally, this should folded into the diagnostic printer.
10208          S.Diag(Templated->getLocation(),
10209                 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10210              << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10211          return;
10212        }
10213      }
10214    }
10215
10216    if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10217        !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10218      return;
10219
10220    // FIXME: For generic lambda parameters, check if the function is a lambda
10221    // call operator, and if so, emit a prettier and more informative
10222    // diagnostic that mentions 'auto' and lambda in addition to
10223    // (or instead of?) the canonical template type parameters.
10224    S.Diag(Templated->getLocation(),
10225           diag::note_ovl_candidate_non_deduced_mismatch)
10226        << FirstTA << SecondTA;
10227    return;
10228  }
10229  // TODO: diagnose these individually, then kill off
10230  // note_ovl_candidate_bad_deduction, which is uselessly vague.
10231  case Sema::TDK_MiscellaneousDeductionFailure:
10232    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10233    MaybeEmitInheritedConstructorNote(SFound);
10234    return;
10235  case Sema::TDK_CUDATargetMismatch:
10236    S.Diag(Templated->getLocation(),
10237           diag::note_cuda_ovl_candidate_target_mismatch);
10238    return;
10239  }
10240}
10241
10242/// Diagnose a failed template-argument deduction, for function calls.
10243static void DiagnoseBadDeduction(Sema &SOverloadCandidate *Cand,
10244                                 unsigned NumArgs,
10245                                 bool TakingCandidateAddress) {
10246  unsigned TDK = Cand->DeductionFailure.Result;
10247  if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10248    if (CheckArityMismatch(SCandNumArgs))
10249      return;
10250  }
10251  DiagnoseBadDeduction(SCand->FoundDeclCand->Function// pattern
10252                       Cand->DeductionFailureNumArgsTakingCandidateAddress);
10253}
10254
10255/// CUDA: diagnose an invalid call across targets.
10256static void DiagnoseBadTarget(Sema &SOverloadCandidate *Cand) {
10257  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10258  FunctionDecl *Callee = Cand->Function;
10259
10260  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10261                           CalleeTarget = S.IdentifyCUDATarget(Callee);
10262
10263  std::string FnDesc;
10264  std::pair<OverloadCandidateKindOverloadCandidateSelectFnKindPair =
10265      ClassifyOverloadCandidate(SCand->FoundDeclCalleeFnDesc);
10266
10267  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10268      << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10269      << FnDesc /* Ignored */
10270      << CalleeTarget << CallerTarget;
10271
10272  // This could be an implicit constructor for which we could not infer the
10273  // target due to a collsion. Diagnose that case.
10274  CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10275  if (Meth != nullptr && Meth->isImplicit()) {
10276    CXXRecordDecl *ParentClass = Meth->getParent();
10277    Sema::CXXSpecialMember CSM;
10278
10279    switch (FnKindPair.first) {
10280    default:
10281      return;
10282    case oc_implicit_default_constructor:
10283      CSM = Sema::CXXDefaultConstructor;
10284      break;
10285    case oc_implicit_copy_constructor:
10286      CSM = Sema::CXXCopyConstructor;
10287      break;
10288    case oc_implicit_move_constructor:
10289      CSM = Sema::CXXMoveConstructor;
10290      break;
10291    case oc_implicit_copy_assignment:
10292      CSM = Sema::CXXCopyAssignment;
10293      break;
10294    case oc_implicit_move_assignment:
10295      CSM = Sema::CXXMoveAssignment;
10296      break;
10297    };
10298
10299    bool ConstRHS = false;
10300    if (Meth->getNumParams()) {
10301      if (const ReferenceType *RT =
10302              Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10303        ConstRHS = RT->getPointeeType().isConstQualified();
10304      }
10305    }
10306
10307    S.inferCUDATargetForImplicitSpecialMember(ParentClassCSMMeth,
10308                                              /* ConstRHS */ ConstRHS,
10309                                              /* Diagnose */ true);
10310  }
10311}
10312
10313static void DiagnoseFailedEnableIfAttr(Sema &SOverloadCandidate *Cand) {
10314  FunctionDecl *Callee = Cand->Function;
10315  EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10316
10317  S.Diag(Callee->getLocation(),
10318         diag::note_ovl_candidate_disabled_by_function_cond_attr)
10319      << Attr->getCond()->getSourceRange() << Attr->getMessage();
10320}
10321
10322static void DiagnoseOpenCLExtensionDisabled(Sema &SOverloadCandidate *Cand) {
10323  FunctionDecl *Callee = Cand->Function;
10324
10325  S.Diag(Callee->getLocation(),
10326         diag::note_ovl_candidate_disabled_by_extension)
10327    << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10328}
10329
10330/// Generates a 'note' diagnostic for an overload candidate.  We've
10331/// already generated a primary error at the call site.
10332///
10333/// It really does need to be a single diagnostic with its caret
10334/// pointed at the candidate declaration.  Yes, this creates some
10335/// major challenges of technical writing.  Yes, this makes pointing
10336/// out problems with specific arguments quite awkward.  It's still
10337/// better than generating twenty screens of text for every failed
10338/// overload.
10339///
10340/// It would be great to be able to express per-candidate problems
10341/// more richly for those diagnostic clients that cared, but we'd
10342/// still have to be just as careful with the default diagnostics.
10343static void NoteFunctionCandidate(Sema &SOverloadCandidate *Cand,
10344                                  unsigned NumArgs,
10345                                  bool TakingCandidateAddress) {
10346  FunctionDecl *Fn = Cand->Function;
10347
10348  // Note deleted candidates, but only if they're viable.
10349  if (Cand->Viable) {
10350    if (Fn->isDeleted()) {
10351      std::string FnDesc;
10352      std::pair<OverloadCandidateKindOverloadCandidateSelectFnKindPair =
10353          ClassifyOverloadCandidate(SCand->FoundDeclFnFnDesc);
10354
10355      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10356          << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10357          << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10358      MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
10359      return;
10360    }
10361
10362    // We don't really have anything else to say about viable candidates.
10363    S.NoteOverloadCandidate(Cand->FoundDeclFn);
10364    return;
10365  }
10366
10367  switch (Cand->FailureKind) {
10368  case ovl_fail_too_many_arguments:
10369  case ovl_fail_too_few_arguments:
10370    return DiagnoseArityMismatch(SCandNumArgs);
10371
10372  case ovl_fail_bad_deduction:
10373    return DiagnoseBadDeduction(SCandNumArgs,
10374                                TakingCandidateAddress);
10375
10376  case ovl_fail_illegal_constructor: {
10377    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10378      << (Fn->getPrimaryTemplate() ? 1 : 0);
10379    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
10380    return;
10381  }
10382
10383  case ovl_fail_trivial_conversion:
10384  case ovl_fail_bad_final_conversion:
10385  case ovl_fail_final_conversion_not_exact:
10386    return S.NoteOverloadCandidate(Cand->FoundDeclFn);
10387
10388  case ovl_fail_bad_conversion: {
10389    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10390    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10391      if (Cand->Conversions[I].isBad())
10392        return DiagnoseBadConversion(SCandITakingCandidateAddress);
10393
10394    // FIXME: this currently happens when we're called from SemaInit
10395    // when user-conversion overload fails.  Figure out how to handle
10396    // those conditions and diagnose them well.
10397    return S.NoteOverloadCandidate(Cand->FoundDeclFn);
10398  }
10399
10400  case ovl_fail_bad_target:
10401    return DiagnoseBadTarget(SCand);
10402
10403  case ovl_fail_enable_if:
10404    return DiagnoseFailedEnableIfAttr(SCand);
10405
10406  case ovl_fail_ext_disabled:
10407    return DiagnoseOpenCLExtensionDisabled(SCand);
10408
10409  case ovl_fail_inhctor_slice:
10410    // It's generally not interesting to note copy/move constructors here.
10411    if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10412      return;
10413    S.Diag(Fn->getLocation(),
10414           diag::note_ovl_candidate_inherited_constructor_slice)
10415      << (Fn->getPrimaryTemplate() ? 1 : 0)
10416      << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10417    MaybeEmitInheritedConstructorNote(SCand->FoundDecl);
10418    return;
10419
10420  case ovl_fail_addr_not_available: {
10421    bool Available = checkAddressOfCandidateIsAvailable(SCand->Function);
10422    (void)Available;
10423    assert(!Available);
10424    break;
10425  }
10426  case ovl_non_default_multiversion_function:
10427    // Do nothing, these should simply be ignored.
10428    break;
10429  }
10430}
10431
10432static void NoteSurrogateCandidate(Sema &SOverloadCandidate *Cand) {
10433  // Desugar the type of the surrogate down to a function type,
10434  // retaining as many typedefs as possible while still showing
10435  // the function type (and, therefore, its parameter types).
10436  QualType FnType = Cand->Surrogate->getConversionType();
10437  bool isLValueReference = false;
10438  bool isRValueReference = false;
10439  bool isPointer = false;
10440  if (const LValueReferenceType *FnTypeRef =
10441        FnType->getAs<LValueReferenceType>()) {
10442    FnType = FnTypeRef->getPointeeType();
10443    isLValueReference = true;
10444  } else if (const RValueReferenceType *FnTypeRef =
10445               FnType->getAs<RValueReferenceType>()) {
10446    FnType = FnTypeRef->getPointeeType();
10447    isRValueReference = true;
10448  }
10449  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10450    FnType = FnTypePtr->getPointeeType();
10451    isPointer = true;
10452  }
10453  // Desugar down to a function type.
10454  FnType = QualType(FnType->getAs<FunctionType>(), 0);
10455  // Reconstruct the pointer/reference as appropriate.
10456  if (isPointerFnType = S.Context.getPointerType(FnType);
10457  if (isRValueReferenceFnType = S.Context.getRValueReferenceType(FnType);
10458  if (isLValueReferenceFnType = S.Context.getLValueReferenceType(FnType);
10459
10460  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10461    << FnType;
10462}
10463
10464static void NoteBuiltinOperatorCandidate(Sema &SStringRef Opc,
10465                                         SourceLocation OpLoc,
10466                                         OverloadCandidate *Cand) {
10467   (0) . __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10467, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10468  std::string TypeStr("operator");
10469  TypeStr += Opc;
10470  TypeStr += "(";
10471  TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10472  if (Cand->Conversions.size() == 1) {
10473    TypeStr += ")";
10474    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10475  } else {
10476    TypeStr += ", ";
10477    TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10478    TypeStr += ")";
10479    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10480  }
10481}
10482
10483static void NoteAmbiguousUserConversions(Sema &SSourceLocation OpLoc,
10484                                         OverloadCandidate *Cand) {
10485  for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10486    if (ICS.isBad()) break// all meaningless after first invalid
10487    if (!ICS.isAmbiguous()) continue;
10488
10489    ICS.DiagnoseAmbiguousConversion(
10490        S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10491  }
10492}
10493
10494static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10495  if (Cand->Function)
10496    return Cand->Function->getLocation();
10497  if (Cand->IsSurrogate)
10498    return Cand->Surrogate->getLocation();
10499  return SourceLocation();
10500}
10501
10502static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10503  switch ((Sema::TemplateDeductionResult)DFI.Result) {
10504  case Sema::TDK_Success:
10505  case Sema::TDK_NonDependentConversionFailure:
10506    llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10507
10508  case Sema::TDK_Invalid:
10509  case Sema::TDK_Incomplete:
10510  case Sema::TDK_IncompletePack:
10511    return 1;
10512
10513  case Sema::TDK_Underqualified:
10514  case Sema::TDK_Inconsistent:
10515    return 2;
10516
10517  case Sema::TDK_SubstitutionFailure:
10518  case Sema::TDK_DeducedMismatch:
10519  case Sema::TDK_DeducedMismatchNested:
10520  case Sema::TDK_NonDeducedMismatch:
10521  case Sema::TDK_MiscellaneousDeductionFailure:
10522  case Sema::TDK_CUDATargetMismatch:
10523    return 3;
10524
10525  case Sema::TDK_InstantiationDepth:
10526    return 4;
10527
10528  case Sema::TDK_InvalidExplicitArguments:
10529    return 5;
10530
10531  case Sema::TDK_TooManyArguments:
10532  case Sema::TDK_TooFewArguments:
10533    return 6;
10534  }
10535  llvm_unreachable("Unhandled deduction result");
10536}
10537
10538namespace {
10539struct CompareOverloadCandidatesForDisplay {
10540  Sema &S;
10541  SourceLocation Loc;
10542  size_t NumArgs;
10543  OverloadCandidateSet::CandidateSetKind CSK;
10544
10545  CompareOverloadCandidatesForDisplay(
10546      Sema &SSourceLocation Loc, size_t NArgs,
10547      OverloadCandidateSet::CandidateSetKind CSK)
10548      : S(S), NumArgs(NArgs), CSK(CSK) {}
10549
10550  bool operator()(const OverloadCandidate *L,
10551                  const OverloadCandidate *R) {
10552    // Fast-path this check.
10553    if (L == Rreturn false;
10554
10555    // Order first by viability.
10556    if (L->Viable) {
10557      if (!R->Viablereturn true;
10558
10559      // TODO: introduce a tri-valued comparison for overload
10560      // candidates.  Would be more worthwhile if we had a sort
10561      // that could exploit it.
10562      if (isBetterOverloadCandidate(S, *L, *RSourceLocation(), CSK))
10563        return true;
10564      if (isBetterOverloadCandidate(S, *R, *LSourceLocation(), CSK))
10565        return false;
10566    } else if (R->Viable)
10567      return false;
10568
10569    Viable == R->Viable", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10569, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(L->Viable == R->Viable);
10570
10571    // Criteria by which we can sort non-viable candidates:
10572    if (!L->Viable) {
10573      // 1. Arity mismatches come after other candidates.
10574      if (L->FailureKind == ovl_fail_too_many_arguments ||
10575          L->FailureKind == ovl_fail_too_few_arguments) {
10576        if (R->FailureKind == ovl_fail_too_many_arguments ||
10577            R->FailureKind == ovl_fail_too_few_arguments) {
10578          int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10579          int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10580          if (LDist == RDist) {
10581            if (L->FailureKind == R->FailureKind)
10582              // Sort non-surrogates before surrogates.
10583              return !L->IsSurrogate && R->IsSurrogate;
10584            // Sort candidates requiring fewer parameters than there were
10585            // arguments given after candidates requiring more parameters
10586            // than there were arguments given.
10587            return L->FailureKind == ovl_fail_too_many_arguments;
10588          }
10589          return LDist < RDist;
10590        }
10591        return false;
10592      }
10593      if (R->FailureKind == ovl_fail_too_many_arguments ||
10594          R->FailureKind == ovl_fail_too_few_arguments)
10595        return true;
10596
10597      // 2. Bad conversions come first and are ordered by the number
10598      // of bad conversions and quality of good conversions.
10599      if (L->FailureKind == ovl_fail_bad_conversion) {
10600        if (R->FailureKind != ovl_fail_bad_conversion)
10601          return true;
10602
10603        // The conversion that can be fixed with a smaller number of changes,
10604        // comes first.
10605        unsigned numLFixes = L->Fix.NumConversionsFixed;
10606        unsigned numRFixes = R->Fix.NumConversionsFixed;
10607        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10608        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10609        if (numLFixes != numRFixes) {
10610          return numLFixes < numRFixes;
10611        }
10612
10613        // If there's any ordering between the defined conversions...
10614        // FIXME: this might not be transitive.
10615        Conversions.size() == R->Conversions.size()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10615, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(L->Conversions.size() == R->Conversions.size());
10616
10617        int leftBetter = 0;
10618        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10619        for (unsigned E = L->Conversions.size(); I != E; ++I) {
10620          switch (CompareImplicitConversionSequences(SLoc,
10621                                                     L->Conversions[I],
10622                                                     R->Conversions[I])) {
10623          case ImplicitConversionSequence::Better:
10624            leftBetter++;
10625            break;
10626
10627          case ImplicitConversionSequence::Worse:
10628            leftBetter--;
10629            break;
10630
10631          case ImplicitConversionSequence::Indistinguishable:
10632            break;
10633          }
10634        }
10635        if (leftBetter > 0return true;
10636        if (leftBetter < 0return false;
10637
10638      } else if (R->FailureKind == ovl_fail_bad_conversion)
10639        return false;
10640
10641      if (L->FailureKind == ovl_fail_bad_deduction) {
10642        if (R->FailureKind != ovl_fail_bad_deduction)
10643          return true;
10644
10645        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10646          return RankDeductionFailure(L->DeductionFailure)
10647               < RankDeductionFailure(R->DeductionFailure);
10648      } else if (R->FailureKind == ovl_fail_bad_deduction)
10649        return false;
10650
10651      // TODO: others?
10652    }
10653
10654    // Sort everything else by location.
10655    SourceLocation LLoc = GetLocationForCandidate(L);
10656    SourceLocation RLoc = GetLocationForCandidate(R);
10657
10658    // Put candidates without locations (e.g. builtins) at the end.
10659    if (LLoc.isInvalid()) return false;
10660    if (RLoc.isInvalid()) return true;
10661
10662    return S.SourceMgr.isBeforeInTranslationUnit(LLocRLoc);
10663  }
10664};
10665}
10666
10667/// CompleteNonViableCandidate - Normally, overload resolution only
10668/// computes up to the first bad conversion. Produces the FixIt set if
10669/// possible.
10670static void CompleteNonViableCandidate(Sema &SOverloadCandidate *Cand,
10671                                       ArrayRef<Expr *> Args) {
10672  Viable", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10672, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Cand->Viable);
10673
10674  // Don't do anything on failures other than bad conversion.
10675  if (Cand->FailureKind != ovl_fail_bad_conversionreturn;
10676
10677  // We only want the FixIts if all the arguments can be corrected.
10678  bool Unfixable = false;
10679  // Use a implicit copy initialization to check conversion fixes.
10680  Cand->Fix.setConversionChecker(TryCopyInitialization);
10681
10682  // Attempt to fix the bad conversion.
10683  unsigned ConvCount = Cand->Conversions.size();
10684  for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10685       ++ConvIdx) {
10686     (0) . __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10686, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10687    if (Cand->Conversions[ConvIdx].isInitialized() &&
10688        Cand->Conversions[ConvIdx].isBad()) {
10689      Unfixable = !Cand->TryToFixBadConversion(ConvIdxS);
10690      break;
10691    }
10692  }
10693
10694  // FIXME: this should probably be preserved from the overload
10695  // operation somehow.
10696  bool SuppressUserConversions = false;
10697
10698  unsigned ConvIdx = 0;
10699  ArrayRef<QualTypeParamTypes;
10700
10701  if (Cand->IsSurrogate) {
10702    QualType ConvType
10703      = Cand->Surrogate->getConversionType().getNonReferenceType();
10704    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10705      ConvType = ConvPtrType->getPointeeType();
10706    ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10707    // Conversion 0 is 'this', which doesn't have a corresponding argument.
10708    ConvIdx = 1;
10709  } else if (Cand->Function) {
10710    ParamTypes =
10711        Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10712    if (isa<CXXMethodDecl>(Cand->Function) &&
10713        !isa<CXXConstructorDecl>(Cand->Function)) {
10714      // Conversion 0 is 'this', which doesn't have a corresponding argument.
10715      ConvIdx = 1;
10716    }
10717  } else {
10718    // Builtin operator.
10719    assert(ConvCount <= 3);
10720    ParamTypes = Cand->BuiltinParamTypes;
10721  }
10722
10723  // Fill in the rest of the conversions.
10724  for (unsigned ArgIdx = 0ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10725    if (Cand->Conversions[ConvIdx].isInitialized()) {
10726      // We've already checked this conversion.
10727    } else if (ArgIdx < ParamTypes.size()) {
10728      if (ParamTypes[ArgIdx]->isDependentType())
10729        Cand->Conversions[ConvIdx].setAsIdentityConversion(
10730            Args[ArgIdx]->getType());
10731      else {
10732        Cand->Conversions[ConvIdx] =
10733            TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10734                                  SuppressUserConversions,
10735                                  /*InOverloadResolution=*/true,
10736                                  /*AllowObjCWritebackConversion=*/
10737                                  S.getLangOpts().ObjCAutoRefCount);
10738        // Store the FixIt in the candidate if it exists.
10739        if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10740          Unfixable = !Cand->TryToFixBadConversion(ConvIdxS);
10741      }
10742    } else
10743      Cand->Conversions[ConvIdx].setEllipsis();
10744  }
10745}
10746
10747/// When overload resolution fails, prints diagnostic messages containing the
10748/// candidates in the candidate set.
10749void OverloadCandidateSet::NoteCandidates(
10750    Sema &SOverloadCandidateDisplayKind OCDArrayRef<Expr *> Args,
10751    StringRef OpcSourceLocation OpLoc,
10752    llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10753  // Sort the candidates by viability and position.  Sorting directly would
10754  // be prohibitive, so we make a set of pointers and sort those.
10755  SmallVector<OverloadCandidate*, 32Cands;
10756  if (OCD == OCD_AllCandidates) Cands.reserve(size());
10757  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10758    if (!Filter(*Cand))
10759      continue;
10760    if (Cand->Viable)
10761      Cands.push_back(Cand);
10762    else if (OCD == OCD_AllCandidates) {
10763      CompleteNonViableCandidate(S, Cand, Args);
10764      if (Cand->Function || Cand->IsSurrogate)
10765        Cands.push_back(Cand);
10766      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10767      // want to list every possible builtin candidate.
10768    }
10769  }
10770
10771  std::stable_sort(Cands.begin(), Cands.end(),
10772            CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10773
10774  bool ReportedAmbiguousConversions = false;
10775
10776  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10777  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10778  unsigned CandsShown = 0;
10779  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10780    OverloadCandidate *Cand = *I;
10781
10782    // Set an arbitrary limit on the number of candidate functions we'll spam
10783    // the user with.  FIXME: This limit should depend on details of the
10784    // candidate list.
10785    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10786      break;
10787    }
10788    ++CandsShown;
10789
10790    if (Cand->Function)
10791      NoteFunctionCandidate(S, Cand, Args.size(),
10792                            /*TakingCandidateAddress=*/false);
10793    else if (Cand->IsSurrogate)
10794      NoteSurrogateCandidate(S, Cand);
10795    else {
10796       (0) . __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10797, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Cand->Viable &&
10797 (0) . __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10797, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "Non-viable built-in candidates are not added to Cands.");
10798      // Generally we only see ambiguities including viable builtin
10799      // operators if overload resolution got screwed up by an
10800      // ambiguous user-defined conversion.
10801      //
10802      // FIXME: It's quite possible for different conversions to see
10803      // different ambiguities, though.
10804      if (!ReportedAmbiguousConversions) {
10805        NoteAmbiguousUserConversions(S, OpLoc, Cand);
10806        ReportedAmbiguousConversions = true;
10807      }
10808
10809      // If this is a viable builtin, print it.
10810      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10811    }
10812  }
10813
10814  if (I != E)
10815    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10816}
10817
10818static SourceLocation
10819GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10820  return Cand->Specialization ? Cand->Specialization->getLocation()
10821                              : SourceLocation();
10822}
10823
10824namespace {
10825struct CompareTemplateSpecCandidatesForDisplay {
10826  Sema &S;
10827  CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10828
10829  bool operator()(const TemplateSpecCandidate *L,
10830                  const TemplateSpecCandidate *R) {
10831    // Fast-path this check.
10832    if (L == R)
10833      return false;
10834
10835    // Assuming that both candidates are not matches...
10836
10837    // Sort by the ranking of deduction failures.
10838    if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10839      return RankDeductionFailure(L->DeductionFailure) <
10840             RankDeductionFailure(R->DeductionFailure);
10841
10842    // Sort everything else by location.
10843    SourceLocation LLoc = GetLocationForCandidate(L);
10844    SourceLocation RLoc = GetLocationForCandidate(R);
10845
10846    // Put candidates without locations (e.g. builtins) at the end.
10847    if (LLoc.isInvalid())
10848      return false;
10849    if (RLoc.isInvalid())
10850      return true;
10851
10852    return S.SourceMgr.isBeforeInTranslationUnit(LLocRLoc);
10853  }
10854};
10855}
10856
10857/// Diagnose a template argument deduction failure.
10858/// We are treating these failures as overload failures due to bad
10859/// deductions.
10860void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10861                                                 bool ForTakingAddress) {
10862  DiagnoseBadDeduction(SFoundDeclSpecialization// pattern
10863                       DeductionFailure/*NumArgs=*/0ForTakingAddress);
10864}
10865
10866void TemplateSpecCandidateSet::destroyCandidates() {
10867  for (iterator i = begin(), e = end(); i != e; ++i) {
10868    i->DeductionFailure.Destroy();
10869  }
10870}
10871
10872void TemplateSpecCandidateSet::clear() {
10873  destroyCandidates();
10874  Candidates.clear();
10875}
10876
10877/// NoteCandidates - When no template specialization match is found, prints
10878/// diagnostic messages containing the non-matching specializations that form
10879/// the candidate set.
10880/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10881/// OCD == OCD_AllCandidates and Cand->Viable == false.
10882void TemplateSpecCandidateSet::NoteCandidates(Sema &SSourceLocation Loc) {
10883  // Sort the candidates by position (assuming no candidate is a match).
10884  // Sorting directly would be prohibitive, so we make a set of pointers
10885  // and sort those.
10886  SmallVector<TemplateSpecCandidate *, 32Cands;
10887  Cands.reserve(size());
10888  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10889    if (Cand->Specialization)
10890      Cands.push_back(Cand);
10891    // Otherwise, this is a non-matching builtin candidate.  We do not,
10892    // in general, want to list every possible builtin candidate.
10893  }
10894
10895  llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10896
10897  // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10898  // for generalization purposes (?).
10899  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10900
10901  SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10902  unsigned CandsShown = 0;
10903  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10904    TemplateSpecCandidate *Cand = *I;
10905
10906    // Set an arbitrary limit on the number of candidates we'll spam
10907    // the user with.  FIXME: This limit should depend on details of the
10908    // candidate list.
10909    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10910      break;
10911    ++CandsShown;
10912
10913     (0) . __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10914, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Cand->Specialization &&
10914 (0) . __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 10914, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Non-matching built-in candidates are not added to Cands.");
10915    Cand->NoteDeductionFailure(S, ForTakingAddress);
10916  }
10917
10918  if (I != E)
10919    S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10920}
10921
10922// [PossiblyAFunctionType]  -->   [Return]
10923// NonFunctionType --> NonFunctionType
10924// R (A) --> R(A)
10925// R (*)(A) --> R (A)
10926// R (&)(A) --> R (A)
10927// R (S::*)(A) --> R (A)
10928QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10929  QualType Ret = PossiblyAFunctionType;
10930  if (const PointerType *ToTypePtr =
10931    PossiblyAFunctionType->getAs<PointerType>())
10932    Ret = ToTypePtr->getPointeeType();
10933  else if (const ReferenceType *ToTypeRef =
10934    PossiblyAFunctionType->getAs<ReferenceType>())
10935    Ret = ToTypeRef->getPointeeType();
10936  else if (const MemberPointerType *MemTypePtr =
10937    PossiblyAFunctionType->getAs<MemberPointerType>())
10938    Ret = MemTypePtr->getPointeeType();
10939  Ret =
10940    Context.getCanonicalType(Ret).getUnqualifiedType();
10941  return Ret;
10942}
10943
10944static bool completeFunctionType(Sema &SFunctionDecl *FDSourceLocation Loc,
10945                                 bool Complain = true) {
10946  if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10947      S.DeduceReturnType(FDLocComplain))
10948    return true;
10949
10950  auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10951  if (S.getLangOpts().CPlusPlus17 &&
10952      isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10953      !S.ResolveExceptionSpec(Loc, FPT))
10954    return true;
10955
10956  return false;
10957}
10958
10959namespace {
10960// A helper class to help with address of function resolution
10961// - allows us to avoid passing around all those ugly parameters
10962class AddressOfFunctionResolver {
10963  SemaS;
10964  ExprSourceExpr;
10965  const QualTypeTargetType;
10966  QualType TargetFunctionType// Extracted function type from target type
10967
10968  bool Complain;
10969  //DeclAccessPair& ResultFunctionAccessPair;
10970  ASTContextContext;
10971
10972  bool TargetTypeIsNonStaticMemberFunction;
10973  bool FoundNonTemplateFunction;
10974  bool StaticMemberFunctionFromBoundPointer;
10975  bool HasComplained;
10976
10977  OverloadExpr::FindResult OvlExprInfo;
10978  OverloadExpr *OvlExpr;
10979  TemplateArgumentListInfo OvlExplicitTemplateArgs;
10980  SmallVector<std::pair<DeclAccessPairFunctionDecl*>, 4Matches;
10981  TemplateSpecCandidateSet FailedCandidates;
10982
10983public:
10984  AddressOfFunctionResolver(Sema &SExpr *SourceExpr,
10985                            const QualType &TargetTypebool Complain)
10986      : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10987        Complain(Complain), Context(S.getASTContext()),
10988        TargetTypeIsNonStaticMemberFunction(
10989            !!TargetType->getAs<MemberPointerType>()),
10990        FoundNonTemplateFunction(false),
10991        StaticMemberFunctionFromBoundPointer(false),
10992        HasComplained(false),
10993        OvlExprInfo(OverloadExpr::find(SourceExpr)),
10994        OvlExpr(OvlExprInfo.Expression),
10995        FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10996    ExtractUnqualifiedFunctionTypeFromTargetType();
10997
10998    if (TargetFunctionType->isFunctionType()) {
10999      if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11000        if (!UME->isImplicitAccess() &&
11001            !S.ResolveSingleFunctionTemplateSpecialization(UME))
11002          StaticMemberFunctionFromBoundPointer = true;
11003    } else if (OvlExpr->hasExplicitTemplateArgs()) {
11004      DeclAccessPair dap;
11005      if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11006              OvlExprfalse, &dap)) {
11007        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11008          if (!Method->isStatic()) {
11009            // If the target type is a non-function type and the function found
11010            // is a non-static member function, pretend as if that was the
11011            // target, it's the only possible type to end up with.
11012            TargetTypeIsNonStaticMemberFunction = true;
11013
11014            // And skip adding the function if its not in the proper form.
11015            // We'll diagnose this due to an empty set of functions.
11016            if (!OvlExprInfo.HasFormOfMemberPointer)
11017              return;
11018          }
11019
11020        Matches.push_back(std::make_pair(dap, Fn));
11021      }
11022      return;
11023    }
11024
11025    if (OvlExpr->hasExplicitTemplateArgs())
11026      OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11027
11028    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11029      // C++ [over.over]p4:
11030      //   If more than one function is selected, [...]
11031      if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11032        if (FoundNonTemplateFunction)
11033          EliminateAllTemplateMatches();
11034        else
11035          EliminateAllExceptMostSpecializedTemplate();
11036      }
11037    }
11038
11039    if (S.getLangOpts().CUDA && Matches.size() > 1)
11040      EliminateSuboptimalCudaMatches();
11041  }
11042
11043  bool hasComplained() const { return HasComplained; }
11044
11045private:
11046  bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11047    QualType Discard;
11048    return Context.hasSameUnqualifiedType(TargetFunctionTypeFD->getType()) ||
11049           S.IsFunctionConversion(FD->getType(), TargetFunctionTypeDiscard);
11050  }
11051
11052  /// \return true if A is considered a better overload candidate for the
11053  /// desired type than B.
11054  bool isBetterCandidate(const FunctionDecl *Aconst FunctionDecl *B) {
11055    // If A doesn't have exactly the correct type, we don't want to classify it
11056    // as "better" than anything else. This way, the user is required to
11057    // disambiguate for us if there are multiple candidates and no exact match.
11058    return candidateHasExactlyCorrectType(A) &&
11059           (!candidateHasExactlyCorrectType(B) ||
11060            compareEnableIfAttrs(SAB) == Comparison::Better);
11061  }
11062
11063  /// \return true if we were able to eliminate all but one overload candidate,
11064  /// false otherwise.
11065  bool eliminiateSuboptimalOverloadCandidates() {
11066    // Same algorithm as overload resolution -- one pass to pick the "best",
11067    // another pass to be sure that nothing is better than the best.
11068    auto Best = Matches.begin();
11069    for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11070      if (isBetterCandidate(I->second, Best->second))
11071        Best = I;
11072
11073    const FunctionDecl *BestFn = Best->second;
11074    auto IsBestOrInferiorToBest = [thisBestFn](
11075        const std::pair<DeclAccessPairFunctionDecl *> &Pair) {
11076      return BestFn == Pair.second || isBetterCandidate(BestFnPair.second);
11077    };
11078
11079    // Note: We explicitly leave Matches unmodified if there isn't a clear best
11080    // option, so we can potentially give the user a better error
11081    if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11082      return false;
11083    Matches[0] = *Best;
11084    Matches.resize(1);
11085    return true;
11086  }
11087
11088  bool isTargetTypeAFunction() const {
11089    return TargetFunctionType->isFunctionType();
11090  }
11091
11092  // [ToType]     [Return]
11093
11094  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11095  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11096  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11097  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11098    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11099  }
11100
11101  // return true if any matching specializations were found
11102  bool AddMatchingTemplateFunction(FunctionTemplateDeclFunctionTemplate,
11103                                   const DeclAccessPairCurAccessFunPair) {
11104    if (CXXMethodDecl *Method
11105              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11106      // Skip non-static function templates when converting to pointer, and
11107      // static when converting to member pointer.
11108      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11109        return false;
11110    }
11111    else if (TargetTypeIsNonStaticMemberFunction)
11112      return false;
11113
11114    // C++ [over.over]p2:
11115    //   If the name is a function template, template argument deduction is
11116    //   done (14.8.2.2), and if the argument deduction succeeds, the
11117    //   resulting template argument list is used to generate a single
11118    //   function template specialization, which is added to the set of
11119    //   overloaded functions considered.
11120    FunctionDecl *Specialization = nullptr;
11121    TemplateDeductionInfo Info(FailedCandidates.getLocation());
11122    if (Sema::TemplateDeductionResult Result
11123          = S.DeduceTemplateArguments(FunctionTemplate,
11124                                      &OvlExplicitTemplateArgs,
11125                                      TargetFunctionType, Specialization,
11126                                      Info, /*IsAddressOfFunction*/true)) {
11127      // Make a note of the failed deduction for diagnostics.
11128      FailedCandidates.addCandidate()
11129          .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11130               MakeDeductionFailureInfo(Context, Result, Info));
11131      return false;
11132    }
11133
11134    // Template argument deduction ensures that we have an exact match or
11135    // compatible pointer-to-function arguments that would be adjusted by ICS.
11136    // This function template specicalization works.
11137    getType()), Context.getCanonicalType(TargetFunctionType))", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11139, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S.isSameOrCompatibleFunctionType(
11138getType()), Context.getCanonicalType(TargetFunctionType))", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11139, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">              Context.getCanonicalType(Specialization->getType()),
11139getType()), Context.getCanonicalType(TargetFunctionType))", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11139, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">              Context.getCanonicalType(TargetFunctionType)));
11140
11141    if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11142      return false;
11143
11144    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11145    return true;
11146  }
11147
11148  bool AddMatchingNonTemplateFunction(NamedDeclFn,
11149                                      const DeclAccessPairCurAccessFunPair) {
11150    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11151      // Skip non-static functions when converting to pointer, and static
11152      // when converting to member pointer.
11153      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11154        return false;
11155    }
11156    else if (TargetTypeIsNonStaticMemberFunction)
11157      return false;
11158
11159    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11160      if (S.getLangOpts().CUDA)
11161        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11162          if (!Caller->isImplicit() && !S.IsAllowedCUDACall(CallerFunDecl))
11163            return false;
11164      if (FunDecl->isMultiVersion()) {
11165        const auto *TA = FunDecl->getAttr<TargetAttr>();
11166        if (TA && !TA->isDefaultVersion())
11167          return false;
11168      }
11169
11170      // If any candidate has a placeholder return type, trigger its deduction
11171      // now.
11172      if (completeFunctionType(SFunDeclSourceExpr->getBeginLoc(),
11173                               Complain)) {
11174        HasComplained |= Complain;
11175        return false;
11176      }
11177
11178      if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11179        return false;
11180
11181      // If we're in C, we need to support types that aren't exactly identical.
11182      if (!S.getLangOpts().CPlusPlus ||
11183          candidateHasExactlyCorrectType(FunDecl)) {
11184        Matches.push_back(std::make_pair(
11185            CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11186        FoundNonTemplateFunction = true;
11187        return true;
11188      }
11189    }
11190
11191    return false;
11192  }
11193
11194  bool FindAllFunctionsThatMatchTargetTypeExactly() {
11195    bool Ret = false;
11196
11197    // If the overload expression doesn't have the form of a pointer to
11198    // member, don't try to convert it to a pointer-to-member type.
11199    if (IsInvalidFormOfPointerToMemberFunction())
11200      return false;
11201
11202    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11203                               E = OvlExpr->decls_end();
11204         I != E; ++I) {
11205      // Look through any using declarations to find the underlying function.
11206      NamedDecl *Fn = (*I)->getUnderlyingDecl();
11207
11208      // C++ [over.over]p3:
11209      //   Non-member functions and static member functions match
11210      //   targets of type "pointer-to-function" or "reference-to-function."
11211      //   Nonstatic member functions match targets of
11212      //   type "pointer-to-member-function."
11213      // Note that according to DR 247, the containing class does not matter.
11214      if (FunctionTemplateDecl *FunctionTemplate
11215                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
11216        if (AddMatchingTemplateFunction(FunctionTemplateI.getPair()))
11217          Ret = true;
11218      }
11219      // If we have explicit template arguments supplied, skip non-templates.
11220      else if (!OvlExpr->hasExplicitTemplateArgs() &&
11221               AddMatchingNonTemplateFunction(FnI.getPair()))
11222        Ret = true;
11223    }
11224    assert(Ret || Matches.empty());
11225    return Ret;
11226  }
11227
11228  void EliminateAllExceptMostSpecializedTemplate() {
11229    //   [...] and any given function template specialization F1 is
11230    //   eliminated if the set contains a second function template
11231    //   specialization whose function template is more specialized
11232    //   than the function template of F1 according to the partial
11233    //   ordering rules of 14.5.5.2.
11234
11235    // The algorithm specified above is quadratic. We instead use a
11236    // two-pass algorithm (similar to the one used to identify the
11237    // best viable function in an overload set) that identifies the
11238    // best function template (if it exists).
11239
11240    UnresolvedSet<4MatchesCopy// TODO: avoid!
11241    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11242      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11243
11244    // TODO: It looks like FailedCandidates does not serve much purpose
11245    // here, since the no_viable diagnostic has index 0.
11246    UnresolvedSetIterator Result = S.getMostSpecialized(
11247        MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11248        SourceExpr->getBeginLoc(), S.PDiag(),
11249        S.PDiag(diag::err_addr_ovl_ambiguous)
11250            << Matches[0].second->getDeclName(),
11251        S.PDiag(diag::note_ovl_candidate)
11252            << (unsigned)oc_function << (unsigned)ocs_described_template,
11253        Complain, TargetFunctionType);
11254
11255    if (Result != MatchesCopy.end()) {
11256      // Make it the first and only element
11257      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11258      Matches[0].second = cast<FunctionDecl>(*Result);
11259      Matches.resize(1);
11260    } else
11261      HasComplained |= Complain;
11262  }
11263
11264  void EliminateAllTemplateMatches() {
11265    //   [...] any function template specializations in the set are
11266    //   eliminated if the set also contains a non-template function, [...]
11267    for (unsigned I = 0N = Matches.size(); I != N; ) {
11268      if (Matches[I].second->getPrimaryTemplate() == nullptr)
11269        ++I;
11270      else {
11271        Matches[I] = Matches[--N];
11272        Matches.resize(N);
11273      }
11274    }
11275  }
11276
11277  void EliminateSuboptimalCudaMatches() {
11278    S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11279  }
11280
11281public:
11282  void ComplainNoMatchesFound() const {
11283    assert(Matches.empty());
11284    S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11285        << OvlExpr->getName() << TargetFunctionType
11286        << OvlExpr->getSourceRange();
11287    if (FailedCandidates.empty())
11288      S.NoteAllOverloadCandidates(OvlExprTargetFunctionType,
11289                                  /*TakingAddress=*/true);
11290    else {
11291      // We have some deduction failure messages. Use them to diagnose
11292      // the function templates, and diagnose the non-template candidates
11293      // normally.
11294      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11295                                 IEnd = OvlExpr->decls_end();
11296           I != IEnd; ++I)
11297        if (FunctionDecl *Fun =
11298                dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11299          if (!functionHasPassObjectSizeParams(Fun))
11300            S.NoteOverloadCandidate(*IFunTargetFunctionType,
11301                                    /*TakingAddress=*/true);
11302      FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11303    }
11304  }
11305
11306  bool IsInvalidFormOfPointerToMemberFunction() const {
11307    return TargetTypeIsNonStaticMemberFunction &&
11308      !OvlExprInfo.HasFormOfMemberPointer;
11309  }
11310
11311  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11312      // TODO: Should we condition this on whether any functions might
11313      // have matched, or is it more appropriate to do that in callers?
11314      // TODO: a fixit wouldn't hurt.
11315      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11316        << TargetType << OvlExpr->getSourceRange();
11317  }
11318
11319  bool IsStaticMemberFunctionFromBoundPointer() const {
11320    return StaticMemberFunctionFromBoundPointer;
11321  }
11322
11323  void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11324    S.Diag(OvlExpr->getBeginLoc(),
11325           diag::err_invalid_form_pointer_member_function)
11326        << OvlExpr->getSourceRange();
11327  }
11328
11329  void ComplainOfInvalidConversion() const {
11330    S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11331        << OvlExpr->getName() << TargetType;
11332  }
11333
11334  void ComplainMultipleMatchesFound() const {
11335     1", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11335, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Matches.size() > 1);
11336    S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11337        << OvlExpr->getName() << OvlExpr->getSourceRange();
11338    S.NoteAllOverloadCandidates(OvlExprTargetFunctionType,
11339                                /*TakingAddress=*/true);
11340  }
11341
11342  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11343
11344  int getNumMatches() const { return Matches.size(); }
11345
11346  FunctionDeclgetMatchingFunctionDecl() const {
11347    if (Matches.size() != 1return nullptr;
11348    return Matches[0].second;
11349  }
11350
11351  const DeclAccessPairgetMatchingFunctionAccessPair() const {
11352    if (Matches.size() != 1return nullptr;
11353    return &Matches[0].first;
11354  }
11355};
11356}
11357
11358/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11359/// an overloaded function (C++ [over.over]), where @p From is an
11360/// expression with overloaded function type and @p ToType is the type
11361/// we're trying to resolve to. For example:
11362///
11363/// @code
11364/// int f(double);
11365/// int f(int);
11366///
11367/// int (*pfd)(double) = f; // selects f(double)
11368/// @endcode
11369///
11370/// This routine returns the resulting FunctionDecl if it could be
11371/// resolved, and NULL otherwise. When @p Complain is true, this
11372/// routine will emit diagnostics if there is an error.
11373FunctionDecl *
11374Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11375                                         QualType TargetType,
11376                                         bool Complain,
11377                                         DeclAccessPair &FoundResult,
11378                                         bool *pHadMultipleCandidates) {
11379  getType() == Context.OverloadTy", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11379, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(AddressOfExpr->getType() == Context.OverloadTy);
11380
11381  AddressOfFunctionResolver Resolver(*thisAddressOfExprTargetType,
11382                                     Complain);
11383  int NumMatches = Resolver.getNumMatches();
11384  FunctionDecl *Fn = nullptr;
11385  bool ShouldComplain = Complain && !Resolver.hasComplained();
11386  if (NumMatches == 0 && ShouldComplain) {
11387    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11388      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11389    else
11390      Resolver.ComplainNoMatchesFound();
11391  }
11392  else if (NumMatches > 1 && ShouldComplain)
11393    Resolver.ComplainMultipleMatchesFound();
11394  else if (NumMatches == 1) {
11395    Fn = Resolver.getMatchingFunctionDecl();
11396    assert(Fn);
11397    if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11398      ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11399    FoundResult = *Resolver.getMatchingFunctionAccessPair();
11400    if (Complain) {
11401      if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11402        Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11403      else
11404        CheckAddressOfMemberAccess(AddressOfExprFoundResult);
11405    }
11406  }
11407
11408  if (pHadMultipleCandidates)
11409    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11410  return Fn;
11411}
11412
11413/// Given an expression that refers to an overloaded function, try to
11414/// resolve that function to a single function that can have its address taken.
11415/// This will modify `Pair` iff it returns non-null.
11416///
11417/// This routine can only realistically succeed if all but one candidates in the
11418/// overload set for SrcExpr cannot have their addresses taken.
11419FunctionDecl *
11420Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11421                                                  DeclAccessPair &Pair) {
11422  OverloadExpr::FindResult R = OverloadExpr::find(E);
11423  OverloadExpr *Ovl = R.Expression;
11424  FunctionDecl *Result = nullptr;
11425  DeclAccessPair DAP;
11426  // Don't use the AddressOfResolver because we're specifically looking for
11427  // cases where we have one overload candidate that lacks
11428  // enable_if/pass_object_size/...
11429  for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11430    auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11431    if (!FD)
11432      return nullptr;
11433
11434    if (!checkAddressOfFunctionIsAvailable(FD))
11435      continue;
11436
11437    // We have more than one result; quit.
11438    if (Result)
11439      return nullptr;
11440    DAP = I.getPair();
11441    Result = FD;
11442  }
11443
11444  if (Result)
11445    Pair = DAP;
11446  return Result;
11447}
11448
11449/// Given an overloaded function, tries to turn it into a non-overloaded
11450/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11451/// will perform access checks, diagnose the use of the resultant decl, and, if
11452/// requested, potentially perform a function-to-pointer decay.
11453///
11454/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11455/// Otherwise, returns true. This may emit diagnostics and return true.
11456bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11457    ExprResult &SrcExprbool DoFunctionPointerConverion) {
11458  Expr *E = SrcExpr.get();
11459   (0) . __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11459, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11460
11461  DeclAccessPair DAP;
11462  FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(EDAP);
11463  if (!Found || Found->isCPUDispatchMultiVersion() ||
11464      Found->isCPUSpecificMultiVersion())
11465    return false;
11466
11467  // Emitting multiple diagnostics for a function that is both inaccessible and
11468  // unavailable is consistent with our behavior elsewhere. So, always check
11469  // for both.
11470  DiagnoseUseOfDecl(FoundE->getExprLoc());
11471  CheckAddressOfMemberAccess(EDAP);
11472  Expr *Fixed = FixOverloadedFunctionReference(EDAPFound);
11473  if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11474    SrcExpr = DefaultFunctionArrayConversion(Fixed/*Diagnose=*/false);
11475  else
11476    SrcExpr = Fixed;
11477  return true;
11478}
11479
11480/// Given an expression that refers to an overloaded function, try to
11481/// resolve that overloaded function expression down to a single function.
11482///
11483/// This routine can only resolve template-ids that refer to a single function
11484/// template, where that template-id refers to a single template whose template
11485/// arguments are either provided by the template-id or have defaults,
11486/// as described in C++0x [temp.arg.explicit]p3.
11487///
11488/// If no template-ids are found, no diagnostics are emitted and NULL is
11489/// returned.
11490FunctionDecl *
11491Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11492                                                  bool Complain,
11493                                                  DeclAccessPair *FoundResult) {
11494  // C++ [over.over]p1:
11495  //   [...] [Note: any redundant set of parentheses surrounding the
11496  //   overloaded function name is ignored (5.1). ]
11497  // C++ [over.over]p1:
11498  //   [...] The overloaded function name can be preceded by the &
11499  //   operator.
11500
11501  // If we didn't actually find any template-ids, we're done.
11502  if (!ovl->hasExplicitTemplateArgs())
11503    return nullptr;
11504
11505  TemplateArgumentListInfo ExplicitTemplateArgs;
11506  ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11507  TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11508
11509  // Look through all of the overloaded functions, searching for one
11510  // whose type matches exactly.
11511  FunctionDecl *Matched = nullptr;
11512  for (UnresolvedSetIterator I = ovl->decls_begin(),
11513         E = ovl->decls_end(); I != E; ++I) {
11514    // C++0x [temp.arg.explicit]p3:
11515    //   [...] In contexts where deduction is done and fails, or in contexts
11516    //   where deduction is not done, if a template argument list is
11517    //   specified and it, along with any default template arguments,
11518    //   identifies a single function template specialization, then the
11519    //   template-id is an lvalue for the function template specialization.
11520    FunctionTemplateDecl *FunctionTemplate
11521      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11522
11523    // C++ [over.over]p2:
11524    //   If the name is a function template, template argument deduction is
11525    //   done (14.8.2.2), and if the argument deduction succeeds, the
11526    //   resulting template argument list is used to generate a single
11527    //   function template specialization, which is added to the set of
11528    //   overloaded functions considered.
11529    FunctionDecl *Specialization = nullptr;
11530    TemplateDeductionInfo Info(FailedCandidates.getLocation());
11531    if (TemplateDeductionResult Result
11532          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11533                                    SpecializationInfo,
11534                                    /*IsAddressOfFunction*/true)) {
11535      // Make a note of the failed deduction for diagnostics.
11536      // TODO: Actually use the failed-deduction info?
11537      FailedCandidates.addCandidate()
11538          .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11539               MakeDeductionFailureInfo(ContextResultInfo));
11540      continue;
11541    }
11542
11543     (0) . __assert_fail ("Specialization && \"no specialization and no error?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11543, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Specialization && "no specialization and no error?");
11544
11545    // Multiple matches; we can't resolve to a single declaration.
11546    if (Matched) {
11547      if (Complain) {
11548        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11549          << ovl->getName();
11550        NoteAllOverloadCandidates(ovl);
11551      }
11552      return nullptr;
11553    }
11554
11555    Matched = Specialization;
11556    if (FoundResult) *FoundResult = I.getPair();
11557  }
11558
11559  if (Matched &&
11560      completeFunctionType(*thisMatchedovl->getExprLoc(), Complain))
11561    return nullptr;
11562
11563  return Matched;
11564}
11565
11566// Resolve and fix an overloaded expression that can be resolved
11567// because it identifies a single function template specialization.
11568//
11569// Last three arguments should only be supplied if Complain = true
11570//
11571// Return true if it was logically possible to so resolve the
11572// expression, regardless of whether or not it succeeded.  Always
11573// returns true if 'complain' is set.
11574bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11575                      ExprResult &SrcExprbool doFunctionPointerConverion,
11576                      bool complainSourceRange OpRangeForComplaining,
11577                                           QualType DestTypeForComplaining,
11578                                            unsigned DiagIDForComplaining) {
11579  getType() == Context.OverloadTy", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11579, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(SrcExpr.get()->getType() == Context.OverloadTy);
11580
11581  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11582
11583  DeclAccessPair found;
11584  ExprResult SingleFunctionExpression;
11585  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11586                           ovl.Expression/*complain*/ false, &found)) {
11587    if (DiagnoseUseOfDecl(fnSrcExpr.get()->getBeginLoc())) {
11588      SrcExpr = ExprError();
11589      return true;
11590    }
11591
11592    // It is only correct to resolve to an instance method if we're
11593    // resolving a form that's permitted to be a pointer to member.
11594    // Otherwise we'll end up making a bound member expression, which
11595    // is illegal in all the contexts we resolve like this.
11596    if (!ovl.HasFormOfMemberPointer &&
11597        isa<CXXMethodDecl>(fn) &&
11598        cast<CXXMethodDecl>(fn)->isInstance()) {
11599      if (!complainreturn false;
11600
11601      Diag(ovl.Expression->getExprLoc(),
11602           diag::err_bound_member_function)
11603        << 0 << ovl.Expression->getSourceRange();
11604
11605      // TODO: I believe we only end up here if there's a mix of
11606      // static and non-static candidates (otherwise the expression
11607      // would have 'bound member' type, not 'overload' type).
11608      // Ideally we would note which candidate was chosen and why
11609      // the static candidates were rejected.
11610      SrcExpr = ExprError();
11611      return true;
11612    }
11613
11614    // Fix the expression to refer to 'fn'.
11615    SingleFunctionExpression =
11616        FixOverloadedFunctionReference(SrcExpr.get(), foundfn);
11617
11618    // If desired, do function-to-pointer decay.
11619    if (doFunctionPointerConverion) {
11620      SingleFunctionExpression =
11621        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11622      if (SingleFunctionExpression.isInvalid()) {
11623        SrcExpr = ExprError();
11624        return true;
11625      }
11626    }
11627  }
11628
11629  if (!SingleFunctionExpression.isUsable()) {
11630    if (complain) {
11631      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11632        << ovl.Expression->getName()
11633        << DestTypeForComplaining
11634        << OpRangeForComplaining
11635        << ovl.Expression->getQualifierLoc().getSourceRange();
11636      NoteAllOverloadCandidates(SrcExpr.get());
11637
11638      SrcExpr = ExprError();
11639      return true;
11640    }
11641
11642    return false;
11643  }
11644
11645  SrcExpr = SingleFunctionExpression;
11646  return true;
11647}
11648
11649/// Add a single candidate to the overload set.
11650static void AddOverloadedCallCandidate(Sema &S,
11651                                       DeclAccessPair FoundDecl,
11652                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
11653                                       ArrayRef<Expr *> Args,
11654                                       OverloadCandidateSet &CandidateSet,
11655                                       bool PartialOverloading,
11656                                       bool KnownValid) {
11657  NamedDecl *Callee = FoundDecl.getDecl();
11658  if (isa<UsingShadowDecl>(Callee))
11659    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11660
11661  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11662    if (ExplicitTemplateArgs) {
11663       (0) . __assert_fail ("!KnownValid && \"Explicit template arguments?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11663, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!KnownValid && "Explicit template arguments?");
11664      return;
11665    }
11666    // Prevent ill-formed function decls to be added as overload candidates.
11667    if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11668      return;
11669
11670    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11671                           /*SuppressUsedConversions=*/false,
11672                           PartialOverloading);
11673    return;
11674  }
11675
11676  if (FunctionTemplateDecl *FuncTemplate
11677      = dyn_cast<FunctionTemplateDecl>(Callee)) {
11678    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11679                                   ExplicitTemplateArgs, Args, CandidateSet,
11680                                   /*SuppressUsedConversions=*/false,
11681                                   PartialOverloading);
11682    return;
11683  }
11684
11685   (0) . __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11685, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!KnownValid && "unhandled case in overloaded call candidate");
11686}
11687
11688/// Add the overload candidates named by callee and/or found by argument
11689/// dependent lookup to the given overload set.
11690void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11691                                       ArrayRef<Expr *> Args,
11692                                       OverloadCandidateSet &CandidateSet,
11693                                       bool PartialOverloading) {
11694
11695#ifndef NDEBUG
11696  // Verify that ArgumentDependentLookup is consistent with the rules
11697  // in C++0x [basic.lookup.argdep]p3:
11698  //
11699  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11700  //   and let Y be the lookup set produced by argument dependent
11701  //   lookup (defined as follows). If X contains
11702  //
11703  //     -- a declaration of a class member, or
11704  //
11705  //     -- a block-scope function declaration that is not a
11706  //        using-declaration, or
11707  //
11708  //     -- a declaration that is neither a function or a function
11709  //        template
11710  //
11711  //   then Y is empty.
11712
11713  if (ULE->requiresADL()) {
11714    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11715           E = ULE->decls_end(); I != E; ++I) {
11716      getDeclContext()->isRecord()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11716, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!(*I)->getDeclContext()->isRecord());
11717      (*I) || !(*I)->getDeclContext()->isFunctionOrMethod()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11718, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<UsingShadowDecl>(*I) ||
11718(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11718, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             !(*I)->getDeclContext()->isFunctionOrMethod());
11719      getUnderlyingDecl()->isFunctionOrFunctionTemplate()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11719, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11720    }
11721  }
11722#endif
11723
11724  // It would be nice to avoid this copy.
11725  TemplateArgumentListInfo TABuffer;
11726  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11727  if (ULE->hasExplicitTemplateArgs()) {
11728    ULE->copyTemplateArgumentsInto(TABuffer);
11729    ExplicitTemplateArgs = &TABuffer;
11730  }
11731
11732  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11733         E = ULE->decls_end(); I != E; ++I)
11734    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11735                               CandidateSet, PartialOverloading,
11736                               /*KnownValid*/ true);
11737
11738  if (ULE->requiresADL())
11739    AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11740                                         Args, ExplicitTemplateArgs,
11741                                         CandidateSet, PartialOverloading);
11742}
11743
11744/// Determine whether a declaration with the specified name could be moved into
11745/// a different namespace.
11746static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11747  switch (Name.getCXXOverloadedOperator()) {
11748  case OO_Newcase OO_Array_New:
11749  case OO_Deletecase OO_Array_Delete:
11750    return false;
11751
11752  default:
11753    return true;
11754  }
11755}
11756
11757/// Attempt to recover from an ill-formed use of a non-dependent name in a
11758/// template, where the non-dependent name was declared after the template
11759/// was defined. This is common in code written for a compilers which do not
11760/// correctly implement two-stage name lookup.
11761///
11762/// Returns true if a viable candidate was found and a diagnostic was issued.
11763static bool
11764DiagnoseTwoPhaseLookup(Sema &SemaRefSourceLocation FnLoc,
11765                       const CXXScopeSpec &SSLookupResult &R,
11766                       OverloadCandidateSet::CandidateSetKind CSK,
11767                       TemplateArgumentListInfo *ExplicitTemplateArgs,
11768                       ArrayRef<Expr *> Args,
11769                       bool *DoDiagnoseEmptyLookup = nullptr) {
11770  if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11771    return false;
11772
11773  for (DeclContext *DC = SemaRef.CurContextDCDC = DC->getParent()) {
11774    if (DC->isTransparentContext())
11775      continue;
11776
11777    SemaRef.LookupQualifiedName(RDC);
11778
11779    if (!R.empty()) {
11780      R.suppressDiagnostics();
11781
11782      if (isa<CXXRecordDecl>(DC)) {
11783        // Don't diagnose names we find in classes; we get much better
11784        // diagnostics for these from DiagnoseEmptyLookup.
11785        R.clear();
11786        if (DoDiagnoseEmptyLookup)
11787          *DoDiagnoseEmptyLookup = true;
11788        return false;
11789      }
11790
11791      OverloadCandidateSet Candidates(FnLocCSK);
11792      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11793        AddOverloadedCallCandidate(SemaRef, I.getPair(),
11794                                   ExplicitTemplateArgs, Args,
11795                                   Candidates, false/*KnownValid*/ false);
11796
11797      OverloadCandidateSet::iterator Best;
11798      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11799        // No viable functions. Don't bother the user with notes for functions
11800        // which don't work and shouldn't be found anyway.
11801        R.clear();
11802        return false;
11803      }
11804
11805      // Find the namespaces where ADL would have looked, and suggest
11806      // declaring the function there instead.
11807      Sema::AssociatedNamespaceSet AssociatedNamespaces;
11808      Sema::AssociatedClassSet AssociatedClasses;
11809      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11810                                                 AssociatedNamespaces,
11811                                                 AssociatedClasses);
11812      Sema::AssociatedNamespaceSet SuggestedNamespaces;
11813      if (canBeDeclaredInNamespace(R.getLookupName())) {
11814        DeclContext *Std = SemaRef.getStdNamespace();
11815        for (Sema::AssociatedNamespaceSet::iterator
11816               it = AssociatedNamespaces.begin(),
11817               end = AssociatedNamespaces.end(); it != end; ++it) {
11818          // Never suggest declaring a function within namespace 'std'.
11819          if (Std && Std->Encloses(*it))
11820            continue;
11821
11822          // Never suggest declaring a function within a namespace with a
11823          // reserved name, like __gnu_cxx.
11824          NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11825          if (NS &&
11826              NS->getQualifiedNameAsString().find("__") != std::string::npos)
11827            continue;
11828
11829          SuggestedNamespaces.insert(*it);
11830        }
11831      }
11832
11833      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11834        << R.getLookupName();
11835      if (SuggestedNamespaces.empty()) {
11836        SemaRef.Diag(Best->Function->getLocation(),
11837                     diag::note_not_found_by_two_phase_lookup)
11838          << R.getLookupName() << 0;
11839      } else if (SuggestedNamespaces.size() == 1) {
11840        SemaRef.Diag(Best->Function->getLocation(),
11841                     diag::note_not_found_by_two_phase_lookup)
11842          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11843      } else {
11844        // FIXME: It would be useful to list the associated namespaces here,
11845        // but the diagnostics infrastructure doesn't provide a way to produce
11846        // a localized representation of a list of items.
11847        SemaRef.Diag(Best->Function->getLocation(),
11848                     diag::note_not_found_by_two_phase_lookup)
11849          << R.getLookupName() << 2;
11850      }
11851
11852      // Try to recover by calling this function.
11853      return true;
11854    }
11855
11856    R.clear();
11857  }
11858
11859  return false;
11860}
11861
11862/// Attempt to recover from ill-formed use of a non-dependent operator in a
11863/// template, where the non-dependent operator was declared after the template
11864/// was defined.
11865///
11866/// Returns true if a viable candidate was found and a diagnostic was issued.
11867static bool
11868DiagnoseTwoPhaseOperatorLookup(Sema &SemaRefOverloadedOperatorKind Op,
11869                               SourceLocation OpLoc,
11870                               ArrayRef<Expr *> Args) {
11871  DeclarationName OpName =
11872    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11873  LookupResult R(SemaRefOpNameOpLocSema::LookupOperatorName);
11874  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11875                                OverloadCandidateSet::CSK_Operator,
11876                                /*ExplicitTemplateArgs=*/nullptr, Args);
11877}
11878
11879namespace {
11880class BuildRecoveryCallExprRAII {
11881  Sema &SemaRef;
11882public:
11883  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11884    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11885    SemaRef.IsBuildingRecoveryCallExpr = true;
11886  }
11887
11888  ~BuildRecoveryCallExprRAII() {
11889    SemaRef.IsBuildingRecoveryCallExpr = false;
11890  }
11891};
11892
11893}
11894
11895/// Attempts to recover from a call where no functions were found.
11896///
11897/// Returns true if new candidates were found.
11898static ExprResult
11899BuildRecoveryCallExpr(Sema &SemaRefScope *SExpr *Fn,
11900                      UnresolvedLookupExpr *ULE,
11901                      SourceLocation LParenLoc,
11902                      MutableArrayRef<Expr *> Args,
11903                      SourceLocation RParenLoc,
11904                      bool EmptyLookupbool AllowTypoCorrection) {
11905  // Do not try to recover if it is already building a recovery call.
11906  // This stops infinite loops for template instantiations like
11907  //
11908  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11909  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11910  //
11911  if (SemaRef.IsBuildingRecoveryCallExpr)
11912    return ExprError();
11913  BuildRecoveryCallExprRAII RCE(SemaRef);
11914
11915  CXXScopeSpec SS;
11916  SS.Adopt(ULE->getQualifierLoc());
11917  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11918
11919  TemplateArgumentListInfo TABuffer;
11920  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11921  if (ULE->hasExplicitTemplateArgs()) {
11922    ULE->copyTemplateArgumentsInto(TABuffer);
11923    ExplicitTemplateArgs = &TABuffer;
11924  }
11925
11926  LookupResult R(SemaRefULE->getName(), ULE->getNameLoc(),
11927                 Sema::LookupOrdinaryName);
11928  bool DoDiagnoseEmptyLookup = EmptyLookup;
11929  if (!DiagnoseTwoPhaseLookup(
11930          SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
11931          ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
11932    NoTypoCorrectionCCC NoTypoValidator{};
11933    FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
11934                                                ExplicitTemplateArgs != nullptr,
11935                                                dyn_cast<MemberExpr>(Fn));
11936    CorrectionCandidateCallback &Validator =
11937        AllowTypoCorrection
11938            ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
11939            : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
11940    if (!DoDiagnoseEmptyLookup ||
11941        SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
11942                                    Args))
11943      return ExprError();
11944  }
11945
11946   (0) . __assert_fail ("!R.empty() && \"lookup results empty despite recovery\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11946, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!R.empty() && "lookup results empty despite recovery");
11947
11948  // If recovery created an ambiguity, just bail out.
11949  if (R.isAmbiguous()) {
11950    R.suppressDiagnostics();
11951    return ExprError();
11952  }
11953
11954  // Build an implicit member call if appropriate.  Just drop the
11955  // casts and such from the call, we don't really care.
11956  ExprResult NewFn = ExprError();
11957  if ((*R.begin())->isCXXClassMember())
11958    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SSTemplateKWLocR,
11959                                                    ExplicitTemplateArgsS);
11960  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11961    NewFn = SemaRef.BuildTemplateIdExpr(SSTemplateKWLocRfalse,
11962                                        ExplicitTemplateArgs);
11963  else
11964    NewFn = SemaRef.BuildDeclarationNameExpr(SSRfalse);
11965
11966  if (NewFn.isInvalid())
11967    return ExprError();
11968
11969  // This shouldn't cause an infinite loop because we're giving it
11970  // an expression with viable lookup results, which should never
11971  // end up here.
11972  return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11973                               MultiExprArg(Args.data(), Args.size()),
11974                               RParenLoc);
11975}
11976
11977/// Constructs and populates an OverloadedCandidateSet from
11978/// the given function.
11979/// \returns true when an the ExprResult output parameter has been set.
11980bool Sema::buildOverloadedCallSet(Scope *SExpr *Fn,
11981                                  UnresolvedLookupExpr *ULE,
11982                                  MultiExprArg Args,
11983                                  SourceLocation RParenLoc,
11984                                  OverloadCandidateSet *CandidateSet,
11985                                  ExprResult *Result) {
11986#ifndef NDEBUG
11987  if (ULE->requiresADL()) {
11988    // To do ADL, we must have found an unqualified name.
11989     (0) . __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 11989, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!ULE->getQualifier() && "qualified name with ADL");
11990
11991    // We don't perform ADL for implicit declarations of builtins.
11992    // Verify that this was correctly set up.
11993    FunctionDecl *F;
11994    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11995        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11996        F->getBuiltinID() && F->isImplicit())
11997      llvm_unreachable("performing ADL for builtin");
11998
11999    // We don't perform ADL in C.
12000     (0) . __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12000, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12001  }
12002#endif
12003
12004  UnbridgedCastsSet UnbridgedCasts;
12005  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12006    *Result = ExprError();
12007    return true;
12008  }
12009
12010  // Add the functions denoted by the callee to the set of candidate
12011  // functions, including those from argument-dependent lookup.
12012  AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12013
12014  if (getLangOpts().MSVCCompat &&
12015      CurContext->isDependentContext() && !isSFINAEContext() &&
12016      (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12017
12018    OverloadCandidateSet::iterator Best;
12019    if (CandidateSet->empty() ||
12020        CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12021            OR_No_Viable_Function) {
12022      // In Microsoft mode, if we are inside a template class member function
12023      // then create a type dependent CallExpr. The goal is to postpone name
12024      // lookup to instantiation time to be able to search into type dependent
12025      // base classes.
12026      CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12027                                      VK_RValue, RParenLoc);
12028      CE->setTypeDependent(true);
12029      CE->setValueDependent(true);
12030      CE->setInstantiationDependent(true);
12031      *Result = CE;
12032      return true;
12033    }
12034  }
12035
12036  if (CandidateSet->empty())
12037    return false;
12038
12039  UnbridgedCasts.restore();
12040  return false;
12041}
12042
12043/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12044/// the completed call expression. If overload resolution fails, emits
12045/// diagnostics and returns ExprError()
12046static ExprResult FinishOverloadedCallExpr(Sema &SemaRefScope *SExpr *Fn,
12047                                           UnresolvedLookupExpr *ULE,
12048                                           SourceLocation LParenLoc,
12049                                           MultiExprArg Args,
12050                                           SourceLocation RParenLoc,
12051                                           Expr *ExecConfig,
12052                                           OverloadCandidateSet *CandidateSet,
12053                                           OverloadCandidateSet::iterator *Best,
12054                                           OverloadingResult OverloadResult,
12055                                           bool AllowTypoCorrection) {
12056  if (CandidateSet->empty())
12057    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12058                                 RParenLoc, /*EmptyLookup=*/true,
12059                                 AllowTypoCorrection);
12060
12061  switch (OverloadResult) {
12062  case OR_Success: {
12063    FunctionDecl *FDecl = (*Best)->Function;
12064    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12065    if (SemaRef.DiagnoseUseOfDecl(FDeclULE->getNameLoc()))
12066      return ExprError();
12067    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12068    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12069                                         ExecConfig, /*IsExecConfig=*/false,
12070                                         (*Best)->IsADLCandidate);
12071  }
12072
12073  case OR_No_Viable_Function: {
12074    // Try to recover by looking for viable functions which the user might
12075    // have meant to call.
12076    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12077                                                Args, RParenLoc,
12078                                                /*EmptyLookup=*/false,
12079                                                AllowTypoCorrection);
12080    if (!Recovery.isInvalid())
12081      return Recovery;
12082
12083    // If the user passes in a function that we can't take the address of, we
12084    // generally end up emitting really bad error messages. Here, we attempt to
12085    // emit better ones.
12086    for (const Expr *Arg : Args) {
12087      if (!Arg->getType()->isFunctionType())
12088        continue;
12089      if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12090        auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12091        if (FD &&
12092            !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12093                                                       Arg->getExprLoc()))
12094          return ExprError();
12095      }
12096    }
12097
12098    SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12099        << ULE->getName() << Fn->getSourceRange();
12100    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12101    break;
12102  }
12103
12104  case OR_Ambiguous:
12105    SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12106        << ULE->getName() << Fn->getSourceRange();
12107    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12108    break;
12109
12110  case OR_Deleted: {
12111    SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12112        << ULE->getName() << Fn->getSourceRange();
12113    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12114
12115    // We emitted an error for the unavailable/deleted function call but keep
12116    // the call in the AST.
12117    FunctionDecl *FDecl = (*Best)->Function;
12118    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12119    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12120                                         ExecConfig, /*IsExecConfig=*/false,
12121                                         (*Best)->IsADLCandidate);
12122  }
12123  }
12124
12125  // Overload resolution failed.
12126  return ExprError();
12127}
12128
12129static void markUnaddressableCandidatesUnviable(Sema &S,
12130                                                OverloadCandidateSet &CS) {
12131  for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12132    if (I->Viable &&
12133        !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12134      I->Viable = false;
12135      I->FailureKind = ovl_fail_addr_not_available;
12136    }
12137  }
12138}
12139
12140/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12141/// (which eventually refers to the declaration Func) and the call
12142/// arguments Args/NumArgs, attempt to resolve the function call down
12143/// to a specific function. If overload resolution succeeds, returns
12144/// the call expression produced by overload resolution.
12145/// Otherwise, emits diagnostics and returns ExprError.
12146ExprResult Sema::BuildOverloadedCallExpr(Scope *SExpr *Fn,
12147                                         UnresolvedLookupExpr *ULE,
12148                                         SourceLocation LParenLoc,
12149                                         MultiExprArg Args,
12150                                         SourceLocation RParenLoc,
12151                                         Expr *ExecConfig,
12152                                         bool AllowTypoCorrection,
12153                                         bool CalleesAddressIsTaken) {
12154  OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12155                                    OverloadCandidateSet::CSK_Normal);
12156  ExprResult result;
12157
12158  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12159                             &result))
12160    return result;
12161
12162  // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12163  // functions that aren't addressible are considered unviable.
12164  if (CalleesAddressIsTaken)
12165    markUnaddressableCandidatesUnviable(*thisCandidateSet);
12166
12167  OverloadCandidateSet::iterator Best;
12168  OverloadingResult OverloadResult =
12169      CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12170
12171  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12172                                  RParenLoc, ExecConfig, &CandidateSet,
12173                                  &Best, OverloadResult,
12174                                  AllowTypoCorrection);
12175}
12176
12177static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12178  return Functions.size() > 1 ||
12179    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12180}
12181
12182/// Create a unary operation that may resolve to an overloaded
12183/// operator.
12184///
12185/// \param OpLoc The location of the operator itself (e.g., '*').
12186///
12187/// \param Opc The UnaryOperatorKind that describes this operator.
12188///
12189/// \param Fns The set of non-member functions that will be
12190/// considered by overload resolution. The caller needs to build this
12191/// set based on the context using, e.g.,
12192/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12193/// set should not contain any member functions; those will be added
12194/// by CreateOverloadedUnaryOp().
12195///
12196/// \param Input The input argument.
12197ExprResult
12198Sema::CreateOverloadedUnaryOp(SourceLocation OpLocUnaryOperatorKind Opc,
12199                              const UnresolvedSetImpl &Fns,
12200                              Expr *Inputbool PerformADL) {
12201  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12202   (0) . __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12202, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12203  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12204  // TODO: provide better source location info.
12205  DeclarationNameInfo OpNameInfo(OpNameOpLoc);
12206
12207  if (checkPlaceholderForOverload(*thisInput))
12208    return ExprError();
12209
12210  Expr *Args[2] = { Inputnullptr };
12211  unsigned NumArgs = 1;
12212
12213  // For post-increment and post-decrement, add the implicit '0' as
12214  // the second argument, so that we know this is a post-increment or
12215  // post-decrement.
12216  if (Opc == UO_PostInc || Opc == UO_PostDec) {
12217    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12218    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12219                                     SourceLocation());
12220    NumArgs = 2;
12221  }
12222
12223  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12224
12225  if (Input->isTypeDependent()) {
12226    if (Fns.empty())
12227      return new (ContextUnaryOperator(InputOpcContext.DependentTy,
12228                                         VK_RValueOK_OrdinaryOpLocfalse);
12229
12230    CXXRecordDecl *NamingClass = nullptr// lookup ignores member operators
12231    UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12232        ContextNamingClassNestedNameSpecifierLoc(), OpNameInfo,
12233        /*ADL*/ trueIsOverloaded(Fns), Fns.begin(), Fns.end());
12234    return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12235                                       Context.DependentTy, VK_RValue, OpLoc,
12236                                       FPOptions());
12237  }
12238
12239  // Build an empty overload set.
12240  OverloadCandidateSet CandidateSet(OpLocOverloadCandidateSet::CSK_Operator);
12241
12242  // Add the candidates from the given function set.
12243  AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12244
12245  // Add operator candidates that are member functions.
12246  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12247
12248  // Add candidates from ADL.
12249  if (PerformADL) {
12250    AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12251                                         /*ExplicitTemplateArgs*/nullptr,
12252                                         CandidateSet);
12253  }
12254
12255  // Add builtin operator candidates.
12256  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12257
12258  bool HadMultipleCandidates = (CandidateSet.size() > 1);
12259
12260  // Perform overload resolution.
12261  OverloadCandidateSet::iterator Best;
12262  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12263  case OR_Success: {
12264    // We found a built-in operator or an overloaded operator.
12265    FunctionDecl *FnDecl = Best->Function;
12266
12267    if (FnDecl) {
12268      Expr *Base = nullptr;
12269      // We matched an overloaded operator. Build a call to that
12270      // operator.
12271
12272      // Convert the arguments.
12273      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12274        CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12275
12276        ExprResult InputRes =
12277          PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12278                                              Best->FoundDecl, Method);
12279        if (InputRes.isInvalid())
12280          return ExprError();
12281        Base = Input = InputRes.get();
12282      } else {
12283        // Convert the arguments.
12284        ExprResult InputInit
12285          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12286                                                      Context,
12287                                                      FnDecl->getParamDecl(0)),
12288                                      SourceLocation(),
12289                                      Input);
12290        if (InputInit.isInvalid())
12291          return ExprError();
12292        Input = InputInit.get();
12293      }
12294
12295      // Build the actual expression node.
12296      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12297                                                Base, HadMultipleCandidates,
12298                                                OpLoc);
12299      if (FnExpr.isInvalid())
12300        return ExprError();
12301
12302      // Determine the result type.
12303      QualType ResultTy = FnDecl->getReturnType();
12304      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12305      ResultTy = ResultTy.getNonLValueExprType(Context);
12306
12307      Args[0] = Input;
12308      CallExpr *TheCall = CXXOperatorCallExpr::Create(
12309          Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12310          FPOptions(), Best->IsADLCandidate);
12311
12312      if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12313        return ExprError();
12314
12315      if (CheckFunctionCall(FnDecl, TheCall,
12316                            FnDecl->getType()->castAs<FunctionProtoType>()))
12317        return ExprError();
12318
12319      return MaybeBindToTemporary(TheCall);
12320    } else {
12321      // We matched a built-in operator. Convert the arguments, then
12322      // break out so that we will build the appropriate built-in
12323      // operator node.
12324      ExprResult InputRes = PerformImplicitConversion(
12325          Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12326          CCK_ForBuiltinOverloadedOp);
12327      if (InputRes.isInvalid())
12328        return ExprError();
12329      Input = InputRes.get();
12330      break;
12331    }
12332  }
12333
12334  case OR_No_Viable_Function:
12335    // This is an erroneous use of an operator which can be overloaded by
12336    // a non-member function. Check for non-member operators which were
12337    // defined too late to be candidates.
12338    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12339      // FIXME: Recover by calling the found function.
12340      return ExprError();
12341
12342    // No viable function; fall through to handling this as a
12343    // built-in operator, which will produce an error message for us.
12344    break;
12345
12346  case OR_Ambiguous:
12347    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12348        << UnaryOperator::getOpcodeStr(Opc)
12349        << Input->getType()
12350        << Input->getSourceRange();
12351    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12352                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
12353    return ExprError();
12354
12355  case OR_Deleted:
12356    Diag(OpLoc, diag::err_ovl_deleted_oper)
12357        << UnaryOperator::getOpcodeStr(Opc) << Input->getSourceRange();
12358    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12359                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
12360    return ExprError();
12361  }
12362
12363  // Either we found no viable overloaded operator or we matched a
12364  // built-in operator. In either case, fall through to trying to
12365  // build a built-in operation.
12366  return CreateBuiltinUnaryOp(OpLocOpcInput);
12367}
12368
12369/// Create a binary operation that may resolve to an overloaded
12370/// operator.
12371///
12372/// \param OpLoc The location of the operator itself (e.g., '+').
12373///
12374/// \param Opc The BinaryOperatorKind that describes this operator.
12375///
12376/// \param Fns The set of non-member functions that will be
12377/// considered by overload resolution. The caller needs to build this
12378/// set based on the context using, e.g.,
12379/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12380/// set should not contain any member functions; those will be added
12381/// by CreateOverloadedBinOp().
12382///
12383/// \param LHS Left-hand argument.
12384/// \param RHS Right-hand argument.
12385ExprResult
12386Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12387                            BinaryOperatorKind Opc,
12388                            const UnresolvedSetImpl &Fns,
12389                            Expr *LHSExpr *RHSbool PerformADL) {
12390  Expr *Args[2] = { LHSRHS };
12391  LHS=RHS=nullptr// Please use only Args instead of LHS/RHS couple
12392
12393  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12394  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12395
12396  // If either side is type-dependent, create an appropriate dependent
12397  // expression.
12398  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12399    if (Fns.empty()) {
12400      // If there are no functions to store, just build a dependent
12401      // BinaryOperator or CompoundAssignment.
12402      if (Opc <= BO_Assign || Opc > BO_OrAssign)
12403        return new (ContextBinaryOperator(
12404            Args[0], Args[1], OpcContext.DependentTyVK_RValueOK_Ordinary,
12405            OpLocFPFeatures);
12406
12407      return new (ContextCompoundAssignOperator(
12408          Args[0], Args[1], OpcContext.DependentTyVK_LValueOK_Ordinary,
12409          Context.DependentTyContext.DependentTyOpLoc,
12410          FPFeatures);
12411    }
12412
12413    // FIXME: save results of ADL from here?
12414    CXXRecordDecl *NamingClass = nullptr// lookup ignores member operators
12415    // TODO: provide better source location info in DNLoc component.
12416    DeclarationNameInfo OpNameInfo(OpNameOpLoc);
12417    UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12418        ContextNamingClassNestedNameSpecifierLoc(), OpNameInfo,
12419        /*ADL*/ PerformADLIsOverloaded(Fns), Fns.begin(), Fns.end());
12420    return CXXOperatorCallExpr::Create(ContextOpFnArgs,
12421                                       Context.DependentTyVK_RValueOpLoc,
12422                                       FPFeatures);
12423  }
12424
12425  // Always do placeholder-like conversions on the RHS.
12426  if (checkPlaceholderForOverload(*thisArgs[1]))
12427    return ExprError();
12428
12429  // Do placeholder-like conversion on the LHS; note that we should
12430  // not get here with a PseudoObject LHS.
12431  getObjectKind() != OK_ObjCProperty", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12431, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12432  if (checkPlaceholderForOverload(*thisArgs[0]))
12433    return ExprError();
12434
12435  // If this is the assignment operator, we only perform overload resolution
12436  // if the left-hand side is a class or enumeration type. This is actually
12437  // a hack. The standard requires that we do overload resolution between the
12438  // various built-in candidates, but as DR507 points out, this can lead to
12439  // problems. So we do it this way, which pretty much follows what GCC does.
12440  // Note that we go the traditional code path for compound assignment forms.
12441  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12442    return CreateBuiltinBinOp(OpLocOpcArgs[0], Args[1]);
12443
12444  // If this is the .* operator, which is not overloadable, just
12445  // create a built-in binary operator.
12446  if (Opc == BO_PtrMemD)
12447    return CreateBuiltinBinOp(OpLocOpcArgs[0], Args[1]);
12448
12449  // Build an empty overload set.
12450  OverloadCandidateSet CandidateSet(OpLocOverloadCandidateSet::CSK_Operator);
12451
12452  // Add the candidates from the given function set.
12453  AddFunctionCandidates(FnsArgsCandidateSet);
12454
12455  // Add operator candidates that are member functions.
12456  AddMemberOperatorCandidates(OpOpLocArgsCandidateSet);
12457
12458  // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12459  // performed for an assignment operator (nor for operator[] nor operator->,
12460  // which don't get here).
12461  if (Opc != BO_Assign && PerformADL)
12462    AddArgumentDependentLookupCandidates(OpNameOpLocArgs,
12463                                         /*ExplicitTemplateArgs*/ nullptr,
12464                                         CandidateSet);
12465
12466  // Add builtin operator candidates.
12467  AddBuiltinOperatorCandidates(OpOpLocArgsCandidateSet);
12468
12469  bool HadMultipleCandidates = (CandidateSet.size() > 1);
12470
12471  // Perform overload resolution.
12472  OverloadCandidateSet::iterator Best;
12473  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12474    case OR_Success: {
12475      // We found a built-in operator or an overloaded operator.
12476      FunctionDecl *FnDecl = Best->Function;
12477
12478      if (FnDecl) {
12479        Expr *Base = nullptr;
12480        // We matched an overloaded operator. Build a call to that
12481        // operator.
12482
12483        // Convert the arguments.
12484        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12485          // Best->Access is only meaningful for class members.
12486          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12487
12488          ExprResult Arg1 =
12489            PerformCopyInitialization(
12490              InitializedEntity::InitializeParameter(Context,
12491                                                     FnDecl->getParamDecl(0)),
12492              SourceLocation(), Args[1]);
12493          if (Arg1.isInvalid())
12494            return ExprError();
12495
12496          ExprResult Arg0 =
12497            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12498                                                Best->FoundDecl, Method);
12499          if (Arg0.isInvalid())
12500            return ExprError();
12501          Base = Args[0] = Arg0.getAs<Expr>();
12502          Args[1] = RHS = Arg1.getAs<Expr>();
12503        } else {
12504          // Convert the arguments.
12505          ExprResult Arg0 = PerformCopyInitialization(
12506            InitializedEntity::InitializeParameter(Context,
12507                                                   FnDecl->getParamDecl(0)),
12508            SourceLocation(), Args[0]);
12509          if (Arg0.isInvalid())
12510            return ExprError();
12511
12512          ExprResult Arg1 =
12513            PerformCopyInitialization(
12514              InitializedEntity::InitializeParameter(Context,
12515                                                     FnDecl->getParamDecl(1)),
12516              SourceLocation(), Args[1]);
12517          if (Arg1.isInvalid())
12518            return ExprError();
12519          Args[0] = LHS = Arg0.getAs<Expr>();
12520          Args[1] = RHS = Arg1.getAs<Expr>();
12521        }
12522
12523        // Build the actual expression node.
12524        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12525                                                  Best->FoundDecl, Base,
12526                                                  HadMultipleCandidates, OpLoc);
12527        if (FnExpr.isInvalid())
12528          return ExprError();
12529
12530        // Determine the result type.
12531        QualType ResultTy = FnDecl->getReturnType();
12532        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12533        ResultTy = ResultTy.getNonLValueExprType(Context);
12534
12535        CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12536            Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12537            Best->IsADLCandidate);
12538
12539        if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12540                                FnDecl))
12541          return ExprError();
12542
12543        ArrayRef<const Expr *> ArgsArray(Args, 2);
12544        const Expr *ImplicitThis = nullptr;
12545        // Cut off the implicit 'this'.
12546        if (isa<CXXMethodDecl>(FnDecl)) {
12547          ImplicitThis = ArgsArray[0];
12548          ArgsArray = ArgsArray.slice(1);
12549        }
12550
12551        // Check for a self move.
12552        if (Op == OO_Equal)
12553          DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12554
12555        checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12556                  isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12557                  VariadicDoesNotApply);
12558
12559        return MaybeBindToTemporary(TheCall);
12560      } else {
12561        // We matched a built-in operator. Convert the arguments, then
12562        // break out so that we will build the appropriate built-in
12563        // operator node.
12564        ExprResult ArgsRes0 = PerformImplicitConversion(
12565            Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12566            AA_Passing, CCK_ForBuiltinOverloadedOp);
12567        if (ArgsRes0.isInvalid())
12568          return ExprError();
12569        Args[0] = ArgsRes0.get();
12570
12571        ExprResult ArgsRes1 = PerformImplicitConversion(
12572            Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12573            AA_Passing, CCK_ForBuiltinOverloadedOp);
12574        if (ArgsRes1.isInvalid())
12575          return ExprError();
12576        Args[1] = ArgsRes1.get();
12577        break;
12578      }
12579    }
12580
12581    case OR_No_Viable_Function: {
12582      // C++ [over.match.oper]p9:
12583      //   If the operator is the operator , [...] and there are no
12584      //   viable functions, then the operator is assumed to be the
12585      //   built-in operator and interpreted according to clause 5.
12586      if (Opc == BO_Comma)
12587        break;
12588
12589      // For class as left operand for assignment or compound assignment
12590      // operator do not fall through to handling in built-in, but report that
12591      // no overloaded assignment operator found
12592      ExprResult Result = ExprError();
12593      if (Args[0]->getType()->isRecordType() &&
12594          Opc >= BO_Assign && Opc <= BO_OrAssign) {
12595        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12596             << BinaryOperator::getOpcodeStr(Opc)
12597             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12598        if (Args[0]->getType()->isIncompleteType()) {
12599          Diag(OpLoc, diag::note_assign_lhs_incomplete)
12600            << Args[0]->getType()
12601            << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12602        }
12603      } else {
12604        // This is an erroneous use of an operator which can be overloaded by
12605        // a non-member function. Check for non-member operators which were
12606        // defined too late to be candidates.
12607        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12608          // FIXME: Recover by calling the found function.
12609          return ExprError();
12610
12611        // No viable function; try to create a built-in operation, which will
12612        // produce an error. Then, show the non-viable candidates.
12613        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12614      }
12615       (0) . __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12616, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Result.isInvalid() &&
12616 (0) . __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12616, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "C++ binary operator overloading is missing candidates!");
12617      if (Result.isInvalid())
12618        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12619                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
12620      return Result;
12621    }
12622
12623    case OR_Ambiguous:
12624      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12625          << BinaryOperator::getOpcodeStr(Opc)
12626          << Args[0]->getType() << Args[1]->getType()
12627          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12628      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12629                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
12630      return ExprError();
12631
12632    case OR_Deleted:
12633      if (isImplicitlyDeleted(Best->Function)) {
12634        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12635        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12636          << Context.getRecordType(Method->getParent())
12637          << getSpecialMember(Method);
12638
12639        // The user probably meant to call this special member. Just
12640        // explain why it's deleted.
12641        NoteDeletedFunction(Method);
12642        return ExprError();
12643      } else {
12644        Diag(OpLoc, diag::err_ovl_deleted_oper)
12645            << BinaryOperator::getOpcodeStr(Opc) << Args[0]->getSourceRange()
12646            << Args[1]->getSourceRange();
12647      }
12648      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12649                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
12650      return ExprError();
12651  }
12652
12653  // We matched a built-in operator; build it.
12654  return CreateBuiltinBinOp(OpLocOpcArgs[0], Args[1]);
12655}
12656
12657ExprResult
12658Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12659                                         SourceLocation RLoc,
12660                                         Expr *BaseExpr *Idx) {
12661  Expr *Args[2] = { BaseIdx };
12662  DeclarationName OpName =
12663      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12664
12665  // If either side is type-dependent, create an appropriate dependent
12666  // expression.
12667  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12668
12669    CXXRecordDecl *NamingClass = nullptr// lookup ignores member operators
12670    // CHECKME: no 'operator' keyword?
12671    DeclarationNameInfo OpNameInfo(OpNameLLoc);
12672    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLocRLoc));
12673    UnresolvedLookupExpr *Fn
12674      = UnresolvedLookupExpr::Create(ContextNamingClass,
12675                                     NestedNameSpecifierLoc(), OpNameInfo,
12676                                     /*ADL*/ true/*Overloaded*/ false,
12677                                     UnresolvedSetIterator(),
12678                                     UnresolvedSetIterator());
12679    // Can't add any actual overloads yet
12680
12681    return CXXOperatorCallExpr::Create(ContextOO_SubscriptFnArgs,
12682                                       Context.DependentTyVK_RValueRLoc,
12683                                       FPOptions());
12684  }
12685
12686  // Handle placeholders on both operands.
12687  if (checkPlaceholderForOverload(*thisArgs[0]))
12688    return ExprError();
12689  if (checkPlaceholderForOverload(*thisArgs[1]))
12690    return ExprError();
12691
12692  // Build an empty overload set.
12693  OverloadCandidateSet CandidateSet(LLocOverloadCandidateSet::CSK_Operator);
12694
12695  // Subscript can only be overloaded as a member function.
12696
12697  // Add operator candidates that are member functions.
12698  AddMemberOperatorCandidates(OO_SubscriptLLocArgsCandidateSet);
12699
12700  // Add builtin operator candidates.
12701  AddBuiltinOperatorCandidates(OO_SubscriptLLocArgsCandidateSet);
12702
12703  bool HadMultipleCandidates = (CandidateSet.size() > 1);
12704
12705  // Perform overload resolution.
12706  OverloadCandidateSet::iterator Best;
12707  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12708    case OR_Success: {
12709      // We found a built-in operator or an overloaded operator.
12710      FunctionDecl *FnDecl = Best->Function;
12711
12712      if (FnDecl) {
12713        // We matched an overloaded operator. Build a call to that
12714        // operator.
12715
12716        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12717
12718        // Convert the arguments.
12719        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12720        ExprResult Arg0 =
12721          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12722                                              Best->FoundDecl, Method);
12723        if (Arg0.isInvalid())
12724          return ExprError();
12725        Args[0] = Arg0.get();
12726
12727        // Convert the arguments.
12728        ExprResult InputInit
12729          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12730                                                      Context,
12731                                                      FnDecl->getParamDecl(0)),
12732                                      SourceLocation(),
12733                                      Args[1]);
12734        if (InputInit.isInvalid())
12735          return ExprError();
12736
12737        Args[1] = InputInit.getAs<Expr>();
12738
12739        // Build the actual expression node.
12740        DeclarationNameInfo OpLocInfo(OpName, LLoc);
12741        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12742        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12743                                                  Best->FoundDecl,
12744                                                  Base,
12745                                                  HadMultipleCandidates,
12746                                                  OpLocInfo.getLoc(),
12747                                                  OpLocInfo.getInfo());
12748        if (FnExpr.isInvalid())
12749          return ExprError();
12750
12751        // Determine the result type
12752        QualType ResultTy = FnDecl->getReturnType();
12753        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12754        ResultTy = ResultTy.getNonLValueExprType(Context);
12755
12756        CXXOperatorCallExpr *TheCall =
12757            CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12758                                        Args, ResultTy, VK, RLoc, FPOptions());
12759
12760        if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12761          return ExprError();
12762
12763        if (CheckFunctionCall(Method, TheCall,
12764                              Method->getType()->castAs<FunctionProtoType>()))
12765          return ExprError();
12766
12767        return MaybeBindToTemporary(TheCall);
12768      } else {
12769        // We matched a built-in operator. Convert the arguments, then
12770        // break out so that we will build the appropriate built-in
12771        // operator node.
12772        ExprResult ArgsRes0 = PerformImplicitConversion(
12773            Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12774            AA_Passing, CCK_ForBuiltinOverloadedOp);
12775        if (ArgsRes0.isInvalid())
12776          return ExprError();
12777        Args[0] = ArgsRes0.get();
12778
12779        ExprResult ArgsRes1 = PerformImplicitConversion(
12780            Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12781            AA_Passing, CCK_ForBuiltinOverloadedOp);
12782        if (ArgsRes1.isInvalid())
12783          return ExprError();
12784        Args[1] = ArgsRes1.get();
12785
12786        break;
12787      }
12788    }
12789
12790    case OR_No_Viable_Function: {
12791      if (CandidateSet.empty())
12792        Diag(LLoc, diag::err_ovl_no_oper)
12793          << Args[0]->getType() << /*subscript*/ 0
12794          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12795      else
12796        Diag(LLoc, diag::err_ovl_no_viable_subscript)
12797          << Args[0]->getType()
12798          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12799      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12800                                  "[]", LLoc);
12801      return ExprError();
12802    }
12803
12804    case OR_Ambiguous:
12805      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12806          << "[]"
12807          << Args[0]->getType() << Args[1]->getType()
12808          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12809      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12810                                  "[]", LLoc);
12811      return ExprError();
12812
12813    case OR_Deleted:
12814      Diag(LLoc, diag::err_ovl_deleted_oper)
12815          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12816      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, "[]", LLoc);
12817      return ExprError();
12818    }
12819
12820  // We matched a built-in operator; build it.
12821  return CreateBuiltinArraySubscriptExpr(Args[0], LLocArgs[1], RLoc);
12822}
12823
12824/// BuildCallToMemberFunction - Build a call to a member
12825/// function. MemExpr is the expression that refers to the member
12826/// function (and includes the object parameter), Args/NumArgs are the
12827/// arguments to the function call (not including the object
12828/// parameter). The caller needs to validate that the member
12829/// expression refers to a non-static member function or an overloaded
12830/// member function.
12831ExprResult
12832Sema::BuildCallToMemberFunction(Scope *SExpr *MemExprE,
12833                                SourceLocation LParenLoc,
12834                                MultiExprArg Args,
12835                                SourceLocation RParenLoc) {
12836  getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12837, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(MemExprE->getType() == Context.BoundMemberTy ||
12837getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12837, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         MemExprE->getType() == Context.OverloadTy);
12838
12839  // Dig out the member expression. This holds both the object
12840  // argument and the member function we're referring to.
12841  Expr *NakedMemExpr = MemExprE->IgnoreParens();
12842
12843  // Determine whether this is a call to a pointer-to-member function.
12844  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12845    getType() == Context.BoundMemberTy", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12845, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(op->getType() == Context.BoundMemberTy);
12846    getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 12846, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12847
12848    QualType fnType =
12849      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12850
12851    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12852    QualType resultType = proto->getCallResultType(Context);
12853    ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12854
12855    // Check that the object type isn't more qualified than the
12856    // member function we're calling.
12857    Qualifiers funcQuals = proto->getMethodQuals();
12858
12859    QualType objectType = op->getLHS()->getType();
12860    if (op->getOpcode() == BO_PtrMemI)
12861      objectType = objectType->castAs<PointerType>()->getPointeeType();
12862    Qualifiers objectQuals = objectType.getQualifiers();
12863
12864    Qualifiers difference = objectQuals - funcQuals;
12865    difference.removeObjCGCAttr();
12866    difference.removeAddressSpace();
12867    if (difference) {
12868      std::string qualsString = difference.getAsString();
12869      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12870        << fnType.getUnqualifiedType()
12871        << qualsString
12872        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12873    }
12874
12875    CXXMemberCallExpr *call =
12876        CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12877                                  valueKind, RParenLoc, proto->getNumParams());
12878
12879    if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12880                            callnullptr))
12881      return ExprError();
12882
12883    if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12884      return ExprError();
12885
12886    if (CheckOtherCall(callproto))
12887      return ExprError();
12888
12889    return MaybeBindToTemporary(call);
12890  }
12891
12892  if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12893    return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
12894                            RParenLoc);
12895
12896  UnbridgedCastsSet UnbridgedCasts;
12897  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12898    return ExprError();
12899
12900  MemberExpr *MemExpr;
12901  CXXMethodDecl *Method = nullptr;
12902  DeclAccessPair FoundDecl = DeclAccessPair::make(nullptrAS_public);
12903  NestedNameSpecifier *Qualifier = nullptr;
12904  if (isa<MemberExpr>(NakedMemExpr)) {
12905    MemExpr = cast<MemberExpr>(NakedMemExpr);
12906    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12907    FoundDecl = MemExpr->getFoundDecl();
12908    Qualifier = MemExpr->getQualifier();
12909    UnbridgedCasts.restore();
12910  } else {
12911    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12912    Qualifier = UnresExpr->getQualifier();
12913
12914    QualType ObjectType = UnresExpr->getBaseType();
12915    Expr::Classification ObjectClassification
12916      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12917                            : UnresExpr->getBase()->Classify(Context);
12918
12919    // Add overload candidates
12920    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12921                                      OverloadCandidateSet::CSK_Normal);
12922
12923    // FIXME: avoid copy.
12924    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12925    if (UnresExpr->hasExplicitTemplateArgs()) {
12926      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12927      TemplateArgs = &TemplateArgsBuffer;
12928    }
12929
12930    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12931           E = UnresExpr->decls_end(); I != E; ++I) {
12932
12933      NamedDecl *Func = *I;
12934      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12935      if (isa<UsingShadowDecl>(Func))
12936        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12937
12938
12939      // Microsoft supports direct constructor calls.
12940      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12941        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12942                             Args, CandidateSet);
12943      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12944        // If explicit template arguments were provided, we can't call a
12945        // non-template member function.
12946        if (TemplateArgs)
12947          continue;
12948
12949        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12950                           ObjectClassification, Args, CandidateSet,
12951                           /*SuppressUserConversions=*/false);
12952      } else {
12953        AddMethodTemplateCandidate(
12954            cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12955            TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12956            /*SuppressUsedConversions=*/false);
12957      }
12958    }
12959
12960    DeclarationName DeclName = UnresExpr->getMemberName();
12961
12962    UnbridgedCasts.restore();
12963
12964    OverloadCandidateSet::iterator Best;
12965    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12966                                            Best)) {
12967    case OR_Success:
12968      Method = cast<CXXMethodDecl>(Best->Function);
12969      FoundDecl = Best->FoundDecl;
12970      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12971      if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12972        return ExprError();
12973      // If FoundDecl is different from Method (such as if one is a template
12974      // and the other a specialization), make sure DiagnoseUseOfDecl is
12975      // called on both.
12976      // FIXME: This would be more comprehensively addressed by modifying
12977      // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12978      // being used.
12979      if (Method != FoundDecl.getDecl() &&
12980                      DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12981        return ExprError();
12982      break;
12983
12984    case OR_No_Viable_Function:
12985      Diag(UnresExpr->getMemberLoc(),
12986           diag::err_ovl_no_viable_member_function_in_call)
12987        << DeclName << MemExprE->getSourceRange();
12988      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12989      // FIXME: Leaking incoming expressions!
12990      return ExprError();
12991
12992    case OR_Ambiguous:
12993      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12994        << DeclName << MemExprE->getSourceRange();
12995      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12996      // FIXME: Leaking incoming expressions!
12997      return ExprError();
12998
12999    case OR_Deleted:
13000      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
13001          << DeclName << MemExprE->getSourceRange();
13002      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13003      // FIXME: Leaking incoming expressions!
13004      return ExprError();
13005    }
13006
13007    MemExprE = FixOverloadedFunctionReference(MemExprEFoundDeclMethod);
13008
13009    // If overload resolution picked a static member, build a
13010    // non-member call based on that function.
13011    if (Method->isStatic()) {
13012      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13013                                   RParenLoc);
13014    }
13015
13016    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13017  }
13018
13019  QualType ResultType = Method->getReturnType();
13020  ExprValueKind VK = Expr::getValueKindForType(ResultType);
13021  ResultType = ResultType.getNonLValueExprType(Context);
13022
13023   (0) . __assert_fail ("Method && \"Member call to something that isn't a method?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13023, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Method && "Member call to something that isn't a method?");
13024  const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13025  CXXMemberCallExpr *TheCall =
13026      CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13027                                RParenLoc, Proto->getNumParams());
13028
13029  // Check for a valid return type.
13030  if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13031                          TheCallMethod))
13032    return ExprError();
13033
13034  // Convert the object argument (for a non-static member function call).
13035  // We only need to do this if there was actually an overload; otherwise
13036  // it was done at lookup.
13037  if (!Method->isStatic()) {
13038    ExprResult ObjectArg =
13039      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13040                                          FoundDeclMethod);
13041    if (ObjectArg.isInvalid())
13042      return ExprError();
13043    MemExpr->setBase(ObjectArg.get());
13044  }
13045
13046  // Convert the rest of the arguments
13047  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13048                              RParenLoc))
13049    return ExprError();
13050
13051  DiagnoseSentinelCalls(Method, LParenLoc, Args);
13052
13053  if (CheckFunctionCall(Method, TheCall, Proto))
13054    return ExprError();
13055
13056  // In the case the method to call was not selected by the overloading
13057  // resolution process, we still need to handle the enable_if attribute. Do
13058  // that here, so it will not hide previous -- and more relevant -- errors.
13059  if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13060    if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13061      Diag(MemE->getMemberLoc(),
13062           diag::err_ovl_no_viable_member_function_in_call)
13063          << Method << Method->getSourceRange();
13064      Diag(Method->getLocation(),
13065           diag::note_ovl_candidate_disabled_by_function_cond_attr)
13066          << Attr->getCond()->getSourceRange() << Attr->getMessage();
13067      return ExprError();
13068    }
13069  }
13070
13071  if ((isa<CXXConstructorDecl>(CurContext) ||
13072       isa<CXXDestructorDecl>(CurContext)) &&
13073      TheCall->getMethodDecl()->isPure()) {
13074    const CXXMethodDecl *MD = TheCall->getMethodDecl();
13075
13076    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13077        MemExpr->performsVirtualDispatch(getLangOpts())) {
13078      Diag(MemExpr->getBeginLoc(),
13079           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13080          << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13081          << MD->getParent()->getDeclName();
13082
13083      Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13084      if (getLangOpts().AppleKext)
13085        Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13086            << MD->getParent()->getDeclName() << MD->getDeclName();
13087    }
13088  }
13089
13090  if (CXXDestructorDecl *DD =
13091          dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13092    // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13093    bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13094    CheckVirtualDtorCall(DDMemExpr->getBeginLoc(), /*IsDelete=*/false,
13095                         CallCanBeVirtual/*WarnOnNonAbstractTypes=*/true,
13096                         MemExpr->getMemberLoc());
13097  }
13098
13099  return MaybeBindToTemporary(TheCall);
13100}
13101
13102/// BuildCallToObjectOfClassType - Build a call to an object of class
13103/// type (C++ [over.call.object]), which can end up invoking an
13104/// overloaded function call operator (@c operator()) or performing a
13105/// user-defined conversion on the object argument.
13106ExprResult
13107Sema::BuildCallToObjectOfClassType(Scope *SExpr *Obj,
13108                                   SourceLocation LParenLoc,
13109                                   MultiExprArg Args,
13110                                   SourceLocation RParenLoc) {
13111  if (checkPlaceholderForOverload(*thisObj))
13112    return ExprError();
13113  ExprResult Object = Obj;
13114
13115  UnbridgedCastsSet UnbridgedCasts;
13116  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13117    return ExprError();
13118
13119   (0) . __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13120, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Object.get()->getType()->isRecordType() &&
13120 (0) . __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13120, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Requires object type argument");
13121  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13122
13123  // C++ [over.call.object]p1:
13124  //  If the primary-expression E in the function call syntax
13125  //  evaluates to a class object of type "cv T", then the set of
13126  //  candidate functions includes at least the function call
13127  //  operators of T. The function call operators of T are obtained by
13128  //  ordinary lookup of the name operator() in the context of
13129  //  (E).operator().
13130  OverloadCandidateSet CandidateSet(LParenLoc,
13131                                    OverloadCandidateSet::CSK_Operator);
13132  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13133
13134  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13135                          diag::err_incomplete_object_call, Object.get()))
13136    return true;
13137
13138  LookupResult R(*thisOpNameLParenLocLookupOrdinaryName);
13139  LookupQualifiedName(RRecord->getDecl());
13140  R.suppressDiagnostics();
13141
13142  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13143       Oper != OperEnd; ++Oper) {
13144    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13145                       Object.get()->Classify(Context), Args, CandidateSet,
13146                       /*SuppressUserConversions=*/false);
13147  }
13148
13149  // C++ [over.call.object]p2:
13150  //   In addition, for each (non-explicit in C++0x) conversion function
13151  //   declared in T of the form
13152  //
13153  //        operator conversion-type-id () cv-qualifier;
13154  //
13155  //   where cv-qualifier is the same cv-qualification as, or a
13156  //   greater cv-qualification than, cv, and where conversion-type-id
13157  //   denotes the type "pointer to function of (P1,...,Pn) returning
13158  //   R", or the type "reference to pointer to function of
13159  //   (P1,...,Pn) returning R", or the type "reference to function
13160  //   of (P1,...,Pn) returning R", a surrogate call function [...]
13161  //   is also considered as a candidate function. Similarly,
13162  //   surrogate call functions are added to the set of candidate
13163  //   functions for each conversion function declared in an
13164  //   accessible base class provided the function is not hidden
13165  //   within T by another intervening declaration.
13166  const auto &Conversions =
13167      cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13168  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13169    NamedDecl *D = *I;
13170    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13171    if (isa<UsingShadowDecl>(D))
13172      D = cast<UsingShadowDecl>(D)->getTargetDecl();
13173
13174    // Skip over templated conversion functions; they aren't
13175    // surrogates.
13176    if (isa<FunctionTemplateDecl>(D))
13177      continue;
13178
13179    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13180    if (!Conv->isExplicit()) {
13181      // Strip the reference type (if any) and then the pointer type (if
13182      // any) to get down to what might be a function type.
13183      QualType ConvType = Conv->getConversionType().getNonReferenceType();
13184      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13185        ConvType = ConvPtrType->getPointeeType();
13186
13187      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13188      {
13189        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13190                              Object.get(), Args, CandidateSet);
13191      }
13192    }
13193  }
13194
13195  bool HadMultipleCandidates = (CandidateSet.size() > 1);
13196
13197  // Perform overload resolution.
13198  OverloadCandidateSet::iterator Best;
13199  switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13200                                          Best)) {
13201  case OR_Success:
13202    // Overload resolution succeeded; we'll build the appropriate call
13203    // below.
13204    break;
13205
13206  case OR_No_Viable_Function:
13207    if (CandidateSet.empty())
13208      Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13209          << Object.get()->getType() << /*call*/ 1
13210          << Object.get()->getSourceRange();
13211    else
13212      Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13213          << Object.get()->getType() << Object.get()->getSourceRange();
13214    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13215    break;
13216
13217  case OR_Ambiguous:
13218    Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13219        << Object.get()->getType() << Object.get()->getSourceRange();
13220    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13221    break;
13222
13223  case OR_Deleted:
13224    Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13225        << Object.get()->getType() << Object.get()->getSourceRange();
13226    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13227    break;
13228  }
13229
13230  if (Best == CandidateSet.end())
13231    return true;
13232
13233  UnbridgedCasts.restore();
13234
13235  if (Best->Function == nullptr) {
13236    // Since there is no function declaration, this is one of the
13237    // surrogate candidates. Dig out the conversion function.
13238    CXXConversionDecl *Conv
13239      = cast<CXXConversionDecl>(
13240                         Best->Conversions[0].UserDefined.ConversionFunction);
13241
13242    CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13243                              Best->FoundDecl);
13244    if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13245      return ExprError();
13246     (0) . __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13247, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Conv == Best->FoundDecl.getDecl() &&
13247 (0) . __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13247, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "Found Decl & conversion-to-functionptr should be same, right?!");
13248    // We selected one of the surrogate functions that converts the
13249    // object parameter to a function pointer. Perform the conversion
13250    // on the object argument, then let ActOnCallExpr finish the job.
13251
13252    // Create an implicit member expr to refer to the conversion operator.
13253    // and then call it.
13254    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13255                                             Conv, HadMultipleCandidates);
13256    if (Call.isInvalid())
13257      return ExprError();
13258    // Record usage of conversion in an implicit cast.
13259    Call = ImplicitCastExpr::Create(ContextCall.get()->getType(),
13260                                    CK_UserDefinedConversionCall.get(),
13261                                    nullptrVK_RValue);
13262
13263    return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13264  }
13265
13266  CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13267
13268  // We found an overloaded operator(). Build a CXXOperatorCallExpr
13269  // that calls this method, using Object for the implicit object
13270  // parameter and passing along the remaining arguments.
13271  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13272
13273  // An error diagnostic has already been printed when parsing the declaration.
13274  if (Method->isInvalidDecl())
13275    return ExprError();
13276
13277  const FunctionProtoType *Proto =
13278    Method->getType()->getAs<FunctionProtoType>();
13279
13280  unsigned NumParams = Proto->getNumParams();
13281
13282  DeclarationNameInfo OpLocInfo(
13283               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13284  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLocRParenLoc));
13285  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13286                                           Obj, HadMultipleCandidates,
13287                                           OpLocInfo.getLoc(),
13288                                           OpLocInfo.getInfo());
13289  if (NewFn.isInvalid())
13290    return true;
13291
13292  // The number of argument slots to allocate in the call. If we have default
13293  // arguments we need to allocate space for them as well. We additionally
13294  // need one more slot for the object parameter.
13295  unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13296
13297  // Build the full argument list for the method call (the implicit object
13298  // parameter is placed at the beginning of the list).
13299  SmallVector<Expr *, 8MethodArgs(NumArgsSlots);
13300
13301  bool IsError = false;
13302
13303  // Initialize the implicit object parameter.
13304  ExprResult ObjRes =
13305    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13306                                        Best->FoundDecl, Method);
13307  if (ObjRes.isInvalid())
13308    IsError = true;
13309  else
13310    Object = ObjRes;
13311  MethodArgs[0] = Object.get();
13312
13313  // Check the argument types.
13314  for (unsigned i = 0i != NumParamsi++) {
13315    Expr *Arg;
13316    if (i < Args.size()) {
13317      Arg = Args[i];
13318
13319      // Pass the argument.
13320
13321      ExprResult InputInit
13322        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13323                                                    Context,
13324                                                    Method->getParamDecl(i)),
13325                                    SourceLocation(), Arg);
13326
13327      IsError |= InputInit.isInvalid();
13328      Arg = InputInit.getAs<Expr>();
13329    } else {
13330      ExprResult DefArg
13331        = BuildCXXDefaultArgExpr(LParenLocMethodMethod->getParamDecl(i));
13332      if (DefArg.isInvalid()) {
13333        IsError = true;
13334        break;
13335      }
13336
13337      Arg = DefArg.getAs<Expr>();
13338    }
13339
13340    MethodArgs[i + 1] = Arg;
13341  }
13342
13343  // If this is a variadic call, handle args passed through "...".
13344  if (Proto->isVariadic()) {
13345    // Promote the arguments (C99 6.5.2.2p7).
13346    for (unsigned i = NumParamse = Args.size(); i < ei++) {
13347      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13348                                                        nullptr);
13349      IsError |= Arg.isInvalid();
13350      MethodArgs[i + 1] = Arg.get();
13351    }
13352  }
13353
13354  if (IsError)
13355    return true;
13356
13357  DiagnoseSentinelCalls(Method, LParenLoc, Args);
13358
13359  // Once we've built TheCall, all of the expressions are properly owned.
13360  QualType ResultTy = Method->getReturnType();
13361  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13362  ResultTy = ResultTy.getNonLValueExprType(Context);
13363
13364  CXXOperatorCallExpr *TheCall =
13365      CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13366                                  ResultTy, VK, RParenLoc, FPOptions());
13367
13368  if (CheckCallReturnType(Method->getReturnType(), LParenLocTheCallMethod))
13369    return true;
13370
13371  if (CheckFunctionCall(MethodTheCallProto))
13372    return true;
13373
13374  return MaybeBindToTemporary(TheCall);
13375}
13376
13377/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13378///  (if one exists), where @c Base is an expression of class type and
13379/// @c Member is the name of the member we're trying to find.
13380ExprResult
13381Sema::BuildOverloadedArrowExpr(Scope *SExpr *BaseSourceLocation OpLoc,
13382                               bool *NoArrowOperatorFound) {
13383   (0) . __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13384, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Base->getType()->isRecordType() &&
13384 (0) . __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13384, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "left-hand side must have class type");
13385
13386  if (checkPlaceholderForOverload(*thisBase))
13387    return ExprError();
13388
13389  SourceLocation Loc = Base->getExprLoc();
13390
13391  // C++ [over.ref]p1:
13392  //
13393  //   [...] An expression x->m is interpreted as (x.operator->())->m
13394  //   for a class object x of type T if T::operator->() exists and if
13395  //   the operator is selected as the best match function by the
13396  //   overload resolution mechanism (13.3).
13397  DeclarationName OpName =
13398    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13399  OverloadCandidateSet CandidateSet(LocOverloadCandidateSet::CSK_Operator);
13400  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13401
13402  if (RequireCompleteType(Loc, Base->getType(),
13403                          diag::err_typecheck_incomplete_tag, Base))
13404    return ExprError();
13405
13406  LookupResult R(*thisOpNameOpLocLookupOrdinaryName);
13407  LookupQualifiedName(RBaseRecord->getDecl());
13408  R.suppressDiagnostics();
13409
13410  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13411       Oper != OperEnd; ++Oper) {
13412    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13413                       None, CandidateSet, /*SuppressUserConversions=*/false);
13414  }
13415
13416  bool HadMultipleCandidates = (CandidateSet.size() > 1);
13417
13418  // Perform overload resolution.
13419  OverloadCandidateSet::iterator Best;
13420  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13421  case OR_Success:
13422    // Overload resolution succeeded; we'll build the call below.
13423    break;
13424
13425  case OR_No_Viable_Function:
13426    if (CandidateSet.empty()) {
13427      QualType BaseType = Base->getType();
13428      if (NoArrowOperatorFound) {
13429        // Report this specific error to the caller instead of emitting a
13430        // diagnostic, as requested.
13431        *NoArrowOperatorFound = true;
13432        return ExprError();
13433      }
13434      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13435        << BaseType << Base->getSourceRange();
13436      if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13437        Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13438          << FixItHint::CreateReplacement(OpLoc, ".");
13439      }
13440    } else
13441      Diag(OpLoc, diag::err_ovl_no_viable_oper)
13442        << "operator->" << Base->getSourceRange();
13443    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13444    return ExprError();
13445
13446  case OR_Ambiguous:
13447    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13448      << "->" << Base->getType() << Base->getSourceRange();
13449    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13450    return ExprError();
13451
13452  case OR_Deleted:
13453    Diag(OpLoc, diag::err_ovl_deleted_oper) << "->" << Base->getSourceRange();
13454    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13455    return ExprError();
13456  }
13457
13458  CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13459
13460  // Convert the object parameter.
13461  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13462  ExprResult BaseResult =
13463    PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13464                                        Best->FoundDecl, Method);
13465  if (BaseResult.isInvalid())
13466    return ExprError();
13467  Base = BaseResult.get();
13468
13469  // Build the operator call.
13470  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13471                                            Base, HadMultipleCandidates, OpLoc);
13472  if (FnExpr.isInvalid())
13473    return ExprError();
13474
13475  QualType ResultTy = Method->getReturnType();
13476  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13477  ResultTy = ResultTy.getNonLValueExprType(Context);
13478  CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13479      ContextOO_ArrowFnExpr.get(), BaseResultTyVKOpLocFPOptions());
13480
13481  if (CheckCallReturnType(Method->getReturnType(), OpLocTheCallMethod))
13482    return ExprError();
13483
13484  if (CheckFunctionCall(MethodTheCall,
13485                        Method->getType()->castAs<FunctionProtoType>()))
13486    return ExprError();
13487
13488  return MaybeBindToTemporary(TheCall);
13489}
13490
13491/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13492/// a literal operator described by the provided lookup results.
13493ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13494                                          DeclarationNameInfo &SuffixInfo,
13495                                          ArrayRef<Expr*> Args,
13496                                          SourceLocation LitEndLoc,
13497                                       TemplateArgumentListInfo *TemplateArgs) {
13498  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13499
13500  OverloadCandidateSet CandidateSet(UDSuffixLoc,
13501                                    OverloadCandidateSet::CSK_Normal);
13502  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13503                        /*SuppressUserConversions=*/true);
13504
13505  bool HadMultipleCandidates = (CandidateSet.size() > 1);
13506
13507  // Perform overload resolution. This will usually be trivial, but might need
13508  // to perform substitutions for a literal operator template.
13509  OverloadCandidateSet::iterator Best;
13510  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13511  case OR_Success:
13512  case OR_Deleted:
13513    break;
13514
13515  case OR_No_Viable_Function:
13516    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13517      << R.getLookupName();
13518    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13519    return ExprError();
13520
13521  case OR_Ambiguous:
13522    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13523    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13524    return ExprError();
13525  }
13526
13527  FunctionDecl *FD = Best->Function;
13528  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13529                                        nullptr, HadMultipleCandidates,
13530                                        SuffixInfo.getLoc(),
13531                                        SuffixInfo.getInfo());
13532  if (Fn.isInvalid())
13533    return true;
13534
13535  // Check the argument types. This should almost always be a no-op, except
13536  // that array-to-pointer decay is applied to string literals.
13537  Expr *ConvArgs[2];
13538  for (unsigned ArgIdx = 0N = Args.size(); ArgIdx != N; ++ArgIdx) {
13539    ExprResult InputInit = PerformCopyInitialization(
13540      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13541      SourceLocation(), Args[ArgIdx]);
13542    if (InputInit.isInvalid())
13543      return true;
13544    ConvArgs[ArgIdx] = InputInit.get();
13545  }
13546
13547  QualType ResultTy = FD->getReturnType();
13548  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13549  ResultTy = ResultTy.getNonLValueExprType(Context);
13550
13551  UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13552      Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13553      VK, LitEndLoc, UDSuffixLoc);
13554
13555  if (CheckCallReturnType(FD->getReturnType(), UDSuffixLocUDLFD))
13556    return ExprError();
13557
13558  if (CheckFunctionCall(FDUDLnullptr))
13559    return ExprError();
13560
13561  return MaybeBindToTemporary(UDL);
13562}
13563
13564/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13565/// given LookupResult is non-empty, it is assumed to describe a member which
13566/// will be invoked. Otherwise, the function will be found via argument
13567/// dependent lookup.
13568/// CallExpr is set to a valid expression and FRS_Success returned on success,
13569/// otherwise CallExpr is set to ExprError() and some non-success value
13570/// is returned.
13571Sema::ForRangeStatus
13572Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13573                                SourceLocation RangeLoc,
13574                                const DeclarationNameInfo &NameInfo,
13575                                LookupResult &MemberLookup,
13576                                OverloadCandidateSet *CandidateSet,
13577                                Expr *RangeExprResult *CallExpr) {
13578  Scope *S = nullptr;
13579
13580  CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13581  if (!MemberLookup.empty()) {
13582    ExprResult MemberRef =
13583        BuildMemberReferenceExpr(RangeRange->getType(), Loc,
13584                                 /*IsPtr=*/falseCXXScopeSpec(),
13585                                 /*TemplateKWLoc=*/SourceLocation(),
13586                                 /*FirstQualifierInScope=*/nullptr,
13587                                 MemberLookup,
13588                                 /*TemplateArgs=*/nullptrS);
13589    if (MemberRef.isInvalid()) {
13590      *CallExpr = ExprError();
13591      return FRS_DiagnosticIssued;
13592    }
13593    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13594    if (CallExpr->isInvalid()) {
13595      *CallExpr = ExprError();
13596      return FRS_DiagnosticIssued;
13597    }
13598  } else {
13599    UnresolvedSet<0FoundNames;
13600    UnresolvedLookupExpr *Fn =
13601      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13602                                   NestedNameSpecifierLoc(), NameInfo,
13603                                   /*NeedsADL=*/true/*Overloaded=*/false,
13604                                   FoundNames.begin(), FoundNames.end());
13605
13606    bool CandidateSetError = buildOverloadedCallSet(SFnFnRangeLoc,
13607                                                    CandidateSetCallExpr);
13608    if (CandidateSet->empty() || CandidateSetError) {
13609      *CallExpr = ExprError();
13610      return FRS_NoViableFunction;
13611    }
13612    OverloadCandidateSet::iterator Best;
13613    OverloadingResult OverloadResult =
13614        CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13615
13616    if (OverloadResult == OR_No_Viable_Function) {
13617      *CallExpr = ExprError();
13618      return FRS_NoViableFunction;
13619    }
13620    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13621                                         Loc, nullptr, CandidateSet, &Best,
13622                                         OverloadResult,
13623                                         /*AllowTypoCorrection=*/false);
13624    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13625      *CallExpr = ExprError();
13626      return FRS_DiagnosticIssued;
13627    }
13628  }
13629  return FRS_Success;
13630}
13631
13632
13633/// FixOverloadedFunctionReference - E is an expression that refers to
13634/// a C++ overloaded function (possibly with some parentheses and
13635/// perhaps a '&' around it). We have resolved the overloaded function
13636/// to the function declaration Fn, so patch up the expression E to
13637/// refer (possibly indirectly) to Fn. Returns the new expr.
13638Expr *Sema::FixOverloadedFunctionReference(Expr *EDeclAccessPair Found,
13639                                           FunctionDecl *Fn) {
13640  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13641    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13642                                                   FoundFn);
13643    if (SubExpr == PE->getSubExpr())
13644      return PE;
13645
13646    return new (ContextParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13647  }
13648
13649  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13650    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13651                                                   FoundFn);
13652     (0) . __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13654, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13653 (0) . __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13654, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                               SubExpr->getType()) &&
13654 (0) . __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13654, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Implicit cast type cannot be determined from overload");
13655     (0) . __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13655, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13656    if (SubExpr == ICE->getSubExpr())
13657      return ICE;
13658
13659    return ImplicitCastExpr::Create(ContextICE->getType(),
13660                                    ICE->getCastKind(),
13661                                    SubExprnullptr,
13662                                    ICE->getValueKind());
13663  }
13664
13665  if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13666    if (!GSE->isResultDependent()) {
13667      Expr *SubExpr =
13668          FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13669      if (SubExpr == GSE->getResultExpr())
13670        return GSE;
13671
13672      // Replace the resulting type information before rebuilding the generic
13673      // selection expression.
13674      ArrayRef<Expr *> A = GSE->getAssocExprs();
13675      SmallVector<Expr *, 4AssocExprs(A.begin(), A.end());
13676      unsigned ResultIdx = GSE->getResultIndex();
13677      AssocExprs[ResultIdx] = SubExpr;
13678
13679      return GenericSelectionExpr::Create(
13680          Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13681          GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13682          GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13683          ResultIdx);
13684    }
13685    // Rather than fall through to the unreachable, return the original generic
13686    // selection expression.
13687    return GSE;
13688  }
13689
13690  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13691     (0) . __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13692, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(UnOp->getOpcode() == UO_AddrOf &&
13692 (0) . __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13692, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Can only take the address of an overloaded function");
13693    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13694      if (Method->isStatic()) {
13695        // Do nothing: static member functions aren't any different
13696        // from non-member functions.
13697      } else {
13698        // Fix the subexpression, which really has to be an
13699        // UnresolvedLookupExpr holding an overloaded member function
13700        // or template.
13701        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13702                                                       FoundFn);
13703        if (SubExpr == UnOp->getSubExpr())
13704          return UnOp;
13705
13706         (0) . __assert_fail ("isa(SubExpr) && \"fixed to something other than a decl ref\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13707, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<DeclRefExpr>(SubExpr)
13707 (0) . __assert_fail ("isa(SubExpr) && \"fixed to something other than a decl ref\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13707, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               && "fixed to something other than a decl ref");
13708         (0) . __assert_fail ("cast(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13709, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13709 (0) . __assert_fail ("cast(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaOverload.cpp", 13709, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               && "fixed to a member ref with no nested name qualifier");
13710
13711        // We have taken the address of a pointer to member
13712        // function. Perform the computation here so that we get the
13713        // appropriate pointer to member type.
13714        QualType ClassType
13715          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13716        QualType MemPtrType
13717          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13718        // Under the MS ABI, lock down the inheritance model now.
13719        if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13720          (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13721
13722        return new (ContextUnaryOperator(SubExprUO_AddrOfMemPtrType,
13723                                           VK_RValueOK_Ordinary,
13724                                           UnOp->getOperatorLoc(), false);
13725      }
13726    }
13727    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13728                                                   FoundFn);
13729    if (SubExpr == UnOp->getSubExpr())
13730      return UnOp;
13731
13732    return new (ContextUnaryOperator(SubExprUO_AddrOf,
13733                                     Context.getPointerType(SubExpr->getType()),
13734                                       VK_RValueOK_Ordinary,
13735                                       UnOp->getOperatorLoc(), false);
13736  }
13737
13738  // C++ [except.spec]p17:
13739  //   An exception-specification is considered to be needed when:
13740  //   - in an expression the function is the unique lookup result or the
13741  //     selected member of a set of overloaded functions
13742  if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13743    ResolveExceptionSpec(E->getExprLoc(), FPT);
13744
13745  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13746    // FIXME: avoid copy.
13747    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13748    if (ULE->hasExplicitTemplateArgs()) {
13749      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13750      TemplateArgs = &TemplateArgsBuffer;
13751    }
13752
13753    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13754                                           ULE->getQualifierLoc(),
13755                                           ULE->getTemplateKeywordLoc(),
13756                                           Fn,
13757                                           /*enclosing*/ false// FIXME?
13758                                           ULE->getNameLoc(),
13759                                           Fn->getType(),
13760                                           VK_LValue,
13761                                           Found.getDecl(),
13762                                           TemplateArgs);
13763    MarkDeclRefReferenced(DRE);
13764    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13765    return DRE;
13766  }
13767
13768  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13769    // FIXME: avoid copy.
13770    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13771    if (MemExpr->hasExplicitTemplateArgs()) {
13772      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13773      TemplateArgs = &TemplateArgsBuffer;
13774    }
13775
13776    Expr *Base;
13777
13778    // If we're filling in a static method where we used to have an
13779    // implicit member access, rewrite to a simple decl ref.
13780    if (MemExpr->isImplicitAccess()) {
13781      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13782        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13783                                               MemExpr->getQualifierLoc(),
13784                                               MemExpr->getTemplateKeywordLoc(),
13785                                               Fn,
13786                                               /*enclosing*/ false,
13787                                               MemExpr->getMemberLoc(),
13788                                               Fn->getType(),
13789                                               VK_LValue,
13790                                               Found.getDecl(),
13791                                               TemplateArgs);
13792        MarkDeclRefReferenced(DRE);
13793        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13794        return DRE;
13795      } else {
13796        SourceLocation Loc = MemExpr->getMemberLoc();
13797        if (MemExpr->getQualifier())
13798          Loc = MemExpr->getQualifierLoc().getBeginLoc();
13799        CheckCXXThisCapture(Loc);
13800        Base = new (ContextCXXThisExpr(Loc,
13801                                         MemExpr->getBaseType(),
13802                                         /*isImplicit=*/true);
13803      }
13804    } else
13805      Base = MemExpr->getBase();
13806
13807    ExprValueKind valueKind;
13808    QualType type;
13809    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13810      valueKind = VK_LValue;
13811      type = Fn->getType();
13812    } else {
13813      valueKind = VK_RValue;
13814      type = Context.BoundMemberTy;
13815    }
13816
13817    MemberExpr *ME = MemberExpr::Create(
13818        ContextBaseMemExpr->isArrow(), MemExpr->getOperatorLoc(),
13819        MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), FnFound,
13820        MemExpr->getMemberNameInfo(), TemplateArgstypevalueKind,
13821        OK_Ordinary);
13822    ME->setHadMultipleCandidates(true);
13823    MarkMemberReferenced(ME);
13824    return ME;
13825  }
13826
13827  llvm_unreachable("Invalid reference to overloaded function");
13828}
13829
13830ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13831                                                DeclAccessPair Found,
13832                                                FunctionDecl *Fn) {
13833  return FixOverloadedFunctionReference(E.get(), FoundFn);
13834}
13835
clang::StandardConversionSequence::setAsIdentityConversion
clang::StandardConversionSequence::getRank
clang::StandardConversionSequence::isPointerConversionToBool
clang::StandardConversionSequence::isPointerConversionToVoidPointer
clang::StandardConversionSequence::getNarrowingKind
clang::StandardConversionSequence::dump
clang::UserDefinedConversionSequence::dump
clang::ImplicitConversionSequence::dump
clang::AmbiguousConversionSequence::construct
clang::AmbiguousConversionSequence::destruct
clang::AmbiguousConversionSequence::copyFrom
clang::DeductionFailureInfo::Destroy
clang::DeductionFailureInfo::getSFINAEDiagnostic
clang::DeductionFailureInfo::getTemplateParameter
clang::DeductionFailureInfo::getTemplateArgumentList
clang::DeductionFailureInfo::getFirstArg
clang::DeductionFailureInfo::getSecondArg
clang::DeductionFailureInfo::getCallArgIndex
clang::OverloadCandidateSet::destroyCandidates
clang::OverloadCandidateSet::clear
clang::Sema::CheckOverload
clang::Sema::IsOverload
clang::Sema::TryImplicitConversion
clang::Sema::PerformImplicitConversion
clang::Sema::PerformImplicitConversion
clang::Sema::IsFunctionConversion
clang::Sema::IsIntegralPromotion
clang::Sema::IsFloatingPointPromotion
clang::Sema::IsComplexPromotion
clang::Sema::IsPointerConversion
clang::Sema::isObjCPointerConversion
clang::Sema::isObjCWritebackConversion
clang::Sema::IsBlockPointerConversion
clang::Sema::HandleFunctionTypeMismatch
clang::Sema::FunctionParamTypesAreEqual
clang::Sema::CheckPointerConversion
clang::Sema::IsMemberPointerConversion
clang::Sema::CheckMemberPointerConversion
clang::Sema::IsQualificationConversion
clang::Sema::DiagnoseMultipleUserDefinedConversion
clang::Sema::CompareReferenceRelationship
clang::Sema::PerformObjectArgumentInitialization
clang::Sema::PerformContextuallyConvertToBool
clang::Sema::CheckConvertedConstantExpression
clang::Sema::CheckConvertedConstantExpression
clang::Sema::PerformContextuallyConvertToObjCPointer
clang::Sema::ICEConvertDiagnoser::match
clang::Sema::PerformContextualImplicitConversion
clang::Sema::AddOverloadCandidate
clang::Sema::SelectBestMethod
clang::Sema::CheckEnableIf
clang::Sema::diagnoseArgDependentDiagnoseIfAttrs
clang::Sema::diagnoseArgIndependentDiagnoseIfAttrs
clang::Sema::AddFunctionCandidates
clang::Sema::AddMethodCandidate
clang::Sema::AddMethodCandidate
clang::Sema::AddMethodTemplateCandidate
clang::Sema::AddTemplateOverloadCandidate
clang::Sema::CheckNonDependentConversions
clang::Sema::AddConversionCandidate
clang::Sema::AddTemplateConversionCandidate
clang::Sema::AddSurrogateCandidate
clang::Sema::AddMemberOperatorCandidates
clang::Sema::AddBuiltinCandidate
clang::Sema::AddBuiltinOperatorCandidates
clang::Sema::AddArgumentDependentLookupCandidates
clang::Sema::isEquivalentInternalLinkageDeclaration
clang::Sema::diagnoseEquivalentInternalLinkageDeclarations
clang::OverloadCandidateSet::BestViableFunction
clang::Sema::checkAddressOfFunctionIsAvailable
clang::Sema::NoteOverloadCandidate
clang::Sema::NoteAllOverloadCandidates
clang::ImplicitConversionSequence::DiagnoseAmbiguousConversion
clang::OverloadCandidateSet::NoteCandidates
clang::TemplateSpecCandidate::NoteDeductionFailure
clang::TemplateSpecCandidateSet::destroyCandidates
clang::TemplateSpecCandidateSet::clear
clang::TemplateSpecCandidateSet::NoteCandidates
clang::Sema::ExtractUnqualifiedFunctionType
clang::Sema::ResolveAddressOfOverloadedFunction
clang::Sema::resolveAddressOfOnlyViableOverloadCandidate
clang::Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate
clang::Sema::ResolveSingleFunctionTemplateSpecialization
clang::Sema::ResolveAndFixSingleFunctionTemplateSpecialization
clang::Sema::AddOverloadedCallCandidates
clang::Sema::buildOverloadedCallSet
clang::Sema::BuildOverloadedCallExpr
clang::Sema::CreateOverloadedUnaryOp
clang::Sema::CreateOverloadedBinOp
clang::Sema::CreateOverloadedArraySubscriptExpr
clang::Sema::BuildCallToMemberFunction
clang::Sema::BuildCallToObjectOfClassType
clang::Sema::BuildOverloadedArrowExpr
clang::Sema::BuildLiteralOperatorCall
clang::Sema::BuildForRangeBeginEndCall
clang::Sema::FixOverloadedFunctionReference
clang::Sema::FixOverloadedFunctionReference