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