clang  10.0.0git
SemaExprCXX.cpp
Go to the documentation of this file.
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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 /// \file
10 /// Implements semantic analysis for C++ expressions.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Template.h"
16 #include "TreeTransform.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTLambda.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaLambda.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 using namespace clang;
43 using namespace sema;
44 
45 /// Handle the result of the special case name lookup for inheriting
46 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47 /// constructor names in member using declarations, even if 'X' is not the
48 /// name of the corresponding type.
50  SourceLocation NameLoc,
51  IdentifierInfo &Name) {
52  NestedNameSpecifier *NNS = SS.getScopeRep();
53 
54  // Convert the nested-name-specifier into a type.
55  QualType Type;
56  switch (NNS->getKind()) {
59  Type = QualType(NNS->getAsType(), 0);
60  break;
61 
63  // Strip off the last layer of the nested-name-specifier and build a
64  // typename type for it.
65  assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66  Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67  NNS->getAsIdentifier());
68  break;
69 
74  llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75  }
76 
77  // This reference to the type is located entirely at the location of the
78  // final identifier in the qualified-id.
79  return CreateParsedType(Type,
80  Context.getTrivialTypeSourceInfo(Type, NameLoc));
81 }
82 
84  SourceLocation NameLoc,
85  Scope *S, CXXScopeSpec &SS,
86  bool EnteringContext) {
87  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88  assert(CurClass && &II == CurClass->getIdentifier() &&
89  "not a constructor name");
90 
91  // When naming a constructor as a member of a dependent context (eg, in a
92  // friend declaration or an inherited constructor declaration), form an
93  // unresolved "typename" type.
94  if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
95  QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96  return ParsedType::make(T);
97  }
98 
99  if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100  return ParsedType();
101 
102  // Find the injected-class-name declaration. Note that we make no attempt to
103  // diagnose cases where the injected-class-name is shadowed: the only
104  // declaration that can validly shadow the injected-class-name is a
105  // non-static data member, and if the class contains both a non-static data
106  // member and a constructor then it is ill-formed (we check that in
107  // CheckCompletedCXXClass).
108  CXXRecordDecl *InjectedClassName = nullptr;
109  for (NamedDecl *ND : CurClass->lookup(&II)) {
110  auto *RD = dyn_cast<CXXRecordDecl>(ND);
111  if (RD && RD->isInjectedClassName()) {
112  InjectedClassName = RD;
113  break;
114  }
115  }
116  if (!InjectedClassName) {
117  if (!CurClass->isInvalidDecl()) {
118  // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119  // properly. Work around it here for now.
121  diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122  }
123  return ParsedType();
124  }
125 
126  QualType T = Context.getTypeDeclType(InjectedClassName);
127  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129 
130  return ParsedType::make(T);
131 }
132 
134  IdentifierInfo &II,
135  SourceLocation NameLoc,
136  Scope *S, CXXScopeSpec &SS,
137  ParsedType ObjectTypePtr,
138  bool EnteringContext) {
139  // Determine where to perform name lookup.
140 
141  // FIXME: This area of the standard is very messy, and the current
142  // wording is rather unclear about which scopes we search for the
143  // destructor name; see core issues 399 and 555. Issue 399 in
144  // particular shows where the current description of destructor name
145  // lookup is completely out of line with existing practice, e.g.,
146  // this appears to be ill-formed:
147  //
148  // namespace N {
149  // template <typename T> struct S {
150  // ~S();
151  // };
152  // }
153  //
154  // void f(N::S<int>* s) {
155  // s->N::S<int>::~S();
156  // }
157  //
158  // See also PR6358 and PR6359.
159  // For this reason, we're currently only doing the C++03 version of this
160  // code; the C++0x version has to wait until we get a proper spec.
161  QualType SearchType;
162  DeclContext *LookupCtx = nullptr;
163  bool isDependent = false;
164  bool LookInScope = false;
165 
166  if (SS.isInvalid())
167  return nullptr;
168 
169  // If we have an object type, it's because we are in a
170  // pseudo-destructor-expression or a member access expression, and
171  // we know what type we're looking for.
172  if (ObjectTypePtr)
173  SearchType = GetTypeFromParser(ObjectTypePtr);
174 
175  if (SS.isSet()) {
176  NestedNameSpecifier *NNS = SS.getScopeRep();
177 
178  bool AlreadySearched = false;
179  bool LookAtPrefix = true;
180  // C++11 [basic.lookup.qual]p6:
181  // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
182  // the type-names are looked up as types in the scope designated by the
183  // nested-name-specifier. Similarly, in a qualified-id of the form:
184  //
185  // nested-name-specifier[opt] class-name :: ~ class-name
186  //
187  // the second class-name is looked up in the same scope as the first.
188  //
189  // Here, we determine whether the code below is permitted to look at the
190  // prefix of the nested-name-specifier.
191  DeclContext *DC = computeDeclContext(SS, EnteringContext);
192  if (DC && DC->isFileContext()) {
193  AlreadySearched = true;
194  LookupCtx = DC;
195  isDependent = false;
196  } else if (DC && isa<CXXRecordDecl>(DC)) {
197  LookAtPrefix = false;
198  LookInScope = true;
199  }
200 
201  // The second case from the C++03 rules quoted further above.
202  NestedNameSpecifier *Prefix = nullptr;
203  if (AlreadySearched) {
204  // Nothing left to do.
205  } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206  CXXScopeSpec PrefixSS;
207  PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
208  LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209  isDependent = isDependentScopeSpecifier(PrefixSS);
210  } else if (ObjectTypePtr) {
211  LookupCtx = computeDeclContext(SearchType);
212  isDependent = SearchType->isDependentType();
213  } else {
214  LookupCtx = computeDeclContext(SS, EnteringContext);
215  isDependent = LookupCtx && LookupCtx->isDependentContext();
216  }
217  } else if (ObjectTypePtr) {
218  // C++ [basic.lookup.classref]p3:
219  // If the unqualified-id is ~type-name, the type-name is looked up
220  // in the context of the entire postfix-expression. If the type T
221  // of the object expression is of a class type C, the type-name is
222  // also looked up in the scope of class C. At least one of the
223  // lookups shall find a name that refers to (possibly
224  // cv-qualified) T.
225  LookupCtx = computeDeclContext(SearchType);
226  isDependent = SearchType->isDependentType();
227  assert((isDependent || !SearchType->isIncompleteType()) &&
228  "Caller should have completed object type");
229 
230  LookInScope = true;
231  } else {
232  // Perform lookup into the current scope (only).
233  LookInScope = true;
234  }
235 
236  TypeDecl *NonMatchingTypeDecl = nullptr;
237  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238  for (unsigned Step = 0; Step != 2; ++Step) {
239  // Look for the name first in the computed lookup context (if we
240  // have one) and, if that fails to find a match, in the scope (if
241  // we're allowed to look there).
242  Found.clear();
243  if (Step == 0 && LookupCtx) {
244  if (RequireCompleteDeclContext(SS, LookupCtx))
245  return nullptr;
246  LookupQualifiedName(Found, LookupCtx);
247  } else if (Step == 1 && LookInScope && S) {
248  LookupName(Found, S);
249  } else {
250  continue;
251  }
252 
253  // FIXME: Should we be suppressing ambiguities here?
254  if (Found.isAmbiguous())
255  return nullptr;
256 
257  if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258  QualType T = Context.getTypeDeclType(Type);
259  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
260 
261  if (SearchType.isNull() || SearchType->isDependentType() ||
262  Context.hasSameUnqualifiedType(T, SearchType)) {
263  // We found our type!
264 
265  return CreateParsedType(T,
266  Context.getTrivialTypeSourceInfo(T, NameLoc));
267  }
268 
269  if (!SearchType.isNull())
270  NonMatchingTypeDecl = Type;
271  }
272 
273  // If the name that we found is a class template name, and it is
274  // the same name as the template name in the last part of the
275  // nested-name-specifier (if present) or the object type, then
276  // this is the destructor for that class.
277  // FIXME: This is a workaround until we get real drafting for core
278  // issue 399, for which there isn't even an obvious direction.
279  if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280  QualType MemberOfType;
281  if (SS.isSet()) {
282  if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283  // Figure out the type of the context, if it has one.
284  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285  MemberOfType = Context.getTypeDeclType(Record);
286  }
287  }
288  if (MemberOfType.isNull())
289  MemberOfType = SearchType;
290 
291  if (MemberOfType.isNull())
292  continue;
293 
294  // We're referring into a class template specialization. If the
295  // class template we found is the same as the template being
296  // specialized, we found what we are looking for.
297  if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
299  = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300  if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301  Template->getCanonicalDecl())
302  return CreateParsedType(
303  MemberOfType,
304  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
305  }
306 
307  continue;
308  }
309 
310  // We're referring to an unresolved class template
311  // specialization. Determine whether we class template we found
312  // is the same as the template being specialized or, if we don't
313  // know which template is being specialized, that it at least
314  // has the same name.
315  if (const TemplateSpecializationType *SpecType
316  = MemberOfType->getAs<TemplateSpecializationType>()) {
317  TemplateName SpecName = SpecType->getTemplateName();
318 
319  // The class template we found is the same template being
320  // specialized.
321  if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322  if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
323  return CreateParsedType(
324  MemberOfType,
325  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
326 
327  continue;
328  }
329 
330  // The class template we found has the same name as the
331  // (dependent) template name being specialized.
332  if (DependentTemplateName *DepTemplate
333  = SpecName.getAsDependentTemplateName()) {
334  if (DepTemplate->isIdentifier() &&
335  DepTemplate->getIdentifier() == Template->getIdentifier())
336  return CreateParsedType(
337  MemberOfType,
338  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
339 
340  continue;
341  }
342  }
343  }
344  }
345 
346  if (isDependent) {
347  // We didn't find our type, but that's okay: it's dependent
348  // anyway.
349 
350  // FIXME: What if we have no nested-name-specifier?
351  QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352  SS.getWithLocInContext(Context),
353  II, NameLoc);
354  return ParsedType::make(T);
355  }
356 
357  if (NonMatchingTypeDecl) {
358  QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359  Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
360  << T << SearchType;
361  Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
362  << T;
363  } else if (ObjectTypePtr)
364  Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
365  << &II;
366  else {
367  SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368  diag::err_destructor_class_name);
369  if (S) {
370  const DeclContext *Ctx = S->getEntity();
371  if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372  DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373  Class->getNameAsString());
374  }
375  }
376 
377  return nullptr;
378 }
379 
381  ParsedType ObjectType) {
383  return nullptr;
384 
386  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
387  return nullptr;
388  }
389 
390  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
391  "unexpected type in getDestructorType");
392  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
393 
394  // If we know the type of the object, check that the correct destructor
395  // type was named now; we can give better diagnostics this way.
396  QualType SearchType = GetTypeFromParser(ObjectType);
397  if (!SearchType.isNull() && !SearchType->isDependentType() &&
398  !Context.hasSameUnqualifiedType(T, SearchType)) {
399  Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
400  << T << SearchType;
401  return nullptr;
402  }
403 
404  return ParsedType::make(T);
405 }
406 
408  const UnqualifiedId &Name) {
410 
411  if (!SS.isValid())
412  return false;
413 
414  switch (SS.getScopeRep()->getKind()) {
418  // Per C++11 [over.literal]p2, literal operators can only be declared at
419  // namespace scope. Therefore, this unqualified-id cannot name anything.
420  // Reject it early, because we have no AST representation for this in the
421  // case where the scope is dependent.
422  Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
423  << SS.getScopeRep();
424  return true;
425 
430  return false;
431  }
432 
433  llvm_unreachable("unknown nested name specifier kind");
434 }
435 
436 /// Build a C++ typeid expression with a type operand.
438  SourceLocation TypeidLoc,
439  TypeSourceInfo *Operand,
440  SourceLocation RParenLoc) {
441  // C++ [expr.typeid]p4:
442  // The top-level cv-qualifiers of the lvalue expression or the type-id
443  // that is the operand of typeid are always ignored.
444  // If the type of the type-id is a class type or a reference to a class
445  // type, the class shall be completely-defined.
446  Qualifiers Quals;
447  QualType T
448  = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
449  Quals);
450  if (T->getAs<RecordType>() &&
451  RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
452  return ExprError();
453 
454  if (T->isVariablyModifiedType())
455  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
456 
457  if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
458  return ExprError();
459 
460  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
461  SourceRange(TypeidLoc, RParenLoc));
462 }
463 
464 /// Build a C++ typeid expression with an expression operand.
466  SourceLocation TypeidLoc,
467  Expr *E,
468  SourceLocation RParenLoc) {
469  bool WasEvaluated = false;
470  if (E && !E->isTypeDependent()) {
471  if (E->getType()->isPlaceholderType()) {
472  ExprResult result = CheckPlaceholderExpr(E);
473  if (result.isInvalid()) return ExprError();
474  E = result.get();
475  }
476 
477  QualType T = E->getType();
478  if (const RecordType *RecordT = T->getAs<RecordType>()) {
479  CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
480  // C++ [expr.typeid]p3:
481  // [...] If the type of the expression is a class type, the class
482  // shall be completely-defined.
483  if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
484  return ExprError();
485 
486  // C++ [expr.typeid]p3:
487  // When typeid is applied to an expression other than an glvalue of a
488  // polymorphic class type [...] [the] expression is an unevaluated
489  // operand. [...]
490  if (RecordD->isPolymorphic() && E->isGLValue()) {
491  // The subexpression is potentially evaluated; switch the context
492  // and recheck the subexpression.
493  ExprResult Result = TransformToPotentiallyEvaluated(E);
494  if (Result.isInvalid()) return ExprError();
495  E = Result.get();
496 
497  // We require a vtable to query the type at run time.
498  MarkVTableUsed(TypeidLoc, RecordD);
499  WasEvaluated = true;
500  }
501  }
502 
503  ExprResult Result = CheckUnevaluatedOperand(E);
504  if (Result.isInvalid())
505  return ExprError();
506  E = Result.get();
507 
508  // C++ [expr.typeid]p4:
509  // [...] If the type of the type-id is a reference to a possibly
510  // cv-qualified type, the result of the typeid expression refers to a
511  // std::type_info object representing the cv-unqualified referenced
512  // type.
513  Qualifiers Quals;
514  QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
515  if (!Context.hasSameType(T, UnqualT)) {
516  T = UnqualT;
517  E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
518  }
519  }
520 
521  if (E->getType()->isVariablyModifiedType())
522  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
523  << E->getType());
524  else if (!inTemplateInstantiation() &&
525  E->HasSideEffects(Context, WasEvaluated)) {
526  // The expression operand for typeid is in an unevaluated expression
527  // context, so side effects could result in unintended consequences.
528  Diag(E->getExprLoc(), WasEvaluated
529  ? diag::warn_side_effects_typeid
530  : diag::warn_side_effects_unevaluated_context);
531  }
532 
533  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
534  SourceRange(TypeidLoc, RParenLoc));
535 }
536 
537 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
540  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
541  // typeid is not supported in OpenCL.
542  if (getLangOpts().OpenCLCPlusPlus) {
543  return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
544  << "typeid");
545  }
546 
547  // Find the std::type_info type.
548  if (!getStdNamespace())
549  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
550 
551  if (!CXXTypeInfoDecl) {
552  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
553  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
554  LookupQualifiedName(R, getStdNamespace());
555  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
556  // Microsoft's typeinfo doesn't have type_info in std but in the global
557  // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
558  if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
559  LookupQualifiedName(R, Context.getTranslationUnitDecl());
560  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
561  }
562  if (!CXXTypeInfoDecl)
563  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
564  }
565 
566  if (!getLangOpts().RTTI) {
567  return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
568  }
569 
570  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
571 
572  if (isType) {
573  // The operand is a type; handle it as such.
574  TypeSourceInfo *TInfo = nullptr;
575  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
576  &TInfo);
577  if (T.isNull())
578  return ExprError();
579 
580  if (!TInfo)
581  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
582 
583  return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
584  }
585 
586  // The operand is an expression.
587  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
588 }
589 
590 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
591 /// a single GUID.
592 static void
595  // Optionally remove one level of pointer, reference or array indirection.
596  const Type *Ty = QT.getTypePtr();
597  if (QT->isPointerType() || QT->isReferenceType())
598  Ty = QT->getPointeeType().getTypePtr();
599  else if (QT->isArrayType())
600  Ty = Ty->getBaseElementTypeUnsafe();
601 
602  const auto *TD = Ty->getAsTagDecl();
603  if (!TD)
604  return;
605 
606  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
607  UuidAttrs.insert(Uuid);
608  return;
609  }
610 
611  // __uuidof can grab UUIDs from template arguments.
612  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
613  const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
614  for (const TemplateArgument &TA : TAL.asArray()) {
615  const UuidAttr *UuidForTA = nullptr;
616  if (TA.getKind() == TemplateArgument::Type)
617  getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
618  else if (TA.getKind() == TemplateArgument::Declaration)
619  getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
620 
621  if (UuidForTA)
622  UuidAttrs.insert(UuidForTA);
623  }
624  }
625 }
626 
627 /// Build a Microsoft __uuidof expression with a type operand.
629  SourceLocation TypeidLoc,
630  TypeSourceInfo *Operand,
631  SourceLocation RParenLoc) {
632  StringRef UuidStr;
633  if (!Operand->getType()->isDependentType()) {
635  getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
636  if (UuidAttrs.empty())
637  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
638  if (UuidAttrs.size() > 1)
639  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
640  UuidStr = UuidAttrs.back()->getGuid();
641  }
642 
643  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
644  SourceRange(TypeidLoc, RParenLoc));
645 }
646 
647 /// Build a Microsoft __uuidof expression with an expression operand.
649  SourceLocation TypeidLoc,
650  Expr *E,
651  SourceLocation RParenLoc) {
652  StringRef UuidStr;
653  if (!E->getType()->isDependentType()) {
655  UuidStr = "00000000-0000-0000-0000-000000000000";
656  } else {
658  getUuidAttrOfType(*this, E->getType(), UuidAttrs);
659  if (UuidAttrs.empty())
660  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
661  if (UuidAttrs.size() > 1)
662  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
663  UuidStr = UuidAttrs.back()->getGuid();
664  }
665  }
666 
667  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
668  SourceRange(TypeidLoc, RParenLoc));
669 }
670 
671 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
674  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
675  // If MSVCGuidDecl has not been cached, do the lookup.
676  if (!MSVCGuidDecl) {
677  IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
678  LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
679  LookupQualifiedName(R, Context.getTranslationUnitDecl());
680  MSVCGuidDecl = R.getAsSingle<RecordDecl>();
681  if (!MSVCGuidDecl)
682  return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
683  }
684 
685  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
686 
687  if (isType) {
688  // The operand is a type; handle it as such.
689  TypeSourceInfo *TInfo = nullptr;
690  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
691  &TInfo);
692  if (T.isNull())
693  return ExprError();
694 
695  if (!TInfo)
696  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
697 
698  return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
699  }
700 
701  // The operand is an expression.
702  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
703 }
704 
705 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
708  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
709  "Unknown C++ Boolean value!");
710  return new (Context)
711  CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
712 }
713 
714 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
717  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
718 }
719 
720 /// ActOnCXXThrow - Parse throw expressions.
723  bool IsThrownVarInScope = false;
724  if (Ex) {
725  // C++0x [class.copymove]p31:
726  // When certain criteria are met, an implementation is allowed to omit the
727  // copy/move construction of a class object [...]
728  //
729  // - in a throw-expression, when the operand is the name of a
730  // non-volatile automatic object (other than a function or catch-
731  // clause parameter) whose scope does not extend beyond the end of the
732  // innermost enclosing try-block (if there is one), the copy/move
733  // operation from the operand to the exception object (15.1) can be
734  // omitted by constructing the automatic object directly into the
735  // exception object
736  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
737  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
738  if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
739  for( ; S; S = S->getParent()) {
740  if (S->isDeclScope(Var)) {
741  IsThrownVarInScope = true;
742  break;
743  }
744 
745  if (S->getFlags() &
749  break;
750  }
751  }
752  }
753  }
754 
755  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
756 }
757 
759  bool IsThrownVarInScope) {
760  // Don't report an error if 'throw' is used in system headers.
761  if (!getLangOpts().CXXExceptions &&
762  !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
763  // Delay error emission for the OpenMP device code.
764  targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
765  }
766 
767  // Exceptions aren't allowed in CUDA device code.
768  if (getLangOpts().CUDA)
769  CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
770  << "throw" << CurrentCUDATarget();
771 
772  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
773  Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
774 
775  if (Ex && !Ex->isTypeDependent()) {
776  QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
777  if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
778  return ExprError();
779 
780  // Initialize the exception result. This implicitly weeds out
781  // abstract types or types with inaccessible copy constructors.
782 
783  // C++0x [class.copymove]p31:
784  // When certain criteria are met, an implementation is allowed to omit the
785  // copy/move construction of a class object [...]
786  //
787  // - in a throw-expression, when the operand is the name of a
788  // non-volatile automatic object (other than a function or
789  // catch-clause
790  // parameter) whose scope does not extend beyond the end of the
791  // innermost enclosing try-block (if there is one), the copy/move
792  // operation from the operand to the exception object (15.1) can be
793  // omitted by constructing the automatic object directly into the
794  // exception object
795  const VarDecl *NRVOVariable = nullptr;
796  if (IsThrownVarInScope)
797  NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
798 
800  OpLoc, ExceptionObjectTy,
801  /*NRVO=*/NRVOVariable != nullptr);
802  ExprResult Res = PerformMoveOrCopyInitialization(
803  Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
804  if (Res.isInvalid())
805  return ExprError();
806  Ex = Res.get();
807  }
808 
809  return new (Context)
810  CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
811 }
812 
813 static void
815  llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
816  llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
817  llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
818  bool ParentIsPublic) {
819  for (const CXXBaseSpecifier &BS : RD->bases()) {
820  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
821  bool NewSubobject;
822  // Virtual bases constitute the same subobject. Non-virtual bases are
823  // always distinct subobjects.
824  if (BS.isVirtual())
825  NewSubobject = VBases.insert(BaseDecl).second;
826  else
827  NewSubobject = true;
828 
829  if (NewSubobject)
830  ++SubobjectsSeen[BaseDecl];
831 
832  // Only add subobjects which have public access throughout the entire chain.
833  bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
834  if (PublicPath)
835  PublicSubobjectsSeen.insert(BaseDecl);
836 
837  // Recurse on to each base subobject.
838  collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
839  PublicPath);
840  }
841 }
842 
845  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
846  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
847  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
848  SubobjectsSeen[RD] = 1;
849  PublicSubobjectsSeen.insert(RD);
850  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
851  /*ParentIsPublic=*/true);
852 
853  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
854  // Skip ambiguous objects.
855  if (SubobjectsSeen[PublicSubobject] > 1)
856  continue;
857 
858  Objects.push_back(PublicSubobject);
859  }
860 }
861 
862 /// CheckCXXThrowOperand - Validate the operand of a throw.
864  QualType ExceptionObjectTy, Expr *E) {
865  // If the type of the exception would be an incomplete type or a pointer
866  // to an incomplete type other than (cv) void the program is ill-formed.
867  QualType Ty = ExceptionObjectTy;
868  bool isPointer = false;
869  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
870  Ty = Ptr->getPointeeType();
871  isPointer = true;
872  }
873  if (!isPointer || !Ty->isVoidType()) {
874  if (RequireCompleteType(ThrowLoc, Ty,
875  isPointer ? diag::err_throw_incomplete_ptr
876  : diag::err_throw_incomplete,
877  E->getSourceRange()))
878  return true;
879 
880  if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
881  diag::err_throw_abstract_type, E))
882  return true;
883  }
884 
885  // If the exception has class type, we need additional handling.
886  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
887  if (!RD)
888  return false;
889 
890  // If we are throwing a polymorphic class type or pointer thereof,
891  // exception handling will make use of the vtable.
892  MarkVTableUsed(ThrowLoc, RD);
893 
894  // If a pointer is thrown, the referenced object will not be destroyed.
895  if (isPointer)
896  return false;
897 
898  // If the class has a destructor, we must be able to call it.
899  if (!RD->hasIrrelevantDestructor()) {
900  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
901  MarkFunctionReferenced(E->getExprLoc(), Destructor);
902  CheckDestructorAccess(E->getExprLoc(), Destructor,
903  PDiag(diag::err_access_dtor_exception) << Ty);
904  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
905  return true;
906  }
907  }
908 
909  // The MSVC ABI creates a list of all types which can catch the exception
910  // object. This list also references the appropriate copy constructor to call
911  // if the object is caught by value and has a non-trivial copy constructor.
912  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
913  // We are only interested in the public, unambiguous bases contained within
914  // the exception object. Bases which are ambiguous or otherwise
915  // inaccessible are not catchable types.
916  llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
917  getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
918 
919  for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
920  // Attempt to lookup the copy constructor. Various pieces of machinery
921  // will spring into action, like template instantiation, which means this
922  // cannot be a simple walk of the class's decls. Instead, we must perform
923  // lookup and overload resolution.
924  CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
925  if (!CD || CD->isDeleted())
926  continue;
927 
928  // Mark the constructor referenced as it is used by this throw expression.
929  MarkFunctionReferenced(E->getExprLoc(), CD);
930 
931  // Skip this copy constructor if it is trivial, we don't need to record it
932  // in the catchable type data.
933  if (CD->isTrivial())
934  continue;
935 
936  // The copy constructor is non-trivial, create a mapping from this class
937  // type to this constructor.
938  // N.B. The selection of copy constructor is not sensitive to this
939  // particular throw-site. Lookup will be performed at the catch-site to
940  // ensure that the copy constructor is, in fact, accessible (via
941  // friendship or any other means).
942  Context.addCopyConstructorForExceptionObject(Subobject, CD);
943 
944  // We don't keep the instantiated default argument expressions around so
945  // we must rebuild them here.
946  for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
947  if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
948  return true;
949  }
950  }
951  }
952 
953  // Under the Itanium C++ ABI, memory for the exception object is allocated by
954  // the runtime with no ability for the compiler to request additional
955  // alignment. Warn if the exception type requires alignment beyond the minimum
956  // guaranteed by the target C++ runtime.
957  if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
958  CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
959  CharUnits ExnObjAlign = Context.getExnObjectAlignment();
960  if (ExnObjAlign < TypeAlign) {
961  Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
962  Diag(ThrowLoc, diag::note_throw_underaligned_obj)
963  << Ty << (unsigned)TypeAlign.getQuantity()
964  << (unsigned)ExnObjAlign.getQuantity();
965  }
966  }
967 
968  return false;
969 }
970 
972  ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
973  DeclContext *CurSemaContext, ASTContext &ASTCtx) {
974 
975  QualType ClassType = ThisTy->getPointeeType();
976  LambdaScopeInfo *CurLSI = nullptr;
977  DeclContext *CurDC = CurSemaContext;
978 
979  // Iterate through the stack of lambdas starting from the innermost lambda to
980  // the outermost lambda, checking if '*this' is ever captured by copy - since
981  // that could change the cv-qualifiers of the '*this' object.
982  // The object referred to by '*this' starts out with the cv-qualifiers of its
983  // member function. We then start with the innermost lambda and iterate
984  // outward checking to see if any lambda performs a by-copy capture of '*this'
985  // - and if so, any nested lambda must respect the 'constness' of that
986  // capturing lamdbda's call operator.
987  //
988 
989  // Since the FunctionScopeInfo stack is representative of the lexical
990  // nesting of the lambda expressions during initial parsing (and is the best
991  // place for querying information about captures about lambdas that are
992  // partially processed) and perhaps during instantiation of function templates
993  // that contain lambda expressions that need to be transformed BUT not
994  // necessarily during instantiation of a nested generic lambda's function call
995  // operator (which might even be instantiated at the end of the TU) - at which
996  // time the DeclContext tree is mature enough to query capture information
997  // reliably - we use a two pronged approach to walk through all the lexically
998  // enclosing lambda expressions:
999  //
1000  // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1001  // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1002  // enclosed by the call-operator of the LSI below it on the stack (while
1003  // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1004  // the stack represents the innermost lambda.
1005  //
1006  // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1007  // represents a lambda's call operator. If it does, we must be instantiating
1008  // a generic lambda's call operator (represented by the Current LSI, and
1009  // should be the only scenario where an inconsistency between the LSI and the
1010  // DeclContext should occur), so climb out the DeclContexts if they
1011  // represent lambdas, while querying the corresponding closure types
1012  // regarding capture information.
1013 
1014  // 1) Climb down the function scope info stack.
1015  for (int I = FunctionScopes.size();
1016  I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1017  (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1018  cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1019  CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1020  CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1021 
1022  if (!CurLSI->isCXXThisCaptured())
1023  continue;
1024 
1025  auto C = CurLSI->getCXXThisCapture();
1026 
1027  if (C.isCopyCapture()) {
1029  if (CurLSI->CallOperator->isConst())
1030  ClassType.addConst();
1031  return ASTCtx.getPointerType(ClassType);
1032  }
1033  }
1034 
1035  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1036  // happen during instantiation of its nested generic lambda call operator)
1037  if (isLambdaCallOperator(CurDC)) {
1038  assert(CurLSI && "While computing 'this' capture-type for a generic "
1039  "lambda, we must have a corresponding LambdaScopeInfo");
1041  "While computing 'this' capture-type for a generic lambda, when we "
1042  "run out of enclosing LSI's, yet the enclosing DC is a "
1043  "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1044  "lambda call oeprator");
1045  assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1046 
1047  auto IsThisCaptured =
1048  [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1049  IsConst = false;
1050  IsByCopy = false;
1051  for (auto &&C : Closure->captures()) {
1052  if (C.capturesThis()) {
1053  if (C.getCaptureKind() == LCK_StarThis)
1054  IsByCopy = true;
1055  if (Closure->getLambdaCallOperator()->isConst())
1056  IsConst = true;
1057  return true;
1058  }
1059  }
1060  return false;
1061  };
1062 
1063  bool IsByCopyCapture = false;
1064  bool IsConstCapture = false;
1065  CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1066  while (Closure &&
1067  IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1068  if (IsByCopyCapture) {
1070  if (IsConstCapture)
1071  ClassType.addConst();
1072  return ASTCtx.getPointerType(ClassType);
1073  }
1074  Closure = isLambdaCallOperator(Closure->getParent())
1075  ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1076  : nullptr;
1077  }
1078  }
1079  return ASTCtx.getPointerType(ClassType);
1080 }
1081 
1083  DeclContext *DC = getFunctionLevelDeclContext();
1084  QualType ThisTy = CXXThisTypeOverride;
1085 
1086  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1087  if (method && method->isInstance())
1088  ThisTy = method->getThisType();
1089  }
1090 
1091  if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1092  inTemplateInstantiation()) {
1093 
1094  assert(isa<CXXRecordDecl>(DC) &&
1095  "Trying to get 'this' type from static method?");
1096 
1097  // This is a lambda call operator that is being instantiated as a default
1098  // initializer. DC must point to the enclosing class type, so we can recover
1099  // the 'this' type from it.
1100 
1101  QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1102  // There are no cv-qualifiers for 'this' within default initializers,
1103  // per [expr.prim.general]p4.
1104  ThisTy = Context.getPointerType(ClassTy);
1105  }
1106 
1107  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1108  // might need to be adjusted if the lambda or any of its enclosing lambda's
1109  // captures '*this' by copy.
1110  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1111  return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1112  CurContext, Context);
1113  return ThisTy;
1114 }
1115 
1117  Decl *ContextDecl,
1118  Qualifiers CXXThisTypeQuals,
1119  bool Enabled)
1120  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1121 {
1122  if (!Enabled || !ContextDecl)
1123  return;
1124 
1125  CXXRecordDecl *Record = nullptr;
1126  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1127  Record = Template->getTemplatedDecl();
1128  else
1129  Record = cast<CXXRecordDecl>(ContextDecl);
1130 
1131  QualType T = S.Context.getRecordType(Record);
1132  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1133 
1135 
1136  this->Enabled = true;
1137 }
1138 
1139 
1141  if (Enabled) {
1142  S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1143  }
1144 }
1145 
1146 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1147  bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1148  const bool ByCopy) {
1149  // We don't need to capture this in an unevaluated context.
1150  if (isUnevaluatedContext() && !Explicit)
1151  return true;
1152 
1153  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1154 
1155  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1156  ? *FunctionScopeIndexToStopAt
1157  : FunctionScopes.size() - 1;
1158 
1159  // Check that we can capture the *enclosing object* (referred to by '*this')
1160  // by the capturing-entity/closure (lambda/block/etc) at
1161  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1162 
1163  // Note: The *enclosing object* can only be captured by-value by a
1164  // closure that is a lambda, using the explicit notation:
1165  // [*this] { ... }.
1166  // Every other capture of the *enclosing object* results in its by-reference
1167  // capture.
1168 
1169  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1170  // stack), we can capture the *enclosing object* only if:
1171  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1172  // - or, 'L' has an implicit capture.
1173  // AND
1174  // -- there is no enclosing closure
1175  // -- or, there is some enclosing closure 'E' that has already captured the
1176  // *enclosing object*, and every intervening closure (if any) between 'E'
1177  // and 'L' can implicitly capture the *enclosing object*.
1178  // -- or, every enclosing closure can implicitly capture the
1179  // *enclosing object*
1180 
1181 
1182  unsigned NumCapturingClosures = 0;
1183  for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1184  if (CapturingScopeInfo *CSI =
1185  dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1186  if (CSI->CXXThisCaptureIndex != 0) {
1187  // 'this' is already being captured; there isn't anything more to do.
1188  CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1189  break;
1190  }
1191  LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1193  // This context can't implicitly capture 'this'; fail out.
1194  if (BuildAndDiagnose)
1195  Diag(Loc, diag::err_this_capture)
1196  << (Explicit && idx == MaxFunctionScopesIndex);
1197  return true;
1198  }
1199  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1200  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1201  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1202  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1203  (Explicit && idx == MaxFunctionScopesIndex)) {
1204  // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1205  // iteration through can be an explicit capture, all enclosing closures,
1206  // if any, must perform implicit captures.
1207 
1208  // This closure can capture 'this'; continue looking upwards.
1209  NumCapturingClosures++;
1210  continue;
1211  }
1212  // This context can't implicitly capture 'this'; fail out.
1213  if (BuildAndDiagnose)
1214  Diag(Loc, diag::err_this_capture)
1215  << (Explicit && idx == MaxFunctionScopesIndex);
1216  return true;
1217  }
1218  break;
1219  }
1220  if (!BuildAndDiagnose) return false;
1221 
1222  // If we got here, then the closure at MaxFunctionScopesIndex on the
1223  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1224  // (including implicit by-reference captures in any enclosing closures).
1225 
1226  // In the loop below, respect the ByCopy flag only for the closure requesting
1227  // the capture (i.e. first iteration through the loop below). Ignore it for
1228  // all enclosing closure's up to NumCapturingClosures (since they must be
1229  // implicitly capturing the *enclosing object* by reference (see loop
1230  // above)).
1231  assert((!ByCopy ||
1232  dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1233  "Only a lambda can capture the enclosing object (referred to by "
1234  "*this) by copy");
1235  QualType ThisTy = getCurrentThisType();
1236  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1237  --idx, --NumCapturingClosures) {
1238  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1239 
1240  // The type of the corresponding data member (not a 'this' pointer if 'by
1241  // copy').
1242  QualType CaptureType = ThisTy;
1243  if (ByCopy) {
1244  // If we are capturing the object referred to by '*this' by copy, ignore
1245  // any cv qualifiers inherited from the type of the member function for
1246  // the type of the closure-type's corresponding data member and any use
1247  // of 'this'.
1248  CaptureType = ThisTy->getPointeeType();
1250  }
1251 
1252  bool isNested = NumCapturingClosures > 1;
1253  CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1254  }
1255  return false;
1256 }
1257 
1259  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1260  /// is a non-lvalue expression whose value is the address of the object for
1261  /// which the function is called.
1262 
1263  QualType ThisTy = getCurrentThisType();
1264  if (ThisTy.isNull())
1265  return Diag(Loc, diag::err_invalid_this_use);
1266  return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1267 }
1268 
1270  bool IsImplicit) {
1271  auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1273  return This;
1274 }
1275 
1278 }
1279 
1281  // If we're outside the body of a member function, then we'll have a specified
1282  // type for 'this'.
1284  return false;
1285 
1286  // Determine whether we're looking into a class that's currently being
1287  // defined.
1288  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1289  return Class && Class->isBeingDefined();
1290 }
1291 
1292 /// Parse construction of a specified type.
1293 /// Can be interpreted either as function-style casting ("int(x)")
1294 /// or class type construction ("ClassType(x,y,z)")
1295 /// or creation of a value-initialized type ("int()").
1296 ExprResult
1298  SourceLocation LParenOrBraceLoc,
1299  MultiExprArg exprs,
1300  SourceLocation RParenOrBraceLoc,
1301  bool ListInitialization) {
1302  if (!TypeRep)
1303  return ExprError();
1304 
1305  TypeSourceInfo *TInfo;
1306  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1307  if (!TInfo)
1309 
1310  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1311  RParenOrBraceLoc, ListInitialization);
1312  // Avoid creating a non-type-dependent expression that contains typos.
1313  // Non-type-dependent expressions are liable to be discarded without
1314  // checking for embedded typos.
1315  if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1316  !Result.get()->isTypeDependent())
1318  return Result;
1319 }
1320 
1321 ExprResult
1323  SourceLocation LParenOrBraceLoc,
1324  MultiExprArg Exprs,
1325  SourceLocation RParenOrBraceLoc,
1326  bool ListInitialization) {
1327  QualType Ty = TInfo->getType();
1328  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1329 
1331  // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1332  // directly. We work around this by dropping the locations of the braces.
1333  SourceRange Locs = ListInitialization
1334  ? SourceRange()
1335  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1336  return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1337  Exprs, Locs.getEnd());
1338  }
1339 
1340  assert((!ListInitialization ||
1341  (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1342  "List initialization must have initializer list as expression.");
1343  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1344 
1347  Exprs.size()
1348  ? ListInitialization
1350  TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1351  : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1352  RParenOrBraceLoc)
1353  : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1354  RParenOrBraceLoc);
1355 
1356  // C++1z [expr.type.conv]p1:
1357  // If the type is a placeholder for a deduced class type, [...perform class
1358  // template argument deduction...]
1359  DeducedType *Deduced = Ty->getContainedDeducedType();
1360  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1362  Kind, Exprs);
1363  if (Ty.isNull())
1364  return ExprError();
1365  Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1366  }
1367 
1368  // C++ [expr.type.conv]p1:
1369  // If the expression list is a parenthesized single expression, the type
1370  // conversion expression is equivalent (in definedness, and if defined in
1371  // meaning) to the corresponding cast expression.
1372  if (Exprs.size() == 1 && !ListInitialization &&
1373  !isa<InitListExpr>(Exprs[0])) {
1374  Expr *Arg = Exprs[0];
1375  return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1376  RParenOrBraceLoc);
1377  }
1378 
1379  // For an expression of the form T(), T shall not be an array type.
1380  QualType ElemTy = Ty;
1381  if (Ty->isArrayType()) {
1382  if (!ListInitialization)
1383  return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1384  << FullRange);
1385  ElemTy = Context.getBaseElementType(Ty);
1386  }
1387 
1388  // There doesn't seem to be an explicit rule against this but sanity demands
1389  // we only construct objects with object types.
1390  if (Ty->isFunctionType())
1391  return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1392  << Ty << FullRange);
1393 
1394  // C++17 [expr.type.conv]p2:
1395  // If the type is cv void and the initializer is (), the expression is a
1396  // prvalue of the specified type that performs no initialization.
1397  if (!Ty->isVoidType() &&
1398  RequireCompleteType(TyBeginLoc, ElemTy,
1399  diag::err_invalid_incomplete_type_use, FullRange))
1400  return ExprError();
1401 
1402  // Otherwise, the expression is a prvalue of the specified type whose
1403  // result object is direct-initialized (11.6) with the initializer.
1404  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1405  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1406 
1407  if (Result.isInvalid())
1408  return Result;
1409 
1410  Expr *Inner = Result.get();
1411  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1412  Inner = BTE->getSubExpr();
1413  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1414  !isa<CXXScalarValueInitExpr>(Inner)) {
1415  // If we created a CXXTemporaryObjectExpr, that node also represents the
1416  // functional cast. Otherwise, create an explicit cast to represent
1417  // the syntactic form of a functional-style cast that was used here.
1418  //
1419  // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1420  // would give a more consistent AST representation than using a
1421  // CXXTemporaryObjectExpr. It's also weird that the functional cast
1422  // is sometimes handled by initialization and sometimes not.
1423  QualType ResultType = Result.get()->getType();
1424  SourceRange Locs = ListInitialization
1425  ? SourceRange()
1426  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1428  Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1429  Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1430  }
1431 
1432  return Result;
1433 }
1434 
1436  // [CUDA] Ignore this function, if we can't call it.
1437  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1438  if (getLangOpts().CUDA &&
1439  IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1440  return false;
1441 
1443  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1444 
1445  if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1446  return Result;
1447 
1448  // In case of CUDA, return true if none of the 1-argument deallocator
1449  // functions are actually callable.
1450  return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1451  assert(FD->getNumParams() == 1 &&
1452  "Only single-operand functions should be in PreventedBy");
1453  return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1454  });
1455 }
1456 
1457 /// Determine whether the given function is a non-placement
1458 /// deallocation function.
1460  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1461  return S.isUsualDeallocationFunction(Method);
1462 
1463  if (FD->getOverloadedOperator() != OO_Delete &&
1464  FD->getOverloadedOperator() != OO_Array_Delete)
1465  return false;
1466 
1467  unsigned UsualParams = 1;
1468 
1469  if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1471  FD->getParamDecl(UsualParams)->getType(),
1472  S.Context.getSizeType()))
1473  ++UsualParams;
1474 
1475  if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1477  FD->getParamDecl(UsualParams)->getType(),
1479  ++UsualParams;
1480 
1481  return UsualParams == FD->getNumParams();
1482 }
1483 
1484 namespace {
1485  struct UsualDeallocFnInfo {
1486  UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1487  UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1488  : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1489  Destroying(false), HasSizeT(false), HasAlignValT(false),
1490  CUDAPref(Sema::CFP_Native) {
1491  // A function template declaration is never a usual deallocation function.
1492  if (!FD)
1493  return;
1494  unsigned NumBaseParams = 1;
1495  if (FD->isDestroyingOperatorDelete()) {
1496  Destroying = true;
1497  ++NumBaseParams;
1498  }
1499 
1500  if (NumBaseParams < FD->getNumParams() &&
1502  FD->getParamDecl(NumBaseParams)->getType(),
1503  S.Context.getSizeType())) {
1504  ++NumBaseParams;
1505  HasSizeT = true;
1506  }
1507 
1508  if (NumBaseParams < FD->getNumParams() &&
1509  FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1510  ++NumBaseParams;
1511  HasAlignValT = true;
1512  }
1513 
1514  // In CUDA, determine how much we'd like / dislike to call this.
1515  if (S.getLangOpts().CUDA)
1516  if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1517  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1518  }
1519 
1520  explicit operator bool() const { return FD; }
1521 
1522  bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1523  bool WantAlign) const {
1524  // C++ P0722:
1525  // A destroying operator delete is preferred over a non-destroying
1526  // operator delete.
1527  if (Destroying != Other.Destroying)
1528  return Destroying;
1529 
1530  // C++17 [expr.delete]p10:
1531  // If the type has new-extended alignment, a function with a parameter
1532  // of type std::align_val_t is preferred; otherwise a function without
1533  // such a parameter is preferred
1534  if (HasAlignValT != Other.HasAlignValT)
1535  return HasAlignValT == WantAlign;
1536 
1537  if (HasSizeT != Other.HasSizeT)
1538  return HasSizeT == WantSize;
1539 
1540  // Use CUDA call preference as a tiebreaker.
1541  return CUDAPref > Other.CUDAPref;
1542  }
1543 
1544  DeclAccessPair Found;
1545  FunctionDecl *FD;
1546  bool Destroying, HasSizeT, HasAlignValT;
1548  };
1549 }
1550 
1551 /// Determine whether a type has new-extended alignment. This may be called when
1552 /// the type is incomplete (for a delete-expression with an incomplete pointee
1553 /// type), in which case it will conservatively return false if the alignment is
1554 /// not known.
1555 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1556  return S.getLangOpts().AlignedAllocation &&
1557  S.getASTContext().getTypeAlignIfKnown(AllocType) >
1559 }
1560 
1561 /// Select the correct "usual" deallocation function to use from a selection of
1562 /// deallocation functions (either global or class-scope).
1563 static UsualDeallocFnInfo resolveDeallocationOverload(
1564  Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1565  llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1566  UsualDeallocFnInfo Best;
1567 
1568  for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1569  UsualDeallocFnInfo Info(S, I.getPair());
1570  if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1571  Info.CUDAPref == Sema::CFP_Never)
1572  continue;
1573 
1574  if (!Best) {
1575  Best = Info;
1576  if (BestFns)
1577  BestFns->push_back(Info);
1578  continue;
1579  }
1580 
1581  if (Best.isBetterThan(Info, WantSize, WantAlign))
1582  continue;
1583 
1584  // If more than one preferred function is found, all non-preferred
1585  // functions are eliminated from further consideration.
1586  if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1587  BestFns->clear();
1588 
1589  Best = Info;
1590  if (BestFns)
1591  BestFns->push_back(Info);
1592  }
1593 
1594  return Best;
1595 }
1596 
1597 /// Determine whether a given type is a class for which 'delete[]' would call
1598 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1599 /// we need to store the array size (even if the type is
1600 /// trivially-destructible).
1602  QualType allocType) {
1603  const RecordType *record =
1604  allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1605  if (!record) return false;
1606 
1607  // Try to find an operator delete[] in class scope.
1608 
1609  DeclarationName deleteName =
1610  S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1611  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1612  S.LookupQualifiedName(ops, record->getDecl());
1613 
1614  // We're just doing this for information.
1615  ops.suppressDiagnostics();
1616 
1617  // Very likely: there's no operator delete[].
1618  if (ops.empty()) return false;
1619 
1620  // If it's ambiguous, it should be illegal to call operator delete[]
1621  // on this thing, so it doesn't matter if we allocate extra space or not.
1622  if (ops.isAmbiguous()) return false;
1623 
1624  // C++17 [expr.delete]p10:
1625  // If the deallocation functions have class scope, the one without a
1626  // parameter of type std::size_t is selected.
1627  auto Best = resolveDeallocationOverload(
1628  S, ops, /*WantSize*/false,
1629  /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1630  return Best && Best.HasSizeT;
1631 }
1632 
1633 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1634 ///
1635 /// E.g.:
1636 /// @code new (memory) int[size][4] @endcode
1637 /// or
1638 /// @code ::new Foo(23, "hello") @endcode
1639 ///
1640 /// \param StartLoc The first location of the expression.
1641 /// \param UseGlobal True if 'new' was prefixed with '::'.
1642 /// \param PlacementLParen Opening paren of the placement arguments.
1643 /// \param PlacementArgs Placement new arguments.
1644 /// \param PlacementRParen Closing paren of the placement arguments.
1645 /// \param TypeIdParens If the type is in parens, the source range.
1646 /// \param D The type to be allocated, as well as array dimensions.
1647 /// \param Initializer The initializing expression or initializer-list, or null
1648 /// if there is none.
1649 ExprResult
1650 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1651  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1652  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1653  Declarator &D, Expr *Initializer) {
1654  Optional<Expr *> ArraySize;
1655  // If the specified type is an array, unwrap it and save the expression.
1656  if (D.getNumTypeObjects() > 0 &&
1658  DeclaratorChunk &Chunk = D.getTypeObject(0);
1659  if (D.getDeclSpec().hasAutoTypeSpec())
1660  return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1661  << D.getSourceRange());
1662  if (Chunk.Arr.hasStatic)
1663  return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1664  << D.getSourceRange());
1665  if (!Chunk.Arr.NumElts && !Initializer)
1666  return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1667  << D.getSourceRange());
1668 
1669  ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1670  D.DropFirstTypeObject();
1671  }
1672 
1673  // Every dimension shall be of constant size.
1674  if (ArraySize) {
1675  for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1677  break;
1678 
1680  if (Expr *NumElts = (Expr *)Array.NumElts) {
1681  if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1682  if (getLangOpts().CPlusPlus14) {
1683  // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1684  // shall be a converted constant expression (5.19) of type std::size_t
1685  // and shall evaluate to a strictly positive value.
1686  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1687  assert(IntWidth && "Builtin type of size 0?");
1688  llvm::APSInt Value(IntWidth);
1689  Array.NumElts
1691  CCEK_NewExpr)
1692  .get();
1693  } else {
1694  Array.NumElts
1695  = VerifyIntegerConstantExpression(NumElts, nullptr,
1696  diag::err_new_array_nonconst)
1697  .get();
1698  }
1699  if (!Array.NumElts)
1700  return ExprError();
1701  }
1702  }
1703  }
1704  }
1705 
1706  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1707  QualType AllocType = TInfo->getType();
1708  if (D.isInvalidType())
1709  return ExprError();
1710 
1711  SourceRange DirectInitRange;
1712  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1713  DirectInitRange = List->getSourceRange();
1714 
1715  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1716  PlacementLParen, PlacementArgs, PlacementRParen,
1717  TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1718  Initializer);
1719 }
1720 
1722  Expr *Init) {
1723  if (!Init)
1724  return true;
1725  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1726  return PLE->getNumExprs() == 0;
1727  if (isa<ImplicitValueInitExpr>(Init))
1728  return true;
1729  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1730  return !CCE->isListInitialization() &&
1731  CCE->getConstructor()->isDefaultConstructor();
1732  else if (Style == CXXNewExpr::ListInit) {
1733  assert(isa<InitListExpr>(Init) &&
1734  "Shouldn't create list CXXConstructExprs for arrays.");
1735  return true;
1736  }
1737  return false;
1738 }
1739 
1740 bool
1742  if (!getLangOpts().AlignedAllocationUnavailable)
1743  return false;
1744  if (FD.isDefined())
1745  return false;
1746  bool IsAligned = false;
1747  if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1748  return true;
1749  return false;
1750 }
1751 
1752 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1753 // implemented in the standard library is selected.
1755  SourceLocation Loc) {
1757  const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1758  StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1759  getASTContext().getTargetInfo().getPlatformName());
1760 
1762  bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1763  Diag(Loc, diag::err_aligned_allocation_unavailable)
1764  << IsDelete << FD.getType().getAsString() << OSName
1765  << alignedAllocMinVersion(T.getOS()).getAsString();
1766  Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1767  }
1768 }
1769 
1770 ExprResult
1771 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1772  SourceLocation PlacementLParen,
1773  MultiExprArg PlacementArgs,
1774  SourceLocation PlacementRParen,
1775  SourceRange TypeIdParens,
1776  QualType AllocType,
1777  TypeSourceInfo *AllocTypeInfo,
1778  Optional<Expr *> ArraySize,
1779  SourceRange DirectInitRange,
1780  Expr *Initializer) {
1781  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1782  SourceLocation StartLoc = Range.getBegin();
1783 
1785  if (DirectInitRange.isValid()) {
1786  assert(Initializer && "Have parens but no initializer.");
1787  initStyle = CXXNewExpr::CallInit;
1788  } else if (Initializer && isa<InitListExpr>(Initializer))
1789  initStyle = CXXNewExpr::ListInit;
1790  else {
1791  assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1792  isa<CXXConstructExpr>(Initializer)) &&
1793  "Initializer expression that cannot have been implicitly created.");
1794  initStyle = CXXNewExpr::NoInit;
1795  }
1796 
1797  Expr **Inits = &Initializer;
1798  unsigned NumInits = Initializer ? 1 : 0;
1799  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1800  assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1801  Inits = List->getExprs();
1802  NumInits = List->getNumExprs();
1803  }
1804 
1805  // C++11 [expr.new]p15:
1806  // A new-expression that creates an object of type T initializes that
1807  // object as follows:
1809  // - If the new-initializer is omitted, the object is default-
1810  // initialized (8.5); if no initialization is performed,
1811  // the object has indeterminate value
1812  = initStyle == CXXNewExpr::NoInit
1814  // - Otherwise, the new-initializer is interpreted according to
1815  // the
1816  // initialization rules of 8.5 for direct-initialization.
1817  : initStyle == CXXNewExpr::ListInit
1819  TypeRange.getBegin(), Initializer->getBeginLoc(),
1820  Initializer->getEndLoc())
1822  DirectInitRange.getBegin(),
1823  DirectInitRange.getEnd());
1824 
1825  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1826  auto *Deduced = AllocType->getContainedDeducedType();
1827  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1828  if (ArraySize)
1829  return ExprError(
1830  Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1831  diag::err_deduced_class_template_compound_type)
1832  << /*array*/ 2
1833  << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1834 
1835  InitializedEntity Entity
1836  = InitializedEntity::InitializeNew(StartLoc, AllocType);
1838  AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1839  if (AllocType.isNull())
1840  return ExprError();
1841  } else if (Deduced) {
1842  bool Braced = (initStyle == CXXNewExpr::ListInit);
1843  if (NumInits == 1) {
1844  if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1845  Inits = p->getInits();
1846  NumInits = p->getNumInits();
1847  Braced = true;
1848  }
1849  }
1850 
1851  if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1852  return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1853  << AllocType << TypeRange);
1854  if (NumInits > 1) {
1855  Expr *FirstBad = Inits[1];
1856  return ExprError(Diag(FirstBad->getBeginLoc(),
1857  diag::err_auto_new_ctor_multiple_expressions)
1858  << AllocType << TypeRange);
1859  }
1860  if (Braced && !getLangOpts().CPlusPlus17)
1861  Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1862  << AllocType << TypeRange;
1863  Expr *Deduce = Inits[0];
1865  if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1866  return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1867  << AllocType << Deduce->getType()
1868  << TypeRange << Deduce->getSourceRange());
1869  if (DeducedType.isNull())
1870  return ExprError();
1871  AllocType = DeducedType;
1872  }
1873 
1874  // Per C++0x [expr.new]p5, the type being constructed may be a
1875  // typedef of an array type.
1876  if (!ArraySize) {
1877  if (const ConstantArrayType *Array
1878  = Context.getAsConstantArrayType(AllocType)) {
1879  ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1880  Context.getSizeType(),
1881  TypeRange.getEnd());
1882  AllocType = Array->getElementType();
1883  }
1884  }
1885 
1886  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1887  return ExprError();
1888 
1889  // In ARC, infer 'retaining' for the allocated
1890  if (getLangOpts().ObjCAutoRefCount &&
1891  AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1892  AllocType->isObjCLifetimeType()) {
1893  AllocType = Context.getLifetimeQualifiedType(AllocType,
1894  AllocType->getObjCARCImplicitLifetime());
1895  }
1896 
1897  QualType ResultType = Context.getPointerType(AllocType);
1898 
1899  if (ArraySize && *ArraySize &&
1900  (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1901  ExprResult result = CheckPlaceholderExpr(*ArraySize);
1902  if (result.isInvalid()) return ExprError();
1903  ArraySize = result.get();
1904  }
1905  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1906  // integral or enumeration type with a non-negative value."
1907  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1908  // enumeration type, or a class type for which a single non-explicit
1909  // conversion function to integral or unscoped enumeration type exists.
1910  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1911  // std::size_t.
1912  llvm::Optional<uint64_t> KnownArraySize;
1913  if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
1914  ExprResult ConvertedSize;
1915  if (getLangOpts().CPlusPlus14) {
1916  assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1917 
1918  ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
1919  AA_Converting);
1920 
1921  if (!ConvertedSize.isInvalid() &&
1922  (*ArraySize)->getType()->getAs<RecordType>())
1923  // Diagnose the compatibility of this conversion.
1924  Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1925  << (*ArraySize)->getType() << 0 << "'size_t'";
1926  } else {
1927  class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1928  protected:
1929  Expr *ArraySize;
1930 
1931  public:
1932  SizeConvertDiagnoser(Expr *ArraySize)
1933  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1934  ArraySize(ArraySize) {}
1935 
1936  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1937  QualType T) override {
1938  return S.Diag(Loc, diag::err_array_size_not_integral)
1939  << S.getLangOpts().CPlusPlus11 << T;
1940  }
1941 
1942  SemaDiagnosticBuilder diagnoseIncomplete(
1943  Sema &S, SourceLocation Loc, QualType T) override {
1944  return S.Diag(Loc, diag::err_array_size_incomplete_type)
1945  << T << ArraySize->getSourceRange();
1946  }
1947 
1948  SemaDiagnosticBuilder diagnoseExplicitConv(
1949  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1950  return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1951  }
1952 
1953  SemaDiagnosticBuilder noteExplicitConv(
1954  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1955  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1956  << ConvTy->isEnumeralType() << ConvTy;
1957  }
1958 
1959  SemaDiagnosticBuilder diagnoseAmbiguous(
1960  Sema &S, SourceLocation Loc, QualType T) override {
1961  return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1962  }
1963 
1964  SemaDiagnosticBuilder noteAmbiguous(
1965  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1966  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967  << ConvTy->isEnumeralType() << ConvTy;
1968  }
1969 
1970  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1971  QualType T,
1972  QualType ConvTy) override {
1973  return S.Diag(Loc,
1974  S.getLangOpts().CPlusPlus11
1975  ? diag::warn_cxx98_compat_array_size_conversion
1976  : diag::ext_array_size_conversion)
1977  << T << ConvTy->isEnumeralType() << ConvTy;
1978  }
1979  } SizeDiagnoser(*ArraySize);
1980 
1981  ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
1982  SizeDiagnoser);
1983  }
1984  if (ConvertedSize.isInvalid())
1985  return ExprError();
1986 
1987  ArraySize = ConvertedSize.get();
1988  QualType SizeType = (*ArraySize)->getType();
1989 
1990  if (!SizeType->isIntegralOrUnscopedEnumerationType())
1991  return ExprError();
1992 
1993  // C++98 [expr.new]p7:
1994  // The expression in a direct-new-declarator shall have integral type
1995  // with a non-negative value.
1996  //
1997  // Let's see if this is a constant < 0. If so, we reject it out of hand,
1998  // per CWG1464. Otherwise, if it's not a constant, we must have an
1999  // unparenthesized array type.
2000  if (!(*ArraySize)->isValueDependent()) {
2002  // We've already performed any required implicit conversion to integer or
2003  // unscoped enumeration type.
2004  // FIXME: Per CWG1464, we are required to check the value prior to
2005  // converting to size_t. This will never find a negative array size in
2006  // C++14 onwards, because Value is always unsigned here!
2007  if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
2008  if (Value.isSigned() && Value.isNegative()) {
2009  return ExprError(Diag((*ArraySize)->getBeginLoc(),
2010  diag::err_typecheck_negative_array_size)
2011  << (*ArraySize)->getSourceRange());
2012  }
2013 
2014  if (!AllocType->isDependentType()) {
2015  unsigned ActiveSizeBits =
2017  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2018  return ExprError(
2019  Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2020  << Value.toString(10) << (*ArraySize)->getSourceRange());
2021  }
2022 
2023  KnownArraySize = Value.getZExtValue();
2024  } else if (TypeIdParens.isValid()) {
2025  // Can't have dynamic array size when the type-id is in parentheses.
2026  Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2027  << (*ArraySize)->getSourceRange()
2028  << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2029  << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2030 
2031  TypeIdParens = SourceRange();
2032  }
2033  }
2034 
2035  // Note that we do *not* convert the argument in any way. It can
2036  // be signed, larger than size_t, whatever.
2037  }
2038 
2039  FunctionDecl *OperatorNew = nullptr;
2040  FunctionDecl *OperatorDelete = nullptr;
2041  unsigned Alignment =
2042  AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2043  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2044  bool PassAlignment = getLangOpts().AlignedAllocation &&
2045  Alignment > NewAlignment;
2046 
2048  if (!AllocType->isDependentType() &&
2049  !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2051  StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2052  AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2053  OperatorNew, OperatorDelete))
2054  return ExprError();
2055 
2056  // If this is an array allocation, compute whether the usual array
2057  // deallocation function for the type has a size_t parameter.
2058  bool UsualArrayDeleteWantsSize = false;
2059  if (ArraySize && !AllocType->isDependentType())
2060  UsualArrayDeleteWantsSize =
2061  doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2062 
2063  SmallVector<Expr *, 8> AllPlaceArgs;
2064  if (OperatorNew) {
2065  const FunctionProtoType *Proto =
2066  OperatorNew->getType()->getAs<FunctionProtoType>();
2067  VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2069 
2070  // We've already converted the placement args, just fill in any default
2071  // arguments. Skip the first parameter because we don't have a corresponding
2072  // argument. Skip the second parameter too if we're passing in the
2073  // alignment; we've already filled it in.
2074  if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2075  PassAlignment ? 2 : 1, PlacementArgs,
2076  AllPlaceArgs, CallType))
2077  return ExprError();
2078 
2079  if (!AllPlaceArgs.empty())
2080  PlacementArgs = AllPlaceArgs;
2081 
2082  // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2083  DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2084 
2085  // FIXME: Missing call to CheckFunctionCall or equivalent
2086 
2087  // Warn if the type is over-aligned and is being allocated by (unaligned)
2088  // global operator new.
2089  if (PlacementArgs.empty() && !PassAlignment &&
2090  (OperatorNew->isImplicit() ||
2091  (OperatorNew->getBeginLoc().isValid() &&
2092  getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2093  if (Alignment > NewAlignment)
2094  Diag(StartLoc, diag::warn_overaligned_type)
2095  << AllocType
2096  << unsigned(Alignment / Context.getCharWidth())
2097  << unsigned(NewAlignment / Context.getCharWidth());
2098  }
2099  }
2100 
2101  // Array 'new' can't have any initializers except empty parentheses.
2102  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2103  // dialect distinction.
2104  if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2105  SourceRange InitRange(Inits[0]->getBeginLoc(),
2106  Inits[NumInits - 1]->getEndLoc());
2107  Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2108  return ExprError();
2109  }
2110 
2111  // If we can perform the initialization, and we've not already done so,
2112  // do it now.
2113  if (!AllocType->isDependentType() &&
2115  llvm::makeArrayRef(Inits, NumInits))) {
2116  // The type we initialize is the complete type, including the array bound.
2117  QualType InitType;
2118  if (KnownArraySize)
2119  InitType = Context.getConstantArrayType(
2120  AllocType,
2122  *KnownArraySize),
2123  *ArraySize, ArrayType::Normal, 0);
2124  else if (ArraySize)
2125  InitType =
2126  Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2127  else
2128  InitType = AllocType;
2129 
2130  InitializedEntity Entity
2131  = InitializedEntity::InitializeNew(StartLoc, InitType);
2132  InitializationSequence InitSeq(*this, Entity, Kind,
2133  MultiExprArg(Inits, NumInits));
2134  ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2135  MultiExprArg(Inits, NumInits));
2136  if (FullInit.isInvalid())
2137  return ExprError();
2138 
2139  // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2140  // we don't want the initialized object to be destructed.
2141  // FIXME: We should not create these in the first place.
2142  if (CXXBindTemporaryExpr *Binder =
2143  dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2144  FullInit = Binder->getSubExpr();
2145 
2146  Initializer = FullInit.get();
2147 
2148  // FIXME: If we have a KnownArraySize, check that the array bound of the
2149  // initializer is no greater than that constant value.
2150 
2151  if (ArraySize && !*ArraySize) {
2152  auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2153  if (CAT) {
2154  // FIXME: Track that the array size was inferred rather than explicitly
2155  // specified.
2156  ArraySize = IntegerLiteral::Create(
2157  Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2158  } else {
2159  Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2160  << Initializer->getSourceRange();
2161  }
2162  }
2163  }
2164 
2165  // Mark the new and delete operators as referenced.
2166  if (OperatorNew) {
2167  if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2168  return ExprError();
2169  MarkFunctionReferenced(StartLoc, OperatorNew);
2170  }
2171  if (OperatorDelete) {
2172  if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2173  return ExprError();
2174  MarkFunctionReferenced(StartLoc, OperatorDelete);
2175  }
2176 
2177  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2178  PassAlignment, UsualArrayDeleteWantsSize,
2179  PlacementArgs, TypeIdParens, ArraySize, initStyle,
2180  Initializer, ResultType, AllocTypeInfo, Range,
2181  DirectInitRange);
2182 }
2183 
2184 /// Checks that a type is suitable as the allocated type
2185 /// in a new-expression.
2187  SourceRange R) {
2188  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2189  // abstract class type or array thereof.
2190  if (AllocType->isFunctionType())
2191  return Diag(Loc, diag::err_bad_new_type)
2192  << AllocType << 0 << R;
2193  else if (AllocType->isReferenceType())
2194  return Diag(Loc, diag::err_bad_new_type)
2195  << AllocType << 1 << R;
2196  else if (!AllocType->isDependentType() &&
2197  RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2198  return true;
2199  else if (RequireNonAbstractType(Loc, AllocType,
2200  diag::err_allocation_of_abstract_type))
2201  return true;
2202  else if (AllocType->isVariablyModifiedType())
2203  return Diag(Loc, diag::err_variably_modified_new_type)
2204  << AllocType;
2205  else if (AllocType.getAddressSpace() != LangAS::Default &&
2206  !getLangOpts().OpenCLCPlusPlus)
2207  return Diag(Loc, diag::err_address_space_qualified_new)
2208  << AllocType.getUnqualifiedType()
2210  else if (getLangOpts().ObjCAutoRefCount) {
2211  if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2212  QualType BaseAllocType = Context.getBaseElementType(AT);
2213  if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2214  BaseAllocType->isObjCLifetimeType())
2215  return Diag(Loc, diag::err_arc_new_array_without_ownership)
2216  << BaseAllocType;
2217  }
2218  }
2219 
2220  return false;
2221 }
2222 
2225  bool &PassAlignment, FunctionDecl *&Operator,
2226  OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2227  OverloadCandidateSet Candidates(R.getNameLoc(),
2229  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2230  Alloc != AllocEnd; ++Alloc) {
2231  // Even member operator new/delete are implicitly treated as
2232  // static, so don't use AddMemberCandidate.
2233  NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2234 
2235  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2236  S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2237  /*ExplicitTemplateArgs=*/nullptr, Args,
2238  Candidates,
2239  /*SuppressUserConversions=*/false);
2240  continue;
2241  }
2242 
2243  FunctionDecl *Fn = cast<FunctionDecl>(D);
2244  S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2245  /*SuppressUserConversions=*/false);
2246  }
2247 
2248  // Do the resolution.
2250  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2251  case OR_Success: {
2252  // Got one!
2253  FunctionDecl *FnDecl = Best->Function;
2254  if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2255  Best->FoundDecl) == Sema::AR_inaccessible)
2256  return true;
2257 
2258  Operator = FnDecl;
2259  return false;
2260  }
2261 
2262  case OR_No_Viable_Function:
2263  // C++17 [expr.new]p13:
2264  // If no matching function is found and the allocated object type has
2265  // new-extended alignment, the alignment argument is removed from the
2266  // argument list, and overload resolution is performed again.
2267  if (PassAlignment) {
2268  PassAlignment = false;
2269  AlignArg = Args[1];
2270  Args.erase(Args.begin() + 1);
2271  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2272  Operator, &Candidates, AlignArg,
2273  Diagnose);
2274  }
2275 
2276  // MSVC will fall back on trying to find a matching global operator new
2277  // if operator new[] cannot be found. Also, MSVC will leak by not
2278  // generating a call to operator delete or operator delete[], but we
2279  // will not replicate that bug.
2280  // FIXME: Find out how this interacts with the std::align_val_t fallback
2281  // once MSVC implements it.
2282  if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2283  S.Context.getLangOpts().MSVCCompat) {
2284  R.clear();
2287  // FIXME: This will give bad diagnostics pointing at the wrong functions.
2288  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2289  Operator, /*Candidates=*/nullptr,
2290  /*AlignArg=*/nullptr, Diagnose);
2291  }
2292 
2293  if (Diagnose) {
2294  PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2295  << R.getLookupName() << Range);
2296 
2297  // If we have aligned candidates, only note the align_val_t candidates
2298  // from AlignedCandidates and the non-align_val_t candidates from
2299  // Candidates.
2300  if (AlignedCandidates) {
2301  auto IsAligned = [](OverloadCandidate &C) {
2302  return C.Function->getNumParams() > 1 &&
2303  C.Function->getParamDecl(1)->getType()->isAlignValT();
2304  };
2305  auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2306 
2307  // This was an overaligned allocation, so list the aligned candidates
2308  // first.
2309  Args.insert(Args.begin() + 1, AlignArg);
2310  AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2311  R.getNameLoc(), IsAligned);
2312  Args.erase(Args.begin() + 1);
2313  Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2314  IsUnaligned);
2315  } else {
2316  Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2317  }
2318  }
2319  return true;
2320 
2321  case OR_Ambiguous:
2322  if (Diagnose) {
2323  Candidates.NoteCandidates(
2325  S.PDiag(diag::err_ovl_ambiguous_call)
2326  << R.getLookupName() << Range),
2327  S, OCD_AmbiguousCandidates, Args);
2328  }
2329  return true;
2330 
2331  case OR_Deleted: {
2332  if (Diagnose) {
2333  Candidates.NoteCandidates(
2335  S.PDiag(diag::err_ovl_deleted_call)
2336  << R.getLookupName() << Range),
2337  S, OCD_AllCandidates, Args);
2338  }
2339  return true;
2340  }
2341  }
2342  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2343 }
2344 
2346  AllocationFunctionScope NewScope,
2347  AllocationFunctionScope DeleteScope,
2348  QualType AllocType, bool IsArray,
2349  bool &PassAlignment, MultiExprArg PlaceArgs,
2350  FunctionDecl *&OperatorNew,
2351  FunctionDecl *&OperatorDelete,
2352  bool Diagnose) {
2353  // --- Choosing an allocation function ---
2354  // C++ 5.3.4p8 - 14 & 18
2355  // 1) If looking in AFS_Global scope for allocation functions, only look in
2356  // the global scope. Else, if AFS_Class, only look in the scope of the
2357  // allocated class. If AFS_Both, look in both.
2358  // 2) If an array size is given, look for operator new[], else look for
2359  // operator new.
2360  // 3) The first argument is always size_t. Append the arguments from the
2361  // placement form.
2362 
2363  SmallVector<Expr*, 8> AllocArgs;
2364  AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2365 
2366  // We don't care about the actual value of these arguments.
2367  // FIXME: Should the Sema create the expression and embed it in the syntax
2368  // tree? Or should the consumer just recalculate the value?
2369  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2370  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2372  Context.getSizeType(),
2373  SourceLocation());
2374  AllocArgs.push_back(&Size);
2375 
2376  QualType AlignValT = Context.VoidTy;
2377  if (PassAlignment) {
2379  AlignValT = Context.getTypeDeclType(getStdAlignValT());
2380  }
2381  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2382  if (PassAlignment)
2383  AllocArgs.push_back(&Align);
2384 
2385  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2386 
2387  // C++ [expr.new]p8:
2388  // If the allocated type is a non-array type, the allocation
2389  // function's name is operator new and the deallocation function's
2390  // name is operator delete. If the allocated type is an array
2391  // type, the allocation function's name is operator new[] and the
2392  // deallocation function's name is operator delete[].
2394  IsArray ? OO_Array_New : OO_New);
2395 
2396  QualType AllocElemType = Context.getBaseElementType(AllocType);
2397 
2398  // Find the allocation function.
2399  {
2400  LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2401 
2402  // C++1z [expr.new]p9:
2403  // If the new-expression begins with a unary :: operator, the allocation
2404  // function's name is looked up in the global scope. Otherwise, if the
2405  // allocated type is a class type T or array thereof, the allocation
2406  // function's name is looked up in the scope of T.
2407  if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2408  LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2409 
2410  // We can see ambiguity here if the allocation function is found in
2411  // multiple base classes.
2412  if (R.isAmbiguous())
2413  return true;
2414 
2415  // If this lookup fails to find the name, or if the allocated type is not
2416  // a class type, the allocation function's name is looked up in the
2417  // global scope.
2418  if (R.empty()) {
2419  if (NewScope == AFS_Class)
2420  return true;
2421 
2423  }
2424 
2425  if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2426  if (PlaceArgs.empty()) {
2427  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2428  } else {
2429  Diag(StartLoc, diag::err_openclcxx_placement_new);
2430  }
2431  return true;
2432  }
2433 
2434  assert(!R.empty() && "implicitly declared allocation functions not found");
2435  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2436 
2437  // We do our own custom access checks below.
2438  R.suppressDiagnostics();
2439 
2440  if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2441  OperatorNew, /*Candidates=*/nullptr,
2442  /*AlignArg=*/nullptr, Diagnose))
2443  return true;
2444  }
2445 
2446  // We don't need an operator delete if we're running under -fno-exceptions.
2447  if (!getLangOpts().Exceptions) {
2448  OperatorDelete = nullptr;
2449  return false;
2450  }
2451 
2452  // Note, the name of OperatorNew might have been changed from array to
2453  // non-array by resolveAllocationOverload.
2455  OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2456  ? OO_Array_Delete
2457  : OO_Delete);
2458 
2459  // C++ [expr.new]p19:
2460  //
2461  // If the new-expression begins with a unary :: operator, the
2462  // deallocation function's name is looked up in the global
2463  // scope. Otherwise, if the allocated type is a class type T or an
2464  // array thereof, the deallocation function's name is looked up in
2465  // the scope of T. If this lookup fails to find the name, or if
2466  // the allocated type is not a class type or array thereof, the
2467  // deallocation function's name is looked up in the global scope.
2468  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2469  if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2470  auto *RD =
2471  cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2472  LookupQualifiedName(FoundDelete, RD);
2473  }
2474  if (FoundDelete.isAmbiguous())
2475  return true; // FIXME: clean up expressions?
2476 
2477  bool FoundGlobalDelete = FoundDelete.empty();
2478  if (FoundDelete.empty()) {
2479  if (DeleteScope == AFS_Class)
2480  return true;
2481 
2484  }
2485 
2486  FoundDelete.suppressDiagnostics();
2487 
2489 
2490  // Whether we're looking for a placement operator delete is dictated
2491  // by whether we selected a placement operator new, not by whether
2492  // we had explicit placement arguments. This matters for things like
2493  // struct A { void *operator new(size_t, int = 0); ... };
2494  // A *a = new A()
2495  //
2496  // We don't have any definition for what a "placement allocation function"
2497  // is, but we assume it's any allocation function whose
2498  // parameter-declaration-clause is anything other than (size_t).
2499  //
2500  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2501  // This affects whether an exception from the constructor of an overaligned
2502  // type uses the sized or non-sized form of aligned operator delete.
2503  bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2504  OperatorNew->isVariadic();
2505 
2506  if (isPlacementNew) {
2507  // C++ [expr.new]p20:
2508  // A declaration of a placement deallocation function matches the
2509  // declaration of a placement allocation function if it has the
2510  // same number of parameters and, after parameter transformations
2511  // (8.3.5), all parameter types except the first are
2512  // identical. [...]
2513  //
2514  // To perform this comparison, we compute the function type that
2515  // the deallocation function should have, and use that type both
2516  // for template argument deduction and for comparison purposes.
2517  QualType ExpectedFunctionType;
2518  {
2519  const FunctionProtoType *Proto
2520  = OperatorNew->getType()->getAs<FunctionProtoType>();
2521 
2522  SmallVector<QualType, 4> ArgTypes;
2523  ArgTypes.push_back(Context.VoidPtrTy);
2524  for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2525  ArgTypes.push_back(Proto->getParamType(I));
2526 
2528  // FIXME: This is not part of the standard's rule.
2529  EPI.Variadic = Proto->isVariadic();
2530 
2531  ExpectedFunctionType
2532  = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2533  }
2534 
2535  for (LookupResult::iterator D = FoundDelete.begin(),
2536  DEnd = FoundDelete.end();
2537  D != DEnd; ++D) {
2538  FunctionDecl *Fn = nullptr;
2539  if (FunctionTemplateDecl *FnTmpl =
2540  dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2541  // Perform template argument deduction to try to match the
2542  // expected function type.
2543  TemplateDeductionInfo Info(StartLoc);
2544  if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2545  Info))
2546  continue;
2547  } else
2548  Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2549 
2551  ExpectedFunctionType,
2552  /*AdjustExcpetionSpec*/true),
2553  ExpectedFunctionType))
2554  Matches.push_back(std::make_pair(D.getPair(), Fn));
2555  }
2556 
2557  if (getLangOpts().CUDA)
2558  EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2559  } else {
2560  // C++1y [expr.new]p22:
2561  // For a non-placement allocation function, the normal deallocation
2562  // function lookup is used
2563  //
2564  // Per [expr.delete]p10, this lookup prefers a member operator delete
2565  // without a size_t argument, but prefers a non-member operator delete
2566  // with a size_t where possible (which it always is in this case).
2568  UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2569  *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2570  /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2571  &BestDeallocFns);
2572  if (Selected)
2573  Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2574  else {
2575  // If we failed to select an operator, all remaining functions are viable
2576  // but ambiguous.
2577  for (auto Fn : BestDeallocFns)
2578  Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2579  }
2580  }
2581 
2582  // C++ [expr.new]p20:
2583  // [...] If the lookup finds a single matching deallocation
2584  // function, that function will be called; otherwise, no
2585  // deallocation function will be called.
2586  if (Matches.size() == 1) {
2587  OperatorDelete = Matches[0].second;
2588 
2589  // C++1z [expr.new]p23:
2590  // If the lookup finds a usual deallocation function (3.7.4.2)
2591  // with a parameter of type std::size_t and that function, considered
2592  // as a placement deallocation function, would have been
2593  // selected as a match for the allocation function, the program
2594  // is ill-formed.
2595  if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2596  isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2597  UsualDeallocFnInfo Info(*this,
2598  DeclAccessPair::make(OperatorDelete, AS_public));
2599  // Core issue, per mail to core reflector, 2016-10-09:
2600  // If this is a member operator delete, and there is a corresponding
2601  // non-sized member operator delete, this isn't /really/ a sized
2602  // deallocation function, it just happens to have a size_t parameter.
2603  bool IsSizedDelete = Info.HasSizeT;
2604  if (IsSizedDelete && !FoundGlobalDelete) {
2605  auto NonSizedDelete =
2606  resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2607  /*WantAlign*/Info.HasAlignValT);
2608  if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2609  NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2610  IsSizedDelete = false;
2611  }
2612 
2613  if (IsSizedDelete) {
2614  SourceRange R = PlaceArgs.empty()
2615  ? SourceRange()
2616  : SourceRange(PlaceArgs.front()->getBeginLoc(),
2617  PlaceArgs.back()->getEndLoc());
2618  Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2619  if (!OperatorDelete->isImplicit())
2620  Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2621  << DeleteName;
2622  }
2623  }
2624 
2625  CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2626  Matches[0].first);
2627  } else if (!Matches.empty()) {
2628  // We found multiple suitable operators. Per [expr.new]p20, that means we
2629  // call no 'operator delete' function, but we should at least warn the user.
2630  // FIXME: Suppress this warning if the construction cannot throw.
2631  Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2632  << DeleteName << AllocElemType;
2633 
2634  for (auto &Match : Matches)
2635  Diag(Match.second->getLocation(),
2636  diag::note_member_declared_here) << DeleteName;
2637  }
2638 
2639  return false;
2640 }
2641 
2642 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2643 /// delete. These are:
2644 /// @code
2645 /// // C++03:
2646 /// void* operator new(std::size_t) throw(std::bad_alloc);
2647 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2648 /// void operator delete(void *) throw();
2649 /// void operator delete[](void *) throw();
2650 /// // C++11:
2651 /// void* operator new(std::size_t);
2652 /// void* operator new[](std::size_t);
2653 /// void operator delete(void *) noexcept;
2654 /// void operator delete[](void *) noexcept;
2655 /// // C++1y:
2656 /// void* operator new(std::size_t);
2657 /// void* operator new[](std::size_t);
2658 /// void operator delete(void *) noexcept;
2659 /// void operator delete[](void *) noexcept;
2660 /// void operator delete(void *, std::size_t) noexcept;
2661 /// void operator delete[](void *, std::size_t) noexcept;
2662 /// @endcode
2663 /// Note that the placement and nothrow forms of new are *not* implicitly
2664 /// declared. Their use requires including <new>.
2667  return;
2668 
2669  // The implicitly declared new and delete operators
2670  // are not supported in OpenCL.
2671  if (getLangOpts().OpenCLCPlusPlus)
2672  return;
2673 
2674  // C++ [basic.std.dynamic]p2:
2675  // [...] The following allocation and deallocation functions (18.4) are
2676  // implicitly declared in global scope in each translation unit of a
2677  // program
2678  //
2679  // C++03:
2680  // void* operator new(std::size_t) throw(std::bad_alloc);
2681  // void* operator new[](std::size_t) throw(std::bad_alloc);
2682  // void operator delete(void*) throw();
2683  // void operator delete[](void*) throw();
2684  // C++11:
2685  // void* operator new(std::size_t);
2686  // void* operator new[](std::size_t);
2687  // void operator delete(void*) noexcept;
2688  // void operator delete[](void*) noexcept;
2689  // C++1y:
2690  // void* operator new(std::size_t);
2691  // void* operator new[](std::size_t);
2692  // void operator delete(void*) noexcept;
2693  // void operator delete[](void*) noexcept;
2694  // void operator delete(void*, std::size_t) noexcept;
2695  // void operator delete[](void*, std::size_t) noexcept;
2696  //
2697  // These implicit declarations introduce only the function names operator
2698  // new, operator new[], operator delete, operator delete[].
2699  //
2700  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2701  // "std" or "bad_alloc" as necessary to form the exception specification.
2702  // However, we do not make these implicit declarations visible to name
2703  // lookup.
2704  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2705  // The "std::bad_alloc" class has not yet been declared, so build it
2706  // implicitly.
2710  &PP.getIdentifierTable().get("bad_alloc"),
2711  nullptr);
2712  getStdBadAlloc()->setImplicit(true);
2713  }
2714  if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2715  // The "std::align_val_t" enum class has not yet been declared, so build it
2716  // implicitly.
2717  auto *AlignValT = EnumDecl::Create(
2719  &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2720  AlignValT->setIntegerType(Context.getSizeType());
2721  AlignValT->setPromotionType(Context.getSizeType());
2722  AlignValT->setImplicit(true);
2723  StdAlignValT = AlignValT;
2724  }
2725 
2726  GlobalNewDeleteDeclared = true;
2727 
2729  QualType SizeT = Context.getSizeType();
2730 
2731  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2732  QualType Return, QualType Param) {
2734  Params.push_back(Param);
2735 
2736  // Create up to four variants of the function (sized/aligned).
2737  bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2738  (Kind == OO_Delete || Kind == OO_Array_Delete);
2739  bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2740 
2741  int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2742  int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2743  for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2744  if (Sized)
2745  Params.push_back(SizeT);
2746 
2747  for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2748  if (Aligned)
2749  Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2750 
2752  Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2753 
2754  if (Aligned)
2755  Params.pop_back();
2756  }
2757  }
2758  };
2759 
2760  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2761  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2762  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2763  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2764 }
2765 
2766 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2767 /// allocation function if it doesn't already exist.
2769  QualType Return,
2770  ArrayRef<QualType> Params) {
2772 
2773  // Check if this function is already declared.
2774  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2775  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2776  Alloc != AllocEnd; ++Alloc) {
2777  // Only look at non-template functions, as it is the predefined,
2778  // non-templated allocation function we are trying to declare here.
2779  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2780  if (Func->getNumParams() == Params.size()) {
2781  llvm::SmallVector<QualType, 3> FuncParams;
2782  for (auto *P : Func->parameters())
2783  FuncParams.push_back(
2784  Context.getCanonicalType(P->getType().getUnqualifiedType()));
2785  if (llvm::makeArrayRef(FuncParams) == Params) {
2786  // Make the function visible to name lookup, even if we found it in
2787  // an unimported module. It either is an implicitly-declared global
2788  // allocation function, or is suppressing that function.
2789  Func->setVisibleDespiteOwningModule();
2790  return;
2791  }
2792  }
2793  }
2794  }
2795 
2797  /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
2798 
2799  QualType BadAllocType;
2800  bool HasBadAllocExceptionSpec
2801  = (Name.getCXXOverloadedOperator() == OO_New ||
2802  Name.getCXXOverloadedOperator() == OO_Array_New);
2803  if (HasBadAllocExceptionSpec) {
2804  if (!getLangOpts().CPlusPlus11) {
2805  BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2806  assert(StdBadAlloc && "Must have std::bad_alloc declared");
2807  EPI.ExceptionSpec.Type = EST_Dynamic;
2808  EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2809  }
2810  } else {
2811  EPI.ExceptionSpec =
2812  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2813  }
2814 
2815  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2816  QualType FnType = Context.getFunctionType(Return, Params, EPI);
2818  Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2819  FnType, /*TInfo=*/nullptr, SC_None, false, true);
2820  Alloc->setImplicit();
2821  // Global allocation functions should always be visible.
2823 
2824  Alloc->addAttr(VisibilityAttr::CreateImplicit(
2825  Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2826  ? VisibilityAttr::Hidden
2828 
2830  for (QualType T : Params) {
2831  ParamDecls.push_back(ParmVarDecl::Create(
2832  Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2833  /*TInfo=*/nullptr, SC_None, nullptr));
2834  ParamDecls.back()->setImplicit();
2835  }
2836  Alloc->setParams(ParamDecls);
2837  if (ExtraAttr)
2838  Alloc->addAttr(ExtraAttr);
2840  IdResolver.tryAddTopLevelDecl(Alloc, Name);
2841  };
2842 
2843  if (!LangOpts.CUDA)
2844  CreateAllocationFunctionDecl(nullptr);
2845  else {
2846  // Host and device get their own declaration so each can be
2847  // defined or re-declared independently.
2848  CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2849  CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2850  }
2851 }
2852 
2854  bool CanProvideSize,
2855  bool Overaligned,
2856  DeclarationName Name) {
2858 
2859  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2861 
2862  // FIXME: It's possible for this to result in ambiguity, through a
2863  // user-declared variadic operator delete or the enable_if attribute. We
2864  // should probably not consider those cases to be usual deallocation
2865  // functions. But for now we just make an arbitrary choice in that case.
2866  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2867  Overaligned);
2868  assert(Result.FD && "operator delete missing from global scope?");
2869  return Result.FD;
2870 }
2871 
2873  CXXRecordDecl *RD) {
2875 
2876  FunctionDecl *OperatorDelete = nullptr;
2877  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2878  return nullptr;
2879  if (OperatorDelete)
2880  return OperatorDelete;
2881 
2882  // If there's no class-specific operator delete, look up the global
2883  // non-array delete.
2885  Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2886  Name);
2887 }
2888 
2890  DeclarationName Name,
2891  FunctionDecl *&Operator, bool Diagnose) {
2892  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2893  // Try to find operator delete/operator delete[] in class scope.
2894  LookupQualifiedName(Found, RD);
2895 
2896  if (Found.isAmbiguous())
2897  return true;
2898 
2899  Found.suppressDiagnostics();
2900 
2901  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2902 
2903  // C++17 [expr.delete]p10:
2904  // If the deallocation functions have class scope, the one without a
2905  // parameter of type std::size_t is selected.
2907  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2908  /*WantAlign*/ Overaligned, &Matches);
2909 
2910  // If we could find an overload, use it.
2911  if (Matches.size() == 1) {
2912  Operator = cast<CXXMethodDecl>(Matches[0].FD);
2913 
2914  // FIXME: DiagnoseUseOfDecl?
2915  if (Operator->isDeleted()) {
2916  if (Diagnose) {
2917  Diag(StartLoc, diag::err_deleted_function_use);
2918  NoteDeletedFunction(Operator);
2919  }
2920  return true;
2921  }
2922 
2923  if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2924  Matches[0].Found, Diagnose) == AR_inaccessible)
2925  return true;
2926 
2927  return false;
2928  }
2929 
2930  // We found multiple suitable operators; complain about the ambiguity.
2931  // FIXME: The standard doesn't say to do this; it appears that the intent
2932  // is that this should never happen.
2933  if (!Matches.empty()) {
2934  if (Diagnose) {
2935  Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2936  << Name << RD;
2937  for (auto &Match : Matches)
2938  Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2939  }
2940  return true;
2941  }
2942 
2943  // We did find operator delete/operator delete[] declarations, but
2944  // none of them were suitable.
2945  if (!Found.empty()) {
2946  if (Diagnose) {
2947  Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2948  << Name << RD;
2949 
2950  for (NamedDecl *D : Found)
2951  Diag(D->getUnderlyingDecl()->getLocation(),
2952  diag::note_member_declared_here) << Name;
2953  }
2954  return true;
2955  }
2956 
2957  Operator = nullptr;
2958  return false;
2959 }
2960 
2961 namespace {
2962 /// Checks whether delete-expression, and new-expression used for
2963 /// initializing deletee have the same array form.
2964 class MismatchingNewDeleteDetector {
2965 public:
2966  enum MismatchResult {
2967  /// Indicates that there is no mismatch or a mismatch cannot be proven.
2968  NoMismatch,
2969  /// Indicates that variable is initialized with mismatching form of \a new.
2970  VarInitMismatches,
2971  /// Indicates that member is initialized with mismatching form of \a new.
2972  MemberInitMismatches,
2973  /// Indicates that 1 or more constructors' definitions could not been
2974  /// analyzed, and they will be checked again at the end of translation unit.
2975  AnalyzeLater
2976  };
2977 
2978  /// \param EndOfTU True, if this is the final analysis at the end of
2979  /// translation unit. False, if this is the initial analysis at the point
2980  /// delete-expression was encountered.
2981  explicit MismatchingNewDeleteDetector(bool EndOfTU)
2982  : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2983  HasUndefinedConstructors(false) {}
2984 
2985  /// Checks whether pointee of a delete-expression is initialized with
2986  /// matching form of new-expression.
2987  ///
2988  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2989  /// point where delete-expression is encountered, then a warning will be
2990  /// issued immediately. If return value is \c AnalyzeLater at the point where
2991  /// delete-expression is seen, then member will be analyzed at the end of
2992  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2993  /// couldn't be analyzed. If at least one constructor initializes the member
2994  /// with matching type of new, the return value is \c NoMismatch.
2995  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2996  /// Analyzes a class member.
2997  /// \param Field Class member to analyze.
2998  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2999  /// for deleting the \p Field.
3000  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3001  FieldDecl *Field;
3002  /// List of mismatching new-expressions used for initialization of the pointee
3004  /// Indicates whether delete-expression was in array form.
3005  bool IsArrayForm;
3006 
3007 private:
3008  const bool EndOfTU;
3009  /// Indicates that there is at least one constructor without body.
3010  bool HasUndefinedConstructors;
3011  /// Returns \c CXXNewExpr from given initialization expression.
3012  /// \param E Expression used for initializing pointee in delete-expression.
3013  /// E can be a single-element \c InitListExpr consisting of new-expression.
3014  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3015  /// Returns whether member is initialized with mismatching form of
3016  /// \c new either by the member initializer or in-class initialization.
3017  ///
3018  /// If bodies of all constructors are not visible at the end of translation
3019  /// unit or at least one constructor initializes member with the matching
3020  /// form of \c new, mismatch cannot be proven, and this function will return
3021  /// \c NoMismatch.
3022  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3023  /// Returns whether variable is initialized with mismatching form of
3024  /// \c new.
3025  ///
3026  /// If variable is initialized with matching form of \c new or variable is not
3027  /// initialized with a \c new expression, this function will return true.
3028  /// If variable is initialized with mismatching form of \c new, returns false.
3029  /// \param D Variable to analyze.
3030  bool hasMatchingVarInit(const DeclRefExpr *D);
3031  /// Checks whether the constructor initializes pointee with mismatching
3032  /// form of \c new.
3033  ///
3034  /// Returns true, if member is initialized with matching form of \c new in
3035  /// member initializer list. Returns false, if member is initialized with the
3036  /// matching form of \c new in this constructor's initializer or given
3037  /// constructor isn't defined at the point where delete-expression is seen, or
3038  /// member isn't initialized by the constructor.
3039  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3040  /// Checks whether member is initialized with matching form of
3041  /// \c new in member initializer list.
3042  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3043  /// Checks whether member is initialized with mismatching form of \c new by
3044  /// in-class initializer.
3045  MismatchResult analyzeInClassInitializer();
3046 };
3047 }
3048 
3049 MismatchingNewDeleteDetector::MismatchResult
3050 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3051  NewExprs.clear();
3052  assert(DE && "Expected delete-expression");
3053  IsArrayForm = DE->isArrayForm();
3054  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3055  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3056  return analyzeMemberExpr(ME);
3057  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3058  if (!hasMatchingVarInit(D))
3059  return VarInitMismatches;
3060  }
3061  return NoMismatch;
3062 }
3063 
3064 const CXXNewExpr *
3065 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3066  assert(E != nullptr && "Expected a valid initializer expression");
3067  E = E->IgnoreParenImpCasts();
3068  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3069  if (ILE->getNumInits() == 1)
3070  E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3071  }
3072 
3073  return dyn_cast_or_null<const CXXNewExpr>(E);
3074 }
3075 
3076 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3077  const CXXCtorInitializer *CI) {
3078  const CXXNewExpr *NE = nullptr;
3079  if (Field == CI->getMember() &&
3080  (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3081  if (NE->isArray() == IsArrayForm)
3082  return true;
3083  else
3084  NewExprs.push_back(NE);
3085  }
3086  return false;
3087 }
3088 
3089 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3090  const CXXConstructorDecl *CD) {
3091  if (CD->isImplicit())
3092  return false;
3093  const FunctionDecl *Definition = CD;
3094  if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3095  HasUndefinedConstructors = true;
3096  return EndOfTU;
3097  }
3098  for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3099  if (hasMatchingNewInCtorInit(CI))
3100  return true;
3101  }
3102  return false;
3103 }
3104 
3105 MismatchingNewDeleteDetector::MismatchResult
3106 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3107  assert(Field != nullptr && "This should be called only for members");
3108  const Expr *InitExpr = Field->getInClassInitializer();
3109  if (!InitExpr)
3110  return EndOfTU ? NoMismatch : AnalyzeLater;
3111  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3112  if (NE->isArray() != IsArrayForm) {
3113  NewExprs.push_back(NE);
3114  return MemberInitMismatches;
3115  }
3116  }
3117  return NoMismatch;
3118 }
3119 
3120 MismatchingNewDeleteDetector::MismatchResult
3121 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3122  bool DeleteWasArrayForm) {
3123  assert(Field != nullptr && "Analysis requires a valid class member.");
3124  this->Field = Field;
3125  IsArrayForm = DeleteWasArrayForm;
3126  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3127  for (const auto *CD : RD->ctors()) {
3128  if (hasMatchingNewInCtor(CD))
3129  return NoMismatch;
3130  }
3131  if (HasUndefinedConstructors)
3132  return EndOfTU ? NoMismatch : AnalyzeLater;
3133  if (!NewExprs.empty())
3134  return MemberInitMismatches;
3135  return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3136  : NoMismatch;
3137 }
3138 
3139 MismatchingNewDeleteDetector::MismatchResult
3140 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3141  assert(ME != nullptr && "Expected a member expression");
3142  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3143  return analyzeField(F, IsArrayForm);
3144  return NoMismatch;
3145 }
3146 
3147 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3148  const CXXNewExpr *NE = nullptr;
3149  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3150  if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3151  NE->isArray() != IsArrayForm) {
3152  NewExprs.push_back(NE);
3153  }
3154  }
3155  return NewExprs.empty();
3156 }
3157 
3158 static void
3160  const MismatchingNewDeleteDetector &Detector) {
3161  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3162  FixItHint H;
3163  if (!Detector.IsArrayForm)
3164  H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3165  else {
3167  DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3168  SemaRef.getLangOpts(), true);
3169  if (RSquare.isValid())
3170  H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3171  }
3172  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3173  << Detector.IsArrayForm << H;
3174 
3175  for (const auto *NE : Detector.NewExprs)
3176  SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3177  << Detector.IsArrayForm;
3178 }
3179 
3180 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3181  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3182  return;
3183  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3184  switch (Detector.analyzeDeleteExpr(DE)) {
3185  case MismatchingNewDeleteDetector::VarInitMismatches:
3186  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3187  DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3188  break;
3189  }
3190  case MismatchingNewDeleteDetector::AnalyzeLater: {
3191  DeleteExprs[Detector.Field].push_back(
3192  std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3193  break;
3194  }
3195  case MismatchingNewDeleteDetector::NoMismatch:
3196  break;
3197  }
3198 }
3199 
3200 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3201  bool DeleteWasArrayForm) {
3202  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3203  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3204  case MismatchingNewDeleteDetector::VarInitMismatches:
3205  llvm_unreachable("This analysis should have been done for class members.");
3206  case MismatchingNewDeleteDetector::AnalyzeLater:
3207  llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3208  "translation unit.");
3209  case MismatchingNewDeleteDetector::MemberInitMismatches:
3210  DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3211  break;
3212  case MismatchingNewDeleteDetector::NoMismatch:
3213  break;
3214  }
3215 }
3216 
3217 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3218 /// @code ::delete ptr; @endcode
3219 /// or
3220 /// @code delete [] ptr; @endcode
3221 ExprResult
3222 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3223  bool ArrayForm, Expr *ExE) {
3224  // C++ [expr.delete]p1:
3225  // The operand shall have a pointer type, or a class type having a single
3226  // non-explicit conversion function to a pointer type. The result has type
3227  // void.
3228  //
3229  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3230 
3231  ExprResult Ex = ExE;
3232  FunctionDecl *OperatorDelete = nullptr;
3233  bool ArrayFormAsWritten = ArrayForm;
3234  bool UsualArrayDeleteWantsSize = false;
3235 
3236  if (!Ex.get()->isTypeDependent()) {
3237  // Perform lvalue-to-rvalue cast, if needed.
3238  Ex = DefaultLvalueConversion(Ex.get());
3239  if (Ex.isInvalid())
3240  return ExprError();
3241 
3242  QualType Type = Ex.get()->getType();
3243 
3244  class DeleteConverter : public ContextualImplicitConverter {
3245  public:
3246  DeleteConverter() : ContextualImplicitConverter(false, true) {}
3247 
3248  bool match(QualType ConvType) override {
3249  // FIXME: If we have an operator T* and an operator void*, we must pick
3250  // the operator T*.
3251  if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3252  if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3253  return true;
3254  return false;
3255  }
3256 
3257  SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3258  QualType T) override {
3259  return S.Diag(Loc, diag::err_delete_operand) << T;
3260  }
3261 
3262  SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3263  QualType T) override {
3264  return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3265  }
3266 
3267  SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3268  QualType T,
3269  QualType ConvTy) override {
3270  return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3271  }
3272 
3273  SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3274  QualType ConvTy) override {
3275  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3276  << ConvTy;
3277  }
3278 
3279  SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3280  QualType T) override {
3281  return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3282  }
3283 
3284  SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3285  QualType ConvTy) override {
3286  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3287  << ConvTy;
3288  }
3289 
3290  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3291  QualType T,
3292  QualType ConvTy) override {
3293  llvm_unreachable("conversion functions are permitted");
3294  }
3295  } Converter;
3296 
3297  Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3298  if (Ex.isInvalid())
3299  return ExprError();
3300  Type = Ex.get()->getType();
3301  if (!Converter.match(Type))
3302  // FIXME: PerformContextualImplicitConversion should return ExprError
3303  // itself in this case.
3304  return ExprError();
3305 
3306  QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3307  QualType PointeeElem = Context.getBaseElementType(Pointee);
3308 
3309  if (Pointee.getAddressSpace() != LangAS::Default &&
3310  !getLangOpts().OpenCLCPlusPlus)
3311  return Diag(Ex.get()->getBeginLoc(),
3312  diag::err_address_space_qualified_delete)
3313  << Pointee.getUnqualifiedType()
3315 
3316  CXXRecordDecl *PointeeRD = nullptr;
3317  if (Pointee->isVoidType() && !isSFINAEContext()) {
3318  // The C++ standard bans deleting a pointer to a non-object type, which
3319  // effectively bans deletion of "void*". However, most compilers support
3320  // this, so we treat it as a warning unless we're in a SFINAE context.
3321  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3322  << Type << Ex.get()->getSourceRange();
3323  } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3324  return ExprError(Diag(StartLoc, diag::err_delete_operand)
3325  << Type << Ex.get()->getSourceRange());
3326  } else if (!Pointee->isDependentType()) {
3327  // FIXME: This can result in errors if the definition was imported from a
3328  // module but is hidden.
3329  if (!RequireCompleteType(StartLoc, Pointee,
3330  diag::warn_delete_incomplete, Ex.get())) {
3331  if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3332  PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3333  }
3334  }
3335 
3336  if (Pointee->isArrayType() && !ArrayForm) {
3337  Diag(StartLoc, diag::warn_delete_array_type)
3338  << Type << Ex.get()->getSourceRange()
3339  << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3340  ArrayForm = true;
3341  }
3342 
3344  ArrayForm ? OO_Array_Delete : OO_Delete);
3345 
3346  if (PointeeRD) {
3347  if (!UseGlobal &&
3348  FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3349  OperatorDelete))
3350  return ExprError();
3351 
3352  // If we're allocating an array of records, check whether the
3353  // usual operator delete[] has a size_t parameter.
3354  if (ArrayForm) {
3355  // If the user specifically asked to use the global allocator,
3356  // we'll need to do the lookup into the class.
3357  if (UseGlobal)
3358  UsualArrayDeleteWantsSize =
3359  doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3360 
3361  // Otherwise, the usual operator delete[] should be the
3362  // function we just found.
3363  else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3364  UsualArrayDeleteWantsSize =
3365  UsualDeallocFnInfo(*this,
3366  DeclAccessPair::make(OperatorDelete, AS_public))
3367  .HasSizeT;
3368  }
3369 
3370  if (!PointeeRD->hasIrrelevantDestructor())
3371  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3372  MarkFunctionReferenced(StartLoc,
3373  const_cast<CXXDestructorDecl*>(Dtor));
3374  if (DiagnoseUseOfDecl(Dtor, StartLoc))
3375  return ExprError();
3376  }
3377 
3378  CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3379  /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3380  /*WarnOnNonAbstractTypes=*/!ArrayForm,
3381  SourceLocation());
3382  }
3383 
3384  if (!OperatorDelete) {
3385  if (getLangOpts().OpenCLCPlusPlus) {
3386  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3387  return ExprError();
3388  }
3389 
3390  bool IsComplete = isCompleteType(StartLoc, Pointee);
3391  bool CanProvideSize =
3392  IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3393  Pointee.isDestructedType());
3394  bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3395 
3396  // Look for a global declaration.
3397  OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3398  Overaligned, DeleteName);
3399  }
3400 
3401  MarkFunctionReferenced(StartLoc, OperatorDelete);
3402 
3403  // Check access and ambiguity of destructor if we're going to call it.
3404  // Note that this is required even for a virtual delete.
3405  bool IsVirtualDelete = false;
3406  if (PointeeRD) {
3407  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3408  CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3409  PDiag(diag::err_access_dtor) << PointeeElem);
3410  IsVirtualDelete = Dtor->isVirtual();
3411  }
3412  }
3413 
3414  DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3415 
3416  // Convert the operand to the type of the first parameter of operator
3417  // delete. This is only necessary if we selected a destroying operator
3418  // delete that we are going to call (non-virtually); converting to void*
3419  // is trivial and left to AST consumers to handle.
3420  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3421  if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3422  Qualifiers Qs = Pointee.getQualifiers();
3423  if (Qs.hasCVRQualifiers()) {
3424  // Qualifiers are irrelevant to this conversion; we're only looking
3425  // for access and ambiguity.
3426  Qs.removeCVRQualifiers();
3427  QualType Unqual = Context.getPointerType(
3429  Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3430  }
3431  Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3432  if (Ex.isInvalid())
3433  return ExprError();
3434  }
3435  }
3436 
3438  Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3439  UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3440  AnalyzeDeleteExprMismatch(Result);
3441  return Result;
3442 }
3443 
3445  bool IsDelete,
3446  FunctionDecl *&Operator) {
3447 
3449  IsDelete ? OO_Delete : OO_New);
3450 
3451  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3453  assert(!R.empty() && "implicitly declared allocation functions not found");
3454  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3455 
3456  // We do our own custom access checks below.
3457  R.suppressDiagnostics();
3458 
3459  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3460  OverloadCandidateSet Candidates(R.getNameLoc(),
3462  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3463  FnOvl != FnOvlEnd; ++FnOvl) {
3464  // Even member operator new/delete are implicitly treated as
3465  // static, so don't use AddMemberCandidate.
3466  NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3467 
3468  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3469  S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3470  /*ExplicitTemplateArgs=*/nullptr, Args,
3471  Candidates,
3472  /*SuppressUserConversions=*/false);
3473  continue;
3474  }
3475 
3476  FunctionDecl *Fn = cast<FunctionDecl>(D);
3477  S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3478  /*SuppressUserConversions=*/false);
3479  }
3480 
3481  SourceRange Range = TheCall->getSourceRange();
3482 
3483  // Do the resolution.
3485  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3486  case OR_Success: {
3487  // Got one!
3488  FunctionDecl *FnDecl = Best->Function;
3489  assert(R.getNamingClass() == nullptr &&
3490  "class members should not be considered");
3491 
3492  if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3493  S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3494  << (IsDelete ? 1 : 0) << Range;
3495  S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3496  << R.getLookupName() << FnDecl->getSourceRange();
3497  return true;
3498  }
3499 
3500  Operator = FnDecl;
3501  return false;
3502  }
3503 
3504  case OR_No_Viable_Function:
3505  Candidates.NoteCandidates(
3506  PartialDiagnosticAt(R.getNameLoc(),
3507  S.PDiag(diag::err_ovl_no_viable_function_in_call)
3508  << R.getLookupName() << Range),
3509  S, OCD_AllCandidates, Args);
3510  return true;
3511 
3512  case OR_Ambiguous:
3513  Candidates.NoteCandidates(
3514  PartialDiagnosticAt(R.getNameLoc(),
3515  S.PDiag(diag::err_ovl_ambiguous_call)
3516  << R.getLookupName() << Range),
3517  S, OCD_AmbiguousCandidates, Args);
3518  return true;
3519 
3520  case OR_Deleted: {
3521  Candidates.NoteCandidates(
3522  PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3523  << R.getLookupName() << Range),
3524  S, OCD_AllCandidates, Args);
3525  return true;
3526  }
3527  }
3528  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3529 }
3530 
3531 ExprResult
3532 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3533  bool IsDelete) {
3534  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3535  if (!getLangOpts().CPlusPlus) {
3536  Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3537  << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3538  << "C++";
3539  return ExprError();
3540  }
3541  // CodeGen assumes it can find the global new and delete to call,
3542  // so ensure that they are declared.
3544 
3545  FunctionDecl *OperatorNewOrDelete = nullptr;
3546  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3547  OperatorNewOrDelete))
3548  return ExprError();
3549  assert(OperatorNewOrDelete && "should be found");
3550 
3551  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3552  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3553 
3554  TheCall->setType(OperatorNewOrDelete->getReturnType());
3555  for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3556  QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3557  InitializedEntity Entity =
3560  Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3561  if (Arg.isInvalid())
3562  return ExprError();
3563  TheCall->setArg(i, Arg.get());
3564  }
3565  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3566  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3567  "Callee expected to be implicit cast to a builtin function pointer");
3568  Callee->setType(OperatorNewOrDelete->getType());
3569 
3570  return TheCallResult;
3571 }
3572 
3574  bool IsDelete, bool CallCanBeVirtual,
3575  bool WarnOnNonAbstractTypes,
3576  SourceLocation DtorLoc) {
3577  if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3578  return;
3579 
3580  // C++ [expr.delete]p3:
3581  // In the first alternative (delete object), if the static type of the
3582  // object to be deleted is different from its dynamic type, the static
3583  // type shall be a base class of the dynamic type of the object to be
3584  // deleted and the static type shall have a virtual destructor or the
3585  // behavior is undefined.
3586  //
3587  const CXXRecordDecl *PointeeRD = dtor->getParent();
3588  // Note: a final class cannot be derived from, no issue there
3589  if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3590  return;
3591 
3592  // If the superclass is in a system header, there's nothing that can be done.
3593  // The `delete` (where we emit the warning) can be in a system header,
3594  // what matters for this warning is where the deleted type is defined.
3595  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3596  return;
3597 
3598  QualType ClassType = dtor->getThisType()->getPointeeType();
3599  if (PointeeRD->isAbstract()) {
3600  // If the class is abstract, we warn by default, because we're
3601  // sure the code has undefined behavior.
3602  Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3603  << ClassType;
3604  } else if (WarnOnNonAbstractTypes) {
3605  // Otherwise, if this is not an array delete, it's a bit suspect,
3606  // but not necessarily wrong.
3607  Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3608  << ClassType;
3609  }
3610  if (!IsDelete) {
3611  std::string TypeStr;
3612  ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3613  Diag(DtorLoc, diag::note_delete_non_virtual)
3614  << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3615  }
3616 }
3617 
3619  SourceLocation StmtLoc,
3620  ConditionKind CK) {
3621  ExprResult E =
3622  CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3623  if (E.isInvalid())
3624  return ConditionError();
3625  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3627 }
3628 
3629 /// Check the use of the given variable as a C++ condition in an if,
3630 /// while, do-while, or switch statement.
3632  SourceLocation StmtLoc,
3633  ConditionKind CK) {
3634  if (ConditionVar->isInvalidDecl())
3635  return ExprError();
3636 
3637  QualType T = ConditionVar->getType();
3638 
3639  // C++ [stmt.select]p2:
3640  // The declarator shall not specify a function or an array.
3641  if (T->isFunctionType())
3642  return ExprError(Diag(ConditionVar->getLocation(),
3643  diag::err_invalid_use_of_function_type)
3644  << ConditionVar->getSourceRange());
3645  else if (T->isArrayType())
3646  return ExprError(Diag(ConditionVar->getLocation(),
3647  diag::err_invalid_use_of_array_type)
3648  << ConditionVar->getSourceRange());
3649 
3650  ExprResult Condition = BuildDeclRefExpr(
3651  ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3652  ConditionVar->getLocation());
3653 
3654  switch (CK) {
3656  return CheckBooleanCondition(StmtLoc, Condition.get());
3657 
3659  return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3660 
3661  case ConditionKind::Switch:
3662  return CheckSwitchCondition(StmtLoc, Condition.get());
3663  }
3664 
3665  llvm_unreachable("unexpected condition kind");
3666 }
3667 
3668 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3669 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3670  // C++ 6.4p4:
3671  // The value of a condition that is an initialized declaration in a statement
3672  // other than a switch statement is the value of the declared variable
3673  // implicitly converted to type bool. If that conversion is ill-formed, the
3674  // program is ill-formed.
3675  // The value of a condition that is an expression is the value of the
3676  // expression, implicitly converted to bool.
3677  //
3678  // FIXME: Return this value to the caller so they don't need to recompute it.
3679  llvm::APSInt Value(/*BitWidth*/1);
3680  return (IsConstexpr && !CondExpr->isValueDependent())
3681  ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3684 }
3685 
3686 /// Helper function to determine whether this is the (deprecated) C++
3687 /// conversion from a string literal to a pointer to non-const char or
3688 /// non-const wchar_t (for narrow and wide string literals,
3689 /// respectively).
3690 bool
3692  // Look inside the implicit cast, if it exists.
3693  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3694  From = Cast->getSubExpr();
3695 
3696  // A string literal (2.13.4) that is not a wide string literal can
3697  // be converted to an rvalue of type "pointer to char"; a wide
3698  // string literal can be converted to an rvalue of type "pointer
3699  // to wchar_t" (C++ 4.2p2).
3700  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3701  if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3702  if (const BuiltinType *ToPointeeType
3703  = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3704  // This conversion is considered only when there is an
3705  // explicit appropriate pointer target type (C++ 4.2p2).
3706  if (!ToPtrType->getPointeeType().hasQualifiers()) {
3707  switch (StrLit->getKind()) {
3708  case StringLiteral::UTF8:
3709  case StringLiteral::UTF16:
3710  case StringLiteral::UTF32:
3711  // We don't allow UTF literals to be implicitly converted
3712  break;
3713  case StringLiteral::Ascii:
3714  return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3715  ToPointeeType->getKind() == BuiltinType::Char_S);
3716  case StringLiteral::Wide:
3718  QualType(ToPointeeType, 0));
3719  }
3720  }
3721  }
3722 
3723  return false;
3724 }
3725 
3727  SourceLocation CastLoc,
3728  QualType Ty,
3729  CastKind Kind,
3730  CXXMethodDecl *Method,
3731  DeclAccessPair FoundDecl,
3732  bool HadMultipleCandidates,
3733  Expr *From) {
3734  switch (Kind) {
3735  default: llvm_unreachable("Unhandled cast kind!");
3736  case CK_ConstructorConversion: {
3737  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3738  SmallVector<Expr*, 8> ConstructorArgs;
3739 
3740  if (S.RequireNonAbstractType(CastLoc, Ty,
3741  diag::err_allocation_of_abstract_type))
3742  return ExprError();
3743 
3744  if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3745  return ExprError();
3746 
3747  S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3749  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3750  return ExprError();
3751 
3753  CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3754  ConstructorArgs, HadMultipleCandidates,
3755  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3757  if (Result.isInvalid())
3758  return ExprError();
3759 
3760  return S.MaybeBindToTemporary(Result.getAs<Expr>());
3761  }
3762 
3763  case CK_UserDefinedConversion: {
3764  assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3765 
3766  S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3767  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3768  return ExprError();
3769 
3770  // Create an implicit call expr that calls it.
3771  CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3772  ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3773  HadMultipleCandidates);
3774  if (Result.isInvalid())
3775  return ExprError();
3776  // Record usage of conversion in an implicit cast.
3777  Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3778  CK_UserDefinedConversion, Result.get(),
3779  nullptr, Result.get()->getValueKind());
3780 
3781  return S.MaybeBindToTemporary(Result.get());
3782  }
3783  }
3784 }
3785 
3786 /// PerformImplicitConversion - Perform an implicit conversion of the
3787 /// expression From to the type ToType using the pre-computed implicit
3788 /// conversion sequence ICS. Returns the converted
3789 /// expression. Action is the kind of conversion we're performing,
3790 /// used in the error message.
3791 ExprResult
3793  const ImplicitConversionSequence &ICS,
3794  AssignmentAction Action,
3795  CheckedConversionKind CCK) {
3796  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3797  if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3798  return From;
3799 
3800  switch (ICS.getKind()) {
3802  ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3803  Action, CCK);
3804  if (Res.isInvalid())
3805  return ExprError();
3806  From = Res.get();
3807  break;
3808  }
3809 
3811 
3814  QualType BeforeToType;
3815  assert(FD && "no conversion function for user-defined conversion seq");
3816  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3817  CastKind = CK_UserDefinedConversion;
3818 
3819  // If the user-defined conversion is specified by a conversion function,
3820  // the initial standard conversion sequence converts the source type to
3821  // the implicit object parameter of the conversion function.
3822  BeforeToType = Context.getTagDeclType(Conv->getParent());
3823  } else {
3824  const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3825  CastKind = CK_ConstructorConversion;
3826  // Do no conversion if dealing with ... for the first conversion.
3827  if (!ICS.UserDefined.EllipsisConversion) {
3828  // If the user-defined conversion is specified by a constructor, the
3829  // initial standard conversion sequence converts the source type to
3830  // the type required by the argument of the constructor
3831  BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3832  }
3833  }
3834  // Watch out for ellipsis conversion.
3835  if (!ICS.UserDefined.EllipsisConversion) {
3836  ExprResult Res =
3837  PerformImplicitConversion(From, BeforeToType,
3839  CCK);
3840  if (Res.isInvalid())
3841  return ExprError();
3842  From = Res.get();
3843  }
3844 
3845  ExprResult CastArg = BuildCXXCastArgument(
3846  *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3847  cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3849 
3850  if (CastArg.isInvalid())
3851  return ExprError();
3852 
3853  From = CastArg.get();
3854 
3855  // C++ [over.match.oper]p7:
3856  // [...] the second standard conversion sequence of a user-defined
3857  // conversion sequence is not applied.
3858  if (CCK == CCK_ForBuiltinOverloadedOp)
3859  return From;
3860 
3861  return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3862  AA_Converting, CCK);
3863  }
3864 
3866  ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3867  PDiag(diag::err_typecheck_ambiguous_condition)
3868  << From->getSourceRange());
3869  return ExprError();
3870 
3872  llvm_unreachable("Cannot perform an ellipsis conversion");
3873 
3875  bool Diagnosed =
3877  From->getType(), From, Action);
3878  assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3879  return ExprError();
3880  }
3881 
3882  // Everything went well.
3883  return From;
3884 }
3885 
3886 /// PerformImplicitConversion - Perform an implicit conversion of the
3887 /// expression From to the type ToType by following the standard
3888 /// conversion sequence SCS. Returns the converted
3889 /// expression. Flavor is the context in which we're performing this
3890 /// conversion, for use in error messages.
3891 ExprResult
3893  const StandardConversionSequence& SCS,
3894  AssignmentAction Action,
3895  CheckedConversionKind CCK) {
3896  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3897 
3898  // Overall FIXME: we are recomputing too many types here and doing far too
3899  // much extra work. What this means is that we need to keep track of more
3900  // information that is computed when we try the implicit conversion initially,
3901  // so that we don't need to recompute anything here.
3902  QualType FromType = From->getType();
3903 
3904  if (SCS.CopyConstructor) {
3905  // FIXME: When can ToType be a reference type?
3906  assert(!ToType->isReferenceType());
3907  if (SCS.Second == ICK_Derived_To_Base) {
3908  SmallVector<Expr*, 8> ConstructorArgs;
3909  if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3910  From, /*FIXME:ConstructLoc*/SourceLocation(),
3911  ConstructorArgs))
3912  return ExprError();
3913  return BuildCXXConstructExpr(
3914  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3916  ConstructorArgs, /*HadMultipleCandidates*/ false,
3917  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3919  }
3920  return BuildCXXConstructExpr(
3921  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3923  From, /*HadMultipleCandidates*/ false,
3924  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3926  }
3927 
3928  // Resolve overloaded function references.
3929  if (Context.hasSameType(FromType, Context.OverloadTy)) {
3930  DeclAccessPair Found;
3932  true, Found);
3933  if (!Fn)
3934  return ExprError();
3935 
3936  if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3937  return ExprError();
3938 
3939  From = FixOverloadedFunctionReference(From, Found, Fn);
3940  FromType = From->getType();
3941  }
3942 
3943  // If we're converting to an atomic type, first convert to the corresponding
3944  // non-atomic type.
3945  QualType ToAtomicType;
3946  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3947  ToAtomicType = ToType;
3948  ToType = ToAtomic->getValueType();
3949  }
3950 
3951  QualType InitialFromType = FromType;
3952  // Perform the first implicit conversion.
3953  switch (SCS.First) {
3954  case ICK_Identity:
3955  if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3956  FromType = FromAtomic->getValueType().getUnqualifiedType();
3957  From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3958  From, /*BasePath=*/nullptr, VK_RValue);
3959  }
3960  break;
3961 
3962  case ICK_Lvalue_To_Rvalue: {
3963  assert(From->getObjectKind() != OK_ObjCProperty);
3964  ExprResult FromRes = DefaultLvalueConversion(From);
3965  assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3966  From = FromRes.get();
3967  FromType = From->getType();
3968  break;
3969  }
3970 
3971  case ICK_Array_To_Pointer:
3972  FromType = Context.getArrayDecayedType(FromType);
3973  From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3974  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3975  break;
3976 
3978  FromType = Context.getPointerType(FromType);
3979  From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3980  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3981  break;
3982 
3983  default:
3984  llvm_unreachable("Improper first standard conversion");
3985  }
3986 
3987  // Perform the second implicit conversion
3988  switch (SCS.Second) {
3989  case ICK_Identity:
3990  // C++ [except.spec]p5:
3991  // [For] assignment to and initialization of pointers to functions,
3992  // pointers to member functions, and references to functions: the
3993  // target entity shall allow at least the exceptions allowed by the
3994  // source value in the assignment or initialization.
3995  switch (Action) {
3996  case AA_Assigning:
3997  case AA_Initializing:
3998  // Note, function argument passing and returning are initialization.
3999  case AA_Passing:
4000  case AA_Returning:
4001  case AA_Sending:
4002  case AA_Passing_CFAudited:
4003  if (CheckExceptionSpecCompatibility(From, ToType))
4004  return ExprError();
4005  break;
4006 
4007  case AA_Casting:
4008  case AA_Converting:
4009  // Casts and implicit conversions are not initialization, so are not
4010  // checked for exception specification mismatches.
4011  break;
4012  }
4013  // Nothing else to do.
4014  break;
4015 
4018  if (ToType->isBooleanType()) {
4019  assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4020  SCS.Second == ICK_Integral_Promotion &&
4021  "only enums with fixed underlying type can promote to bool");
4022  From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4023  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4024  } else {
4025  From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4026  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4027  }
4028  break;
4029 
4032  From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4033  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4034  break;
4035 
4036  case ICK_Complex_Promotion:
4037  case ICK_Complex_Conversion: {
4038  QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4039  QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4040  CastKind CK;
4041  if (FromEl->isRealFloatingType()) {
4042  if (ToEl->isRealFloatingType())
4043  CK = CK_FloatingComplexCast;
4044  else
4045  CK = CK_FloatingComplexToIntegralComplex;
4046  } else if (ToEl->isRealFloatingType()) {
4047  CK = CK_IntegralComplexToFloatingComplex;
4048  } else {
4049  CK = CK_IntegralComplexCast;
4050  }
4051  From = ImpCastExprToType(From, ToType, CK,
4052  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4053  break;
4054  }
4055 
4056  case ICK_Floating_Integral:
4057  if (ToType->isRealFloatingType())
4058  From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4059  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4060  else
4061  From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4062  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4063  break;
4064 
4066  From = ImpCastExprToType(From, ToType, CK_NoOp,
4067  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4068  break;
4069 
4071  case ICK_Pointer_Conversion: {
4072  if (SCS.IncompatibleObjC && Action != AA_Casting) {
4073  // Diagnose incompatible Objective-C conversions
4074  if (Action == AA_Initializing || Action == AA_Assigning)
4075  Diag(From->getBeginLoc(),
4076  diag::ext_typecheck_convert_incompatible_pointer)
4077  << ToType << From->getType() << Action << From->getSourceRange()
4078  << 0;
4079  else
4080  Diag(From->getBeginLoc(),
4081  diag::ext_typecheck_convert_incompatible_pointer)
4082  << From->getType() << ToType << Action << From->getSourceRange()
4083  << 0;
4084 
4085  if (From->getType()->isObjCObjectPointerType() &&
4086  ToType->isObjCObjectPointerType())
4090  From->getType())) {
4091  if (Action == AA_Initializing)
4092  Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4093  else
4094  Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4095  << (Action == AA_Casting) << From->getType() << ToType
4096  << From->getSourceRange();
4097  }
4098 
4099  // Defer address space conversion to the third conversion.
4100  QualType FromPteeType = From->getType()->getPointeeType();
4101  QualType ToPteeType = ToType->getPointeeType();
4102  QualType NewToType = ToType;
4103  if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4104  FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4105  NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4106  NewToType = Context.getAddrSpaceQualType(NewToType,
4107  FromPteeType.getAddressSpace());
4108  if (ToType->isObjCObjectPointerType())
4109  NewToType = Context.getObjCObjectPointerType(NewToType);
4110  else if (ToType->isBlockPointerType())
4111  NewToType = Context.getBlockPointerType(NewToType);
4112  else
4113  NewToType = Context.getPointerType(NewToType);
4114  }
4115 
4116  CastKind Kind;
4117  CXXCastPath BasePath;
4118  if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4119  return ExprError();
4120 
4121  // Make sure we extend blocks if necessary.
4122  // FIXME: doing this here is really ugly.
4123  if (Kind == CK_BlockPointerToObjCPointerCast) {
4124  ExprResult E = From;
4126  From = E.get();
4127  }
4128  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4129  CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4130  From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
4131  .get();
4132  break;
4133  }
4134 
4135  case ICK_Pointer_Member: {
4136  CastKind Kind;
4137  CXXCastPath BasePath;
4138  if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4139  return ExprError();
4140  if (CheckExceptionSpecCompatibility(From, ToType))
4141  return ExprError();
4142 
4143  // We may not have been able to figure out what this member pointer resolved
4144  // to up until this exact point. Attempt to lock-in it's inheritance model.
4146  (void)isCompleteType(From->getExprLoc(), From->getType());
4147  (void)isCompleteType(From->getExprLoc(), ToType);
4148  }
4149 
4150  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4151  .get();
4152  break;
4153  }
4154 
4156  // Perform half-to-boolean conversion via float.
4157  if (From->getType()->isHalfType()) {
4158  From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4159  FromType = Context.FloatTy;
4160  }
4161 
4162  From = ImpCastExprToType(From, Context.BoolTy,
4163  ScalarTypeToBooleanCastKind(FromType),
4164  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4165  break;
4166 
4167  case ICK_Derived_To_Base: {
4168  CXXCastPath BasePath;
4170  From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4171  From->getSourceRange(), &BasePath, CStyle))
4172  return ExprError();
4173 
4174  From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4175  CK_DerivedToBase, From->getValueKind(),
4176  &BasePath, CCK).get();
4177  break;
4178  }
4179 
4180  case ICK_Vector_Conversion:
4181  From = ImpCastExprToType(From, ToType, CK_BitCast,
4182  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4183  break;
4184 
4185  case ICK_Vector_Splat: {
4186  // Vector splat from any arithmetic type to a vector.
4187  Expr *Elem = prepareVectorSplat(ToType, From).get();
4188  From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4189  /*BasePath=*/nullptr, CCK).get();
4190  break;
4191  }
4192 
4193  case ICK_Complex_Real:
4194  // Case 1. x -> _Complex y
4195  if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4196  QualType ElType = ToComplex->getElementType();
4197  bool isFloatingComplex = ElType->isRealFloatingType();
4198 
4199  // x -> y
4200  if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4201  // do nothing
4202  } else if (From->getType()->isRealFloatingType()) {
4203  From = ImpCastExprToType(From, ElType,
4204  isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4205  } else {
4206  assert(From->getType()->isIntegerType());
4207  From = ImpCastExprToType(From, ElType,
4208  isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4209  }
4210  // y -> _Complex y
4211  From = ImpCastExprToType(From, ToType,
4212  isFloatingComplex ? CK_FloatingRealToComplex
4213  : CK_IntegralRealToComplex).get();
4214 
4215  // Case 2. _Complex x -> y
4216  } else {
4217  const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4218  assert(FromComplex);
4219 
4220  QualType ElType = FromComplex->getElementType();
4221  bool isFloatingComplex = ElType->isRealFloatingType();
4222 
4223  // _Complex x -> x
4224  From = ImpCastExprToType(From, ElType,
4225  isFloatingComplex ? CK_FloatingComplexToReal
4226  : CK_IntegralComplexToReal,
4227  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4228 
4229  // x -> y
4230  if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4231  // do nothing
4232  } else if (ToType->isRealFloatingType()) {
4233  From = ImpCastExprToType(From, ToType,
4234  isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4235  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4236  } else {
4237  assert(ToType->isIntegerType());
4238  From = ImpCastExprToType(From, ToType,
4239  isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4240  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4241  }
4242  }
4243  break;
4244 
4246  LangAS AddrSpaceL =
4247  ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4248  LangAS AddrSpaceR =
4249  FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4250  assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4251  "Invalid cast");
4252  CastKind Kind =
4253  AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4254  From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4255  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4256  break;
4257  }
4258 
4260  ExprResult FromRes = From;
4261  Sema::AssignConvertType ConvTy =
4263  if (FromRes.isInvalid())
4264  return ExprError();
4265  From = FromRes.get();
4266  assert ((ConvTy == Sema::Compatible) &&
4267  "Improper transparent union conversion");
4268  (void)ConvTy;
4269  break;
4270  }
4271 
4274  From = ImpCastExprToType(From, ToType,
4275  CK_ZeroToOCLOpaqueType,
4276  From->getValueKind()).get();
4277  break;
4278 
4279  case ICK_Lvalue_To_Rvalue:
4280  case ICK_Array_To_Pointer:
4283  case ICK_Qualification:
4285  case ICK_C_Only_Conversion:
4287  llvm_unreachable("Improper second standard conversion");
4288  }
4289 
4290  switch (SCS.Third) {
4291  case ICK_Identity:
4292  // Nothing to do.
4293  break;
4294 
4296  // If both sides are functions (or pointers/references to them), there could
4297  // be incompatible exception declarations.
4298  if (CheckExceptionSpecCompatibility(From, ToType))
4299  return ExprError();
4300 
4301  From = ImpCastExprToType(From, ToType, CK_NoOp,
4302  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4303  break;
4304 
4305  case ICK_Qualification: {
4306  // The qualification keeps the category of the inner expression, unless the
4307  // target type isn't a reference.
4308  ExprValueKind VK =
4309  ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4310 
4311  CastKind CK = CK_NoOp;
4312 
4313  if (ToType->isReferenceType() &&
4314  ToType->getPointeeType().getAddressSpace() !=
4315  From->getType().getAddressSpace())
4316  CK = CK_AddressSpaceConversion;
4317 
4318  if (ToType->isPointerType() &&
4319  ToType->getPointeeType().getAddressSpace() !=
4320  From->getType()->getPointeeType().getAddressSpace())
4321  CK = CK_AddressSpaceConversion;
4322 
4323  From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4324  /*BasePath=*/nullptr, CCK)
4325  .get();
4326 
4328  !getLangOpts().WritableStrings) {
4329  Diag(From->getBeginLoc(),
4330  getLangOpts().CPlusPlus11
4331  ? diag::ext_deprecated_string_literal_conversion
4332  : diag::warn_deprecated_string_literal_conversion)
4333  << ToType.getNonReferenceType();
4334  }
4335 
4336  break;
4337  }
4338 
4339  default:
4340  llvm_unreachable("Improper third standard conversion");
4341  }
4342 
4343  // If this conversion sequence involved a scalar -> atomic conversion, perform
4344  // that conversion now.
4345  if (!ToAtomicType.isNull()) {
4346  assert(Context.hasSameType(
4347  ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4348  From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4349  VK_RValue, nullptr, CCK).get();
4350  }
4351 
4352  // If this conversion sequence succeeded and involved implicitly converting a
4353  // _Nullable type to a _Nonnull one, complain.
4354  if (!isCast(CCK))
4355  diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4356  From->getBeginLoc());
4357 
4358  return From;
4359 }
4360 
4361 /// Check the completeness of a type in a unary type trait.
4362 ///
4363 /// If the particular type trait requires a complete type, tries to complete
4364 /// it. If completing the type fails, a diagnostic is emitted and false
4365 /// returned. If completing the type succeeds or no completion was required,
4366 /// returns true.
4368  SourceLocation Loc,
4369  QualType ArgTy) {
4370  // C++0x [meta.unary.prop]p3:
4371  // For all of the class templates X declared in this Clause, instantiating
4372  // that template with a template argument that is a class template
4373  // specialization may result in the implicit instantiation of the template
4374  // argument if and only if the semantics of X require that the argument
4375  // must be a complete type.
4376  // We apply this rule to all the type trait expressions used to implement
4377  // these class templates. We also try to follow any GCC documented behavior
4378  // in these expressions to ensure portability of standard libraries.
4379  switch (UTT) {
4380  default: llvm_unreachable("not a UTT");
4381  // is_complete_type somewhat obviously cannot require a complete type.
4382  case UTT_IsCompleteType:
4383  // Fall-through
4384 
4385  // These traits are modeled on the type predicates in C++0x
4386  // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4387  // requiring a complete type, as whether or not they return true cannot be
4388  // impacted by the completeness of the type.
4389  case UTT_IsVoid:
4390  case UTT_IsIntegral:
4391  case UTT_IsFloatingPoint:
4392  case UTT_IsArray:
4393  case UTT_IsPointer:
4394  case UTT_IsLvalueReference:
4395  case UTT_IsRvalueReference:
4398  case UTT_IsEnum:
4399  case UTT_IsUnion:
4400  case UTT_IsClass:
4401  case UTT_IsFunction:
4402  case UTT_IsReference:
4403  case UTT_IsArithmetic:
4404  case UTT_IsFundamental:
4405  case UTT_IsObject:
4406  case UTT_IsScalar:
4407  case UTT_IsCompound:
4408  case UTT_IsMemberPointer:
4409  // Fall-through
4410 
4411  // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4412  // which requires some of its traits to have the complete type. However,
4413  // the completeness of the type cannot impact these traits' semantics, and
4414  // so they don't require it. This matches the comments on these traits in
4415  // Table 49.
4416  case UTT_IsConst:
4417  case UTT_IsVolatile:
4418  case UTT_IsSigned:
4419  case UTT_IsUnsigned:
4420 
4421  // This type trait always returns false, checking the type is moot.
4422  case UTT_IsInterfaceClass:
4423  return true;
4424 
4425  // C++14 [meta.unary.prop]:
4426  // If T is a non-union class type, T shall be a complete type.
4427  case UTT_IsEmpty:
4428  case UTT_IsPolymorphic:
4429  case UTT_IsAbstract:
4430  if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4431  if (!RD->isUnion())
4432  return !S.RequireCompleteType(
4433  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4434  return true;
4435 
4436  // C++14 [meta.unary.prop]:
4437  // If T is a class type, T shall be a complete type.
4438  case UTT_IsFinal:
4439  case UTT_IsSealed:
4440  if (ArgTy->getAsCXXRecordDecl())
4441  return !S.RequireCompleteType(
4442  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4443  return true;
4444 
4445  // C++1z [meta.unary.prop]:
4446  // remove_all_extents_t<T> shall be a complete type or cv void.
4447  case UTT_IsAggregate:
4448  case UTT_IsTrivial:
4450  case UTT_IsStandardLayout:
4451  case UTT_IsPOD:
4452  case UTT_IsLiteral:
4453  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4454  // or an array of unknown bound. But GCC actually imposes the same constraints
4455  // as above.
4456  case UTT_HasNothrowAssign:
4459  case UTT_HasNothrowCopy:
4460  case UTT_HasTrivialAssign:
4464  case UTT_HasTrivialCopy:
4467  ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4468  LLVM_FALLTHROUGH;
4469 
4470  // C++1z [meta.unary.prop]:
4471  // T shall be a complete type, cv void, or an array of unknown bound.
4472  case UTT_IsDestructible:
4476  if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4477  return true;
4478 
4479  return !S.RequireCompleteType(
4480  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4481  }
4482 }
4483 
4485  Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4486  bool (CXXRecordDecl::*HasTrivial)() const,
4487  bool (CXXRecordDecl::*HasNonTrivial)() const,
4488  bool (CXXMethodDecl::*IsDesiredOp)() const)
4489 {
4490  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4491  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4492  return true;
4493 
4495  DeclarationNameInfo NameInfo(Name, KeyLoc);
4496  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4497  if (Self.LookupQualifiedName(Res, RD)) {
4498  bool FoundOperator = false;
4499  Res.suppressDiagnostics();
4500  for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4501  Op != OpEnd; ++Op) {
4502  if (isa<FunctionTemplateDecl>(*Op))
4503  continue;
4504 
4505  CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4506  if((Operator->*IsDesiredOp)()) {
4507  FoundOperator = true;
4508  const FunctionProtoType *CPT =
4509  Operator->getType()->getAs<FunctionProtoType>();
4510  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4511  if (!CPT || !CPT->isNothrow())
4512  return false;
4513  }
4514  }
4515  return FoundOperator;
4516  }
4517  return false;
4518 }
4519 
4520 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4521  SourceLocation KeyLoc, QualType T) {
4522  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4523 
4524  ASTContext &C = Self.Context;
4525  switch(UTT) {
4526  default: llvm_unreachable("not a UTT");
4527  // Type trait expressions corresponding to the primary type category
4528  // predicates in C++0x [meta.unary.cat].
4529  case UTT_IsVoid:
4530  return T->isVoidType();
4531  case UTT_IsIntegral:
4532  return T->isIntegralType(C);
4533  case UTT_IsFloatingPoint:
4534  return T->isFloatingType();
4535  case UTT_IsArray:
4536  return T->isArrayType();
4537  case UTT_IsPointer:
4538  return T->isPointerType();
4539  case UTT_IsLvalueReference:
4540  return T->isLValueReferenceType();
4541  case UTT_IsRvalueReference:
4542  return T->isRValueReferenceType();
4544  return T->isMemberFunctionPointerType();
4546  return T->isMemberDataPointerType();
4547  case UTT_IsEnum:
4548  return T->isEnumeralType();
4549  case UTT_IsUnion:
4550  return T->isUnionType();
4551  case UTT_IsClass:
4552  return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4553  case UTT_IsFunction:
4554  return T->isFunctionType();
4555 
4556  // Type trait expressions which correspond to the convenient composition
4557  // predicates in C++0x [meta.unary.comp].
4558  case UTT_IsReference:
4559  return T->isReferenceType();
4560  case UTT_IsArithmetic:
4561  return T->isArithmeticType() && !T->isEnumeralType();
4562  case UTT_IsFundamental:
4563  return T->isFundamentalType();
4564  case UTT_IsObject:
4565  return T->isObjectType();
4566  case UTT_IsScalar:
4567  // Note: semantic analysis depends on Objective-C lifetime types to be
4568  // considered scalar types. However, such types do not actually behave
4569  // like scalar types at run time (since they may require retain/release
4570  // operations), so we report them as non-scalar.
4571  if (T->isObjCLifetimeType()) {
4572  switch (T.getObjCLifetime()) {
4573  case Qualifiers::OCL_None:
4575  return true;
4576 
4578  case Qualifiers::OCL_Weak:
4580  return false;
4581  }
4582  }
4583 
4584  return T->isScalarType();
4585  case UTT_IsCompound:
4586  return T->isCompoundType();
4587  case UTT_IsMemberPointer:
4588  return T->isMemberPointerType();
4589 
4590  // Type trait expressions which correspond to the type property predicates
4591  // in C++0x [meta.unary.prop].
4592  case UTT_IsConst:
4593  return T.isConstQualified();
4594  case UTT_IsVolatile:
4595  return T.isVolatileQualified();
4596  case UTT_IsTrivial:
4597  return T.isTrivialType(C);
4599  return T.isTriviallyCopyableType(C);
4600  case UTT_IsStandardLayout:
4601  return T->isStandardLayoutType();
4602  case UTT_IsPOD:
4603  return T.isPODType(C);
4604  case UTT_IsLiteral:
4605  return T->isLiteralType(C);
4606  case UTT_IsEmpty:
4607  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4608  return !RD->isUnion() && RD->isEmpty();
4609  return false;
4610  case UTT_IsPolymorphic:
4611  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4612  return !RD->isUnion() && RD->isPolymorphic();
4613  return false;
4614  case UTT_IsAbstract:
4615  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4616  return !RD->isUnion() && RD->isAbstract();
4617  return false;
4618  case UTT_IsAggregate:
4619  // Report vector extensions and complex types as aggregates because they
4620  // support aggregate initialization. GCC mirrors this behavior for vectors
4621  // but not _Complex.
4622  return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4623  T->isAnyComplexType();
4624  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4625  // even then only when it is used with the 'interface struct ...' syntax
4626  // Clang doesn't support /CLR which makes this type trait moot.
4627  case UTT_IsInterfaceClass:
4628  return false;
4629  case UTT_IsFinal:
4630  case UTT_IsSealed:
4631  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4632  return RD->hasAttr<FinalAttr>();
4633  return false;
4634  case UTT_IsSigned:
4635  // Enum types should always return false.
4636  // Floating points should always return true.
4637  return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
4638  case UTT_IsUnsigned:
4639  return T->isUnsignedIntegerType();
4640 
4641  // Type trait expressions which query classes regarding their construction,
4642  // destruction, and copying. Rather than being based directly on the
4643  // related type predicates in the standard, they are specified by both
4644  // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4645  // specifications.
4646  //
4647  // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4648  // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4649  //
4650  // Note that these builtins do not behave as documented in g++: if a class
4651  // has both a trivial and a non-trivial special member of a particular kind,
4652  // they return false! For now, we emulate this behavior.
4653  // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4654  // does not correctly compute triviality in the presence of multiple special
4655  // members of the same kind. Revisit this once the g++ bug is fixed.
4657  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4658  // If __is_pod (type) is true then the trait is true, else if type is
4659  // a cv class or union type (or array thereof) with a trivial default
4660  // constructor ([class.ctor]) then the trait is true, else it is false.
4661  if (T.isPODType(C))
4662  return true;
4663  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4664  return RD->hasTrivialDefaultConstructor() &&
4665  !RD->hasNonTrivialDefaultConstructor();
4666  return false;
4668  // This trait is implemented by MSVC 2012 and needed to parse the
4669  // standard library headers. Specifically this is used as the logic
4670  // behind std::is_trivially_move_constructible (20.9.4.3).
4671  if (T.isPODType(C))
4672  return true;
4673  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4674  return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4675  return false;
4676  case UTT_HasTrivialCopy:
4677  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4678  // If __is_pod (type) is true or type is a reference type then
4679  // the trait is true, else if type is a cv class or union type
4680  // with a trivial copy constructor ([class.copy]) then the trait
4681  // is true, else it is false.
4682  if (T.isPODType(C) || T->isReferenceType())
4683  return true;
4684  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4685  return RD->hasTrivialCopyConstructor() &&
4686  !RD->hasNonTrivialCopyConstructor();
4687  return false;
4689  // This trait is implemented by MSVC 2012 and needed to parse the
4690  // standard library headers. Specifically it is used as the logic
4691  // behind std::is_trivially_move_assignable (20.9.4.3)
4692  if (T.isPODType(C))
4693  return true;
4694  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4695  return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4696  return false;
4697  case UTT_HasTrivialAssign:
4698  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4699  // If type is const qualified or is a reference type then the
4700  // trait is false. Otherwise if __is_pod (type) is true then the
4701  // trait is true, else if type is a cv class or union type with
4702  // a trivial copy assignment ([class.copy]) then the trait is
4703  // true, else it is false.
4704  // Note: the const and reference restrictions are interesting,
4705  // given that const and reference members don't prevent a class
4706  // from having a trivial copy assignment operator (but do cause
4707  // errors if the copy assignment operator is actually used, q.v.
4708  // [class.copy]p12).
4709 
4710  if (T.isConstQualified())
4711  return false;
4712  if (T.isPODType(C))
4713  return true;
4714  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4715  return RD->hasTrivialCopyAssignment() &&
4716  !RD->hasNonTrivialCopyAssignment();
4717  return false;
4718  case UTT_IsDestructible:
4721  // C++14 [meta.unary.prop]:
4722  // For reference types, is_destructible<T>::value is true.
4723  if (T->isReferenceType())
4724  return true;
4725 
4726  // Objective-C++ ARC: autorelease types don't require destruction.
4727  if (T->isObjCLifetimeType() &&
4729  return true;
4730 
4731  // C++14 [meta.unary.prop]:
4732  // For incomplete types and function types, is_destructible<T>::value is
4733  // false.
4734  if (T->isIncompleteType() || T->isFunctionType())
4735  return false;
4736 
4737  // A type that requires destruction (via a non-trivial destructor or ARC
4738  // lifetime semantics) is not trivially-destructible.
4740  return false;
4741 
4742  // C++14 [meta.unary.prop]:
4743  // For object types and given U equal to remove_all_extents_t<T>, if the
4744  // expression std::declval<U&>().~U() is well-formed when treated as an
4745  // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4746  if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4747  CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4748  if (!Destructor)
4749  return false;
4750  // C++14 [dcl.fct.def.delete]p2:
4751  // A program that refers to a deleted function implicitly or
4752  // explicitly, other than to declare it, is ill-formed.
4753  if (Destructor->isDeleted())
4754  return false;
4755  if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4756  return false;
4757  if (UTT == UTT_IsNothrowDestructible) {
4758  const FunctionProtoType *CPT =
4759  Destructor->getType()->getAs<FunctionProtoType>();
4760  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4761  if (!CPT || !CPT->isNothrow())
4762  return false;
4763  }
4764  }
4765  return true;
4766 
4768  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4769  // If __is_pod (type) is true or type is a reference type
4770  // then the trait is true, else if type is a cv class or union
4771  // type (or array thereof) with a trivial destructor
4772  // ([class.dtor]) then the trait is true, else it is
4773  // false.
4774  if (T.isPODType(C) || T->isReferenceType())
4775  return true;
4776 
4777  // Objective-C++ ARC: autorelease types don't require destruction.
4778  if (T->isObjCLifetimeType() &&
4780  return true;
4781 
4782  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4783  return RD->hasTrivialDestructor();
4784  return false;
4785  // TODO: Propagate nothrowness for implicitly declared special members.
4786  case UTT_HasNothrowAssign:
4787  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4788  // If type is const qualified or is a reference type then the
4789  // trait is false. Otherwise if __has_trivial_assign (type)
4790  // is true then the trait is true, else if type is a cv class
4791  // or union type with copy assignment operators that are known
4792  // not to throw an exception then the trait is true, else it is
4793  // false.
4794  if (C.getBaseElementType(T).isConstQualified())
4795  return false;
4796  if (T->isReferenceType())
4797  return false;
4798  if (T.isPODType(C) || T->isObjCLifetimeType())
4799  return true;
4800 
4801  if (const RecordType *RT = T->getAs<RecordType>())
4802  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4806  return false;
4808  // This trait is implemented by MSVC 2012 and needed to parse the
4809  // standard library headers. Specifically this is used as the logic
4810  // behind std::is_nothrow_move_assignable (20.9.4.3).
4811  if (T.isPODType(C))
4812  return true;
4813 
4814  if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4815  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4819  return false;
4820  case UTT_HasNothrowCopy:
4821  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4822  // If __has_trivial_copy (type) is true then the trait is true, else
4823  // if type is a cv class or union type with copy constructors that are
4824  // known not to throw an exception then the trait is true, else it is
4825  // false.
4826  if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4827  return true;
4828  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4829  if (RD->hasTrivialCopyConstructor() &&
4830  !RD->hasNonTrivialCopyConstructor())
4831  return true;
4832 
4833  bool FoundConstructor = false;
4834  unsigned FoundTQs;
4835  for (const auto *ND : Self.LookupConstructors(RD)) {
4836  // A template constructor is never a copy constructor.
4837  // FIXME: However, it may actually be selected at the actual overload
4838  // resolution point.
4839  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4840  continue;
4841  // UsingDecl itself is not a constructor
4842  if (isa<UsingDecl>(ND))
4843  continue;
4844  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4845  if (Constructor->isCopyConstructor(FoundTQs)) {
4846  FoundConstructor = true;
4847  const FunctionProtoType *CPT
4848  = Constructor->getType()->getAs<FunctionProtoType>();
4849  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4850  if (!CPT)
4851  return false;
4852  // TODO: check whether evaluating default arguments can throw.
4853  // For now, we'll be conservative and assume that they can throw.
4854  if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4855  return false;
4856  }
4857  }
4858 
4859  return FoundConstructor;
4860  }
4861  return false;
4863  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4864  // If __has_trivial_constructor (type) is true then the trait is
4865  // true, else if type is a cv class or union type (or array
4866  // thereof) with a default constructor that is known not to
4867  // throw an exception then the trait is true, else it is false.
4868  if (T.isPODType(C) || T->isObjCLifetimeType())
4869  return true;
4870  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4871  if (RD->hasTrivialDefaultConstructor() &&
4872  !RD->hasNonTrivialDefaultConstructor())
4873  return true;
4874 
4875  bool FoundConstructor = false;
4876  for (const auto *ND : Self.LookupConstructors(RD)) {
4877  // FIXME: In C++0x, a constructor template can be a default constructor.
4878  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4879  continue;
4880  // UsingDecl itself is not a constructor
4881  if (isa<UsingDecl>(ND))
4882  continue;
4883  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4884  if (Constructor->isDefaultConstructor()) {
4885  FoundConstructor = true;
4886  const FunctionProtoType *CPT
4887  = Constructor->getType()->getAs<FunctionProtoType>();
4888  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4889  if (!CPT)
4890  return false;
4891  // FIXME: check whether evaluating default arguments can throw.
4892  // For now, we'll be conservative and assume that they can throw.
4893  if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4894  return false;
4895  }
4896  }
4897  return FoundConstructor;
4898  }
4899  return false;
4901  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4902  // If type is a class type with a virtual destructor ([class.dtor])
4903  // then the trait is true, else it is false.
4904  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4905  if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4906  return Destructor->isVirtual();
4907  return false;
4908 
4909  // These type trait expressions are modeled on the specifications for the
4910  // Embarcadero C++0x type trait functions:
4911  // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4912  case UTT_IsCompleteType:
4913  // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4914  // Returns True if and only if T is a complete type at the point of the
4915  // function call.
4916  return !T->isIncompleteType();
4918  return C.hasUniqueObjectRepresentations(T);
4919  }
4920 }
4921 
4922 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4923  QualType RhsT, SourceLocation KeyLoc);
4924 
4927  SourceLocation RParenLoc) {
4928  if (Kind <= UTT_Last)
4929  return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4930 
4931  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4932  // traits to avoid duplication.
4933  if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4934  return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4935  Args[1]->getType(), RParenLoc);
4936 
4937  switch (Kind) {
4942  // C++11 [meta.unary.prop]:
4943  // is_trivially_constructible is defined as:
4944  //
4945  // is_constructible<T, Args...>::value is true and the variable
4946  // definition for is_constructible, as defined below, is known to call
4947  // no operation that is not trivial.
4948  //
4949  // The predicate condition for a template specialization
4950  // is_constructible<T, Args...> shall be satisfied if and only if the
4951  // following variable definition would be well-formed for some invented
4952  // variable t:
4953  //
4954  // T t(create<Args>()...);
4955  assert(!Args.empty());
4956 
4957  // Precondition: T and all types in the parameter pack Args shall be
4958  // complete types, (possibly cv-qualified) void, or arrays of
4959  // unknown bound.
4960  for (const auto *TSI : Args) {
4961  QualType ArgTy = TSI->getType();
4962  if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4963  continue;
4964 
4965  if (S.RequireCompleteType(KWLoc, ArgTy,
4966  diag::err_incomplete_type_used_in_type_trait_expr))
4967  return false;
4968  }
4969 
4970  // Make sure the first argument is not incomplete nor a function type.
4971  QualType T = Args[0]->getType();
4972  if (T->isIncompleteType() || T->isFunctionType())
4973  return false;
4974 
4975  // Make sure the first argument is not an abstract type.
4976  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4977  if (RD && RD->isAbstract())
4978  return false;
4979 
4980  SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4981  SmallVector<Expr *, 2> ArgExprs;
4982  ArgExprs.reserve(Args.size() - 1);
4983  for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4984  QualType ArgTy = Args[I]->getType();
4985  if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4986  ArgTy = S.Context.getRValueReferenceType(ArgTy);
4987  OpaqueArgExprs.push_back(
4988  OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4989  ArgTy.getNonLValueExprType(S.Context),
4990  Expr::getValueKindForType(ArgTy)));
4991  }
4992  for (Expr &E : OpaqueArgExprs)
4993  ArgExprs.push_back(&E);
4994 
4995  // Perform the initialization in an unevaluated context within a SFINAE
4996  // trap at translation unit scope.
4999  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5003  RParenLoc));
5004  InitializationSequence Init(S, To, InitKind, ArgExprs);
5005  if (Init.Failed())
5006  return false;
5007 
5008  ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5009  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5010  return false;
5011 
5012  if (Kind == clang::TT_IsConstructible)
5013  return true;
5014 
5016  if (!T->isReferenceType())
5017  return false;
5018 
5019  return !Init.isDirectReferenceBinding();
5020  }
5021 
5023  return S.canThrow(Result.get()) == CT_Cannot;
5024 
5025  if (Kind == clang::TT_IsTriviallyConstructible) {
5026  // Under Objective-C ARC and Weak, if the destination has non-trivial
5027  // Objective-C lifetime, this is a non-trivial construction.
5029  return false;
5030 
5031  // The initialization succeeded; now make sure there are no non-trivial
5032  // calls.
5033  return !Result.get()->hasNonTrivialCall(S.Context);
5034  }
5035 
5036  llvm_unreachable("unhandled type trait");
5037  return false;
5038  }
5039  default: llvm_unreachable("not a TT");
5040  }
5041 
5042  return false;
5043 }
5044 
5047  SourceLocation RParenLoc) {
5048  QualType ResultType = Context.getLogicalOperationType();
5049 
5051  *this, Kind, KWLoc, Args[0]->getType()))
5052  return ExprError();
5053 
5054  bool Dependent = false;
5055  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5056  if (Args[I]->getType()->isDependentType()) {
5057  Dependent = true;
5058  break;
5059  }
5060  }
5061 
5062  bool Result = false;
5063  if (!Dependent)
5064  Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5065 
5066  return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5067  RParenLoc, Result);
5068 }
5069 
5071  ArrayRef<ParsedType> Args,
5072  SourceLocation RParenLoc) {
5073  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5074  ConvertedArgs.reserve(Args.size());
5075 
5076  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5077  TypeSourceInfo *TInfo;
5078  QualType T = GetTypeFromParser(Args[I], &TInfo);
5079  if (!TInfo)
5080  TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5081 
5082  ConvertedArgs.push_back(TInfo);
5083  }
5084 
5085  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5086 }
5087 
5088 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5089  QualType RhsT, SourceLocation KeyLoc) {
5090  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5091  "Cannot evaluate traits of dependent types");
5092 
5093  switch(BTT) {
5094  case BTT_IsBaseOf: {
5095  // C++0x [meta.rel]p2
5096  // Base is a base class of Derived without regard to cv-qualifiers or
5097  // Base and Derived are not unions and name the same class type without
5098  // regard to cv-qualifiers.
5099 
5100  const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5101  const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5102  if (!rhsRecord || !lhsRecord) {
5103  const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5104  const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5105  if (!LHSObjTy || !RHSObjTy)
5106  return false;
5107 
5108  ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5109  ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5110  if (!BaseInterface || !DerivedInterface)
5111  return false;
5112 
5113  if (Self.RequireCompleteType(
5114  KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5115  return false;
5116 
5117  return BaseInterface->isSuperClassOf(DerivedInterface);
5118  }
5119 
5120  assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5121  == (lhsRecord == rhsRecord));
5122 
5123  // Unions are never base classes, and never have base classes.
5124  // It doesn't matter if they are complete or not. See PR#41843
5125  if (lhsRecord && lhsRecord->getDecl()->isUnion())
5126  return false;
5127  if (rhsRecord && rhsRecord->getDecl()->isUnion())
5128  return false;
5129 
5130  if (lhsRecord == rhsRecord)
5131  return true;
5132 
5133  // C++0x [meta.rel]p2:
5134  // If Base and Derived are class types and are different types
5135  // (ignoring possible cv-qualifiers) then Derived shall be a
5136  // complete type.
5137  if (Self.RequireCompleteType(KeyLoc, RhsT,
5138  diag::err_incomplete_type_used_in_type_trait_expr))
5139  return false;
5140 
5141  return cast<CXXRecordDecl>(rhsRecord->getDecl())
5142  ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5143  }
5144  case BTT_IsSame:
5145  return Self.Context.hasSameType(LhsT, RhsT);
5146  case BTT_TypeCompatible: {
5147  // GCC ignores cv-qualifiers on arrays for this builtin.
5148  Qualifiers LhsQuals, RhsQuals;
5149  QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5150  QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5151  return Self.Context.typesAreCompatible(Lhs, Rhs);
5152  }
5153  case BTT_IsConvertible:
5154  case BTT_IsConvertibleTo: {
5155  // C++0x [meta.rel]p4:
5156  // Given the following function prototype:
5157  //
5158  // template <class T>
5159  // typename add_rvalue_reference<T>::type create();
5160  //
5161  // the predicate condition for a template specialization
5162  // is_convertible<From, To> shall be satisfied if and only if
5163  // the return expression in the following code would be
5164  // well-formed, including any implicit conversions to the return
5165  // type of the function:
5166  //
5167  // To test() {
5168  // return create<From>();
5169  // }
5170  //
5171  // Access checking is performed as if in a context unrelated to To and
5172  // From. Only the validity of the immediate context of the expression
5173  // of the return-statement (including conversions to the return type)
5174  // is considered.
5175  //
5176  // We model the initialization as a copy-initialization of a temporary
5177  // of the appropriate type, which for this expression is identical to the
5178  // return statement (since NRVO doesn't apply).
5179 
5180  // Functions aren't allowed to return function or array types.
5181  if (RhsT->isFunctionType() || RhsT->isArrayType())
5182  return false;
5183 
5184  // A return statement in a void function must have void type.
5185  if (RhsT->isVoidType())
5186  return LhsT->isVoidType();
5187 
5188  // A function definition requires a complete, non-abstract return type.
5189  if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5190  return false;
5191 
5192  // Compute the result of add_rvalue_reference.
5193  if (LhsT->isObjectType() || LhsT->isFunctionType())
5194  LhsT = Self.Context.getRValueReferenceType(LhsT);
5195 
5196  // Build a fake source and destination for initialization.
5198  OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5200  Expr *FromPtr = &From;
5202  SourceLocation()));
5203 
5204  // Perform the initialization in an unevaluated context within a SFINAE
5205  // trap at translation unit scope.
5208  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5209  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5210  InitializationSequence Init(Self, To, Kind, FromPtr);
5211  if (Init.Failed())
5212  return false;
5213 
5214  ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5215  return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5216  }
5217 
5218  case BTT_IsAssignable:
5221  // C++11 [meta.unary.prop]p3:
5222  // is_trivially_assignable is defined as:
5223  // is_assignable<T, U>::value is true and the assignment, as defined by
5224  // is_assignable, is known to call no operation that is not trivial
5225  //
5226  // is_assignable is defined as:
5227  // The expression declval<T>() = declval<U>() is well-formed when
5228  // treated as an unevaluated operand (Clause 5).
5229  //
5230  // For both, T and U shall be complete types, (possibly cv-qualified)
5231  // void, or arrays of unknown bound.
5232  if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5233  Self.RequireCompleteType(KeyLoc, LhsT,
5234  diag::err_incomplete_type_used_in_type_trait_expr))
5235  return false;
5236  if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5237  Self.RequireCompleteType(KeyLoc, RhsT,
5238  diag::err_incomplete_type_used_in_type_trait_expr))
5239  return false;
5240 
5241  // cv void is never assignable.
5242  if (LhsT->isVoidType() || RhsT->isVoidType())
5243  return false;
5244 
5245  // Build expressions that emulate the effect of declval<T>() and
5246  // declval<U>().
5247  if (LhsT->isObjectType() || LhsT->isFunctionType())
5248  LhsT = Self.Context.getRValueReferenceType(LhsT);
5249  if (RhsT->isObjectType() || RhsT->isFunctionType())
5250  RhsT = Self.Context.getRValueReferenceType(RhsT);
5251  OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5253  OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5255 
5256  // Attempt the assignment in an unevaluated context within a SFINAE
5257  // trap at translation unit scope.
5260  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5261  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5262  ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5263  &Rhs);
5264  if (Result.isInvalid())
5265  return false;
5266 
5267  // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5268  Self.CheckUnusedVolatileAssignment(Result.get());
5269 
5270  if (SFINAE.hasErrorOccurred())
5271  return false;
5272 
5273  if (BTT == BTT_IsAssignable)
5274  return true;
5275 
5276  if (BTT == BTT_IsNothrowAssignable)
5277  return Self.canThrow(Result.get()) == CT_Cannot;
5278 
5279  if (BTT == BTT_IsTriviallyAssignable) {
5280  // Under Objective-C ARC and Weak, if the destination has non-trivial
5281  // Objective-C lifetime, this is a non-trivial assignment.
5283  return false;
5284 
5285  return !Result.get()->hasNonTrivialCall(Self.Context);
5286  }
5287 
5288  llvm_unreachable("unhandled type trait");
5289  return false;
5290  }
5291  default: llvm_unreachable("not a BTT");
5292  }
5293  llvm_unreachable("Unknown type trait or not implemented");
5294 }
5295 
5297  SourceLocation KWLoc,
5298  ParsedType Ty,
5299  Expr* DimExpr,
5300  SourceLocation RParen) {
5301  TypeSourceInfo *TSInfo;
5302  QualType T = GetTypeFromParser(Ty, &TSInfo);
5303  if (!TSInfo)
5304  TSInfo = Context.getTrivialTypeSourceInfo(T);
5305 
5306  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5307 }
5308 
5309 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5310  QualType T, Expr *DimExpr,
5311  SourceLocation KeyLoc) {
5312  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5313 
5314  switch(ATT) {
5315  case ATT_ArrayRank:
5316  if (T->isArrayType()) {
5317  unsigned Dim = 0;
5318  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5319  ++Dim;
5320  T = AT->getElementType();
5321  }
5322  return Dim;
5323  }
5324  return 0;
5325 
5326  case ATT_ArrayExtent: {
5328  uint64_t Dim;
5329  if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5330  diag::err_dimension_expr_not_constant_integer,
5331  false).isInvalid())
5332  return 0;
5333  if (Value.isSigned() && Value.isNegative()) {
5334  Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5335  << DimExpr->getSourceRange();
5336  return 0;
5337  }
5338  Dim = Value.getLimitedValue();
5339 
5340  if (T->isArrayType()) {
5341  unsigned D = 0;
5342  bool Matched = false;
5343  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5344  if (Dim == D) {
5345  Matched = true;
5346  break;
5347  }
5348  ++D;
5349  T = AT->getElementType();
5350  }
5351 
5352  if (Matched && T->isArrayType()) {
5353  if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5354  return CAT->getSize().getLimitedValue();
5355  }
5356  }
5357  return 0;
5358  }
5359  }
5360  llvm_unreachable("Unknown type trait or not implemented");
5361 }
5362 
5364  SourceLocation KWLoc,
5365  TypeSourceInfo *TSInfo,
5366  Expr* DimExpr,
5367  SourceLocation RParen) {
5368  QualType T = TSInfo->getType();
5369 
5370  // FIXME: This should likely be tracked as an APInt to remove any host
5371  // assumptions about the width of size_t on the target.
5372  uint64_t Value = 0;
5373  if (!T->isDependentType())
5374  Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5375 
5376  // While the specification for these traits from the Embarcadero C++
5377  // compiler's documentation says the return type is 'unsigned int', Clang
5378  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5379  // compiler, there is no difference. On several other platforms this is an
5380  // important distinction.
5381  return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5382  RParen, Context.getSizeType());
5383 }
5384 
5386  SourceLocation KWLoc,
5387  Expr *Queried,
5388  SourceLocation RParen) {
5389  // If error parsing the expression, ignore.
5390  if (!Queried)
5391  return ExprError();
5392 
5393  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5394 
5395  return Result;
5396 }
5397 
5399  switch (ET) {
5400  case ET_IsLValueExpr: return E->isLValue();
5401  case ET_IsRValueExpr: return E->isRValue();
5402  }
5403  llvm_unreachable("Expression trait not covered by switch");
5404 }
5405 
5407  SourceLocation KWLoc,
5408  Expr *Queried,
5409  SourceLocation RParen) {
5410  if (Queried->isTypeDependent()) {
5411  // Delay type-checking for type-dependent expressions.
5412  } else if (Queried->getType()->isPlaceholderType()) {
5413  ExprResult PE = CheckPlaceholderExpr(Queried);
5414  if (PE.isInvalid()) return ExprError();
5415  return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5416  }
5417 
5418  bool Value = EvaluateExpressionTrait(ET, Queried);
5419 
5420  return new (Context)
5421  ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5422 }
5423 
5425  ExprValueKind &VK,
5426  SourceLocation Loc,
5427  bool isIndirect) {
5428  assert(!LHS.get()->getType()->isPlaceholderType() &&
5429  !RHS.get()->getType()->isPlaceholderType() &&
5430  "placeholders should have been weeded out by now");
5431 
5432  // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5433  // temporary materialization conversion otherwise.
5434  if (isIndirect)
5435  LHS = DefaultLvalueConversion(LHS.get());
5436  else if (LHS.get()->isRValue())
5438  if (LHS.isInvalid())
5439  return QualType();
5440 
5441  // The RHS always undergoes lvalue conversions.
5442  RHS = DefaultLvalueConversion(RHS.get());
5443  if (RHS.isInvalid()) return QualType();
5444 
5445  const char *OpSpelling = isIndirect ? "->*" : ".*";
5446  // C++ 5.5p2
5447  // The binary operator .* [p3: ->*] binds its second operand, which shall
5448  // be of type "pointer to member of T" (where T is a completely-defined
5449  // class type) [...]
5450  QualType RHSType = RHS.get()->getType();
5451  const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5452  if (!MemPtr) {
5453  Diag(Loc, diag::err_bad_memptr_rhs)
5454  << OpSpelling << RHSType << RHS.get()->getSourceRange();
5455  return QualType();
5456  }
5457 
5458  QualType Class(MemPtr->getClass(), 0);
5459 
5460  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5461  // member pointer points must be completely-defined. However, there is no
5462  // reason for this semantic distinction, and the rule is not enforced by
5463  // other compilers. Therefore, we do not check this property, as it is
5464  // likely to be considered a defect.
5465 
5466  // C++ 5.5p2
5467  // [...] to its first operand, which shall be of class T or of a class of
5468  // which T is an unambiguous and accessible base class. [p3: a pointer to
5469  // such a class]
5470  QualType LHSType = LHS.get()->getType();
5471  if (isIndirect) {
5472  if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5473  LHSType = Ptr->getPointeeType();
5474  else {
5475  Diag(Loc, diag::err_bad_memptr_lhs)
5476  << OpSpelling << 1 << LHSType
5478  return QualType();
5479  }
5480  }
5481 
5482  if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5483  // If we want to check the hierarchy, we need a complete type.
5484  if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5485  OpSpelling, (int)isIndirect)) {
5486  return QualType();
5487  }
5488 
5489  if (!IsDerivedFrom(Loc, LHSType, Class)) {
5490  Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5491  << (int)isIndirect << LHS.get()->getType();
5492  return QualType();
5493  }
5494 
5495  CXXCastPath BasePath;
5497  LHSType, Class, Loc,
5498  SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5499  &BasePath))
5500  return QualType();
5501 
5502  // Cast LHS to type of use.
5503  QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5504  if (isIndirect)
5505  UseType = Context.getPointerType(UseType);
5506  ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5507  LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5508  &BasePath);
5509  }
5510 
5511  if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5512  // Diagnose use of pointer-to-member type which when used as
5513  // the functional cast in a pointer-to-member expression.
5514  Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5515  return QualType();
5516  }
5517 
5518  // C++ 5.5p2
5519  // The result is an object or a function of the type specified by the
5520  // second operand.
5521  // The cv qualifiers are the union of those in the pointer and the left side,
5522  // in accordance with 5.5p5 and 5.2.5.
5523  QualType Result = MemPtr->getPointeeType();
5524  Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5525 
5526  // C++0x [expr.mptr.oper]p6:
5527  // In a .* expression whose object expression is an rvalue, the program is
5528  // ill-formed if the second operand is a pointer to member function with
5529  // ref-qualifier &. In a ->* expression or in a .* expression whose object
5530  // expression is an lvalue, the program is ill-formed if the second operand
5531  // is a pointer to member function with ref-qualifier &&.
5532  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5533  switch (Proto->getRefQualifier()) {
5534  case RQ_None:
5535  // Do nothing
5536  break;
5537 
5538  case RQ_LValue:
5539  if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5540  // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5541  // is (exactly) 'const'.
5542  if (Proto->isConst() && !Proto->isVolatile())
5543  Diag(Loc, getLangOpts().CPlusPlus2a
5544  ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5545  : diag::ext_pointer_to_const_ref_member_on_rvalue);
5546  else
5547  Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5548  << RHSType << 1 << LHS.get()->getSourceRange();
5549  }
5550  break;
5551 
5552  case RQ_RValue:
5553  if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5554  Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5555  << RHSType << 0 << LHS.get()->getSourceRange();
5556  break;
5557  }
5558  }
5559 
5560  // C++ [expr.mptr.oper]p6:
5561  // The result of a .* expression whose second operand is a pointer
5562  // to a data member is of the same value category as its
5563  // first operand. The result of a .* expression whose second
5564  // operand is a pointer to a member function is a prvalue. The
5565  // result of an ->* expression is an lvalue if its second operand
5566  // is a pointer to data member and a prvalue otherwise.
5567  if (Result->isFunctionType()) {
5568  VK = VK_RValue;
5569  return Context.BoundMemberTy;
5570  } else if (isIndirect) {
5571  VK = VK_LValue;
5572  } else {
5573  VK = LHS.get()->getValueKind();
5574  }
5575 
5576  return Result;
5577 }
5578 
5579 /// Try to convert a type to another according to C++11 5.16p3.
5580 ///
5581 /// This is part of the parameter validation for the ? operator. If either
5582 /// value operand is a class type, the two operands are attempted to be
5583 /// converted to each other. This function does the conversion in one direction.
5584 /// It returns true if the program is ill-formed and has already been diagnosed
5585 /// as such.
5586 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5587  SourceLocation QuestionLoc,
5588  bool &HaveConversion,
5589  QualType &ToType) {
5590  HaveConversion = false;
5591  ToType = To->getType();
5592 
5595  // C++11 5.16p3
5596  // The process for determining whether an operand expression E1 of type T1
5597  // can be converted to match an operand expression E2 of type T2 is defined
5598  // as follows:
5599  // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5600  // implicitly converted to type "lvalue reference to T2", subject to the
5601  // constraint that in the conversion the reference must bind directly to
5602  // an lvalue.
5603  // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5604  // implicitly converted to the type "rvalue reference to R2", subject to
5605  // the constraint that the reference must bind directly.
5606  if (To->isLValue() || To->isXValue()) {
5607  QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5608  : Self.Context.getRValueReferenceType(ToType);
5609 
5611 
5612  InitializationSequence InitSeq(Self, Entity, Kind, From);
5613  if (InitSeq.isDirectReferenceBinding()) {
5614  ToType = T;
5615  HaveConversion = true;
5616  return false;
5617  }
5618 
5619  if (InitSeq.isAmbiguous())
5620  return InitSeq.Diagnose(Self, Entity, Kind, From);
5621  }
5622 
5623  // -- If E2 is an rvalue, or if the conversion above cannot be done:
5624  // -- if E1 and E2 have class type, and the underlying class types are
5625  // the same or one is a base class of the other:
5626  QualType FTy = From->getType();
5627  QualType TTy = To->getType();
5628  const RecordType *FRec = FTy->getAs<RecordType>();
5629  const RecordType *TRec = TTy->getAs<RecordType>();
5630  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5631  Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5632  if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5633  Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5634  // E1 can be converted to match E2 if the class of T2 is the
5635  // same type as, or a base class of, the class of T1, and
5636  // [cv2 > cv1].
5637  if (FRec == TRec || FDerivedFromT) {
5638  if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5640  InitializationSequence InitSeq(Self, Entity, Kind, From);
5641  if (InitSeq) {
5642  HaveConversion = true;
5643  return false;
5644  }
5645 
5646  if (InitSeq.isAmbiguous())
5647  return InitSeq.Diagnose(Self, Entity, Kind, From);
5648  }
5649  }
5650 
5651  return false;
5652  }
5653 
5654  // -- Otherwise: E1 can be converted to match E2 if E1 can be
5655  // implicitly converted to the type that expression E2 would have
5656  // if E2 were converted to an rvalue (or the type it has, if E2 is
5657  // an rvalue).
5658  //
5659  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5660  // to the array-to-pointer or function-to-pointer conversions.
5661  TTy = TTy.getNonLValueExprType(Self.Context);
5662 
5664  InitializationSequence InitSeq(Self, Entity, Kind, From);
5665  HaveConversion = !InitSeq.Failed();
5666  ToType = TTy;
5667  if (InitSeq.isAmbiguous())
5668  return InitSeq.Diagnose(Self, Entity, Kind, From);
5669 
5670  return false;
5671 }
5672 
5673 /// Try to find a common type for two according to C++0x 5.16p5.
5674 ///
5675 /// This is part of the parameter validation for the ? operator. If either
5676 /// value operand is a class type, overload resolution is used to find a
5677 /// conversion to a common type.
5678 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5679  SourceLocation QuestionLoc) {
5680  Expr *Args[2] = { LHS.get(), RHS.get() };
5681  OverloadCandidateSet CandidateSet(QuestionLoc,
5683  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5684  CandidateSet);
5685 
5687  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5688  case OR_Success: {
5689  // We found a match. Perform the conversions on the arguments and move on.
5690  ExprResult LHSRes = Self.PerformImplicitConversion(
5691  LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5693  if (LHSRes.isInvalid())
5694  break;
5695  LHS = LHSRes;
5696 
5697  ExprResult RHSRes = Self.PerformImplicitConversion(
5698  RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5700  if (RHSRes.isInvalid())
5701  break;
5702  RHS = RHSRes;
5703  if (Best->Function)
5704  Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5705  return false;
5706  }
5707 
5708  case OR_No_Viable_Function:
5709 
5710  // Emit a better diagnostic if one of the expressions is a null pointer
5711  // constant and the other is a pointer type. In this case, the user most
5712  // likely forgot to take the address of the other expression.
5713  if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5714  return true;
5715 
5716  Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5717  << LHS.get()->getType() << RHS.get()->getType()
5718  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5719  return true;
5720 
5721  case OR_Ambiguous:
5722  Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5723  << LHS.get()->getType() << RHS.get()->getType()
5724  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5725  // FIXME: Print the possible common types by printing the return types of
5726  // the viable candidates.
5727  break;
5728 
5729  case OR_Deleted:
5730  llvm_unreachable("Conditional operator has only built-in overloads");
5731  }
5732  return true;
5733 }
5734 
5735 /// Perform an "extended" implicit conversion as returned by
5736 /// TryClassUnification.
5737 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5740  InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5741  Expr *Arg = E.get();
5742  InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5743  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5744  if (Result.isInvalid())
5745  return true;
5746 
5747  E = Result;
5748  return false;
5749 }
5750 
5751 // Check the condition operand of ?: to see if it is valid for the GCC
5752 // extension.
5754  QualType CondTy) {
5755  if (!CondTy->isVectorType() || CondTy->isExtVectorType())
5756  return false;
5757  const QualType EltTy =
5758  cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5759 
5760  assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
5761  "Vectors cant be boolean or enum types");
5762  return EltTy->isIntegralType(Ctx);
5763 }
5764 
5766  ExprResult &RHS,
5767  SourceLocation QuestionLoc) {
5769  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5770 
5771  QualType CondType = Cond.get()->getType();
5772  const auto *CondVT = CondType->getAs<VectorType>();
5773  QualType CondElementTy = CondVT->getElementType();
5774  unsigned CondElementCount = CondVT->getNumElements();
5775  QualType LHSType = LHS.get()->getType();
5776  const auto *LHSVT = LHSType->getAs<VectorType>();
5777  QualType RHSType = RHS.get()->getType();
5778  const auto *RHSVT = RHSType->getAs<VectorType>();
5779 
5780  QualType ResultType;
5781 
5782  // FIXME: In the future we should define what the Extvector conditional
5783  // operator looks like.
5784  if (LHSVT && isa<ExtVectorType>(LHSVT)) {
5785  Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5786  << /*isExtVector*/ true << LHSType;
5787  return {};
5788  }
5789 
5790  if (RHSVT && isa<ExtVectorType>(RHSVT)) {
5791  Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5792  << /*isExtVector*/ true << RHSType;
5793  return {};
5794  }
5795 
5796  if (LHSVT && RHSVT) {
5797  // If both are vector types, they must be the same type.
5798  if (!Context.hasSameType(LHSType, RHSType)) {
5799  Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors)
5800  << LHSType << RHSType;
5801  return {};
5802  }
5803  ResultType = LHSType;
5804  } else if (LHSVT || RHSVT) {
5805  ResultType = CheckVectorOperands(
5806  LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5807  /*AllowBoolConversions*/ false);
5808  if (ResultType.isNull())
5809  return {};
5810  } else {
5811  // Both are scalar.
5812  QualType ResultElementTy;
5813  LHSType = LHSType.getCanonicalType().getUnqualifiedType();
5814  RHSType = RHSType.getCanonicalType().getUnqualifiedType();
5815 
5816  if (Context.hasSameType(LHSType, RHSType))
5817  ResultElementTy = LHSType;
5818  else
5819  ResultElementTy =
5820  UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
5821 
5822  if (ResultElementTy->isEnumeralType()) {
5823  Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5824  << /*isExtVector*/ false << ResultElementTy;
5825  return {};
5826  }
5827  ResultType = Context.getVectorType(
5828  ResultElementTy, CondType->getAs<VectorType>()->getNumElements(),
5830 
5831  LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5832  RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5833  }
5834 
5835  assert(!ResultType.isNull() && ResultType->isVectorType() &&
5836  "Result should have been a vector type");
5837  QualType ResultElementTy = ResultType->getAs<VectorType>()->getElementType();
5838  unsigned ResultElementCount =
5839  ResultType->getAs<VectorType>()->getNumElements();
5840 
5841  if (ResultElementCount != CondElementCount) {
5842  Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5843  << ResultType;
5844  return {};
5845  }
5846 
5847  if (Context.getTypeSize(ResultElementTy) !=
5848  Context.getTypeSize(CondElementTy)) {
5849  Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
5850  << ResultType;
5851  return {};
5852  }
5853 
5854  return ResultType;
5855 }
5856 
5857 /// Check the operands of ?: under C++ semantics.
5858 ///
5859 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5860 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5861 ///
5862 /// This function also implements GCC's vector extension for conditionals.
5863 /// GCC's vector extension permits the use of a?b:c where the type of
5864 /// a is that of a integer vector with the same number of elements and
5865 /// size as the vectors of b and c. If one of either b or c is a scalar
5866 /// it is implicitly converted to match the type of the vector.
5867 /// Otherwise the expression is ill-formed. If both b and c are scalars,
5868 /// then b and c are checked and converted to the type of a if possible.
5869 /// Unlike the OpenCL ?: operator, the expression is evaluated as
5870 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5872  ExprResult &RHS, ExprValueKind &VK,
5873  ExprObjectKind &OK,
5874  SourceLocation QuestionLoc) {
5875  // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5876  // pointers.
5877 
5878  // Assume r-value.
5879  VK = VK_RValue;
5880  OK = OK_Ordinary;
5881  bool IsVectorConditional =
5882  isValidVectorForConditionalCondition(Context, Cond.get()->getType());
5883 
5884  // C++11 [expr.cond]p1
5885  // The first expression is contextually converted to bool.
5886  if (!Cond.get()->isTypeDependent()) {
5887  ExprResult CondRes = IsVectorConditional
5889  : CheckCXXBooleanCondition(Cond.get());
5890  if (CondRes.isInvalid())
5891  return QualType();
5892  Cond = CondRes;
5893  } else {
5894  // To implement C++, the first expression typically doesn't alter the result
5895  // type of the conditional, however the GCC compatible vector extension
5896  // changes the result type to be that of the conditional. Since we cannot
5897  // know if this is a vector extension here, delay the conversion of the
5898  // LHS/RHS below until later.
5899  return Context.DependentTy;
5900  }
5901 
5902 
5903  // Either of the arguments dependent?
5904  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5905  return Context.DependentTy;
5906 
5907  // C++11 [expr.cond]p2
5908  // If either the second or the third operand has type (cv) void, ...
5909  QualType LTy = LHS.get()->getType();
5910  QualType RTy = RHS.get()->getType();
5911  bool LVoid = LTy->isVoidType();
5912  bool RVoid = RTy->isVoidType();
5913  if (LVoid || RVoid) {
5914  // ... one of the following shall hold:
5915  // -- The second or the third operand (but not both) is a (possibly
5916  // parenthesized) throw-expression; the result is of the type
5917  // and value category of the other.
5918  bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5919  bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5920 
5921  // Void expressions aren't legal in the vector-conditional expressions.
5922  if (IsVectorConditional) {
5923  SourceRange DiagLoc =
5924  LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
5925  bool IsThrow = LVoid ? LThrow : RThrow;
5926  Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
5927  << DiagLoc << IsThrow;
5928  return QualType();
5929  }
5930 
5931  if (LThrow != RThrow) {
5932  Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5933  VK = NonThrow->getValueKind();
5934  // DR (no number yet): the result is a bit-field if the
5935  // non-throw-expression operand is a bit-field.
5936  OK = NonThrow->getObjectKind();
5937  return NonThrow->getType();
5938  }
5939 
5940  // -- Both the second and third operands have type void; the result is of
5941  // type void and is a prvalue.
5942  if (LVoid && RVoid)
5943  return Context.VoidTy;
5944 
5945  // Neither holds, error.
5946  Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5947  << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5948  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5949  return QualType();
5950  }
5951 
5952  // Neither is void.
5953  if (IsVectorConditional)
5954  return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
5955 
5956  // C++11 [expr.cond]p3
5957  // Otherwise, if the second and third operand have different types, and
5958  // either has (cv) class type [...] an attempt is made to convert each of
5959  // those operands to the type of the other.
5960  if (!Context.hasSameType(LTy, RTy) &&
5961  (LTy->isRecordType() || RTy->isRecordType())) {
5962  // These return true if a single direction is already ambiguous.
5963  QualType L2RType, R2LType;
5964  bool HaveL2R, HaveR2L;
5965  if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5966  return QualType();
5967  if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5968  return QualType();
5969 
5970  // If both can be converted, [...] the program is ill-formed.
5971  if (HaveL2R && HaveR2L) {
5972  Diag(QuestionLoc, diag::err_conditional_ambiguous)
5973  << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5974  return QualType();
5975  }
5976 
5977  // If exactly one conversion is possible, that conversion is applied to
5978  // the chosen operand and the converted operands are used in place of the
5979  // original operands for the remainder of this section.
5980  if (HaveL2R) {
5981  if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5982  return QualType();
5983  LTy = LHS.get()->getType();
5984  } else if (HaveR2L) {
5985  if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5986  return QualType();
5987  RTy = RHS.get()->getType();
5988  }
5989  }
5990 
5991  // C++11 [expr.cond]p3
5992  // if both are glvalues of the same value category and the same type except
5993  // for cv-qualification, an attempt is made to convert each of those
5994  // operands to the type of the other.
5995  // FIXME:
5996  // Resolving a defect in P0012R1: we extend this to cover all cases where
5997  // one of the operands is reference-compatible with the other, in order
5998  // to support conditionals between functions differing in noexcept. This
5999  // will similarly cover difference in array bounds after P0388R4.
6000  // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6001  // that instead?
6002  ExprValueKind LVK = LHS.get()->getValueKind();
6003  ExprValueKind RVK = RHS.get()->getValueKind();
6004  if (!Context.hasSameType(LTy, RTy) &&
6005  LVK == RVK && LVK != VK_RValue) {
6006  // DerivedToBase was already handled by the class-specific case above.
6007  // FIXME: Should we allow ObjC conversions here?
6008  const ReferenceConversions AllowedConversions =
6009  ReferenceConversions::Qualification |
6010  ReferenceConversions::NestedQualification |
6012 
6013  ReferenceConversions RefConv;
6014  if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6015  Ref_Compatible &&
6016  !(RefConv & ~AllowedConversions) &&
6017  // [...] subject to the constraint that the reference must bind
6018  // directly [...]
6019  !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6020  RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6021  RTy = RHS.get()->getType();
6022  } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6023  Ref_Compatible &&
6024  !(RefConv & ~AllowedConversions) &&
6025  !LHS.get()->refersToBitField() &&
6026  !LHS.get()->refersToVectorElement()) {
6027  LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6028  LTy = LHS.get()->getType();
6029  }
6030  }
6031 
6032  // C++11 [expr.cond]p4
6033  // If the second and third operands are glvalues of the same value
6034  // category and have the same type, the result is of that type and
6035  // value category and it is a bit-field if the second or the third
6036  // operand is a bit-field, or if both are bit-fields.
6037  // We only extend this to bitfields, not to the crazy other kinds of
6038  // l-values.
6039  bool Same = Context.hasSameType(LTy, RTy);
6040  if (Same && LVK == RVK && LVK != VK_RValue &&
6041  LHS.get()->isOrdinaryOrBitFieldObject() &&
6042  RHS.get()->isOrdinaryOrBitFieldObject()) {
6043  VK = LHS.get()->getValueKind();
6044  if (LHS.get()->getObjectKind() == OK_BitField ||
6045  RHS.get()->getObjectKind() == OK_BitField)
6046  OK = OK_BitField;
6047 
6048  // If we have function pointer types, unify them anyway to unify their
6049  // exception specifications, if any.
6050  if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6051  Qualifiers Qs = LTy.getQualifiers();
6052  LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
6053  /*ConvertArgs*/false);
6054  LTy = Context.getQualifiedType(LTy, Qs);
6055 
6056  assert(!LTy.isNull() && "failed to find composite pointer type for "
6057  "canonically equivalent function ptr types");
6058  assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6059  }
6060 
6061  return LTy;
6062  }
6063 
6064  // C++11 [expr.cond]p5
6065  // Otherwise, the result is a prvalue. If the second and third operands
6066  // do not have the same type, and either has (cv) class type, ...
6067  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6068  // ... overload resolution is used to determine the conversions (if any)
6069  // to be applied to the operands. If the overload resolution fails, the
6070  // program is ill-formed.
6071  if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6072  return QualType();
6073  }
6074 
6075  // C++11 [expr.cond]p6
6076  // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6077  // conversions are performed on the second and third operands.
6079  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6080  if (LHS.isInvalid() || RHS.isInvalid())
6081  return QualType();
6082  LTy = LHS.get()->getType();
6083  RTy = RHS.get()->getType();
6084 
6085  // After those conversions, one of the following shall hold:
6086  // -- The second and third operands have the same type; the result
6087  // is of that type. If the operands have class type, the result
6088  // is a prvalue temporary of the result type, which is
6089  // copy-initialized from either the second operand or the third
6090  // operand depending on the value of the first operand.
6091  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6092  if (LTy->isRecordType()) {
6093  // The operands have class type. Make a temporary copy.
6095 
6096  ExprResult LHSCopy = PerformCopyInitialization(Entity,
6097  SourceLocation(),
6098  LHS);
6099  if (LHSCopy.isInvalid())
6100  return QualType();
6101 
6102  ExprResult RHSCopy = PerformCopyInitialization(Entity,
6103  SourceLocation(),
6104  RHS);
6105  if (RHSCopy.isInvalid())
6106  return QualType();
6107 
6108  LHS = LHSCopy;
6109  RHS = RHSCopy;
6110  }
6111 
6112  // If we have function pointer types, unify them anyway to unify their
6113  // exception specifications, if any.
6114  if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6115  LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6116  assert(!LTy.isNull() && "failed to find composite pointer type for "
6117  "canonically equivalent function ptr types");
6118  }
6119 
6120  return LTy;
6121  }
6122 
6123  // Extension: conditional operator involving vector types.
6124  if (LTy->isVectorType() || RTy->isVectorType())
6125  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6126  /*AllowBothBool*/true,
6127  /*AllowBoolConversions*/false);
6128 
6129  // -- The second and third operands have arithmetic or enumeration type;
6130  // the usual arithmetic conversions are performed to bring them to a
6131  // common type, and the result is of that type.
6132  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6133  QualType ResTy =
6134  UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6135  if (LHS.isInvalid() || RHS.isInvalid())
6136  return QualType();
6137  if (ResTy.isNull()) {
6138  Diag(QuestionLoc,
6139  diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6140  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6141  return QualType();
6142  }
6143 
6144  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6145  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6146 
6147  return ResTy;
6148  }
6149 
6150  // -- The second and third operands have pointer type, or one has pointer
6151  // type and the other is a null pointer constant, or both are null
6152  // pointer constants, at least one of which is non-integral; pointer
6153  // conversions and qualification conversions are performed to bring them
6154  // to their composite pointer type. The result is of the composite
6155  // pointer type.
6156  // -- The second and third operands have pointer to member type, or one has
6157  // pointer to member type and the other is a null pointer constant;
6158  // pointer to member conversions and qualification conversions are
6159  // performed to bring them to a common type, whose cv-qualification
6160  // shall match the cv-qualification of either the second or the third
6161  // operand. The result is of the common type.
6162  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6163  if (!Composite.isNull())
6164  return Composite;
6165 
6166  // Similarly, attempt to find composite type of two objective-c pointers.
6167  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6168  if (!Composite.isNull())
6169  return Composite;
6170 
6171  // Check if we are using a null with a non-pointer type.
6172  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6173  return QualType();
6174 
6175  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6176  << LHS.get()->getType() << RHS.get()->getType()
6177  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6178  return QualType();
6179 }
6180 
6184  SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6185  ExceptionSpecificationType EST1 = ESI1.Type;
6186  ExceptionSpecificationType EST2 = ESI2.Type;
6187 
6188  // If either of them can throw anything, that is the result.
6189  if (EST1 == EST_None) return ESI1;
6190  if (EST2 == EST_None) return ESI2;
6191  if (EST1 == EST_MSAny) return ESI1;
6192  if (EST2 == EST_MSAny) return ESI2;
6193  if (EST1 == EST_NoexceptFalse) return ESI1;
6194  if (EST2 == EST_NoexceptFalse) return ESI2;
6195 
6196  // If either of them is non-throwing, the result is the other.
6197  if (EST1 == EST_NoThrow) return ESI2;
6198  if (EST2 == EST_NoThrow) return ESI1;
6199  if (EST1 == EST_DynamicNone) return ESI2;
6200  if (EST2 == EST_DynamicNone) return ESI1;
6201  if (EST1 == EST_BasicNoexcept) return ESI2;
6202  if (EST2 == EST_BasicNoexcept) return ESI1;
6203  if (EST1 == EST_NoexceptTrue) return ESI2;
6204  if (EST2 == EST_NoexceptTrue) return ESI1;
6205 
6206  // If we're left with value-dependent computed noexcept expressions, we're
6207  // stuck. Before C++17, we can just drop the exception specification entirely,
6208  // since it's not actually part of the canonical type. And this should never
6209  // happen in C++17, because it would mean we were computing the composite
6210  // pointer type of dependent types, which should never happen.
6211  if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6212  assert(!S.getLangOpts().CPlusPlus17 &&
6213  "computing composite pointer type of dependent types");
6215  }
6216 
6217  // Switch over the possibilities so that people adding new values know to
6218  // update this function.
6219  switch (EST1) {
6220  case EST_None:
6221  case EST_DynamicNone:
6222  case EST_MSAny:
6223  case EST_BasicNoexcept:
6224  case EST_DependentNoexcept:
6225  case EST_NoexceptFalse:
6226  case EST_NoexceptTrue:
6227  case EST_NoThrow:
6228  llvm_unreachable("handled above");
6229 
6230  case EST_Dynamic: {
6231  // This is the fun case: both exception specifications are dynamic. Form
6232  // the union of the two lists.
6233  assert(EST2 == EST_Dynamic && "other cases should already be handled");
6234  llvm::SmallPtrSet<QualType, 8> Found;
6235  for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6236  for (QualType E : Exceptions)
6237  if (Found.insert(S.Context.getCanonicalType(E)).second)
6238  ExceptionTypeStorage.push_back(E);
6239 
6241  Result.Exceptions = ExceptionTypeStorage;
6242  return Result;
6243  }
6244 
6245  case EST_Unevaluated:
6246  case EST_Uninstantiated:
6247  case EST_Unparsed:
6248  llvm_unreachable("shouldn't see unresolved exception specifications here");
6249  }
6250 
6251  llvm_unreachable("invalid ExceptionSpecificationType");
6252 }
6253 
6254 /// Find a merged pointer type and convert the two expressions to it.
6255 ///
6256 /// This finds the composite pointer type for \p E1 and \p E2 according to
6257 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6258 /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6259 /// is \c true).
6260 ///
6261 /// \param Loc The location of the operator requiring these two expressions to
6262 /// be converted to the composite pointer type.
6263 ///
6264 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6266  Expr *&E1, Expr *&E2,
6267  bool ConvertArgs) {
6268  assert(getLangOpts().CPlusPlus && "This function assumes C++");
6269 
6270  // C++1z [expr]p14:
6271  // The composite pointer type of two operands p1 and p2 having types T1
6272  // and T2
6273  QualType T1 = E1->getType(), T2 = E2->getType();
6274 
6275  // where at least one is a pointer or pointer to member type or
6276  // std::nullptr_t is:
6277  bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6278  T1->isNullPtrType();
6279  bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6280  T2->isNullPtrType();
6281  if (!T1IsPointerLike && !T2IsPointerLike)
6282  return QualType();
6283 
6284  // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6285  // This can't actually happen, following the standard, but we also use this
6286  // to implement the end of [expr.conv], which hits this case.
6287  //
6288  // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6289  if (T1IsPointerLike &&
6291  if (ConvertArgs)
6292  E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6293  ? CK_NullToMemberPointer
6294  : CK_NullToPointer).get();
6295  return T1;
6296  }
6297  if (T2IsPointerLike &&
6299  if (ConvertArgs)
6300  E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6301  ? CK_NullToMemberPointer
6302  : CK_NullToPointer).get();
6303  return T2;
6304  }
6305 
6306  // Now both have to be pointers or member pointers.
6307  if (!T1IsPointerLike || !T2IsPointerLike)
6308  return QualType();
6309  assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6310  "nullptr_t should be a null pointer constant");
6311 
6312  struct Step {
6313  enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6314  // Qualifiers to apply under the step kind.
6315  Qualifiers Quals;
6316  /// The class for a pointer-to-member; a constant array type with a bound
6317  /// (if any) for an array.
6318  const Type *ClassOrBound;
6319 
6320  Step(Kind K, const Type *ClassOrBound = nullptr)
6321  : K(K), Quals(), ClassOrBound(ClassOrBound) {}
6322  QualType rebuild(ASTContext &Ctx, QualType T) const {
6323  T = Ctx.getQualifiedType(T, Quals);
6324  switch (K) {
6325  case Pointer:
6326  return Ctx.getPointerType(T);
6327  case MemberPointer:
6328  return Ctx.getMemberPointerType(T, ClassOrBound);
6329  case ObjCPointer:
6330  return Ctx.getObjCObjectPointerType(T);
6331  case Array:
6332  if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6333  return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6334  ArrayType::Normal, 0);
6335  else
6336  return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6337  }
6338  llvm_unreachable("unknown step kind");
6339  }
6340  };
6341 
6342  SmallVector<Step, 8> Steps;
6343 
6344  // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6345  // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6346  // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6347  // respectively;
6348  // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6349  // to member of C2 of type cv2 U2" for some non-function type U, where
6350  // C1 is reference-related to C2 or C2 is reference-related to C1, the
6351  // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6352  // respectively;
6353  // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6354  // T2;
6355  //
6356  // Dismantle T1 and T2 to simultaneously determine whether they are similar
6357  // and to prepare to form the cv-combined type if so.
6358  QualType Composite1 = T1;
6359  QualType Composite2 = T2;
6360  unsigned NeedConstBefore = 0;
6361  while (true) {
6362  assert(!Composite1.isNull() && !Composite2.isNull());
6363 
6364  Qualifiers Q1, Q2;
6365  Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6366  Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6367 
6368  // Top-level qualifiers are ignored. Merge at all lower levels.
6369  if (!Steps.empty()) {
6370  // Find the qualifier union: (approximately) the unique minimal set of
6371  // qualifiers that is compatible with both types.
6372  Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6373  Q2.getCVRUQualifiers());
6374 
6375  // Under one level of pointer or pointer-to-member, we can change to an
6376  // unambiguous compatible address space.
6377  if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6378  Quals.setAddressSpace(Q1.getAddressSpace());
6379  } else if (Steps.size() == 1) {
6380  bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6381  bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6382  if (MaybeQ1 == MaybeQ2)
6383  return QualType(); // No unique best address space.
6384  Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6385  : Q2.getAddressSpace());
6386  } else {
6387  return QualType();
6388  }
6389 
6390  // FIXME: In C, we merge __strong and none to __strong at the top level.
6391  if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6392  Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6393  else
6394  return QualType();
6395 
6396  // Mismatched lifetime qualifiers never compatibly include each other.
6397  if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6398  Quals.setObjCLifetime(Q1.getObjCLifetime());
6399  else
6400  return QualType();
6401 
6402  Steps.back().Quals = Quals;
6403  if (Q1 != Quals || Q2 != Quals)
6404  NeedConstBefore = Steps.size() - 1;
6405  }
6406 
6407  // FIXME: Can we unify the following with UnwrapSimilarTypes?
6408  const PointerType *Ptr1, *Ptr2;
6409  if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6410  (Ptr2 = Composite2->getAs<PointerType>())) {
6411  Composite1 = Ptr1->getPointeeType();
6412  Composite2 = Ptr2->getPointeeType();
6413  Steps.emplace_back(Step::Pointer);
6414  continue;
6415  }
6416 
6417  const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6418  if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6419  (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6420  Composite1 = ObjPtr1->getPointeeType();
6421  Composite2 = ObjPtr2->getPointeeType();
6422  Steps.emplace_back(Step::ObjCPointer);
6423  continue;
6424  }
6425 
6426  const MemberPointerType *MemPtr1, *MemPtr2;
6427  if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6428  (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6429  Composite1 = MemPtr1->getPointeeType();
6430  Composite2 = MemPtr2->getPointeeType();
6431 
6432  // At the top level, we can perform a base-to-derived pointer-to-member
6433  // conversion:
6434  //
6435  // - [...] where C1 is reference-related to C2 or C2 is
6436  // reference-related to C1
6437  //
6438  // (Note that the only kinds of reference-relatedness in scope here are
6439  // "same type or derived from".) At any other level, the class must
6440  // exactly match.
6441  const Type *Class = nullptr;
6442  QualType Cls1(MemPtr1->getClass(), 0);
6443  QualType Cls2(MemPtr2->getClass(), 0);
6444  if (Context.hasSameType(Cls1, Cls2))
6445  Class = MemPtr1->getClass();
6446  else if (Steps.empty())
6447  Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6448  IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6449  if (!Class)
6450  return QualType();
6451 
6452  Steps.emplace_back(Step::MemberPointer, Class);
6453  continue;
6454  }
6455 
6456  // Special case: at the top level, we can decompose an Objective-C pointer
6457  // and a 'cv void *'. Unify the qualifiers.
6458  if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6459  Composite2->isObjCObjectPointerType()) ||
6460  (Composite1->isObjCObjectPointerType() &&
6461  Composite2->isVoidPointerType()))) {
6462  Composite1 = Composite1->getPointeeType();
6463  Composite2 = Composite2->getPointeeType();
6464  Steps.emplace_back(Step::Pointer);
6465  continue;
6466  }
6467 
6468  // FIXME: arrays
6469 
6470  // FIXME: block pointer types?
6471 
6472  // Cannot unwrap any more types.
6473  break;
6474  }
6475 
6476  // - if T1 or T2 is "pointer to noexcept function" and the other type is
6477  // "pointer to function", where the function types are otherwise the same,
6478  // "pointer to function";
6479  // - if T1 or T2 is "pointer to member of C1 of type function", the other
6480  // type is "pointer to member of C2 of type noexcept function", and C1
6481  // is reference-related to C2 or C2 is reference-related to C1, where
6482  // the function types are otherwise the same, "pointer to member of C2 of
6483  // type function" or "pointer to member of C1 of type function",
6484  // respectively;
6485  //
6486  // We also support 'noreturn' here, so as a Clang extension we generalize the
6487  // above to:
6488  //
6489  // - [Clang] If T1 and T2 are both of type "pointer to function" or
6490  // "pointer to member function" and the pointee types can be unified
6491  // by a function pointer conversion, that conversion is applied
6492  // before checking the following rules.
6493  //
6494  // We've already unwrapped down to the function types, and we want to merge
6495  // rather than just convert, so do this ourselves rather than calling
6496  // IsFunctionConversion.
6497  //
6498  // FIXME: In order to match the standard wording as closely as possible, we
6499  // currently only do this under a single level of pointers. Ideally, we would
6500  // allow this in general, and set NeedConstBefore to the relevant depth on
6501  // the side(s) where we changed anything. If we permit that, we should also
6502  // consider this conversion when determining type similarity and model it as
6503  // a qualification conversion.
6504  if (Steps.size() == 1) {
6505  if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6506  if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6507  FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6508  FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6509 
6510  // The result is noreturn if both operands are.
6511  bool Noreturn =
6512  EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6513  EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6514  EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6515 
6516  // The result is nothrow if both operands are.
6517  SmallVector<QualType, 8> ExceptionTypeStorage;
6518  EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6520  ExceptionTypeStorage);
6521 
6522  Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6523  FPT1->getParamTypes(), EPI1);
6524  Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6525  FPT2->getParamTypes(), EPI2);
6526  }
6527  }
6528  }
6529 
6530  // There are some more conversions we can perform under exactly one pointer.
6531  if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6532  !Context.hasSameType(Composite1, Composite2)) {
6533  // - if T1 or T2 is "pointer to cv1 void" and the other type is
6534  // "pointer to cv2 T", where T is an object type or void,
6535  // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6536  if (Composite1->isVoidType() && Composite2->isObjectType())
6537  Composite2 = Composite1;
6538  else if (Composite2->isVoidType() && Composite1->isObjectType())
6539  Composite1 = Composite2;
6540  // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6541  // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6542  // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6543  // T1, respectively;
6544  //
6545  // The "similar type" handling covers all of this except for the "T1 is a
6546  // base class of T2" case in the definition of reference-related.
6547  else if (IsDerivedFrom(Loc, Composite1, Composite2))
6548  Composite1 = Composite2;
6549  else if (IsDerivedFrom(Loc, Composite2, Composite1))
6550  Composite2 = Composite1;
6551  }
6552 
6553  // At this point, either the inner types are the same or we have failed to
6554  // find a composite pointer type.
6555  if (!Context.hasSameType(Composite1, Composite2))
6556  return QualType();
6557 
6558  // Per C++ [conv.qual]p3, add 'const' to every level before the last
6559  // differing qualifier.
6560  for (unsigned I = 0; I != NeedConstBefore; ++I)
6561  Steps[I].Quals.addConst();
6562 
6563  // Rebuild the composite type.
6564  QualType Composite = Composite1;
6565  for (auto &S : llvm::reverse(Steps))
6566  Composite = S.rebuild(Context, Composite);
6567 
6568  if (ConvertArgs) {
6569  // Convert the expressions to the composite pointer type.
6570  InitializedEntity Entity =
6574 
6575  InitializationSequence E1ToC(*this, Entity, Kind, E1);
6576  if (!E1ToC)
6577  return QualType();
6578 
6579  InitializationSequence E2ToC(*this, Entity, Kind, E2);
6580  if (!E2ToC)
6581  return QualType();
6582 
6583  // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6584  ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6585  if (E1Result.isInvalid())
6586  return QualType();
6587  E1 = E1Result.get();
6588 
6589  ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6590  if (E2Result.isInvalid())
6591  return QualType();
6592  E2 = E2Result.get();
6593  }
6594 
6595  return Composite;
6596 }
6597 
6599  if (!E)
6600  return ExprError();
6601 
6602  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6603 
6604  // If the result is a glvalue, we shouldn't bind it.
6605  if (!E->isRValue())
6606  return E;
6607 
6608  // In ARC, calls that return a retainable type can return retained,
6609  // in which case we have to insert a consuming cast.
6610  if (getLangOpts().ObjCAutoRefCount &&
6611  E->getType()->isObjCRetainableType()) {
6612 
6613  bool ReturnsRetained;
6614 
6615  // For actual calls, we compute this by examining the type of the
6616  // called value.
6617  if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6618  Expr *Callee = Call->getCallee()->IgnoreParens();
6619  QualType T = Callee->getType();
6620 
6621  if (T == Context.BoundMemberTy) {
6622  // Handle pointer-to-members.
6623  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6624  T = BinOp->getRHS()->getType();
6625  else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6626  T = Mem->getMemberDecl()->getType();
6627  }
6628 
6629  if (const PointerType *Ptr = T->getAs<PointerType>())
6630  T = Ptr->getPointeeType();
6631  else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6632  T = Ptr->getPointeeType();
6633  else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6634  T = MemPtr->getPointeeType();
6635 
6636  const FunctionType *FTy = T->getAs<FunctionType>();
6637  assert(FTy && "call to value not of function type?");
6638  ReturnsRetained = FTy->getExtInfo().getProducesResult();
6639 
6640  // ActOnStmtExpr arranges things so that StmtExprs of retainable
6641  // type always produce a +1 object.
6642  } else if (isa<StmtExpr>(E)) {
6643  ReturnsRetained = true;
6644 
6645  // We hit this case with the lambda conversion-to-block optimization;
6646  // we don't want any extra casts here.
6647  } else if (isa<CastExpr>(E) &&
6648  isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6649  return E;
6650 
6651  // For message sends and property references, we try to find an
6652  // actual method. FIXME: we should infer retention by selector in
6653  // cases where we don't have an actual method.
6654  } else {
6655  ObjCMethodDecl *D = nullptr;
6656  if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6657  D = Send->getMethodDecl();
6658  } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6659  D = BoxedExpr->getBoxingMethod();
6660  } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6661  // Don't do reclaims if we're using the zero-element array
6662  // constant.
6663  if (ArrayLit->getNumElements() == 0 &&
6665  return E;
6666 
6667  D = ArrayLit->getArrayWithObjectsMethod();
6668  } else if (ObjCDictionaryLiteral *DictLit
6669  = dyn_cast<ObjCDictionaryLiteral>(E)) {
6670  // Don't do reclaims if we're using the zero-element dictionary
6671  // constant.
6672  if (DictLit->getNumElements() == 0 &&
6674  return E;
6675 
6676  D = DictLit->getDictWithObjectsMethod();
6677  }
6678 
6679  ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6680 
6681  // Don't do reclaims on performSelector calls; despite their
6682  // return type, the invoked method doesn't necessarily actually
6683  // return an object.
6684  if (!ReturnsRetained &&
6685  D && D->getMethodFamily() == OMF_performSelector)
6686  return E;
6687  }
6688 
6689  // Don't reclaim an object of Class type.
6690  if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6691  return E;
6692 
6694 
6695  CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6696  : CK_ARCReclaimReturnedObject);
6697  return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6698  VK_RValue);
6699  }
6700 
6701  if (!getLangOpts().CPlusPlus)
6702  return E;
6703 
6704  // Search for the base element type (cf. ASTContext::getBaseElementType) with
6705  // a fast path for the common case that the type is directly a RecordType.
6706  const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6707  const RecordType *RT = nullptr;
6708  while (!RT) {
6709  switch (T->getTypeClass()) {
6710  case Type::Record:
6711  RT = cast<RecordType>(T);
6712  break;
6713  case Type::ConstantArray:
6714  case Type::IncompleteArray:
6715  case Type::VariableArray:
6716  case Type::DependentSizedArray:
6717  T = cast<ArrayType>(T)->getElementType().getTypePtr();
6718  break;
6719  default:
6720  return E;
6721  }
6722  }
6723 
6724  // That should be enough to guarantee that this type is complete, if we're
6725  // not processing a decltype expression.
6726  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6727  if (RD->isInvalidDecl() || RD->isDependentContext())
6728  return E;
6729 
6730  bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6732  CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6733 
6734  if (Destructor) {
6735  MarkFunctionReferenced(E->getExprLoc(), Destructor);
6736  CheckDestructorAccess(E->getExprLoc(), Destructor,
6737  PDiag(diag::err_access_dtor_temp)
6738  << E->getType());
6739  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6740  return ExprError();
6741 
6742  // If destructor is trivial, we can avoid the extra copy.
6743  if (Destructor->isTrivial())
6744  return E;
6745 
6746  // We need a cleanup, but we don't need to remember the temporary.
6748  }
6749 
6750  CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6752 
6753  if (IsDecltype)
6754  ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6755 
6756  return Bind;
6757 }
6758 
6759 ExprResult
6761  if (SubExpr.isInvalid())
6762  return ExprError();
6763 
6764  return MaybeCreateExprWithCleanups(SubExpr.get());
6765 }
6766 
6768  assert(SubExpr && "subexpression can't be null!");
6769 
6771 
6772  unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6773  assert(ExprCleanupObjects.size() >= FirstCleanup);
6774  assert(Cleanup.exprNeedsCleanups() ||
6775  ExprCleanupObjects.size() == FirstCleanup);
6776  if (!Cleanup.exprNeedsCleanups())
6777  return SubExpr;
6778 
6779  auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6780  ExprCleanupObjects.size() - FirstCleanup);
6781 
6782  auto *E = ExprWithCleanups::Create(
6783  Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6785 
6786  return E;
6787 }
6788 
6790  assert(SubStmt && "sub-statement can't be null!");
6791 
6793 
6794  if (!Cleanup.exprNeedsCleanups())
6795  return SubStmt;
6796 
6797  // FIXME: In order to attach the temporaries, wrap the statement into
6798  // a StmtExpr; currently this is only used for asm statements.
6799  // This is hacky, either create a new CXXStmtWithTemporaries statement or
6800  // a new AsmStmtWithTemporaries.
6801  CompoundStmt *CompStmt = CompoundStmt::Create(
6802  Context, SubStmt, SourceLocation(), SourceLocation());
6803  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6804  SourceLocation());
6805  return MaybeCreateExprWithCleanups(E);
6806 }
6807 
6808 /// Process the expression contained within a decltype. For such expressions,
6809 /// certain semantic checks on temporaries are delayed until this point, and
6810 /// are omitted for the 'topmost' call in the decltype expression. If the
6811 /// topmost call bound a temporary, strip that temporary off the expression.
6813  assert(ExprEvalContexts.back().ExprContext ==
6815  "not in a decltype expression");
6816 
6818  if (Result.isInvalid())
6819  return ExprError();
6820  E = Result.get();
6821 
6822  // C++11 [expr.call]p11:
6823  // If a function call is a prvalue of object type,
6824  // -- if the function call is either
6825  // -- the operand of a decltype-specifier, or
6826  // -- the right operand of a comma operator that is the operand of a
6827  // decltype-specifier,
6828  // a temporary object is not introduced for the prvalue.
6829 
6830  // Recursively rebuild ParenExprs and comma expressions to strip out the
6831  // outermost CXXBindTemporaryExpr, if any.
6832  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6833  ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6834  if (SubExpr.isInvalid())
6835  return ExprError();
6836  if (SubExpr.get() == PE->getSubExpr())
6837  return E;
6838  return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6839  }
6840  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6841  if (BO->getOpcode() == BO_Comma) {
6842  ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6843  if (RHS.isInvalid())
6844  return ExprError();
6845  if (RHS.get() == BO->getRHS())
6846  return E;
6847  return new (Context) BinaryOperator(
6848  BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6849  BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6850  }
6851  }
6852 
6853  CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6854  CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6855  : nullptr;
6856  if (TopCall)
6857  E = TopCall;
6858  else
6859  TopBind = nullptr;
6860 
6861  // Disable the special decltype handling now.
6862  ExprEvalContexts.back().ExprContext =
6864 
6865  Result = CheckUnevaluatedOperand(E);
6866  if (Result.isInvalid())
6867  return ExprError();
6868  E = Result.get();
6869 
6870  // In MS mode, don't perform any extra checking of call return types within a
6871  // decltype expression.
6872  if (getLangOpts().MSVCCompat)
6873  return E;
6874 
6875  // Perform the semantic checks we delayed until this point.
6876  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6877  I != N; ++I) {
6878  CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6879  if (Call == TopCall)
6880  continue;
6881 
6883  Call->getBeginLoc(), Call, Call->getDirectCallee()))
6884  return ExprError();
6885  }
6886 
6887  // Now all relevant types are complete, check the destructors are accessible
6888  // and non-deleted, and annotate them on the temporaries.
6889  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6890  I != N; ++I) {
6891  CXXBindTemporaryExpr *Bind =
6892  ExprEvalContexts.back().DelayedDecltypeBinds[I];
6893  if (Bind == TopBind)
6894  continue;
6895 
6896  CXXTemporary *Temp = Bind->getTemporary();
6897 
6898  CXXRecordDecl *RD =
6900  CXXDestructorDecl *Destructor = LookupDestructor(RD);
6901  Temp->setDestructor(Destructor);
6902 
6903  MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6904  CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6905  PDiag(diag::err_access_dtor_temp)
6906  << Bind->getType());
6907  if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6908  return ExprError();
6909 
6910  // We need a cleanup, but we don't need to remember the temporary.
6912  }
6913 
6914  // Possibly strip off the top CXXBindTemporaryExpr.
6915  return E;
6916 }
6917 
6918 /// Note a set of 'operator->' functions that were used for a member access.
6919 static void noteOperatorArrows(Sema &S,
6920  ArrayRef<FunctionDecl *> OperatorArrows) {
6921  unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6922  // FIXME: Make this configurable?
6923  unsigned Limit = 9;
6924  if (OperatorArrows.size() > Limit) {
6925  // Produce Limit-1 normal notes and one 'skipping' note.
6926  SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6927  SkipCount = OperatorArrows.size() - (Limit - 1);
6928  }
6929 
6930  for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6931  if (I == SkipStart) {
6932  S.Diag(OperatorArrows[I]->getLocation(),
6933  diag::note_operator_arrows_suppressed)
6934  << SkipCount;
6935  I += SkipCount;
6936  } else {
6937  S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6938  << OperatorArrows[I]->getCallResultType();
6939  ++I;
6940  }
6941  }
6942 }
6943 
6945  SourceLocation OpLoc,
6946  tok::TokenKind OpKind,
6947  ParsedType &ObjectType,
6948  bool &MayBePseudoDestructor) {
6949  // Since this might be a postfix expression, get rid of ParenListExprs.
6951  if (Result.isInvalid()) return ExprError();
6952  Base = Result.get();
6953 
6954  Result = CheckPlaceholderExpr(Base);
6955  if (Result.isInvalid()) return ExprError();
6956  Base = Result.get();
6957 
6958  QualType BaseType = Base->getType();
6959  MayBePseudoDestructor = false;
6960  if (BaseType->isDependentType()) {
6961  // If we have a pointer to a dependent type and are using the -> operator,
6962  // the object type is the type that the pointer points to. We might still
6963  // have enough information about that type to do something useful.
6964  if (OpKind == tok::arrow)
6965  if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6966  BaseType = Ptr->getPointeeType();
6967 
6968  ObjectType = ParsedType::make(BaseType);
6969  MayBePseudoDestructor = true;
6970  return Base;
6971  }
6972 
6973  // C++ [over.match.oper]p8:
6974  // [...] When operator->returns, the operator-> is applied to the value
6975  // returned, with the original second operand.
6976  if (OpKind == tok::arrow) {
6977  QualType StartingType = BaseType;
6978  bool NoArrowOperatorFound = false;
6979  bool FirstIteration = true;
6980  FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6981  // The set of types we've considered so far.
6982  llvm::SmallPtrSet<CanQualType,8> CTypes;
6983  SmallVector<FunctionDecl*, 8> OperatorArrows;
6984  CTypes.insert(Context.getCanonicalType(BaseType));
6985 
6986  while (BaseType->isRecordType()) {
6987  if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6988  Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6989  << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6990  noteOperatorArrows(*this, OperatorArrows);
6991  Diag(OpLoc, diag::note_operator_arrow_depth)
6992  << getLangOpts().ArrowDepth;
6993  return ExprError();
6994  }
6995 
6996  Result = BuildOverloadedArrowExpr(
6997  S, Base, OpLoc,
6998  // When in a template specialization and on the first loop iteration,
6999  // potentially give the default diagnostic (with the fixit in a
7000  // separate note) instead of having the error reported back to here
7001  // and giving a diagnostic with a fixit attached to the error itself.
7002  (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7003  ? nullptr
7004  : &NoArrowOperatorFound);
7005  if (Result.isInvalid()) {
7006  if (NoArrowOperatorFound) {
7007  if (FirstIteration) {
7008  Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7009  << BaseType << 1 << Base->getSourceRange()
7010  << FixItHint::CreateReplacement(OpLoc, ".");
7011  OpKind = tok::period;
7012  break;
7013  }
7014  Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7015  << BaseType << Base->getSourceRange();
7016  CallExpr *CE = dyn_cast<CallExpr>(Base);
7017  if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7018  Diag(CD->getBeginLoc(),
7019  diag::note_member_reference_arrow_from_operator_arrow);
7020  }
7021  }
7022  return ExprError();
7023  }
7024  Base = Result.get();
7025  if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7026  OperatorArrows.push_back(OpCall->getDirectCallee());
7027  BaseType = Base->getType();
7028  CanQualType CBaseType = Context.getCanonicalType(BaseType);
7029  if (!CTypes.insert(CBaseType).second) {
7030  Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7031  noteOperatorArrows(*this, OperatorArrows);
7032  return ExprError();
7033  }
7034  FirstIteration = false;
7035  }
7036 
7037  if (OpKind == tok::arrow) {
7038  if (BaseType->isPointerType())
7039  BaseType = BaseType->getPointeeType();
7040  else if (auto *AT = Context.getAsArrayType(BaseType))
7041  BaseType = AT->getElementType();
7042  }
7043  }
7044 
7045  // Objective-C properties allow "." access on Objective-C pointer types,
7046  // so adjust the base type to the object type itself.
7047  if (BaseType->isObjCObjectPointerType())
7048  BaseType = BaseType->getPointeeType();
7049 
7050  // C++ [basic.lookup.classref]p2:
7051  // [...] If the type of the object expression is of pointer to scalar
7052  // type, the unqualified-id is looked up in the context of the complete
7053  // postfix-expression.
7054  //
7055  // This also indicates that we could be parsing a pseudo-destructor-name.
7056  // Note that Objective-C class and object types can be pseudo-destructor
7057  // expressions or normal member (ivar or property) access expressions, and
7058  // it's legal for the type to be incomplete if this is a pseudo-destructor
7059  // call. We'll do more incomplete-type checks later in the lookup process,
7060  // so just skip this check for ObjC types.
7061  if (!BaseType->isRecordType()) {
7062  ObjectType = ParsedType::make(BaseType);
7063  MayBePseudoDestructor = true;
7064  return Base;
7065  }
7066 
7067  // The object type must be complete (or dependent), or
7068  // C++11 [expr.prim.general]p3:
7069  // Unlike the object expression in other contexts, *this is not required to
7070  // be of complete type for purposes of class member access (5.2.5) outside
7071  // the member function body.
7072  if (!BaseType->isDependentType() &&
7073  !isThisOutsideMemberFunctionBody(BaseType) &&
7074  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
7075  return ExprError();
7076 
7077  // C++ [basic.lookup.classref]p2:
7078  // If the id-expression in a class member access (5.2.5) is an
7079  // unqualified-id, and the type of the object expression is of a class
7080  // type C (or of pointer to a class type C), the unqualified-id is looked
7081  // up in the scope of class C. [...]
7082  ObjectType = ParsedType::make(BaseType);
7083  return Base;
7084 }
7085 
7086 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
7087  tok::TokenKind& OpKind, SourceLocation OpLoc) {
7088  if (Base->hasPlaceholderType()) {
7089  ExprResult result = S.CheckPlaceholderExpr(Base);
7090  if (result.isInvalid()) return true;
7091  Base = result.get();
7092  }
7093  ObjectType = Base->getType();
7094 
7095  // C++ [expr.pseudo]p2:
7096  // The left-hand side of the dot operator shall be of scalar type. The
7097  // left-hand side of the arrow operator shall be of pointer to scalar type.
7098  // This scalar type is the object type.
7099  // Note that this is rather different from the normal handling for the
7100  // arrow operator.
7101  if (OpKind == tok::arrow) {
7102  if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7103  ObjectType = Ptr->getPointeeType();
7104  } else if (!Base->isTypeDependent()) {
7105  // The user wrote "p->" when they probably meant "p."; fix it.
7106  S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7107  << ObjectType << true
7108  << FixItHint::CreateReplacement(OpLoc, ".");
7109  if (S.isSFINAEContext())
7110  return true;
7111 
7112  OpKind = tok::period;
7113  }
7114  }
7115 
7116  return false;
7117 }
7118 
7119 /// Check if it's ok to try and recover dot pseudo destructor calls on
7120 /// pointer objects.
7121 static bool
7123  QualType DestructedType) {
7124  // If this is a record type, check if its destructor is callable.
7125  if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7126  if (RD->hasDefinition())
7127  if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7128  return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7129  return false;
7130  }
7131 
7132  // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7133  return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7134  DestructedType->isVectorType();
7135 }
7136 
7138  SourceLocation OpLoc,
7139  tok::TokenKind OpKind,
7140  const CXXScopeSpec &SS,
7141  TypeSourceInfo *ScopeTypeInfo,
7142  SourceLocation CCLoc,
7143  SourceLocation TildeLoc,
7144  PseudoDestructorTypeStorage Destructed) {
7145  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7146 
7147  QualType ObjectType;
7148  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7149  return ExprError();
7150 
7151  if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7152  !ObjectType->isVectorType()) {
7153  if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7154  Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7155  else {
7156  Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7157  << ObjectType << Base->getSourceRange();
7158  return ExprError();
7159  }
7160  }
7161 
7162  // C++ [expr.pseudo]p2:
7163  // [...] The cv-unqualified versions of the object type and of the type
7164  // designated by the pseudo-destructor-name shall be the same type.
7165  if (DestructedTypeInfo) {
7166  QualType DestructedType = DestructedTypeInfo->getType();
7167  SourceLocation DestructedTypeStart
7168  = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
7169  if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7170  if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7171  // Detect dot pseudo destructor calls on pointer objects, e.g.:
7172  // Foo *foo;
7173  // foo.~Foo();
7174  if (OpKind == tok::period && ObjectType->isPointerType() &&
7175  Context.hasSameUnqualifiedType(DestructedType,
7176  ObjectType->getPointeeType())) {
7177  auto Diagnostic =
7178  Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7179  << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7180 
7181  // Issue a fixit only when the destructor is valid.
7183  *this, DestructedType))
7184  Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7185 
7186  // Recover by setting the object type to the destructed type and the
7187  // operator to '->'.
7188  ObjectType = DestructedType;
7189  OpKind = tok::arrow;
7190  } else {
7191  Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7192  << ObjectType << DestructedType << Base->getSourceRange()
7193  << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7194 
7195  // Recover by setting the destructed type to the object type.
7196  DestructedType = ObjectType;
7197  DestructedTypeInfo =
7198  Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7199  Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7200  }
7201  } else if (DestructedType.getObjCLifetime() !=
7202  ObjectType.getObjCLifetime()) {
7203 
7204  if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7205  // Okay: just pretend that the user provided the correctly-qualified
7206  // type.
7207  } else {
7208  Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7209  << ObjectType << DestructedType << Base->getSourceRange()
7210  << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7211  }
7212 
7213  // Recover by setting the destructed type to the object type.
7214  DestructedType = ObjectType;
7215  DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7216  DestructedTypeStart);
7217  Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7218  }
7219  }
7220  }
7221 
7222  // C++ [expr.pseudo]p2:
7223  // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7224  // form
7225  //
7226  // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7227  //
7228  // shall designate the same scalar type.
7229  if (ScopeTypeInfo) {
7230  QualType ScopeType = ScopeTypeInfo->getType();
7231  if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7232  !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7233 
7234  Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
7235  diag::err_pseudo_dtor_type_mismatch)
7236  << ObjectType << ScopeType << Base->getSourceRange()
7237  << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
7238 
7239  ScopeType = QualType();
7240  ScopeTypeInfo = nullptr;
7241  }
7242  }
7243 
7244  Expr *Result
7245  = new (Context) CXXPseudoDestructorExpr(Context, Base,
7246  OpKind == tok::arrow, OpLoc,
7248  ScopeTypeInfo,
7249  CCLoc,
7250  TildeLoc,
7251  Destructed);
7252 
7253  return Result;
7254 }
7255 
7257  SourceLocation OpLoc,
7258  tok::TokenKind OpKind,
7259  CXXScopeSpec &SS,
7260  UnqualifiedId &FirstTypeName,
7261  SourceLocation CCLoc,
7262  SourceLocation TildeLoc,
7263  UnqualifiedId &SecondTypeName) {
7264  assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7265  FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7266  "Invalid first type name in pseudo-destructor");
7267  assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7268  SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7269  "Invalid second type name in pseudo-destructor");
7270 
7271  QualType ObjectType;
7272  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7273  return ExprError();
7274 
7275  // Compute the object type that we should use for name lookup purposes. Only
7276  // record types and dependent types matter.
7277  ParsedType ObjectTypePtrForLookup;
7278  if (!SS.isSet()) {
7279  if (ObjectType->isRecordType())
7280  ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7281  else if (ObjectType->isDependentType())
7282  ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7283  }
7284 
7285  // Convert the name of the type being destructed (following the ~) into a
7286  // type (with source-location information).
7287  QualType DestructedType;
7288  TypeSourceInfo *DestructedTypeInfo = nullptr;
7289  PseudoDestructorTypeStorage Destructed;
7290  if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7291  ParsedType T = getTypeName(*SecondTypeName.Identifier,
7292  SecondTypeName.StartLocation,
7293  S, &SS, true, false, ObjectTypePtrForLookup,
7294  /*IsCtorOrDtorName*/true);
7295  if (!T &&
7296  ((SS.isSet() && !computeDeclContext(SS, false)) ||
7297  (!SS.isSet() && ObjectType->isDependentType()))) {
7298  // The name of the type being destroyed is a dependent name, and we
7299  // couldn't find anything useful in scope. Just store the identifier and
7300  // it's location, and we'll perform (qualified) name lookup again at
7301  // template instantiation time.
7302  Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7303  SecondTypeName.StartLocation);
7304  } else if (!T) {
7305  Diag(SecondTypeName.StartLocation,
7306  diag::err_pseudo_dtor_destructor_non_type)
7307  << SecondTypeName.Identifier << ObjectType;
7308  if (isSFINAEContext())
7309  return ExprError();
7310 
7311  // Recover by assuming we had the right type all along.
7312  DestructedType = ObjectType;
7313  } else
7314  DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7315  } else {
7316  // Resolve the template-id to a type.
7317  TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7318  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7319  TemplateId->NumArgs);
7321  SS,
7322  TemplateId->TemplateKWLoc,
7323  TemplateId->Template,
7324  TemplateId->Name,
7325  TemplateId->TemplateNameLoc,
7326  TemplateId->LAngleLoc,
7327  TemplateArgsPtr,
7328  TemplateId->RAngleLoc,
7329  /*IsCtorOrDtorName*/true);
7330  if (T.isInvalid() || !T.get()) {
7331  // Recover by assuming we had the right type all along.
7332  DestructedType = ObjectType;
7333  } else
7334  DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7335  }
7336 
7337  // If we've performed some kind of recovery, (re-)build the type source
7338  // information.
7339  if (!DestructedType.isNull()) {
7340  if (!DestructedTypeInfo)
7341  DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7342  SecondTypeName.StartLocation);
7343  Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7344  }
7345 
7346  // Convert the name of the scope type (the type prior to '::') into a type.
7347  TypeSourceInfo *ScopeTypeInfo = nullptr;
7348  QualType ScopeType;
7349  if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7350  FirstTypeName.Identifier) {
7351  if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7352  ParsedType T = getTypeName(*FirstTypeName.Identifier,
7353  FirstTypeName.StartLocation,
7354  S, &SS, true, false, ObjectTypePtrForLookup,
7355  /*IsCtorOrDtorName*/true);
7356  if (!T) {
7357  Diag(FirstTypeName.StartLocation,
7358  diag::err_pseudo_dtor_destructor_non_type)
7359  << FirstTypeName.Identifier << ObjectType;
7360 
7361  if (isSFINAEContext())
7362  return ExprError();
7363 
7364  // Just drop this type. It's unnecessary anyway.
7365  ScopeType = QualType();
7366  } else
7367  ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7368  } else {
7369  // Resolve the template-id to a type.
7370  TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7371  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7372  TemplateId->NumArgs);
7374  SS,
7375  TemplateId->TemplateKWLoc,
7376  TemplateId->Template,
7377  TemplateId->Name,
7378  TemplateId->TemplateNameLoc,
7379  TemplateId->LAngleLoc,
7380  TemplateArgsPtr,
7381  TemplateId->RAngleLoc,
7382  /*IsCtorOrDtorName*/true);
7383  if (T.isInvalid() || !T.get()) {
7384  // Recover by dropping this type.
7385  ScopeType = QualType();
7386  } else
7387  ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7388  }
7389  }
7390 
7391  if (!ScopeType.isNull() && !ScopeTypeInfo)
7392  ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7393  FirstTypeName.StartLocation);
7394 
7395 
7396  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7397  ScopeTypeInfo, CCLoc, TildeLoc,
7398  Destructed);
7399 }
7400 
7402  SourceLocation OpLoc,
7403  tok::TokenKind OpKind,
7404  SourceLocation TildeLoc,
7405  const DeclSpec& DS) {
7406  QualType ObjectType;
7407  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7408  return ExprError();
7409 
7411  false);
7412 
7413  TypeLocBuilder TLB;
7414  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7415  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7416  TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7417  PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7418 
7419  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7420  nullptr, SourceLocation(), TildeLoc,
7421  Destructed);
7422 }
7423 
7425  CXXConversionDecl *Method,
7426  bool HadMultipleCandidates) {
7427  // Convert the expression to match the conversion function's implicit object
7428  // parameter.
7429  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7430  FoundDecl, Method);
7431  if (Exp.isInvalid())
7432  return true;
7433 
7434  if (Method->getParent()->isLambda() &&
7435  Method->getConversionType()->isBlockPointerType()) {
7436  // This is a lambda conversion to block pointer; check if the argument
7437  // was a LambdaExpr.
7438  Expr *SubE = E;
7439  CastExpr *CE = dyn_cast<CastExpr>(SubE);
7440  if (CE && CE->getCastKind() == CK_NoOp)
7441  SubE = CE->getSubExpr();
7442  SubE = SubE->IgnoreParens();
7443  if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7444  SubE = BE->getSubExpr();
7445  if (isa<LambdaExpr>(SubE)) {
7446  // For the conversion to block pointer on a lambda expression, we
7447  // construct a special BlockLiteral instead; this doesn't really make
7448  // a difference in ARC, but outside of ARC the resulting block literal
7449  // follows the normal lifetime rules for block literals instead of being
7450  // autoreleased.
7451  DiagnosticErrorTrap Trap(Diags);
7455  Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7457 
7458  if (BlockExp.isInvalid())
7459  Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7460  return BlockExp;
7461  }
7462  }
7463 
7464  MemberExpr *ME =
7465  BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7467  DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7468  HadMultipleCandidates, DeclarationNameInfo(),
7470 
7471  QualType ResultType = Method->getReturnType();
7472  ExprValueKind VK = Expr::getValueKindForType(ResultType);
7473  ResultType = ResultType.getNonLValueExprType(Context);
7474 
7476  Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
7477 
7478  if (CheckFunctionCall(Method, CE,
7479  Method->getType()->castAs<FunctionProtoType>()))
7480  return ExprError();
7481 
7482  return CE;
7483 }
7484 
7486  SourceLocation RParen) {
7487  // If the operand is an unresolved lookup expression, the expression is ill-
7488  // formed per [over.over]p1, because overloaded function names cannot be used
7489  // without arguments except in explicit contexts.
7490  ExprResult R = CheckPlaceholderExpr(Operand);
7491  if (R.isInvalid())
7492  return R;
7493 
7494  R = CheckUnevaluatedOperand(R.get());
7495  if (R.isInvalid())
7496  return ExprError();
7497 
7498  Operand = R.get();
7499 
7500  if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
7501  // The expression operand for noexcept is in an unevaluated expression
7502  // context, so side effects could result in unintended consequences.
7503  Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7504  }
7505 
7506  CanThrowResult CanThrow = canThrow(Operand);
7507  return new (Context)
7508  CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7509 }
7510 
7512  Expr *Operand, SourceLocation RParen) {
7513  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7514 }
7515 
7517  // In C++11, discarded-value expressions of a certain form are special,
7518  // according to [expr]p10:
7519  // The lvalue-to-rvalue conversion (4.1) is applied only if the
7520  // expression is an lvalue of volatile-qualified type and it has
7521  // one of the following forms:
7522  E = E->IgnoreParens();
7523 
7524  // - id-expression (5.1.1),
7525  if (isa<DeclRefExpr>(E))
7526  return true;
7527 
7528  // - subscripting (5.2.1),
7529  if (isa<ArraySubscriptExpr>(E))
7530  return true;
7531 
7532  // - class member access (5.2.5),
7533  if (isa<MemberExpr>(E))
7534  return true;
7535 
7536  // - indirection (5.3.1),
7537  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7538  if (UO->getOpcode() == UO_Deref)
7539  return true;
7540 
7541  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7542  // - pointer-to-member operation (5.5),
7543  if (BO->isPtrMemOp())
7544  return true;
7545 
7546  // - comma expression (5.18) where the right operand is one of the above.
7547  if (BO->getOpcode() == BO_Comma)
7548  return IsSpecialDiscardedValue(BO->getRHS());
7549  }
7550 
7551  // - conditional expression (5.16) where both the second and the third
7552  // operands are one of the above, or
7553  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7554  return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7555  IsSpecialDiscardedValue(CO->getFalseExpr());
7556  // The related edge case of "*x ?: *x".
7557  if (BinaryConditionalOperator *BCO =
7558  dyn_cast<BinaryConditionalOperator>(E)) {
7559  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7560  return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7561  IsSpecialDiscardedValue(BCO->getFalseExpr());
7562  }
7563 
7564  // Objective-C++ extensions to the rule.
7565  if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7566  return true;
7567 
7568  return false;
7569 }
7570 
7571 /// Perform the conversions required for an expression used in a
7572 /// context that ignores the result.
7574  if (E->hasPlaceholderType()) {
7575  ExprResult result = CheckPlaceholderExpr(E);
7576  if (result.isInvalid()) return E;
7577  E = result.get();
7578  }
7579 
7580  // C99 6.3.2.1:
7581  // [Except in specific positions,] an lvalue that does not have
7582  // array type is converted to the value stored in the
7583  // designated object (and is no longer an lvalue).
7584  if (E->isRValue()) {
7585  // In C, function designators (i.e. expressions of function type)
7586  // are r-values, but we still want to do function-to-pointer decay
7587  // on them. This is both technically correct and convenient for
7588  // some clients.
7589  if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7591 
7592  return E;
7593  }
7594 
7595  if (getLangOpts().CPlusPlus) {
7596  // The C++11 standard defines the notion of a discarded-value expression;
7597  // normally, we don't need to do anything to handle it, but if it is a
7598  // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7599  // conversion.
7600  if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7601  E->getType().isVolatileQualified()) {
7602  if (IsSpecialDiscardedValue(E)) {
7604  if (Res.isInvalid())
7605  return E;
7606  E = Res.get();
7607  } else {
7608  // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7609  // it occurs as a discarded-value expression.
7611  }
7612  }
7613 
7614  // C++1z:
7615  // If the expression is a prvalue after this optional conversion, the
7616  // temporary materialization conversion is applied.
7617  //
7618  // We skip this step: IR generation is able to synthesize the storage for
7619  // itself in the aggregate case, and adding the extra node to the AST is
7620  // just clutter.
7621  // FIXME: We don't emit lifetime markers for the temporaries due to this.
7622  // FIXME: Do any other AST consumers care about this?
7623  return E;
7624  }
7625 
7626  // GCC seems to also exclude expressions of incomplete enum type.
7627  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7628  if (!T->getDecl()->isComplete()) {
7629  // FIXME: stupid workaround for a codegen bug!
7630  E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7631  return E;
7632  }
7633  }
7634 
7636  if (Res.isInvalid())
7637  return E;
7638  E = Res.get();
7639 
7640  if (!E->getType()->isVoidType())
7642  diag::err_incomplete_type);
7643  return E;
7644 }
7645 
7647  // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7648  // it occurs as an unevaluated operand.
7650 
7651  return E;
7652 }
7653 
7654 // If we can unambiguously determine whether Var can never be used
7655 // in a constant expression, return true.
7656 // - if the variable and its initializer are non-dependent, then
7657 // we can unambiguously check if the variable is a constant expression.
7658 // - if the initializer is not value dependent - we can determine whether
7659 // it can be used to initialize a constant expression. If Init can not
7660 // be used to initialize a constant expression we conclude that Var can
7661 // never be a constant expression.
7662 // - FXIME: if the initializer is dependent, we can still do some analysis and
7663 // identify certain cases unambiguously as non-const by using a Visitor:
7664 // - such as those that involve odr-use of a ParmVarDecl, involve a new
7665 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7667  ASTContext &Context) {
7668  if (isa<ParmVarDecl>(Var)) return true;
7669  const VarDecl *DefVD = nullptr;
7670 
7671  // If there is no initializer - this can not be a constant expression.
7672  if (!Var->getAnyInitializer(DefVD)) return true;
7673  assert(DefVD);
7674  if (DefVD->isWeak()) return false;
7675  EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7676 
7677  Expr *Init = cast<Expr>(Eval->Value);
7678 
7679  if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7680  // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7681  // of value-dependent expressions, and use it here to determine whether the
7682  // initializer is a potential constant expression.
7683  return false;
7684  }
7685 
7686  return !Var->isUsableInConstantExpressions(Context);
7687 }
7688 
7689 /// Check if the current lambda has any potential captures
7690 /// that must be captured by any of its enclosing lambdas that are ready to
7691 /// capture. If there is a lambda that can capture a nested
7692 /// potential-capture, go ahead and do so. Also, check to see if any
7693 /// variables are uncaptureable or do not involve an odr-use so do not
7694 /// need to be captured.
7695 
7697  Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7698 
7699  assert(!S.isUnevaluatedContext());
7700  assert(S.CurContext->isDependentContext());
7701 #ifndef NDEBUG
7702  DeclContext *DC = S.CurContext;
7703  while (DC && isa<CapturedDecl>(DC))
7704  DC = DC->getParent();
7705  assert(
7706  CurrentLSI->CallOperator == DC &&
7707  "The current call operator must be synchronized with Sema's CurContext");
7708 #endif // NDEBUG
7709 
7710  const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7711 
7712  // All the potentially captureable variables in the current nested
7713  // lambda (within a generic outer lambda), must be captured by an
7714  // outer lambda that is enclosed within a non-dependent context.
7715  CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
7716  // If the variable is clearly identified as non-odr-used and the full
7717  // expression is not instantiation dependent, only then do we not
7718  // need to check enclosing lambda's for speculative captures.
7719  // For e.g.:
7720  // Even though 'x' is not odr-used, it should be captured.
7721  // int test() {
7722  // const int x = 10;
7723  // auto L = [=](auto a) {
7724  // (void) +x + a;
7725  // };
7726  // }
7727  if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7728  !IsFullExprInstantiationDependent)
7729  return;
7730 
7731  // If we have a capture-capable lambda for the variable, go ahead and
7732  // capture the variable in that lambda (and all its enclosing lambdas).
7733  if (const Optional<unsigned> Index =
7735  S.FunctionScopes, Var, S))
7737  Index.getValue());
7738  const bool IsVarNeverAConstantExpression =
7740  if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7741  // This full expression is not instantiation dependent or the variable
7742  // can not be used in a constant expression - which means
7743  // this variable must be odr-used here, so diagnose a
7744  // capture violation early, if the variable is un-captureable.
7745  // This is purely for diagnosing errors early. Otherwise, this
7746  // error would get diagnosed when the lambda becomes capture ready.
7747  QualType CaptureType, DeclRefType;
7748  SourceLocation ExprLoc = VarExpr->getExprLoc();
7749  if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7750  /*EllipsisLoc*/ SourceLocation(),
7751  /*BuildAndDiagnose*/false, CaptureType,
7752  DeclRefType, nullptr)) {
7753  // We will never be able to capture this variable, and we need
7754  // to be able to in any and all instantiations, so diagnose it.
7755  S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7756  /*EllipsisLoc*/ SourceLocation(),
7757  /*BuildAndDiagnose*/true, CaptureType,
7758  DeclRefType, nullptr);
7759  }
7760  }
7761  });
7762 
7763  // Check if 'this' needs to be captured.
7764  if (CurrentLSI->hasPotentialThisCapture()) {
7765  // If we have a capture-capable lambda for 'this', go ahead and capture
7766  // 'this' in that lambda (and all its enclosing lambdas).
7767  if (const Optional<unsigned> Index =
7769  S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7770  const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7772  /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7773  &FunctionScopeIndexOfCapturableLambda);
7774  }
7775  }
7776 
7777  // Reset all the potential captures at the end of each full-expression.
7778  CurrentLSI->clearPotentialCaptures();
7779 }
7780 
7783  const TypoCorrection &TC) {
7784  LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7785  Consumer.getLookupResult().getLookupKind());
7786  const CXXScopeSpec *SS = Consumer.getSS();
7787  CXXScopeSpec NewSS;
7788 
7789  // Use an approprate CXXScopeSpec for building the expr.
7790  if (auto *NNS = TC.getCorrectionSpecifier())
7791  NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7792  else if (SS && !TC.WillReplaceSpecifier())
7793  NewSS = *SS;
7794 
7795  if (auto *ND = TC.getFoundDecl()) {
7796  R.setLookupName(ND->getDeclName());
7797  R.addDecl(ND);
7798  if (ND->isCXXClassMember()) {
7799  // Figure out the correct naming class to add to the LookupResult.
7800  CXXRecordDecl *Record = nullptr;
7801  if (auto *NNS = TC.getCorrectionSpecifier())
7802  Record = NNS->getAsType()->getAsCXXRecordDecl();
7803  if (!Record)
7804  Record =
7805  dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7806  if (Record)
7807  R.setNamingClass(Record);
7808 
7809  // Detect and handle the case where the decl might be an implicit
7810  // member.
7811  bool MightBeImplicitMember;
7812  if (!Consumer.isAddressOfOperand())
7813  MightBeImplicitMember = true;
7814  else if (!NewSS.isEmpty())
7815  MightBeImplicitMember = false;
7816  else if (R.isOverloadedResult())
7817  MightBeImplicitMember = false;
7818  else if (R.isUnresolvableResult())
7819  MightBeImplicitMember = true;
7820  else
7821  MightBeImplicitMember = isa<FieldDecl>(ND) ||
7822  isa<IndirectFieldDecl>(ND) ||
7823  isa<MSPropertyDecl>(ND);
7824 
7825  if (MightBeImplicitMember)
7826  return SemaRef.BuildPossibleImplicitMemberExpr(
7827  NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7828  /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7829  } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7830  return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7831  Ivar->getIdentifier());
7832  }
7833  }
7834 
7835  return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7836  /*AcceptInvalidDecl*/ true);
7837 }
7838 
7839 namespace {
7840 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7842 
7843 public:
7844  explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7845  : TypoExprs(TypoExprs) {}
7846  bool VisitTypoExpr(TypoExpr *TE) {
7847  TypoExprs.insert(TE);
7848  return true;
7849  }
7850 };
7851 
7852 class TransformTypos : public TreeTransform<TransformTypos> {
7853  typedef TreeTransform<TransformTypos> BaseTransform;
7854 
7855  VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7856  // process of being initialized.
7857  llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7858  llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7859  llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7860  llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7861 
7862  /// Emit diagnostics for all of the TypoExprs encountered.
7863  ///
7864  /// If the TypoExprs were successfully corrected, then the diagnostics should
7865  /// suggest the corrections. Otherwise the diagnostics will not suggest
7866  /// anything (having been passed an empty TypoCorrection).
7867  ///
7868  /// If we've failed to correct due to ambiguous corrections, we need to
7869  /// be sure to pass empty corrections and replacements. Otherwise it's
7870  /// possible that the Consumer has a TypoCorrection that failed to ambiguity
7871  /// and we don't want to report those diagnostics.
7872  void EmitAllDiagnostics(bool IsAmbiguous) {
7873  for (TypoExpr *TE : TypoExprs) {
7874  auto &State = SemaRef.getTypoExprState(TE);
7875  if (State.DiagHandler) {
7876  TypoCorrection TC = IsAmbiguous
7877  ? TypoCorrection() : State.Consumer->getCurrentCorrection();
7878  ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
7879 
7880  // Extract the NamedDecl from the transformed TypoExpr and add it to the
7881  // TypoCorrection, replacing the existing decls. This ensures the right
7882  // NamedDecl is used in diagnostics e.g. in the case where overload
7883  // resolution was used to select one from several possible decls that
7884  // had been stored in the TypoCorrection.
7885  if (auto *ND = getDeclFromExpr(
7886  Replacement.isInvalid() ? nullptr : Replacement.get()))
7887  TC.setCorrectionDecl(ND);
7888 
7889  State.DiagHandler(TC);
7890  }
7891  SemaRef.clearDelayedTypo(TE);
7892  }
7893  }
7894 
7895  /// If corrections for the first TypoExpr have been exhausted for a
7896  /// given combination of the other TypoExprs, retry those corrections against
7897  /// the next combination of substitutions for the other TypoExprs by advancing
7898  /// to the next potential correction of the second TypoExpr. For the second
7899  /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7900  /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7901  /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7902  /// TransformCache). Returns true if there is still any untried combinations
7903  /// of corrections.
7904  bool CheckAndAdvanceTypoExprCorrectionStreams() {
7905  for (auto TE : TypoExprs) {
7906  auto &State = SemaRef.getTypoExprState(TE);
7907  TransformCache.erase(TE);
7908  if (!State.Consumer->finished())
7909  return true;
7910  State.Consumer->resetCorrectionStream();
7911  }
7912  return false;
7913  }
7914 
7916  if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7917  E = OverloadResolution[OE];
7918 
7919  if (!E)
7920  return nullptr;
7921  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7922  return DRE->getFoundDecl();
7923  if (auto *ME = dyn_cast<MemberExpr>(E))
7924  return ME->getFoundDecl();
7925  // FIXME: Add any other expr types that could be be seen by the delayed typo
7926  // correction TreeTransform for which the corresponding TypoCorrection could
7927  // contain multiple decls.
7928  return nullptr;
7929  }
7930 
7931  ExprResult TryTransform(Expr *E) {
7932  Sema::SFINAETrap Trap(SemaRef);
7933  ExprResult Res = TransformExpr(E);
7934  if (Trap.hasErrorOccurred() || Res.isInvalid())
7935  return ExprError();
7936 
7937  return ExprFilter(Res.get());
7938  }
7939 
7940  // Since correcting typos may intoduce new TypoExprs, this function
7941  // checks for new TypoExprs and recurses if it finds any. Note that it will
7942  // only succeed if it is able to correct all typos in the given expression.
7943  ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
7944  if (Res.isInvalid()) {
7945  return Res;
7946  }
7947  // Check to see if any new TypoExprs were created. If so, we need to recurse
7948  // to check their validity.
7949  Expr *FixedExpr = Res.get();
7950 
7951  auto SavedTypoExprs = std::move(TypoExprs);
7952  auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
7953  TypoExprs.clear();
7954  AmbiguousTypoExprs.clear();
7955 
7956  FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
7957  if (!TypoExprs.empty()) {
7958  // Recurse to handle newly created TypoExprs. If we're not able to
7959  // handle them, discard these TypoExprs.
7960  ExprResult RecurResult =
7961  RecursiveTransformLoop(FixedExpr, IsAmbiguous);
7962  if (RecurResult.isInvalid()) {
7963  Res = ExprError();
7964  // Recursive corrections didn't work, wipe them away and don't add
7965  // them to the TypoExprs set. Remove them from Sema's TypoExpr list
7966  // since we don't want to clear them twice. Note: it's possible the
7967  // TypoExprs were created recursively and thus won't be in our
7968  // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
7969  auto &SemaTypoExprs = SemaRef.TypoExprs;
7970  for (auto TE : TypoExprs) {
7971  TransformCache.erase(TE);
7972  SemaRef.clearDelayedTypo(TE);
7973 
7974  auto SI = find(SemaTypoExprs, TE);
7975  if (SI != SemaTypoExprs.end()) {
7976  SemaTypoExprs.erase(SI);
7977  }
7978  }
7979  } else {
7980  // TypoExpr is valid: add newly created TypoExprs since we were
7981  // able to correct them.
7982  Res = RecurResult;
7983  SavedTypoExprs.set_union(TypoExprs);
7984  }
7985  }
7986 
7987  TypoExprs = std::move(SavedTypoExprs);
7988  AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
7989 
7990  return Res;
7991  }
7992 
7993  // Try to transform the given expression, looping through the correction
7994  // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
7995  //
7996  // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
7997  // true and this method immediately will return an `ExprError`.
7998  ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
7999  ExprResult Res;
8000  auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8001  SemaRef.TypoExprs.clear();
8002 
8003  while (true) {
8004  Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8005 
8006  // Recursion encountered an ambiguous correction. This means that our
8007  // correction itself is ambiguous, so stop now.
8008  if (IsAmbiguous)
8009  break;
8010 
8011  // If the transform is still valid after checking for any new typos,
8012  // it's good to go.
8013  if (!Res.isInvalid())
8014  break;
8015 
8016  // The transform was invalid, see if we have any TypoExprs with untried
8017  // correction candidates.
8018  if (!CheckAndAdvanceTypoExprCorrectionStreams())
8019  break;
8020  }
8021 
8022  // If we found a valid result, double check to make sure it's not ambiguous.
8023  if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8024  auto SavedTransformCache =
8025  llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8026 
8027  // Ensure none of the TypoExprs have multiple typo correction candidates
8028  // with the same edit length that pass all the checks and filters.
8029  while (!AmbiguousTypoExprs.empty()) {
8030  auto TE = AmbiguousTypoExprs.back();
8031 
8032  // TryTransform itself can create new Typos, adding them to the TypoExpr map
8033  // and invalidating our TypoExprState, so always fetch it instead of storing.
8034  SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8035 
8036  TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8037  TypoCorrection Next;
8038  do {
8039  // Fetch the next correction by erasing the typo from the cache and calling
8040  // `TryTransform` which will iterate through corrections in
8041  // `TransformTypoExpr`.
8042  TransformCache.erase(TE);
8043  ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8044 
8045  if (!AmbigRes.isInvalid() || IsAmbiguous) {
8046  SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8047  SavedTransformCache.erase(TE);
8048  Res = ExprError();
8049  IsAmbiguous = true;
8050  break;
8051  }
8052  } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8053  Next.getEditDistance(false) == TC.getEditDistance(false));
8054 
8055  if (IsAmbiguous)
8056  break;
8057 
8058  AmbiguousTypoExprs.remove(TE);
8059  SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8060  }
8061  TransformCache = std::move(SavedTransformCache);
8062  }
8063 
8064  // Wipe away any newly created TypoExprs that we don't know about. Since we
8065  // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8066  // possible if a `TypoExpr` is created during a transformation but then
8067  // fails before we can discover it.
8068  auto &SemaTypoExprs = SemaRef.TypoExprs;
8069  for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8070  auto TE = *Iterator;
8071  auto FI = find(TypoExprs, TE);
8072  if (FI != TypoExprs.end()) {
8073  Iterator++;
8074  continue;
8075  }
8076  SemaRef.clearDelayedTypo(TE);
8077  Iterator = SemaTypoExprs.erase(Iterator);
8078  }
8079  SemaRef.TypoExprs = std::move(SavedTypoExprs);
8080 
8081  return Res;
8082  }
8083 
8084 public:
8085  TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8086  : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8087 
8088  ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8089  MultiExprArg Args,
8090  SourceLocation RParenLoc,
8091  Expr *ExecConfig = nullptr) {
8092  auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8093  RParenLoc, ExecConfig);
8094  if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8095  if (Result.isUsable()) {
8096  Expr *ResultCall = Result.get();
8097  if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8098  ResultCall = BE->getSubExpr();
8099  if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8100  OverloadResolution[OE] = CE->getCallee();
8101  }
8102  }
8103  return Result;
8104  }
8105 
8106  ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8107 
8108  ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8109 
8110  ExprResult Transform(Expr *E) {
8111  bool IsAmbiguous = false;
8112  ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8113 
8114  if (!Res.isUsable())
8115  FindTypoExprs(TypoExprs).TraverseStmt(E);
8116 
8117  EmitAllDiagnostics(IsAmbiguous);
8118 
8119  return Res;
8120  }
8121 
8122  ExprResult TransformTypoExpr(TypoExpr *E) {
8123  // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8124  // cached transformation result if there is one and the TypoExpr isn't the
8125  // first one that was encountered.
8126  auto &CacheEntry = TransformCache[E];
8127  if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8128  return CacheEntry;
8129  }
8130 
8131  auto &State = SemaRef.getTypoExprState(E);
8132  assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8133 
8134  // For the first TypoExpr and an uncached TypoExpr, find the next likely
8135  // typo correction and return it.
8136  while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8137  if (InitDecl && TC.getFoundDecl() == InitDecl)
8138  continue;
8139  // FIXME: If we would typo-correct to an invalid declaration, it's
8140  // probably best to just suppress all errors from this typo correction.
8141  ExprResult NE = State.RecoveryHandler ?
8142  State.RecoveryHandler(SemaRef, E, TC) :
8143  attemptRecovery(SemaRef, *State.Consumer, TC);
8144  if (!NE.isInvalid()) {
8145  // Check whether there may be a second viable correction with the same
8146  // edit distance; if so, remember this TypoExpr may have an ambiguous
8147  // correction so it can be more thoroughly vetted later.
8148  TypoCorrection Next;
8149  if ((Next = State.Consumer->peekNextCorrection()) &&
8150  Next.getEditDistance(false) == TC.getEditDistance(false)) {
8151  AmbiguousTypoExprs.insert(E);
8152  } else {
8153  AmbiguousTypoExprs.remove(E);
8154  }
8155  assert(!NE.isUnset() &&
8156  "Typo was transformed into a valid-but-null ExprResult");
8157  return CacheEntry = NE;
8158  }
8159  }
8160  return CacheEntry = ExprError();
8161  }
8162 };
8163 }
8164 
8165 ExprResult
8167  llvm::function_ref<ExprResult(Expr *)> Filter) {
8168  // If the current evaluation context indicates there are uncorrected typos
8169  // and the current expression isn't guaranteed to not have typos, try to
8170  // resolve any TypoExpr nodes that might be in the expression.
8171  if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8172  (E->isTypeDependent() || E->isValueDependent() ||
8173  E->isInstantiationDependent())) {
8174  auto TyposResolved = DelayedTypos.size();
8175  auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8176  TyposResolved -= DelayedTypos.size();
8177  if (Result.isInvalid() || Result.get() != E) {
8178  ExprEvalContexts.back().NumTypos -= TyposResolved;
8179  return Result;
8180  }
8181  assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8182  }
8183  return E;
8184 }
8185 
8187  bool DiscardedValue,
8188  bool IsConstexpr) {
8189  ExprResult FullExpr = FE;
8190 
8191  if (!FullExpr.get())
8192  return ExprError();
8193 
8194  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
8195  return ExprError();
8196 
8197  if (DiscardedValue) {
8198  // Top-level expressions default to 'id' when we're in a debugger.
8199  if (getLangOpts().DebuggerCastResultToId &&
8200  FullExpr.get()->getType() == Context.UnknownAnyTy) {
8201  FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8202  if (FullExpr.isInvalid())
8203  return ExprError();
8204  }
8205 
8206  FullExpr = CheckPlaceholderExpr(FullExpr.get());
8207  if (FullExpr.isInvalid())
8208  return ExprError();
8209 
8210  FullExpr = IgnoredValueConversions(FullExpr.get());
8211  if (FullExpr.isInvalid())
8212  return ExprError();
8213 
8214  DiagnoseUnusedExprResult(FullExpr.get());
8215  }
8216 
8217  FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
8218  if (FullExpr.isInvalid())
8219  return ExprError();
8220 
8221  CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8222 
8223  // At the end of this full expression (which could be a deeply nested
8224  // lambda), if there is a potential capture within the nested lambda,
8225  // have the outer capture-able lambda try and capture it.
8226  // Consider the following code:
8227  // void f(int, int);
8228  // void f(const int&, double);
8229  // void foo() {
8230  // const int x = 10, y = 20;
8231  // auto L = [=](auto a) {
8232  // auto M = [=](auto b) {
8233  // f(x, b); <-- requires x to be captured by L and M
8234  // f(y, a); <-- requires y to be captured by L, but not all Ms
8235  // };
8236  // };
8237  // }
8238 
8239  // FIXME: Also consider what happens for something like this that involves
8240  // the gnu-extension statement-expressions or even lambda-init-captures:
8241  // void f() {
8242  // const int n = 0;
8243  // auto L = [&](auto a) {
8244  // +n + ({ 0; a; });
8245  // };
8246  // }
8247  //
8248  // Here, we see +n, and then the full-expression 0; ends, so we don't
8249  // capture n (and instead remove it from our list of potential captures),
8250  // and then the full-expression +n + ({ 0; }); ends, but it's too late
8251  // for us to see that we need to capture n after all.
8252 
8253  LambdaScopeInfo *const CurrentLSI =
8254  getCurLambda(/*IgnoreCapturedRegions=*/true);
8255  // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8256  // even if CurContext is not a lambda call operator. Refer to that Bug Report
8257  // for an example of the code that might cause this asynchrony.
8258  // By ensuring we are in the context of a lambda's call operator
8259  // we can fix the bug (we only need to check whether we need to capture
8260  // if we are within a lambda's body); but per the comments in that
8261  // PR, a proper fix would entail :
8262  // "Alternative suggestion:
8263  // - Add to Sema an integer holding the smallest (outermost) scope
8264  // index that we are *lexically* within, and save/restore/set to
8265  // FunctionScopes.size() in InstantiatingTemplate's
8266  // constructor/destructor.
8267  // - Teach the handful of places that iterate over FunctionScopes to
8268  // stop at the outermost enclosing lexical scope."
8269  DeclContext *DC = CurContext;
8270  while (DC && isa<CapturedDecl>(DC))
8271  DC = DC->getParent();
8272  const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8273  if (IsInLambdaDeclContext && CurrentLSI &&
8274  CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8276  *this);
8277  return MaybeCreateExprWithCleanups(FullExpr);
8278 }
8279 
8281  if (!FullStmt) return StmtError();
8282 
8283  return MaybeCreateStmtWithCleanups(FullStmt);
8284 }
8285 
8288  CXXScopeSpec &SS,
8289  const DeclarationNameInfo &TargetNameInfo) {
8290  DeclarationName TargetName = TargetNameInfo.getName();
8291  if (!TargetName)
8292  return IER_DoesNotExist;
8293 
8294  // If the name itself is dependent, then the result is dependent.
8295  if (TargetName.isDependentName())
8296  return IER_Dependent;
8297 
8298  // Do the redeclaration lookup in the current scope.
8299  LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8301  LookupParsedName(R, S, &SS);
8302  R.suppressDiagnostics();
8303 
8304  switch (R.getResultKind()) {
8305  case LookupResult::Found:
8309  return IER_Exists;
8310 
8312  return IER_DoesNotExist;
8313 
8315  return IER_Dependent;
8316  }
8317 
8318  llvm_unreachable("Invalid LookupResult Kind!");
8319 }
8320 
8323  bool IsIfExists, CXXScopeSpec &SS,
8324  UnqualifiedId &Name) {
8325  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8326 
8327  // Check for an unexpanded parameter pack.
8328  auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8329  if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8330  DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8331  return IER_Error;
8332 
8333  return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8334 }
8335 
8337  return BuildExprRequirement(E, /*IsSimple=*/true,
8338  /*NoexceptLoc=*/SourceLocation(),
8339  /*ReturnTypeRequirement=*/{});
8340 }
8341 
8344  SourceLocation NameLoc, IdentifierInfo *TypeName,
8345  TemplateIdAnnotation *TemplateId) {
8346  assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8347  "Exactly one of TypeName and TemplateId must be specified.");
8348  TypeSourceInfo *TSI = nullptr;
8349  if (TypeName) {
8350  QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8351  SS.getWithLocInContext(Context), *TypeName,
8352  NameLoc, &TSI, /*DeducedTypeContext=*/false);
8353  if (T.isNull())
8354  return nullptr;
8355  } else {
8356  ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8357  TemplateId->NumArgs);
8358  TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8359  TemplateId->TemplateKWLoc,
8360  TemplateId->Template, TemplateId->Name,
8361  TemplateId->TemplateNameLoc,
8362  TemplateId->LAngleLoc, ArgsPtr,
8363  TemplateId->RAngleLoc);
8364  if (T.isInvalid())
8365  return nullptr;
8366  if (GetTypeFromParser(T.get(), &TSI).isNull())
8367  return nullptr;
8368  }
8369  return BuildTypeRequirement(TSI);
8370 }
8371 
8374  return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8375  /*ReturnTypeRequirement=*/{});
8376 }
8377 
8380  Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8382  // C++2a [expr.prim.req.compound] p1.3.3
8383  // [..] the expression is deduced against an invented function template
8384  // F [...] F is a void function template with a single type template
8385  // parameter T declared with the constrained-parameter. Form a new
8386  // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8387  // around the constrained-parameter. F has a single parameter whose
8388  // type-specifier is cv T followed by the abstract-declarator. [...]
8389  //
8390  // The cv part is done in the calling function - we get the concept with
8391  // arguments and the abstract declarator with the correct CV qualification and
8392  // have to synthesize T and the single parameter of F.
8393  auto &II = Context.Idents.get("expr-type");
8395  SourceLocation(),
8396  SourceLocation(), Depth,
8397  /*Index=*/0, &II,
8398  /*Typename=*/true,
8399  /*ParameterPack=*/false,
8400  /*HasTypeConstraint=*/true);
8401 
8402  if (ActOnTypeConstraint(SS, TypeConstraint, TParam,
8403  /*EllpsisLoc=*/SourceLocation()))
8404  // Just produce a requirement with no type requirements.
8405  return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8406 
8408  SourceLocation(),
8409  ArrayRef<NamedDecl *>(TParam),
8410  SourceLocation(),
8411  /*RequiresClause=*/nullptr);
8412  return BuildExprRequirement(
8413  E, /*IsSimple=*/false, NoexceptLoc,
8415 }
8416 
8419  Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8420  concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8422  ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8423  if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8425  else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8427  else if (ReturnTypeRequirement.isSubstitutionFailure())
8429  else if (ReturnTypeRequirement.isTypeConstraint()) {
8430  // C++2a [expr.prim.req]p1.3.3
8431  // The immediately-declared constraint ([temp]) of decltype((E)) shall
8432  // be satisfied.
8433  TemplateParameterList *TPL =
8434  ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8435  QualType MatchedType =
8436  BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType();
8438  Args.push_back(TemplateArgument(MatchedType));
8440  MultiLevelTemplateArgumentList MLTAL(TAL);
8441  for (unsigned I = 0; I < TPL->getDepth(); ++I)
8442  MLTAL.addOuterRetainedLevel();
8443  Expr *IDC =
8444  cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
8445  ->getImmediatelyDeclaredConstraint();
8446  ExprResult Constraint = SubstExpr(IDC, MLTAL);
8447  assert(!Constraint.isInvalid() &&
8448  "Substitution cannot fail as it is simply putting a type template "
8449  "argument into a concept specialization expression's parameter.");
8450 
8451  SubstitutedConstraintExpr =
8452  cast<ConceptSpecializationExpr>(Constraint.get());
8453  if (!SubstitutedConstraintExpr->isSatisfied())
8455  }
8456  return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8457  ReturnTypeRequirement, Status,
8458  SubstitutedConstraintExpr);
8459 }
8460 
8463  concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8464  bool IsSimple, SourceLocation NoexceptLoc,
8465  concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8466  return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8467  IsSimple, NoexceptLoc,
8468  ReturnTypeRequirement);
8469 }
8470 
8473  return new (Context) concepts::TypeRequirement(Type);
8474 }
8475 
8479  return new (Context) concepts::TypeRequirement(SubstDiag);
8480 }
8481 
8483  return BuildNestedRequirement(Constraint);
8484 }
8485 
8488  ConstraintSatisfaction Satisfaction;
8489  if (!Constraint->isInstantiationDependent() &&
8490  CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
8491  Constraint->getSourceRange(), Satisfaction))
8492  return nullptr;
8493  return new (Context) concepts::NestedRequirement(Context, Constraint,
8494  Satisfaction);
8495 }
8496 
8500  return new (Context) concepts::NestedRequirement(SubstDiag);
8501 }
8502 
8505  ArrayRef<ParmVarDecl *> LocalParameters,
8506  Scope *BodyScope) {
8507  assert(BodyScope);
8508 
8510  RequiresKWLoc);
8511 
8512  PushDeclContext(BodyScope, Body);
8513 
8514  for (ParmVarDecl *Param : LocalParameters) {
8515  if (Param->hasDefaultArg())
8516  // C++2a [expr.prim.req] p4
8517  // [...] A local parameter of a requires-expression shall not have a
8518  // default argument. [...]
8519  Diag(Param->getDefaultArgRange().getBegin(),
8520  diag::err_requires_expr_local_parameter_default_argument);
8521  // Ignore default argument and move on
8522 
8523  Param->setDeclContext(Body);
8524  // If this has an identifier, add it to the scope stack.
8525  if (Param->getIdentifier()) {
8526  CheckShadow(BodyScope, Param);
8527  PushOnScopeChains(Param, BodyScope);
8528  }
8529  }
8530  return Body;
8531 }
8532 
8534  assert(CurContext && "DeclContext imbalance!");
8536  assert(CurContext && "Popped translation unit!");
8537 }
8538 
8539 ExprResult
8541  RequiresExprBodyDecl *Body,
8542  ArrayRef<ParmVarDecl *> LocalParameters,
8543  ArrayRef<concepts::Requirement *> Requirements,
8544  SourceLocation ClosingBraceLoc) {
8545  return RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
8546  Requirements, ClosingBraceLoc);
8547 }
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, tok::TokenKind &OpKind, SourceLocation OpLoc)
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:119
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:409
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable...
VariadicCallType
Definition: Sema.h:10527
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:276
QualType getCurrentThisType()
Try to retrieve the type of the &#39;this&#39; pointer.
This is the scope of a C++ try statement.
Definition: Scope.h:101
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:683
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:2517
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:559
Represents a function declaration or definition.
Definition: Decl.h:1783
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:7341
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true)
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:242
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ...
Definition: Overload.h:390
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2353
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:800
static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E)
SourceRange getCorrectionRange() const
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
no exception specification
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1874
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition: DeclSpec.cpp:135
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:15196
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
QualType getPointeeType() const
Definition: Type.h:2627
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2428
A (possibly-)qualified type.
Definition: Type.h:654
ASTConsumer & Consumer
Definition: Sema.h:386
bool isBlockPointerType() const
Definition: Type.h:6512
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:81
Simple class containing the result of Sema::CorrectTypo.
static bool IsSpecialDiscardedValue(Expr *E)
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2185
base_class_range bases()
Definition: DeclCXX.h:587
bool isArrayType() const
Definition: Type.h:6570
bool isMemberPointerType() const
Definition: Type.h:6552
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2919
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id)
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2702
static InitializedEntity InitializeException(SourceLocation ThrowLoc, QualType Type, bool NRVO)
Create the initialization entity for an exception object.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1018
A requires-expression requirement which queries the validity and properties of an expression (&#39;simple...
Definition: ExprConcepts.h:253
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2224
bool isMemberDataPointerType() const
Definition: Type.h:6563
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn&#39;t alre...
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3435
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:248
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static ConditionResult ConditionError()
Definition: Sema.h:11024
QualType CXXThisTypeOverride
When non-NULL, the C++ &#39;this&#39; expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:5612
bool isArithmeticType() const
Definition: Type.cpp:2036
Stmt - This represents one statement.
Definition: Stmt.h:66
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:988
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2689
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:4088
Provides information about an attempted template argument deduction, whose success or failure was des...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
Microsoft __if_not_exists.
Definition: Sema.h:7452
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:994
Vector conversions.
Definition: Overload.h:161
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2021
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:481
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2352
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:823
Microsoft&#39;s &#39;__super&#39; specifier, stored as a CXXRecordDecl* of the class it appeared in...
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization)
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:140
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:336
bool isRecordType() const
Definition: Type.h:6594
unsigned getTypeAlignIfKnown(QualType T) const
Return the ABI-specified alignment of a type, in bits, or 0 if the type is incomplete and we cannot d...
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, Optional< unsigned > NumExpanded=None)
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:556
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1958
static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Try to find a common type for two according to C++0x 5.16p5.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1411
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1305
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:6954
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4086
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
bool isVirtual() const
Definition: DeclCXX.h:1976
bool isExtVectorType() const
Definition: Type.h:6610
void setType(QualType t)
Definition: Expr.h:138
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:10601
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
Microsoft __if_exists.
Definition: Sema.h:7449
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
StringRef P
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1994
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6452
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:17915
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2918
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
The base class of the type hierarchy.
Definition: Type.h:1450
concepts::Requirement * ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId)
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:47
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:284
void setObjCGCAttr(GC type)
Definition: Type.h:308
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1174
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S)
Check if the current lambda has any potential captures that must be captured by any of its enclosing ...
static RequiresExpr * Create(ASTContext &C, SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef< ParmVarDecl *> LocalParameters, ArrayRef< concepts::Requirement *> Requirements, SourceLocation RBraceLoc)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:49
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1422
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:404
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent...
Definition: ExprCXX.h:2715
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:1932
Ambiguous candidates found.
Definition: Overload.h:59
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:138
QualType withConst() const
Definition: Type.h:826
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST...
Definition: Sema.h:10671
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
A container of type source information.
Definition: Type.h:6227
static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo *> Args, SourceLocation RParenLoc)
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6140
QualType getLogicalOperationType() const
The result type of logical operations, &#39;<&#39;, &#39;>&#39;, &#39;!=&#39;, etc.
Definition: ASTContext.h:1810
capture_const_range captures() const
Definition: DeclCXX.h:1019
Conversions between compatible types in C99.
Definition: Overload.h:155
constexpr XRayInstrMask Function
Definition: XRayInstr.h:38
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=CSK_unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:1955
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:1971
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2883
static CXXFunctionalCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, TypeSourceInfo *Written, CastKind Kind, Expr *Op, const CXXCastPath *Path, SourceLocation LPLoc, SourceLocation RPLoc)
Definition: ExprCXX.cpp:895
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1219
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2752
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2383
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:554
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:15519
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition: ScopeInfo.h:967
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2869
size_t param_size() const
Definition: Decl.h:2415
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2135
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Definition: Type.cpp:2241
An identifier, stored as an IdentifierInfo*.
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1968
This file provides some common utility functions for processing Lambda related AST Constructs...
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:124
RAII object that enters a new expression evaluation context.
Definition: Sema.h:12029
Represents a variable declaration or definition.
Definition: Decl.h:820
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool isStructureType() const
Definition: Type.cpp:495
bool hasPotentialThisCapture() const
Definition: ScopeInfo.h:918
ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
static ExprResult attemptRecovery(Sema &SemaRef, const TypoCorrectionConsumer &Consumer, const TypoCorrection &TC)
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition: Sema.h:4982
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:602
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1792
QualType getReturnType() const
Definition: Decl.h:2445
DiagnosticsEngine & Diags
Definition: Sema.h:387
static QualType adjustCVQualifiersForCXXThisWithinLambda(ArrayRef< FunctionScopeInfo *> FunctionScopes, QualType ThisTy, DeclContext *CurSemaContext, ASTContext &ASTCtx)
unsigned getNumParams() const
Definition: Type.h:3964
bool isEnumeralType() const
Definition: Type.h:6598
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3684
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init.ref]).
Definition: SemaInit.cpp:3450
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:2487
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:827
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3837
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
CUDAFunctionPreference
Definition: Sema.h:11339
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType)
Determine whether a type has new-extended alignment.
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1009
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:414
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:5849
bool isAmbiguous() const
Definition: Lookup.h:301
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
A namespace, stored as a NamespaceDecl*.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:395
bool isInvalidDecl() const
Definition: DeclBase.h:553
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
static InitializationKind CreateDirectList(SourceLocation InitLoc)
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:282
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:16151
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1140
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, QualType allocType)
Determine whether a given type is a class for which &#39;delete[]&#39; would call a member &#39;operator delete[]...
Represents a parameter to a function.
Definition: Decl.h:1595
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isUnset() const
Definition: Ownership.h:168
noexcept(expression), value-dependent
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2448
The collection of all-type qualifiers we support.
Definition: Type.h:143
Information about a template-id annotation token.
bool isXValue() const
Definition: Expr.h:260
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit=false)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType...
ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef< ParmVarDecl *> LocalParameters, ArrayRef< concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc)
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2281
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, TypeSourceInfo *Type, SourceLocation LParenLoc, ArrayRef< Expr *> Args, SourceLocation RParenLoc)
Definition: ExprCXX.cpp:1379
Expr * FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
Represents a struct/union/class.
Definition: Decl.h:3748
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:99
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:7587
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T)
Perform an "extended" implicit conversion as returned by TryClassUnification.
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:361
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1012
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:152
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3838
Represents a class template specialization, which refers to a class template with a given set of temp...
One of these records is kept for each identifier that is lexed.
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3644
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1063
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
void visitPotentialCaptures(llvm::function_ref< void(VarDecl *, Expr *)> Callback) const
Definition: ScopeInfo.cpp:232
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5165
Step
Definition: OpenMPClause.h:151
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:218
bool isConst() const
Definition: DeclCXX.h:1973
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:4081
Represents a class type in Objective C.
Definition: Type.h:5694
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
void DropFirstTypeObject()
Definition: DeclSpec.h:2241
A C++ nested-name-specifier augmented with source location information.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:8412
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:446
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1195
LineState State
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:517
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:344
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4080
A C-style cast.
Definition: Sema.h:10460
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:950
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:1981
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:275
Represents a member of a struct/union/class.
Definition: Decl.h:2729
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
The current expression is potentially evaluated at run time, which means that code may be generated t...
Identity conversion (no conversion)
Definition: Overload.h:107
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with &#39;::operator new(size_t)&#39; is g...
Definition: TargetInfo.h:555
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:780
bool isAbstractType(SourceLocation Loc, QualType T)
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:529
Floating point conversions (C++ [conv.double].
Definition: Overload.h:137
bool isReferenceType() const
Definition: Type.h:6516
CXXRecordDecl * getStdBadAlloc() const
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2712
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1244
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
static const TST TST_error
Definition: DeclSpec.h:310
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen)
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse &#39;nullptr&#39;.
static bool resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl< Expr *> &Args, bool &PassAlignment, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
A conditional (?:) operator.
Definition: Sema.h:10583
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:244
LookupResultKind getResultKind() const
Definition: Lookup.h:321
Expr * getSubExpr()
Definition: Expr.h:3202
ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:723
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:188
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:470
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:15279
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:6433
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
A user-defined literal name, e.g., operator "" _i.
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
IdentifierTable & Idents
Definition: ASTContext.h:580
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:100
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
bool isInvalidType() const
Definition: DeclSpec.h:2530
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
bool getProducesResult() const
Definition: Type.h:3580
DeclClass * getAsSingle() const
Definition: Lookup.h:507
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:128
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
bool isGLValue() const
Definition: Expr.h:261
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:997
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2984
Describes an C or C++ initializer list.
Definition: Expr.h:4403
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:764
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional< unsigned > DependentDeductionDepth=None, bool IgnoreConstraints=false)
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:71
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
ActOnCXXThrow - Parse throw expressions.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:960
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:54
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1817
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10878
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:527
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace...
Represents the results of name lookup.
Definition: Lookup.h:46
PtrTy get() const
Definition: Ownership.h:170
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1406
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:6929
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:140
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1866
Microsoft throw(...) extension.
Succeeded, but refers to a deleted function.
Definition: Overload.h:62
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10870
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2289
CanThrowResult canThrow(const Stmt *E)
ArrayTypeInfo Arr
Definition: DeclSpec.h:1545
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:414
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of &#39;this&#39; is actually available in the current context, if it is a potentially ev...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2220
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
StmtResult StmtError()
Definition: Ownership.h:280
Represents a declaration of a type.
Definition: Decl.h:3029
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3434
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6326
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:319
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion, integral conversion, floating point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, or boolean conversion.
Definition: Overload.h:267
QualType getExceptionObjectType(QualType T) const
A conversion for an operand of a builtin overloaded operator.
Definition: Sema.h:10466
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
const Type * getClass() const
Definition: Type.h:2867
bool isRValueReferenceType() const
Definition: Type.h:6524
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:10456
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over...
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:913
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:960
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:81
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:7750
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:1953
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
New-expression has a C++98 paren-delimited initializer.
Definition: ExprCXX.h:2157
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5978
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:122
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:139
ExprResult ActOnCXXThis(SourceLocation loc)
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3150
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:662
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1373
ArrayTypeTrait
Names for the array type traits.
Definition: TypeTraits.h:90
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1392
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1818
Preprocessor & PP
Definition: Sema.h:384
const LangOptions & getLangOpts() const
Definition: Sema.h:1324
static FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage)
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:928
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:691
bool isScalarType() const
Definition: Type.h:6866
An ordinary object is located at an address in memory.
Definition: Specifiers.h:141
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
The number of conversion kinds.
Definition: Overload.h:191
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1770
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:8441
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2291
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:6394
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5930
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:271
bool getNoReturn() const
Definition: Type.h:3579
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1124
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3034
ExprResult CheckUnevaluatedOperand(Expr *E)
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:142
Integral promotions (C++ [conv.prom])
Definition: Overload.h:125
const LangOptions & LangOpts
Definition: Sema.h:383
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
This object can be modified without requiring retains or releases.
Definition: Type.h:164
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
Represents the this expression in C++.
Definition: ExprCXX.h:1097
C-only conversion between pointers with incompatible types.
Definition: Overload.h:188
arg_iterator arg_end()
Definition: Expr.h:2747
New-expression has no initializer as written.
Definition: ExprCXX.h:2154
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type)
Create the initialization entity for an object allocated via new.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1612
TypeTrait
Names for traits that operate specifically on types.
Definition: TypeTraits.h:20
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
bool isArrayForm() const
Definition: ExprCXX.h:2386
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:8450
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1857
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3461
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7713
bool isHalfType() const
Definition: Type.h:6783
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:220
bool hasAttr() const
Definition: DeclBase.h:542
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3732
An error occurred.
Definition: Sema.h:4994
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:336
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2479
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1332
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:198
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1690
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:118
A functional-style cast.
Definition: Sema.h:10462
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2323
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:12839
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1163
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3501
Transparent Union Conversions.
Definition: Overload.h:173
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:158
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1998
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:583
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType...
Defines a function that returns the minimum OS versions supporting C++17&#39;s aligned allocation functio...
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:149
SourceRange getRange() const
Definition: DeclSpec.h:68
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:29
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:869
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
Check the use of the given variable as a C++ condition in an if, while, do-while, or switch statement...
TST getTypeSpecType() const
Definition: DeclSpec.h:479
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3401
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:151
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
unsigned hasStatic
True if this dimension included the &#39;static&#39; keyword.
Definition: DeclSpec.h:1230
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1430
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:2053
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1800
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:800
QualType getElementType() const
Definition: Type.h:2567
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4675
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:2923
This represents one expression.
Definition: Expr.h:108
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo *> Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition: ExprCXX.cpp:1718
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:122
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5224
static ExprResult BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, DeclAccessPair FoundDecl, bool HadMultipleCandidates, Expr *From)
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2827
Represents the body of a requires-expression.
Definition: DeclCXX.h:1909
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:50
bool isDeclScope(Decl *D)
isDeclScope - Return true if this is the scope that the specified decl is declared in...
Definition: Scope.h:323
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:396
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4022
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, SourceLocation KeyLoc, QualType T)
DeclContext * getEntity() const
Definition: Scope.h:327
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr *> ConstraintExprs, ArrayRef< TemplateArgument > TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a &#39;conjunction&#39;) given...
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1270
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion...
Definition: Overload.h:399
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
bool isObjCRetainableType() const
Definition: Type.cpp:4060
Inits[]
Definition: OpenMPClause.h:150
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5579
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2649
New-expression has a C++11 list-initializer.
Definition: ExprCXX.h:2160
static UsualDeallocFnInfo resolveDeallocationOverload(Sema &S, LookupResult &R, bool WantSize, bool WantAlign, llvm::SmallVectorImpl< UsualDeallocFnInfo > *BestFns=nullptr)
Select the correct "usual" deallocation function to use from a selection of deallocation functions (e...
const CXXScopeSpec * getSS() const
Definition: SemaInternal.h:200
Expr * getCallee()
Definition: Expr.h:2663
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2071
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:558
Zero constant to queue.
Definition: Overload.h:182
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Defines the clang::Preprocessor interface.
bool isNullPtrType() const
Definition: Type.h:6802
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:15007
#define bool
Definition: stdbool.h:15
bool isFileContext() const
Definition: DeclBase.h:1854
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:327
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:304
DeclContext * getDeclContext()
Definition: DeclBase.h:438
Overload resolution succeeded.
Definition: Overload.h:53
bool isAnyComplexType() const
Definition: Type.h:6602
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:14757
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:293
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:17987
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2681
Represents a C++ template name within the type system.
Definition: TemplateName.h:191
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7919
Defines the clang::TypeLoc interface and its subclasses.
int Depth
Definition: ASTDiff.cpp:190
A namespace alias, stored as a NamespaceAliasDecl*.
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:143
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1042
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:15344
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2589
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:739
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1928
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1117
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, QualType RhsT, SourceLocation KeyLoc)
QualType getType() const
Definition: Expr.h:137
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1698
ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a Microsoft __uuidof expression with a type operand.
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:621
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1180
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence...
Definition: Overload.h:552
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:257
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
void setAddressSpace(LangAS space)
Definition: Type.h:379
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
static void collectPublicBases(CXXRecordDecl *RD, llvm::DenseMap< CXXRecordDecl *, unsigned > &SubobjectsSeen, llvm::SmallPtrSetImpl< CXXRecordDecl *> &VBases, llvm::SetVector< CXXRecordDecl *> &PublicSubobjectsSeen, bool ParentIsPublic)
A boolean condition, from &#39;if&#39;, &#39;while&#39;, &#39;for&#39;, or &#39;do&#39;.
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:950
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:64
QualType getRecordType(const RecordDecl *Decl) const
bool isInvalid() const
Definition: Ownership.h:166
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:2046
static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, QualType T, Expr *DimExpr, SourceLocation KeyLoc)
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1401
Represents a GCC generic vector type.
Definition: Type.h:3235
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2580
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
Definition: SemaExprCXX.cpp:49
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1091
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:16790
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4833
static bool isValidVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6925
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1430
The symbol exists.
Definition: Sema.h:4984
ValueDecl * getDecl()
Definition: Expr.h:1247
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ &#39;delete&#39; expression.
bool isUsable() const
Definition: Ownership.h:167
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2713
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1417
The result type of a method or function.
TemplateParameterList * getTypeConstraintTemplateParameterList() const
Definition: ExprConcepts.h:320
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2122
bool isUnionType() const
Definition: Type.cpp:527
const Expr * getSubExpr() const
Definition: ExprCXX.h:1396
void removeLocalCVRQualifiers(unsigned Mask)
Definition: Type.h:6362
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1251
bool hasEmptyCollections() const
Are the empty collection symbols available?
Definition: ObjCRuntime.h:419
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:283
concepts::ExprRequirement * BuildExprRequirement(Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional< Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause)
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6289
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:126
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:421
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3604
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen)
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:110
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3848
bool isVoidPointerType() const
Definition: Type.cpp:521
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6315
RecordDecl * getDecl() const
Definition: Type.h:4505
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr *> Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8693
noexcept(expression), evals to &#39;false&#39;
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
void EraseUnwantedCUDAMatches(const FunctionDecl *Caller, SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl *>> &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:213
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
Expr * getArgument()
Definition: ExprCXX.h:2401
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1590
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:217
void MarkThisReferenced(CXXThisExpr *This)
CanThrowResult
Possible results from evaluation of a noexcept expression.
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
CanQualType OverloadTy
Definition: ASTContext.h:1045
There is no lifetime qualification on this type.
Definition: Type.h:160
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:1075
llvm::cl::opt< std::string > Filter
Integral conversions (C++ [conv.integral])
Definition: Overload.h:134
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1053
Complex promotions (Clang extension)
Definition: Overload.h:131
#define false
Definition: stdbool.h:17
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:171
Kind
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1011
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:513
QualType getCanonicalType() const
Definition: Type.h:6295
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope)
not a target-specific vector type
Definition: Type.h:3239
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3813
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we&#39;re currently inside an ObjC method...
Definition: SemaExpr.cpp:2743
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:200
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:769
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:917
ASTContext & getASTContext() const
Definition: Sema.h:1331
concepts::Requirement * ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc)
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1231
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3743
Encodes a location in the source.
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
Definition: ASTContext.h:2210
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4521
llvm::APSInt APSInt
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:6379
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6377
Represents a C++ temporary.
Definition: ExprCXX.h:1341
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2166
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:797
enum clang::DeclaratorChunk::@219 Kind
CastKind getCastKind() const
Definition: Expr.h:3196
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2383
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name)
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:2100
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
DeclarationName getName() const
getName - Returns the embedded declaration name.
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:273
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:171
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9679
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:74
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:914
A vector splat from an arithmetic type.
Definition: Overload.h:164
bool isUsualDeallocationFunction(SmallVectorImpl< const FunctionDecl *> &PreventedBy) const
Determine whether this is a usual deallocation function (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or delete[] operator with a particular signature.
Definition: DeclCXX.cpp:2183
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:139
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1844
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
const LookupResult & getLookupResult() const
Definition: SemaInternal.h:197
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1346
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2466
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:590
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
No ref-qualifier was provided.
Definition: Type.h:1403
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:5729
CanQualType FloatTy
Definition: ASTContext.h:1028
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1354
Objective-C ARC writeback conversion.
Definition: Overload.h:176
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2422
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:10469
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CanQualType VoidTy
Definition: ASTContext.h:1016
bool isArray() const
Definition: ExprCXX.h:2223
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:24
Describes the kind of initialization being performed, along with location information for tokens rela...
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
static void getUnambiguousPublicSubobjects(CXXRecordDecl *RD, llvm::SmallVectorImpl< CXXRecordDecl *> &Objects)
Look up any declaration with any name.
Definition: Sema.h:3477
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:8614
bool isMemberFunctionPointerType() const
Definition: Type.h:6556
bool isAnyPointerType() const
Definition: Type.h:6508
bool isObjCObjectPointerType() const
Definition: Type.h:6618
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:15779
llvm::APInt APInt
Definition: Integral.h:27
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:146
const TypoExprState & getTypoExprState(TypoExpr *TE) const
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax...
Definition: Overload.h:907
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3274
static bool VariableCanNeverBeAConstantExpression(VarDecl *Var, ASTContext &Context)
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1174
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:258
Requests that all candidates be shown.
Definition: Overload.h:68
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:207
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1824
No entity found met the criteria.
Definition: Lookup.h:50
TypeClass getTypeClass() const
Definition: Type.h:1876
bool isThisOutsideMemberFunctionBody(QualType BaseType)
Determine whether the given type is the type of *this that is used outside of the body of a member fu...
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2020
The name is a dependent name, so the results will differ from one instantiation to the next...
Definition: Sema.h:4991
An expression trait intrinsic.
Definition: ExprCXX.h:2785
EnumDecl * getDecl() const
Definition: Type.h:4528
RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef< ParmVarDecl *> LocalParameters, Scope *BodyScope)
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:158
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:145
bool isVectorType() const
Definition: Type.h:6606
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:167
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1409
Assigning into this object requires a lifetime extension.
Definition: Type.h:177
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3954
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:124
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:896
Constant expression in a noptr-new-declarator.
Definition: Sema.h:3009
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
ActOnCXXNew - Parsed a C++ &#39;new&#39; expression.
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, SourceLocation Loc, QualType ArgTy)
Check the completeness of a type in a unary type trait.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2345
QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:224
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
A POD class for pairing a NamedDecl* with an access specifier.
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose=true)
Checks access to an overloaded operator new or delete.
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists), where Base is an expression of class type and Member is the name of the member we&#39;re trying to find.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6751
The scope of a struct/union/class definition.
Definition: Scope.h:65
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1930
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array&#39;s size can require, which limits the maximu...
Definition: Type.cpp:174
Represents a template argument.
Definition: TemplateBase.h:50
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9608
static const TST TST_decltype_auto
Definition: DeclSpec.h:301
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
This file provides some common utility functions for processing Lambdas.
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:328
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2672
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:3020
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1427
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1808
ExtInfo getExtInfo() const
Definition: Type.h:3691
not evaluated yet, for special member function
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef< QualType > Params)
DeclareGlobalAllocationFunction - Declares a single implicit global allocation function if it doesn&#39;t...
CanQualType NullPtrTy
Definition: ASTContext.h:1044
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2359
llvm::SmallVector< TypoExpr *, 2 > TypoExprs
Holds TypoExprs that are created from createDelayedTypo.
Definition: Sema.h:423
static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, Expr *Init)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:402
static void noteOperatorArrows(Sema &S, ArrayRef< FunctionDecl *> OperatorArrows)
Note a set of &#39;operator->&#39; functions that were used for a member access.
static const TST TST_decltype
Definition: DeclSpec.h:300
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:228
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:529
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:223
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
Optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo *> FunctionScopes, VarDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:173
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
AccessSpecifier getAccess() const
Definition: DeclBase.h:473
Conversions allowed in C, but not C++.
Definition: Overload.h:185
A constant boolean condition from &#39;if constexpr&#39;.
void ActOnFinishRequiresExpr()
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:113
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2444
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared...
Definition: Sema.h:987
The name of a declaration.
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:382
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:990
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2046
bool isBooleanType() const
Definition: Type.h:6894
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1297
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6704
AllocationFunctionScope
The scope in which to find allocation functions.
Definition: Sema.h:5724
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2833
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2260
IdentifierResolver IdResolver
Definition: Sema.h:901
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type. ...
Definition: Type.cpp:2091
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:586
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1499
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
A type that was preceded by the &#39;template&#39; keyword, stored as a Type*.
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4252
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr *> Args, SmallVectorImpl< Expr *> &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5262
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1237
bool hasCVRQualifiers() const
Definition: Type.h:275
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2995
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Definition: Sema.h:658
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:404
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression&#39;s result is syntactically ignored, perform any conversions that are required.
Represents a pointer to an Objective C object.
Definition: Type.h:5951
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:3958
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
Pointer to a block type.
Definition: Type.h:2716
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
static void DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, const MismatchingNewDeleteDetector &Detector)
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2410
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:83
bool isIncompleteArrayType() const
Definition: Type.h:6578
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4495
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
Complex values, per C99 6.2.5p11.
Definition: Type.h:2554
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1013
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
The lookup is a reference to this name that is not for the purpose of redeclaring the name...
Definition: Sema.h:3485
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:162
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2155
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6811
Look for allocation functions in both the global scope and in the scope of the allocated class...
Definition: Sema.h:5732
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1084
arg_iterator arg_begin()
Definition: Expr.h:2744
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2108
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
CanQualType DependentTy
Definition: ASTContext.h:1045
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
bool isFunctionType() const
Definition: Type.h:6500
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled=true)
Introduce a new scope where &#39;this&#39; may be allowed (when enabled), using the given declaration (which ...
QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:8471
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2321
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1112
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl)
Checks access to an overloaded member operator, including conversion operators.
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={})
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
The template argument is a type.
Definition: TemplateBase.h:59
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
Block Pointer conversions.
Definition: Overload.h:170
Holds information about the various types of exception specification.
Definition: Type.h:3811
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1524
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
The "class" keyword.
Definition: Type.h:5198
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2915
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
SmallVector< BlockDecl *, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:607
Represents a base class of a C++ class.
Definition: DeclCXX.h:145
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:144
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2716
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr *> Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
Capture & getCXXThisCapture()
Retrieve the capture of C++ &#39;this&#39;, if it has been captured.
Definition: ScopeInfo.h:682
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:1931
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2104
Condition in a constexpr if statement.
Definition: Sema.h:3010
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3816
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2115
static void getUuidAttrOfType(Sema &SemaRef, QualType QT, llvm::SmallSetVector< const UuidAttr *, 1 > &UuidAttrs)
Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to a single GUID...
bool isClassType() const
Definition: Type.cpp:489
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, SourceLocation QuestionLoc, bool &HaveConversion, QualType &ToType)
Try to convert a type to another according to C++11 5.16p3.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2305
EnumDecl * getStdAlignValT() const
A template argument list.
Definition: DeclTemplate.h:239
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
bool isLValueReferenceType() const
Definition: Type.h:6520
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:2925
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, and if so, remove it from the list of volatile-qualified assignments that we are going to warn are deprecated.
Definition: SemaExpr.cpp:15263
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:403
Reading or writing from this object requires a barrier call.
Definition: Type.h:174
An integral condition for a &#39;switch&#39; statement.
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:694
QualType getParamType(unsigned i) const
Definition: Type.h:3966
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:116
bool Failed() const
Determine whether the initialization sequence is invalid.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2836
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
Describes the sequence of initializations required to initialize a given object or reference with a s...
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
ActionResult< Expr * > ExprResult
Definition: Ownership.h:263
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6336
Only look for allocation functions in the global scope.
Definition: Sema.h:5726
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
Compatible - the types are compatible according to the standard.
Definition: Sema.h:10603
bool isValid() const
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr *> &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo *> Args, SourceLocation RParenLoc)
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6777
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:402
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3181
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3808
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1006
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1238
static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, Sema &Self, SourceLocation KeyLoc, ASTContext &C, bool(CXXRecordDecl::*HasTrivial)() const, bool(CXXRecordDecl::*HasNonTrivial)() const, bool(CXXMethodDecl::*IsDesiredOp)() const)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6283
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that&#39;s ...
Represents the specialization of a concept - evaluates to a prvalue of type bool. ...
Definition: ExprConcepts.h:40
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R)
Checks that a type is suitable as the allocated type in a new-expression.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1895
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=None, OverloadCandidateParamOrder PO={})
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:397
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:679
bool isRValue() const
Definition: Expr.h:259
Declaration of a class template.
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4016
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:476
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2465
void addAttr(Attr *A)
Definition: DeclBase.cpp:832
SourceManager & getSourceManager() const
Definition: Sema.h:1329
iterator end() const
Definition: Lookup.h:336
A template-id, e.g., f<int>.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:263
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1327
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1711
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2546
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion)
type checking for vector binary operators.
Definition: SemaExpr.cpp:9130
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:160
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3868
ExprResult ExprError()
Definition: Ownership.h:279
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type...
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
unsigned getNumElements() const
Definition: Type.h:3271
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:6467
Microsoft __declspec(nothrow) extension.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2150
static bool canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, QualType DestructedType)
Check if it&#39;s ok to try and recover dot pseudo destructor calls on pointer objects.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1171
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:825
bool isUnion() const
Definition: Decl.h:3407
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4996
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2259
bool isPointerType() const
Definition: Type.h:6504
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:179
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: Type.h:366
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion...
Definition: Overload.h:261
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
No viable function found.
Definition: Overload.h:56
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
QualType getType() const
Definition: Decl.h:630
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:129
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
bool isFloatingType() const
Definition: Type.cpp:2005
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:385
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1531
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we&#39;re implicitly casting from a _Nullable pointer type to a _Nonnull one. ...
Definition: Sema.cpp:487
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:17398
This represents a decl that may have a name.
Definition: Decl.h:223
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:645
Expr * getRepAsExpr() const
Definition: DeclSpec.h:497
CanQualType BoolTy
Definition: ASTContext.h:1017
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression&#39;s return type is complete.
Definition: SemaExpr.cpp:17270
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1000
No keyword precedes the qualified type name.
Definition: Type.h:5227
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1882
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13460
iterator begin() const
Definition: Lookup.h:335
bool isInterfaceType() const
Definition: Type.cpp:507
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:149
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:606
Describes an entity that is being initialized.
unsigned NumArgs
NumArgs - The number of template arguments.
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr *> Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:370
The global specifier &#39;::&#39;. There is no stored value.
Decl * getCalleeDecl()
Definition: Expr.h:2675
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, bool IsDelete, FunctionDecl *&Operator)
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3242
ctor_range ctors() const
Definition: DeclCXX.h:649
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
SourceLocation getBegin() const
AssignmentAction
Definition: Sema.h:2894
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:724
void WillReplaceSpecifier(bool ForceReplacement)
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2935
This scope corresponds to an Objective-C method body.
Definition: Scope.h:95
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3843
The symbol does not exist.
Definition: Sema.h:4987
Declaration of a template function.
Definition: DeclTemplate.h:977
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
Attr - This represents one attribute.
Definition: Attr.h:45
SourceLocation getLocation() const
Definition: DeclBase.h:429
QualType getPointeeType() const
Definition: Type.h:2853
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5432
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6238
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3344
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
noexcept(expression), evals to &#39;true&#39;
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef< Expr *> PlacementArgs, SourceRange TypeIdParens, Optional< Expr *> ArraySize, InitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange)
Create a c++ new expression.
Definition: ExprCXX.cpp:258
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1364
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form, which contains extra information on the evaluated value of the initializer.
Definition: Decl.cpp:2342
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2991
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type...
const FormatStyle & Style
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:8481
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1080
Structure used to store a statement, the constant value to which it was evaluated (if any)...
Definition: Decl.h:784
A RAII object to temporarily push a declaration context.
Definition: Sema.h:797
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:6478
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5967
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:256