clang  8.0.0svn
SemaExprCXX.cpp
Go to the documentation of this file.
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// Implements semantic analysis for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14 
16 #include "TreeTransform.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTLambda.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaLambda.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 using namespace clang;
43 using namespace sema;
44 
45 /// Handle the result of the special case name lookup for inheriting
46 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47 /// constructor names in member using declarations, even if 'X' is not the
48 /// name of the corresponding type.
50  SourceLocation NameLoc,
51  IdentifierInfo &Name) {
52  NestedNameSpecifier *NNS = SS.getScopeRep();
53 
54  // Convert the nested-name-specifier into a type.
55  QualType Type;
56  switch (NNS->getKind()) {
59  Type = QualType(NNS->getAsType(), 0);
60  break;
61 
63  // Strip off the last layer of the nested-name-specifier and build a
64  // typename type for it.
65  assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66  Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67  NNS->getAsIdentifier());
68  break;
69 
74  llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75  }
76 
77  // This reference to the type is located entirely at the location of the
78  // final identifier in the qualified-id.
79  return CreateParsedType(Type,
80  Context.getTrivialTypeSourceInfo(Type, NameLoc));
81 }
82 
84  SourceLocation NameLoc,
85  Scope *S, CXXScopeSpec &SS,
86  bool EnteringContext) {
87  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88  assert(CurClass && &II == CurClass->getIdentifier() &&
89  "not a constructor name");
90 
91  // When naming a constructor as a member of a dependent context (eg, in a
92  // friend declaration or an inherited constructor declaration), form an
93  // unresolved "typename" type.
94  if (CurClass->isDependentContext() && !EnteringContext) {
95  QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96  return ParsedType::make(T);
97  }
98 
99  if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100  return ParsedType();
101 
102  // Find the injected-class-name declaration. Note that we make no attempt to
103  // diagnose cases where the injected-class-name is shadowed: the only
104  // declaration that can validly shadow the injected-class-name is a
105  // non-static data member, and if the class contains both a non-static data
106  // member and a constructor then it is ill-formed (we check that in
107  // CheckCompletedCXXClass).
108  CXXRecordDecl *InjectedClassName = nullptr;
109  for (NamedDecl *ND : CurClass->lookup(&II)) {
110  auto *RD = dyn_cast<CXXRecordDecl>(ND);
111  if (RD && RD->isInjectedClassName()) {
112  InjectedClassName = RD;
113  break;
114  }
115  }
116  if (!InjectedClassName) {
117  if (!CurClass->isInvalidDecl()) {
118  // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119  // properly. Work around it here for now.
121  diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122  }
123  return ParsedType();
124  }
125 
126  QualType T = Context.getTypeDeclType(InjectedClassName);
127  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129 
130  return ParsedType::make(T);
131 }
132 
134  IdentifierInfo &II,
135  SourceLocation NameLoc,
136  Scope *S, CXXScopeSpec &SS,
137  ParsedType ObjectTypePtr,
138  bool EnteringContext) {
139  // Determine where to perform name lookup.
140 
141  // FIXME: This area of the standard is very messy, and the current
142  // wording is rather unclear about which scopes we search for the
143  // destructor name; see core issues 399 and 555. Issue 399 in
144  // particular shows where the current description of destructor name
145  // lookup is completely out of line with existing practice, e.g.,
146  // this appears to be ill-formed:
147  //
148  // namespace N {
149  // template <typename T> struct S {
150  // ~S();
151  // };
152  // }
153  //
154  // void f(N::S<int>* s) {
155  // s->N::S<int>::~S();
156  // }
157  //
158  // See also PR6358 and PR6359.
159  // For this reason, we're currently only doing the C++03 version of this
160  // code; the C++0x version has to wait until we get a proper spec.
161  QualType SearchType;
162  DeclContext *LookupCtx = nullptr;
163  bool isDependent = false;
164  bool LookInScope = false;
165 
166  if (SS.isInvalid())
167  return nullptr;
168 
169  // If we have an object type, it's because we are in a
170  // pseudo-destructor-expression or a member access expression, and
171  // we know what type we're looking for.
172  if (ObjectTypePtr)
173  SearchType = GetTypeFromParser(ObjectTypePtr);
174 
175  if (SS.isSet()) {
176  NestedNameSpecifier *NNS = SS.getScopeRep();
177 
178  bool AlreadySearched = false;
179  bool LookAtPrefix = true;
180  // C++11 [basic.lookup.qual]p6:
181  // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
182  // the type-names are looked up as types in the scope designated by the
183  // nested-name-specifier. Similarly, in a qualified-id of the form:
184  //
185  // nested-name-specifier[opt] class-name :: ~ class-name
186  //
187  // the second class-name is looked up in the same scope as the first.
188  //
189  // Here, we determine whether the code below is permitted to look at the
190  // prefix of the nested-name-specifier.
191  DeclContext *DC = computeDeclContext(SS, EnteringContext);
192  if (DC && DC->isFileContext()) {
193  AlreadySearched = true;
194  LookupCtx = DC;
195  isDependent = false;
196  } else if (DC && isa<CXXRecordDecl>(DC)) {
197  LookAtPrefix = false;
198  LookInScope = true;
199  }
200 
201  // The second case from the C++03 rules quoted further above.
202  NestedNameSpecifier *Prefix = nullptr;
203  if (AlreadySearched) {
204  // Nothing left to do.
205  } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206  CXXScopeSpec PrefixSS;
207  PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
208  LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209  isDependent = isDependentScopeSpecifier(PrefixSS);
210  } else if (ObjectTypePtr) {
211  LookupCtx = computeDeclContext(SearchType);
212  isDependent = SearchType->isDependentType();
213  } else {
214  LookupCtx = computeDeclContext(SS, EnteringContext);
215  isDependent = LookupCtx && LookupCtx->isDependentContext();
216  }
217  } else if (ObjectTypePtr) {
218  // C++ [basic.lookup.classref]p3:
219  // If the unqualified-id is ~type-name, the type-name is looked up
220  // in the context of the entire postfix-expression. If the type T
221  // of the object expression is of a class type C, the type-name is
222  // also looked up in the scope of class C. At least one of the
223  // lookups shall find a name that refers to (possibly
224  // cv-qualified) T.
225  LookupCtx = computeDeclContext(SearchType);
226  isDependent = SearchType->isDependentType();
227  assert((isDependent || !SearchType->isIncompleteType()) &&
228  "Caller should have completed object type");
229 
230  LookInScope = true;
231  } else {
232  // Perform lookup into the current scope (only).
233  LookInScope = true;
234  }
235 
236  TypeDecl *NonMatchingTypeDecl = nullptr;
237  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238  for (unsigned Step = 0; Step != 2; ++Step) {
239  // Look for the name first in the computed lookup context (if we
240  // have one) and, if that fails to find a match, in the scope (if
241  // we're allowed to look there).
242  Found.clear();
243  if (Step == 0 && LookupCtx) {
244  if (RequireCompleteDeclContext(SS, LookupCtx))
245  return nullptr;
246  LookupQualifiedName(Found, LookupCtx);
247  } else if (Step == 1 && LookInScope && S) {
248  LookupName(Found, S);
249  } else {
250  continue;
251  }
252 
253  // FIXME: Should we be suppressing ambiguities here?
254  if (Found.isAmbiguous())
255  return nullptr;
256 
257  if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258  QualType T = Context.getTypeDeclType(Type);
259  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
260 
261  if (SearchType.isNull() || SearchType->isDependentType() ||
262  Context.hasSameUnqualifiedType(T, SearchType)) {
263  // We found our type!
264 
265  return CreateParsedType(T,
266  Context.getTrivialTypeSourceInfo(T, NameLoc));
267  }
268 
269  if (!SearchType.isNull())
270  NonMatchingTypeDecl = Type;
271  }
272 
273  // If the name that we found is a class template name, and it is
274  // the same name as the template name in the last part of the
275  // nested-name-specifier (if present) or the object type, then
276  // this is the destructor for that class.
277  // FIXME: This is a workaround until we get real drafting for core
278  // issue 399, for which there isn't even an obvious direction.
279  if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280  QualType MemberOfType;
281  if (SS.isSet()) {
282  if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283  // Figure out the type of the context, if it has one.
284  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285  MemberOfType = Context.getTypeDeclType(Record);
286  }
287  }
288  if (MemberOfType.isNull())
289  MemberOfType = SearchType;
290 
291  if (MemberOfType.isNull())
292  continue;
293 
294  // We're referring into a class template specialization. If the
295  // class template we found is the same as the template being
296  // specialized, we found what we are looking for.
297  if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
299  = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300  if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301  Template->getCanonicalDecl())
302  return CreateParsedType(
303  MemberOfType,
304  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
305  }
306 
307  continue;
308  }
309 
310  // We're referring to an unresolved class template
311  // specialization. Determine whether we class template we found
312  // is the same as the template being specialized or, if we don't
313  // know which template is being specialized, that it at least
314  // has the same name.
315  if (const TemplateSpecializationType *SpecType
316  = MemberOfType->getAs<TemplateSpecializationType>()) {
317  TemplateName SpecName = SpecType->getTemplateName();
318 
319  // The class template we found is the same template being
320  // specialized.
321  if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322  if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
323  return CreateParsedType(
324  MemberOfType,
325  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
326 
327  continue;
328  }
329 
330  // The class template we found has the same name as the
331  // (dependent) template name being specialized.
332  if (DependentTemplateName *DepTemplate
333  = SpecName.getAsDependentTemplateName()) {
334  if (DepTemplate->isIdentifier() &&
335  DepTemplate->getIdentifier() == Template->getIdentifier())
336  return CreateParsedType(
337  MemberOfType,
338  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
339 
340  continue;
341  }
342  }
343  }
344  }
345 
346  if (isDependent) {
347  // We didn't find our type, but that's okay: it's dependent
348  // anyway.
349 
350  // FIXME: What if we have no nested-name-specifier?
351  QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352  SS.getWithLocInContext(Context),
353  II, NameLoc);
354  return ParsedType::make(T);
355  }
356 
357  if (NonMatchingTypeDecl) {
358  QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359  Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
360  << T << SearchType;
361  Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
362  << T;
363  } else if (ObjectTypePtr)
364  Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
365  << &II;
366  else {
367  SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368  diag::err_destructor_class_name);
369  if (S) {
370  const DeclContext *Ctx = S->getEntity();
371  if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372  DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373  Class->getNameAsString());
374  }
375  }
376 
377  return nullptr;
378 }
379 
381  ParsedType ObjectType) {
383  return nullptr;
384 
386  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
387  return nullptr;
388  }
389 
390  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
391  "unexpected type in getDestructorType");
392  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
393 
394  // If we know the type of the object, check that the correct destructor
395  // type was named now; we can give better diagnostics this way.
396  QualType SearchType = GetTypeFromParser(ObjectType);
397  if (!SearchType.isNull() && !SearchType->isDependentType() &&
398  !Context.hasSameUnqualifiedType(T, SearchType)) {
399  Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
400  << T << SearchType;
401  return nullptr;
402  }
403 
404  return ParsedType::make(T);
405 }
406 
408  const UnqualifiedId &Name) {
410 
411  if (!SS.isValid())
412  return false;
413 
414  switch (SS.getScopeRep()->getKind()) {
418  // Per C++11 [over.literal]p2, literal operators can only be declared at
419  // namespace scope. Therefore, this unqualified-id cannot name anything.
420  // Reject it early, because we have no AST representation for this in the
421  // case where the scope is dependent.
422  Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
423  << SS.getScopeRep();
424  return true;
425 
430  return false;
431  }
432 
433  llvm_unreachable("unknown nested name specifier kind");
434 }
435 
436 /// Build a C++ typeid expression with a type operand.
438  SourceLocation TypeidLoc,
439  TypeSourceInfo *Operand,
440  SourceLocation RParenLoc) {
441  // C++ [expr.typeid]p4:
442  // The top-level cv-qualifiers of the lvalue expression or the type-id
443  // that is the operand of typeid are always ignored.
444  // If the type of the type-id is a class type or a reference to a class
445  // type, the class shall be completely-defined.
446  Qualifiers Quals;
447  QualType T
448  = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
449  Quals);
450  if (T->getAs<RecordType>() &&
451  RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
452  return ExprError();
453 
454  if (T->isVariablyModifiedType())
455  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
456 
457  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
458  SourceRange(TypeidLoc, RParenLoc));
459 }
460 
461 /// Build a C++ typeid expression with an expression operand.
463  SourceLocation TypeidLoc,
464  Expr *E,
465  SourceLocation RParenLoc) {
466  bool WasEvaluated = false;
467  if (E && !E->isTypeDependent()) {
468  if (E->getType()->isPlaceholderType()) {
469  ExprResult result = CheckPlaceholderExpr(E);
470  if (result.isInvalid()) return ExprError();
471  E = result.get();
472  }
473 
474  QualType T = E->getType();
475  if (const RecordType *RecordT = T->getAs<RecordType>()) {
476  CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
477  // C++ [expr.typeid]p3:
478  // [...] If the type of the expression is a class type, the class
479  // shall be completely-defined.
480  if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
481  return ExprError();
482 
483  // C++ [expr.typeid]p3:
484  // When typeid is applied to an expression other than an glvalue of a
485  // polymorphic class type [...] [the] expression is an unevaluated
486  // operand. [...]
487  if (RecordD->isPolymorphic() && E->isGLValue()) {
488  // The subexpression is potentially evaluated; switch the context
489  // and recheck the subexpression.
490  ExprResult Result = TransformToPotentiallyEvaluated(E);
491  if (Result.isInvalid()) return ExprError();
492  E = Result.get();
493 
494  // We require a vtable to query the type at run time.
495  MarkVTableUsed(TypeidLoc, RecordD);
496  WasEvaluated = true;
497  }
498  }
499 
500  // C++ [expr.typeid]p4:
501  // [...] If the type of the type-id is a reference to a possibly
502  // cv-qualified type, the result of the typeid expression refers to a
503  // std::type_info object representing the cv-unqualified referenced
504  // type.
505  Qualifiers Quals;
506  QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
507  if (!Context.hasSameType(T, UnqualT)) {
508  T = UnqualT;
509  E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
510  }
511  }
512 
513  if (E->getType()->isVariablyModifiedType())
514  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
515  << E->getType());
516  else if (!inTemplateInstantiation() &&
517  E->HasSideEffects(Context, WasEvaluated)) {
518  // The expression operand for typeid is in an unevaluated expression
519  // context, so side effects could result in unintended consequences.
520  Diag(E->getExprLoc(), WasEvaluated
521  ? diag::warn_side_effects_typeid
522  : diag::warn_side_effects_unevaluated_context);
523  }
524 
525  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
526  SourceRange(TypeidLoc, RParenLoc));
527 }
528 
529 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
532  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
533  // OpenCL C++ 1.0 s2.9: typeid is not supported.
534  if (getLangOpts().OpenCLCPlusPlus) {
535  return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
536  << "typeid");
537  }
538 
539  // Find the std::type_info type.
540  if (!getStdNamespace())
541  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
542 
543  if (!CXXTypeInfoDecl) {
544  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
545  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
546  LookupQualifiedName(R, getStdNamespace());
547  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
548  // Microsoft's typeinfo doesn't have type_info in std but in the global
549  // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
550  if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
551  LookupQualifiedName(R, Context.getTranslationUnitDecl());
552  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
553  }
554  if (!CXXTypeInfoDecl)
555  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
556  }
557 
558  if (!getLangOpts().RTTI) {
559  return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
560  }
561 
562  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
563 
564  if (isType) {
565  // The operand is a type; handle it as such.
566  TypeSourceInfo *TInfo = nullptr;
567  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
568  &TInfo);
569  if (T.isNull())
570  return ExprError();
571 
572  if (!TInfo)
573  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
574 
575  return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
576  }
577 
578  // The operand is an expression.
579  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
580 }
581 
582 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
583 /// a single GUID.
584 static void
587  // Optionally remove one level of pointer, reference or array indirection.
588  const Type *Ty = QT.getTypePtr();
589  if (QT->isPointerType() || QT->isReferenceType())
590  Ty = QT->getPointeeType().getTypePtr();
591  else if (QT->isArrayType())
592  Ty = Ty->getBaseElementTypeUnsafe();
593 
594  const auto *TD = Ty->getAsTagDecl();
595  if (!TD)
596  return;
597 
598  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
599  UuidAttrs.insert(Uuid);
600  return;
601  }
602 
603  // __uuidof can grab UUIDs from template arguments.
604  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
605  const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
606  for (const TemplateArgument &TA : TAL.asArray()) {
607  const UuidAttr *UuidForTA = nullptr;
608  if (TA.getKind() == TemplateArgument::Type)
609  getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
610  else if (TA.getKind() == TemplateArgument::Declaration)
611  getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
612 
613  if (UuidForTA)
614  UuidAttrs.insert(UuidForTA);
615  }
616  }
617 }
618 
619 /// Build a Microsoft __uuidof expression with a type operand.
621  SourceLocation TypeidLoc,
622  TypeSourceInfo *Operand,
623  SourceLocation RParenLoc) {
624  StringRef UuidStr;
625  if (!Operand->getType()->isDependentType()) {
627  getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
628  if (UuidAttrs.empty())
629  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
630  if (UuidAttrs.size() > 1)
631  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
632  UuidStr = UuidAttrs.back()->getGuid();
633  }
634 
635  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
636  SourceRange(TypeidLoc, RParenLoc));
637 }
638 
639 /// Build a Microsoft __uuidof expression with an expression operand.
641  SourceLocation TypeidLoc,
642  Expr *E,
643  SourceLocation RParenLoc) {
644  StringRef UuidStr;
645  if (!E->getType()->isDependentType()) {
647  UuidStr = "00000000-0000-0000-0000-000000000000";
648  } else {
650  getUuidAttrOfType(*this, E->getType(), UuidAttrs);
651  if (UuidAttrs.empty())
652  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
653  if (UuidAttrs.size() > 1)
654  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
655  UuidStr = UuidAttrs.back()->getGuid();
656  }
657  }
658 
659  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
660  SourceRange(TypeidLoc, RParenLoc));
661 }
662 
663 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
666  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
667  // If MSVCGuidDecl has not been cached, do the lookup.
668  if (!MSVCGuidDecl) {
669  IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
670  LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
671  LookupQualifiedName(R, Context.getTranslationUnitDecl());
672  MSVCGuidDecl = R.getAsSingle<RecordDecl>();
673  if (!MSVCGuidDecl)
674  return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
675  }
676 
677  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
678 
679  if (isType) {
680  // The operand is a type; handle it as such.
681  TypeSourceInfo *TInfo = nullptr;
682  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
683  &TInfo);
684  if (T.isNull())
685  return ExprError();
686 
687  if (!TInfo)
688  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
689 
690  return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
691  }
692 
693  // The operand is an expression.
694  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
695 }
696 
697 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
700  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
701  "Unknown C++ Boolean value!");
702  return new (Context)
703  CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
704 }
705 
706 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
709  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
710 }
711 
712 /// ActOnCXXThrow - Parse throw expressions.
715  bool IsThrownVarInScope = false;
716  if (Ex) {
717  // C++0x [class.copymove]p31:
718  // When certain criteria are met, an implementation is allowed to omit the
719  // copy/move construction of a class object [...]
720  //
721  // - in a throw-expression, when the operand is the name of a
722  // non-volatile automatic object (other than a function or catch-
723  // clause parameter) whose scope does not extend beyond the end of the
724  // innermost enclosing try-block (if there is one), the copy/move
725  // operation from the operand to the exception object (15.1) can be
726  // omitted by constructing the automatic object directly into the
727  // exception object
728  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
729  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
730  if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
731  for( ; S; S = S->getParent()) {
732  if (S->isDeclScope(Var)) {
733  IsThrownVarInScope = true;
734  break;
735  }
736 
737  if (S->getFlags() &
741  break;
742  }
743  }
744  }
745  }
746 
747  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
748 }
749 
751  bool IsThrownVarInScope) {
752  // Don't report an error if 'throw' is used in system headers.
753  if (!getLangOpts().CXXExceptions &&
754  !getSourceManager().isInSystemHeader(OpLoc) &&
755  (!getLangOpts().OpenMPIsDevice ||
756  !getLangOpts().OpenMPHostCXXExceptions ||
757  isInOpenMPTargetExecutionDirective() ||
758  isInOpenMPDeclareTargetContext()))
759  Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
760 
761  // Exceptions aren't allowed in CUDA device code.
762  if (getLangOpts().CUDA)
763  CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764  << "throw" << CurrentCUDATarget();
765 
766  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767  Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768 
769  if (Ex && !Ex->isTypeDependent()) {
770  QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771  if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
772  return ExprError();
773 
774  // Initialize the exception result. This implicitly weeds out
775  // abstract types or types with inaccessible copy constructors.
776 
777  // C++0x [class.copymove]p31:
778  // When certain criteria are met, an implementation is allowed to omit the
779  // copy/move construction of a class object [...]
780  //
781  // - in a throw-expression, when the operand is the name of a
782  // non-volatile automatic object (other than a function or
783  // catch-clause
784  // parameter) whose scope does not extend beyond the end of the
785  // innermost enclosing try-block (if there is one), the copy/move
786  // operation from the operand to the exception object (15.1) can be
787  // omitted by constructing the automatic object directly into the
788  // exception object
789  const VarDecl *NRVOVariable = nullptr;
790  if (IsThrownVarInScope)
791  NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
792 
794  OpLoc, ExceptionObjectTy,
795  /*NRVO=*/NRVOVariable != nullptr);
796  ExprResult Res = PerformMoveOrCopyInitialization(
797  Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798  if (Res.isInvalid())
799  return ExprError();
800  Ex = Res.get();
801  }
802 
803  return new (Context)
804  CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
805 }
806 
807 static void
809  llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810  llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811  llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812  bool ParentIsPublic) {
813  for (const CXXBaseSpecifier &BS : RD->bases()) {
814  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815  bool NewSubobject;
816  // Virtual bases constitute the same subobject. Non-virtual bases are
817  // always distinct subobjects.
818  if (BS.isVirtual())
819  NewSubobject = VBases.insert(BaseDecl).second;
820  else
821  NewSubobject = true;
822 
823  if (NewSubobject)
824  ++SubobjectsSeen[BaseDecl];
825 
826  // Only add subobjects which have public access throughout the entire chain.
827  bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828  if (PublicPath)
829  PublicSubobjectsSeen.insert(BaseDecl);
830 
831  // Recurse on to each base subobject.
832  collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833  PublicPath);
834  }
835 }
836 
839  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842  SubobjectsSeen[RD] = 1;
843  PublicSubobjectsSeen.insert(RD);
844  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845  /*ParentIsPublic=*/true);
846 
847  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848  // Skip ambiguous objects.
849  if (SubobjectsSeen[PublicSubobject] > 1)
850  continue;
851 
852  Objects.push_back(PublicSubobject);
853  }
854 }
855 
856 /// CheckCXXThrowOperand - Validate the operand of a throw.
858  QualType ExceptionObjectTy, Expr *E) {
859  // If the type of the exception would be an incomplete type or a pointer
860  // to an incomplete type other than (cv) void the program is ill-formed.
861  QualType Ty = ExceptionObjectTy;
862  bool isPointer = false;
863  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
864  Ty = Ptr->getPointeeType();
865  isPointer = true;
866  }
867  if (!isPointer || !Ty->isVoidType()) {
868  if (RequireCompleteType(ThrowLoc, Ty,
869  isPointer ? diag::err_throw_incomplete_ptr
870  : diag::err_throw_incomplete,
871  E->getSourceRange()))
872  return true;
873 
874  if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
875  diag::err_throw_abstract_type, E))
876  return true;
877  }
878 
879  // If the exception has class type, we need additional handling.
880  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881  if (!RD)
882  return false;
883 
884  // If we are throwing a polymorphic class type or pointer thereof,
885  // exception handling will make use of the vtable.
886  MarkVTableUsed(ThrowLoc, RD);
887 
888  // If a pointer is thrown, the referenced object will not be destroyed.
889  if (isPointer)
890  return false;
891 
892  // If the class has a destructor, we must be able to call it.
893  if (!RD->hasIrrelevantDestructor()) {
894  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895  MarkFunctionReferenced(E->getExprLoc(), Destructor);
896  CheckDestructorAccess(E->getExprLoc(), Destructor,
897  PDiag(diag::err_access_dtor_exception) << Ty);
898  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
899  return true;
900  }
901  }
902 
903  // The MSVC ABI creates a list of all types which can catch the exception
904  // object. This list also references the appropriate copy constructor to call
905  // if the object is caught by value and has a non-trivial copy constructor.
906  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
907  // We are only interested in the public, unambiguous bases contained within
908  // the exception object. Bases which are ambiguous or otherwise
909  // inaccessible are not catchable types.
910  llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911  getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
912 
913  for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
914  // Attempt to lookup the copy constructor. Various pieces of machinery
915  // will spring into action, like template instantiation, which means this
916  // cannot be a simple walk of the class's decls. Instead, we must perform
917  // lookup and overload resolution.
918  CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919  if (!CD)
920  continue;
921 
922  // Mark the constructor referenced as it is used by this throw expression.
923  MarkFunctionReferenced(E->getExprLoc(), CD);
924 
925  // Skip this copy constructor if it is trivial, we don't need to record it
926  // in the catchable type data.
927  if (CD->isTrivial())
928  continue;
929 
930  // The copy constructor is non-trivial, create a mapping from this class
931  // type to this constructor.
932  // N.B. The selection of copy constructor is not sensitive to this
933  // particular throw-site. Lookup will be performed at the catch-site to
934  // ensure that the copy constructor is, in fact, accessible (via
935  // friendship or any other means).
936  Context.addCopyConstructorForExceptionObject(Subobject, CD);
937 
938  // We don't keep the instantiated default argument expressions around so
939  // we must rebuild them here.
940  for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
941  if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942  return true;
943  }
944  }
945  }
946 
947  return false;
948 }
949 
951  ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952  DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953 
954  QualType ClassType = ThisTy->getPointeeType();
955  LambdaScopeInfo *CurLSI = nullptr;
956  DeclContext *CurDC = CurSemaContext;
957 
958  // Iterate through the stack of lambdas starting from the innermost lambda to
959  // the outermost lambda, checking if '*this' is ever captured by copy - since
960  // that could change the cv-qualifiers of the '*this' object.
961  // The object referred to by '*this' starts out with the cv-qualifiers of its
962  // member function. We then start with the innermost lambda and iterate
963  // outward checking to see if any lambda performs a by-copy capture of '*this'
964  // - and if so, any nested lambda must respect the 'constness' of that
965  // capturing lamdbda's call operator.
966  //
967 
968  // Since the FunctionScopeInfo stack is representative of the lexical
969  // nesting of the lambda expressions during initial parsing (and is the best
970  // place for querying information about captures about lambdas that are
971  // partially processed) and perhaps during instantiation of function templates
972  // that contain lambda expressions that need to be transformed BUT not
973  // necessarily during instantiation of a nested generic lambda's function call
974  // operator (which might even be instantiated at the end of the TU) - at which
975  // time the DeclContext tree is mature enough to query capture information
976  // reliably - we use a two pronged approach to walk through all the lexically
977  // enclosing lambda expressions:
978  //
979  // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980  // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981  // enclosed by the call-operator of the LSI below it on the stack (while
982  // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983  // the stack represents the innermost lambda.
984  //
985  // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986  // represents a lambda's call operator. If it does, we must be instantiating
987  // a generic lambda's call operator (represented by the Current LSI, and
988  // should be the only scenario where an inconsistency between the LSI and the
989  // DeclContext should occur), so climb out the DeclContexts if they
990  // represent lambdas, while querying the corresponding closure types
991  // regarding capture information.
992 
993  // 1) Climb down the function scope info stack.
994  for (int I = FunctionScopes.size();
995  I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996  (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997  cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
998  CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999  CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1000 
1001  if (!CurLSI->isCXXThisCaptured())
1002  continue;
1003 
1004  auto C = CurLSI->getCXXThisCapture();
1005 
1006  if (C.isCopyCapture()) {
1008  if (CurLSI->CallOperator->isConst())
1009  ClassType.addConst();
1010  return ASTCtx.getPointerType(ClassType);
1011  }
1012  }
1013 
1014  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015  // happen during instantiation of its nested generic lambda call operator)
1016  if (isLambdaCallOperator(CurDC)) {
1017  assert(CurLSI && "While computing 'this' capture-type for a generic "
1018  "lambda, we must have a corresponding LambdaScopeInfo");
1020  "While computing 'this' capture-type for a generic lambda, when we "
1021  "run out of enclosing LSI's, yet the enclosing DC is a "
1022  "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1023  "lambda call oeprator");
1024  assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1025 
1026  auto IsThisCaptured =
1027  [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028  IsConst = false;
1029  IsByCopy = false;
1030  for (auto &&C : Closure->captures()) {
1031  if (C.capturesThis()) {
1032  if (C.getCaptureKind() == LCK_StarThis)
1033  IsByCopy = true;
1034  if (Closure->getLambdaCallOperator()->isConst())
1035  IsConst = true;
1036  return true;
1037  }
1038  }
1039  return false;
1040  };
1041 
1042  bool IsByCopyCapture = false;
1043  bool IsConstCapture = false;
1044  CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045  while (Closure &&
1046  IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047  if (IsByCopyCapture) {
1049  if (IsConstCapture)
1050  ClassType.addConst();
1051  return ASTCtx.getPointerType(ClassType);
1052  }
1053  Closure = isLambdaCallOperator(Closure->getParent())
1054  ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055  : nullptr;
1056  }
1057  }
1058  return ASTCtx.getPointerType(ClassType);
1059 }
1060 
1062  DeclContext *DC = getFunctionLevelDeclContext();
1063  QualType ThisTy = CXXThisTypeOverride;
1064 
1065  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066  if (method && method->isInstance())
1067  ThisTy = method->getThisType(Context);
1068  }
1069 
1070  if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1071  inTemplateInstantiation()) {
1072 
1073  assert(isa<CXXRecordDecl>(DC) &&
1074  "Trying to get 'this' type from static method?");
1075 
1076  // This is a lambda call operator that is being instantiated as a default
1077  // initializer. DC must point to the enclosing class type, so we can recover
1078  // the 'this' type from it.
1079 
1080  QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081  // There are no cv-qualifiers for 'this' within default initializers,
1082  // per [expr.prim.general]p4.
1083  ThisTy = Context.getPointerType(ClassTy);
1084  }
1085 
1086  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087  // might need to be adjusted if the lambda or any of its enclosing lambda's
1088  // captures '*this' by copy.
1089  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090  return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091  CurContext, Context);
1092  return ThisTy;
1093 }
1094 
1096  Decl *ContextDecl,
1097  unsigned CXXThisTypeQuals,
1098  bool Enabled)
1099  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100 {
1101  if (!Enabled || !ContextDecl)
1102  return;
1103 
1104  CXXRecordDecl *Record = nullptr;
1105  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106  Record = Template->getTemplatedDecl();
1107  else
1108  Record = cast<CXXRecordDecl>(ContextDecl);
1109 
1110  // We care only for CVR qualifiers here, so cut everything else.
1111  CXXThisTypeQuals &= Qualifiers::FastMask;
1113  = S.Context.getPointerType(
1114  S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1115 
1116  this->Enabled = true;
1117 }
1118 
1119 
1121  if (Enabled) {
1122  S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1123  }
1124 }
1125 
1127  QualType ThisTy, SourceLocation Loc,
1128  const bool ByCopy) {
1129 
1130  QualType AdjustedThisTy = ThisTy;
1131  // The type of the corresponding data member (not a 'this' pointer if 'by
1132  // copy').
1133  QualType CaptureThisFieldTy = ThisTy;
1134  if (ByCopy) {
1135  // If we are capturing the object referred to by '*this' by copy, ignore any
1136  // cv qualifiers inherited from the type of the member function for the type
1137  // of the closure-type's corresponding data member and any use of 'this'.
1138  CaptureThisFieldTy = ThisTy->getPointeeType();
1139  CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1140  AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1141  }
1142 
1143  FieldDecl *Field = FieldDecl::Create(
1144  Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1145  Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1146  ICIS_NoInit);
1147 
1148  Field->setImplicit(true);
1149  Field->setAccess(AS_private);
1150  RD->addDecl(Field);
1151  Expr *This =
1152  new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1153  if (ByCopy) {
1154  Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1155  UO_Deref,
1156  This).get();
1158  nullptr, CaptureThisFieldTy, Loc);
1159  InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1160  InitializationSequence Init(S, Entity, InitKind, StarThis);
1161  ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1162  if (ER.isInvalid()) return nullptr;
1163  return ER.get();
1164  }
1165  return This;
1166 }
1167 
1168 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1169  bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1170  const bool ByCopy) {
1171  // We don't need to capture this in an unevaluated context.
1172  if (isUnevaluatedContext() && !Explicit)
1173  return true;
1174 
1175  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1176 
1177  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1178  ? *FunctionScopeIndexToStopAt
1179  : FunctionScopes.size() - 1;
1180 
1181  // Check that we can capture the *enclosing object* (referred to by '*this')
1182  // by the capturing-entity/closure (lambda/block/etc) at
1183  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1184 
1185  // Note: The *enclosing object* can only be captured by-value by a
1186  // closure that is a lambda, using the explicit notation:
1187  // [*this] { ... }.
1188  // Every other capture of the *enclosing object* results in its by-reference
1189  // capture.
1190 
1191  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1192  // stack), we can capture the *enclosing object* only if:
1193  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1194  // - or, 'L' has an implicit capture.
1195  // AND
1196  // -- there is no enclosing closure
1197  // -- or, there is some enclosing closure 'E' that has already captured the
1198  // *enclosing object*, and every intervening closure (if any) between 'E'
1199  // and 'L' can implicitly capture the *enclosing object*.
1200  // -- or, every enclosing closure can implicitly capture the
1201  // *enclosing object*
1202 
1203 
1204  unsigned NumCapturingClosures = 0;
1205  for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1206  if (CapturingScopeInfo *CSI =
1207  dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1208  if (CSI->CXXThisCaptureIndex != 0) {
1209  // 'this' is already being captured; there isn't anything more to do.
1210  CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1211  break;
1212  }
1213  LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1215  // This context can't implicitly capture 'this'; fail out.
1216  if (BuildAndDiagnose)
1217  Diag(Loc, diag::err_this_capture)
1218  << (Explicit && idx == MaxFunctionScopesIndex);
1219  return true;
1220  }
1221  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1222  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1223  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1224  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1225  (Explicit && idx == MaxFunctionScopesIndex)) {
1226  // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1227  // iteration through can be an explicit capture, all enclosing closures,
1228  // if any, must perform implicit captures.
1229 
1230  // This closure can capture 'this'; continue looking upwards.
1231  NumCapturingClosures++;
1232  continue;
1233  }
1234  // This context can't implicitly capture 'this'; fail out.
1235  if (BuildAndDiagnose)
1236  Diag(Loc, diag::err_this_capture)
1237  << (Explicit && idx == MaxFunctionScopesIndex);
1238  return true;
1239  }
1240  break;
1241  }
1242  if (!BuildAndDiagnose) return false;
1243 
1244  // If we got here, then the closure at MaxFunctionScopesIndex on the
1245  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1246  // (including implicit by-reference captures in any enclosing closures).
1247 
1248  // In the loop below, respect the ByCopy flag only for the closure requesting
1249  // the capture (i.e. first iteration through the loop below). Ignore it for
1250  // all enclosing closure's up to NumCapturingClosures (since they must be
1251  // implicitly capturing the *enclosing object* by reference (see loop
1252  // above)).
1253  assert((!ByCopy ||
1254  dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1255  "Only a lambda can capture the enclosing object (referred to by "
1256  "*this) by copy");
1257  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1258  // contexts.
1259  QualType ThisTy = getCurrentThisType();
1260  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1261  --idx, --NumCapturingClosures) {
1262  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1263  Expr *ThisExpr = nullptr;
1264 
1265  if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1266  // For lambda expressions, build a field and an initializing expression,
1267  // and capture the *enclosing object* by copy only if this is the first
1268  // iteration.
1269  ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1270  ByCopy && idx == MaxFunctionScopesIndex);
1271 
1272  } else if (CapturedRegionScopeInfo *RSI
1273  = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1274  ThisExpr =
1275  captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1276  false/*ByCopy*/);
1277 
1278  bool isNested = NumCapturingClosures > 1;
1279  CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1280  }
1281  return false;
1282 }
1283 
1285  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1286  /// is a non-lvalue expression whose value is the address of the object for
1287  /// which the function is called.
1288 
1289  QualType ThisTy = getCurrentThisType();
1290  if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1291 
1292  CheckCXXThisCapture(Loc);
1293  return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1294 }
1295 
1297  // If we're outside the body of a member function, then we'll have a specified
1298  // type for 'this'.
1300  return false;
1301 
1302  // Determine whether we're looking into a class that's currently being
1303  // defined.
1304  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1305  return Class && Class->isBeingDefined();
1306 }
1307 
1308 /// Parse construction of a specified type.
1309 /// Can be interpreted either as function-style casting ("int(x)")
1310 /// or class type construction ("ClassType(x,y,z)")
1311 /// or creation of a value-initialized type ("int()").
1312 ExprResult
1314  SourceLocation LParenOrBraceLoc,
1315  MultiExprArg exprs,
1316  SourceLocation RParenOrBraceLoc,
1317  bool ListInitialization) {
1318  if (!TypeRep)
1319  return ExprError();
1320 
1321  TypeSourceInfo *TInfo;
1322  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1323  if (!TInfo)
1325 
1326  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1327  RParenOrBraceLoc, ListInitialization);
1328  // Avoid creating a non-type-dependent expression that contains typos.
1329  // Non-type-dependent expressions are liable to be discarded without
1330  // checking for embedded typos.
1331  if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1332  !Result.get()->isTypeDependent())
1334  return Result;
1335 }
1336 
1337 ExprResult
1339  SourceLocation LParenOrBraceLoc,
1340  MultiExprArg Exprs,
1341  SourceLocation RParenOrBraceLoc,
1342  bool ListInitialization) {
1343  QualType Ty = TInfo->getType();
1344  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1345 
1347  // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1348  // directly. We work around this by dropping the locations of the braces.
1349  SourceRange Locs = ListInitialization
1350  ? SourceRange()
1351  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1352  return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1353  Exprs, Locs.getEnd());
1354  }
1355 
1356  assert((!ListInitialization ||
1357  (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1358  "List initialization must have initializer list as expression.");
1359  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1360 
1363  Exprs.size()
1364  ? ListInitialization
1366  TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1367  : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1368  RParenOrBraceLoc)
1369  : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1370  RParenOrBraceLoc);
1371 
1372  // C++1z [expr.type.conv]p1:
1373  // If the type is a placeholder for a deduced class type, [...perform class
1374  // template argument deduction...]
1375  DeducedType *Deduced = Ty->getContainedDeducedType();
1376  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1378  Kind, Exprs);
1379  if (Ty.isNull())
1380  return ExprError();
1381  Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1382  }
1383 
1384  // C++ [expr.type.conv]p1:
1385  // If the expression list is a parenthesized single expression, the type
1386  // conversion expression is equivalent (in definedness, and if defined in
1387  // meaning) to the corresponding cast expression.
1388  if (Exprs.size() == 1 && !ListInitialization &&
1389  !isa<InitListExpr>(Exprs[0])) {
1390  Expr *Arg = Exprs[0];
1391  return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1392  RParenOrBraceLoc);
1393  }
1394 
1395  // For an expression of the form T(), T shall not be an array type.
1396  QualType ElemTy = Ty;
1397  if (Ty->isArrayType()) {
1398  if (!ListInitialization)
1399  return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1400  << FullRange);
1401  ElemTy = Context.getBaseElementType(Ty);
1402  }
1403 
1404  // There doesn't seem to be an explicit rule against this but sanity demands
1405  // we only construct objects with object types.
1406  if (Ty->isFunctionType())
1407  return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1408  << Ty << FullRange);
1409 
1410  // C++17 [expr.type.conv]p2:
1411  // If the type is cv void and the initializer is (), the expression is a
1412  // prvalue of the specified type that performs no initialization.
1413  if (!Ty->isVoidType() &&
1414  RequireCompleteType(TyBeginLoc, ElemTy,
1415  diag::err_invalid_incomplete_type_use, FullRange))
1416  return ExprError();
1417 
1418  // Otherwise, the expression is a prvalue of the specified type whose
1419  // result object is direct-initialized (11.6) with the initializer.
1420  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1421  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1422 
1423  if (Result.isInvalid())
1424  return Result;
1425 
1426  Expr *Inner = Result.get();
1427  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1428  Inner = BTE->getSubExpr();
1429  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1430  !isa<CXXScalarValueInitExpr>(Inner)) {
1431  // If we created a CXXTemporaryObjectExpr, that node also represents the
1432  // functional cast. Otherwise, create an explicit cast to represent
1433  // the syntactic form of a functional-style cast that was used here.
1434  //
1435  // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1436  // would give a more consistent AST representation than using a
1437  // CXXTemporaryObjectExpr. It's also weird that the functional cast
1438  // is sometimes handled by initialization and sometimes not.
1439  QualType ResultType = Result.get()->getType();
1440  SourceRange Locs = ListInitialization
1441  ? SourceRange()
1442  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1444  Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1445  Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1446  }
1447 
1448  return Result;
1449 }
1450 
1452  // [CUDA] Ignore this function, if we can't call it.
1453  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1454  if (getLangOpts().CUDA &&
1455  IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1456  return false;
1457 
1459  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1460 
1461  if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1462  return Result;
1463 
1464  // In case of CUDA, return true if none of the 1-argument deallocator
1465  // functions are actually callable.
1466  return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1467  assert(FD->getNumParams() == 1 &&
1468  "Only single-operand functions should be in PreventedBy");
1469  return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1470  });
1471 }
1472 
1473 /// Determine whether the given function is a non-placement
1474 /// deallocation function.
1476  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1477  return S.isUsualDeallocationFunction(Method);
1478 
1479  if (FD->getOverloadedOperator() != OO_Delete &&
1480  FD->getOverloadedOperator() != OO_Array_Delete)
1481  return false;
1482 
1483  unsigned UsualParams = 1;
1484 
1485  if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1487  FD->getParamDecl(UsualParams)->getType(),
1488  S.Context.getSizeType()))
1489  ++UsualParams;
1490 
1491  if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1493  FD->getParamDecl(UsualParams)->getType(),
1495  ++UsualParams;
1496 
1497  return UsualParams == FD->getNumParams();
1498 }
1499 
1500 namespace {
1501  struct UsualDeallocFnInfo {
1502  UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1503  UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1504  : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1505  Destroying(false), HasSizeT(false), HasAlignValT(false),
1506  CUDAPref(Sema::CFP_Native) {
1507  // A function template declaration is never a usual deallocation function.
1508  if (!FD)
1509  return;
1510  unsigned NumBaseParams = 1;
1511  if (FD->isDestroyingOperatorDelete()) {
1512  Destroying = true;
1513  ++NumBaseParams;
1514  }
1515  if (FD->getNumParams() == NumBaseParams + 2)
1516  HasAlignValT = HasSizeT = true;
1517  else if (FD->getNumParams() == NumBaseParams + 1) {
1518  HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1519  HasAlignValT = !HasSizeT;
1520  }
1521 
1522  // In CUDA, determine how much we'd like / dislike to call this.
1523  if (S.getLangOpts().CUDA)
1524  if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1525  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1526  }
1527 
1528  explicit operator bool() const { return FD; }
1529 
1530  bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1531  bool WantAlign) const {
1532  // C++ P0722:
1533  // A destroying operator delete is preferred over a non-destroying
1534  // operator delete.
1535  if (Destroying != Other.Destroying)
1536  return Destroying;
1537 
1538  // C++17 [expr.delete]p10:
1539  // If the type has new-extended alignment, a function with a parameter
1540  // of type std::align_val_t is preferred; otherwise a function without
1541  // such a parameter is preferred
1542  if (HasAlignValT != Other.HasAlignValT)
1543  return HasAlignValT == WantAlign;
1544 
1545  if (HasSizeT != Other.HasSizeT)
1546  return HasSizeT == WantSize;
1547 
1548  // Use CUDA call preference as a tiebreaker.
1549  return CUDAPref > Other.CUDAPref;
1550  }
1551 
1552  DeclAccessPair Found;
1553  FunctionDecl *FD;
1554  bool Destroying, HasSizeT, HasAlignValT;
1556  };
1557 }
1558 
1559 /// Determine whether a type has new-extended alignment. This may be called when
1560 /// the type is incomplete (for a delete-expression with an incomplete pointee
1561 /// type), in which case it will conservatively return false if the alignment is
1562 /// not known.
1563 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1564  return S.getLangOpts().AlignedAllocation &&
1565  S.getASTContext().getTypeAlignIfKnown(AllocType) >
1567 }
1568 
1569 /// Select the correct "usual" deallocation function to use from a selection of
1570 /// deallocation functions (either global or class-scope).
1571 static UsualDeallocFnInfo resolveDeallocationOverload(
1572  Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1573  llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1574  UsualDeallocFnInfo Best;
1575 
1576  for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1577  UsualDeallocFnInfo Info(S, I.getPair());
1578  if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1579  Info.CUDAPref == Sema::CFP_Never)
1580  continue;
1581 
1582  if (!Best) {
1583  Best = Info;
1584  if (BestFns)
1585  BestFns->push_back(Info);
1586  continue;
1587  }
1588 
1589  if (Best.isBetterThan(Info, WantSize, WantAlign))
1590  continue;
1591 
1592  // If more than one preferred function is found, all non-preferred
1593  // functions are eliminated from further consideration.
1594  if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1595  BestFns->clear();
1596 
1597  Best = Info;
1598  if (BestFns)
1599  BestFns->push_back(Info);
1600  }
1601 
1602  return Best;
1603 }
1604 
1605 /// Determine whether a given type is a class for which 'delete[]' would call
1606 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1607 /// we need to store the array size (even if the type is
1608 /// trivially-destructible).
1610  QualType allocType) {
1611  const RecordType *record =
1612  allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1613  if (!record) return false;
1614 
1615  // Try to find an operator delete[] in class scope.
1616 
1617  DeclarationName deleteName =
1618  S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1619  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1620  S.LookupQualifiedName(ops, record->getDecl());
1621 
1622  // We're just doing this for information.
1623  ops.suppressDiagnostics();
1624 
1625  // Very likely: there's no operator delete[].
1626  if (ops.empty()) return false;
1627 
1628  // If it's ambiguous, it should be illegal to call operator delete[]
1629  // on this thing, so it doesn't matter if we allocate extra space or not.
1630  if (ops.isAmbiguous()) return false;
1631 
1632  // C++17 [expr.delete]p10:
1633  // If the deallocation functions have class scope, the one without a
1634  // parameter of type std::size_t is selected.
1635  auto Best = resolveDeallocationOverload(
1636  S, ops, /*WantSize*/false,
1637  /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1638  return Best && Best.HasSizeT;
1639 }
1640 
1641 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1642 ///
1643 /// E.g.:
1644 /// @code new (memory) int[size][4] @endcode
1645 /// or
1646 /// @code ::new Foo(23, "hello") @endcode
1647 ///
1648 /// \param StartLoc The first location of the expression.
1649 /// \param UseGlobal True if 'new' was prefixed with '::'.
1650 /// \param PlacementLParen Opening paren of the placement arguments.
1651 /// \param PlacementArgs Placement new arguments.
1652 /// \param PlacementRParen Closing paren of the placement arguments.
1653 /// \param TypeIdParens If the type is in parens, the source range.
1654 /// \param D The type to be allocated, as well as array dimensions.
1655 /// \param Initializer The initializing expression or initializer-list, or null
1656 /// if there is none.
1657 ExprResult
1658 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1659  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1660  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1661  Declarator &D, Expr *Initializer) {
1662  Expr *ArraySize = nullptr;
1663  // If the specified type is an array, unwrap it and save the expression.
1664  if (D.getNumTypeObjects() > 0 &&
1666  DeclaratorChunk &Chunk = D.getTypeObject(0);
1667  if (D.getDeclSpec().hasAutoTypeSpec())
1668  return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1669  << D.getSourceRange());
1670  if (Chunk.Arr.hasStatic)
1671  return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1672  << D.getSourceRange());
1673  if (!Chunk.Arr.NumElts)
1674  return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1675  << D.getSourceRange());
1676 
1677  ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1678  D.DropFirstTypeObject();
1679  }
1680 
1681  // Every dimension shall be of constant size.
1682  if (ArraySize) {
1683  for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1685  break;
1686 
1688  if (Expr *NumElts = (Expr *)Array.NumElts) {
1689  if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1690  if (getLangOpts().CPlusPlus14) {
1691  // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1692  // shall be a converted constant expression (5.19) of type std::size_t
1693  // and shall evaluate to a strictly positive value.
1694  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1695  assert(IntWidth && "Builtin type of size 0?");
1696  llvm::APSInt Value(IntWidth);
1697  Array.NumElts
1699  CCEK_NewExpr)
1700  .get();
1701  } else {
1702  Array.NumElts
1703  = VerifyIntegerConstantExpression(NumElts, nullptr,
1704  diag::err_new_array_nonconst)
1705  .get();
1706  }
1707  if (!Array.NumElts)
1708  return ExprError();
1709  }
1710  }
1711  }
1712  }
1713 
1714  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1715  QualType AllocType = TInfo->getType();
1716  if (D.isInvalidType())
1717  return ExprError();
1718 
1719  SourceRange DirectInitRange;
1720  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1721  DirectInitRange = List->getSourceRange();
1722 
1723  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1724  PlacementLParen, PlacementArgs, PlacementRParen,
1725  TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1726  Initializer);
1727 }
1728 
1730  Expr *Init) {
1731  if (!Init)
1732  return true;
1733  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1734  return PLE->getNumExprs() == 0;
1735  if (isa<ImplicitValueInitExpr>(Init))
1736  return true;
1737  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1738  return !CCE->isListInitialization() &&
1739  CCE->getConstructor()->isDefaultConstructor();
1740  else if (Style == CXXNewExpr::ListInit) {
1741  assert(isa<InitListExpr>(Init) &&
1742  "Shouldn't create list CXXConstructExprs for arrays.");
1743  return true;
1744  }
1745  return false;
1746 }
1747 
1748 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1749 // implemented in the standard library is selected.
1751  SourceLocation Loc, bool IsDelete,
1752  Sema &S) {
1753  if (!S.getLangOpts().AlignedAllocationUnavailable)
1754  return;
1755 
1756  // Return if there is a definition.
1757  if (FD.isDefined())
1758  return;
1759 
1760  bool IsAligned = false;
1761  if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
1762  const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1763  StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1765 
1766  S.Diag(Loc, diag::err_aligned_allocation_unavailable)
1767  << IsDelete << FD.getType().getAsString() << OSName
1768  << alignedAllocMinVersion(T.getOS()).getAsString();
1769  S.Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1770  }
1771 }
1772 
1773 ExprResult
1774 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1775  SourceLocation PlacementLParen,
1776  MultiExprArg PlacementArgs,
1777  SourceLocation PlacementRParen,
1778  SourceRange TypeIdParens,
1779  QualType AllocType,
1780  TypeSourceInfo *AllocTypeInfo,
1781  Expr *ArraySize,
1782  SourceRange DirectInitRange,
1783  Expr *Initializer) {
1784  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1785  SourceLocation StartLoc = Range.getBegin();
1786 
1788  if (DirectInitRange.isValid()) {
1789  assert(Initializer && "Have parens but no initializer.");
1790  initStyle = CXXNewExpr::CallInit;
1791  } else if (Initializer && isa<InitListExpr>(Initializer))
1792  initStyle = CXXNewExpr::ListInit;
1793  else {
1794  assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1795  isa<CXXConstructExpr>(Initializer)) &&
1796  "Initializer expression that cannot have been implicitly created.");
1797  initStyle = CXXNewExpr::NoInit;
1798  }
1799 
1800  Expr **Inits = &Initializer;
1801  unsigned NumInits = Initializer ? 1 : 0;
1802  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1803  assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1804  Inits = List->getExprs();
1805  NumInits = List->getNumExprs();
1806  }
1807 
1808  // C++11 [expr.new]p15:
1809  // A new-expression that creates an object of type T initializes that
1810  // object as follows:
1812  // - If the new-initializer is omitted, the object is default-
1813  // initialized (8.5); if no initialization is performed,
1814  // the object has indeterminate value
1815  = initStyle == CXXNewExpr::NoInit
1817  // - Otherwise, the new-initializer is interpreted according to
1818  // the
1819  // initialization rules of 8.5 for direct-initialization.
1820  : initStyle == CXXNewExpr::ListInit
1822  TypeRange.getBegin(), Initializer->getBeginLoc(),
1823  Initializer->getEndLoc())
1825  DirectInitRange.getBegin(),
1826  DirectInitRange.getEnd());
1827 
1828  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1829  auto *Deduced = AllocType->getContainedDeducedType();
1830  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1831  if (ArraySize)
1832  return ExprError(Diag(ArraySize->getExprLoc(),
1833  diag::err_deduced_class_template_compound_type)
1834  << /*array*/ 2 << ArraySize->getSourceRange());
1835 
1836  InitializedEntity Entity
1837  = InitializedEntity::InitializeNew(StartLoc, AllocType);
1839  AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1840  if (AllocType.isNull())
1841  return ExprError();
1842  } else if (Deduced) {
1843  bool Braced = (initStyle == CXXNewExpr::ListInit);
1844  if (NumInits == 1) {
1845  if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1846  Inits = p->getInits();
1847  NumInits = p->getNumInits();
1848  Braced = true;
1849  }
1850  }
1851 
1852  if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1853  return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1854  << AllocType << TypeRange);
1855  if (NumInits > 1) {
1856  Expr *FirstBad = Inits[1];
1857  return ExprError(Diag(FirstBad->getBeginLoc(),
1858  diag::err_auto_new_ctor_multiple_expressions)
1859  << AllocType << TypeRange);
1860  }
1861  if (Braced && !getLangOpts().CPlusPlus17)
1862  Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1863  << AllocType << TypeRange;
1864  Expr *Deduce = Inits[0];
1866  if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1867  return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1868  << AllocType << Deduce->getType()
1869  << TypeRange << Deduce->getSourceRange());
1870  if (DeducedType.isNull())
1871  return ExprError();
1872  AllocType = DeducedType;
1873  }
1874 
1875  // Per C++0x [expr.new]p5, the type being constructed may be a
1876  // typedef of an array type.
1877  if (!ArraySize) {
1878  if (const ConstantArrayType *Array
1879  = Context.getAsConstantArrayType(AllocType)) {
1880  ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1881  Context.getSizeType(),
1882  TypeRange.getEnd());
1883  AllocType = Array->getElementType();
1884  }
1885  }
1886 
1887  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1888  return ExprError();
1889 
1890  // In ARC, infer 'retaining' for the allocated
1891  if (getLangOpts().ObjCAutoRefCount &&
1892  AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1893  AllocType->isObjCLifetimeType()) {
1894  AllocType = Context.getLifetimeQualifiedType(AllocType,
1895  AllocType->getObjCARCImplicitLifetime());
1896  }
1897 
1898  QualType ResultType = Context.getPointerType(AllocType);
1899 
1900  if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1901  ExprResult result = CheckPlaceholderExpr(ArraySize);
1902  if (result.isInvalid()) return ExprError();
1903  ArraySize = result.get();
1904  }
1905  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1906  // integral or enumeration type with a non-negative value."
1907  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1908  // enumeration type, or a class type for which a single non-explicit
1909  // conversion function to integral or unscoped enumeration type exists.
1910  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1911  // std::size_t.
1912  llvm::Optional<uint64_t> KnownArraySize;
1913  if (ArraySize && !ArraySize->isTypeDependent()) {
1914  ExprResult ConvertedSize;
1915  if (getLangOpts().CPlusPlus14) {
1916  assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1917 
1918  ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1919  AA_Converting);
1920 
1921  if (!ConvertedSize.isInvalid() &&
1922  ArraySize->getType()->getAs<RecordType>())
1923  // Diagnose the compatibility of this conversion.
1924  Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1925  << ArraySize->getType() << 0 << "'size_t'";
1926  } else {
1927  class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1928  protected:
1929  Expr *ArraySize;
1930 
1931  public:
1932  SizeConvertDiagnoser(Expr *ArraySize)
1933  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1934  ArraySize(ArraySize) {}
1935 
1936  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1937  QualType T) override {
1938  return S.Diag(Loc, diag::err_array_size_not_integral)
1939  << S.getLangOpts().CPlusPlus11 << T;
1940  }
1941 
1942  SemaDiagnosticBuilder diagnoseIncomplete(
1943  Sema &S, SourceLocation Loc, QualType T) override {
1944  return S.Diag(Loc, diag::err_array_size_incomplete_type)
1945  << T << ArraySize->getSourceRange();
1946  }
1947 
1948  SemaDiagnosticBuilder diagnoseExplicitConv(
1949  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1950  return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1951  }
1952 
1953  SemaDiagnosticBuilder noteExplicitConv(
1954  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1955  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1956  << ConvTy->isEnumeralType() << ConvTy;
1957  }
1958 
1959  SemaDiagnosticBuilder diagnoseAmbiguous(
1960  Sema &S, SourceLocation Loc, QualType T) override {
1961  return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1962  }
1963 
1964  SemaDiagnosticBuilder noteAmbiguous(
1965  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1966  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967  << ConvTy->isEnumeralType() << ConvTy;
1968  }
1969 
1970  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1971  QualType T,
1972  QualType ConvTy) override {
1973  return S.Diag(Loc,
1974  S.getLangOpts().CPlusPlus11
1975  ? diag::warn_cxx98_compat_array_size_conversion
1976  : diag::ext_array_size_conversion)
1977  << T << ConvTy->isEnumeralType() << ConvTy;
1978  }
1979  } SizeDiagnoser(ArraySize);
1980 
1981  ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1982  SizeDiagnoser);
1983  }
1984  if (ConvertedSize.isInvalid())
1985  return ExprError();
1986 
1987  ArraySize = ConvertedSize.get();
1988  QualType SizeType = ArraySize->getType();
1989 
1990  if (!SizeType->isIntegralOrUnscopedEnumerationType())
1991  return ExprError();
1992 
1993  // C++98 [expr.new]p7:
1994  // The expression in a direct-new-declarator shall have integral type
1995  // with a non-negative value.
1996  //
1997  // Let's see if this is a constant < 0. If so, we reject it out of hand,
1998  // per CWG1464. Otherwise, if it's not a constant, we must have an
1999  // unparenthesized array type.
2000  if (!ArraySize->isValueDependent()) {
2001  llvm::APSInt Value;
2002  // We've already performed any required implicit conversion to integer or
2003  // unscoped enumeration type.
2004  // FIXME: Per CWG1464, we are required to check the value prior to
2005  // converting to size_t. This will never find a negative array size in
2006  // C++14 onwards, because Value is always unsigned here!
2007  if (ArraySize->isIntegerConstantExpr(Value, Context)) {
2008  if (Value.isSigned() && Value.isNegative()) {
2009  return ExprError(Diag(ArraySize->getBeginLoc(),
2010  diag::err_typecheck_negative_array_size)
2011  << ArraySize->getSourceRange());
2012  }
2013 
2014  if (!AllocType->isDependentType()) {
2015  unsigned ActiveSizeBits =
2017  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2018  return ExprError(
2019  Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2020  << Value.toString(10) << ArraySize->getSourceRange());
2021  }
2022 
2023  KnownArraySize = Value.getZExtValue();
2024  } else if (TypeIdParens.isValid()) {
2025  // Can't have dynamic array size when the type-id is in parentheses.
2026  Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2027  << ArraySize->getSourceRange()
2028  << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2029  << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2030 
2031  TypeIdParens = SourceRange();
2032  }
2033  }
2034 
2035  // Note that we do *not* convert the argument in any way. It can
2036  // be signed, larger than size_t, whatever.
2037  }
2038 
2039  FunctionDecl *OperatorNew = nullptr;
2040  FunctionDecl *OperatorDelete = nullptr;
2041  unsigned Alignment =
2042  AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2043  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2044  bool PassAlignment = getLangOpts().AlignedAllocation &&
2045  Alignment > NewAlignment;
2046 
2048  if (!AllocType->isDependentType() &&
2049  !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2050  FindAllocationFunctions(StartLoc,
2051  SourceRange(PlacementLParen, PlacementRParen),
2052  Scope, Scope, AllocType, ArraySize, PassAlignment,
2053  PlacementArgs, OperatorNew, OperatorDelete))
2054  return ExprError();
2055 
2056  // If this is an array allocation, compute whether the usual array
2057  // deallocation function for the type has a size_t parameter.
2058  bool UsualArrayDeleteWantsSize = false;
2059  if (ArraySize && !AllocType->isDependentType())
2060  UsualArrayDeleteWantsSize =
2061  doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2062 
2063  SmallVector<Expr *, 8> AllPlaceArgs;
2064  if (OperatorNew) {
2065  const FunctionProtoType *Proto =
2066  OperatorNew->getType()->getAs<FunctionProtoType>();
2067  VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2069 
2070  // We've already converted the placement args, just fill in any default
2071  // arguments. Skip the first parameter because we don't have a corresponding
2072  // argument. Skip the second parameter too if we're passing in the
2073  // alignment; we've already filled it in.
2074  if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2075  PassAlignment ? 2 : 1, PlacementArgs,
2076  AllPlaceArgs, CallType))
2077  return ExprError();
2078 
2079  if (!AllPlaceArgs.empty())
2080  PlacementArgs = AllPlaceArgs;
2081 
2082  // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2083  DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2084 
2085  // FIXME: Missing call to CheckFunctionCall or equivalent
2086 
2087  // Warn if the type is over-aligned and is being allocated by (unaligned)
2088  // global operator new.
2089  if (PlacementArgs.empty() && !PassAlignment &&
2090  (OperatorNew->isImplicit() ||
2091  (OperatorNew->getBeginLoc().isValid() &&
2092  getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2093  if (Alignment > NewAlignment)
2094  Diag(StartLoc, diag::warn_overaligned_type)
2095  << AllocType
2096  << unsigned(Alignment / Context.getCharWidth())
2097  << unsigned(NewAlignment / Context.getCharWidth());
2098  }
2099  }
2100 
2101  // Array 'new' can't have any initializers except empty parentheses.
2102  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2103  // dialect distinction.
2104  if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2105  SourceRange InitRange(Inits[0]->getBeginLoc(),
2106  Inits[NumInits - 1]->getEndLoc());
2107  Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2108  return ExprError();
2109  }
2110 
2111  // If we can perform the initialization, and we've not already done so,
2112  // do it now.
2113  if (!AllocType->isDependentType() &&
2115  llvm::makeArrayRef(Inits, NumInits))) {
2116  // The type we initialize is the complete type, including the array bound.
2117  QualType InitType;
2118  if (KnownArraySize)
2119  InitType = Context.getConstantArrayType(
2120  AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2121  *KnownArraySize),
2122  ArrayType::Normal, 0);
2123  else if (ArraySize)
2124  InitType =
2126  else
2127  InitType = AllocType;
2128 
2129  InitializedEntity Entity
2130  = InitializedEntity::InitializeNew(StartLoc, InitType);
2131  InitializationSequence InitSeq(*this, Entity, Kind,
2132  MultiExprArg(Inits, NumInits));
2133  ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2134  MultiExprArg(Inits, NumInits));
2135  if (FullInit.isInvalid())
2136  return ExprError();
2137 
2138  // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2139  // we don't want the initialized object to be destructed.
2140  // FIXME: We should not create these in the first place.
2141  if (CXXBindTemporaryExpr *Binder =
2142  dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2143  FullInit = Binder->getSubExpr();
2144 
2145  Initializer = FullInit.get();
2146  }
2147 
2148  // Mark the new and delete operators as referenced.
2149  if (OperatorNew) {
2150  if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2151  return ExprError();
2152  MarkFunctionReferenced(StartLoc, OperatorNew);
2153  diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
2154  }
2155  if (OperatorDelete) {
2156  if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2157  return ExprError();
2158  MarkFunctionReferenced(StartLoc, OperatorDelete);
2159  diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
2160  }
2161 
2162  // C++0x [expr.new]p17:
2163  // If the new expression creates an array of objects of class type,
2164  // access and ambiguity control are done for the destructor.
2165  QualType BaseAllocType = Context.getBaseElementType(AllocType);
2166  if (ArraySize && !BaseAllocType->isDependentType()) {
2167  if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2168  if (CXXDestructorDecl *dtor = LookupDestructor(
2169  cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2170  MarkFunctionReferenced(StartLoc, dtor);
2171  CheckDestructorAccess(StartLoc, dtor,
2172  PDiag(diag::err_access_dtor)
2173  << BaseAllocType);
2174  if (DiagnoseUseOfDecl(dtor, StartLoc))
2175  return ExprError();
2176  }
2177  }
2178  }
2179 
2180  return new (Context)
2181  CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2182  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2183  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2184  Range, DirectInitRange);
2185 }
2186 
2187 /// Checks that a type is suitable as the allocated type
2188 /// in a new-expression.
2190  SourceRange R) {
2191  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2192  // abstract class type or array thereof.
2193  if (AllocType->isFunctionType())
2194  return Diag(Loc, diag::err_bad_new_type)
2195  << AllocType << 0 << R;
2196  else if (AllocType->isReferenceType())
2197  return Diag(Loc, diag::err_bad_new_type)
2198  << AllocType << 1 << R;
2199  else if (!AllocType->isDependentType() &&
2200  RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2201  return true;
2202  else if (RequireNonAbstractType(Loc, AllocType,
2203  diag::err_allocation_of_abstract_type))
2204  return true;
2205  else if (AllocType->isVariablyModifiedType())
2206  return Diag(Loc, diag::err_variably_modified_new_type)
2207  << AllocType;
2208  else if (AllocType.getAddressSpace() != LangAS::Default &&
2209  !getLangOpts().OpenCLCPlusPlus)
2210  return Diag(Loc, diag::err_address_space_qualified_new)
2211  << AllocType.getUnqualifiedType()
2213  else if (getLangOpts().ObjCAutoRefCount) {
2214  if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2215  QualType BaseAllocType = Context.getBaseElementType(AT);
2216  if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2217  BaseAllocType->isObjCLifetimeType())
2218  return Diag(Loc, diag::err_arc_new_array_without_ownership)
2219  << BaseAllocType;
2220  }
2221  }
2222 
2223  return false;
2224 }
2225 
2228  bool &PassAlignment, FunctionDecl *&Operator,
2229  OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2230  OverloadCandidateSet Candidates(R.getNameLoc(),
2232  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2233  Alloc != AllocEnd; ++Alloc) {
2234  // Even member operator new/delete are implicitly treated as
2235  // static, so don't use AddMemberCandidate.
2236  NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2237 
2238  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2239  S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2240  /*ExplicitTemplateArgs=*/nullptr, Args,
2241  Candidates,
2242  /*SuppressUserConversions=*/false);
2243  continue;
2244  }
2245 
2246  FunctionDecl *Fn = cast<FunctionDecl>(D);
2247  S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2248  /*SuppressUserConversions=*/false);
2249  }
2250 
2251  // Do the resolution.
2253  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2254  case OR_Success: {
2255  // Got one!
2256  FunctionDecl *FnDecl = Best->Function;
2257  if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2258  Best->FoundDecl) == Sema::AR_inaccessible)
2259  return true;
2260 
2261  Operator = FnDecl;
2262  return false;
2263  }
2264 
2265  case OR_No_Viable_Function:
2266  // C++17 [expr.new]p13:
2267  // If no matching function is found and the allocated object type has
2268  // new-extended alignment, the alignment argument is removed from the
2269  // argument list, and overload resolution is performed again.
2270  if (PassAlignment) {
2271  PassAlignment = false;
2272  AlignArg = Args[1];
2273  Args.erase(Args.begin() + 1);
2274  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2275  Operator, &Candidates, AlignArg,
2276  Diagnose);
2277  }
2278 
2279  // MSVC will fall back on trying to find a matching global operator new
2280  // if operator new[] cannot be found. Also, MSVC will leak by not
2281  // generating a call to operator delete or operator delete[], but we
2282  // will not replicate that bug.
2283  // FIXME: Find out how this interacts with the std::align_val_t fallback
2284  // once MSVC implements it.
2285  if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2286  S.Context.getLangOpts().MSVCCompat) {
2287  R.clear();
2290  // FIXME: This will give bad diagnostics pointing at the wrong functions.
2291  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2292  Operator, /*Candidates=*/nullptr,
2293  /*AlignArg=*/nullptr, Diagnose);
2294  }
2295 
2296  if (Diagnose) {
2297  S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2298  << R.getLookupName() << Range;
2299 
2300  // If we have aligned candidates, only note the align_val_t candidates
2301  // from AlignedCandidates and the non-align_val_t candidates from
2302  // Candidates.
2303  if (AlignedCandidates) {
2304  auto IsAligned = [](OverloadCandidate &C) {
2305  return C.Function->getNumParams() > 1 &&
2306  C.Function->getParamDecl(1)->getType()->isAlignValT();
2307  };
2308  auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2309 
2310  // This was an overaligned allocation, so list the aligned candidates
2311  // first.
2312  Args.insert(Args.begin() + 1, AlignArg);
2313  AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2314  R.getNameLoc(), IsAligned);
2315  Args.erase(Args.begin() + 1);
2316  Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2317  IsUnaligned);
2318  } else {
2319  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2320  }
2321  }
2322  return true;
2323 
2324  case OR_Ambiguous:
2325  if (Diagnose) {
2326  S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2327  << R.getLookupName() << Range;
2328  Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2329  }
2330  return true;
2331 
2332  case OR_Deleted: {
2333  if (Diagnose) {
2334  S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2335  << Best->Function->isDeleted() << R.getLookupName()
2336  << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2337  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2338  }
2339  return true;
2340  }
2341  }
2342  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2343 }
2344 
2346  AllocationFunctionScope NewScope,
2347  AllocationFunctionScope DeleteScope,
2348  QualType AllocType, bool IsArray,
2349  bool &PassAlignment, MultiExprArg PlaceArgs,
2350  FunctionDecl *&OperatorNew,
2351  FunctionDecl *&OperatorDelete,
2352  bool Diagnose) {
2353  // --- Choosing an allocation function ---
2354  // C++ 5.3.4p8 - 14 & 18
2355  // 1) If looking in AFS_Global scope for allocation functions, only look in
2356  // the global scope. Else, if AFS_Class, only look in the scope of the
2357  // allocated class. If AFS_Both, look in both.
2358  // 2) If an array size is given, look for operator new[], else look for
2359  // operator new.
2360  // 3) The first argument is always size_t. Append the arguments from the
2361  // placement form.
2362 
2363  SmallVector<Expr*, 8> AllocArgs;
2364  AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2365 
2366  // We don't care about the actual value of these arguments.
2367  // FIXME: Should the Sema create the expression and embed it in the syntax
2368  // tree? Or should the consumer just recalculate the value?
2369  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2370  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2372  Context.getSizeType(),
2373  SourceLocation());
2374  AllocArgs.push_back(&Size);
2375 
2376  QualType AlignValT = Context.VoidTy;
2377  if (PassAlignment) {
2379  AlignValT = Context.getTypeDeclType(getStdAlignValT());
2380  }
2381  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2382  if (PassAlignment)
2383  AllocArgs.push_back(&Align);
2384 
2385  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2386 
2387  // C++ [expr.new]p8:
2388  // If the allocated type is a non-array type, the allocation
2389  // function's name is operator new and the deallocation function's
2390  // name is operator delete. If the allocated type is an array
2391  // type, the allocation function's name is operator new[] and the
2392  // deallocation function's name is operator delete[].
2394  IsArray ? OO_Array_New : OO_New);
2395 
2396  QualType AllocElemType = Context.getBaseElementType(AllocType);
2397 
2398  // Find the allocation function.
2399  {
2400  LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2401 
2402  // C++1z [expr.new]p9:
2403  // If the new-expression begins with a unary :: operator, the allocation
2404  // function's name is looked up in the global scope. Otherwise, if the
2405  // allocated type is a class type T or array thereof, the allocation
2406  // function's name is looked up in the scope of T.
2407  if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2408  LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2409 
2410  // We can see ambiguity here if the allocation function is found in
2411  // multiple base classes.
2412  if (R.isAmbiguous())
2413  return true;
2414 
2415  // If this lookup fails to find the name, or if the allocated type is not
2416  // a class type, the allocation function's name is looked up in the
2417  // global scope.
2418  if (R.empty()) {
2419  if (NewScope == AFS_Class)
2420  return true;
2421 
2423  }
2424 
2425  if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2426  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2427  return true;
2428  }
2429 
2430  assert(!R.empty() && "implicitly declared allocation functions not found");
2431  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2432 
2433  // We do our own custom access checks below.
2434  R.suppressDiagnostics();
2435 
2436  if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2437  OperatorNew, /*Candidates=*/nullptr,
2438  /*AlignArg=*/nullptr, Diagnose))
2439  return true;
2440  }
2441 
2442  // We don't need an operator delete if we're running under -fno-exceptions.
2443  if (!getLangOpts().Exceptions) {
2444  OperatorDelete = nullptr;
2445  return false;
2446  }
2447 
2448  // Note, the name of OperatorNew might have been changed from array to
2449  // non-array by resolveAllocationOverload.
2451  OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2452  ? OO_Array_Delete
2453  : OO_Delete);
2454 
2455  // C++ [expr.new]p19:
2456  //
2457  // If the new-expression begins with a unary :: operator, the
2458  // deallocation function's name is looked up in the global
2459  // scope. Otherwise, if the allocated type is a class type T or an
2460  // array thereof, the deallocation function's name is looked up in
2461  // the scope of T. If this lookup fails to find the name, or if
2462  // the allocated type is not a class type or array thereof, the
2463  // deallocation function's name is looked up in the global scope.
2464  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2465  if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2466  CXXRecordDecl *RD
2467  = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2468  LookupQualifiedName(FoundDelete, RD);
2469  }
2470  if (FoundDelete.isAmbiguous())
2471  return true; // FIXME: clean up expressions?
2472 
2473  bool FoundGlobalDelete = FoundDelete.empty();
2474  if (FoundDelete.empty()) {
2475  if (DeleteScope == AFS_Class)
2476  return true;
2477 
2480  }
2481 
2482  FoundDelete.suppressDiagnostics();
2483 
2485 
2486  // Whether we're looking for a placement operator delete is dictated
2487  // by whether we selected a placement operator new, not by whether
2488  // we had explicit placement arguments. This matters for things like
2489  // struct A { void *operator new(size_t, int = 0); ... };
2490  // A *a = new A()
2491  //
2492  // We don't have any definition for what a "placement allocation function"
2493  // is, but we assume it's any allocation function whose
2494  // parameter-declaration-clause is anything other than (size_t).
2495  //
2496  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2497  // This affects whether an exception from the constructor of an overaligned
2498  // type uses the sized or non-sized form of aligned operator delete.
2499  bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2500  OperatorNew->isVariadic();
2501 
2502  if (isPlacementNew) {
2503  // C++ [expr.new]p20:
2504  // A declaration of a placement deallocation function matches the
2505  // declaration of a placement allocation function if it has the
2506  // same number of parameters and, after parameter transformations
2507  // (8.3.5), all parameter types except the first are
2508  // identical. [...]
2509  //
2510  // To perform this comparison, we compute the function type that
2511  // the deallocation function should have, and use that type both
2512  // for template argument deduction and for comparison purposes.
2513  QualType ExpectedFunctionType;
2514  {
2515  const FunctionProtoType *Proto
2516  = OperatorNew->getType()->getAs<FunctionProtoType>();
2517 
2518  SmallVector<QualType, 4> ArgTypes;
2519  ArgTypes.push_back(Context.VoidPtrTy);
2520  for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2521  ArgTypes.push_back(Proto->getParamType(I));
2522 
2524  // FIXME: This is not part of the standard's rule.
2525  EPI.Variadic = Proto->isVariadic();
2526 
2527  ExpectedFunctionType
2528  = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2529  }
2530 
2531  for (LookupResult::iterator D = FoundDelete.begin(),
2532  DEnd = FoundDelete.end();
2533  D != DEnd; ++D) {
2534  FunctionDecl *Fn = nullptr;
2535  if (FunctionTemplateDecl *FnTmpl =
2536  dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2537  // Perform template argument deduction to try to match the
2538  // expected function type.
2539  TemplateDeductionInfo Info(StartLoc);
2540  if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2541  Info))
2542  continue;
2543  } else
2544  Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2545 
2547  ExpectedFunctionType,
2548  /*AdjustExcpetionSpec*/true),
2549  ExpectedFunctionType))
2550  Matches.push_back(std::make_pair(D.getPair(), Fn));
2551  }
2552 
2553  if (getLangOpts().CUDA)
2554  EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2555  } else {
2556  // C++1y [expr.new]p22:
2557  // For a non-placement allocation function, the normal deallocation
2558  // function lookup is used
2559  //
2560  // Per [expr.delete]p10, this lookup prefers a member operator delete
2561  // without a size_t argument, but prefers a non-member operator delete
2562  // with a size_t where possible (which it always is in this case).
2564  UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2565  *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2566  /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2567  &BestDeallocFns);
2568  if (Selected)
2569  Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2570  else {
2571  // If we failed to select an operator, all remaining functions are viable
2572  // but ambiguous.
2573  for (auto Fn : BestDeallocFns)
2574  Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2575  }
2576  }
2577 
2578  // C++ [expr.new]p20:
2579  // [...] If the lookup finds a single matching deallocation
2580  // function, that function will be called; otherwise, no
2581  // deallocation function will be called.
2582  if (Matches.size() == 1) {
2583  OperatorDelete = Matches[0].second;
2584 
2585  // C++1z [expr.new]p23:
2586  // If the lookup finds a usual deallocation function (3.7.4.2)
2587  // with a parameter of type std::size_t and that function, considered
2588  // as a placement deallocation function, would have been
2589  // selected as a match for the allocation function, the program
2590  // is ill-formed.
2591  if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2592  isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2593  UsualDeallocFnInfo Info(*this,
2594  DeclAccessPair::make(OperatorDelete, AS_public));
2595  // Core issue, per mail to core reflector, 2016-10-09:
2596  // If this is a member operator delete, and there is a corresponding
2597  // non-sized member operator delete, this isn't /really/ a sized
2598  // deallocation function, it just happens to have a size_t parameter.
2599  bool IsSizedDelete = Info.HasSizeT;
2600  if (IsSizedDelete && !FoundGlobalDelete) {
2601  auto NonSizedDelete =
2602  resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2603  /*WantAlign*/Info.HasAlignValT);
2604  if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2605  NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2606  IsSizedDelete = false;
2607  }
2608 
2609  if (IsSizedDelete) {
2610  SourceRange R = PlaceArgs.empty()
2611  ? SourceRange()
2612  : SourceRange(PlaceArgs.front()->getBeginLoc(),
2613  PlaceArgs.back()->getEndLoc());
2614  Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2615  if (!OperatorDelete->isImplicit())
2616  Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2617  << DeleteName;
2618  }
2619  }
2620 
2621  CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2622  Matches[0].first);
2623  } else if (!Matches.empty()) {
2624  // We found multiple suitable operators. Per [expr.new]p20, that means we
2625  // call no 'operator delete' function, but we should at least warn the user.
2626  // FIXME: Suppress this warning if the construction cannot throw.
2627  Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2628  << DeleteName << AllocElemType;
2629 
2630  for (auto &Match : Matches)
2631  Diag(Match.second->getLocation(),
2632  diag::note_member_declared_here) << DeleteName;
2633  }
2634 
2635  return false;
2636 }
2637 
2638 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2639 /// delete. These are:
2640 /// @code
2641 /// // C++03:
2642 /// void* operator new(std::size_t) throw(std::bad_alloc);
2643 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2644 /// void operator delete(void *) throw();
2645 /// void operator delete[](void *) throw();
2646 /// // C++11:
2647 /// void* operator new(std::size_t);
2648 /// void* operator new[](std::size_t);
2649 /// void operator delete(void *) noexcept;
2650 /// void operator delete[](void *) noexcept;
2651 /// // C++1y:
2652 /// void* operator new(std::size_t);
2653 /// void* operator new[](std::size_t);
2654 /// void operator delete(void *) noexcept;
2655 /// void operator delete[](void *) noexcept;
2656 /// void operator delete(void *, std::size_t) noexcept;
2657 /// void operator delete[](void *, std::size_t) noexcept;
2658 /// @endcode
2659 /// Note that the placement and nothrow forms of new are *not* implicitly
2660 /// declared. Their use requires including <new>.
2663  return;
2664 
2665  // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2666  // are not supported.
2667  if (getLangOpts().OpenCLCPlusPlus)
2668  return;
2669 
2670  // C++ [basic.std.dynamic]p2:
2671  // [...] The following allocation and deallocation functions (18.4) are
2672  // implicitly declared in global scope in each translation unit of a
2673  // program
2674  //
2675  // C++03:
2676  // void* operator new(std::size_t) throw(std::bad_alloc);
2677  // void* operator new[](std::size_t) throw(std::bad_alloc);
2678  // void operator delete(void*) throw();
2679  // void operator delete[](void*) throw();
2680  // C++11:
2681  // void* operator new(std::size_t);
2682  // void* operator new[](std::size_t);
2683  // void operator delete(void*) noexcept;
2684  // void operator delete[](void*) noexcept;
2685  // C++1y:
2686  // void* operator new(std::size_t);
2687  // void* operator new[](std::size_t);
2688  // void operator delete(void*) noexcept;
2689  // void operator delete[](void*) noexcept;
2690  // void operator delete(void*, std::size_t) noexcept;
2691  // void operator delete[](void*, std::size_t) noexcept;
2692  //
2693  // These implicit declarations introduce only the function names operator
2694  // new, operator new[], operator delete, operator delete[].
2695  //
2696  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2697  // "std" or "bad_alloc" as necessary to form the exception specification.
2698  // However, we do not make these implicit declarations visible to name
2699  // lookup.
2700  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2701  // The "std::bad_alloc" class has not yet been declared, so build it
2702  // implicitly.
2706  &PP.getIdentifierTable().get("bad_alloc"),
2707  nullptr);
2708  getStdBadAlloc()->setImplicit(true);
2709  }
2710  if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2711  // The "std::align_val_t" enum class has not yet been declared, so build it
2712  // implicitly.
2713  auto *AlignValT = EnumDecl::Create(
2715  &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2716  AlignValT->setIntegerType(Context.getSizeType());
2717  AlignValT->setPromotionType(Context.getSizeType());
2718  AlignValT->setImplicit(true);
2719  StdAlignValT = AlignValT;
2720  }
2721 
2722  GlobalNewDeleteDeclared = true;
2723 
2725  QualType SizeT = Context.getSizeType();
2726 
2727  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2728  QualType Return, QualType Param) {
2730  Params.push_back(Param);
2731 
2732  // Create up to four variants of the function (sized/aligned).
2733  bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2734  (Kind == OO_Delete || Kind == OO_Array_Delete);
2735  bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2736 
2737  int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2738  int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2739  for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2740  if (Sized)
2741  Params.push_back(SizeT);
2742 
2743  for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2744  if (Aligned)
2745  Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2746 
2748  Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2749 
2750  if (Aligned)
2751  Params.pop_back();
2752  }
2753  }
2754  };
2755 
2756  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2757  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2758  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2759  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2760 }
2761 
2762 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2763 /// allocation function if it doesn't already exist.
2765  QualType Return,
2766  ArrayRef<QualType> Params) {
2768 
2769  // Check if this function is already declared.
2770  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2771  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2772  Alloc != AllocEnd; ++Alloc) {
2773  // Only look at non-template functions, as it is the predefined,
2774  // non-templated allocation function we are trying to declare here.
2775  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2776  if (Func->getNumParams() == Params.size()) {
2777  llvm::SmallVector<QualType, 3> FuncParams;
2778  for (auto *P : Func->parameters())
2779  FuncParams.push_back(
2780  Context.getCanonicalType(P->getType().getUnqualifiedType()));
2781  if (llvm::makeArrayRef(FuncParams) == Params) {
2782  // Make the function visible to name lookup, even if we found it in
2783  // an unimported module. It either is an implicitly-declared global
2784  // allocation function, or is suppressing that function.
2785  Func->setVisibleDespiteOwningModule();
2786  return;
2787  }
2788  }
2789  }
2790  }
2791 
2793 
2794  QualType BadAllocType;
2795  bool HasBadAllocExceptionSpec
2796  = (Name.getCXXOverloadedOperator() == OO_New ||
2797  Name.getCXXOverloadedOperator() == OO_Array_New);
2798  if (HasBadAllocExceptionSpec) {
2799  if (!getLangOpts().CPlusPlus11) {
2800  BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2801  assert(StdBadAlloc && "Must have std::bad_alloc declared");
2803  EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2804  }
2805  } else {
2806  EPI.ExceptionSpec =
2807  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2808  }
2809 
2810  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2811  QualType FnType = Context.getFunctionType(Return, Params, EPI);
2813  Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2814  FnType, /*TInfo=*/nullptr, SC_None, false, true);
2815  Alloc->setImplicit();
2816  // Global allocation functions should always be visible.
2818 
2819  // Implicit sized deallocation functions always have default visibility.
2820  Alloc->addAttr(
2821  VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
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 = ToType->isReferenceType() ?
4275  From->getValueKind() : VK_RValue;
4276  From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
4277  CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
4278 
4280  !getLangOpts().WritableStrings) {
4281  Diag(From->getBeginLoc(),
4282  getLangOpts().CPlusPlus11
4283  ? diag::ext_deprecated_string_literal_conversion
4284  : diag::warn_deprecated_string_literal_conversion)
4285  << ToType.getNonReferenceType();
4286  }
4287 
4288  break;
4289  }
4290 
4291  default:
4292  llvm_unreachable("Improper third standard conversion");
4293  }
4294 
4295  // If this conversion sequence involved a scalar -> atomic conversion, perform
4296  // that conversion now.
4297  if (!ToAtomicType.isNull()) {
4298  assert(Context.hasSameType(
4299  ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4300  From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4301  VK_RValue, nullptr, CCK).get();
4302  }
4303 
4304  // If this conversion sequence succeeded and involved implicitly converting a
4305  // _Nullable type to a _Nonnull one, complain.
4306  if (!isCast(CCK))
4307  diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4308  From->getBeginLoc());
4309 
4310  return From;
4311 }
4312 
4313 /// Check the completeness of a type in a unary type trait.
4314 ///
4315 /// If the particular type trait requires a complete type, tries to complete
4316 /// it. If completing the type fails, a diagnostic is emitted and false
4317 /// returned. If completing the type succeeds or no completion was required,
4318 /// returns true.
4320  SourceLocation Loc,
4321  QualType ArgTy) {
4322  // C++0x [meta.unary.prop]p3:
4323  // For all of the class templates X declared in this Clause, instantiating
4324  // that template with a template argument that is a class template
4325  // specialization may result in the implicit instantiation of the template
4326  // argument if and only if the semantics of X require that the argument
4327  // must be a complete type.
4328  // We apply this rule to all the type trait expressions used to implement
4329  // these class templates. We also try to follow any GCC documented behavior
4330  // in these expressions to ensure portability of standard libraries.
4331  switch (UTT) {
4332  default: llvm_unreachable("not a UTT");
4333  // is_complete_type somewhat obviously cannot require a complete type.
4334  case UTT_IsCompleteType:
4335  // Fall-through
4336 
4337  // These traits are modeled on the type predicates in C++0x
4338  // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4339  // requiring a complete type, as whether or not they return true cannot be
4340  // impacted by the completeness of the type.
4341  case UTT_IsVoid:
4342  case UTT_IsIntegral:
4343  case UTT_IsFloatingPoint:
4344  case UTT_IsArray:
4345  case UTT_IsPointer:
4346  case UTT_IsLvalueReference:
4347  case UTT_IsRvalueReference:
4350  case UTT_IsEnum:
4351  case UTT_IsUnion:
4352  case UTT_IsClass:
4353  case UTT_IsFunction:
4354  case UTT_IsReference:
4355  case UTT_IsArithmetic:
4356  case UTT_IsFundamental:
4357  case UTT_IsObject:
4358  case UTT_IsScalar:
4359  case UTT_IsCompound:
4360  case UTT_IsMemberPointer:
4361  // Fall-through
4362 
4363  // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4364  // which requires some of its traits to have the complete type. However,
4365  // the completeness of the type cannot impact these traits' semantics, and
4366  // so they don't require it. This matches the comments on these traits in
4367  // Table 49.
4368  case UTT_IsConst:
4369  case UTT_IsVolatile:
4370  case UTT_IsSigned:
4371  case UTT_IsUnsigned:
4372 
4373  // This type trait always returns false, checking the type is moot.
4374  case UTT_IsInterfaceClass:
4375  return true;
4376 
4377  // C++14 [meta.unary.prop]:
4378  // If T is a non-union class type, T shall be a complete type.
4379  case UTT_IsEmpty:
4380  case UTT_IsPolymorphic:
4381  case UTT_IsAbstract:
4382  if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4383  if (!RD->isUnion())
4384  return !S.RequireCompleteType(
4385  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4386  return true;
4387 
4388  // C++14 [meta.unary.prop]:
4389  // If T is a class type, T shall be a complete type.
4390  case UTT_IsFinal:
4391  case UTT_IsSealed:
4392  if (ArgTy->getAsCXXRecordDecl())
4393  return !S.RequireCompleteType(
4394  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4395  return true;
4396 
4397  // C++1z [meta.unary.prop]:
4398  // remove_all_extents_t<T> shall be a complete type or cv void.
4399  case UTT_IsAggregate:
4400  case UTT_IsTrivial:
4402  case UTT_IsStandardLayout:
4403  case UTT_IsPOD:
4404  case UTT_IsLiteral:
4405  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4406  // or an array of unknown bound. But GCC actually imposes the same constraints
4407  // as above.
4408  case UTT_HasNothrowAssign:
4411  case UTT_HasNothrowCopy:
4412  case UTT_HasTrivialAssign:
4416  case UTT_HasTrivialCopy:
4419  ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4420  LLVM_FALLTHROUGH;
4421 
4422  // C++1z [meta.unary.prop]:
4423  // T shall be a complete type, cv void, or an array of unknown bound.
4424  case UTT_IsDestructible:
4428  if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4429  return true;
4430 
4431  return !S.RequireCompleteType(
4432  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4433  }
4434 }
4435 
4437  Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4438  bool (CXXRecordDecl::*HasTrivial)() const,
4439  bool (CXXRecordDecl::*HasNonTrivial)() const,
4440  bool (CXXMethodDecl::*IsDesiredOp)() const)
4441 {
4442  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4443  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4444  return true;
4445 
4447  DeclarationNameInfo NameInfo(Name, KeyLoc);
4448  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4449  if (Self.LookupQualifiedName(Res, RD)) {
4450  bool FoundOperator = false;
4451  Res.suppressDiagnostics();
4452  for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4453  Op != OpEnd; ++Op) {
4454  if (isa<FunctionTemplateDecl>(*Op))
4455  continue;
4456 
4457  CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4458  if((Operator->*IsDesiredOp)()) {
4459  FoundOperator = true;
4460  const FunctionProtoType *CPT =
4461  Operator->getType()->getAs<FunctionProtoType>();
4462  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4463  if (!CPT || !CPT->isNothrow())
4464  return false;
4465  }
4466  }
4467  return FoundOperator;
4468  }
4469  return false;
4470 }
4471 
4472 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4473  SourceLocation KeyLoc, QualType T) {
4474  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4475 
4476  ASTContext &C = Self.Context;
4477  switch(UTT) {
4478  default: llvm_unreachable("not a UTT");
4479  // Type trait expressions corresponding to the primary type category
4480  // predicates in C++0x [meta.unary.cat].
4481  case UTT_IsVoid:
4482  return T->isVoidType();
4483  case UTT_IsIntegral:
4484  return T->isIntegralType(C);
4485  case UTT_IsFloatingPoint:
4486  return T->isFloatingType();
4487  case UTT_IsArray:
4488  return T->isArrayType();
4489  case UTT_IsPointer:
4490  return T->isPointerType();
4491  case UTT_IsLvalueReference:
4492  return T->isLValueReferenceType();
4493  case UTT_IsRvalueReference:
4494  return T->isRValueReferenceType();
4496  return T->isMemberFunctionPointerType();
4498  return T->isMemberDataPointerType();
4499  case UTT_IsEnum:
4500  return T->isEnumeralType();
4501  case UTT_IsUnion:
4502  return T->isUnionType();
4503  case UTT_IsClass:
4504  return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4505  case UTT_IsFunction:
4506  return T->isFunctionType();
4507 
4508  // Type trait expressions which correspond to the convenient composition
4509  // predicates in C++0x [meta.unary.comp].
4510  case UTT_IsReference:
4511  return T->isReferenceType();
4512  case UTT_IsArithmetic:
4513  return T->isArithmeticType() && !T->isEnumeralType();
4514  case UTT_IsFundamental:
4515  return T->isFundamentalType();
4516  case UTT_IsObject:
4517  return T->isObjectType();
4518  case UTT_IsScalar:
4519  // Note: semantic analysis depends on Objective-C lifetime types to be
4520  // considered scalar types. However, such types do not actually behave
4521  // like scalar types at run time (since they may require retain/release
4522  // operations), so we report them as non-scalar.
4523  if (T->isObjCLifetimeType()) {
4524  switch (T.getObjCLifetime()) {
4525  case Qualifiers::OCL_None:
4527  return true;
4528 
4530  case Qualifiers::OCL_Weak:
4532  return false;
4533  }
4534  }
4535 
4536  return T->isScalarType();
4537  case UTT_IsCompound:
4538  return T->isCompoundType();
4539  case UTT_IsMemberPointer:
4540  return T->isMemberPointerType();
4541 
4542  // Type trait expressions which correspond to the type property predicates
4543  // in C++0x [meta.unary.prop].
4544  case UTT_IsConst:
4545  return T.isConstQualified();
4546  case UTT_IsVolatile:
4547  return T.isVolatileQualified();
4548  case UTT_IsTrivial:
4549  return T.isTrivialType(C);
4551  return T.isTriviallyCopyableType(C);
4552  case UTT_IsStandardLayout:
4553  return T->isStandardLayoutType();
4554  case UTT_IsPOD:
4555  return T.isPODType(C);
4556  case UTT_IsLiteral:
4557  return T->isLiteralType(C);
4558  case UTT_IsEmpty:
4559  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4560  return !RD->isUnion() && RD->isEmpty();
4561  return false;
4562  case UTT_IsPolymorphic:
4563  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4564  return !RD->isUnion() && RD->isPolymorphic();
4565  return false;
4566  case UTT_IsAbstract:
4567  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4568  return !RD->isUnion() && RD->isAbstract();
4569  return false;
4570  case UTT_IsAggregate:
4571  // Report vector extensions and complex types as aggregates because they
4572  // support aggregate initialization. GCC mirrors this behavior for vectors
4573  // but not _Complex.
4574  return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4575  T->isAnyComplexType();
4576  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4577  // even then only when it is used with the 'interface struct ...' syntax
4578  // Clang doesn't support /CLR which makes this type trait moot.
4579  case UTT_IsInterfaceClass:
4580  return false;
4581  case UTT_IsFinal:
4582  case UTT_IsSealed:
4583  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4584  return RD->hasAttr<FinalAttr>();
4585  return false;
4586  case UTT_IsSigned:
4587  return T->isSignedIntegerType();
4588  case UTT_IsUnsigned:
4589  return T->isUnsignedIntegerType();
4590 
4591  // Type trait expressions which query classes regarding their construction,
4592  // destruction, and copying. Rather than being based directly on the
4593  // related type predicates in the standard, they are specified by both
4594  // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4595  // specifications.
4596  //
4597  // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4598  // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4599  //
4600  // Note that these builtins do not behave as documented in g++: if a class
4601  // has both a trivial and a non-trivial special member of a particular kind,
4602  // they return false! For now, we emulate this behavior.
4603  // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4604  // does not correctly compute triviality in the presence of multiple special
4605  // members of the same kind. Revisit this once the g++ bug is fixed.
4607  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4608  // If __is_pod (type) is true then the trait is true, else if type is
4609  // a cv class or union type (or array thereof) with a trivial default
4610  // constructor ([class.ctor]) then the trait is true, else it is false.
4611  if (T.isPODType(C))
4612  return true;
4613  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4614  return RD->hasTrivialDefaultConstructor() &&
4615  !RD->hasNonTrivialDefaultConstructor();
4616  return false;
4618  // This trait is implemented by MSVC 2012 and needed to parse the
4619  // standard library headers. Specifically this is used as the logic
4620  // behind std::is_trivially_move_constructible (20.9.4.3).
4621  if (T.isPODType(C))
4622  return true;
4623  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4624  return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4625  return false;
4626  case UTT_HasTrivialCopy:
4627  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4628  // If __is_pod (type) is true or type is a reference type then
4629  // the trait is true, else if type is a cv class or union type
4630  // with a trivial copy constructor ([class.copy]) then the trait
4631  // is true, else it is false.
4632  if (T.isPODType(C) || T->isReferenceType())
4633  return true;
4634  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4635  return RD->hasTrivialCopyConstructor() &&
4636  !RD->hasNonTrivialCopyConstructor();
4637  return false;
4639  // This trait is implemented by MSVC 2012 and needed to parse the
4640  // standard library headers. Specifically it is used as the logic
4641  // behind std::is_trivially_move_assignable (20.9.4.3)
4642  if (T.isPODType(C))
4643  return true;
4644  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4645  return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4646  return false;
4647  case UTT_HasTrivialAssign:
4648  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4649  // If type is const qualified or is a reference type then the
4650  // trait is false. Otherwise if __is_pod (type) is true then the
4651  // trait is true, else if type is a cv class or union type with
4652  // a trivial copy assignment ([class.copy]) then the trait is
4653  // true, else it is false.
4654  // Note: the const and reference restrictions are interesting,
4655  // given that const and reference members don't prevent a class
4656  // from having a trivial copy assignment operator (but do cause
4657  // errors if the copy assignment operator is actually used, q.v.
4658  // [class.copy]p12).
4659 
4660  if (T.isConstQualified())
4661  return false;
4662  if (T.isPODType(C))
4663  return true;
4664  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4665  return RD->hasTrivialCopyAssignment() &&
4666  !RD->hasNonTrivialCopyAssignment();
4667  return false;
4668  case UTT_IsDestructible:
4671  // C++14 [meta.unary.prop]:
4672  // For reference types, is_destructible<T>::value is true.
4673  if (T->isReferenceType())
4674  return true;
4675 
4676  // Objective-C++ ARC: autorelease types don't require destruction.
4677  if (T->isObjCLifetimeType() &&
4679  return true;
4680 
4681  // C++14 [meta.unary.prop]:
4682  // For incomplete types and function types, is_destructible<T>::value is
4683  // false.
4684  if (T->isIncompleteType() || T->isFunctionType())
4685  return false;
4686 
4687  // A type that requires destruction (via a non-trivial destructor or ARC
4688  // lifetime semantics) is not trivially-destructible.
4690  return false;
4691 
4692  // C++14 [meta.unary.prop]:
4693  // For object types and given U equal to remove_all_extents_t<T>, if the
4694  // expression std::declval<U&>().~U() is well-formed when treated as an
4695  // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4696  if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4697  CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4698  if (!Destructor)
4699  return false;
4700  // C++14 [dcl.fct.def.delete]p2:
4701  // A program that refers to a deleted function implicitly or
4702  // explicitly, other than to declare it, is ill-formed.
4703  if (Destructor->isDeleted())
4704  return false;
4705  if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4706  return false;
4707  if (UTT == UTT_IsNothrowDestructible) {
4708  const FunctionProtoType *CPT =
4709  Destructor->getType()->getAs<FunctionProtoType>();
4710  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4711  if (!CPT || !CPT->isNothrow())
4712  return false;
4713  }
4714  }
4715  return true;
4716 
4718  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4719  // If __is_pod (type) is true or type is a reference type
4720  // then the trait is true, else if type is a cv class or union
4721  // type (or array thereof) with a trivial destructor
4722  // ([class.dtor]) then the trait is true, else it is
4723  // false.
4724  if (T.isPODType(C) || T->isReferenceType())
4725  return true;
4726 
4727  // Objective-C++ ARC: autorelease types don't require destruction.
4728  if (T->isObjCLifetimeType() &&
4730  return true;
4731 
4732  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4733  return RD->hasTrivialDestructor();
4734  return false;
4735  // TODO: Propagate nothrowness for implicitly declared special members.
4736  case UTT_HasNothrowAssign:
4737  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4738  // If type is const qualified or is a reference type then the
4739  // trait is false. Otherwise if __has_trivial_assign (type)
4740  // is true then the trait is true, else if type is a cv class
4741  // or union type with copy assignment operators that are known
4742  // not to throw an exception then the trait is true, else it is
4743  // false.
4744  if (C.getBaseElementType(T).isConstQualified())
4745  return false;
4746  if (T->isReferenceType())
4747  return false;
4748  if (T.isPODType(C) || T->isObjCLifetimeType())
4749  return true;
4750 
4751  if (const RecordType *RT = T->getAs<RecordType>())
4752  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4756  return false;
4758  // This trait is implemented by MSVC 2012 and needed to parse the
4759  // standard library headers. Specifically this is used as the logic
4760  // behind std::is_nothrow_move_assignable (20.9.4.3).
4761  if (T.isPODType(C))
4762  return true;
4763 
4764  if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4765  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4769  return false;
4770  case UTT_HasNothrowCopy:
4771  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4772  // If __has_trivial_copy (type) is true then the trait is true, else
4773  // if type is a cv class or union type with copy constructors that are
4774  // known not to throw an exception then the trait is true, else it is
4775  // false.
4776  if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4777  return true;
4778  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4779  if (RD->hasTrivialCopyConstructor() &&
4780  !RD->hasNonTrivialCopyConstructor())
4781  return true;
4782 
4783  bool FoundConstructor = false;
4784  unsigned FoundTQs;
4785  for (const auto *ND : Self.LookupConstructors(RD)) {
4786  // A template constructor is never a copy constructor.
4787  // FIXME: However, it may actually be selected at the actual overload
4788  // resolution point.
4789  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4790  continue;
4791  // UsingDecl itself is not a constructor
4792  if (isa<UsingDecl>(ND))
4793  continue;
4794  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4795  if (Constructor->isCopyConstructor(FoundTQs)) {
4796  FoundConstructor = true;
4797  const FunctionProtoType *CPT
4798  = Constructor->getType()->getAs<FunctionProtoType>();
4799  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4800  if (!CPT)
4801  return false;
4802  // TODO: check whether evaluating default arguments can throw.
4803  // For now, we'll be conservative and assume that they can throw.
4804  if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4805  return false;
4806  }
4807  }
4808 
4809  return FoundConstructor;
4810  }
4811  return false;
4813  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4814  // If __has_trivial_constructor (type) is true then the trait is
4815  // true, else if type is a cv class or union type (or array
4816  // thereof) with a default constructor that is known not to
4817  // throw an exception then the trait is true, else it is false.
4818  if (T.isPODType(C) || T->isObjCLifetimeType())
4819  return true;
4820  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4821  if (RD->hasTrivialDefaultConstructor() &&
4822  !RD->hasNonTrivialDefaultConstructor())
4823  return true;
4824 
4825  bool FoundConstructor = false;
4826  for (const auto *ND : Self.LookupConstructors(RD)) {
4827  // FIXME: In C++0x, a constructor template can be a default constructor.
4828  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4829  continue;
4830  // UsingDecl itself is not a constructor
4831  if (isa<UsingDecl>(ND))
4832  continue;
4833  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4834  if (Constructor->isDefaultConstructor()) {
4835  FoundConstructor = true;
4836  const FunctionProtoType *CPT
4837  = Constructor->getType()->getAs<FunctionProtoType>();
4838  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4839  if (!CPT)
4840  return false;
4841  // FIXME: check whether evaluating default arguments can throw.
4842  // For now, we'll be conservative and assume that they can throw.
4843  if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4844  return false;
4845  }
4846  }
4847  return FoundConstructor;
4848  }
4849  return false;
4851  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4852  // If type is a class type with a virtual destructor ([class.dtor])
4853  // then the trait is true, else it is false.
4854  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4855  if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4856  return Destructor->isVirtual();
4857  return false;
4858 
4859  // These type trait expressions are modeled on the specifications for the
4860  // Embarcadero C++0x type trait functions:
4861  // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4862  case UTT_IsCompleteType:
4863  // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4864  // Returns True if and only if T is a complete type at the point of the
4865  // function call.
4866  return !T->isIncompleteType();
4868  return C.hasUniqueObjectRepresentations(T);
4869  }
4870 }
4871 
4872 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4873  QualType RhsT, SourceLocation KeyLoc);
4874 
4877  SourceLocation RParenLoc) {
4878  if (Kind <= UTT_Last)
4879  return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4880 
4881  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4882  // traits to avoid duplication.
4883  if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4884  return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4885  Args[1]->getType(), RParenLoc);
4886 
4887  switch (Kind) {
4892  // C++11 [meta.unary.prop]:
4893  // is_trivially_constructible is defined as:
4894  //
4895  // is_constructible<T, Args...>::value is true and the variable
4896  // definition for is_constructible, as defined below, is known to call
4897  // no operation that is not trivial.
4898  //
4899  // The predicate condition for a template specialization
4900  // is_constructible<T, Args...> shall be satisfied if and only if the
4901  // following variable definition would be well-formed for some invented
4902  // variable t:
4903  //
4904  // T t(create<Args>()...);
4905  assert(!Args.empty());
4906 
4907  // Precondition: T and all types in the parameter pack Args shall be
4908  // complete types, (possibly cv-qualified) void, or arrays of
4909  // unknown bound.
4910  for (const auto *TSI : Args) {
4911  QualType ArgTy = TSI->getType();
4912  if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4913  continue;
4914 
4915  if (S.RequireCompleteType(KWLoc, ArgTy,
4916  diag::err_incomplete_type_used_in_type_trait_expr))
4917  return false;
4918  }
4919 
4920  // Make sure the first argument is not incomplete nor a function type.
4921  QualType T = Args[0]->getType();
4922  if (T->isIncompleteType() || T->isFunctionType())
4923  return false;
4924 
4925  // Make sure the first argument is not an abstract type.
4926  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4927  if (RD && RD->isAbstract())
4928  return false;
4929 
4930  SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4931  SmallVector<Expr *, 2> ArgExprs;
4932  ArgExprs.reserve(Args.size() - 1);
4933  for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4934  QualType ArgTy = Args[I]->getType();
4935  if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4936  ArgTy = S.Context.getRValueReferenceType(ArgTy);
4937  OpaqueArgExprs.push_back(
4938  OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4939  ArgTy.getNonLValueExprType(S.Context),
4940  Expr::getValueKindForType(ArgTy)));
4941  }
4942  for (Expr &E : OpaqueArgExprs)
4943  ArgExprs.push_back(&E);
4944 
4945  // Perform the initialization in an unevaluated context within a SFINAE
4946  // trap at translation unit scope.
4949  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4953  RParenLoc));
4954  InitializationSequence Init(S, To, InitKind, ArgExprs);
4955  if (Init.Failed())
4956  return false;
4957 
4958  ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4959  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4960  return false;
4961 
4962  if (Kind == clang::TT_IsConstructible)
4963  return true;
4964 
4966  if (!T->isReferenceType())
4967  return false;
4968 
4969  return !Init.isDirectReferenceBinding();
4970  }
4971 
4973  return S.canThrow(Result.get()) == CT_Cannot;
4974 
4975  if (Kind == clang::TT_IsTriviallyConstructible) {
4976  // Under Objective-C ARC and Weak, if the destination has non-trivial
4977  // Objective-C lifetime, this is a non-trivial construction.
4979  return false;
4980 
4981  // The initialization succeeded; now make sure there are no non-trivial
4982  // calls.
4983  return !Result.get()->hasNonTrivialCall(S.Context);
4984  }
4985 
4986  llvm_unreachable("unhandled type trait");
4987  return false;
4988  }
4989  default: llvm_unreachable("not a TT");
4990  }
4991 
4992  return false;
4993 }
4994 
4997  SourceLocation RParenLoc) {
4998  QualType ResultType = Context.getLogicalOperationType();
4999 
5001  *this, Kind, KWLoc, Args[0]->getType()))
5002  return ExprError();
5003 
5004  bool Dependent = false;
5005  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5006  if (Args[I]->getType()->isDependentType()) {
5007  Dependent = true;
5008  break;
5009  }
5010  }
5011 
5012  bool Result = false;
5013  if (!Dependent)
5014  Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5015 
5016  return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5017  RParenLoc, Result);
5018 }
5019 
5021  ArrayRef<ParsedType> Args,
5022  SourceLocation RParenLoc) {
5023  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5024  ConvertedArgs.reserve(Args.size());
5025 
5026  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5027  TypeSourceInfo *TInfo;
5028  QualType T = GetTypeFromParser(Args[I], &TInfo);
5029  if (!TInfo)
5030  TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5031 
5032  ConvertedArgs.push_back(TInfo);
5033  }
5034 
5035  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5036 }
5037 
5038 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5039  QualType RhsT, SourceLocation KeyLoc) {
5040  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5041  "Cannot evaluate traits of dependent types");
5042 
5043  switch(BTT) {
5044  case BTT_IsBaseOf: {
5045  // C++0x [meta.rel]p2
5046  // Base is a base class of Derived without regard to cv-qualifiers or
5047  // Base and Derived are not unions and name the same class type without
5048  // regard to cv-qualifiers.
5049 
5050  const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5051  const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5052  if (!rhsRecord || !lhsRecord) {
5053  const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5054  const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5055  if (!LHSObjTy || !RHSObjTy)
5056  return false;
5057 
5058  ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5059  ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5060  if (!BaseInterface || !DerivedInterface)
5061  return false;
5062 
5063  if (Self.RequireCompleteType(
5064  KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5065  return false;
5066 
5067  return BaseInterface->isSuperClassOf(DerivedInterface);
5068  }
5069 
5070  assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5071  == (lhsRecord == rhsRecord));
5072 
5073  if (lhsRecord == rhsRecord)
5074  return !lhsRecord->getDecl()->isUnion();
5075 
5076  // C++0x [meta.rel]p2:
5077  // If Base and Derived are class types and are different types
5078  // (ignoring possible cv-qualifiers) then Derived shall be a
5079  // complete type.
5080  if (Self.RequireCompleteType(KeyLoc, RhsT,
5081  diag::err_incomplete_type_used_in_type_trait_expr))
5082  return false;
5083 
5084  return cast<CXXRecordDecl>(rhsRecord->getDecl())
5085  ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5086  }
5087  case BTT_IsSame:
5088  return Self.Context.hasSameType(LhsT, RhsT);
5089  case BTT_TypeCompatible: {
5090  // GCC ignores cv-qualifiers on arrays for this builtin.
5091  Qualifiers LhsQuals, RhsQuals;
5092  QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5093  QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5094  return Self.Context.typesAreCompatible(Lhs, Rhs);
5095  }
5096  case BTT_IsConvertible:
5097  case BTT_IsConvertibleTo: {
5098  // C++0x [meta.rel]p4:
5099  // Given the following function prototype:
5100  //
5101  // template <class T>
5102  // typename add_rvalue_reference<T>::type create();
5103  //
5104  // the predicate condition for a template specialization
5105  // is_convertible<From, To> shall be satisfied if and only if
5106  // the return expression in the following code would be
5107  // well-formed, including any implicit conversions to the return
5108  // type of the function:
5109  //
5110  // To test() {
5111  // return create<From>();
5112  // }
5113  //
5114  // Access checking is performed as if in a context unrelated to To and
5115  // From. Only the validity of the immediate context of the expression
5116  // of the return-statement (including conversions to the return type)
5117  // is considered.
5118  //
5119  // We model the initialization as a copy-initialization of a temporary
5120  // of the appropriate type, which for this expression is identical to the
5121  // return statement (since NRVO doesn't apply).
5122 
5123  // Functions aren't allowed to return function or array types.
5124  if (RhsT->isFunctionType() || RhsT->isArrayType())
5125  return false;
5126 
5127  // A return statement in a void function must have void type.
5128  if (RhsT->isVoidType())
5129  return LhsT->isVoidType();
5130 
5131  // A function definition requires a complete, non-abstract return type.
5132  if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5133  return false;
5134 
5135  // Compute the result of add_rvalue_reference.
5136  if (LhsT->isObjectType() || LhsT->isFunctionType())
5137  LhsT = Self.Context.getRValueReferenceType(LhsT);
5138 
5139  // Build a fake source and destination for initialization.
5141  OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5143  Expr *FromPtr = &From;
5145  SourceLocation()));
5146 
5147  // Perform the initialization in an unevaluated context within a SFINAE
5148  // trap at translation unit scope.
5151  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5152  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5153  InitializationSequence Init(Self, To, Kind, FromPtr);
5154  if (Init.Failed())
5155  return false;
5156 
5157  ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5158  return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5159  }
5160 
5161  case BTT_IsAssignable:
5164  // C++11 [meta.unary.prop]p3:
5165  // is_trivially_assignable is defined as:
5166  // is_assignable<T, U>::value is true and the assignment, as defined by
5167  // is_assignable, is known to call no operation that is not trivial
5168  //
5169  // is_assignable is defined as:
5170  // The expression declval<T>() = declval<U>() is well-formed when
5171  // treated as an unevaluated operand (Clause 5).
5172  //
5173  // For both, T and U shall be complete types, (possibly cv-qualified)
5174  // void, or arrays of unknown bound.
5175  if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5176  Self.RequireCompleteType(KeyLoc, LhsT,
5177  diag::err_incomplete_type_used_in_type_trait_expr))
5178  return false;
5179  if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5180  Self.RequireCompleteType(KeyLoc, RhsT,
5181  diag::err_incomplete_type_used_in_type_trait_expr))
5182  return false;
5183 
5184  // cv void is never assignable.
5185  if (LhsT->isVoidType() || RhsT->isVoidType())
5186  return false;
5187 
5188  // Build expressions that emulate the effect of declval<T>() and
5189  // declval<U>().
5190  if (LhsT->isObjectType() || LhsT->isFunctionType())
5191  LhsT = Self.Context.getRValueReferenceType(LhsT);
5192  if (RhsT->isObjectType() || RhsT->isFunctionType())
5193  RhsT = Self.Context.getRValueReferenceType(RhsT);
5194  OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5196  OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5198 
5199  // Attempt the assignment in an unevaluated context within a SFINAE
5200  // trap at translation unit scope.
5203  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5204  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5205  ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5206  &Rhs);
5207  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5208  return false;
5209 
5210  if (BTT == BTT_IsAssignable)
5211  return true;
5212 
5213  if (BTT == BTT_IsNothrowAssignable)
5214  return Self.canThrow(Result.get()) == CT_Cannot;
5215 
5216  if (BTT == BTT_IsTriviallyAssignable) {
5217  // Under Objective-C ARC and Weak, if the destination has non-trivial
5218  // Objective-C lifetime, this is a non-trivial assignment.
5220  return false;
5221 
5222  return !Result.get()->hasNonTrivialCall(Self.Context);
5223  }
5224 
5225  llvm_unreachable("unhandled type trait");
5226  return false;
5227  }
5228  default: llvm_unreachable("not a BTT");
5229  }
5230  llvm_unreachable("Unknown type trait or not implemented");
5231 }
5232 
5234  SourceLocation KWLoc,
5235  ParsedType Ty,
5236  Expr* DimExpr,
5237  SourceLocation RParen) {
5238  TypeSourceInfo *TSInfo;
5239  QualType T = GetTypeFromParser(Ty, &TSInfo);
5240  if (!TSInfo)
5241  TSInfo = Context.getTrivialTypeSourceInfo(T);
5242 
5243  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5244 }
5245 
5246 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5247  QualType T, Expr *DimExpr,
5248  SourceLocation KeyLoc) {
5249  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5250 
5251  switch(ATT) {
5252  case ATT_ArrayRank:
5253  if (T->isArrayType()) {
5254  unsigned Dim = 0;
5255  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5256  ++Dim;
5257  T = AT->getElementType();
5258  }
5259  return Dim;
5260  }
5261  return 0;
5262 
5263  case ATT_ArrayExtent: {
5264  llvm::APSInt Value;
5265  uint64_t Dim;
5266  if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5267  diag::err_dimension_expr_not_constant_integer,
5268  false).isInvalid())
5269  return 0;
5270  if (Value.isSigned() && Value.isNegative()) {
5271  Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5272  << DimExpr->getSourceRange();
5273  return 0;
5274  }
5275  Dim = Value.getLimitedValue();
5276 
5277  if (T->isArrayType()) {
5278  unsigned D = 0;
5279  bool Matched = false;
5280  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5281  if (Dim == D) {
5282  Matched = true;
5283  break;
5284  }
5285  ++D;
5286  T = AT->getElementType();
5287  }
5288 
5289  if (Matched && T->isArrayType()) {
5290  if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5291  return CAT->getSize().getLimitedValue();
5292  }
5293  }
5294  return 0;
5295  }
5296  }
5297  llvm_unreachable("Unknown type trait or not implemented");
5298 }
5299 
5301  SourceLocation KWLoc,
5302  TypeSourceInfo *TSInfo,
5303  Expr* DimExpr,
5304  SourceLocation RParen) {
5305  QualType T = TSInfo->getType();
5306 
5307  // FIXME: This should likely be tracked as an APInt to remove any host
5308  // assumptions about the width of size_t on the target.
5309  uint64_t Value = 0;
5310  if (!T->isDependentType())
5311  Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5312 
5313  // While the specification for these traits from the Embarcadero C++
5314  // compiler's documentation says the return type is 'unsigned int', Clang
5315  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5316  // compiler, there is no difference. On several other platforms this is an
5317  // important distinction.
5318  return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5319  RParen, Context.getSizeType());
5320 }
5321 
5323  SourceLocation KWLoc,
5324  Expr *Queried,
5325  SourceLocation RParen) {
5326  // If error parsing the expression, ignore.
5327  if (!Queried)
5328  return ExprError();
5329 
5330  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5331 
5332  return Result;
5333 }
5334 
5336  switch (ET) {
5337  case ET_IsLValueExpr: return E->isLValue();
5338  case ET_IsRValueExpr: return E->isRValue();
5339  }
5340  llvm_unreachable("Expression trait not covered by switch");
5341 }
5342 
5344  SourceLocation KWLoc,
5345  Expr *Queried,
5346  SourceLocation RParen) {
5347  if (Queried->isTypeDependent()) {
5348  // Delay type-checking for type-dependent expressions.
5349  } else if (Queried->getType()->isPlaceholderType()) {
5350  ExprResult PE = CheckPlaceholderExpr(Queried);
5351  if (PE.isInvalid()) return ExprError();
5352  return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5353  }
5354 
5355  bool Value = EvaluateExpressionTrait(ET, Queried);
5356 
5357  return new (Context)
5358  ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.