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