clang  8.0.0svn
SemaExprCXX.cpp
Go to the documentation of this file.
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// Implements semantic analysis for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14 
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) {
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  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
458  SourceRange(TypeidLoc, RParenLoc));
459 }
460 
461 /// Build a C++ typeid expression with an expression operand.
463  SourceLocation TypeidLoc,
464  Expr *E,
465  SourceLocation RParenLoc) {
466  bool WasEvaluated = false;
467  if (E && !E->isTypeDependent()) {
468  if (E->getType()->isPlaceholderType()) {
469  ExprResult result = CheckPlaceholderExpr(E);
470  if (result.isInvalid()) return ExprError();
471  E = result.get();
472  }
473 
474  QualType T = E->getType();
475  if (const RecordType *RecordT = T->getAs<RecordType>()) {
476  CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
477  // C++ [expr.typeid]p3:
478  // [...] If the type of the expression is a class type, the class
479  // shall be completely-defined.
480  if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
481  return ExprError();
482 
483  // C++ [expr.typeid]p3:
484  // When typeid is applied to an expression other than an glvalue of a
485  // polymorphic class type [...] [the] expression is an unevaluated
486  // operand. [...]
487  if (RecordD->isPolymorphic() && E->isGLValue()) {
488  // The subexpression is potentially evaluated; switch the context
489  // and recheck the subexpression.
490  ExprResult Result = TransformToPotentiallyEvaluated(E);
491  if (Result.isInvalid()) return ExprError();
492  E = Result.get();
493 
494  // We require a vtable to query the type at run time.
495  MarkVTableUsed(TypeidLoc, RecordD);
496  WasEvaluated = true;
497  }
498  }
499 
500  // C++ [expr.typeid]p4:
501  // [...] If the type of the type-id is a reference to a possibly
502  // cv-qualified type, the result of the typeid expression refers to a
503  // std::type_info object representing the cv-unqualified referenced
504  // type.
505  Qualifiers Quals;
506  QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
507  if (!Context.hasSameType(T, UnqualT)) {
508  T = UnqualT;
509  E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
510  }
511  }
512 
513  if (E->getType()->isVariablyModifiedType())
514  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
515  << E->getType());
516  else if (!inTemplateInstantiation() &&
517  E->HasSideEffects(Context, WasEvaluated)) {
518  // The expression operand for typeid is in an unevaluated expression
519  // context, so side effects could result in unintended consequences.
520  Diag(E->getExprLoc(), WasEvaluated
521  ? diag::warn_side_effects_typeid
522  : diag::warn_side_effects_unevaluated_context);
523  }
524 
525  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
526  SourceRange(TypeidLoc, RParenLoc));
527 }
528 
529 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
532  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
533  // OpenCL C++ 1.0 s2.9: typeid is not supported.
534  if (getLangOpts().OpenCLCPlusPlus) {
535  return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
536  << "typeid");
537  }
538 
539  // Find the std::type_info type.
540  if (!getStdNamespace())
541  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
542 
543  if (!CXXTypeInfoDecl) {
544  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
545  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
546  LookupQualifiedName(R, getStdNamespace());
547  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
548  // Microsoft's typeinfo doesn't have type_info in std but in the global
549  // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
550  if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
551  LookupQualifiedName(R, Context.getTranslationUnitDecl());
552  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
553  }
554  if (!CXXTypeInfoDecl)
555  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
556  }
557 
558  if (!getLangOpts().RTTI) {
559  return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
560  }
561 
562  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
563 
564  if (isType) {
565  // The operand is a type; handle it as such.
566  TypeSourceInfo *TInfo = nullptr;
567  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
568  &TInfo);
569  if (T.isNull())
570  return ExprError();
571 
572  if (!TInfo)
573  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
574 
575  return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
576  }
577 
578  // The operand is an expression.
579  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
580 }
581 
582 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
583 /// a single GUID.
584 static void
587  // Optionally remove one level of pointer, reference or array indirection.
588  const Type *Ty = QT.getTypePtr();
589  if (QT->isPointerType() || QT->isReferenceType())
590  Ty = QT->getPointeeType().getTypePtr();
591  else if (QT->isArrayType())
592  Ty = Ty->getBaseElementTypeUnsafe();
593 
594  const auto *TD = Ty->getAsTagDecl();
595  if (!TD)
596  return;
597 
598  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
599  UuidAttrs.insert(Uuid);
600  return;
601  }
602 
603  // __uuidof can grab UUIDs from template arguments.
604  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
605  const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
606  for (const TemplateArgument &TA : TAL.asArray()) {
607  const UuidAttr *UuidForTA = nullptr;
608  if (TA.getKind() == TemplateArgument::Type)
609  getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
610  else if (TA.getKind() == TemplateArgument::Declaration)
611  getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
612 
613  if (UuidForTA)
614  UuidAttrs.insert(UuidForTA);
615  }
616  }
617 }
618 
619 /// Build a Microsoft __uuidof expression with a type operand.
621  SourceLocation TypeidLoc,
622  TypeSourceInfo *Operand,
623  SourceLocation RParenLoc) {
624  StringRef UuidStr;
625  if (!Operand->getType()->isDependentType()) {
627  getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
628  if (UuidAttrs.empty())
629  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
630  if (UuidAttrs.size() > 1)
631  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
632  UuidStr = UuidAttrs.back()->getGuid();
633  }
634 
635  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
636  SourceRange(TypeidLoc, RParenLoc));
637 }
638 
639 /// Build a Microsoft __uuidof expression with an expression operand.
641  SourceLocation TypeidLoc,
642  Expr *E,
643  SourceLocation RParenLoc) {
644  StringRef UuidStr;
645  if (!E->getType()->isDependentType()) {
647  UuidStr = "00000000-0000-0000-0000-000000000000";
648  } else {
650  getUuidAttrOfType(*this, E->getType(), UuidAttrs);
651  if (UuidAttrs.empty())
652  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
653  if (UuidAttrs.size() > 1)
654  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
655  UuidStr = UuidAttrs.back()->getGuid();
656  }
657  }
658 
659  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
660  SourceRange(TypeidLoc, RParenLoc));
661 }
662 
663 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
666  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
667  // If MSVCGuidDecl has not been cached, do the lookup.
668  if (!MSVCGuidDecl) {
669  IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
670  LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
671  LookupQualifiedName(R, Context.getTranslationUnitDecl());
672  MSVCGuidDecl = R.getAsSingle<RecordDecl>();
673  if (!MSVCGuidDecl)
674  return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
675  }
676 
677  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
678 
679  if (isType) {
680  // The operand is a type; handle it as such.
681  TypeSourceInfo *TInfo = nullptr;
682  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
683  &TInfo);
684  if (T.isNull())
685  return ExprError();
686 
687  if (!TInfo)
688  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
689 
690  return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
691  }
692 
693  // The operand is an expression.
694  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
695 }
696 
697 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
700  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
701  "Unknown C++ Boolean value!");
702  return new (Context)
703  CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
704 }
705 
706 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
709  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
710 }
711 
712 /// ActOnCXXThrow - Parse throw expressions.
715  bool IsThrownVarInScope = false;
716  if (Ex) {
717  // C++0x [class.copymove]p31:
718  // When certain criteria are met, an implementation is allowed to omit the
719  // copy/move construction of a class object [...]
720  //
721  // - in a throw-expression, when the operand is the name of a
722  // non-volatile automatic object (other than a function or catch-
723  // clause parameter) whose scope does not extend beyond the end of the
724  // innermost enclosing try-block (if there is one), the copy/move
725  // operation from the operand to the exception object (15.1) can be
726  // omitted by constructing the automatic object directly into the
727  // exception object
728  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
729  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
730  if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
731  for( ; S; S = S->getParent()) {
732  if (S->isDeclScope(Var)) {
733  IsThrownVarInScope = true;
734  break;
735  }
736 
737  if (S->getFlags() &
741  break;
742  }
743  }
744  }
745  }
746 
747  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
748 }
749 
751  bool IsThrownVarInScope) {
752  // Don't report an error if 'throw' is used in system headers.
753  if (!getLangOpts().CXXExceptions &&
754  !getSourceManager().isInSystemHeader(OpLoc) &&
755  (!getLangOpts().OpenMPIsDevice ||
756  !getLangOpts().OpenMPHostCXXExceptions ||
757  isInOpenMPTargetExecutionDirective() ||
758  isInOpenMPDeclareTargetContext()))
759  Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
760 
761  // Exceptions aren't allowed in CUDA device code.
762  if (getLangOpts().CUDA)
763  CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764  << "throw" << CurrentCUDATarget();
765 
766  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767  Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768 
769  if (Ex && !Ex->isTypeDependent()) {
770  QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771  if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
772  return ExprError();
773 
774  // Initialize the exception result. This implicitly weeds out
775  // abstract types or types with inaccessible copy constructors.
776 
777  // C++0x [class.copymove]p31:
778  // When certain criteria are met, an implementation is allowed to omit the
779  // copy/move construction of a class object [...]
780  //
781  // - in a throw-expression, when the operand is the name of a
782  // non-volatile automatic object (other than a function or
783  // catch-clause
784  // parameter) whose scope does not extend beyond the end of the
785  // innermost enclosing try-block (if there is one), the copy/move
786  // operation from the operand to the exception object (15.1) can be
787  // omitted by constructing the automatic object directly into the
788  // exception object
789  const VarDecl *NRVOVariable = nullptr;
790  if (IsThrownVarInScope)
791  NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
792 
794  OpLoc, ExceptionObjectTy,
795  /*NRVO=*/NRVOVariable != nullptr);
796  ExprResult Res = PerformMoveOrCopyInitialization(
797  Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798  if (Res.isInvalid())
799  return ExprError();
800  Ex = Res.get();
801  }
802 
803  return new (Context)
804  CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
805 }
806 
807 static void
809  llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810  llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811  llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812  bool ParentIsPublic) {
813  for (const CXXBaseSpecifier &BS : RD->bases()) {
814  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815  bool NewSubobject;
816  // Virtual bases constitute the same subobject. Non-virtual bases are
817  // always distinct subobjects.
818  if (BS.isVirtual())
819  NewSubobject = VBases.insert(BaseDecl).second;
820  else
821  NewSubobject = true;
822 
823  if (NewSubobject)
824  ++SubobjectsSeen[BaseDecl];
825 
826  // Only add subobjects which have public access throughout the entire chain.
827  bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828  if (PublicPath)
829  PublicSubobjectsSeen.insert(BaseDecl);
830 
831  // Recurse on to each base subobject.
832  collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833  PublicPath);
834  }
835 }
836 
839  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842  SubobjectsSeen[RD] = 1;
843  PublicSubobjectsSeen.insert(RD);
844  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845  /*ParentIsPublic=*/true);
846 
847  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848  // Skip ambiguous objects.
849  if (SubobjectsSeen[PublicSubobject] > 1)
850  continue;
851 
852  Objects.push_back(PublicSubobject);
853  }
854 }
855 
856 /// CheckCXXThrowOperand - Validate the operand of a throw.
858  QualType ExceptionObjectTy, Expr *E) {
859  // If the type of the exception would be an incomplete type or a pointer
860  // to an incomplete type other than (cv) void the program is ill-formed.
861  QualType Ty = ExceptionObjectTy;
862  bool isPointer = false;
863  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
864  Ty = Ptr->getPointeeType();
865  isPointer = true;
866  }
867  if (!isPointer || !Ty->isVoidType()) {
868  if (RequireCompleteType(ThrowLoc, Ty,
869  isPointer ? diag::err_throw_incomplete_ptr
870  : diag::err_throw_incomplete,
871  E->getSourceRange()))
872  return true;
873 
874  if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
875  diag::err_throw_abstract_type, E))
876  return true;
877  }
878 
879  // If the exception has class type, we need additional handling.
880  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881  if (!RD)
882  return false;
883 
884  // If we are throwing a polymorphic class type or pointer thereof,
885  // exception handling will make use of the vtable.
886  MarkVTableUsed(ThrowLoc, RD);
887 
888  // If a pointer is thrown, the referenced object will not be destroyed.
889  if (isPointer)
890  return false;
891 
892  // If the class has a destructor, we must be able to call it.
893  if (!RD->hasIrrelevantDestructor()) {
894  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895  MarkFunctionReferenced(E->getExprLoc(), Destructor);
896  CheckDestructorAccess(E->getExprLoc(), Destructor,
897  PDiag(diag::err_access_dtor_exception) << Ty);
898  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
899  return true;
900  }
901  }
902 
903  // The MSVC ABI creates a list of all types which can catch the exception
904  // object. This list also references the appropriate copy constructor to call
905  // if the object is caught by value and has a non-trivial copy constructor.
906  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
907  // We are only interested in the public, unambiguous bases contained within
908  // the exception object. Bases which are ambiguous or otherwise
909  // inaccessible are not catchable types.
910  llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911  getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
912 
913  for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
914  // Attempt to lookup the copy constructor. Various pieces of machinery
915  // will spring into action, like template instantiation, which means this
916  // cannot be a simple walk of the class's decls. Instead, we must perform
917  // lookup and overload resolution.
918  CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919  if (!CD)
920  continue;
921 
922  // Mark the constructor referenced as it is used by this throw expression.
923  MarkFunctionReferenced(E->getExprLoc(), CD);
924 
925  // Skip this copy constructor if it is trivial, we don't need to record it
926  // in the catchable type data.
927  if (CD->isTrivial())
928  continue;
929 
930  // The copy constructor is non-trivial, create a mapping from this class
931  // type to this constructor.
932  // N.B. The selection of copy constructor is not sensitive to this
933  // particular throw-site. Lookup will be performed at the catch-site to
934  // ensure that the copy constructor is, in fact, accessible (via
935  // friendship or any other means).
936  Context.addCopyConstructorForExceptionObject(Subobject, CD);
937 
938  // We don't keep the instantiated default argument expressions around so
939  // we must rebuild them here.
940  for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
941  if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942  return true;
943  }
944  }
945  }
946 
947  return false;
948 }
949 
951  ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952  DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953 
954  QualType ClassType = ThisTy->getPointeeType();
955  LambdaScopeInfo *CurLSI = nullptr;
956  DeclContext *CurDC = CurSemaContext;
957 
958  // Iterate through the stack of lambdas starting from the innermost lambda to
959  // the outermost lambda, checking if '*this' is ever captured by copy - since
960  // that could change the cv-qualifiers of the '*this' object.
961  // The object referred to by '*this' starts out with the cv-qualifiers of its
962  // member function. We then start with the innermost lambda and iterate
963  // outward checking to see if any lambda performs a by-copy capture of '*this'
964  // - and if so, any nested lambda must respect the 'constness' of that
965  // capturing lamdbda's call operator.
966  //
967 
968  // Since the FunctionScopeInfo stack is representative of the lexical
969  // nesting of the lambda expressions during initial parsing (and is the best
970  // place for querying information about captures about lambdas that are
971  // partially processed) and perhaps during instantiation of function templates
972  // that contain lambda expressions that need to be transformed BUT not
973  // necessarily during instantiation of a nested generic lambda's function call
974  // operator (which might even be instantiated at the end of the TU) - at which
975  // time the DeclContext tree is mature enough to query capture information
976  // reliably - we use a two pronged approach to walk through all the lexically
977  // enclosing lambda expressions:
978  //
979  // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980  // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981  // enclosed by the call-operator of the LSI below it on the stack (while
982  // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983  // the stack represents the innermost lambda.
984  //
985  // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986  // represents a lambda's call operator. If it does, we must be instantiating
987  // a generic lambda's call operator (represented by the Current LSI, and
988  // should be the only scenario where an inconsistency between the LSI and the
989  // DeclContext should occur), so climb out the DeclContexts if they
990  // represent lambdas, while querying the corresponding closure types
991  // regarding capture information.
992 
993  // 1) Climb down the function scope info stack.
994  for (int I = FunctionScopes.size();
995  I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996  (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997  cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
998  CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999  CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1000 
1001  if (!CurLSI->isCXXThisCaptured())
1002  continue;
1003 
1004  auto C = CurLSI->getCXXThisCapture();
1005 
1006  if (C.isCopyCapture()) {
1008  if (CurLSI->CallOperator->isConst())
1009  ClassType.addConst();
1010  return ASTCtx.getPointerType(ClassType);
1011  }
1012  }
1013 
1014  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015  // happen during instantiation of its nested generic lambda call operator)
1016  if (isLambdaCallOperator(CurDC)) {
1017  assert(CurLSI && "While computing 'this' capture-type for a generic "
1018  "lambda, we must have a corresponding LambdaScopeInfo");
1020  "While computing 'this' capture-type for a generic lambda, when we "
1021  "run out of enclosing LSI's, yet the enclosing DC is a "
1022  "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1023  "lambda call oeprator");
1024  assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1025 
1026  auto IsThisCaptured =
1027  [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028  IsConst = false;
1029  IsByCopy = false;
1030  for (auto &&C : Closure->captures()) {
1031  if (C.capturesThis()) {
1032  if (C.getCaptureKind() == LCK_StarThis)
1033  IsByCopy = true;
1034  if (Closure->getLambdaCallOperator()->isConst())
1035  IsConst = true;
1036  return true;
1037  }
1038  }
1039  return false;
1040  };
1041 
1042  bool IsByCopyCapture = false;
1043  bool IsConstCapture = false;
1044  CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045  while (Closure &&
1046  IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047  if (IsByCopyCapture) {
1049  if (IsConstCapture)
1050  ClassType.addConst();
1051  return ASTCtx.getPointerType(ClassType);
1052  }
1053  Closure = isLambdaCallOperator(Closure->getParent())
1054  ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055  : nullptr;
1056  }
1057  }
1058  return ASTCtx.getPointerType(ClassType);
1059 }
1060 
1062  DeclContext *DC = getFunctionLevelDeclContext();
1063  QualType ThisTy = CXXThisTypeOverride;
1064 
1065  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066  if (method && method->isInstance())
1067  ThisTy = method->getThisType(Context);
1068  }
1069 
1070  if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1071  inTemplateInstantiation()) {
1072 
1073  assert(isa<CXXRecordDecl>(DC) &&
1074  "Trying to get 'this' type from static method?");
1075 
1076  // This is a lambda call operator that is being instantiated as a default
1077  // initializer. DC must point to the enclosing class type, so we can recover
1078  // the 'this' type from it.
1079 
1080  QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081  // There are no cv-qualifiers for 'this' within default initializers,
1082  // per [expr.prim.general]p4.
1083  ThisTy = Context.getPointerType(ClassTy);
1084  }
1085 
1086  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087  // might need to be adjusted if the lambda or any of its enclosing lambda's
1088  // captures '*this' by copy.
1089  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090  return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091  CurContext, Context);
1092  return ThisTy;
1093 }
1094 
1096  Decl *ContextDecl,
1097  unsigned CXXThisTypeQuals,
1098  bool Enabled)
1099  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100 {
1101  if (!Enabled || !ContextDecl)
1102  return;
1103 
1104  CXXRecordDecl *Record = nullptr;
1105  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106  Record = Template->getTemplatedDecl();
1107  else
1108  Record = cast<CXXRecordDecl>(ContextDecl);
1109 
1110  // We care only for CVR qualifiers here, so cut everything else.
1111  CXXThisTypeQuals &= Qualifiers::FastMask;
1113  = S.Context.getPointerType(
1114  S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1115 
1116  this->Enabled = true;
1117 }
1118 
1119 
1121  if (Enabled) {
1122  S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1123  }
1124 }
1125 
1127  QualType ThisTy, SourceLocation Loc,
1128  const bool ByCopy) {
1129 
1130  QualType AdjustedThisTy = ThisTy;
1131  // The type of the corresponding data member (not a 'this' pointer if 'by
1132  // copy').
1133  QualType CaptureThisFieldTy = ThisTy;
1134  if (ByCopy) {
1135  // If we are capturing the object referred to by '*this' by copy, ignore any
1136  // cv qualifiers inherited from the type of the member function for the type
1137  // of the closure-type's corresponding data member and any use of 'this'.
1138  CaptureThisFieldTy = ThisTy->getPointeeType();
1139  CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1140  AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1141  }
1142 
1143  FieldDecl *Field = FieldDecl::Create(
1144  Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1145  Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1146  ICIS_NoInit);
1147 
1148  Field->setImplicit(true);
1149  Field->setAccess(AS_private);
1150  RD->addDecl(Field);
1151  Expr *This =
1152  new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1153  if (ByCopy) {
1154  Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1155  UO_Deref,
1156  This).get();
1158  nullptr, CaptureThisFieldTy, Loc);
1159  InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1160  InitializationSequence Init(S, Entity, InitKind, StarThis);
1161  ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1162  if (ER.isInvalid()) return nullptr;
1163  return ER.get();
1164  }
1165  return This;
1166 }
1167 
1168 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1169  bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1170  const bool ByCopy) {
1171  // We don't need to capture this in an unevaluated context.
1172  if (isUnevaluatedContext() && !Explicit)
1173  return true;
1174 
1175  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1176 
1177  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1178  ? *FunctionScopeIndexToStopAt
1179  : FunctionScopes.size() - 1;
1180 
1181  // Check that we can capture the *enclosing object* (referred to by '*this')
1182  // by the capturing-entity/closure (lambda/block/etc) at
1183  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1184 
1185  // Note: The *enclosing object* can only be captured by-value by a
1186  // closure that is a lambda, using the explicit notation:
1187  // [*this] { ... }.
1188  // Every other capture of the *enclosing object* results in its by-reference
1189  // capture.
1190 
1191  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1192  // stack), we can capture the *enclosing object* only if:
1193  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1194  // - or, 'L' has an implicit capture.
1195  // AND
1196  // -- there is no enclosing closure
1197  // -- or, there is some enclosing closure 'E' that has already captured the
1198  // *enclosing object*, and every intervening closure (if any) between 'E'
1199  // and 'L' can implicitly capture the *enclosing object*.
1200  // -- or, every enclosing closure can implicitly capture the
1201  // *enclosing object*
1202 
1203 
1204  unsigned NumCapturingClosures = 0;
1205  for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1206  if (CapturingScopeInfo *CSI =
1207  dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1208  if (CSI->CXXThisCaptureIndex != 0) {
1209  // 'this' is already being captured; there isn't anything more to do.
1210  CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1211  break;
1212  }
1213  LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1215  // This context can't implicitly capture 'this'; fail out.
1216  if (BuildAndDiagnose)
1217  Diag(Loc, diag::err_this_capture)
1218  << (Explicit && idx == MaxFunctionScopesIndex);
1219  return true;
1220  }
1221  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1222  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1223  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1224  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1225  (Explicit && idx == MaxFunctionScopesIndex)) {
1226  // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1227  // iteration through can be an explicit capture, all enclosing closures,
1228  // if any, must perform implicit captures.
1229 
1230  // This closure can capture 'this'; continue looking upwards.
1231  NumCapturingClosures++;
1232  continue;
1233  }
1234  // This context can't implicitly capture 'this'; fail out.
1235  if (BuildAndDiagnose)
1236  Diag(Loc, diag::err_this_capture)
1237  << (Explicit && idx == MaxFunctionScopesIndex);
1238  return true;
1239  }
1240  break;
1241  }
1242  if (!BuildAndDiagnose) return false;
1243 
1244  // If we got here, then the closure at MaxFunctionScopesIndex on the
1245  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1246  // (including implicit by-reference captures in any enclosing closures).
1247 
1248  // In the loop below, respect the ByCopy flag only for the closure requesting
1249  // the capture (i.e. first iteration through the loop below). Ignore it for
1250  // all enclosing closure's up to NumCapturingClosures (since they must be
1251  // implicitly capturing the *enclosing object* by reference (see loop
1252  // above)).
1253  assert((!ByCopy ||
1254  dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1255  "Only a lambda can capture the enclosing object (referred to by "
1256  "*this) by copy");
1257  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1258  // contexts.
1259  QualType ThisTy = getCurrentThisType();
1260  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1261  --idx, --NumCapturingClosures) {
1262  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1263  Expr *ThisExpr = nullptr;
1264 
1265  if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1266  // For lambda expressions, build a field and an initializing expression,
1267  // and capture the *enclosing object* by copy only if this is the first
1268  // iteration.
1269  ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1270  ByCopy && idx == MaxFunctionScopesIndex);
1271 
1272  } else if (CapturedRegionScopeInfo *RSI
1273  = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1274  ThisExpr =
1275  captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1276  false/*ByCopy*/);
1277 
1278  bool isNested = NumCapturingClosures > 1;
1279  CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1280  }
1281  return false;
1282 }
1283 
1285  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1286  /// is a non-lvalue expression whose value is the address of the object for
1287  /// which the function is called.
1288 
1289  QualType ThisTy = getCurrentThisType();
1290  if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1291 
1292  CheckCXXThisCapture(Loc);
1293  return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1294 }
1295 
1297  // If we're outside the body of a member function, then we'll have a specified
1298  // type for 'this'.
1300  return false;
1301 
1302  // Determine whether we're looking into a class that's currently being
1303  // defined.
1304  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1305  return Class && Class->isBeingDefined();
1306 }
1307 
1308 /// Parse construction of a specified type.
1309 /// Can be interpreted either as function-style casting ("int(x)")
1310 /// or class type construction ("ClassType(x,y,z)")
1311 /// or creation of a value-initialized type ("int()").
1312 ExprResult
1314  SourceLocation LParenOrBraceLoc,
1315  MultiExprArg exprs,
1316  SourceLocation RParenOrBraceLoc,
1317  bool ListInitialization) {
1318  if (!TypeRep)
1319  return ExprError();
1320 
1321  TypeSourceInfo *TInfo;
1322  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1323  if (!TInfo)
1325 
1326  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1327  RParenOrBraceLoc, ListInitialization);
1328  // Avoid creating a non-type-dependent expression that contains typos.
1329  // Non-type-dependent expressions are liable to be discarded without
1330  // checking for embedded typos.
1331  if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1332  !Result.get()->isTypeDependent())
1334  return Result;
1335 }
1336 
1337 ExprResult
1339  SourceLocation LParenOrBraceLoc,
1340  MultiExprArg Exprs,
1341  SourceLocation RParenOrBraceLoc,
1342  bool ListInitialization) {
1343  QualType Ty = TInfo->getType();
1344  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1345 
1347  // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1348  // directly. We work around this by dropping the locations of the braces.
1349  SourceRange Locs = ListInitialization
1350  ? SourceRange()
1351  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1352  return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1353  Exprs, Locs.getEnd());
1354  }
1355 
1356  assert((!ListInitialization ||
1357  (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1358  "List initialization must have initializer list as expression.");
1359  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1360 
1363  Exprs.size()
1364  ? ListInitialization
1366  TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1367  : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1368  RParenOrBraceLoc)
1369  : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1370  RParenOrBraceLoc);
1371 
1372  // C++1z [expr.type.conv]p1:
1373  // If the type is a placeholder for a deduced class type, [...perform class
1374  // template argument deduction...]
1375  DeducedType *Deduced = Ty->getContainedDeducedType();
1376  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1378  Kind, Exprs);
1379  if (Ty.isNull())
1380  return ExprError();
1381  Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1382  }
1383 
1384  // C++ [expr.type.conv]p1:
1385  // If the expression list is a parenthesized single expression, the type
1386  // conversion expression is equivalent (in definedness, and if defined in
1387  // meaning) to the corresponding cast expression.
1388  if (Exprs.size() == 1 && !ListInitialization &&
1389  !isa<InitListExpr>(Exprs[0])) {
1390  Expr *Arg = Exprs[0];
1391  return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1392  RParenOrBraceLoc);
1393  }
1394 
1395  // For an expression of the form T(), T shall not be an array type.
1396  QualType ElemTy = Ty;
1397  if (Ty->isArrayType()) {
1398  if (!ListInitialization)
1399  return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1400  << FullRange);
1401  ElemTy = Context.getBaseElementType(Ty);
1402  }
1403 
1404  // There doesn't seem to be an explicit rule against this but sanity demands
1405  // we only construct objects with object types.
1406  if (Ty->isFunctionType())
1407  return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1408  << Ty << FullRange);
1409 
1410  // C++17 [expr.type.conv]p2:
1411  // If the type is cv void and the initializer is (), the expression is a
1412  // prvalue of the specified type that performs no initialization.
1413  if (!Ty->isVoidType() &&
1414  RequireCompleteType(TyBeginLoc, ElemTy,
1415  diag::err_invalid_incomplete_type_use, FullRange))
1416  return ExprError();
1417 
1418  // Otherwise, the expression is a prvalue of the specified type whose
1419  // result object is direct-initialized (11.6) with the initializer.
1420  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1421  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1422 
1423  if (Result.isInvalid())
1424  return Result;
1425 
1426  Expr *Inner = Result.get();
1427  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1428  Inner = BTE->getSubExpr();
1429  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1430  !isa<CXXScalarValueInitExpr>(Inner)) {
1431  // If we created a CXXTemporaryObjectExpr, that node also represents the
1432  // functional cast. Otherwise, create an explicit cast to represent
1433  // the syntactic form of a functional-style cast that was used here.
1434  //
1435  // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1436  // would give a more consistent AST representation than using a
1437  // CXXTemporaryObjectExpr. It's also weird that the functional cast
1438  // is sometimes handled by initialization and sometimes not.
1439  QualType ResultType = Result.get()->getType();
1440  SourceRange Locs = ListInitialization
1441  ? SourceRange()
1442  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1444  Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1445  Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1446  }
1447 
1448  return Result;
1449 }
1450 
1451 /// Determine whether the given function is a non-placement
1452 /// deallocation function.
1454  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1455  return Method->isUsualDeallocationFunction();
1456 
1457  if (FD->getOverloadedOperator() != OO_Delete &&
1458  FD->getOverloadedOperator() != OO_Array_Delete)
1459  return false;
1460 
1461  unsigned UsualParams = 1;
1462 
1463  if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1465  FD->getParamDecl(UsualParams)->getType(),
1466  S.Context.getSizeType()))
1467  ++UsualParams;
1468 
1469  if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1471  FD->getParamDecl(UsualParams)->getType(),
1473  ++UsualParams;
1474 
1475  return UsualParams == FD->getNumParams();
1476 }
1477 
1478 namespace {
1479  struct UsualDeallocFnInfo {
1480  UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1481  UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1482  : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1483  Destroying(false), HasSizeT(false), HasAlignValT(false),
1484  CUDAPref(Sema::CFP_Native) {
1485  // A function template declaration is never a usual deallocation function.
1486  if (!FD)
1487  return;
1488  unsigned NumBaseParams = 1;
1489  if (FD->isDestroyingOperatorDelete()) {
1490  Destroying = true;
1491  ++NumBaseParams;
1492  }
1493  if (FD->getNumParams() == NumBaseParams + 2)
1494  HasAlignValT = HasSizeT = true;
1495  else if (FD->getNumParams() == NumBaseParams + 1) {
1496  HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1497  HasAlignValT = !HasSizeT;
1498  }
1499 
1500  // In CUDA, determine how much we'd like / dislike to call this.
1501  if (S.getLangOpts().CUDA)
1502  if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1503  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1504  }
1505 
1506  explicit operator bool() const { return FD; }
1507 
1508  bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1509  bool WantAlign) const {
1510  // C++ P0722:
1511  // A destroying operator delete is preferred over a non-destroying
1512  // operator delete.
1513  if (Destroying != Other.Destroying)
1514  return Destroying;
1515 
1516  // C++17 [expr.delete]p10:
1517  // If the type has new-extended alignment, a function with a parameter
1518  // of type std::align_val_t is preferred; otherwise a function without
1519  // such a parameter is preferred
1520  if (HasAlignValT != Other.HasAlignValT)
1521  return HasAlignValT == WantAlign;
1522 
1523  if (HasSizeT != Other.HasSizeT)
1524  return HasSizeT == WantSize;
1525 
1526  // Use CUDA call preference as a tiebreaker.
1527  return CUDAPref > Other.CUDAPref;
1528  }
1529 
1530  DeclAccessPair Found;
1531  FunctionDecl *FD;
1532  bool Destroying, HasSizeT, HasAlignValT;
1534  };
1535 }
1536 
1537 /// Determine whether a type has new-extended alignment. This may be called when
1538 /// the type is incomplete (for a delete-expression with an incomplete pointee
1539 /// type), in which case it will conservatively return false if the alignment is
1540 /// not known.
1541 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1542  return S.getLangOpts().AlignedAllocation &&
1543  S.getASTContext().getTypeAlignIfKnown(AllocType) >
1545 }
1546 
1547 /// Select the correct "usual" deallocation function to use from a selection of
1548 /// deallocation functions (either global or class-scope).
1549 static UsualDeallocFnInfo resolveDeallocationOverload(
1550  Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1551  llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1552  UsualDeallocFnInfo Best;
1553 
1554  for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1555  UsualDeallocFnInfo Info(S, I.getPair());
1556  if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1557  Info.CUDAPref == Sema::CFP_Never)
1558  continue;
1559 
1560  if (!Best) {
1561  Best = Info;
1562  if (BestFns)
1563  BestFns->push_back(Info);
1564  continue;
1565  }
1566 
1567  if (Best.isBetterThan(Info, WantSize, WantAlign))
1568  continue;
1569 
1570  // If more than one preferred function is found, all non-preferred
1571  // functions are eliminated from further consideration.
1572  if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1573  BestFns->clear();
1574 
1575  Best = Info;
1576  if (BestFns)
1577  BestFns->push_back(Info);
1578  }
1579 
1580  return Best;
1581 }
1582 
1583 /// Determine whether a given type is a class for which 'delete[]' would call
1584 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1585 /// we need to store the array size (even if the type is
1586 /// trivially-destructible).
1588  QualType allocType) {
1589  const RecordType *record =
1590  allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1591  if (!record) return false;
1592 
1593  // Try to find an operator delete[] in class scope.
1594 
1595  DeclarationName deleteName =
1596  S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1597  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1598  S.LookupQualifiedName(ops, record->getDecl());
1599 
1600  // We're just doing this for information.
1601  ops.suppressDiagnostics();
1602 
1603  // Very likely: there's no operator delete[].
1604  if (ops.empty()) return false;
1605 
1606  // If it's ambiguous, it should be illegal to call operator delete[]
1607  // on this thing, so it doesn't matter if we allocate extra space or not.
1608  if (ops.isAmbiguous()) return false;
1609 
1610  // C++17 [expr.delete]p10:
1611  // If the deallocation functions have class scope, the one without a
1612  // parameter of type std::size_t is selected.
1613  auto Best = resolveDeallocationOverload(
1614  S, ops, /*WantSize*/false,
1615  /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1616  return Best && Best.HasSizeT;
1617 }
1618 
1619 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1620 ///
1621 /// E.g.:
1622 /// @code new (memory) int[size][4] @endcode
1623 /// or
1624 /// @code ::new Foo(23, "hello") @endcode
1625 ///
1626 /// \param StartLoc The first location of the expression.
1627 /// \param UseGlobal True if 'new' was prefixed with '::'.
1628 /// \param PlacementLParen Opening paren of the placement arguments.
1629 /// \param PlacementArgs Placement new arguments.
1630 /// \param PlacementRParen Closing paren of the placement arguments.
1631 /// \param TypeIdParens If the type is in parens, the source range.
1632 /// \param D The type to be allocated, as well as array dimensions.
1633 /// \param Initializer The initializing expression or initializer-list, or null
1634 /// if there is none.
1635 ExprResult
1636 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1637  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1638  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1639  Declarator &D, Expr *Initializer) {
1640  Expr *ArraySize = nullptr;
1641  // If the specified type is an array, unwrap it and save the expression.
1642  if (D.getNumTypeObjects() > 0 &&
1644  DeclaratorChunk &Chunk = D.getTypeObject(0);
1645  if (D.getDeclSpec().hasAutoTypeSpec())
1646  return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1647  << D.getSourceRange());
1648  if (Chunk.Arr.hasStatic)
1649  return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1650  << D.getSourceRange());
1651  if (!Chunk.Arr.NumElts)
1652  return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1653  << D.getSourceRange());
1654 
1655  ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1656  D.DropFirstTypeObject();
1657  }
1658 
1659  // Every dimension shall be of constant size.
1660  if (ArraySize) {
1661  for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1663  break;
1664 
1666  if (Expr *NumElts = (Expr *)Array.NumElts) {
1667  if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1668  if (getLangOpts().CPlusPlus14) {
1669  // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1670  // shall be a converted constant expression (5.19) of type std::size_t
1671  // and shall evaluate to a strictly positive value.
1672  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1673  assert(IntWidth && "Builtin type of size 0?");
1674  llvm::APSInt Value(IntWidth);
1675  Array.NumElts
1677  CCEK_NewExpr)
1678  .get();
1679  } else {
1680  Array.NumElts
1681  = VerifyIntegerConstantExpression(NumElts, nullptr,
1682  diag::err_new_array_nonconst)
1683  .get();
1684  }
1685  if (!Array.NumElts)
1686  return ExprError();
1687  }
1688  }
1689  }
1690  }
1691 
1692  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1693  QualType AllocType = TInfo->getType();
1694  if (D.isInvalidType())
1695  return ExprError();
1696 
1697  SourceRange DirectInitRange;
1698  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1699  DirectInitRange = List->getSourceRange();
1700 
1701  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1702  PlacementLParen, PlacementArgs, PlacementRParen,
1703  TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1704  Initializer);
1705 }
1706 
1708  Expr *Init) {
1709  if (!Init)
1710  return true;
1711  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1712  return PLE->getNumExprs() == 0;
1713  if (isa<ImplicitValueInitExpr>(Init))
1714  return true;
1715  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1716  return !CCE->isListInitialization() &&
1717  CCE->getConstructor()->isDefaultConstructor();
1718  else if (Style == CXXNewExpr::ListInit) {
1719  assert(isa<InitListExpr>(Init) &&
1720  "Shouldn't create list CXXConstructExprs for arrays.");
1721  return true;
1722  }
1723  return false;
1724 }
1725 
1726 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1727 // implemented in the standard library is selected.
1729  SourceLocation Loc, bool IsDelete,
1730  Sema &S) {
1731  if (!S.getLangOpts().AlignedAllocationUnavailable)
1732  return;
1733 
1734  // Return if there is a definition.
1735  if (FD.isDefined())
1736  return;
1737 
1738  bool IsAligned = false;
1739  if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
1740  const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1741  StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1743 
1744  S.Diag(Loc, diag::err_aligned_allocation_unavailable)
1745  << IsDelete << FD.getType().getAsString() << OSName
1746  << alignedAllocMinVersion(T.getOS()).getAsString();
1747  S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1748  }
1749 }
1750 
1751 ExprResult
1752 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1753  SourceLocation PlacementLParen,
1754  MultiExprArg PlacementArgs,
1755  SourceLocation PlacementRParen,
1756  SourceRange TypeIdParens,
1757  QualType AllocType,
1758  TypeSourceInfo *AllocTypeInfo,
1759  Expr *ArraySize,
1760  SourceRange DirectInitRange,
1761  Expr *Initializer) {
1762  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1763  SourceLocation StartLoc = Range.getBegin();
1764 
1766  if (DirectInitRange.isValid()) {
1767  assert(Initializer && "Have parens but no initializer.");
1768  initStyle = CXXNewExpr::CallInit;
1769  } else if (Initializer && isa<InitListExpr>(Initializer))
1770  initStyle = CXXNewExpr::ListInit;
1771  else {
1772  assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1773  isa<CXXConstructExpr>(Initializer)) &&
1774  "Initializer expression that cannot have been implicitly created.");
1775  initStyle = CXXNewExpr::NoInit;
1776  }
1777 
1778  Expr **Inits = &Initializer;
1779  unsigned NumInits = Initializer ? 1 : 0;
1780  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1781  assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1782  Inits = List->getExprs();
1783  NumInits = List->getNumExprs();
1784  }
1785 
1786  // C++11 [expr.new]p15:
1787  // A new-expression that creates an object of type T initializes that
1788  // object as follows:
1790  // - If the new-initializer is omitted, the object is default-
1791  // initialized (8.5); if no initialization is performed,
1792  // the object has indeterminate value
1793  = initStyle == CXXNewExpr::NoInit
1795  // - Otherwise, the new-initializer is interpreted according to
1796  // the
1797  // initialization rules of 8.5 for direct-initialization.
1798  : initStyle == CXXNewExpr::ListInit
1800  TypeRange.getBegin(), Initializer->getBeginLoc(),
1801  Initializer->getEndLoc())
1803  DirectInitRange.getBegin(),
1804  DirectInitRange.getEnd());
1805 
1806  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1807  auto *Deduced = AllocType->getContainedDeducedType();
1808  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1809  if (ArraySize)
1810  return ExprError(Diag(ArraySize->getExprLoc(),
1811  diag::err_deduced_class_template_compound_type)
1812  << /*array*/ 2 << ArraySize->getSourceRange());
1813 
1814  InitializedEntity Entity
1815  = InitializedEntity::InitializeNew(StartLoc, AllocType);
1817  AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1818  if (AllocType.isNull())
1819  return ExprError();
1820  } else if (Deduced) {
1821  bool Braced = (initStyle == CXXNewExpr::ListInit);
1822  if (NumInits == 1) {
1823  if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1824  Inits = p->getInits();
1825  NumInits = p->getNumInits();
1826  Braced = true;
1827  }
1828  }
1829 
1830  if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1831  return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1832  << AllocType << TypeRange);
1833  if (NumInits > 1) {
1834  Expr *FirstBad = Inits[1];
1835  return ExprError(Diag(FirstBad->getBeginLoc(),
1836  diag::err_auto_new_ctor_multiple_expressions)
1837  << AllocType << TypeRange);
1838  }
1839  if (Braced && !getLangOpts().CPlusPlus17)
1840  Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1841  << AllocType << TypeRange;
1842  Expr *Deduce = Inits[0];
1844  if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1845  return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1846  << AllocType << Deduce->getType()
1847  << TypeRange << Deduce->getSourceRange());
1848  if (DeducedType.isNull())
1849  return ExprError();
1850  AllocType = DeducedType;
1851  }
1852 
1853  // Per C++0x [expr.new]p5, the type being constructed may be a
1854  // typedef of an array type.
1855  if (!ArraySize) {
1856  if (const ConstantArrayType *Array
1857  = Context.getAsConstantArrayType(AllocType)) {
1858  ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1859  Context.getSizeType(),
1860  TypeRange.getEnd());
1861  AllocType = Array->getElementType();
1862  }
1863  }
1864 
1865  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1866  return ExprError();
1867 
1868  // In ARC, infer 'retaining' for the allocated
1869  if (getLangOpts().ObjCAutoRefCount &&
1870  AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1871  AllocType->isObjCLifetimeType()) {
1872  AllocType = Context.getLifetimeQualifiedType(AllocType,
1873  AllocType->getObjCARCImplicitLifetime());
1874  }
1875 
1876  QualType ResultType = Context.getPointerType(AllocType);
1877 
1878  if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1879  ExprResult result = CheckPlaceholderExpr(ArraySize);
1880  if (result.isInvalid()) return ExprError();
1881  ArraySize = result.get();
1882  }
1883  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1884  // integral or enumeration type with a non-negative value."
1885  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1886  // enumeration type, or a class type for which a single non-explicit
1887  // conversion function to integral or unscoped enumeration type exists.
1888  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1889  // std::size_t.
1890  llvm::Optional<uint64_t> KnownArraySize;
1891  if (ArraySize && !ArraySize->isTypeDependent()) {
1892  ExprResult ConvertedSize;
1893  if (getLangOpts().CPlusPlus14) {
1894  assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1895 
1896  ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1897  AA_Converting);
1898 
1899  if (!ConvertedSize.isInvalid() &&
1900  ArraySize->getType()->getAs<RecordType>())
1901  // Diagnose the compatibility of this conversion.
1902  Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1903  << ArraySize->getType() << 0 << "'size_t'";
1904  } else {
1905  class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1906  protected:
1907  Expr *ArraySize;
1908 
1909  public:
1910  SizeConvertDiagnoser(Expr *ArraySize)
1911  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1912  ArraySize(ArraySize) {}
1913 
1914  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1915  QualType T) override {
1916  return S.Diag(Loc, diag::err_array_size_not_integral)
1917  << S.getLangOpts().CPlusPlus11 << T;
1918  }
1919 
1920  SemaDiagnosticBuilder diagnoseIncomplete(
1921  Sema &S, SourceLocation Loc, QualType T) override {
1922  return S.Diag(Loc, diag::err_array_size_incomplete_type)
1923  << T << ArraySize->getSourceRange();
1924  }
1925 
1926  SemaDiagnosticBuilder diagnoseExplicitConv(
1927  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1928  return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1929  }
1930 
1931  SemaDiagnosticBuilder noteExplicitConv(
1932  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1933  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1934  << ConvTy->isEnumeralType() << ConvTy;
1935  }
1936 
1937  SemaDiagnosticBuilder diagnoseAmbiguous(
1938  Sema &S, SourceLocation Loc, QualType T) override {
1939  return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1940  }
1941 
1942  SemaDiagnosticBuilder noteAmbiguous(
1943  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1944  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1945  << ConvTy->isEnumeralType() << ConvTy;
1946  }
1947 
1948  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1949  QualType T,
1950  QualType ConvTy) override {
1951  return S.Diag(Loc,
1952  S.getLangOpts().CPlusPlus11
1953  ? diag::warn_cxx98_compat_array_size_conversion
1954  : diag::ext_array_size_conversion)
1955  << T << ConvTy->isEnumeralType() << ConvTy;
1956  }
1957  } SizeDiagnoser(ArraySize);
1958 
1959  ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1960  SizeDiagnoser);
1961  }
1962  if (ConvertedSize.isInvalid())
1963  return ExprError();
1964 
1965  ArraySize = ConvertedSize.get();
1966  QualType SizeType = ArraySize->getType();
1967 
1968  if (!SizeType->isIntegralOrUnscopedEnumerationType())
1969  return ExprError();
1970 
1971  // C++98 [expr.new]p7:
1972  // The expression in a direct-new-declarator shall have integral type
1973  // with a non-negative value.
1974  //
1975  // Let's see if this is a constant < 0. If so, we reject it out of hand,
1976  // per CWG1464. Otherwise, if it's not a constant, we must have an
1977  // unparenthesized array type.
1978  if (!ArraySize->isValueDependent()) {
1979  llvm::APSInt Value;
1980  // We've already performed any required implicit conversion to integer or
1981  // unscoped enumeration type.
1982  // FIXME: Per CWG1464, we are required to check the value prior to
1983  // converting to size_t. This will never find a negative array size in
1984  // C++14 onwards, because Value is always unsigned here!
1985  if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1986  if (Value.isSigned() && Value.isNegative()) {
1987  return ExprError(Diag(ArraySize->getBeginLoc(),
1988  diag::err_typecheck_negative_array_size)
1989  << ArraySize->getSourceRange());
1990  }
1991 
1992  if (!AllocType->isDependentType()) {
1993  unsigned ActiveSizeBits =
1995  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1996  return ExprError(
1997  Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
1998  << Value.toString(10) << ArraySize->getSourceRange());
1999  }
2000 
2001  KnownArraySize = Value.getZExtValue();
2002  } else if (TypeIdParens.isValid()) {
2003  // Can't have dynamic array size when the type-id is in parentheses.
2004  Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2005  << ArraySize->getSourceRange()
2006  << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2007  << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2008 
2009  TypeIdParens = SourceRange();
2010  }
2011  }
2012 
2013  // Note that we do *not* convert the argument in any way. It can
2014  // be signed, larger than size_t, whatever.
2015  }
2016 
2017  FunctionDecl *OperatorNew = nullptr;
2018  FunctionDecl *OperatorDelete = nullptr;
2019  unsigned Alignment =
2020  AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2021  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2022  bool PassAlignment = getLangOpts().AlignedAllocation &&
2023  Alignment > NewAlignment;
2024 
2026  if (!AllocType->isDependentType() &&
2027  !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2028  FindAllocationFunctions(StartLoc,
2029  SourceRange(PlacementLParen, PlacementRParen),
2030  Scope, Scope, AllocType, ArraySize, PassAlignment,
2031  PlacementArgs, OperatorNew, OperatorDelete))
2032  return ExprError();
2033 
2034  // If this is an array allocation, compute whether the usual array
2035  // deallocation function for the type has a size_t parameter.
2036  bool UsualArrayDeleteWantsSize = false;
2037  if (ArraySize && !AllocType->isDependentType())
2038  UsualArrayDeleteWantsSize =
2039  doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2040 
2041  SmallVector<Expr *, 8> AllPlaceArgs;
2042  if (OperatorNew) {
2043  const FunctionProtoType *Proto =
2044  OperatorNew->getType()->getAs<FunctionProtoType>();
2045  VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2047 
2048  // We've already converted the placement args, just fill in any default
2049  // arguments. Skip the first parameter because we don't have a corresponding
2050  // argument. Skip the second parameter too if we're passing in the
2051  // alignment; we've already filled it in.
2052  if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2053  PassAlignment ? 2 : 1, PlacementArgs,
2054  AllPlaceArgs, CallType))
2055  return ExprError();
2056 
2057  if (!AllPlaceArgs.empty())
2058  PlacementArgs = AllPlaceArgs;
2059 
2060  // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2061  DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2062 
2063  // FIXME: Missing call to CheckFunctionCall or equivalent
2064 
2065  // Warn if the type is over-aligned and is being allocated by (unaligned)
2066  // global operator new.
2067  if (PlacementArgs.empty() && !PassAlignment &&
2068  (OperatorNew->isImplicit() ||
2069  (OperatorNew->getBeginLoc().isValid() &&
2070  getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2071  if (Alignment > NewAlignment)
2072  Diag(StartLoc, diag::warn_overaligned_type)
2073  << AllocType
2074  << unsigned(Alignment / Context.getCharWidth())
2075  << unsigned(NewAlignment / Context.getCharWidth());
2076  }
2077  }
2078 
2079  // Array 'new' can't have any initializers except empty parentheses.
2080  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2081  // dialect distinction.
2082  if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2083  SourceRange InitRange(Inits[0]->getBeginLoc(),
2084  Inits[NumInits - 1]->getEndLoc());
2085  Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2086  return ExprError();
2087  }
2088 
2089  // If we can perform the initialization, and we've not already done so,
2090  // do it now.
2091  if (!AllocType->isDependentType() &&
2093  llvm::makeArrayRef(Inits, NumInits))) {
2094  // The type we initialize is the complete type, including the array bound.
2095  QualType InitType;
2096  if (KnownArraySize)
2097  InitType = Context.getConstantArrayType(
2098  AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2099  *KnownArraySize),
2100  ArrayType::Normal, 0);
2101  else if (ArraySize)
2102  InitType =
2104  else
2105  InitType = AllocType;
2106 
2107  InitializedEntity Entity
2108  = InitializedEntity::InitializeNew(StartLoc, InitType);
2109  InitializationSequence InitSeq(*this, Entity, Kind,
2110  MultiExprArg(Inits, NumInits));
2111  ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2112  MultiExprArg(Inits, NumInits));
2113  if (FullInit.isInvalid())
2114  return ExprError();
2115 
2116  // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2117  // we don't want the initialized object to be destructed.
2118  // FIXME: We should not create these in the first place.
2119  if (CXXBindTemporaryExpr *Binder =
2120  dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2121  FullInit = Binder->getSubExpr();
2122 
2123  Initializer = FullInit.get();
2124  }
2125 
2126  // Mark the new and delete operators as referenced.
2127  if (OperatorNew) {
2128  if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2129  return ExprError();
2130  MarkFunctionReferenced(StartLoc, OperatorNew);
2131  diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
2132  }
2133  if (OperatorDelete) {
2134  if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2135  return ExprError();
2136  MarkFunctionReferenced(StartLoc, OperatorDelete);
2137  diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
2138  }
2139 
2140  // C++0x [expr.new]p17:
2141  // If the new expression creates an array of objects of class type,
2142  // access and ambiguity control are done for the destructor.
2143  QualType BaseAllocType = Context.getBaseElementType(AllocType);
2144  if (ArraySize && !BaseAllocType->isDependentType()) {
2145  if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2146  if (CXXDestructorDecl *dtor = LookupDestructor(
2147  cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2148  MarkFunctionReferenced(StartLoc, dtor);
2149  CheckDestructorAccess(StartLoc, dtor,
2150  PDiag(diag::err_access_dtor)
2151  << BaseAllocType);
2152  if (DiagnoseUseOfDecl(dtor, StartLoc))
2153  return ExprError();
2154  }
2155  }
2156  }
2157 
2158  return new (Context)
2159  CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2160  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2161  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2162  Range, DirectInitRange);
2163 }
2164 
2165 /// Checks that a type is suitable as the allocated type
2166 /// in a new-expression.
2168  SourceRange R) {
2169  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2170  // abstract class type or array thereof.
2171  if (AllocType->isFunctionType())
2172  return Diag(Loc, diag::err_bad_new_type)
2173  << AllocType << 0 << R;
2174  else if (AllocType->isReferenceType())
2175  return Diag(Loc, diag::err_bad_new_type)
2176  << AllocType << 1 << R;
2177  else if (!AllocType->isDependentType() &&
2178  RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2179  return true;
2180  else if (RequireNonAbstractType(Loc, AllocType,
2181  diag::err_allocation_of_abstract_type))
2182  return true;
2183  else if (AllocType->isVariablyModifiedType())
2184  return Diag(Loc, diag::err_variably_modified_new_type)
2185  << AllocType;
2186  else if (AllocType.getAddressSpace() != LangAS::Default &&
2187  !getLangOpts().OpenCLCPlusPlus)
2188  return Diag(Loc, diag::err_address_space_qualified_new)
2189  << AllocType.getUnqualifiedType()
2191  else if (getLangOpts().ObjCAutoRefCount) {
2192  if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2193  QualType BaseAllocType = Context.getBaseElementType(AT);
2194  if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2195  BaseAllocType->isObjCLifetimeType())
2196  return Diag(Loc, diag::err_arc_new_array_without_ownership)
2197  << BaseAllocType;
2198  }
2199  }
2200 
2201  return false;
2202 }
2203 
2206  bool &PassAlignment, FunctionDecl *&Operator,
2207  OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2208  OverloadCandidateSet Candidates(R.getNameLoc(),
2210  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2211  Alloc != AllocEnd; ++Alloc) {
2212  // Even member operator new/delete are implicitly treated as
2213  // static, so don't use AddMemberCandidate.
2214  NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2215 
2216  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2217  S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2218  /*ExplicitTemplateArgs=*/nullptr, Args,
2219  Candidates,
2220  /*SuppressUserConversions=*/false);
2221  continue;
2222  }
2223 
2224  FunctionDecl *Fn = cast<FunctionDecl>(D);
2225  S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2226  /*SuppressUserConversions=*/false);
2227  }
2228 
2229  // Do the resolution.
2231  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2232  case OR_Success: {
2233  // Got one!
2234  FunctionDecl *FnDecl = Best->Function;
2235  if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2236  Best->FoundDecl) == Sema::AR_inaccessible)
2237  return true;
2238 
2239  Operator = FnDecl;
2240  return false;
2241  }
2242 
2243  case OR_No_Viable_Function:
2244  // C++17 [expr.new]p13:
2245  // If no matching function is found and the allocated object type has
2246  // new-extended alignment, the alignment argument is removed from the
2247  // argument list, and overload resolution is performed again.
2248  if (PassAlignment) {
2249  PassAlignment = false;
2250  AlignArg = Args[1];
2251  Args.erase(Args.begin() + 1);
2252  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2253  Operator, &Candidates, AlignArg,
2254  Diagnose);
2255  }
2256 
2257  // MSVC will fall back on trying to find a matching global operator new
2258  // if operator new[] cannot be found. Also, MSVC will leak by not
2259  // generating a call to operator delete or operator delete[], but we
2260  // will not replicate that bug.
2261  // FIXME: Find out how this interacts with the std::align_val_t fallback
2262  // once MSVC implements it.
2263  if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2264  S.Context.getLangOpts().MSVCCompat) {
2265  R.clear();
2268  // FIXME: This will give bad diagnostics pointing at the wrong functions.
2269  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2270  Operator, /*Candidates=*/nullptr,
2271  /*AlignArg=*/nullptr, Diagnose);
2272  }
2273 
2274  if (Diagnose) {
2275  S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2276  << R.getLookupName() << Range;
2277 
2278  // If we have aligned candidates, only note the align_val_t candidates
2279  // from AlignedCandidates and the non-align_val_t candidates from
2280  // Candidates.
2281  if (AlignedCandidates) {
2282  auto IsAligned = [](OverloadCandidate &C) {
2283  return C.Function->getNumParams() > 1 &&
2284  C.Function->getParamDecl(1)->getType()->isAlignValT();
2285  };
2286  auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2287 
2288  // This was an overaligned allocation, so list the aligned candidates
2289  // first.
2290  Args.insert(Args.begin() + 1, AlignArg);
2291  AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2292  R.getNameLoc(), IsAligned);
2293  Args.erase(Args.begin() + 1);
2294  Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2295  IsUnaligned);
2296  } else {
2297  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2298  }
2299  }
2300  return true;
2301 
2302  case OR_Ambiguous:
2303  if (Diagnose) {
2304  S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2305  << R.getLookupName() << Range;
2306  Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2307  }
2308  return true;
2309 
2310  case OR_Deleted: {
2311  if (Diagnose) {
2312  S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2313  << Best->Function->isDeleted() << R.getLookupName()
2314  << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2315  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2316  }
2317  return true;
2318  }
2319  }
2320  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2321 }
2322 
2324  AllocationFunctionScope NewScope,
2325  AllocationFunctionScope DeleteScope,
2326  QualType AllocType, bool IsArray,
2327  bool &PassAlignment, MultiExprArg PlaceArgs,
2328  FunctionDecl *&OperatorNew,
2329  FunctionDecl *&OperatorDelete,
2330  bool Diagnose) {
2331  // --- Choosing an allocation function ---
2332  // C++ 5.3.4p8 - 14 & 18
2333  // 1) If looking in AFS_Global scope for allocation functions, only look in
2334  // the global scope. Else, if AFS_Class, only look in the scope of the
2335  // allocated class. If AFS_Both, look in both.
2336  // 2) If an array size is given, look for operator new[], else look for
2337  // operator new.
2338  // 3) The first argument is always size_t. Append the arguments from the
2339  // placement form.
2340 
2341  SmallVector<Expr*, 8> AllocArgs;
2342  AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2343 
2344  // We don't care about the actual value of these arguments.
2345  // FIXME: Should the Sema create the expression and embed it in the syntax
2346  // tree? Or should the consumer just recalculate the value?
2347  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2348  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2350  Context.getSizeType(),
2351  SourceLocation());
2352  AllocArgs.push_back(&Size);
2353 
2354  QualType AlignValT = Context.VoidTy;
2355  if (PassAlignment) {
2357  AlignValT = Context.getTypeDeclType(getStdAlignValT());
2358  }
2359  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2360  if (PassAlignment)
2361  AllocArgs.push_back(&Align);
2362 
2363  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2364 
2365  // C++ [expr.new]p8:
2366  // If the allocated type is a non-array type, the allocation
2367  // function's name is operator new and the deallocation function's
2368  // name is operator delete. If the allocated type is an array
2369  // type, the allocation function's name is operator new[] and the
2370  // deallocation function's name is operator delete[].
2372  IsArray ? OO_Array_New : OO_New);
2373 
2374  QualType AllocElemType = Context.getBaseElementType(AllocType);
2375 
2376  // Find the allocation function.
2377  {
2378  LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2379 
2380  // C++1z [expr.new]p9:
2381  // If the new-expression begins with a unary :: operator, the allocation
2382  // function's name is looked up in the global scope. Otherwise, if the
2383  // allocated type is a class type T or array thereof, the allocation
2384  // function's name is looked up in the scope of T.
2385  if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2386  LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2387 
2388  // We can see ambiguity here if the allocation function is found in
2389  // multiple base classes.
2390  if (R.isAmbiguous())
2391  return true;
2392 
2393  // If this lookup fails to find the name, or if the allocated type is not
2394  // a class type, the allocation function's name is looked up in the
2395  // global scope.
2396  if (R.empty()) {
2397  if (NewScope == AFS_Class)
2398  return true;
2399 
2401  }
2402 
2403  if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2404  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2405  return true;
2406  }
2407 
2408  assert(!R.empty() && "implicitly declared allocation functions not found");
2409  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2410 
2411  // We do our own custom access checks below.
2412  R.suppressDiagnostics();
2413 
2414  if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2415  OperatorNew, /*Candidates=*/nullptr,
2416  /*AlignArg=*/nullptr, Diagnose))
2417  return true;
2418  }
2419 
2420  // We don't need an operator delete if we're running under -fno-exceptions.
2421  if (!getLangOpts().Exceptions) {
2422  OperatorDelete = nullptr;
2423  return false;
2424  }
2425 
2426  // Note, the name of OperatorNew might have been changed from array to
2427  // non-array by resolveAllocationOverload.
2429  OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2430  ? OO_Array_Delete
2431  : OO_Delete);
2432 
2433  // C++ [expr.new]p19:
2434  //
2435  // If the new-expression begins with a unary :: operator, the
2436  // deallocation function's name is looked up in the global
2437  // scope. Otherwise, if the allocated type is a class type T or an
2438  // array thereof, the deallocation function's name is looked up in
2439  // the scope of T. If this lookup fails to find the name, or if
2440  // the allocated type is not a class type or array thereof, the
2441  // deallocation function's name is looked up in the global scope.
2442  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2443  if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2444  CXXRecordDecl *RD
2445  = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2446  LookupQualifiedName(FoundDelete, RD);
2447  }
2448  if (FoundDelete.isAmbiguous())
2449  return true; // FIXME: clean up expressions?
2450 
2451  bool FoundGlobalDelete = FoundDelete.empty();
2452  if (FoundDelete.empty()) {
2453  if (DeleteScope == AFS_Class)
2454  return true;
2455 
2458  }
2459 
2460  FoundDelete.suppressDiagnostics();
2461 
2463 
2464  // Whether we're looking for a placement operator delete is dictated
2465  // by whether we selected a placement operator new, not by whether
2466  // we had explicit placement arguments. This matters for things like
2467  // struct A { void *operator new(size_t, int = 0); ... };
2468  // A *a = new A()
2469  //
2470  // We don't have any definition for what a "placement allocation function"
2471  // is, but we assume it's any allocation function whose
2472  // parameter-declaration-clause is anything other than (size_t).
2473  //
2474  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2475  // This affects whether an exception from the constructor of an overaligned
2476  // type uses the sized or non-sized form of aligned operator delete.
2477  bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2478  OperatorNew->isVariadic();
2479 
2480  if (isPlacementNew) {
2481  // C++ [expr.new]p20:
2482  // A declaration of a placement deallocation function matches the
2483  // declaration of a placement allocation function if it has the
2484  // same number of parameters and, after parameter transformations
2485  // (8.3.5), all parameter types except the first are
2486  // identical. [...]
2487  //
2488  // To perform this comparison, we compute the function type that
2489  // the deallocation function should have, and use that type both
2490  // for template argument deduction and for comparison purposes.
2491  QualType ExpectedFunctionType;
2492  {
2493  const FunctionProtoType *Proto
2494  = OperatorNew->getType()->getAs<FunctionProtoType>();
2495 
2496  SmallVector<QualType, 4> ArgTypes;
2497  ArgTypes.push_back(Context.VoidPtrTy);
2498  for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2499  ArgTypes.push_back(Proto->getParamType(I));
2500 
2502  // FIXME: This is not part of the standard's rule.
2503  EPI.Variadic = Proto->isVariadic();
2504 
2505  ExpectedFunctionType
2506  = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2507  }
2508 
2509  for (LookupResult::iterator D = FoundDelete.begin(),
2510  DEnd = FoundDelete.end();
2511  D != DEnd; ++D) {
2512  FunctionDecl *Fn = nullptr;
2513  if (FunctionTemplateDecl *FnTmpl =
2514  dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2515  // Perform template argument deduction to try to match the
2516  // expected function type.
2517  TemplateDeductionInfo Info(StartLoc);
2518  if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2519  Info))
2520  continue;
2521  } else
2522  Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2523 
2525  ExpectedFunctionType,
2526  /*AdjustExcpetionSpec*/true),
2527  ExpectedFunctionType))
2528  Matches.push_back(std::make_pair(D.getPair(), Fn));
2529  }
2530 
2531  if (getLangOpts().CUDA)
2532  EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2533  } else {
2534  // C++1y [expr.new]p22:
2535  // For a non-placement allocation function, the normal deallocation
2536  // function lookup is used
2537  //
2538  // Per [expr.delete]p10, this lookup prefers a member operator delete
2539  // without a size_t argument, but prefers a non-member operator delete
2540  // with a size_t where possible (which it always is in this case).
2542  UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2543  *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2544  /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2545  &BestDeallocFns);
2546  if (Selected)
2547  Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2548  else {
2549  // If we failed to select an operator, all remaining functions are viable
2550  // but ambiguous.
2551  for (auto Fn : BestDeallocFns)
2552  Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2553  }
2554  }
2555 
2556  // C++ [expr.new]p20:
2557  // [...] If the lookup finds a single matching deallocation
2558  // function, that function will be called; otherwise, no
2559  // deallocation function will be called.
2560  if (Matches.size() == 1) {
2561  OperatorDelete = Matches[0].second;
2562 
2563  // C++1z [expr.new]p23:
2564  // If the lookup finds a usual deallocation function (3.7.4.2)
2565  // with a parameter of type std::size_t and that function, considered
2566  // as a placement deallocation function, would have been
2567  // selected as a match for the allocation function, the program
2568  // is ill-formed.
2569  if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2570  isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2571  UsualDeallocFnInfo Info(*this,
2572  DeclAccessPair::make(OperatorDelete, AS_public));
2573  // Core issue, per mail to core reflector, 2016-10-09:
2574  // If this is a member operator delete, and there is a corresponding
2575  // non-sized member operator delete, this isn't /really/ a sized
2576  // deallocation function, it just happens to have a size_t parameter.
2577  bool IsSizedDelete = Info.HasSizeT;
2578  if (IsSizedDelete && !FoundGlobalDelete) {
2579  auto NonSizedDelete =
2580  resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2581  /*WantAlign*/Info.HasAlignValT);
2582  if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2583  NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2584  IsSizedDelete = false;
2585  }
2586 
2587  if (IsSizedDelete) {
2588  SourceRange R = PlaceArgs.empty()
2589  ? SourceRange()
2590  : SourceRange(PlaceArgs.front()->getBeginLoc(),
2591  PlaceArgs.back()->getEndLoc());
2592  Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2593  if (!OperatorDelete->isImplicit())
2594  Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2595  << DeleteName;
2596  }
2597  }
2598 
2599  CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2600  Matches[0].first);
2601  } else if (!Matches.empty()) {
2602  // We found multiple suitable operators. Per [expr.new]p20, that means we
2603  // call no 'operator delete' function, but we should at least warn the user.
2604  // FIXME: Suppress this warning if the construction cannot throw.
2605  Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2606  << DeleteName << AllocElemType;
2607 
2608  for (auto &Match : Matches)
2609  Diag(Match.second->getLocation(),
2610  diag::note_member_declared_here) << DeleteName;
2611  }
2612 
2613  return false;
2614 }
2615 
2616 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2617 /// delete. These are:
2618 /// @code
2619 /// // C++03:
2620 /// void* operator new(std::size_t) throw(std::bad_alloc);
2621 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2622 /// void operator delete(void *) throw();
2623 /// void operator delete[](void *) throw();
2624 /// // C++11:
2625 /// void* operator new(std::size_t);
2626 /// void* operator new[](std::size_t);
2627 /// void operator delete(void *) noexcept;
2628 /// void operator delete[](void *) noexcept;
2629 /// // C++1y:
2630 /// void* operator new(std::size_t);
2631 /// void* operator new[](std::size_t);
2632 /// void operator delete(void *) noexcept;
2633 /// void operator delete[](void *) noexcept;
2634 /// void operator delete(void *, std::size_t) noexcept;
2635 /// void operator delete[](void *, std::size_t) noexcept;
2636 /// @endcode
2637 /// Note that the placement and nothrow forms of new are *not* implicitly
2638 /// declared. Their use requires including <new>.
2641  return;
2642 
2643  // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2644  // are not supported.
2645  if (getLangOpts().OpenCLCPlusPlus)
2646  return;
2647 
2648  // C++ [basic.std.dynamic]p2:
2649  // [...] The following allocation and deallocation functions (18.4) are
2650  // implicitly declared in global scope in each translation unit of a
2651  // program
2652  //
2653  // C++03:
2654  // void* operator new(std::size_t) throw(std::bad_alloc);
2655  // void* operator new[](std::size_t) throw(std::bad_alloc);
2656  // void operator delete(void*) throw();
2657  // void operator delete[](void*) throw();
2658  // C++11:
2659  // void* operator new(std::size_t);
2660  // void* operator new[](std::size_t);
2661  // void operator delete(void*) noexcept;
2662  // void operator delete[](void*) noexcept;
2663  // C++1y:
2664  // void* operator new(std::size_t);
2665  // void* operator new[](std::size_t);
2666  // void operator delete(void*) noexcept;
2667  // void operator delete[](void*) noexcept;
2668  // void operator delete(void*, std::size_t) noexcept;
2669  // void operator delete[](void*, std::size_t) noexcept;
2670  //
2671  // These implicit declarations introduce only the function names operator
2672  // new, operator new[], operator delete, operator delete[].
2673  //
2674  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2675  // "std" or "bad_alloc" as necessary to form the exception specification.
2676  // However, we do not make these implicit declarations visible to name
2677  // lookup.
2678  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2679  // The "std::bad_alloc" class has not yet been declared, so build it
2680  // implicitly.
2684  &PP.getIdentifierTable().get("bad_alloc"),
2685  nullptr);
2686  getStdBadAlloc()->setImplicit(true);
2687  }
2688  if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2689  // The "std::align_val_t" enum class has not yet been declared, so build it
2690  // implicitly.
2691  auto *AlignValT = EnumDecl::Create(
2693  &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2694  AlignValT->setIntegerType(Context.getSizeType());
2695  AlignValT->setPromotionType(Context.getSizeType());
2696  AlignValT->setImplicit(true);
2697  StdAlignValT = AlignValT;
2698  }
2699 
2700  GlobalNewDeleteDeclared = true;
2701 
2703  QualType SizeT = Context.getSizeType();
2704 
2705  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2706  QualType Return, QualType Param) {
2708  Params.push_back(Param);
2709 
2710  // Create up to four variants of the function (sized/aligned).
2711  bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2712  (Kind == OO_Delete || Kind == OO_Array_Delete);
2713  bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2714 
2715  int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2716  int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2717  for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2718  if (Sized)
2719  Params.push_back(SizeT);
2720 
2721  for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2722  if (Aligned)
2723  Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2724 
2726  Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2727 
2728  if (Aligned)
2729  Params.pop_back();
2730  }
2731  }
2732  };
2733 
2734  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2735  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2736  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2737  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2738 }
2739 
2740 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2741 /// allocation function if it doesn't already exist.
2743  QualType Return,
2744  ArrayRef<QualType> Params) {
2746 
2747  // Check if this function is already declared.
2748  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2749  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2750  Alloc != AllocEnd; ++Alloc) {
2751  // Only look at non-template functions, as it is the predefined,
2752  // non-templated allocation function we are trying to declare here.
2753  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2754  if (Func->getNumParams() == Params.size()) {
2755  llvm::SmallVector<QualType, 3> FuncParams;
2756  for (auto *P : Func->parameters())
2757  FuncParams.push_back(
2758  Context.getCanonicalType(P->getType().getUnqualifiedType()));
2759  if (llvm::makeArrayRef(FuncParams) == Params) {
2760  // Make the function visible to name lookup, even if we found it in
2761  // an unimported module. It either is an implicitly-declared global
2762  // allocation function, or is suppressing that function.
2763  Func->setVisibleDespiteOwningModule();
2764  return;
2765  }
2766  }
2767  }
2768  }
2769 
2771 
2772  QualType BadAllocType;
2773  bool HasBadAllocExceptionSpec
2774  = (Name.getCXXOverloadedOperator() == OO_New ||
2775  Name.getCXXOverloadedOperator() == OO_Array_New);
2776  if (HasBadAllocExceptionSpec) {
2777  if (!getLangOpts().CPlusPlus11) {
2778  BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2779  assert(StdBadAlloc && "Must have std::bad_alloc declared");
2781  EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2782  }
2783  } else {
2784  EPI.ExceptionSpec =
2785  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2786  }
2787 
2788  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2789  QualType FnType = Context.getFunctionType(Return, Params, EPI);
2791  Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2792  FnType, /*TInfo=*/nullptr, SC_None, false, true);
2793  Alloc->setImplicit();
2794  // Global allocation functions should always be visible.
2796 
2797  // Implicit sized deallocation functions always have default visibility.
2798  Alloc->addAttr(
2799  VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2800 
2802  for (QualType T : Params) {
2803  ParamDecls.push_back(ParmVarDecl::Create(
2804  Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2805  /*TInfo=*/nullptr, SC_None, nullptr));
2806  ParamDecls.back()->setImplicit();
2807  }
2808  Alloc->setParams(ParamDecls);
2809  if (ExtraAttr)
2810  Alloc->addAttr(ExtraAttr);
2812  IdResolver.tryAddTopLevelDecl(Alloc, Name);
2813  };
2814 
2815  if (!LangOpts.CUDA)
2816  CreateAllocationFunctionDecl(nullptr);
2817  else {
2818  // Host and device get their own declaration so each can be
2819  // defined or re-declared independently.
2820  CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2821  CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2822  }
2823 }
2824 
2826  bool CanProvideSize,
2827  bool Overaligned,
2828  DeclarationName Name) {
2830 
2831  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2833 
2834  // FIXME: It's possible for this to result in ambiguity, through a
2835  // user-declared variadic operator delete or the enable_if attribute. We
2836  // should probably not consider those cases to be usual deallocation
2837  // functions. But for now we just make an arbitrary choice in that case.
2838  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2839  Overaligned);
2840  assert(Result.FD && "operator delete missing from global scope?");
2841  return Result.FD;
2842 }
2843 
2845  CXXRecordDecl *RD) {
2847 
2848  FunctionDecl *OperatorDelete = nullptr;
2849  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2850  return nullptr;
2851  if (OperatorDelete)
2852  return OperatorDelete;
2853 
2854  // If there's no class-specific operator delete, look up the global
2855  // non-array delete.
2857  Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2858  Name);
2859 }
2860 
2862  DeclarationName Name,
2863  FunctionDecl *&Operator, bool Diagnose) {
2864  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2865  // Try to find operator delete/operator delete[] in class scope.
2866  LookupQualifiedName(Found, RD);
2867 
2868  if (Found.isAmbiguous())
2869  return true;
2870 
2871  Found.suppressDiagnostics();
2872 
2873  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2874 
2875  // C++17 [expr.delete]p10:
2876  // If the deallocation functions have class scope, the one without a
2877  // parameter of type std::size_t is selected.
2879  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2880  /*WantAlign*/ Overaligned, &Matches);
2881 
2882  // If we could find an overload, use it.
2883  if (Matches.size() == 1) {
2884  Operator = cast<CXXMethodDecl>(Matches[0].FD);
2885 
2886  // FIXME: DiagnoseUseOfDecl?
2887  if (Operator->isDeleted()) {
2888  if (Diagnose) {
2889  Diag(StartLoc, diag::err_deleted_function_use);
2890  NoteDeletedFunction(Operator);
2891  }
2892  return true;
2893  }
2894 
2895  if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2896  Matches[0].Found, Diagnose) == AR_inaccessible)
2897  return true;
2898 
2899  return false;
2900  }
2901 
2902  // We found multiple suitable operators; complain about the ambiguity.
2903  // FIXME: The standard doesn't say to do this; it appears that the intent
2904  // is that this should never happen.
2905  if (!Matches.empty()) {
2906  if (Diagnose) {
2907  Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2908  << Name << RD;
2909  for (auto &Match : Matches)
2910  Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2911  }
2912  return true;
2913  }
2914 
2915  // We did find operator delete/operator delete[] declarations, but
2916  // none of them were suitable.
2917  if (!Found.empty()) {
2918  if (Diagnose) {
2919  Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2920  << Name << RD;
2921 
2922  for (NamedDecl *D : Found)
2923  Diag(D->getUnderlyingDecl()->getLocation(),
2924  diag::note_member_declared_here) << Name;
2925  }
2926  return true;
2927  }
2928 
2929  Operator = nullptr;
2930  return false;
2931 }
2932 
2933 namespace {
2934 /// Checks whether delete-expression, and new-expression used for
2935 /// initializing deletee have the same array form.
2936 class MismatchingNewDeleteDetector {
2937 public:
2938  enum MismatchResult {
2939  /// Indicates that there is no mismatch or a mismatch cannot be proven.
2940  NoMismatch,
2941  /// Indicates that variable is initialized with mismatching form of \a new.
2942  VarInitMismatches,
2943  /// Indicates that member is initialized with mismatching form of \a new.
2944  MemberInitMismatches,
2945  /// Indicates that 1 or more constructors' definitions could not been
2946  /// analyzed, and they will be checked again at the end of translation unit.
2947  AnalyzeLater
2948  };
2949 
2950  /// \param EndOfTU True, if this is the final analysis at the end of
2951  /// translation unit. False, if this is the initial analysis at the point
2952  /// delete-expression was encountered.
2953  explicit MismatchingNewDeleteDetector(bool EndOfTU)
2954  : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2955  HasUndefinedConstructors(false) {}
2956 
2957  /// Checks whether pointee of a delete-expression is initialized with
2958  /// matching form of new-expression.
2959  ///
2960  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2961  /// point where delete-expression is encountered, then a warning will be
2962  /// issued immediately. If return value is \c AnalyzeLater at the point where
2963  /// delete-expression is seen, then member will be analyzed at the end of
2964  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2965  /// couldn't be analyzed. If at least one constructor initializes the member
2966  /// with matching type of new, the return value is \c NoMismatch.
2967  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2968  /// Analyzes a class member.
2969  /// \param Field Class member to analyze.
2970  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2971  /// for deleting the \p Field.
2972  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2973  FieldDecl *Field;
2974  /// List of mismatching new-expressions used for initialization of the pointee
2976  /// Indicates whether delete-expression was in array form.
2977  bool IsArrayForm;
2978 
2979 private:
2980  const bool EndOfTU;
2981  /// Indicates that there is at least one constructor without body.
2982  bool HasUndefinedConstructors;
2983  /// Returns \c CXXNewExpr from given initialization expression.
2984  /// \param E Expression used for initializing pointee in delete-expression.
2985  /// E can be a single-element \c InitListExpr consisting of new-expression.
2986  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2987  /// Returns whether member is initialized with mismatching form of
2988  /// \c new either by the member initializer or in-class initialization.
2989  ///
2990  /// If bodies of all constructors are not visible at the end of translation
2991  /// unit or at least one constructor initializes member with the matching
2992  /// form of \c new, mismatch cannot be proven, and this function will return
2993  /// \c NoMismatch.
2994  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2995  /// Returns whether variable is initialized with mismatching form of
2996  /// \c new.
2997  ///
2998  /// If variable is initialized with matching form of \c new or variable is not
2999  /// initialized with a \c new expression, this function will return true.
3000  /// If variable is initialized with mismatching form of \c new, returns false.
3001  /// \param D Variable to analyze.
3002  bool hasMatchingVarInit(const DeclRefExpr *D);
3003  /// Checks whether the constructor initializes pointee with mismatching
3004  /// form of \c new.
3005  ///
3006  /// Returns true, if member is initialized with matching form of \c new in
3007  /// member initializer list. Returns false, if member is initialized with the
3008  /// matching form of \c new in this constructor's initializer or given
3009  /// constructor isn't defined at the point where delete-expression is seen, or
3010  /// member isn't initialized by the constructor.
3011  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3012  /// Checks whether member is initialized with matching form of
3013  /// \c new in member initializer list.
3014  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3015  /// Checks whether member is initialized with mismatching form of \c new by
3016  /// in-class initializer.
3017  MismatchResult analyzeInClassInitializer();
3018 };
3019 }
3020 
3021 MismatchingNewDeleteDetector::MismatchResult
3022 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3023  NewExprs.clear();
3024  assert(DE && "Expected delete-expression");
3025  IsArrayForm = DE->isArrayForm();
3026  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3027  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3028  return analyzeMemberExpr(ME);
3029  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3030  if (!hasMatchingVarInit(D))
3031  return VarInitMismatches;
3032  }
3033  return NoMismatch;
3034 }
3035 
3036 const CXXNewExpr *
3037 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3038  assert(E != nullptr && "Expected a valid initializer expression");
3039  E = E->IgnoreParenImpCasts();
3040  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3041  if (ILE->getNumInits() == 1)
3042  E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3043  }
3044 
3045  return dyn_cast_or_null<const CXXNewExpr>(E);
3046 }
3047 
3048 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3049  const CXXCtorInitializer *CI) {
3050  const CXXNewExpr *NE = nullptr;
3051  if (Field == CI->getMember() &&
3052  (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3053  if (NE->isArray() == IsArrayForm)
3054  return true;
3055  else
3056  NewExprs.push_back(NE);
3057  }
3058  return false;
3059 }
3060 
3061 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3062  const CXXConstructorDecl *CD) {
3063  if (CD->isImplicit())
3064  return false;
3065  const FunctionDecl *Definition = CD;
3066  if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3067  HasUndefinedConstructors = true;
3068  return EndOfTU;
3069  }
3070  for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3071  if (hasMatchingNewInCtorInit(CI))
3072  return true;
3073  }
3074  return false;
3075 }
3076 
3077 MismatchingNewDeleteDetector::MismatchResult
3078 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3079  assert(Field != nullptr && "This should be called only for members");
3080  const Expr *InitExpr = Field->getInClassInitializer();
3081  if (!InitExpr)
3082  return EndOfTU ? NoMismatch : AnalyzeLater;
3083  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3084  if (NE->isArray() != IsArrayForm) {
3085  NewExprs.push_back(NE);
3086  return MemberInitMismatches;
3087  }
3088  }
3089  return NoMismatch;
3090 }
3091 
3092 MismatchingNewDeleteDetector::MismatchResult
3093 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3094  bool DeleteWasArrayForm) {
3095  assert(Field != nullptr && "Analysis requires a valid class member.");
3096  this->Field = Field;
3097  IsArrayForm = DeleteWasArrayForm;
3098  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3099  for (const auto *CD : RD->ctors()) {
3100  if (hasMatchingNewInCtor(CD))
3101  return NoMismatch;
3102  }
3103  if (HasUndefinedConstructors)
3104  return EndOfTU ? NoMismatch : AnalyzeLater;
3105  if (!NewExprs.empty())
3106  return MemberInitMismatches;
3107  return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3108  : NoMismatch;
3109 }
3110 
3111 MismatchingNewDeleteDetector::MismatchResult
3112 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3113  assert(ME != nullptr && "Expected a member expression");
3114  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3115  return analyzeField(F, IsArrayForm);
3116  return NoMismatch;
3117 }
3118 
3119 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3120  const CXXNewExpr *NE = nullptr;
3121  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3122  if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3123  NE->isArray() != IsArrayForm) {
3124  NewExprs.push_back(NE);
3125  }
3126  }
3127  return NewExprs.empty();
3128 }
3129 
3130 static void
3132  const MismatchingNewDeleteDetector &Detector) {
3133  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3134  FixItHint H;
3135  if (!Detector.IsArrayForm)
3136  H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3137  else {
3139  DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3140  SemaRef.getLangOpts(), true);
3141  if (RSquare.isValid())
3142  H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3143  }
3144  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3145  << Detector.IsArrayForm << H;
3146 
3147  for (const auto *NE : Detector.NewExprs)
3148  SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3149  << Detector.IsArrayForm;
3150 }
3151 
3152 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3153  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3154  return;
3155  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3156  switch (Detector.analyzeDeleteExpr(DE)) {
3157  case MismatchingNewDeleteDetector::VarInitMismatches:
3158  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3159  DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3160  break;
3161  }
3162  case MismatchingNewDeleteDetector::AnalyzeLater: {
3163  DeleteExprs[Detector.Field].push_back(
3164  std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3165  break;
3166  }
3167  case MismatchingNewDeleteDetector::NoMismatch:
3168  break;
3169  }
3170 }
3171 
3172 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3173  bool DeleteWasArrayForm) {
3174  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3175  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3176  case MismatchingNewDeleteDetector::VarInitMismatches:
3177  llvm_unreachable("This analysis should have been done for class members.");
3178  case MismatchingNewDeleteDetector::AnalyzeLater:
3179  llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3180  "translation unit.");
3181  case MismatchingNewDeleteDetector::MemberInitMismatches:
3182  DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3183  break;
3184  case MismatchingNewDeleteDetector::NoMismatch:
3185  break;
3186  }
3187 }
3188 
3189 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3190 /// @code ::delete ptr; @endcode
3191 /// or
3192 /// @code delete [] ptr; @endcode
3193 ExprResult
3194 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3195  bool ArrayForm, Expr *ExE) {
3196  // C++ [expr.delete]p1:
3197  // The operand shall have a pointer type, or a class type having a single
3198  // non-explicit conversion function to a pointer type. The result has type
3199  // void.
3200  //
3201  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3202 
3203  ExprResult Ex = ExE;
3204  FunctionDecl *OperatorDelete = nullptr;
3205  bool ArrayFormAsWritten = ArrayForm;
3206  bool UsualArrayDeleteWantsSize = false;
3207 
3208  if (!Ex.get()->isTypeDependent()) {
3209  // Perform lvalue-to-rvalue cast, if needed.
3210  Ex = DefaultLvalueConversion(Ex.get());
3211  if (Ex.isInvalid())
3212  return ExprError();
3213 
3214  QualType Type = Ex.get()->getType();
3215 
3216  class DeleteConverter : public ContextualImplicitConverter {
3217  public:
3218  DeleteConverter() : ContextualImplicitConverter(false, true) {}
3219 
3220  bool match(QualType ConvType) override {
3221  // FIXME: If we have an operator T* and an operator void*, we must pick
3222  // the operator T*.
3223  if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3224  if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3225  return true;
3226  return false;
3227  }
3228 
3229  SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3230  QualType T) override {
3231  return S.Diag(Loc, diag::err_delete_operand) << T;
3232  }
3233 
3234  SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3235  QualType T) override {
3236  return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3237  }
3238 
3239  SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3240  QualType T,
3241  QualType ConvTy) override {
3242  return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3243  }
3244 
3245  SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3246  QualType ConvTy) override {
3247  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3248  << ConvTy;
3249  }
3250 
3251  SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3252  QualType T) override {
3253  return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3254  }
3255 
3256  SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3257  QualType ConvTy) override {
3258  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3259  << ConvTy;
3260  }
3261 
3262  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3263  QualType T,
3264  QualType ConvTy) override {
3265  llvm_unreachable("conversion functions are permitted");
3266  }
3267  } Converter;
3268 
3269  Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3270  if (Ex.isInvalid())
3271  return ExprError();
3272  Type = Ex.get()->getType();
3273  if (!Converter.match(Type))
3274  // FIXME: PerformContextualImplicitConversion should return ExprError
3275  // itself in this case.
3276  return ExprError();
3277 
3278  QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3279  QualType PointeeElem = Context.getBaseElementType(Pointee);
3280 
3281  if (Pointee.getAddressSpace() != LangAS::Default &&
3282  !getLangOpts().OpenCLCPlusPlus)
3283  return Diag(Ex.get()->getBeginLoc(),
3284  diag::err_address_space_qualified_delete)
3285  << Pointee.getUnqualifiedType()
3287 
3288  CXXRecordDecl *PointeeRD = nullptr;
3289  if (Pointee->isVoidType() && !isSFINAEContext()) {
3290  // The C++ standard bans deleting a pointer to a non-object type, which
3291  // effectively bans deletion of "void*". However, most compilers support
3292  // this, so we treat it as a warning unless we're in a SFINAE context.
3293  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3294  << Type << Ex.get()->getSourceRange();
3295  } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3296  return ExprError(Diag(StartLoc, diag::err_delete_operand)
3297  << Type << Ex.get()->getSourceRange());
3298  } else if (!Pointee->isDependentType()) {
3299  // FIXME: This can result in errors if the definition was imported from a
3300  // module but is hidden.
3301  if (!RequireCompleteType(StartLoc, Pointee,
3302  diag::warn_delete_incomplete, Ex.get())) {
3303  if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3304  PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3305  }
3306  }
3307 
3308  if (Pointee->isArrayType() && !ArrayForm) {
3309  Diag(StartLoc, diag::warn_delete_array_type)
3310  << Type << Ex.get()->getSourceRange()
3311  << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3312  ArrayForm = true;
3313  }
3314 
3316  ArrayForm ? OO_Array_Delete : OO_Delete);
3317 
3318  if (PointeeRD) {
3319  if (!UseGlobal &&
3320  FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3321  OperatorDelete))
3322  return ExprError();
3323 
3324  // If we're allocating an array of records, check whether the
3325  // usual operator delete[] has a size_t parameter.
3326  if (ArrayForm) {
3327  // If the user specifically asked to use the global allocator,
3328  // we'll need to do the lookup into the class.
3329  if (UseGlobal)
3330  UsualArrayDeleteWantsSize =
3331  doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3332 
3333  // Otherwise, the usual operator delete[] should be the
3334  // function we just found.
3335  else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3336  UsualArrayDeleteWantsSize =
3337  UsualDeallocFnInfo(*this,
3338  DeclAccessPair::make(OperatorDelete, AS_public))
3339  .HasSizeT;
3340  }
3341 
3342  if (!PointeeRD->hasIrrelevantDestructor())
3343  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3344  MarkFunctionReferenced(StartLoc,
3345  const_cast<CXXDestructorDecl*>(Dtor));
3346  if (DiagnoseUseOfDecl(Dtor, StartLoc))
3347  return ExprError();
3348  }
3349 
3350  CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3351  /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3352  /*WarnOnNonAbstractTypes=*/!ArrayForm,
3353  SourceLocation());
3354  }
3355 
3356  if (!OperatorDelete) {
3357  if (getLangOpts().OpenCLCPlusPlus) {
3358  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3359  return ExprError();
3360  }
3361 
3362  bool IsComplete = isCompleteType(StartLoc, Pointee);
3363  bool CanProvideSize =
3364  IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3365  Pointee.isDestructedType());
3366  bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3367 
3368  // Look for a global declaration.
3369  OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3370  Overaligned, DeleteName);
3371  }
3372 
3373  MarkFunctionReferenced(StartLoc, OperatorDelete);
3374 
3375  // Check access and ambiguity of destructor if we're going to call it.
3376  // Note that this is required even for a virtual delete.
3377  bool IsVirtualDelete = false;
3378  if (PointeeRD) {
3379  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3380  CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3381  PDiag(diag::err_access_dtor) << PointeeElem);
3382  IsVirtualDelete = Dtor->isVirtual();
3383  }
3384  }
3385 
3386  diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3387  *this);
3388 
3389  // Convert the operand to the type of the first parameter of operator
3390  // delete. This is only necessary if we selected a destroying operator
3391  // delete that we are going to call (non-virtually); converting to void*
3392  // is trivial and left to AST consumers to handle.
3393  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3394  if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3395  Qualifiers Qs = Pointee.getQualifiers();
3396  if (Qs.hasCVRQualifiers()) {
3397  // Qualifiers are irrelevant to this conversion; we're only looking
3398  // for access and ambiguity.
3399  Qs.removeCVRQualifiers();
3400  QualType Unqual = Context.getPointerType(
3402  Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3403  }
3404  Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3405  if (Ex.isInvalid())
3406  return ExprError();
3407  }
3408  }
3409 
3411  Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3412  UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3413  AnalyzeDeleteExprMismatch(Result);
3414  return Result;
3415 }
3416 
3418  bool IsDelete,
3419  FunctionDecl *&Operator) {
3420 
3422  IsDelete ? OO_Delete : OO_New);
3423 
3424  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3426  assert(!R.empty() && "implicitly declared allocation functions not found");
3427  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3428 
3429  // We do our own custom access checks below.
3430  R.suppressDiagnostics();
3431 
3432  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3433  OverloadCandidateSet Candidates(R.getNameLoc(),
3435  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3436  FnOvl != FnOvlEnd; ++FnOvl) {
3437  // Even member operator new/delete are implicitly treated as
3438  // static, so don't use AddMemberCandidate.
3439  NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3440 
3441  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3442  S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3443  /*ExplicitTemplateArgs=*/nullptr, Args,
3444  Candidates,
3445  /*SuppressUserConversions=*/false);
3446  continue;
3447  }
3448 
3449  FunctionDecl *Fn = cast<FunctionDecl>(D);
3450  S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3451  /*SuppressUserConversions=*/false);
3452  }
3453 
3454  SourceRange Range = TheCall->getSourceRange();
3455 
3456  // Do the resolution.
3458  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3459  case OR_Success: {
3460  // Got one!
3461  FunctionDecl *FnDecl = Best->Function;
3462  assert(R.getNamingClass() == nullptr &&
3463  "class members should not be considered");
3464 
3465  if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3466  S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3467  << (IsDelete ? 1 : 0) << Range;
3468  S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3469  << R.getLookupName() << FnDecl->getSourceRange();
3470  return true;
3471  }
3472 
3473  Operator = FnDecl;
3474  return false;
3475  }
3476 
3477  case OR_No_Viable_Function:
3478  S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3479  << R.getLookupName() << Range;
3480  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3481  return true;
3482 
3483  case OR_Ambiguous:
3484  S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3485  << R.getLookupName() << Range;
3486  Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3487  return true;
3488 
3489  case OR_Deleted: {
3490  S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3491  << Best->Function->isDeleted() << R.getLookupName()
3492  << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3493  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3494  return true;
3495  }
3496  }
3497  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3498 }
3499 
3500 ExprResult
3501 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3502  bool IsDelete) {
3503  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3504  if (!getLangOpts().CPlusPlus) {
3505  Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3506  << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3507  << "C++";
3508  return ExprError();
3509  }
3510  // CodeGen assumes it can find the global new and delete to call,
3511  // so ensure that they are declared.
3513 
3514  FunctionDecl *OperatorNewOrDelete = nullptr;
3515  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3516  OperatorNewOrDelete))
3517  return ExprError();
3518  assert(OperatorNewOrDelete && "should be found");
3519 
3520  TheCall->setType(OperatorNewOrDelete->getReturnType());
3521  for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3522  QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3523  InitializedEntity Entity =
3526  Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3527  if (Arg.isInvalid())
3528  return ExprError();
3529  TheCall->setArg(i, Arg.get());
3530  }
3531  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3532  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3533  "Callee expected to be implicit cast to a builtin function pointer");
3534  Callee->setType(OperatorNewOrDelete->getType());
3535 
3536  return TheCallResult;
3537 }
3538 
3540  bool IsDelete, bool CallCanBeVirtual,
3541  bool WarnOnNonAbstractTypes,
3542  SourceLocation DtorLoc) {
3543  if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3544  return;
3545 
3546  // C++ [expr.delete]p3:
3547  // In the first alternative (delete object), if the static type of the
3548  // object to be deleted is different from its dynamic type, the static
3549  // type shall be a base class of the dynamic type of the object to be
3550  // deleted and the static type shall have a virtual destructor or the
3551  // behavior is undefined.
3552  //
3553  const CXXRecordDecl *PointeeRD = dtor->getParent();
3554  // Note: a final class cannot be derived from, no issue there
3555  if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3556  return;
3557 
3558  // If the superclass is in a system header, there's nothing that can be done.
3559  // The `delete` (where we emit the warning) can be in a system header,
3560  // what matters for this warning is where the deleted type is defined.
3561  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3562  return;
3563 
3564  QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3565  if (PointeeRD->isAbstract()) {
3566  // If the class is abstract, we warn by default, because we're
3567  // sure the code has undefined behavior.
3568  Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3569  << ClassType;
3570  } else if (WarnOnNonAbstractTypes) {
3571  // Otherwise, if this is not an array delete, it's a bit suspect,
3572  // but not necessarily wrong.
3573  Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3574  << ClassType;
3575  }
3576  if (!IsDelete) {
3577  std::string TypeStr;
3578  ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3579  Diag(DtorLoc, diag::note_delete_non_virtual)
3580  << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3581  }
3582 }
3583 
3585  SourceLocation StmtLoc,
3586  ConditionKind CK) {
3587  ExprResult E =
3588  CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3589  if (E.isInvalid())
3590  return ConditionError();
3591  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3593 }
3594 
3595 /// Check the use of the given variable as a C++ condition in an if,
3596 /// while, do-while, or switch statement.
3598  SourceLocation StmtLoc,
3599  ConditionKind CK) {
3600  if (ConditionVar->isInvalidDecl())
3601  return ExprError();
3602 
3603  QualType T = ConditionVar->getType();
3604 
3605  // C++ [stmt.select]p2:
3606  // The declarator shall not specify a function or an array.
3607  if (T->isFunctionType())
3608  return ExprError(Diag(ConditionVar->getLocation(),
3609  diag::err_invalid_use_of_function_type)
3610  << ConditionVar->getSourceRange());
3611  else if (T->isArrayType())
3612  return ExprError(Diag(ConditionVar->getLocation(),
3613  diag::err_invalid_use_of_array_type)
3614  << ConditionVar->getSourceRange());
3615 
3616  ExprResult Condition = DeclRefExpr::Create(
3617  Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3618  /*enclosing*/ false, ConditionVar->getLocation(),
3619  ConditionVar->getType().getNonReferenceType(), VK_LValue);
3620 
3621  MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3622 
3623  switch (CK) {
3625  return CheckBooleanCondition(StmtLoc, Condition.get());
3626 
3628  return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3629 
3630  case ConditionKind::Switch:
3631  return CheckSwitchCondition(StmtLoc, Condition.get());
3632  }
3633 
3634  llvm_unreachable("unexpected condition kind");
3635 }
3636 
3637 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3638 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3639  // C++ 6.4p4:
3640  // The value of a condition that is an initialized declaration in a statement
3641  // other than a switch statement is the value of the declared variable
3642  // implicitly converted to type bool. If that conversion is ill-formed, the
3643  // program is ill-formed.
3644  // The value of a condition that is an expression is the value of the
3645  // expression, implicitly converted to bool.
3646  //
3647  // FIXME: Return this value to the caller so they don't need to recompute it.
3648  llvm::APSInt Value(/*BitWidth*/1);
3649  return (IsConstexpr && !CondExpr->isValueDependent())
3650  ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3653 }
3654 
3655 /// Helper function to determine whether this is the (deprecated) C++
3656 /// conversion from a string literal to a pointer to non-const char or
3657 /// non-const wchar_t (for narrow and wide string literals,
3658 /// respectively).
3659 bool
3661  // Look inside the implicit cast, if it exists.
3662  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3663  From = Cast->getSubExpr();
3664 
3665  // A string literal (2.13.4) that is not a wide string literal can
3666  // be converted to an rvalue of type "pointer to char"; a wide
3667  // string literal can be converted to an rvalue of type "pointer
3668  // to wchar_t" (C++ 4.2p2).
3669  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3670  if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3671  if (const BuiltinType *ToPointeeType
3672  = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3673  // This conversion is considered only when there is an
3674  // explicit appropriate pointer target type (C++ 4.2p2).
3675  if (!ToPtrType->getPointeeType().hasQualifiers()) {
3676  switch (StrLit->getKind()) {
3677  case StringLiteral::UTF8:
3678  case StringLiteral::UTF16:
3679  case StringLiteral::UTF32:
3680  // We don't allow UTF literals to be implicitly converted
3681  break;
3682  case StringLiteral::Ascii:
3683  return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3684  ToPointeeType->getKind() == BuiltinType::Char_S);
3685  case StringLiteral::Wide:
3687  QualType(ToPointeeType, 0));
3688  }
3689  }
3690  }
3691 
3692  return false;
3693 }
3694 
3696  SourceLocation CastLoc,
3697  QualType Ty,
3698  CastKind Kind,
3699  CXXMethodDecl *Method,
3700  DeclAccessPair FoundDecl,
3701  bool HadMultipleCandidates,
3702  Expr *From) {
3703  switch (Kind) {
3704  default: llvm_unreachable("Unhandled cast kind!");
3705  case CK_ConstructorConversion: {
3706  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3707  SmallVector<Expr*, 8> ConstructorArgs;
3708 
3709  if (S.RequireNonAbstractType(CastLoc, Ty,
3710  diag::err_allocation_of_abstract_type))
3711  return ExprError();
3712 
3713  if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3714  return ExprError();
3715 
3716  S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3718  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3719  return ExprError();
3720 
3722  CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3723  ConstructorArgs, HadMultipleCandidates,
3724  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3726  if (Result.isInvalid())
3727  return ExprError();
3728 
3729  return S.MaybeBindToTemporary(Result.getAs<Expr>());
3730  }
3731 
3732  case CK_UserDefinedConversion: {
3733  assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3734 
3735  S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3736  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3737  return ExprError();
3738 
3739  // Create an implicit call expr that calls it.
3740  CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3741  ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3742  HadMultipleCandidates);
3743  if (Result.isInvalid())
3744  return ExprError();
3745  // Record usage of conversion in an implicit cast.
3746  Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3747  CK_UserDefinedConversion, Result.get(),
3748  nullptr, Result.get()->getValueKind());
3749 
3750  return S.MaybeBindToTemporary(Result.get());
3751  }
3752  }
3753 }
3754 
3755 /// PerformImplicitConversion - Perform an implicit conversion of the
3756 /// expression From to the type ToType using the pre-computed implicit
3757 /// conversion sequence ICS. Returns the converted
3758 /// expression. Action is the kind of conversion we're performing,
3759 /// used in the error message.
3760 ExprResult
3762  const ImplicitConversionSequence &ICS,
3763  AssignmentAction Action,
3764  CheckedConversionKind CCK) {
3765  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3766  if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3767  return From;
3768 
3769  switch (ICS.getKind()) {
3771  ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3772  Action, CCK);
3773  if (Res.isInvalid())
3774  return ExprError();
3775  From = Res.get();
3776  break;
3777  }
3778 
3780 
3783  QualType BeforeToType;
3784  assert(FD && "no conversion function for user-defined conversion seq");
3785  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3786  CastKind = CK_UserDefinedConversion;
3787 
3788  // If the user-defined conversion is specified by a conversion function,
3789  // the initial standard conversion sequence converts the source type to
3790  // the implicit object parameter of the conversion function.
3791  BeforeToType = Context.getTagDeclType(Conv->getParent());
3792  } else {
3793  const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3794  CastKind = CK_ConstructorConversion;
3795  // Do no conversion if dealing with ... for the first conversion.
3796  if (!ICS.UserDefined.EllipsisConversion) {
3797  // If the user-defined conversion is specified by a constructor, the
3798  // initial standard conversion sequence converts the source type to
3799  // the type required by the argument of the constructor
3800  BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3801  }
3802  }
3803  // Watch out for ellipsis conversion.
3804  if (!ICS.UserDefined.EllipsisConversion) {
3805  ExprResult Res =
3806  PerformImplicitConversion(From, BeforeToType,
3808  CCK);
3809  if (Res.isInvalid())
3810  return ExprError();
3811  From = Res.get();
3812  }
3813 
3814  ExprResult CastArg = BuildCXXCastArgument(
3815  *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3816  cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3818 
3819  if (CastArg.isInvalid())
3820  return ExprError();
3821 
3822  From = CastArg.get();
3823 
3824  // C++ [over.match.oper]p7:
3825  // [...] the second standard conversion sequence of a user-defined
3826  // conversion sequence is not applied.
3827  if (CCK == CCK_ForBuiltinOverloadedOp)
3828  return From;
3829 
3830  return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3831  AA_Converting, CCK);
3832  }
3833 
3835  ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3836  PDiag(diag::err_typecheck_ambiguous_condition)
3837  << From->getSourceRange());
3838  return ExprError();
3839 
3841  llvm_unreachable("Cannot perform an ellipsis conversion");
3842 
3844  bool Diagnosed =
3846  From->getType(), From, Action);
3847  assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3848  return ExprError();
3849  }
3850 
3851  // Everything went well.
3852  return From;
3853 }
3854 
3855 /// PerformImplicitConversion - Perform an implicit conversion of the
3856 /// expression From to the type ToType by following the standard
3857 /// conversion sequence SCS. Returns the converted
3858 /// expression. Flavor is the context in which we're performing this
3859 /// conversion, for use in error messages.
3860 ExprResult
3862  const StandardConversionSequence& SCS,
3863  AssignmentAction Action,
3864  CheckedConversionKind CCK) {
3865  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3866 
3867  // Overall FIXME: we are recomputing too many types here and doing far too
3868  // much extra work. What this means is that we need to keep track of more
3869  // information that is computed when we try the implicit conversion initially,
3870  // so that we don't need to recompute anything here.
3871  QualType FromType = From->getType();
3872 
3873  if (SCS.CopyConstructor) {
3874  // FIXME: When can ToType be a reference type?
3875  assert(!ToType->isReferenceType());
3876  if (SCS.Second == ICK_Derived_To_Base) {
3877  SmallVector<Expr*, 8> ConstructorArgs;
3878  if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3879  From, /*FIXME:ConstructLoc*/SourceLocation(),
3880  ConstructorArgs))
3881  return ExprError();
3882  return BuildCXXConstructExpr(
3883  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3885  ConstructorArgs, /*HadMultipleCandidates*/ false,
3886  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3888  }
3889  return BuildCXXConstructExpr(
3890  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3892  From, /*HadMultipleCandidates*/ false,
3893  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3895  }
3896 
3897  // Resolve overloaded function references.
3898  if (Context.hasSameType(FromType, Context.OverloadTy)) {
3899  DeclAccessPair Found;
3901  true, Found);
3902  if (!Fn)
3903  return ExprError();
3904 
3905  if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3906  return ExprError();
3907 
3908  From = FixOverloadedFunctionReference(From, Found, Fn);
3909  FromType = From->getType();
3910  }
3911 
3912  // If we're converting to an atomic type, first convert to the corresponding
3913  // non-atomic type.
3914  QualType ToAtomicType;
3915  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3916  ToAtomicType = ToType;
3917  ToType = ToAtomic->getValueType();
3918  }
3919 
3920  QualType InitialFromType = FromType;
3921  // Perform the first implicit conversion.
3922  switch (SCS.First) {
3923  case ICK_Identity:
3924  if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3925  FromType = FromAtomic->getValueType().getUnqualifiedType();
3926  From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3927  From, /*BasePath=*/nullptr, VK_RValue);
3928  }
3929  break;
3930 
3931  case ICK_Lvalue_To_Rvalue: {
3932  assert(From->getObjectKind() != OK_ObjCProperty);
3933  ExprResult FromRes = DefaultLvalueConversion(From);
3934  assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3935  From = FromRes.get();
3936  FromType = From->getType();
3937  break;
3938  }
3939 
3940  case ICK_Array_To_Pointer:
3941  FromType = Context.getArrayDecayedType(FromType);
3942  From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3943  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3944  break;
3945 
3947  FromType = Context.getPointerType(FromType);
3948  From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3949  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3950  break;
3951 
3952  default:
3953  llvm_unreachable("Improper first standard conversion");
3954  }
3955 
3956  // Perform the second implicit conversion
3957  switch (SCS.Second) {
3958  case ICK_Identity:
3959  // C++ [except.spec]p5:
3960  // [For] assignment to and initialization of pointers to functions,
3961  // pointers to member functions, and references to functions: the
3962  // target entity shall allow at least the exceptions allowed by the
3963  // source value in the assignment or initialization.
3964  switch (Action) {
3965  case AA_Assigning:
3966  case AA_Initializing:
3967  // Note, function argument passing and returning are initialization.
3968  case AA_Passing:
3969  case AA_Returning:
3970  case AA_Sending:
3971  case AA_Passing_CFAudited:
3972  if (CheckExceptionSpecCompatibility(From, ToType))
3973  return ExprError();
3974  break;
3975 
3976  case AA_Casting:
3977  case AA_Converting:
3978  // Casts and implicit conversions are not initialization, so are not
3979  // checked for exception specification mismatches.
3980  break;
3981  }
3982  // Nothing else to do.
3983  break;
3984 
3987  if (ToType->isBooleanType()) {
3988  assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3989  SCS.Second == ICK_Integral_Promotion &&
3990  "only enums with fixed underlying type can promote to bool");
3991  From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3992  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3993  } else {
3994  From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3995  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3996  }
3997  break;
3998 
4001  From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4002  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4003  break;
4004 
4005  case ICK_Complex_Promotion:
4006  case ICK_Complex_Conversion: {
4007  QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4008  QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4009  CastKind CK;
4010  if (FromEl->isRealFloatingType()) {
4011  if (ToEl->isRealFloatingType())
4012  CK = CK_FloatingComplexCast;
4013  else
4014  CK = CK_FloatingComplexToIntegralComplex;
4015  } else if (ToEl->isRealFloatingType()) {
4016  CK = CK_IntegralComplexToFloatingComplex;
4017  } else {
4018  CK = CK_IntegralComplexCast;
4019  }
4020  From = ImpCastExprToType(From, ToType, CK,
4021  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4022  break;
4023  }
4024 
4025  case ICK_Floating_Integral:
4026  if (ToType->isRealFloatingType())
4027  From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4028  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4029  else
4030  From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4031  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4032  break;
4033 
4035  From = ImpCastExprToType(From, ToType, CK_NoOp,
4036  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4037  break;
4038 
4040  case ICK_Pointer_Conversion: {
4041  if (SCS.IncompatibleObjC && Action != AA_Casting) {
4042  // Diagnose incompatible Objective-C conversions
4043  if (Action == AA_Initializing || Action == AA_Assigning)
4044  Diag(From->getBeginLoc(),
4045  diag::ext_typecheck_convert_incompatible_pointer)
4046  << ToType << From->getType() << Action << From->getSourceRange()
4047  << 0;
4048  else
4049  Diag(From->getBeginLoc(),
4050  diag::ext_typecheck_convert_incompatible_pointer)
4051  << From->getType() << ToType << Action << From->getSourceRange()
4052  << 0;
4053 
4054  if (From->getType()->isObjCObjectPointerType() &&
4055  ToType->isObjCObjectPointerType())
4059  From->getType())) {
4060  if (Action == AA_Initializing)
4061  Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4062  else
4063  Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4064  << (Action == AA_Casting) << From->getType() << ToType
4065  << From->getSourceRange();
4066  }
4067 
4068  CastKind Kind;
4069  CXXCastPath BasePath;
4070  if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
4071  return ExprError();
4072 
4073  // Make sure we extend blocks if necessary.
4074  // FIXME: doing this here is really ugly.
4075  if (Kind == CK_BlockPointerToObjCPointerCast) {
4076  ExprResult E = From;
4078  From = E.get();
4079  }
4080  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4081  CheckObjCConversion(SourceRange(), ToType, From, CCK);
4082  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4083  .get();
4084  break;
4085  }
4086 
4087  case ICK_Pointer_Member: {
4088  CastKind Kind;
4089  CXXCastPath BasePath;
4090  if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4091  return ExprError();
4092  if (CheckExceptionSpecCompatibility(From, ToType))
4093  return ExprError();
4094 
4095  // We may not have been able to figure out what this member pointer resolved
4096  // to up until this exact point. Attempt to lock-in it's inheritance model.
4098  (void)isCompleteType(From->getExprLoc(), From->getType());
4099  (void)isCompleteType(From->getExprLoc(), ToType);
4100  }
4101 
4102  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4103  .get();
4104  break;
4105  }
4106 
4108  // Perform half-to-boolean conversion via float.
4109  if (From->getType()->isHalfType()) {
4110  From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4111  FromType = Context.FloatTy;
4112  }
4113 
4114  From = ImpCastExprToType(From, Context.BoolTy,
4115  ScalarTypeToBooleanCastKind(FromType),
4116  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4117  break;
4118 
4119  case ICK_Derived_To_Base: {
4120  CXXCastPath BasePath;
4122  From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4123  From->getSourceRange(), &BasePath, CStyle))
4124  return ExprError();
4125 
4126  From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4127  CK_DerivedToBase, From->getValueKind(),
4128  &BasePath, CCK).get();
4129  break;
4130  }
4131 
4132  case ICK_Vector_Conversion:
4133  From = ImpCastExprToType(From, ToType, CK_BitCast,
4134  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4135  break;
4136 
4137  case ICK_Vector_Splat: {
4138  // Vector splat from any arithmetic type to a vector.
4139  Expr *Elem = prepareVectorSplat(ToType, From).get();
4140  From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4141  /*BasePath=*/nullptr, CCK).get();
4142  break;
4143  }
4144 
4145  case ICK_Complex_Real:
4146  // Case 1. x -> _Complex y
4147  if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4148  QualType ElType = ToComplex->getElementType();
4149  bool isFloatingComplex = ElType->isRealFloatingType();
4150 
4151  // x -> y
4152  if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4153  // do nothing
4154  } else if (From->getType()->isRealFloatingType()) {
4155  From = ImpCastExprToType(From, ElType,
4156  isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4157  } else {
4158  assert(From->getType()->isIntegerType());
4159  From = ImpCastExprToType(From, ElType,
4160  isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4161  }
4162  // y -> _Complex y
4163  From = ImpCastExprToType(From, ToType,
4164  isFloatingComplex ? CK_FloatingRealToComplex
4165  : CK_IntegralRealToComplex).get();
4166 
4167  // Case 2. _Complex x -> y
4168  } else {
4169  const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4170  assert(FromComplex);
4171 
4172  QualType ElType = FromComplex->getElementType();
4173  bool isFloatingComplex = ElType->isRealFloatingType();
4174 
4175  // _Complex x -> x
4176  From = ImpCastExprToType(From, ElType,
4177  isFloatingComplex ? CK_FloatingComplexToReal
4178  : CK_IntegralComplexToReal,
4179  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4180 
4181  // x -> y
4182  if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4183  // do nothing
4184  } else if (ToType->isRealFloatingType()) {
4185  From = ImpCastExprToType(From, ToType,
4186  isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4187  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4188  } else {
4189  assert(ToType->isIntegerType());
4190  From = ImpCastExprToType(From, ToType,
4191  isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4192  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4193  }
4194  }
4195  break;
4196 
4198  From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
4199  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4200  break;
4201  }
4202 
4204  ExprResult FromRes = From;
4205  Sema::AssignConvertType ConvTy =
4207  if (FromRes.isInvalid())
4208  return ExprError();
4209  From = FromRes.get();
4210  assert ((ConvTy == Sema::Compatible) &&
4211  "Improper transparent union conversion");
4212  (void)ConvTy;
4213  break;
4214  }
4215 
4217  From = ImpCastExprToType(From, ToType,
4218  CK_ZeroToOCLEvent,
4219  From->getValueKind()).get();
4220  break;
4221 
4223  From = ImpCastExprToType(From, ToType,
4224  CK_ZeroToOCLQueue,
4225  From->getValueKind()).get();
4226  break;
4227 
4228  case ICK_Lvalue_To_Rvalue:
4229  case ICK_Array_To_Pointer:
4232  case ICK_Qualification:
4234  case ICK_C_Only_Conversion:
4236  llvm_unreachable("Improper second standard conversion");
4237  }
4238 
4239  switch (SCS.Third) {
4240  case ICK_Identity:
4241  // Nothing to do.
4242  break;
4243 
4245  // If both sides are functions (or pointers/references to them), there could
4246  // be incompatible exception declarations.
4247  if (CheckExceptionSpecCompatibility(From, ToType))
4248  return ExprError();
4249 
4250  From = ImpCastExprToType(From, ToType, CK_NoOp,
4251  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4252  break;
4253 
4254  case ICK_Qualification: {
4255  // The qualification keeps the category of the inner expression, unless the
4256  // target type isn't a reference.
4257  ExprValueKind VK = ToType->isReferenceType() ?
4258  From->getValueKind() : VK_RValue;
4259  From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
4260  CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
4261 
4263  !getLangOpts().WritableStrings) {
4264  Diag(From->getBeginLoc(),
4265  getLangOpts().CPlusPlus11
4266  ? diag::ext_deprecated_string_literal_conversion
4267  : diag::warn_deprecated_string_literal_conversion)
4268  << ToType.getNonReferenceType();
4269  }
4270 
4271  break;
4272  }
4273 
4274  default:
4275  llvm_unreachable("Improper third standard conversion");
4276  }
4277 
4278  // If this conversion sequence involved a scalar -> atomic conversion, perform
4279  // that conversion now.
4280  if (!ToAtomicType.isNull()) {
4281  assert(Context.hasSameType(
4282  ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4283  From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4284  VK_RValue, nullptr, CCK).get();
4285  }
4286 
4287  // If this conversion sequence succeeded and involved implicitly converting a
4288  // _Nullable type to a _Nonnull one, complain.
4289  if (!isCast(CCK))
4290  diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4291  From->getBeginLoc());
4292 
4293  return From;
4294 }
4295 
4296 /// Check the completeness of a type in a unary type trait.
4297 ///
4298 /// If the particular type trait requires a complete type, tries to complete
4299 /// it. If completing the type fails, a diagnostic is emitted and false
4300 /// returned. If completing the type succeeds or no completion was required,
4301 /// returns true.
4303  SourceLocation Loc,
4304  QualType ArgTy) {
4305  // C++0x [meta.unary.prop]p3:
4306  // For all of the class templates X declared in this Clause, instantiating
4307  // that template with a template argument that is a class template
4308  // specialization may result in the implicit instantiation of the template
4309  // argument if and only if the semantics of X require that the argument
4310  // must be a complete type.
4311  // We apply this rule to all the type trait expressions used to implement
4312  // these class templates. We also try to follow any GCC documented behavior
4313  // in these expressions to ensure portability of standard libraries.
4314  switch (UTT) {
4315  default: llvm_unreachable("not a UTT");
4316  // is_complete_type somewhat obviously cannot require a complete type.
4317  case UTT_IsCompleteType:
4318  // Fall-through
4319 
4320  // These traits are modeled on the type predicates in C++0x
4321  // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4322  // requiring a complete type, as whether or not they return true cannot be
4323  // impacted by the completeness of the type.
4324  case UTT_IsVoid:
4325  case UTT_IsIntegral:
4326  case UTT_IsFloatingPoint:
4327  case UTT_IsArray:
4328  case UTT_IsPointer:
4329  case UTT_IsLvalueReference:
4330  case UTT_IsRvalueReference:
4333  case UTT_IsEnum:
4334  case UTT_IsUnion:
4335  case UTT_IsClass:
4336  case UTT_IsFunction:
4337  case UTT_IsReference:
4338  case UTT_IsArithmetic:
4339  case UTT_IsFundamental:
4340  case UTT_IsObject:
4341  case UTT_IsScalar:
4342  case UTT_IsCompound:
4343  case UTT_IsMemberPointer:
4344  // Fall-through
4345 
4346  // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4347  // which requires some of its traits to have the complete type. However,
4348  // the completeness of the type cannot impact these traits' semantics, and
4349  // so they don't require it. This matches the comments on these traits in
4350  // Table 49.
4351  case UTT_IsConst:
4352  case UTT_IsVolatile:
4353  case UTT_IsSigned:
4354  case UTT_IsUnsigned:
4355 
4356  // This type trait always returns false, checking the type is moot.
4357  case UTT_IsInterfaceClass:
4358  return true;
4359 
4360  // C++14 [meta.unary.prop]:
4361  // If T is a non-union class type, T shall be a complete type.
4362  case UTT_IsEmpty:
4363  case UTT_IsPolymorphic:
4364  case UTT_IsAbstract:
4365  if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4366  if (!RD->isUnion())
4367  return !S.RequireCompleteType(
4368  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4369  return true;
4370 
4371  // C++14 [meta.unary.prop]:
4372  // If T is a class type, T shall be a complete type.
4373  case UTT_IsFinal:
4374  case UTT_IsSealed:
4375  if (ArgTy->getAsCXXRecordDecl())
4376  return !S.RequireCompleteType(
4377  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4378  return true;
4379 
4380  // C++1z [meta.unary.prop]:
4381  // remove_all_extents_t<T> shall be a complete type or cv void.
4382  case UTT_IsAggregate:
4383  case UTT_IsTrivial:
4385  case UTT_IsStandardLayout:
4386  case UTT_IsPOD:
4387  case UTT_IsLiteral:
4388  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4389  // or an array of unknown bound. But GCC actually imposes the same constraints
4390  // as above.
4391  case UTT_HasNothrowAssign:
4394  case UTT_HasNothrowCopy:
4395  case UTT_HasTrivialAssign:
4399  case UTT_HasTrivialCopy:
4402  ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4403  LLVM_FALLTHROUGH;
4404 
4405  // C++1z [meta.unary.prop]:
4406  // T shall be a complete type, cv void, or an array of unknown bound.
4407  case UTT_IsDestructible:
4411  if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4412  return true;
4413 
4414  return !S.RequireCompleteType(
4415  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4416  }
4417 }
4418 
4420  Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4421  bool (CXXRecordDecl::*HasTrivial)() const,
4422  bool (CXXRecordDecl::*HasNonTrivial)() const,
4423  bool (CXXMethodDecl::*IsDesiredOp)() const)
4424 {
4425  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4426  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4427  return true;
4428 
4430  DeclarationNameInfo NameInfo(Name, KeyLoc);
4431  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4432  if (Self.LookupQualifiedName(Res, RD)) {
4433  bool FoundOperator = false;
4434  Res.suppressDiagnostics();
4435  for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4436  Op != OpEnd; ++Op) {
4437  if (isa<FunctionTemplateDecl>(*Op))
4438  continue;
4439 
4440  CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4441  if((Operator->*IsDesiredOp)()) {
4442  FoundOperator = true;
4443  const FunctionProtoType *CPT =
4444  Operator->getType()->getAs<FunctionProtoType>();
4445  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4446  if (!CPT || !CPT->isNothrow())
4447  return false;
4448  }
4449  }
4450  return FoundOperator;
4451  }
4452  return false;
4453 }
4454 
4455 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4456  SourceLocation KeyLoc, QualType T) {
4457  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4458 
4459  ASTContext &C = Self.Context;
4460  switch(UTT) {
4461  default: llvm_unreachable("not a UTT");
4462  // Type trait expressions corresponding to the primary type category
4463  // predicates in C++0x [meta.unary.cat].
4464  case UTT_IsVoid:
4465  return T->isVoidType();
4466  case UTT_IsIntegral:
4467  return T->isIntegralType(C);
4468  case UTT_IsFloatingPoint:
4469  return T->isFloatingType();
4470  case UTT_IsArray:
4471  return T->isArrayType();
4472  case UTT_IsPointer:
4473  return T->isPointerType();
4474  case UTT_IsLvalueReference:
4475  return T->isLValueReferenceType();
4476  case UTT_IsRvalueReference:
4477  return T->isRValueReferenceType();
4479  return T->isMemberFunctionPointerType();
4481  return T->isMemberDataPointerType();
4482  case UTT_IsEnum:
4483  return T->isEnumeralType();
4484  case UTT_IsUnion:
4485  return T->isUnionType();
4486  case UTT_IsClass:
4487  return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4488  case UTT_IsFunction:
4489  return T->isFunctionType();
4490 
4491  // Type trait expressions which correspond to the convenient composition
4492  // predicates in C++0x [meta.unary.comp].
4493  case UTT_IsReference:
4494  return T->isReferenceType();
4495  case UTT_IsArithmetic:
4496  return T->isArithmeticType() && !T->isEnumeralType();
4497  case UTT_IsFundamental:
4498  return T->isFundamentalType();
4499  case UTT_IsObject:
4500  return T->isObjectType();
4501  case UTT_IsScalar:
4502  // Note: semantic analysis depends on Objective-C lifetime types to be
4503  // considered scalar types. However, such types do not actually behave
4504  // like scalar types at run time (since they may require retain/release
4505  // operations), so we report them as non-scalar.
4506  if (T->isObjCLifetimeType()) {
4507  switch (T.getObjCLifetime()) {
4508  case Qualifiers::OCL_None:
4510  return true;
4511 
4513  case Qualifiers::OCL_Weak:
4515  return false;
4516  }
4517  }
4518 
4519  return T->isScalarType();
4520  case UTT_IsCompound:
4521  return T->isCompoundType();
4522  case UTT_IsMemberPointer:
4523  return T->isMemberPointerType();
4524 
4525  // Type trait expressions which correspond to the type property predicates
4526  // in C++0x [meta.unary.prop].
4527  case UTT_IsConst:
4528  return T.isConstQualified();
4529  case UTT_IsVolatile:
4530  return T.isVolatileQualified();
4531  case UTT_IsTrivial:
4532  return T.isTrivialType(C);
4534  return T.isTriviallyCopyableType(C);
4535  case UTT_IsStandardLayout:
4536  return T->isStandardLayoutType();
4537  case UTT_IsPOD:
4538  return T.isPODType(C);
4539  case UTT_IsLiteral:
4540  return T->isLiteralType(C);
4541  case UTT_IsEmpty:
4542  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4543  return !RD->isUnion() && RD->isEmpty();
4544  return false;
4545  case UTT_IsPolymorphic:
4546  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4547  return !RD->isUnion() && RD->isPolymorphic();
4548  return false;
4549  case UTT_IsAbstract:
4550  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4551  return !RD->isUnion() && RD->isAbstract();
4552  return false;
4553  case UTT_IsAggregate:
4554  // Report vector extensions and complex types as aggregates because they
4555  // support aggregate initialization. GCC mirrors this behavior for vectors
4556  // but not _Complex.
4557  return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4558  T->isAnyComplexType();
4559  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4560  // even then only when it is used with the 'interface struct ...' syntax
4561  // Clang doesn't support /CLR which makes this type trait moot.
4562  case UTT_IsInterfaceClass:
4563  return false;
4564  case UTT_IsFinal:
4565  case UTT_IsSealed:
4566  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4567  return RD->hasAttr<FinalAttr>();
4568  return false;
4569  case UTT_IsSigned:
4570  return T->isSignedIntegerType();
4571  case UTT_IsUnsigned:
4572  return T->isUnsignedIntegerType();
4573 
4574  // Type trait expressions which query classes regarding their construction,
4575  // destruction, and copying. Rather than being based directly on the
4576  // related type predicates in the standard, they are specified by both
4577  // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4578  // specifications.
4579  //
4580  // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4581  // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4582  //
4583  // Note that these builtins do not behave as documented in g++: if a class
4584  // has both a trivial and a non-trivial special member of a particular kind,
4585  // they return false! For now, we emulate this behavior.
4586  // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4587  // does not correctly compute triviality in the presence of multiple special
4588  // members of the same kind. Revisit this once the g++ bug is fixed.
4590  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4591  // If __is_pod (type) is true then the trait is true, else if type is
4592  // a cv class or union type (or array thereof) with a trivial default
4593  // constructor ([class.ctor]) then the trait is true, else it is false.
4594  if (T.isPODType(C))
4595  return true;
4596  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4597  return RD->hasTrivialDefaultConstructor() &&
4598  !RD->hasNonTrivialDefaultConstructor();
4599  return false;
4601  // This trait is implemented by MSVC 2012 and needed to parse the
4602  // standard library headers. Specifically this is used as the logic
4603  // behind std::is_trivially_move_constructible (20.9.4.3).
4604  if (T.isPODType(C))
4605  return true;
4606  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4607  return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4608  return false;
4609  case UTT_HasTrivialCopy:
4610  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4611  // If __is_pod (type) is true or type is a reference type then
4612  // the trait is true, else if type is a cv class or union type
4613  // with a trivial copy constructor ([class.copy]) then the trait
4614  // is true, else it is false.
4615  if (T.isPODType(C) || T->isReferenceType())
4616  return true;
4617  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4618  return RD->hasTrivialCopyConstructor() &&
4619  !RD->hasNonTrivialCopyConstructor();
4620  return false;
4622  // This trait is implemented by MSVC 2012 and needed to parse the
4623  // standard library headers. Specifically it is used as the logic
4624  // behind std::is_trivially_move_assignable (20.9.4.3)
4625  if (T.isPODType(C))
4626  return true;
4627  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4628  return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4629  return false;
4630  case UTT_HasTrivialAssign:
4631  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4632  // If type is const qualified or is a reference type then the
4633  // trait is false. Otherwise if __is_pod (type) is true then the
4634  // trait is true, else if type is a cv class or union type with
4635  // a trivial copy assignment ([class.copy]) then the trait is
4636  // true, else it is false.
4637  // Note: the const and reference restrictions are interesting,
4638  // given that const and reference members don't prevent a class
4639  // from having a trivial copy assignment operator (but do cause
4640  // errors if the copy assignment operator is actually used, q.v.
4641  // [class.copy]p12).
4642 
4643  if (T.isConstQualified())
4644  return false;
4645  if (T.isPODType(C))
4646  return true;
4647  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4648  return RD->hasTrivialCopyAssignment() &&
4649  !RD->hasNonTrivialCopyAssignment();
4650  return false;
4651  case UTT_IsDestructible:
4654  // C++14 [meta.unary.prop]:
4655  // For reference types, is_destructible<T>::value is true.
4656  if (T->isReferenceType())
4657  return true;
4658 
4659  // Objective-C++ ARC: autorelease types don't require destruction.
4660  if (T->isObjCLifetimeType() &&
4662  return true;
4663 
4664  // C++14 [meta.unary.prop]:
4665  // For incomplete types and function types, is_destructible<T>::value is
4666  // false.
4667  if (T->isIncompleteType() || T->isFunctionType())
4668  return false;
4669 
4670  // A type that requires destruction (via a non-trivial destructor or ARC
4671  // lifetime semantics) is not trivially-destructible.
4673  return false;
4674 
4675  // C++14 [meta.unary.prop]:
4676  // For object types and given U equal to remove_all_extents_t<T>, if the
4677  // expression std::declval<U&>().~U() is well-formed when treated as an
4678  // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4679  if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4680  CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4681  if (!Destructor)
4682  return false;
4683  // C++14 [dcl.fct.def.delete]p2:
4684  // A program that refers to a deleted function implicitly or
4685  // explicitly, other than to declare it, is ill-formed.
4686  if (Destructor->isDeleted())
4687  return false;
4688  if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4689  return false;
4690  if (UTT == UTT_IsNothrowDestructible) {
4691  const FunctionProtoType *CPT =
4692  Destructor->getType()->getAs<FunctionProtoType>();
4693  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4694  if (!CPT || !CPT->isNothrow())
4695  return false;
4696  }
4697  }
4698  return true;
4699 
4701  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4702  // If __is_pod (type) is true or type is a reference type
4703  // then the trait is true, else if type is a cv class or union
4704  // type (or array thereof) with a trivial destructor
4705  // ([class.dtor]) then the trait is true, else it is
4706  // false.
4707  if (T.isPODType(C) || T->isReferenceType())
4708  return true;
4709 
4710  // Objective-C++ ARC: autorelease types don't require destruction.
4711  if (T->isObjCLifetimeType() &&
4713  return true;
4714 
4715  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4716  return RD->hasTrivialDestructor();
4717  return false;
4718  // TODO: Propagate nothrowness for implicitly declared special members.
4719  case UTT_HasNothrowAssign:
4720  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4721  // If type is const qualified or is a reference type then the
4722  // trait is false. Otherwise if __has_trivial_assign (type)
4723  // is true then the trait is true, else if type is a cv class
4724  // or union type with copy assignment operators that are known
4725  // not to throw an exception then the trait is true, else it is
4726  // false.
4727  if (C.getBaseElementType(T).isConstQualified())
4728  return false;
4729  if (T->isReferenceType())
4730  return false;
4731  if (T.isPODType(C) || T->isObjCLifetimeType())
4732  return true;
4733 
4734  if (const RecordType *RT = T->getAs<RecordType>())
4735  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4739  return false;
4741  // This trait is implemented by MSVC 2012 and needed to parse the
4742  // standard library headers. Specifically this is used as the logic
4743  // behind std::is_nothrow_move_assignable (20.9.4.3).
4744  if (T.isPODType(C))
4745  return true;
4746 
4747  if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4748  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4752  return false;
4753  case UTT_HasNothrowCopy:
4754  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4755  // If __has_trivial_copy (type) is true then the trait is true, else
4756  // if type is a cv class or union type with copy constructors that are
4757  // known not to throw an exception then the trait is true, else it is
4758  // false.
4759  if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4760  return true;
4761  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4762  if (RD->hasTrivialCopyConstructor() &&
4763  !RD->hasNonTrivialCopyConstructor())
4764  return true;
4765 
4766  bool FoundConstructor = false;
4767  unsigned FoundTQs;
4768  for (const auto *ND : Self.LookupConstructors(RD)) {
4769  // A template constructor is never a copy constructor.
4770  // FIXME: However, it may actually be selected at the actual overload
4771  // resolution point.
4772  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4773  continue;
4774  // UsingDecl itself is not a constructor
4775  if (isa<UsingDecl>(ND))
4776  continue;
4777  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4778  if (Constructor->isCopyConstructor(FoundTQs)) {
4779  FoundConstructor = true;
4780  const FunctionProtoType *CPT
4781  = Constructor->getType()->getAs<FunctionProtoType>();
4782  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4783  if (!CPT)
4784  return false;
4785  // TODO: check whether evaluating default arguments can throw.
4786  // For now, we'll be conservative and assume that they can throw.
4787  if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4788  return false;
4789  }
4790  }
4791 
4792  return FoundConstructor;
4793  }
4794  return false;
4796  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4797  // If __has_trivial_constructor (type) is true then the trait is
4798  // true, else if type is a cv class or union type (or array
4799  // thereof) with a default constructor that is known not to
4800  // throw an exception then the trait is true, else it is false.
4801  if (T.isPODType(C) || T->isObjCLifetimeType())
4802  return true;
4803  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4804  if (RD->hasTrivialDefaultConstructor() &&
4805  !RD->hasNonTrivialDefaultConstructor())
4806  return true;
4807 
4808  bool FoundConstructor = false;
4809  for (const auto *ND : Self.LookupConstructors(RD)) {
4810  // FIXME: In C++0x, a constructor template can be a default constructor.
4811  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4812  continue;
4813  // UsingDecl itself is not a constructor
4814  if (isa<UsingDecl>(ND))
4815  continue;
4816  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4817  if (Constructor->isDefaultConstructor()) {
4818  FoundConstructor = true;
4819  const FunctionProtoType *CPT
4820  = Constructor->getType()->getAs<FunctionProtoType>();
4821  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4822  if (!CPT)
4823  return false;
4824  // FIXME: check whether evaluating default arguments can throw.
4825  // For now, we'll be conservative and assume that they can throw.
4826  if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4827  return false;
4828  }
4829  }
4830  return FoundConstructor;
4831  }
4832  return false;
4834  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4835  // If type is a class type with a virtual destructor ([class.dtor])
4836  // then the trait is true, else it is false.
4837  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4838  if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4839  return Destructor->isVirtual();
4840  return false;
4841 
4842  // These type trait expressions are modeled on the specifications for the
4843  // Embarcadero C++0x type trait functions:
4844  // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4845  case UTT_IsCompleteType:
4846  // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4847  // Returns True if and only if T is a complete type at the point of the
4848  // function call.
4849  return !T->isIncompleteType();
4851  return C.hasUniqueObjectRepresentations(T);
4852  }
4853 }
4854 
4855 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4856  QualType RhsT, SourceLocation KeyLoc);
4857 
4860  SourceLocation RParenLoc) {
4861  if (Kind <= UTT_Last)
4862  return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4863 
4864  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4865  // traits to avoid duplication.
4866  if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4867  return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4868  Args[1]->getType(), RParenLoc);
4869 
4870  switch (Kind) {
4875  // C++11 [meta.unary.prop]:
4876  // is_trivially_constructible is defined as:
4877  //
4878  // is_constructible<T, Args...>::value is true and the variable
4879  // definition for is_constructible, as defined below, is known to call
4880  // no operation that is not trivial.
4881  //
4882  // The predicate condition for a template specialization
4883  // is_constructible<T, Args...> shall be satisfied if and only if the
4884  // following variable definition would be well-formed for some invented
4885  // variable t:
4886  //
4887  // T t(create<Args>()...);
4888  assert(!Args.empty());
4889 
4890  // Precondition: T and all types in the parameter pack Args shall be
4891  // complete types, (possibly cv-qualified) void, or arrays of
4892  // unknown bound.
4893  for (const auto *TSI : Args) {
4894  QualType ArgTy = TSI->getType();
4895  if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4896  continue;
4897 
4898  if (S.RequireCompleteType(KWLoc, ArgTy,
4899  diag::err_incomplete_type_used_in_type_trait_expr))
4900  return false;
4901  }
4902 
4903  // Make sure the first argument is not incomplete nor a function type.
4904  QualType T = Args[0]->getType();
4905  if (T->isIncompleteType() || T->isFunctionType())
4906  return false;
4907 
4908  // Make sure the first argument is not an abstract type.
4909  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4910  if (RD && RD->isAbstract())
4911  return false;
4912 
4913  SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4914  SmallVector<Expr *, 2> ArgExprs;
4915  ArgExprs.reserve(Args.size() - 1);
4916  for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4917  QualType ArgTy = Args[I]->getType();
4918  if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4919  ArgTy = S.Context.getRValueReferenceType(ArgTy);
4920  OpaqueArgExprs.push_back(
4921  OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4922  ArgTy.getNonLValueExprType(S.Context),
4923  Expr::getValueKindForType(ArgTy)));
4924  }
4925  for (Expr &E : OpaqueArgExprs)
4926  ArgExprs.push_back(&E);
4927 
4928  // Perform the initialization in an unevaluated context within a SFINAE
4929  // trap at translation unit scope.
4932  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4936  RParenLoc));
4937  InitializationSequence Init(S, To, InitKind, ArgExprs);
4938  if (Init.Failed())
4939  return false;
4940 
4941  ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4942  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4943  return false;
4944 
4945  if (Kind == clang::TT_IsConstructible)
4946  return true;
4947 
4949  if (!T->isReferenceType())
4950  return false;
4951 
4952  return !Init.isDirectReferenceBinding();
4953  }
4954 
4956  return S.canThrow(Result.get()) == CT_Cannot;
4957 
4958  if (Kind == clang::TT_IsTriviallyConstructible) {
4959  // Under Objective-C ARC and Weak, if the destination has non-trivial
4960  // Objective-C lifetime, this is a non-trivial construction.
4962  return false;
4963 
4964  // The initialization succeeded; now make sure there are no non-trivial
4965  // calls.
4966  return !Result.get()->hasNonTrivialCall(S.Context);
4967  }
4968 
4969  llvm_unreachable("unhandled type trait");
4970  return false;
4971  }
4972  default: llvm_unreachable("not a TT");
4973  }
4974 
4975  return false;
4976 }
4977 
4980  SourceLocation RParenLoc) {
4981  QualType ResultType = Context.getLogicalOperationType();
4982 
4984  *this, Kind, KWLoc, Args[0]->getType()))
4985  return ExprError();
4986 
4987  bool Dependent = false;
4988  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4989  if (Args[I]->getType()->isDependentType()) {
4990  Dependent = true;
4991  break;
4992  }
4993  }
4994 
4995  bool Result = false;
4996  if (!Dependent)
4997  Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4998 
4999  return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5000  RParenLoc, Result);
5001 }
5002 
5004  ArrayRef<ParsedType> Args,
5005  SourceLocation RParenLoc) {
5006  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5007  ConvertedArgs.reserve(Args.size());
5008 
5009  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5010  TypeSourceInfo *TInfo;
5011  QualType T = GetTypeFromParser(Args[I], &TInfo);
5012  if (!TInfo)
5013  TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5014 
5015  ConvertedArgs.push_back(TInfo);
5016  }
5017 
5018  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5019 }
5020 
5021 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5022  QualType RhsT, SourceLocation KeyLoc) {
5023  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5024  "Cannot evaluate traits of dependent types");
5025 
5026  switch(BTT) {
5027  case BTT_IsBaseOf: {
5028  // C++0x [meta.rel]p2
5029  // Base is a base class of Derived without regard to cv-qualifiers or
5030  // Base and Derived are not unions and name the same class type without
5031  // regard to cv-qualifiers.
5032 
5033  const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5034  const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5035  if (!rhsRecord || !lhsRecord) {
5036  const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5037  const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5038  if (!LHSObjTy || !RHSObjTy)
5039  return false;
5040 
5041  ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5042  ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5043  if (!BaseInterface || !DerivedInterface)
5044  return false;
5045 
5046  if (Self.RequireCompleteType(
5047  KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5048  return false;
5049 
5050  return BaseInterface->isSuperClassOf(DerivedInterface);
5051  }
5052 
5053  assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5054  == (lhsRecord == rhsRecord));
5055 
5056  if (lhsRecord == rhsRecord)
5057  return !lhsRecord->getDecl()->isUnion();
5058 
5059  // C++0x [meta.rel]p2:
5060  // If Base and Derived are class types and are different types
5061  // (ignoring possible cv-qualifiers) then Derived shall be a
5062  // complete type.
5063  if (Self.RequireCompleteType(KeyLoc, RhsT,
5064  diag::err_incomplete_type_used_in_type_trait_expr))
5065  return false;
5066 
5067  return cast<CXXRecordDecl>(rhsRecord->getDecl())
5068  ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5069  }
5070  case BTT_IsSame:
5071  return Self.Context.hasSameType(LhsT, RhsT);
5072  case BTT_TypeCompatible: {
5073  // GCC ignores cv-qualifiers on arrays for this builtin.
5074  Qualifiers LhsQuals, RhsQuals;
5075  QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5076  QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5077  return Self.Context.typesAreCompatible(Lhs, Rhs);
5078  }
5079  case BTT_IsConvertible:
5080  case BTT_IsConvertibleTo: {
5081  // C++0x [meta.rel]p4:
5082  // Given the following function prototype:
5083  //
5084  // template <class T>
5085  // typename add_rvalue_reference<T>::type create();
5086  //
5087  // the predicate condition for a template specialization
5088  // is_convertible<From, To> shall be satisfied if and only if
5089  // the return expression in the following code would be
5090  // well-formed, including any implicit conversions to the return
5091  // type of the function:
5092  //
5093  // To test() {
5094  // return create<From>();
5095  // }
5096  //
5097  // Access checking is performed as if in a context unrelated to To and
5098  // From. Only the validity of the immediate context of the expression
5099  // of the return-statement (including conversions to the return type)
5100  // is considered.
5101  //
5102  // We model the initialization as a copy-initialization of a temporary
5103  // of the appropriate type, which for this expression is identical to the
5104  // return statement (since NRVO doesn't apply).
5105 
5106  // Functions aren't allowed to return function or array types.
5107  if (RhsT->isFunctionType() || RhsT->isArrayType())
5108  return false;
5109 
5110  // A return statement in a void function must have void type.
5111  if (RhsT->isVoidType())
5112  return LhsT->isVoidType();
5113 
5114  // A function definition requires a complete, non-abstract return type.
5115  if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5116  return false;
5117 
5118  // Compute the result of add_rvalue_reference.
5119  if (LhsT->isObjectType() || LhsT->isFunctionType())
5120  LhsT = Self.Context.getRValueReferenceType(LhsT);
5121 
5122  // Build a fake source and destination for initialization.
5124  OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5126  Expr *FromPtr = &From;
5128  SourceLocation()));
5129 
5130  // Perform the initialization in an unevaluated context within a SFINAE
5131  // trap at translation unit scope.
5134  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5135  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5136  InitializationSequence Init(Self, To, Kind, FromPtr);
5137  if (Init.Failed())
5138  return false;
5139 
5140  ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5141  return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5142  }
5143 
5144  case BTT_IsAssignable:
5147  // C++11 [meta.unary.prop]p3:
5148  // is_trivially_assignable is defined as:
5149  // is_assignable<T, U>::value is true and the assignment, as defined by
5150  // is_assignable, is known to call no operation that is not trivial
5151  //
5152  // is_assignable is defined as:
5153  // The expression declval<T>() = declval<U>() is well-formed when
5154  // treated as an unevaluated operand (Clause 5).
5155  //
5156  // For both, T and U shall be complete types, (possibly cv-qualified)
5157  // void, or arrays of unknown bound.
5158  if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5159  Self.RequireCompleteType(KeyLoc, LhsT,
5160  diag::err_incomplete_type_used_in_type_trait_expr))
5161  return false;
5162  if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5163  Self.RequireCompleteType(KeyLoc, RhsT,
5164  diag::err_incomplete_type_used_in_type_trait_expr))
5165  return false;
5166 
5167  // cv void is never assignable.
5168  if (LhsT->isVoidType() || RhsT->isVoidType())
5169  return false;
5170 
5171  // Build expressions that emulate the effect of declval<T>() and
5172  // declval<U>().
5173  if (LhsT->isObjectType() || LhsT->isFunctionType())
5174  LhsT = Self.Context.getRValueReferenceType(LhsT);
5175  if (RhsT->isObjectType() || RhsT->isFunctionType())
5176  RhsT = Self.Context.getRValueReferenceType(RhsT);
5177  OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5179  OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5181 
5182  // Attempt the assignment in an unevaluated context within a SFINAE
5183  // trap at translation unit scope.
5186  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5187  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5188  ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5189  &Rhs);
5190  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5191  return false;
5192 
5193  if (BTT == BTT_IsAssignable)
5194  return true;
5195 
5196  if (BTT == BTT_IsNothrowAssignable)
5197  return Self.canThrow(Result.get()) == CT_Cannot;
5198 
5199  if (BTT == BTT_IsTriviallyAssignable) {
5200  // Under Objective-C ARC and Weak, if the destination has non-trivial
5201  // Objective-C lifetime, this is a non-trivial assignment.
5203  return false;
5204 
5205  return !Result.get()->hasNonTrivialCall(Self.Context);
5206  }
5207 
5208  llvm_unreachable("unhandled type trait");
5209  return false;
5210  }
5211  default: llvm_unreachable("not a BTT");
5212  }
5213  llvm_unreachable("Unknown type trait or not implemented");
5214 }
5215 
5217  SourceLocation KWLoc,
5218  ParsedType Ty,
5219  Expr* DimExpr,
5220  SourceLocation RParen) {
5221  TypeSourceInfo *TSInfo;
5222  QualType T = GetTypeFromParser(Ty, &TSInfo);
5223  if (!TSInfo)
5224  TSInfo = Context.getTrivialTypeSourceInfo(T);
5225 
5226  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5227 }
5228 
5229 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5230  QualType T, Expr *DimExpr,
5231  SourceLocation KeyLoc) {
5232  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5233 
5234  switch(ATT) {
5235  case ATT_ArrayRank:
5236  if (T->isArrayType()) {
5237  unsigned Dim = 0;
5238  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5239  ++Dim;
5240  T = AT->getElementType();
5241  }
5242  return Dim;
5243  }
5244  return 0;
5245 
5246  case ATT_ArrayExtent: {
5247  llvm::APSInt Value;
5248  uint64_t Dim;
5249  if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5250  diag::err_dimension_expr_not_constant_integer,
5251  false).isInvalid())
5252  return 0;
5253  if (Value.isSigned() && Value.isNegative()) {
5254  Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5255  << DimExpr->getSourceRange();
5256  return 0;
5257  }
5258  Dim = Value.getLimitedValue();
5259 
5260  if (T->isArrayType()) {
5261  unsigned D = 0;
5262  bool Matched = false;
5263  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5264  if (Dim == D) {
5265  Matched = true;
5266  break;
5267  }
5268  ++D;
5269  T = AT->getElementType();
5270  }
5271 
5272  if (Matched && T->isArrayType()) {
5273  if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5274  return CAT->getSize().getLimitedValue();
5275  }
5276  }
5277  return 0;
5278  }
5279  }
5280  llvm_unreachable("Unknown type trait or not implemented");
5281 }
5282 
5284  SourceLocation KWLoc,
5285  TypeSourceInfo *TSInfo,
5286  Expr* DimExpr,
5287  SourceLocation RParen) {
5288  QualType T = TSInfo->getType();
5289 
5290  // FIXME: This should likely be tracked as an APInt to remove any host
5291  // assumptions about the width of size_t on the target.
5292  uint64_t Value = 0;
5293  if (!T->isDependentType())
5294  Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5295 
5296  // While the specification for these traits from the Embarcadero C++
5297  // compiler's documentation says the return type is 'unsigned int', Clang
5298  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5299  // compiler, there is no difference. On several other platforms this is an
5300  // important distinction.
5301  return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5302  RParen, Context.getSizeType());
5303 }
5304 
5306  SourceLocation KWLoc,
5307  Expr *Queried,
5308  SourceLocation RParen) {
5309  // If error parsing the expression, ignore.
5310  if (!Queried)
5311  return ExprError();
5312 
5313  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5314 
5315  return Result;
5316 }
5317 
5319  switch (ET) {
5320  case ET_IsLValueExpr: return E->isLValue();
5321  case ET_IsRValueExpr: return E->isRValue();
5322  }
5323  llvm_unreachable("Expression trait not covered by switch");
5324 }
5325 
5327  SourceLocation KWLoc,
5328  Expr *Queried,
5329  SourceLocation RParen) {
5330  if (Queried->isTypeDependent()) {
5331  // Delay type-checking for type-dependent expressions.
5332  } else if (Queried->getType()->isPlaceholderType()) {
5333  ExprResult PE = CheckPlaceholderExpr(Queried);
5334  if (PE.isInvalid()) return ExprError();
5335  return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5336  }
5337 
5338  bool Value = EvaluateExpressionTrait(ET, Queried);
5339 
5340  return new (Context)
5341  ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5342 }
5343 
5345  ExprValueKind &VK,
5346  SourceLocation Loc,
5347  bool isIndirect) {
5348  assert(!LHS.get()->getType()->isPlaceholderType() &&
5349  !RHS.get()->getType()->isPlaceholderType() &&
5350  "placeholders should have been weeded out by now");
5351 
5352  // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5353  // temporary materialization conversion otherwise.
5354  if (isIndirect)
5355  LHS = DefaultLvalueConversion(LHS.get());
5356  else if (LHS.get()->isRValue())
5358  if (LHS.isInvalid())
5359  return QualType();