Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// \file
10
/// Implements semantic analysis for C++ expressions.
11
///
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Sema/Template.h"
15
#include "clang/Sema/SemaInternal.h"
16
#include "TreeTransform.h"
17
#include "TypeLocBuilder.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/ASTLambda.h"
20
#include "clang/AST/CXXInheritance.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"
25
#include "clang/AST/RecursiveASTVisitor.h"
26
#include "clang/AST/TypeLoc.h"
27
#include "clang/Basic/AlignedAllocation.h"
28
#include "clang/Basic/PartialDiagnostic.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "clang/Lex/Preprocessor.h"
31
#include "clang/Sema/DeclSpec.h"
32
#include "clang/Sema/Initialization.h"
33
#include "clang/Sema/Lookup.h"
34
#include "clang/Sema/ParsedTemplate.h"
35
#include "clang/Sema/Scope.h"
36
#include "clang/Sema/ScopeInfo.h"
37
#include "clang/Sema/SemaLambda.h"
38
#include "clang/Sema/TemplateDeduction.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.
49
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50
                                              SourceLocation NameLoc,
51
514
                                              IdentifierInfo &Name) {
52
514
  NestedNameSpecifier *NNS = SS.getScopeRep();
53
54
  // Convert the nested-name-specifier into a type.
55
514
  QualType Type;
56
514
  switch (NNS->getKind()) {
57
511
  case NestedNameSpecifier::TypeSpec:
58
512
  case NestedNameSpecifier::TypeSpecWithTemplate:
59
512
    Type = QualType(NNS->getAsType(), 0);
60
512
    break;
61
62
2
  case NestedNameSpecifier::Identifier:
63
    // Strip off the last layer of the nested-name-specifier and build a
64
    // typename type for it.
65
2
    assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66
0
    Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67
2
                                        NNS->getAsIdentifier());
68
2
    break;
69
70
0
  case NestedNameSpecifier::Global:
71
0
  case NestedNameSpecifier::Super:
72
0
  case NestedNameSpecifier::Namespace:
73
0
  case NestedNameSpecifier::NamespaceAlias:
74
0
    llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75
514
  }
76
77
  // This reference to the type is located entirely at the location of the
78
  // final identifier in the qualified-id.
79
514
  return CreateParsedType(Type,
80
514
                          Context.getTrivialTypeSourceInfo(Type, NameLoc));
81
514
}
82
83
ParsedType Sema::getConstructorName(IdentifierInfo &II,
84
                                    SourceLocation NameLoc,
85
                                    Scope *S, CXXScopeSpec &SS,
86
273k
                                    bool EnteringContext) {
87
273k
  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88
273k
  assert(CurClass && &II == CurClass->getIdentifier() &&
89
273k
         "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
273k
  if (CurClass->isDependentContext() && 
!EnteringContext186k
&&
SS.getScopeRep()3
) {
95
1
    QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96
1
    return ParsedType::make(T);
97
1
  }
98
99
273k
  if (SS.isNotEmpty() && 
RequireCompleteDeclContext(SS, CurClass)28.3k
)
100
0
    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
273k
  CXXRecordDecl *InjectedClassName = nullptr;
109
273k
  for (NamedDecl *ND : CurClass->lookup(&II)) {
110
273k
    auto *RD = dyn_cast<CXXRecordDecl>(ND);
111
273k
    if (RD && RD->isInjectedClassName()) {
112
273k
      InjectedClassName = RD;
113
273k
      break;
114
273k
    }
115
273k
  }
116
273k
  if (!InjectedClassName) {
117
2
    if (!CurClass->isInvalidDecl()) {
118
      // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119
      // properly. Work around it here for now.
120
1
      Diag(SS.getLastQualifierNameLoc(),
121
1
           diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122
1
    }
123
2
    return ParsedType();
124
2
  }
125
126
273k
  QualType T = Context.getTypeDeclType(InjectedClassName);
127
273k
  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128
273k
  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130
273k
  return ParsedType::make(T);
131
273k
}
132
133
ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
134
                                   IdentifierInfo &II,
135
                                   SourceLocation NameLoc,
136
                                   Scope *S, CXXScopeSpec &SS,
137
                                   ParsedType ObjectTypePtr,
138
42.6k
                                   bool EnteringContext) {
139
  // Determine where to perform name lookup.
140
141
  // FIXME: This area of the standard is very messy, and the current
142
  // wording is rather unclear about which scopes we search for the
143
  // destructor name; see core issues 399 and 555. Issue 399 in
144
  // particular shows where the current description of destructor name
145
  // lookup is completely out of line with existing practice, e.g.,
146
  // this appears to be ill-formed:
147
  //
148
  //   namespace N {
149
  //     template <typename T> struct S {
150
  //       ~S();
151
  //     };
152
  //   }
153
  //
154
  //   void f(N::S<int>* s) {
155
  //     s->N::S<int>::~S();
156
  //   }
157
  //
158
  // See also PR6358 and PR6359.
159
  //
160
  // For now, we accept all the cases in which the name given could plausibly
161
  // be interpreted as a correct destructor name, issuing off-by-default
162
  // extension diagnostics on the cases that don't strictly conform to the
163
  // C++20 rules. This basically means we always consider looking in the
164
  // nested-name-specifier prefix, the complete nested-name-specifier, and
165
  // the scope, and accept if we find the expected type in any of the three
166
  // places.
167
168
42.6k
  if (SS.isInvalid())
169
7
    return nullptr;
170
171
  // Whether we've failed with a diagnostic already.
172
42.6k
  bool Failed = false;
173
174
42.6k
  llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175
42.6k
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
177
  // If we have an object type, it's because we are in a
178
  // pseudo-destructor-expression or a member access expression, and
179
  // we know what type we're looking for.
180
42.6k
  QualType SearchType =
181
42.6k
      ObjectTypePtr ? 
GetTypeFromParser(ObjectTypePtr)291
:
QualType()42.3k
;
182
183
42.7k
  auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
184
85.2k
    auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
185
85.2k
      auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
186
85.2k
      if (!Type)
187
30
        return false;
188
189
85.2k
      if (SearchType.isNull() || 
SearchType->isDependentType()642
)
190
84.5k
        return true;
191
192
642
      QualType T = Context.getTypeDeclType(Type);
193
642
      return Context.hasSameUnqualifiedType(T, SearchType);
194
85.2k
    };
195
196
42.7k
    unsigned NumAcceptableResults = 0;
197
42.7k
    for (NamedDecl *D : Found) {
198
42.6k
      if (IsAcceptableResult(D))
199
42.5k
        ++NumAcceptableResults;
200
201
      // Don't list a class twice in the lookup failure diagnostic if it's
202
      // found by both its injected-class-name and by the name in the enclosing
203
      // scope.
204
42.6k
      if (auto *RD = dyn_cast<CXXRecordDecl>(D))
205
42.5k
        if (RD->isInjectedClassName())
206
42.1k
          D = cast<NamedDecl>(RD->getParent());
207
208
42.6k
      if (FoundDeclSet.insert(D).second)
209
42.6k
        FoundDecls.push_back(D);
210
42.6k
    }
211
212
    // As an extension, attempt to "fix" an ambiguity by erasing all non-type
213
    // results, and all non-matching results if we have a search type. It's not
214
    // clear what the right behavior is if destructor lookup hits an ambiguity,
215
    // but other compilers do generally accept at least some kinds of
216
    // ambiguity.
217
42.7k
    if (Found.isAmbiguous() && 
NumAcceptableResults == 16
) {
218
6
      Diag(NameLoc, diag::ext_dtor_name_ambiguous);
219
6
      LookupResult::Filter F = Found.makeFilter();
220
18
      while (F.hasNext()) {
221
12
        NamedDecl *D = F.next();
222
12
        if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
223
12
          Diag(D->getLocation(), diag::note_destructor_type_here)
224
12
              << Context.getTypeDeclType(TD);
225
0
        else
226
0
          Diag(D->getLocation(), diag::note_destructor_nontype_here);
227
228
12
        if (!IsAcceptableResult(D))
229
6
          F.erase();
230
12
      }
231
6
      F.done();
232
6
    }
233
234
42.7k
    if (Found.isAmbiguous())
235
0
      Failed = true;
236
237
42.7k
    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
238
42.6k
      if (IsAcceptableResult(Type)) {
239
42.5k
        QualType T = Context.getTypeDeclType(Type);
240
42.5k
        MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
241
42.5k
        return CreateParsedType(T,
242
42.5k
                                Context.getTrivialTypeSourceInfo(T, NameLoc));
243
42.5k
      }
244
42.6k
    }
245
246
173
    return nullptr;
247
42.7k
  };
248
249
42.6k
  bool IsDependent = false;
250
251
42.6k
  auto LookupInObjectType = [&]() -> ParsedType {
252
100
    if (Failed || SearchType.isNull())
253
29
      return nullptr;
254
255
71
    IsDependent |= SearchType->isDependentType();
256
257
71
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
258
71
    DeclContext *LookupCtx = computeDeclContext(SearchType);
259
71
    if (!LookupCtx)
260
1
      return nullptr;
261
70
    LookupQualifiedName(Found, LookupCtx);
262
70
    return CheckLookupResult(Found);
263
71
  };
264
265
42.6k
  auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
266
238
    if (Failed)
267
0
      return nullptr;
268
269
238
    IsDependent |= isDependentScopeSpecifier(LookupSS);
270
238
    DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
271
238
    if (!LookupCtx)
272
1
      return nullptr;
273
274
237
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
275
237
    if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
276
0
      Failed = true;
277
0
      return nullptr;
278
0
    }
279
237
    LookupQualifiedName(Found, LookupCtx);
280
237
    return CheckLookupResult(Found);
281
237
  };
282
283
42.6k
  auto LookupInScope = [&]() -> ParsedType {
284
42.4k
    if (Failed || !S)
285
7
      return nullptr;
286
287
42.4k
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
288
42.4k
    LookupName(Found, S);
289
42.4k
    return CheckLookupResult(Found);
290
42.4k
  };
291
292
  // C++2a [basic.lookup.qual]p6:
293
  //   In a qualified-id of the form
294
  //
295
  //     nested-name-specifier[opt] type-name :: ~ type-name
296
  //
297
  //   the second type-name is looked up in the same scope as the first.
298
  //
299
  // We interpret this as meaning that if you do a dual-scope lookup for the
300
  // first name, you also do a dual-scope lookup for the second name, per
301
  // C++ [basic.lookup.classref]p4:
302
  //
303
  //   If the id-expression in a class member access is a qualified-id of the
304
  //   form
305
  //
306
  //     class-name-or-namespace-name :: ...
307
  //
308
  //   the class-name-or-namespace-name following the . or -> is first looked
309
  //   up in the class of the object expression and the name, if found, is used.
310
  //   Otherwise, it is looked up in the context of the entire
311
  //   postfix-expression.
312
  //
313
  // This looks in the same scopes as for an unqualified destructor name:
314
  //
315
  // C++ [basic.lookup.classref]p3:
316
  //   If the unqualified-id is ~ type-name, the type-name is looked up
317
  //   in the context of the entire postfix-expression. If the type T
318
  //   of the object expression is of a class type C, the type-name is
319
  //   also looked up in the scope of class C. At least one of the
320
  //   lookups shall find a name that refers to cv T.
321
  //
322
  // FIXME: The intent is unclear here. Should type-name::~type-name look in
323
  // the scope anyway if it finds a non-matching name declared in the class?
324
  // If both lookups succeed and find a dependent result, which result should
325
  // we retain? (Same question for p->~type-name().)
326
327
42.6k
  if (NestedNameSpecifier *Prefix =
328
42.6k
      SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
329
    // This is
330
    //
331
    //   nested-name-specifier type-name :: ~ type-name
332
    //
333
    // Look for the second type-name in the nested-name-specifier.
334
189
    CXXScopeSpec PrefixSS;
335
189
    PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
336
189
    if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
337
155
      return T;
338
42.4k
  } else {
339
    // This is one of
340
    //
341
    //   type-name :: ~ type-name
342
    //   ~ type-name
343
    //
344
    // Look in the scope and (if any) the object type.
345
42.4k
    if (ParsedType T = LookupInScope())
346
42.3k
      return T;
347
100
    if (ParsedType T = LookupInObjectType())
348
42
      return T;
349
100
  }
350
351
92
  if (Failed)
352
0
    return nullptr;
353
354
92
  if (IsDependent) {
355
    // We didn't find our type, but that's OK: it's dependent anyway.
356
357
    // FIXME: What if we have no nested-name-specifier?
358
3
    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
359
3
                                   SS.getWithLocInContext(Context),
360
3
                                   II, NameLoc);
361
3
    return ParsedType::make(T);
362
3
  }
363
364
  // The remaining cases are all non-standard extensions imitating the behavior
365
  // of various other compilers.
366
89
  unsigned NumNonExtensionDecls = FoundDecls.size();
367
368
89
  if (SS.isSet()) {
369
    // For compatibility with older broken C++ rules and existing code,
370
    //
371
    //   nested-name-specifier :: ~ type-name
372
    //
373
    // also looks for type-name within the nested-name-specifier.
374
49
    if (ParsedType T = LookupInNestedNameSpec(SS)) {
375
30
      Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
376
30
          << SS.getRange()
377
30
          << FixItHint::CreateInsertion(SS.getEndLoc(),
378
30
                                        ("::" + II.getName()).str());
379
30
      return T;
380
30
    }
381
382
    // For compatibility with other compilers and older versions of Clang,
383
    //
384
    //   nested-name-specifier type-name :: ~ type-name
385
    //
386
    // also looks for type-name in the scope. Unfortunately, we can't
387
    // reasonably apply this fallback for dependent nested-name-specifiers.
388
19
    if (SS.getScopeRep()->getPrefix()) {
389
10
      if (ParsedType T = LookupInScope()) {
390
10
        Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
391
10
            << FixItHint::CreateRemoval(SS.getRange());
392
10
        Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
393
10
            << GetTypeFromParser(T);
394
10
        return T;
395
10
      }
396
10
    }
397
19
  }
398
399
  // We didn't find anything matching; tell the user what we did find (if
400
  // anything).
401
402
  // Don't tell the user about declarations we shouldn't have found.
403
49
  FoundDecls.resize(NumNonExtensionDecls);
404
405
  // List types before non-types.
406
49
  std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
407
49
                   [](NamedDecl *A, NamedDecl *B) {
408
0
                     return isa<TypeDecl>(A->getUnderlyingDecl()) >
409
0
                            isa<TypeDecl>(B->getUnderlyingDecl());
410
0
                   });
411
412
  // Suggest a fixit to properly name the destroyed type.
413
49
  auto MakeFixItHint = [&]{
414
49
    const CXXRecordDecl *Destroyed = nullptr;
415
    // FIXME: If we have a scope specifier, suggest its last component?
416
49
    if (!SearchType.isNull())
417
29
      Destroyed = SearchType->getAsCXXRecordDecl();
418
20
    else if (S)
419
20
      Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
420
49
    if (Destroyed)
421
41
      return FixItHint::CreateReplacement(SourceRange(NameLoc),
422
41
                                          Destroyed->getNameAsString());
423
8
    return FixItHint();
424
49
  };
425
426
49
  if (FoundDecls.empty()) {
427
    // FIXME: Attempt typo-correction?
428
26
    Diag(NameLoc, diag::err_undeclared_destructor_name)
429
26
      << &II << MakeFixItHint();
430
26
  } else 
if (23
!SearchType.isNull()23
&&
FoundDecls.size() == 121
) {
431
21
    if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
432
21
      assert(!SearchType.isNull() &&
433
21
             "should only reject a type result if we have a search type");
434
0
      QualType T = Context.getTypeDeclType(TD);
435
21
      Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
436
21
          << T << SearchType << MakeFixItHint();
437
21
    } else {
438
0
      Diag(NameLoc, diag::err_destructor_expr_nontype)
439
0
          << &II << MakeFixItHint();
440
0
    }
441
21
  } else {
442
2
    Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
443
2
                                      : 
diag::err_destructor_expr_mismatch0
)
444
2
        << &II << SearchType << MakeFixItHint();
445
2
  }
446
447
23
  for (NamedDecl *FoundD : FoundDecls) {
448
23
    if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
449
21
      Diag(FoundD->getLocation(), diag::note_destructor_type_here)
450
21
          << Context.getTypeDeclType(TD);
451
2
    else
452
2
      Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
453
2
          << FoundD;
454
23
  }
455
456
49
  return nullptr;
457
89
}
458
459
ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
460
26
                                              ParsedType ObjectType) {
461
26
  if (DS.getTypeSpecType() == DeclSpec::TST_error)
462
1
    return nullptr;
463
464
25
  if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
465
6
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
466
6
    return nullptr;
467
6
  }
468
469
19
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
470
19
         "unexpected type in getDestructorType");
471
0
  QualType T = BuildDecltypeType(DS.getRepAsExpr());
472
473
  // If we know the type of the object, check that the correct destructor
474
  // type was named now; we can give better diagnostics this way.
475
19
  QualType SearchType = GetTypeFromParser(ObjectType);
476
19
  if (!SearchType.isNull() && 
!SearchType->isDependentType()18
&&
477
19
      
!Context.hasSameUnqualifiedType(T, SearchType)18
) {
478
5
    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
479
5
      << T << SearchType;
480
5
    return nullptr;
481
5
  }
482
483
14
  return ParsedType::make(T);
484
19
}
485
486
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
487
796
                                  const UnqualifiedId &Name, bool IsUDSuffix) {
488
796
  assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
489
796
  if (!IsUDSuffix) {
490
    // [over.literal] p8
491
    //
492
    // double operator""_Bq(long double);  // OK: not a reserved identifier
493
    // double operator"" _Bq(long double); // ill-formed, no diagnostic required
494
461
    IdentifierInfo *II = Name.Identifier;
495
461
    ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
496
461
    SourceLocation Loc = Name.getEndLoc();
497
461
    if (isReservedInAllContexts(Status) &&
498
461
        
!PP.getSourceManager().isInSystemHeader(Loc)2
) {
499
2
      Diag(Loc, diag::warn_reserved_extern_symbol)
500
2
          << II << static_cast<int>(Status)
501
2
          << FixItHint::CreateReplacement(
502
2
                 Name.getSourceRange(),
503
2
                 (StringRef("operator\"\"") + II->getName()).str());
504
2
    }
505
461
  }
506
507
796
  if (!SS.isValid())
508
781
    return false;
509
510
15
  switch (SS.getScopeRep()->getKind()) {
511
0
  case NestedNameSpecifier::Identifier:
512
6
  case NestedNameSpecifier::TypeSpec:
513
6
  case NestedNameSpecifier::TypeSpecWithTemplate:
514
    // Per C++11 [over.literal]p2, literal operators can only be declared at
515
    // namespace scope. Therefore, this unqualified-id cannot name anything.
516
    // Reject it early, because we have no AST representation for this in the
517
    // case where the scope is dependent.
518
6
    Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
519
6
        << SS.getScopeRep();
520
6
    return true;
521
522
1
  case NestedNameSpecifier::Global:
523
1
  case NestedNameSpecifier::Super:
524
9
  case NestedNameSpecifier::Namespace:
525
9
  case NestedNameSpecifier::NamespaceAlias:
526
9
    return false;
527
15
  }
528
529
0
  llvm_unreachable("unknown nested name specifier kind");
530
0
}
531
532
/// Build a C++ typeid expression with a type operand.
533
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
534
                                SourceLocation TypeidLoc,
535
                                TypeSourceInfo *Operand,
536
5.43k
                                SourceLocation RParenLoc) {
537
  // C++ [expr.typeid]p4:
538
  //   The top-level cv-qualifiers of the lvalue expression or the type-id
539
  //   that is the operand of typeid are always ignored.
540
  //   If the type of the type-id is a class type or a reference to a class
541
  //   type, the class shall be completely-defined.
542
5.43k
  Qualifiers Quals;
543
5.43k
  QualType T
544
5.43k
    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
545
5.43k
                                      Quals);
546
5.43k
  if (T->getAs<RecordType>() &&
547
5.43k
      
RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)269
)
548
5
    return ExprError();
549
550
5.43k
  if (T->isVariablyModifiedType())
551
1
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
552
553
5.43k
  if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
554
6
    return ExprError();
555
556
5.42k
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
557
5.42k
                                     SourceRange(TypeidLoc, RParenLoc));
558
5.43k
}
559
560
/// Build a C++ typeid expression with an expression operand.
561
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
562
                                SourceLocation TypeidLoc,
563
                                Expr *E,
564
343
                                SourceLocation RParenLoc) {
565
343
  bool WasEvaluated = false;
566
343
  if (E && !E->isTypeDependent()) {
567
328
    if (E->getType()->isPlaceholderType()) {
568
1
      ExprResult result = CheckPlaceholderExpr(E);
569
1
      if (result.isInvalid()) 
return ExprError()0
;
570
1
      E = result.get();
571
1
    }
572
573
328
    QualType T = E->getType();
574
328
    if (const RecordType *RecordT = T->getAs<RecordType>()) {
575
149
      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
576
      // C++ [expr.typeid]p3:
577
      //   [...] If the type of the expression is a class type, the class
578
      //   shall be completely-defined.
579
149
      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
580
1
        return ExprError();
581
582
      // C++ [expr.typeid]p3:
583
      //   When typeid is applied to an expression other than an glvalue of a
584
      //   polymorphic class type [...] [the] expression is an unevaluated
585
      //   operand. [...]
586
148
      if (RecordD->isPolymorphic() && 
E->isGLValue()122
) {
587
115
        if (isUnevaluatedContext()) {
588
          // The operand was processed in unevaluated context, switch the
589
          // context and recheck the subexpression.
590
114
          ExprResult Result = TransformToPotentiallyEvaluated(E);
591
114
          if (Result.isInvalid())
592
10
            return ExprError();
593
104
          E = Result.get();
594
104
        }
595
596
        // We require a vtable to query the type at run time.
597
105
        MarkVTableUsed(TypeidLoc, RecordD);
598
105
        WasEvaluated = true;
599
105
      }
600
148
    }
601
602
317
    ExprResult Result = CheckUnevaluatedOperand(E);
603
317
    if (Result.isInvalid())
604
0
      return ExprError();
605
317
    E = Result.get();
606
607
    // C++ [expr.typeid]p4:
608
    //   [...] If the type of the type-id is a reference to a possibly
609
    //   cv-qualified type, the result of the typeid expression refers to a
610
    //   std::type_info object representing the cv-unqualified referenced
611
    //   type.
612
317
    Qualifiers Quals;
613
317
    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
614
317
    if (!Context.hasSameType(T, UnqualT)) {
615
21
      T = UnqualT;
616
21
      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
617
21
    }
618
317
  }
619
620
332
  if (E->getType()->isVariablyModifiedType())
621
1
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
622
1
                     << E->getType());
623
331
  else if (!inTemplateInstantiation() &&
624
331
           
E->HasSideEffects(Context, WasEvaluated)304
) {
625
    // The expression operand for typeid is in an unevaluated expression
626
    // context, so side effects could result in unintended consequences.
627
73
    Diag(E->getExprLoc(), WasEvaluated
628
73
                              ? 
diag::warn_side_effects_typeid42
629
73
                              : 
diag::warn_side_effects_unevaluated_context31
);
630
73
  }
631
632
331
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
633
331
                                     SourceRange(TypeidLoc, RParenLoc));
634
332
}
635
636
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
637
ExprResult
638
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
639
5.65k
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
640
  // typeid is not supported in OpenCL.
641
5.65k
  if (getLangOpts().OpenCLCPlusPlus) {
642
1
    return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
643
1
                     << "typeid");
644
1
  }
645
646
  // Find the std::type_info type.
647
5.65k
  if (!getStdNamespace())
648
1
    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
649
650
5.65k
  if (!CXXTypeInfoDecl) {
651
592
    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
652
592
    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
653
592
    LookupQualifiedName(R, getStdNamespace());
654
592
    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
655
    // Microsoft's typeinfo doesn't have type_info in std but in the global
656
    // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
657
592
    if (!CXXTypeInfoDecl && 
LangOpts.MSVCCompat4
) {
658
1
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
659
1
      CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
660
1
    }
661
592
    if (!CXXTypeInfoDecl)
662
3
      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
663
592
  }
664
665
5.65k
  if (!getLangOpts().RTTI) {
666
1
    return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
667
1
  }
668
669
5.65k
  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
670
671
5.65k
  if (isType) {
672
    // The operand is a type; handle it as such.
673
5.33k
    TypeSourceInfo *TInfo = nullptr;
674
5.33k
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
675
5.33k
                                   &TInfo);
676
5.33k
    if (T.isNull())
677
0
      return ExprError();
678
679
5.33k
    if (!TInfo)
680
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
681
682
5.33k
    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
683
5.33k
  }
684
685
  // The operand is an expression.
686
316
  ExprResult Result =
687
316
      BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
688
689
316
  if (!getLangOpts().RTTIData && 
!Result.isInvalid()15
)
690
15
    if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
691
15
      if (CTE->isPotentiallyEvaluated() && 
!CTE->isMostDerived(Context)11
)
692
7
        Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
693
7
            << (getDiagnostics().getDiagnosticOptions().getFormat() ==
694
7
                DiagnosticOptions::MSVC);
695
316
  return Result;
696
5.65k
}
697
698
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
699
/// a single GUID.
700
static void
701
getUuidAttrOfType(Sema &SemaRef, QualType QT,
702
175
                  llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
703
  // Optionally remove one level of pointer, reference or array indirection.
704
175
  const Type *Ty = QT.getTypePtr();
705
175
  if (QT->isPointerType() || 
QT->isReferenceType()169
)
706
6
    Ty = QT->getPointeeType().getTypePtr();
707
169
  else if (QT->isArrayType())
708
10
    Ty = Ty->getBaseElementTypeUnsafe();
709
710
175
  const auto *TD = Ty->getAsTagDecl();
711
175
  if (!TD)
712
5
    return;
713
714
170
  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
715
155
    UuidAttrs.insert(Uuid);
716
155
    return;
717
155
  }
718
719
  // __uuidof can grab UUIDs from template arguments.
720
15
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
721
6
    const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
722
9
    for (const TemplateArgument &TA : TAL.asArray()) {
723
9
      const UuidAttr *UuidForTA = nullptr;
724
9
      if (TA.getKind() == TemplateArgument::Type)
725
9
        getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
726
0
      else if (TA.getKind() == TemplateArgument::Declaration)
727
0
        getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
728
729
9
      if (UuidForTA)
730
0
        UuidAttrs.insert(UuidForTA);
731
9
    }
732
6
  }
733
15
}
734
735
/// Build a Microsoft __uuidof expression with a type operand.
736
ExprResult Sema::BuildCXXUuidof(QualType Type,
737
                                SourceLocation TypeidLoc,
738
                                TypeSourceInfo *Operand,
739
162
                                SourceLocation RParenLoc) {
740
162
  MSGuidDecl *Guid = nullptr;
741
162
  if (!Operand->getType()->isDependentType()) {
742
147
    llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
743
147
    getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
744
147
    if (UuidAttrs.empty())
745
9
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
746
138
    if (UuidAttrs.size() > 1)
747
1
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
748
137
    Guid = UuidAttrs.back()->getGuidDecl();
749
137
  }
750
751
152
  return new (Context)
752
152
      CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
753
162
}
754
755
/// Build a Microsoft __uuidof expression with an expression operand.
756
ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
757
35
                                Expr *E, SourceLocation RParenLoc) {
758
35
  MSGuidDecl *Guid = nullptr;
759
35
  if (!E->getType()->isDependentType()) {
760
32
    if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
761
      // A null pointer results in {00000000-0000-0000-0000-000000000000}.
762
13
      Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
763
19
    } else {
764
19
      llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
765
19
      getUuidAttrOfType(*this, E->getType(), UuidAttrs);
766
19
      if (UuidAttrs.empty())
767
4
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
768
15
      if (UuidAttrs.size() > 1)
769
1
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
770
14
      Guid = UuidAttrs.back()->getGuidDecl();
771
14
    }
772
32
  }
773
774
30
  return new (Context)
775
30
      CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
776
35
}
777
778
/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
779
ExprResult
780
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
781
178
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
782
178
  QualType GuidType = Context.getMSGuidType();
783
178
  GuidType.addConst();
784
785
178
  if (isType) {
786
    // The operand is a type; handle it as such.
787
147
    TypeSourceInfo *TInfo = nullptr;
788
147
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
789
147
                                   &TInfo);
790
147
    if (T.isNull())
791
0
      return ExprError();
792
793
147
    if (!TInfo)
794
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
795
796
147
    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
797
147
  }
798
799
  // The operand is an expression.
800
31
  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
801
178
}
802
803
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
804
ExprResult
805
293k
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
806
293k
  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
807
293k
         "Unknown C++ Boolean value!");
808
0
  return new (Context)
809
293k
      CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
810
293k
}
811
812
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
813
ExprResult
814
91.0k
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
815
91.0k
  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
816
91.0k
}
817
818
/// ActOnCXXThrow - Parse throw expressions.
819
ExprResult
820
14.9k
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
821
14.9k
  bool IsThrownVarInScope = false;
822
14.9k
  if (Ex) {
823
    // C++0x [class.copymove]p31:
824
    //   When certain criteria are met, an implementation is allowed to omit the
825
    //   copy/move construction of a class object [...]
826
    //
827
    //     - in a throw-expression, when the operand is the name of a
828
    //       non-volatile automatic object (other than a function or catch-
829
    //       clause parameter) whose scope does not extend beyond the end of the
830
    //       innermost enclosing try-block (if there is one), the copy/move
831
    //       operation from the operand to the exception object (15.1) can be
832
    //       omitted by constructing the automatic object directly into the
833
    //       exception object
834
8.03k
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
835
583
      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
836
577
        if (Var->hasLocalStorage() && 
!Var->getType().isVolatileQualified()554
) {
837
619
          for( ; S; 
S = S->getParent()65
) {
838
619
            if (S->isDeclScope(Var)) {
839
94
              IsThrownVarInScope = true;
840
94
              break;
841
94
            }
842
843
525
            if (S->getFlags() &
844
525
                (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
845
525
                 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
846
525
                 Scope::TryScope))
847
460
              break;
848
525
          }
849
554
        }
850
577
      }
851
8.03k
  }
852
853
14.9k
  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
854
14.9k
}
855
856
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
857
15.0k
                               bool IsThrownVarInScope) {
858
  // Don't report an error if 'throw' is used in system headers.
859
15.0k
  if (!getLangOpts().CXXExceptions &&
860
15.0k
      
!getSourceManager().isInSystemHeader(OpLoc)13
&&
!getLangOpts().CUDA13
) {
861
    // Delay error emission for the OpenMP device code.
862
10
    targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
863
10
  }
864
865
  // Exceptions aren't allowed in CUDA device code.
866
15.0k
  if (getLangOpts().CUDA)
867
19
    CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
868
19
        << "throw" << CurrentCUDATarget();
869
870
15.0k
  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
871
232
    Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
872
873
15.0k
  if (Ex && 
!Ex->isTypeDependent()8.11k
) {
874
    // Initialize the exception result.  This implicitly weeds out
875
    // abstract types or types with inaccessible copy constructors.
876
877
    // C++0x [class.copymove]p31:
878
    //   When certain criteria are met, an implementation is allowed to omit the
879
    //   copy/move construction of a class object [...]
880
    //
881
    //     - in a throw-expression, when the operand is the name of a
882
    //       non-volatile automatic object (other than a function or
883
    //       catch-clause
884
    //       parameter) whose scope does not extend beyond the end of the
885
    //       innermost enclosing try-block (if there is one), the copy/move
886
    //       operation from the operand to the exception object (15.1) can be
887
    //       omitted by constructing the automatic object directly into the
888
    //       exception object
889
6.75k
    NamedReturnInfo NRInfo =
890
6.75k
        IsThrownVarInScope ? 
getNamedReturnInfo(Ex)103
:
NamedReturnInfo()6.64k
;
891
892
6.75k
    QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
893
6.75k
    if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
894
42
      return ExprError();
895
896
6.70k
    InitializedEntity Entity =
897
6.70k
        InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
898
6.70k
    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
899
6.70k
    if (Res.isInvalid())
900
18
      return ExprError();
901
6.69k
    Ex = Res.get();
902
6.69k
  }
903
904
  // PPC MMA non-pointer types are not allowed as throw expr types.
905
14.9k
  if (Ex && 
Context.getTargetInfo().getTriple().isPPC64()8.05k
)
906
12
    CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
907
908
14.9k
  return new (Context)
909
14.9k
      CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
910
15.0k
}
911
912
static void
913
collectPublicBases(CXXRecordDecl *RD,
914
                   llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
915
                   llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
916
                   llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
917
47
                   bool ParentIsPublic) {
918
47
  for (const CXXBaseSpecifier &BS : RD->bases()) {
919
16
    CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
920
16
    bool NewSubobject;
921
    // Virtual bases constitute the same subobject.  Non-virtual bases are
922
    // always distinct subobjects.
923
16
    if (BS.isVirtual())
924
4
      NewSubobject = VBases.insert(BaseDecl).second;
925
12
    else
926
12
      NewSubobject = true;
927
928
16
    if (NewSubobject)
929
14
      ++SubobjectsSeen[BaseDecl];
930
931
    // Only add subobjects which have public access throughout the entire chain.
932
16
    bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
933
16
    if (PublicPath)
934
10
      PublicSubobjectsSeen.insert(BaseDecl);
935
936
    // Recurse on to each base subobject.
937
16
    collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
938
16
                       PublicPath);
939
16
  }
940
47
}
941
942
static void getUnambiguousPublicSubobjects(
943
31
    CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
944
31
  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
945
31
  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
946
31
  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
947
31
  SubobjectsSeen[RD] = 1;
948
31
  PublicSubobjectsSeen.insert(RD);
949
31
  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
950
31
                     /*ParentIsPublic=*/true);
951
952
39
  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
953
    // Skip ambiguous objects.
954
39
    if (SubobjectsSeen[PublicSubobject] > 1)
955
0
      continue;
956
957
39
    Objects.push_back(PublicSubobject);
958
39
  }
959
31
}
960
961
/// CheckCXXThrowOperand - Validate the operand of a throw.
962
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
963
6.75k
                                QualType ExceptionObjectTy, Expr *E) {
964
  //   If the type of the exception would be an incomplete type or a pointer
965
  //   to an incomplete type other than (cv) void the program is ill-formed.
966
6.75k
  QualType Ty = ExceptionObjectTy;
967
6.75k
  bool isPointer = false;
968
6.75k
  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
969
147
    Ty = Ptr->getPointeeType();
970
147
    isPointer = true;
971
147
  }
972
6.75k
  if (!isPointer || 
!Ty->isVoidType()147
) {
973
6.74k
    if (RequireCompleteType(ThrowLoc, Ty,
974
6.74k
                            isPointer ? 
diag::err_throw_incomplete_ptr139
975
6.74k
                                      : 
diag::err_throw_incomplete6.60k
,
976
6.74k
                            E->getSourceRange()))
977
33
      return true;
978
979
6.71k
    if (!isPointer && 
Ty->isSizelessType()6.59k
) {
980
4
      Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
981
4
      return true;
982
4
    }
983
984
6.71k
    if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
985
6.71k
                               diag::err_throw_abstract_type, E))
986
3
      return true;
987
6.71k
  }
988
989
  // If the exception has class type, we need additional handling.
990
6.71k
  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
991
6.71k
  if (!RD)
992
1.12k
    return false;
993
994
  // If we are throwing a polymorphic class type or pointer thereof,
995
  // exception handling will make use of the vtable.
996
5.59k
  MarkVTableUsed(ThrowLoc, RD);
997
998
  // If a pointer is thrown, the referenced object will not be destroyed.
999
5.59k
  if (isPointer)
1000
16
    return false;
1001
1002
  // If the class has a destructor, we must be able to call it.
1003
5.57k
  if (!RD->hasIrrelevantDestructor()) {
1004
5.39k
    if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1005
5.39k
      MarkFunctionReferenced(E->getExprLoc(), Destructor);
1006
5.39k
      CheckDestructorAccess(E->getExprLoc(), Destructor,
1007
5.39k
                            PDiag(diag::err_access_dtor_exception) << Ty);
1008
5.39k
      if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1009
1
        return true;
1010
5.39k
    }
1011
5.39k
  }
1012
1013
  // The MSVC ABI creates a list of all types which can catch the exception
1014
  // object.  This list also references the appropriate copy constructor to call
1015
  // if the object is caught by value and has a non-trivial copy constructor.
1016
5.57k
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1017
    // We are only interested in the public, unambiguous bases contained within
1018
    // the exception object.  Bases which are ambiguous or otherwise
1019
    // inaccessible are not catchable types.
1020
31
    llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1021
31
    getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1022
1023
39
    for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1024
      // Attempt to lookup the copy constructor.  Various pieces of machinery
1025
      // will spring into action, like template instantiation, which means this
1026
      // cannot be a simple walk of the class's decls.  Instead, we must perform
1027
      // lookup and overload resolution.
1028
39
      CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1029
39
      if (!CD || CD->isDeleted())
1030
4
        continue;
1031
1032
      // Mark the constructor referenced as it is used by this throw expression.
1033
35
      MarkFunctionReferenced(E->getExprLoc(), CD);
1034
1035
      // Skip this copy constructor if it is trivial, we don't need to record it
1036
      // in the catchable type data.
1037
35
      if (CD->isTrivial())
1038
15
        continue;
1039
1040
      // The copy constructor is non-trivial, create a mapping from this class
1041
      // type to this constructor.
1042
      // N.B.  The selection of copy constructor is not sensitive to this
1043
      // particular throw-site.  Lookup will be performed at the catch-site to
1044
      // ensure that the copy constructor is, in fact, accessible (via
1045
      // friendship or any other means).
1046
20
      Context.addCopyConstructorForExceptionObject(Subobject, CD);
1047
1048
      // We don't keep the instantiated default argument expressions around so
1049
      // we must rebuild them here.
1050
26
      for (unsigned I = 1, E = CD->getNumParams(); I != E; 
++I6
) {
1051
7
        if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1052
1
          return true;
1053
7
      }
1054
20
    }
1055
31
  }
1056
1057
  // Under the Itanium C++ ABI, memory for the exception object is allocated by
1058
  // the runtime with no ability for the compiler to request additional
1059
  // alignment. Warn if the exception type requires alignment beyond the minimum
1060
  // guaranteed by the target C++ runtime.
1061
5.57k
  if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1062
5.54k
    CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1063
5.54k
    CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1064
5.54k
    if (ExnObjAlign < TypeAlign) {
1065
29
      Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1066
29
      Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1067
29
          << Ty << (unsigned)TypeAlign.getQuantity()
1068
29
          << (unsigned)ExnObjAlign.getQuantity();
1069
29
    }
1070
5.54k
  }
1071
1072
5.57k
  return false;
1073
5.57k
}
1074
1075
static QualType adjustCVQualifiersForCXXThisWithinLambda(
1076
    ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1077
3.23k
    DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1078
1079
3.23k
  QualType ClassType = ThisTy->getPointeeType();
1080
3.23k
  LambdaScopeInfo *CurLSI = nullptr;
1081
3.23k
  DeclContext *CurDC = CurSemaContext;
1082
1083
  // Iterate through the stack of lambdas starting from the innermost lambda to
1084
  // the outermost lambda, checking if '*this' is ever captured by copy - since
1085
  // that could change the cv-qualifiers of the '*this' object.
1086
  // The object referred to by '*this' starts out with the cv-qualifiers of its
1087
  // member function.  We then start with the innermost lambda and iterate
1088
  // outward checking to see if any lambda performs a by-copy capture of '*this'
1089
  // - and if so, any nested lambda must respect the 'constness' of that
1090
  // capturing lamdbda's call operator.
1091
  //
1092
1093
  // Since the FunctionScopeInfo stack is representative of the lexical
1094
  // nesting of the lambda expressions during initial parsing (and is the best
1095
  // place for querying information about captures about lambdas that are
1096
  // partially processed) and perhaps during instantiation of function templates
1097
  // that contain lambda expressions that need to be transformed BUT not
1098
  // necessarily during instantiation of a nested generic lambda's function call
1099
  // operator (which might even be instantiated at the end of the TU) - at which
1100
  // time the DeclContext tree is mature enough to query capture information
1101
  // reliably - we use a two pronged approach to walk through all the lexically
1102
  // enclosing lambda expressions:
1103
  //
1104
  //  1) Climb down the FunctionScopeInfo stack as long as each item represents
1105
  //  a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1106
  //  enclosed by the call-operator of the LSI below it on the stack (while
1107
  //  tracking the enclosing DC for step 2 if needed).  Note the topmost LSI on
1108
  //  the stack represents the innermost lambda.
1109
  //
1110
  //  2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1111
  //  represents a lambda's call operator.  If it does, we must be instantiating
1112
  //  a generic lambda's call operator (represented by the Current LSI, and
1113
  //  should be the only scenario where an inconsistency between the LSI and the
1114
  //  DeclContext should occur), so climb out the DeclContexts if they
1115
  //  represent lambdas, while querying the corresponding closure types
1116
  //  regarding capture information.
1117
1118
  // 1) Climb down the function scope info stack.
1119
3.23k
  for (int I = FunctionScopes.size();
1120
7.14k
       I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1121
7.14k
       
(4.53k
!CurLSI4.53k
||
!CurLSI->Lambda1.31k
|| CurLSI->Lambda->getDeclContext() ==
1122
1.30k
                       cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1123
4.46k
       
CurDC = getLambdaAwareParentOfDeclContext(CurDC)3.90k
) {
1124
4.46k
    CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1125
1126
4.46k
    if (!CurLSI->isCXXThisCaptured())
1127
1.89k
        continue;
1128
1129
2.57k
    auto C = CurLSI->getCXXThisCapture();
1130
1131
2.57k
    if (C.isCopyCapture()) {
1132
560
      ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1133
560
      if (CurLSI->CallOperator->isConst())
1134
240
        ClassType.addConst();
1135
560
      return ASTCtx.getPointerType(ClassType);
1136
560
    }
1137
2.57k
  }
1138
1139
  // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1140
  //    can happen during instantiation of its nested generic lambda call
1141
  //    operator); 2. if we're in a lambda scope (lambda body).
1142
2.67k
  if (CurLSI && 
isLambdaCallOperator(CurDC)2.66k
) {
1143
148
    assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1144
148
           "While computing 'this' capture-type for a generic lambda, when we "
1145
148
           "run out of enclosing LSI's, yet the enclosing DC is a "
1146
148
           "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1147
148
           "lambda call oeprator");
1148
0
    assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1149
1150
0
    auto IsThisCaptured =
1151
232
        [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1152
232
      IsConst = false;
1153
232
      IsByCopy = false;
1154
232
      for (auto &&C : Closure->captures()) {
1155
232
        if (C.capturesThis()) {
1156
232
          if (C.getCaptureKind() == LCK_StarThis)
1157
36
            IsByCopy = true;
1158
232
          if (Closure->getLambdaCallOperator()->isConst())
1159
196
            IsConst = true;
1160
232
          return true;
1161
232
        }
1162
232
      }
1163
0
      return false;
1164
232
    };
1165
1166
148
    bool IsByCopyCapture = false;
1167
148
    bool IsConstCapture = false;
1168
148
    CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1169
344
    while (Closure &&
1170
344
           
IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)232
) {
1171
232
      if (IsByCopyCapture) {
1172
36
        ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1173
36
        if (IsConstCapture)
1174
0
          ClassType.addConst();
1175
36
        return ASTCtx.getPointerType(ClassType);
1176
36
      }
1177
196
      Closure = isLambdaCallOperator(Closure->getParent())
1178
196
                    ? 
cast<CXXRecordDecl>(Closure->getParent()->getParent())84
1179
196
                    : 
nullptr112
;
1180
196
    }
1181
148
  }
1182
2.64k
  return ASTCtx.getPointerType(ClassType);
1183
2.67k
}
1184
1185
2.21M
QualType Sema::getCurrentThisType() {
1186
2.21M
  DeclContext *DC = getFunctionLevelDeclContext();
1187
2.21M
  QualType ThisTy = CXXThisTypeOverride;
1188
1189
2.21M
  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1190
2.20M
    if (method && method->isInstance())
1191
2.20M
      ThisTy = method->getThisType();
1192
2.20M
  }
1193
1194
2.21M
  if (ThisTy.isNull() && 
isLambdaCallOperator(CurContext)9.38k
&&
1195
2.21M
      
inTemplateInstantiation()61
&&
isa<CXXRecordDecl>(DC)41
) {
1196
1197
    // This is a lambda call operator that is being instantiated as a default
1198
    // initializer. DC must point to the enclosing class type, so we can recover
1199
    // the 'this' type from it.
1200
40
    QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1201
    // There are no cv-qualifiers for 'this' within default initializers,
1202
    // per [expr.prim.general]p4.
1203
40
    ThisTy = Context.getPointerType(ClassTy);
1204
40
  }
1205
1206
  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1207
  // might need to be adjusted if the lambda or any of its enclosing lambda's
1208
  // captures '*this' by copy.
1209
2.21M
  if (!ThisTy.isNull() && 
isLambdaCallOperator(CurContext)2.20M
)
1210
3.23k
    return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1211
3.23k
                                                    CurContext, Context);
1212
2.21M
  return ThisTy;
1213
2.21M
}
1214
1215
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1216
                                         Decl *ContextDecl,
1217
                                         Qualifiers CXXThisTypeQuals,
1218
                                         bool Enabled)
1219
  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1220
4.47M
{
1221
4.47M
  if (!Enabled || 
!ContextDecl2.85M
)
1222
1.81M
    return;
1223
1224
2.66M
  CXXRecordDecl *Record = nullptr;
1225
2.66M
  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1226
60.7k
    Record = Template->getTemplatedDecl();
1227
2.60M
  else
1228
2.60M
    Record = cast<CXXRecordDecl>(ContextDecl);
1229
1230
2.66M
  QualType T = S.Context.getRecordType(Record);
1231
2.66M
  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1232
1233
2.66M
  S.CXXThisTypeOverride = S.Context.getPointerType(T);
1234
1235
2.66M
  this->Enabled = true;
1236
2.66M
}
1237
1238
1239
4.47M
Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1240
4.47M
  if (Enabled) {
1241
2.66M
    S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1242
2.66M
  }
1243
4.47M
}
1244
1245
90
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1246
90
  SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1247
90
  assert(!LSI->isCXXThisCaptured());
1248
  //  [=, this] {};   // until C++20: Error: this when = is the default
1249
90
  if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1250
90
      
!Sema.getLangOpts().CPlusPlus2012
)
1251
6
    return;
1252
84
  Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1253
84
      << FixItHint::CreateInsertion(
1254
84
             DiagLoc, LSI->NumExplicitCaptures > 0 ? 
", this"0
: "this");
1255
84
}
1256
1257
bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1258
    bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1259
1.11M
    const bool ByCopy) {
1260
  // We don't need to capture this in an unevaluated context.
1261
1.11M
  if (isUnevaluatedContext() && 
!Explicit3.63k
)
1262
3.63k
    return true;
1263
1264
1.10M
  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1265
1266
1.10M
  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1267
1.10M
                                         ? 
*FunctionScopeIndexToStopAt36
1268
1.10M
                                         : 
FunctionScopes.size() - 11.10M
;
1269
1270
  // Check that we can capture the *enclosing object* (referred to by '*this')
1271
  // by the capturing-entity/closure (lambda/block/etc) at
1272
  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1273
1274
  // Note: The *enclosing object* can only be captured by-value by a
1275
  // closure that is a lambda, using the explicit notation:
1276
  //    [*this] { ... }.
1277
  // Every other capture of the *enclosing object* results in its by-reference
1278
  // capture.
1279
1280
  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1281
  // stack), we can capture the *enclosing object* only if:
1282
  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1283
  // -  or, 'L' has an implicit capture.
1284
  // AND
1285
  //   -- there is no enclosing closure
1286
  //   -- or, there is some enclosing closure 'E' that has already captured the
1287
  //      *enclosing object*, and every intervening closure (if any) between 'E'
1288
  //      and 'L' can implicitly capture the *enclosing object*.
1289
  //   -- or, every enclosing closure can implicitly capture the
1290
  //      *enclosing object*
1291
1292
1293
1.10M
  unsigned NumCapturingClosures = 0;
1294
1.11M
  for (int idx = MaxFunctionScopesIndex; idx >= 0; 
idx--11.5k
) {
1295
1.11M
    if (CapturingScopeInfo *CSI =
1296
1.11M
            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1297
23.4k
      if (CSI->CXXThisCaptureIndex != 0) {
1298
        // 'this' is already being captured; there isn't anything more to do.
1299
11.7k
        CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1300
11.7k
        break;
1301
11.7k
      }
1302
11.6k
      LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1303
11.6k
      if (LSI && 
isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)1.04k
) {
1304
        // This context can't implicitly capture 'this'; fail out.
1305
40
        if (BuildAndDiagnose) {
1306
32
          Diag(Loc, diag::err_this_capture)
1307
32
              << (Explicit && 
idx == MaxFunctionScopesIndex0
);
1308
32
          if (!Explicit)
1309
32
            buildLambdaThisCaptureFixit(*this, LSI);
1310
32
        }
1311
40
        return true;
1312
40
      }
1313
11.5k
      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1314
11.5k
          
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval11.2k
||
1315
11.5k
          
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block11.0k
||
1316
11.5k
          
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion10.9k
||
1317
11.5k
          
(471
Explicit471
&&
idx == MaxFunctionScopesIndex413
)) {
1318
        // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1319
        // iteration through can be an explicit capture, all enclosing closures,
1320
        // if any, must perform implicit captures.
1321
1322
        // This closure can capture 'this'; continue looking upwards.
1323
11.5k
        NumCapturingClosures++;
1324
11.5k
        continue;
1325
11.5k
      }
1326
      // This context can't implicitly capture 'this'; fail out.
1327
60
      if (BuildAndDiagnose)
1328
48
        Diag(Loc, diag::err_this_capture)
1329
48
            << (Explicit && 
idx == MaxFunctionScopesIndex2
);
1330
1331
60
      if (!Explicit)
1332
58
        buildLambdaThisCaptureFixit(*this, LSI);
1333
60
      return true;
1334
11.5k
    }
1335
1.09M
    break;
1336
1.11M
  }
1337
1.10M
  if (!BuildAndDiagnose) 
return false77
;
1338
1339
  // If we got here, then the closure at MaxFunctionScopesIndex on the
1340
  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1341
  // (including implicit by-reference captures in any enclosing closures).
1342
1343
  // In the loop below, respect the ByCopy flag only for the closure requesting
1344
  // the capture (i.e. first iteration through the loop below).  Ignore it for
1345
  // all enclosing closure's up to NumCapturingClosures (since they must be
1346
  // implicitly capturing the *enclosing  object* by reference (see loop
1347
  // above)).
1348
1.10M
  assert((!ByCopy ||
1349
1.10M
          isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1350
1.10M
         "Only a lambda can capture the enclosing object (referred to by "
1351
1.10M
         "*this) by copy");
1352
0
  QualType ThisTy = getCurrentThisType();
1353
1.11M
  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1354
1.10M
       
--idx, --NumCapturingClosures11.4k
) {
1355
11.4k
    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1356
1357
    // The type of the corresponding data member (not a 'this' pointer if 'by
1358
    // copy').
1359
11.4k
    QualType CaptureType = ThisTy;
1360
11.4k
    if (ByCopy) {
1361
      // If we are capturing the object referred to by '*this' by copy, ignore
1362
      // any cv qualifiers inherited from the type of the member function for
1363
      // the type of the closure-type's corresponding data member and any use
1364
      // of 'this'.
1365
137
      CaptureType = ThisTy->getPointeeType();
1366
137
      CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1367
137
    }
1368
1369
11.4k
    bool isNested = NumCapturingClosures > 1;
1370
11.4k
    CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1371
11.4k
  }
1372
1.10M
  return false;
1373
1.10M
}
1374
1375
233k
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1376
  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1377
  /// is a non-lvalue expression whose value is the address of the object for
1378
  /// which the function is called.
1379
1380
233k
  QualType ThisTy = getCurrentThisType();
1381
233k
  if (ThisTy.isNull())
1382
36
    return Diag(Loc, diag::err_invalid_this_use);
1383
233k
  return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1384
233k
}
1385
1386
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1387
1.10M
                             bool IsImplicit) {
1388
1.10M
  auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1389
1.10M
  MarkThisReferenced(This);
1390
1.10M
  return This;
1391
1.10M
}
1392
1393
1.11M
void Sema::MarkThisReferenced(CXXThisExpr *This) {
1394
1.11M
  CheckCXXThisCapture(This->getExprLoc());
1395
1.11M
}
1396
1397
934k
bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1398
  // If we're outside the body of a member function, then we'll have a specified
1399
  // type for 'this'.
1400
934k
  if (CXXThisTypeOverride.isNull())
1401
934k
    return false;
1402
1403
  // Determine whether we're looking into a class that's currently being
1404
  // defined.
1405
576
  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1406
576
  return Class && Class->isBeingDefined();
1407
934k
}
1408
1409
/// Parse construction of a specified type.
1410
/// Can be interpreted either as function-style casting ("int(x)")
1411
/// or class type construction ("ClassType(x,y,z)")
1412
/// or creation of a value-initialized type ("int()").
1413
ExprResult
1414
Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1415
                                SourceLocation LParenOrBraceLoc,
1416
                                MultiExprArg exprs,
1417
                                SourceLocation RParenOrBraceLoc,
1418
334k
                                bool ListInitialization) {
1419
334k
  if (!TypeRep)
1420
5
    return ExprError();
1421
1422
334k
  TypeSourceInfo *TInfo;
1423
334k
  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1424
334k
  if (!TInfo)
1425
0
    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1426
1427
334k
  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1428
334k
                                          RParenOrBraceLoc, ListInitialization);
1429
  // Avoid creating a non-type-dependent expression that contains typos.
1430
  // Non-type-dependent expressions are liable to be discarded without
1431
  // checking for embedded typos.
1432
334k
  if (!Result.isInvalid() && 
Result.get()->isInstantiationDependent()334k
&&
1433
334k
      
!Result.get()->isTypeDependent()251k
)
1434
4.41k
    Result = CorrectDelayedTyposInExpr(Result.get());
1435
330k
  else if (Result.isInvalid())
1436
229
    Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1437
229
                                RParenOrBraceLoc, exprs, Ty);
1438
334k
  return Result;
1439
334k
}
1440
1441
ExprResult
1442
Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1443
                                SourceLocation LParenOrBraceLoc,
1444
                                MultiExprArg Exprs,
1445
                                SourceLocation RParenOrBraceLoc,
1446
394k
                                bool ListInitialization) {
1447
394k
  QualType Ty = TInfo->getType();
1448
394k
  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1449
1450
394k
  assert((!ListInitialization ||
1451
394k
          (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1452
394k
         "List initialization must have initializer list as expression.");
1453
0
  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1454
1455
394k
  InitializedEntity Entity =
1456
394k
      InitializedEntity::InitializeTemporary(Context, TInfo);
1457
394k
  InitializationKind Kind =
1458
394k
      Exprs.size()
1459
394k
          ? 
ListInitialization227k
1460
227k
                ? InitializationKind::CreateDirectList(
1461
10.8k
                      TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1462
227k
                : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1463
216k
                                                   RParenOrBraceLoc)
1464
394k
          : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1465
167k
                                            RParenOrBraceLoc);
1466
1467
  // C++1z [expr.type.conv]p1:
1468
  //   If the type is a placeholder for a deduced class type, [...perform class
1469
  //   template argument deduction...]
1470
394k
  DeducedType *Deduced = Ty->getContainedDeducedType();
1471
394k
  if (Deduced && 
isa<DeducedTemplateSpecializationType>(Deduced)96
) {
1472
96
    Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1473
96
                                                     Kind, Exprs);
1474
96
    if (Ty.isNull())
1475
6
      return ExprError();
1476
90
    Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1477
90
  }
1478
1479
394k
  if (Ty->isDependentType() || 
CallExpr::hasAnyTypeDependentArguments(Exprs)144k
) {
1480
    // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1481
    // directly. We work around this by dropping the locations of the braces.
1482
254k
    SourceRange Locs = ListInitialization
1483
254k
                           ? 
SourceRange()6.63k
1484
254k
                           : 
SourceRange(LParenOrBraceLoc, RParenOrBraceLoc)247k
;
1485
254k
    return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(),
1486
254k
                                              TInfo, Locs.getBegin(), Exprs,
1487
254k
                                              Locs.getEnd());
1488
254k
  }
1489
1490
  // C++ [expr.type.conv]p1:
1491
  // If the expression list is a parenthesized single expression, the type
1492
  // conversion expression is equivalent (in definedness, and if defined in
1493
  // meaning) to the corresponding cast expression.
1494
140k
  if (Exprs.size() == 1 && 
!ListInitialization67.2k
&&
1495
140k
      
!isa<InitListExpr>(Exprs[0])63.0k
) {
1496
63.0k
    Expr *Arg = Exprs[0];
1497
63.0k
    return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1498
63.0k
                                      RParenOrBraceLoc);
1499
63.0k
  }
1500
1501
  //   For an expression of the form T(), T shall not be an array type.
1502
77.7k
  QualType ElemTy = Ty;
1503
77.7k
  if (Ty->isArrayType()) {
1504
73
    if (!ListInitialization)
1505
5
      return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1506
5
                         << FullRange);
1507
68
    ElemTy = Context.getBaseElementType(Ty);
1508
68
  }
1509
1510
  // Only construct objects with object types.
1511
  // The standard doesn't explicitly forbid function types here, but that's an
1512
  // obvious oversight, as there's no way to dynamically construct a function
1513
  // in general.
1514
77.7k
  if (Ty->isFunctionType())
1515
16
    return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1516
16
                       << Ty << FullRange);
1517
1518
  // C++17 [expr.type.conv]p2:
1519
  //   If the type is cv void and the initializer is (), the expression is a
1520
  //   prvalue of the specified type that performs no initialization.
1521
77.6k
  if (!Ty->isVoidType() &&
1522
77.6k
      RequireCompleteType(TyBeginLoc, ElemTy,
1523
76.5k
                          diag::err_invalid_incomplete_type_use, FullRange))
1524
48
    return ExprError();
1525
1526
  //   Otherwise, the expression is a prvalue of the specified type whose
1527
  //   result object is direct-initialized (11.6) with the initializer.
1528
77.6k
  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1529
77.6k
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1530
1531
77.6k
  if (Result.isInvalid())
1532
179
    return Result;
1533
1534
77.4k
  Expr *Inner = Result.get();
1535
77.4k
  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1536
5.64k
    Inner = BTE->getSubExpr();
1537
77.4k
  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1538
77.4k
      
!isa<CXXScalarValueInitExpr>(Inner)16.6k
) {
1539
    // If we created a CXXTemporaryObjectExpr, that node also represents the
1540
    // functional cast. Otherwise, create an explicit cast to represent
1541
    // the syntactic form of a functional-style cast that was used here.
1542
    //
1543
    // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1544
    // would give a more consistent AST representation than using a
1545
    // CXXTemporaryObjectExpr. It's also weird that the functional cast
1546
    // is sometimes handled by initialization and sometimes not.
1547
3.60k
    QualType ResultType = Result.get()->getType();
1548
3.60k
    SourceRange Locs = ListInitialization
1549
3.60k
                           ? 
SourceRange()3.54k
1550
3.60k
                           : 
SourceRange(LParenOrBraceLoc, RParenOrBraceLoc)62
;
1551
3.60k
    Result = CXXFunctionalCastExpr::Create(
1552
3.60k
        Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1553
3.60k
        Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1554
3.60k
        Locs.getBegin(), Locs.getEnd());
1555
3.60k
  }
1556
1557
77.4k
  return Result;
1558
77.6k
}
1559
1560
996
bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1561
  // [CUDA] Ignore this function, if we can't call it.
1562
996
  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1563
996
  if (getLangOpts().CUDA) {
1564
200
    auto CallPreference = IdentifyCUDAPreference(Caller, Method);
1565
    // If it's not callable at all, it's not the right function.
1566
200
    if (CallPreference < CFP_WrongSide)
1567
0
      return false;
1568
200
    if (CallPreference == CFP_WrongSide) {
1569
      // Maybe. We have to check if there are better alternatives.
1570
99
      DeclContext::lookup_result R =
1571
99
          Method->getDeclContext()->lookup(Method->getDeclName());
1572
173
      for (const auto *D : R) {
1573
173
        if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1574
173
          if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
1575
95
            return false;
1576
173
        }
1577
173
      }
1578
      // We've found no better variants.
1579
99
    }
1580
200
  }
1581
1582
901
  SmallVector<const FunctionDecl*, 4> PreventedBy;
1583
901
  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1584
1585
901
  if (Result || 
!getLangOpts().CUDA150
||
PreventedBy.empty()18
)
1586
883
    return Result;
1587
1588
  // In case of CUDA, return true if none of the 1-argument deallocator
1589
  // functions are actually callable.
1590
22
  
return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) 18
{
1591
22
    assert(FD->getNumParams() == 1 &&
1592
22
           "Only single-operand functions should be in PreventedBy");
1593
0
    return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1594
22
  });
1595
901
}
1596
1597
/// Determine whether the given function is a non-placement
1598
/// deallocation function.
1599
28.2k
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1600
28.2k
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1601
875
    return S.isUsualDeallocationFunction(Method);
1602
1603
27.3k
  if (FD->getOverloadedOperator() != OO_Delete &&
1604
27.3k
      
FD->getOverloadedOperator() != OO_Array_Delete10.6k
)
1605
0
    return false;
1606
1607
27.3k
  unsigned UsualParams = 1;
1608
1609
27.3k
  if (S.getLangOpts().SizedDeallocation && 
UsualParams < FD->getNumParams()182
&&
1610
27.3k
      S.Context.hasSameUnqualifiedType(
1611
122
          FD->getParamDecl(UsualParams)->getType(),
1612
122
          S.Context.getSizeType()))
1613
75
    ++UsualParams;
1614
1615
27.3k
  if (S.getLangOpts().AlignedAllocation && 
UsualParams < FD->getNumParams()4.55k
&&
1616
27.3k
      S.Context.hasSameUnqualifiedType(
1617
3.10k
          FD->getParamDecl(UsualParams)->getType(),
1618
3.10k
          S.Context.getTypeDeclType(S.getStdAlignValT())))
1619
1.87k
    ++UsualParams;
1620
1621
27.3k
  return UsualParams == FD->getNumParams();
1622
27.3k
}
1623
1624
namespace {
1625
  struct UsualDeallocFnInfo {
1626
13.5k
    UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1627
    UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1628
        : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1629
          Destroying(false), HasSizeT(false), HasAlignValT(false),
1630
27.2k
          CUDAPref(Sema::CFP_Native) {
1631
      // A function template declaration is never a usual deallocation function.
1632
27.2k
      if (!FD)
1633
4
        return;
1634
27.2k
      unsigned NumBaseParams = 1;
1635
27.2k
      if (FD->isDestroyingOperatorDelete()) {
1636
139
        Destroying = true;
1637
139
        ++NumBaseParams;
1638
139
      }
1639
1640
27.2k
      if (NumBaseParams < FD->getNumParams() &&
1641
27.2k
          S.Context.hasSameUnqualifiedType(
1642
19.0k
              FD->getParamDecl(NumBaseParams)->getType(),
1643
19.0k
              S.Context.getSizeType())) {
1644
1.42k
        ++NumBaseParams;
1645
1.42k
        HasSizeT = true;
1646
1.42k
      }
1647
1648
27.2k
      if (NumBaseParams < FD->getNumParams() &&
1649
27.2k
          
FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()18.2k
) {
1650
9.85k
        ++NumBaseParams;
1651
9.85k
        HasAlignValT = true;
1652
9.85k
      }
1653
1654
      // In CUDA, determine how much we'd like / dislike to call this.
1655
27.2k
      if (S.getLangOpts().CUDA)
1656
236
        if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1657
236
          CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1658
27.2k
    }
1659
1660
39.4k
    explicit operator bool() const { return FD; }
1661
1662
    bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1663
1.69k
                      bool WantAlign) const {
1664
      // C++ P0722:
1665
      //   A destroying operator delete is preferred over a non-destroying
1666
      //   operator delete.
1667
1.69k
      if (Destroying != Other.Destroying)
1668
30
        return Destroying;
1669
1670
      // C++17 [expr.delete]p10:
1671
      //   If the type has new-extended alignment, a function with a parameter
1672
      //   of type std::align_val_t is preferred; otherwise a function without
1673
      //   such a parameter is preferred
1674
1.66k
      if (HasAlignValT != Other.HasAlignValT)
1675
1.54k
        return HasAlignValT == WantAlign;
1676
1677
120
      if (HasSizeT != Other.HasSizeT)
1678
106
        return HasSizeT == WantSize;
1679
1680
      // Use CUDA call preference as a tiebreaker.
1681
14
      return CUDAPref > Other.CUDAPref;
1682
120
    }
1683
1684
    DeclAccessPair Found;
1685
    FunctionDecl *FD;
1686
    bool Destroying, HasSizeT, HasAlignValT;
1687
    Sema::CUDAFunctionPreference CUDAPref;
1688
  };
1689
}
1690
1691
/// Determine whether a type has new-extended alignment. This may be called when
1692
/// the type is incomplete (for a delete-expression with an incomplete pointee
1693
/// type), in which case it will conservatively return false if the alignment is
1694
/// not known.
1695
12.8k
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1696
12.8k
  return S.getLangOpts().AlignedAllocation &&
1697
12.8k
         S.getASTContext().getTypeAlignIfKnown(AllocType) >
1698
2.01k
             S.getASTContext().getTargetInfo().getNewAlign();
1699
12.8k
}
1700
1701
/// Select the correct "usual" deallocation function to use from a selection of
1702
/// deallocation functions (either global or class-scope).
1703
static UsualDeallocFnInfo resolveDeallocationOverload(
1704
    Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1705
13.5k
    llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1706
13.5k
  UsualDeallocFnInfo Best;
1707
1708
40.5k
  for (auto I = R.begin(), E = R.end(); I != E; 
++I27.0k
) {
1709
27.0k
    UsualDeallocFnInfo Info(S, I.getPair());
1710
27.0k
    if (!Info || 
!isNonPlacementDeallocationFunction(S, Info.FD)27.0k
||
1711
27.0k
        
Info.CUDAPref == Sema::CFP_Never9.85k
)
1712
17.2k
      continue;
1713
1714
9.84k
    if (!Best) {
1715
8.19k
      Best = Info;
1716
8.19k
      if (BestFns)
1717
2.89k
        BestFns->push_back(Info);
1718
8.19k
      continue;
1719
8.19k
    }
1720
1721
1.65k
    if (Best.isBetterThan(Info, WantSize, WantAlign))
1722
1.49k
      continue;
1723
1724
    //   If more than one preferred function is found, all non-preferred
1725
    //   functions are eliminated from further consideration.
1726
155
    if (BestFns && 
Info.isBetterThan(Best, WantSize, WantAlign)42
)
1727
38
      BestFns->clear();
1728
1729
155
    Best = Info;
1730
155
    if (BestFns)
1731
42
      BestFns->push_back(Info);
1732
155
  }
1733
1734
13.5k
  return Best;
1735
13.5k
}
1736
1737
/// Determine whether a given type is a class for which 'delete[]' would call
1738
/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1739
/// we need to store the array size (even if the type is
1740
/// trivially-destructible).
1741
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1742
1.71k
                                         QualType allocType) {
1743
1.71k
  const RecordType *record =
1744
1.71k
    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1745
1.71k
  if (!record) 
return false1.33k
;
1746
1747
  // Try to find an operator delete[] in class scope.
1748
1749
384
  DeclarationName deleteName =
1750
384
    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1751
384
  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1752
384
  S.LookupQualifiedName(ops, record->getDecl());
1753
1754
  // We're just doing this for information.
1755
384
  ops.suppressDiagnostics();
1756
1757
  // Very likely: there's no operator delete[].
1758
384
  if (ops.empty()) 
return false339
;
1759
1760
  // If it's ambiguous, it should be illegal to call operator delete[]
1761
  // on this thing, so it doesn't matter if we allocate extra space or not.
1762
45
  if (ops.isAmbiguous()) 
return false0
;
1763
1764
  // C++17 [expr.delete]p10:
1765
  //   If the deallocation functions have class scope, the one without a
1766
  //   parameter of type std::size_t is selected.
1767
45
  auto Best = resolveDeallocationOverload(
1768
45
      S, ops, /*WantSize*/false,
1769
45
      /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1770
45
  return Best && Best.HasSizeT;
1771
45
}
1772
1773
/// Parsed a C++ 'new' expression (C++ 5.3.4).
1774
///
1775
/// E.g.:
1776
/// @code new (memory) int[size][4] @endcode
1777
/// or
1778
/// @code ::new Foo(23, "hello") @endcode
1779
///
1780
/// \param StartLoc The first location of the expression.
1781
/// \param UseGlobal True if 'new' was prefixed with '::'.
1782
/// \param PlacementLParen Opening paren of the placement arguments.
1783
/// \param PlacementArgs Placement new arguments.
1784
/// \param PlacementRParen Closing paren of the placement arguments.
1785
/// \param TypeIdParens If the type is in parens, the source range.
1786
/// \param D The type to be allocated, as well as array dimensions.
1787
/// \param Initializer The initializing expression or initializer-list, or null
1788
///   if there is none.
1789
ExprResult
1790
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1791
                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1792
                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1793
26.5k
                  Declarator &D, Expr *Initializer) {
1794
26.5k
  Optional<Expr *> ArraySize;
1795
  // If the specified type is an array, unwrap it and save the expression.
1796
26.5k
  if (D.getNumTypeObjects() > 0 &&
1797
26.5k
      
D.getTypeObject(0).Kind == DeclaratorChunk::Array1.56k
) {
1798
1.52k
    DeclaratorChunk &Chunk = D.getTypeObject(0);
1799
1.52k
    if (D.getDeclSpec().hasAutoTypeSpec())
1800
0
      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1801
0
        << D.getSourceRange());
1802
1.52k
    if (Chunk.Arr.hasStatic)
1803
0
      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1804
0
        << D.getSourceRange());
1805
1.52k
    if (!Chunk.Arr.NumElts && 
!Initializer33
)
1806
9
      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1807
9
        << D.getSourceRange());
1808
1809
1.51k
    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1810
1.51k
    D.DropFirstTypeObject();
1811
1.51k
  }
1812
1813
  // Every dimension shall be of constant size.
1814
26.5k
  if (ArraySize) {
1815
1.57k
    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; 
++I55
) {
1816
141
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1817
72
        break;
1818
1819
69
      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1820
69
      if (Expr *NumElts = (Expr *)Array.NumElts) {
1821
69
        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1822
          // FIXME: GCC permits constant folding here. We should either do so consistently
1823
          // or not do so at all, rather than changing behavior in C++14 onwards.
1824
69
          if (getLangOpts().CPlusPlus14) {
1825
            // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1826
            //   shall be a converted constant expression (5.19) of type std::size_t
1827
            //   and shall evaluate to a strictly positive value.
1828
27
            llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1829
27
            Array.NumElts
1830
27
             = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1831
27
                                                CCEK_ArrayBound)
1832
27
                 .get();
1833
42
          } else {
1834
42
            Array.NumElts =
1835
42
                VerifyIntegerConstantExpression(
1836
42
                    NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1837
42
                    .get();
1838
42
          }
1839
69
          if (!Array.NumElts)
1840
14
            return ExprError();
1841
69
        }
1842
69
      }
1843
69
    }
1844
1.51k
  }
1845
1846
26.5k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1847
26.5k
  QualType AllocType = TInfo->getType();
1848
26.5k
  if (D.isInvalidType())
1849
13
    return ExprError();
1850
1851
26.5k
  SourceRange DirectInitRange;
1852
26.5k
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1853
23.1k
    DirectInitRange = List->getSourceRange();
1854
1855
26.5k
  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1856
26.5k
                     PlacementLParen, PlacementArgs, PlacementRParen,
1857
26.5k
                     TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1858
26.5k
                     Initializer);
1859
26.5k
}
1860
1861
static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1862
2.17k
                                       Expr *Init) {
1863
2.17k
  if (!Init)
1864
2.03k
    return true;
1865
144
  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1866
59
    return PLE->getNumExprs() == 0;
1867
85
  if (isa<ImplicitValueInitExpr>(Init))
1868
0
    return true;
1869
85
  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1870
0
    return !CCE->isListInitialization() &&
1871
0
           CCE->getConstructor()->isDefaultConstructor();
1872
85
  else if (Style == CXXNewExpr::ListInit) {
1873
85
    assert(isa<InitListExpr>(Init) &&
1874
85
           "Shouldn't create list CXXConstructExprs for arrays.");
1875
0
    return true;
1876
85
  }
1877
0
  return false;
1878
85
}
1879
1880
bool
1881
2.26M
Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1882
2.26M
  if (!getLangOpts().AlignedAllocationUnavailable)
1883
2.26M
    return false;
1884
479
  if (FD.isDefined())
1885
180
    return false;
1886
299
  Optional<unsigned> AlignmentParam;
1887
299
  if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1888
299
      
AlignmentParam.hasValue()259
)
1889
161
    return true;
1890
138
  return false;
1891
299
}
1892
1893
// Emit a diagnostic if an aligned allocation/deallocation function that is not
1894
// implemented in the standard library is selected.
1895
void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1896
2.26M
                                                SourceLocation Loc) {
1897
2.26M
  if (isUnavailableAlignedAllocationFunction(FD)) {
1898
161
    const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1899
161
    StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1900
161
        getASTContext().getTargetInfo().getPlatformName());
1901
161
    VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1902
1903
161
    OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1904
161
    bool IsDelete = Kind == OO_Delete || 
Kind == OO_Array_Delete105
;
1905
161
    Diag(Loc, diag::err_aligned_allocation_unavailable)
1906
161
        << IsDelete << FD.getType().getAsString() << OSName
1907
161
        << OSVersion.getAsString() << OSVersion.empty();
1908
161
    Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1909
161
  }
1910
2.26M
}
1911
1912
ExprResult
1913
Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1914
                  SourceLocation PlacementLParen,
1915
                  MultiExprArg PlacementArgs,
1916
                  SourceLocation PlacementRParen,
1917
                  SourceRange TypeIdParens,
1918
                  QualType AllocType,
1919
                  TypeSourceInfo *AllocTypeInfo,
1920
                  Optional<Expr *> ArraySize,
1921
                  SourceRange DirectInitRange,
1922
28.8k
                  Expr *Initializer) {
1923
28.8k
  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1924
28.8k
  SourceLocation StartLoc = Range.getBegin();
1925
1926
28.8k
  CXXNewExpr::InitializationStyle initStyle;
1927
28.8k
  if (DirectInitRange.isValid()) {
1928
24.5k
    assert(Initializer && "Have parens but no initializer.");
1929
0
    initStyle = CXXNewExpr::CallInit;
1930
24.5k
  } else 
if (4.31k
Initializer4.31k
&&
isa<InitListExpr>(Initializer)185
)
1931
185
    initStyle = CXXNewExpr::ListInit;
1932
4.13k
  else {
1933
4.13k
    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1934
4.13k
            isa<CXXConstructExpr>(Initializer)) &&
1935
4.13k
           "Initializer expression that cannot have been implicitly created.");
1936
0
    initStyle = CXXNewExpr::NoInit;
1937
4.13k
  }
1938
1939
0
  Expr **Inits = &Initializer;
1940
28.8k
  unsigned NumInits = Initializer ? 
124.7k
:
04.13k
;
1941
28.8k
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1942
24.5k
    assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1943
0
    Inits = List->getExprs();
1944
24.5k
    NumInits = List->getNumExprs();
1945
24.5k
  }
1946
1947
  // C++11 [expr.new]p15:
1948
  //   A new-expression that creates an object of type T initializes that
1949
  //   object as follows:
1950
0
  InitializationKind Kind
1951
      //     - If the new-initializer is omitted, the object is default-
1952
      //       initialized (8.5); if no initialization is performed,
1953
      //       the object has indeterminate value
1954
28.8k
      = initStyle == CXXNewExpr::NoInit
1955
28.8k
            ? 
InitializationKind::CreateDefault(TypeRange.getBegin())4.13k
1956
            //     - Otherwise, the new-initializer is interpreted according to
1957
            //     the
1958
            //       initialization rules of 8.5 for direct-initialization.
1959
28.8k
            : 
initStyle == CXXNewExpr::ListInit24.7k
1960
24.7k
                  ? InitializationKind::CreateDirectList(
1961
185
                        TypeRange.getBegin(), Initializer->getBeginLoc(),
1962
185
                        Initializer->getEndLoc())
1963
24.7k
                  : InitializationKind::CreateDirect(TypeRange.getBegin(),
1964
24.5k
                                                     DirectInitRange.getBegin(),
1965
24.5k
                                                     DirectInitRange.getEnd());
1966
1967
  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1968
28.8k
  auto *Deduced = AllocType->getContainedDeducedType();
1969
28.8k
  if (Deduced && 
isa<DeducedTemplateSpecializationType>(Deduced)71
) {
1970
19
    if (ArraySize)
1971
1
      return ExprError(
1972
1
          Diag(*ArraySize ? 
(*ArraySize)->getExprLoc()0
: TypeRange.getBegin(),
1973
1
               diag::err_deduced_class_template_compound_type)
1974
1
          << /*array*/ 2
1975
1
          << (*ArraySize ? 
(*ArraySize)->getSourceRange()0
: TypeRange));
1976
1977
18
    InitializedEntity Entity
1978
18
      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1979
18
    AllocType = DeduceTemplateSpecializationFromInitializer(
1980
18
        AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1981
18
    if (AllocType.isNull())
1982
0
      return ExprError();
1983
28.8k
  } else if (Deduced) {
1984
52
    bool Braced = (initStyle == CXXNewExpr::ListInit);
1985
52
    if (NumInits == 1) {
1986
49
      if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1987
20
        Inits = p->getInits();
1988
20
        NumInits = p->getNumInits();
1989
20
        Braced = true;
1990
20
      }
1991
49
    }
1992
1993
52
    if (initStyle == CXXNewExpr::NoInit || 
NumInits == 051
)
1994
6
      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1995
6
                       << AllocType << TypeRange);
1996
46
    if (NumInits > 1) {
1997
10
      Expr *FirstBad = Inits[1];
1998
10
      return ExprError(Diag(FirstBad->getBeginLoc(),
1999
10
                            diag::err_auto_new_ctor_multiple_expressions)
2000
10
                       << AllocType << TypeRange);
2001
10
    }
2002
36
    if (Braced && 
!getLangOpts().CPlusPlus177
)
2003
5
      Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2004
5
          << AllocType << TypeRange;
2005
36
    Expr *Deduce = Inits[0];
2006
36
    QualType DeducedType;
2007
36
    if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
2008
1
      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2009
1
                       << AllocType << Deduce->getType()
2010
1
                       << TypeRange << Deduce->getSourceRange());
2011
35
    if (DeducedType.isNull())
2012
1
      return ExprError();
2013
34
    AllocType = DeducedType;
2014
34
  }
2015
2016
  // Per C++0x [expr.new]p5, the type being constructed may be a
2017
  // typedef of an array type.
2018
28.8k
  if (!ArraySize) {
2019
26.6k
    if (const ConstantArrayType *Array
2020
26.6k
                              = Context.getAsConstantArrayType(AllocType)) {
2021
8
      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2022
8
                                         Context.getSizeType(),
2023
8
                                         TypeRange.getEnd());
2024
8
      AllocType = Array->getElementType();
2025
8
    }
2026
26.6k
  }
2027
2028
28.8k
  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2029
61
    return ExprError();
2030
2031
  // In ARC, infer 'retaining' for the allocated
2032
28.7k
  if (getLangOpts().ObjCAutoRefCount &&
2033
28.7k
      
AllocType.getObjCLifetime() == Qualifiers::OCL_None31
&&
2034
28.7k
      
AllocType->isObjCLifetimeType()14
) {
2035
0
    AllocType = Context.getLifetimeQualifiedType(AllocType,
2036
0
                                    AllocType->getObjCARCImplicitLifetime());
2037
0
  }
2038
2039
28.7k
  QualType ResultType = Context.getPointerType(AllocType);
2040
2041
28.7k
  if (ArraySize && 
*ArraySize2.21k
&&
2042
28.7k
      
(*ArraySize)->getType()->isNonOverloadPlaceholderType()2.17k
) {
2043
4
    ExprResult result = CheckPlaceholderExpr(*ArraySize);
2044
4
    if (result.isInvalid()) 
return ExprError()0
;
2045
4
    ArraySize = result.get();
2046
4
  }
2047
  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2048
  //   integral or enumeration type with a non-negative value."
2049
  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2050
  //   enumeration type, or a class type for which a single non-explicit
2051
  //   conversion function to integral or unscoped enumeration type exists.
2052
  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2053
  //   std::size_t.
2054
28.7k
  llvm::Optional<uint64_t> KnownArraySize;
2055
28.7k
  if (ArraySize && 
*ArraySize2.21k
&&
!(*ArraySize)->isTypeDependent()2.17k
) {
2056
2.16k
    ExprResult ConvertedSize;
2057
2.16k
    if (getLangOpts().CPlusPlus14) {
2058
513
      assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2059
2060
0
      ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2061
513
                                                AA_Converting);
2062
2063
513
      if (!ConvertedSize.isInvalid() &&
2064
513
          
(*ArraySize)->getType()->getAs<RecordType>()507
)
2065
        // Diagnose the compatibility of this conversion.
2066
14
        Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2067
14
          << (*ArraySize)->getType() << 0 << "'size_t'";
2068
1.65k
    } else {
2069
1.65k
      class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2070
1.65k
      protected:
2071
1.65k
        Expr *ArraySize;
2072
2073
1.65k
      public:
2074
1.65k
        SizeConvertDiagnoser(Expr *ArraySize)
2075
1.65k
            : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2076
1.65k
              ArraySize(ArraySize) {}
2077
2078
1.65k
        SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2079
1.65k
                                             QualType T) override {
2080
5
          return S.Diag(Loc, diag::err_array_size_not_integral)
2081
5
                   << S.getLangOpts().CPlusPlus11 << T;
2082
5
        }
2083
2084
1.65k
        SemaDiagnosticBuilder diagnoseIncomplete(
2085
1.65k
            Sema &S, SourceLocation Loc, QualType T) override {
2086
0
          return S.Diag(Loc, diag::err_array_size_incomplete_type)
2087
0
                   << T << ArraySize->getSourceRange();
2088
0
        }
2089
2090
1.65k
        SemaDiagnosticBuilder diagnoseExplicitConv(
2091
1.65k
            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2092
1
          return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2093
1
        }
2094
2095
1.65k
        SemaDiagnosticBuilder noteExplicitConv(
2096
1.65k
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2097
1
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2098
1
                   << ConvTy->isEnumeralType() << ConvTy;
2099
1
        }
2100
2101
1.65k
        SemaDiagnosticBuilder diagnoseAmbiguous(
2102
1.65k
            Sema &S, SourceLocation Loc, QualType T) override {
2103
9
          return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2104
9
        }
2105
2106
1.65k
        SemaDiagnosticBuilder noteAmbiguous(
2107
1.65k
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2108
18
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2109
18
                   << ConvTy->isEnumeralType() << ConvTy;
2110
18
        }
2111
2112
1.65k
        SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2113
1.65k
                                                 QualType T,
2114
1.65k
                                                 QualType ConvTy) override {
2115
15
          return S.Diag(Loc,
2116
15
                        S.getLangOpts().CPlusPlus11
2117
15
                          ? 
diag::warn_cxx98_compat_array_size_conversion8
2118
15
                          : 
diag::ext_array_size_conversion7
)
2119
15
                   << T << ConvTy->isEnumeralType() << ConvTy;
2120
15
        }
2121
1.65k
      } SizeDiagnoser(*ArraySize);
2122
2123
1.65k
      ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2124
1.65k
                                                          SizeDiagnoser);
2125
1.65k
    }
2126
2.16k
    if (ConvertedSize.isInvalid())
2127
6
      return ExprError();
2128
2129
2.16k
    ArraySize = ConvertedSize.get();
2130
2.16k
    QualType SizeType = (*ArraySize)->getType();
2131
2132
2.16k
    if (!SizeType->isIntegralOrUnscopedEnumerationType())
2133
14
      return ExprError();
2134
2135
    // C++98 [expr.new]p7:
2136
    //   The expression in a direct-new-declarator shall have integral type
2137
    //   with a non-negative value.
2138
    //
2139
    // Let's see if this is a constant < 0. If so, we reject it out of hand,
2140
    // per CWG1464. Otherwise, if it's not a constant, we must have an
2141
    // unparenthesized array type.
2142
2143
    // We've already performed any required implicit conversion to integer or
2144
    // unscoped enumeration type.
2145
    // FIXME: Per CWG1464, we are required to check the value prior to
2146
    // converting to size_t. This will never find a negative array size in
2147
    // C++14 onwards, because Value is always unsigned here!
2148
2.14k
    if (Optional<llvm::APSInt> Value =
2149
2.14k
            (*ArraySize)->getIntegerConstantExpr(Context)) {
2150
668
      if (Value->isSigned() && 
Value->isNegative()360
) {
2151
4
        return ExprError(Diag((*ArraySize)->getBeginLoc(),
2152
4
                              diag::err_typecheck_negative_array_size)
2153
4
                         << (*ArraySize)->getSourceRange());
2154
4
      }
2155
2156
664
      if (!AllocType->isDependentType()) {
2157
646
        unsigned ActiveSizeBits =
2158
646
            ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
2159
646
        if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2160
9
          return ExprError(
2161
9
              Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2162
9
              << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2163
646
      }
2164
2165
655
      KnownArraySize = Value->getZExtValue();
2166
1.47k
    } else if (TypeIdParens.isValid()) {
2167
      // Can't have dynamic array size when the type-id is in parentheses.
2168
8
      Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2169
8
          << (*ArraySize)->getSourceRange()
2170
8
          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2171
8
          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2172
2173
8
      TypeIdParens = SourceRange();
2174
8
    }
2175
2176
    // Note that we do *not* convert the argument in any way.  It can
2177
    // be signed, larger than size_t, whatever.
2178
2.14k
  }
2179
2180
28.7k
  FunctionDecl *OperatorNew = nullptr;
2181
28.7k
  FunctionDecl *OperatorDelete = nullptr;
2182
28.7k
  unsigned Alignment =
2183
28.7k
      AllocType->isDependentType() ? 
022.8k
:
Context.getTypeAlign(AllocType)5.90k
;
2184
28.7k
  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2185
28.7k
  bool PassAlignment = getLangOpts().AlignedAllocation &&
2186
28.7k
                       
Alignment > NewAlignment1.42k
;
2187
2188
28.7k
  AllocationFunctionScope Scope = UseGlobal ? 
AFS_Global18.7k
:
AFS_Both9.97k
;
2189
28.7k
  if (!AllocType->isDependentType() &&
2190
28.7k
      
!Expr::hasAnyTypeDependentArguments(PlacementArgs)5.90k
&&
2191
28.7k
      FindAllocationFunctions(
2192
5.89k
          StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2193
5.89k
          AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2194
5.89k
          OperatorNew, OperatorDelete))
2195
74
    return ExprError();
2196
2197
  // If this is an array allocation, compute whether the usual array
2198
  // deallocation function for the type has a size_t parameter.
2199
28.6k
  bool UsualArrayDeleteWantsSize = false;
2200
28.6k
  if (ArraySize && 
!AllocType->isDependentType()2.17k
)
2201
1.69k
    UsualArrayDeleteWantsSize =
2202
1.69k
        doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2203
2204
28.6k
  SmallVector<Expr *, 8> AllPlaceArgs;
2205
28.6k
  if (OperatorNew) {
2206
5.82k
    auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2207
5.82k
    VariadicCallType CallType = Proto->isVariadic() ? 
VariadicFunction24
2208
5.82k
                                                    : 
VariadicDoesNotApply5.80k
;
2209
2210
    // We've already converted the placement args, just fill in any default
2211
    // arguments. Skip the first parameter because we don't have a corresponding
2212
    // argument. Skip the second parameter too if we're passing in the
2213
    // alignment; we've already filled it in.
2214
5.82k
    unsigned NumImplicitArgs = PassAlignment ? 
2120
:
15.70k
;
2215
5.82k
    if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2216
5.82k
                               NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2217
5.82k
                               CallType))
2218
1
      return ExprError();
2219
2220
5.82k
    if (!AllPlaceArgs.empty())
2221
1.66k
      PlacementArgs = AllPlaceArgs;
2222
2223
    // We would like to perform some checking on the given `operator new` call,
2224
    // but the PlacementArgs does not contain the implicit arguments,
2225
    // namely allocation size and maybe allocation alignment,
2226
    // so we need to conjure them.
2227
2228
5.82k
    QualType SizeTy = Context.getSizeType();
2229
5.82k
    unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2230
2231
5.82k
    llvm::APInt SingleEltSize(
2232
5.82k
        SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2233
2234
    // How many bytes do we want to allocate here?
2235
5.82k
    llvm::Optional<llvm::APInt> AllocationSize;
2236
5.82k
    if (!ArraySize.hasValue() && 
!AllocType->isDependentType()4.12k
) {
2237
      // For non-array operator new, we only want to allocate one element.
2238
4.12k
      AllocationSize = SingleEltSize;
2239
4.12k
    } else 
if (1.69k
KnownArraySize.hasValue()1.69k
&&
!AllocType->isDependentType()635
) {
2240
      // For array operator new, only deal with static array size case.
2241
635
      bool Overflow;
2242
635
      AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2243
635
                           .umul_ov(SingleEltSize, Overflow);
2244
635
      (void)Overflow;
2245
635
      assert(
2246
635
          !Overflow &&
2247
635
          "Expected that all the overflows would have been handled already.");
2248
635
    }
2249
2250
0
    IntegerLiteral AllocationSizeLiteral(
2251
5.82k
        Context, AllocationSize.getValueOr(llvm::APInt::getZero(SizeTyWidth)),
2252
5.82k
        SizeTy, SourceLocation());
2253
    // Otherwise, if we failed to constant-fold the allocation size, we'll
2254
    // just give up and pass-in something opaque, that isn't a null pointer.
2255
5.82k
    OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2256
5.82k
                                         OK_Ordinary, /*SourceExpr=*/nullptr);
2257
2258
    // Let's synthesize the alignment argument in case we will need it.
2259
    // Since we *really* want to allocate these on stack, this is slightly ugly
2260
    // because there might not be a `std::align_val_t` type.
2261
5.82k
    EnumDecl *StdAlignValT = getStdAlignValT();
2262
5.82k
    QualType AlignValT =
2263
5.82k
        StdAlignValT ? 
Context.getTypeDeclType(StdAlignValT)3.80k
:
SizeTy2.01k
;
2264
5.82k
    IntegerLiteral AlignmentLiteral(
2265
5.82k
        Context,
2266
5.82k
        llvm::APInt(Context.getTypeSize(SizeTy),
2267
5.82k
                    Alignment / Context.getCharWidth()),
2268
5.82k
        SizeTy, SourceLocation());
2269
5.82k
    ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2270
5.82k
                                      CK_IntegralCast, &AlignmentLiteral,
2271
5.82k
                                      VK_PRValue, FPOptionsOverride());
2272
2273
    // Adjust placement args by prepending conjured size and alignment exprs.
2274
5.82k
    llvm::SmallVector<Expr *, 8> CallArgs;
2275
5.82k
    CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2276
5.82k
    CallArgs.emplace_back(AllocationSize.hasValue()
2277
5.82k
                              ? 
static_cast<Expr *>(&AllocationSizeLiteral)4.76k
2278
5.82k
                              : 
&OpaqueAllocationSize1.05k
);
2279
5.82k
    if (PassAlignment)
2280
120
      CallArgs.emplace_back(&DesiredAlignment);
2281
5.82k
    CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2282
2283
5.82k
    DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2284
2285
5.82k
    checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2286
5.82k
              /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2287
2288
    // Warn if the type is over-aligned and is being allocated by (unaligned)
2289
    // global operator new.
2290
5.82k
    if (PlacementArgs.empty() && 
!PassAlignment4.16k
&&
2291
5.82k
        
(4.08k
OperatorNew->isImplicit()4.08k
||
2292
4.08k
         
(2.12k
OperatorNew->getBeginLoc().isValid()2.12k
&&
2293
3.83k
          
getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())2.11k
))) {
2294
3.83k
      if (Alignment > NewAlignment)
2295
39
        Diag(StartLoc, diag::warn_overaligned_type)
2296
39
            << AllocType
2297
39
            << unsigned(Alignment / Context.getCharWidth())
2298
39
            << unsigned(NewAlignment / Context.getCharWidth());
2299
3.83k
    }
2300
5.82k
  }
2301
2302
  // Array 'new' can't have any initializers except empty parentheses.
2303
  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2304
  // dialect distinction.
2305
28.6k
  if (ArraySize && 
!isLegalArrayNewInitializer(initStyle, Initializer)2.17k
) {
2306
20
    SourceRange InitRange(Inits[0]->getBeginLoc(),
2307
20
                          Inits[NumInits - 1]->getEndLoc());
2308
20
    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2309
20
    return ExprError();
2310
20
  }
2311
2312
  // If we can perform the initialization, and we've not already done so,
2313
  // do it now.
2314
28.6k
  if (!AllocType->isDependentType() &&
2315
28.6k
      !Expr::hasAnyTypeDependentArguments(
2316
5.81k
          llvm::makeArrayRef(Inits, NumInits))) {
2317
    // The type we initialize is the complete type, including the array bound.
2318
5.78k
    QualType InitType;
2319
5.78k
    if (KnownArraySize)
2320
619
      InitType = Context.getConstantArrayType(
2321
619
          AllocType,
2322
619
          llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2323
619
                      *KnownArraySize),
2324
619
          *ArraySize, ArrayType::Normal, 0);
2325
5.16k
    else if (ArraySize)
2326
1.05k
      InitType =
2327
1.05k
          Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2328
4.11k
    else
2329
4.11k
      InitType = AllocType;
2330
2331
5.78k
    InitializedEntity Entity
2332
5.78k
      = InitializedEntity::InitializeNew(StartLoc, InitType);
2333
5.78k
    InitializationSequence InitSeq(*this, Entity, Kind,
2334
5.78k
                                   MultiExprArg(Inits, NumInits));
2335
5.78k
    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2336
5.78k
                                          MultiExprArg(Inits, NumInits));
2337
5.78k
    if (FullInit.isInvalid())
2338
66
      return ExprError();
2339
2340
    // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2341
    // we don't want the initialized object to be destructed.
2342
    // FIXME: We should not create these in the first place.
2343
5.72k
    if (CXXBindTemporaryExpr *Binder =
2344
5.72k
            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2345
0
      FullInit = Binder->getSubExpr();
2346
2347
5.72k
    Initializer = FullInit.get();
2348
2349
    // FIXME: If we have a KnownArraySize, check that the array bound of the
2350
    // initializer is no greater than that constant value.
2351
2352
5.72k
    if (ArraySize && 
!*ArraySize1.65k
) {
2353
26
      auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2354
26
      if (CAT) {
2355
        // FIXME: Track that the array size was inferred rather than explicitly
2356
        // specified.
2357
22
        ArraySize = IntegerLiteral::Create(
2358
22
            Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2359
22
      } else {
2360
4
        Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2361
4
            << Initializer->getSourceRange();
2362
4
      }
2363
26
    }
2364
5.72k
  }
2365
2366
  // Mark the new and delete operators as referenced.
2367
28.5k
  if (OperatorNew) {
2368
5.74k
    if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2369
0
      return ExprError();
2370
5.74k
    MarkFunctionReferenced(StartLoc, OperatorNew);
2371
5.74k
  }
2372
28.5k
  if (OperatorDelete) {
2373
3.20k
    if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2374
38
      return ExprError();
2375
3.16k
    MarkFunctionReferenced(StartLoc, OperatorDelete);
2376
3.16k
  }
2377
2378
28.5k
  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2379
28.5k
                            PassAlignment, UsualArrayDeleteWantsSize,
2380
28.5k
                            PlacementArgs, TypeIdParens, ArraySize, initStyle,
2381
28.5k
                            Initializer, ResultType, AllocTypeInfo, Range,
2382
28.5k
                            DirectInitRange);
2383
28.5k
}
2384
2385
/// Checks that a type is suitable as the allocated type
2386
/// in a new-expression.
2387
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2388
28.8k
                              SourceRange R) {
2389
  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2390
  //   abstract class type or array thereof.
2391
28.8k
  if (AllocType->isFunctionType())
2392
0
    return Diag(Loc, diag::err_bad_new_type)
2393
0
      << AllocType << 0 << R;
2394
28.8k
  else if (AllocType->isReferenceType())
2395
4
    return Diag(Loc, diag::err_bad_new_type)
2396
4
      << AllocType << 1 << R;
2397
28.8k
  else if (!AllocType->isDependentType() &&
2398
28.8k
           RequireCompleteSizedType(
2399
5.99k
               Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2400
38
    return true;
2401
28.7k
  else if (RequireNonAbstractType(Loc, AllocType,
2402
28.7k
                                  diag::err_allocation_of_abstract_type))
2403
8
    return true;
2404
28.7k
  else if (AllocType->isVariablyModifiedType())
2405
3
    return Diag(Loc, diag::err_variably_modified_new_type)
2406
3
             << AllocType;
2407
28.7k
  else if (AllocType.getAddressSpace() != LangAS::Default &&
2408
28.7k
           
!getLangOpts().OpenCLCPlusPlus8
)
2409
8
    return Diag(Loc, diag::err_address_space_qualified_new)
2410
8
      << AllocType.getUnqualifiedType()
2411
8
      << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2412
28.7k
  else if (getLangOpts().ObjCAutoRefCount) {
2413
31
    if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2414
0
      QualType BaseAllocType = Context.getBaseElementType(AT);
2415
0
      if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2416
0
          BaseAllocType->isObjCLifetimeType())
2417
0
        return Diag(Loc, diag::err_arc_new_array_without_ownership)
2418
0
          << BaseAllocType;
2419
0
    }
2420
31
  }
2421
2422
28.7k
  return false;
2423
28.8k
}
2424
2425
static bool resolveAllocationOverload(
2426
    Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2427
    bool &PassAlignment, FunctionDecl *&Operator,
2428
6.71k
    OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2429
6.71k
  OverloadCandidateSet Candidates(R.getNameLoc(),
2430
6.71k
                                  OverloadCandidateSet::CSK_Normal);
2431
6.71k
  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2432
29.1k
       Alloc != AllocEnd; 
++Alloc22.4k
) {
2433
    // Even member operator new/delete are implicitly treated as
2434
    // static, so don't use AddMemberCandidate.
2435
22.4k
    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2436
2437
22.4k
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2438
60
      S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2439
60
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
2440
60
                                     Candidates,
2441
60
                                     /*SuppressUserConversions=*/false);
2442
60
      continue;
2443
60
    }
2444
2445
22.3k
    FunctionDecl *Fn = cast<FunctionDecl>(D);
2446
22.3k
    S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2447
22.3k
                           /*SuppressUserConversions=*/false);
2448
22.3k
  }
2449
2450
  // Do the resolution.
2451
6.71k
  OverloadCandidateSet::iterator Best;
2452
6.71k
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2453
6.54k
  case OR_Success: {
2454
    // Got one!
2455
6.54k
    FunctionDecl *FnDecl = Best->Function;
2456
6.54k
    if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2457
6.54k
                                Best->FoundDecl) == Sema::AR_inaccessible)
2458
8
      return true;
2459
2460
6.54k
    Operator = FnDecl;
2461
6.54k
    return false;
2462
6.54k
  }
2463
2464
149
  case OR_No_Viable_Function:
2465
    // C++17 [expr.new]p13:
2466
    //   If no matching function is found and the allocated object type has
2467
    //   new-extended alignment, the alignment argument is removed from the
2468
    //   argument list, and overload resolution is performed again.
2469
149
    if (PassAlignment) {
2470
90
      PassAlignment = false;
2471
90
      AlignArg = Args[1];
2472
90
      Args.erase(Args.begin() + 1);
2473
90
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2474
90
                                       Operator, &Candidates, AlignArg,
2475
90
                                       Diagnose);
2476
90
    }
2477
2478
    // MSVC will fall back on trying to find a matching global operator new
2479
    // if operator new[] cannot be found.  Also, MSVC will leak by not
2480
    // generating a call to operator delete or operator delete[], but we
2481
    // will not replicate that bug.
2482
    // FIXME: Find out how this interacts with the std::align_val_t fallback
2483
    // once MSVC implements it.
2484
59
    if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2485
59
        
S.Context.getLangOpts().MSVCCompat5
) {
2486
4
      R.clear();
2487
4
      R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2488
4
      S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2489
      // FIXME: This will give bad diagnostics pointing at the wrong functions.
2490
4
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2491
4
                                       Operator, /*Candidates=*/nullptr,
2492
4
                                       /*AlignArg=*/nullptr, Diagnose);
2493
4
    }
2494
2495
55
    if (Diagnose) {
2496
      // If this is an allocation of the form 'new (p) X' for some object
2497
      // pointer p (or an expression that will decay to such a pointer),
2498
      // diagnose the missing inclusion of <new>.
2499
48
      if (!R.isClassLookup() && 
Args.size() == 242
&&
2500
48
          
(30
Args[1]->getType()->isObjectPointerType()30
||
2501
30
           
Args[1]->getType()->isArrayType()18
)) {
2502
16
        S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2503
16
            << R.getLookupName() << Range;
2504
        // Listing the candidates is unlikely to be useful; skip it.
2505
16
        return true;
2506
16
      }
2507
2508
      // Finish checking all candidates before we note any. This checking can
2509
      // produce additional diagnostics so can't be interleaved with our
2510
      // emission of notes.
2511
      //
2512
      // For an aligned allocation, separately check the aligned and unaligned
2513
      // candidates with their respective argument lists.
2514
32
      SmallVector<OverloadCandidate*, 32> Cands;
2515
32
      SmallVector<OverloadCandidate*, 32> AlignedCands;
2516
32
      llvm::SmallVector<Expr*, 4> AlignedArgs;
2517
32
      if (AlignedCandidates) {
2518
32
        auto IsAligned = [](OverloadCandidate &C) {
2519
32
          return C.Function->getNumParams() > 1 &&
2520
32
                 
C.Function->getParamDecl(1)->getType()->isAlignValT()24
;
2521
32
        };
2522
16
        auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2523
2524
4
        AlignedArgs.reserve(Args.size() + 1);
2525
4
        AlignedArgs.push_back(Args[0]);
2526
4
        AlignedArgs.push_back(AlignArg);
2527
4
        AlignedArgs.append(Args.begin() + 1, Args.end());
2528
4
        AlignedCands = AlignedCandidates->CompleteCandidates(
2529
4
            S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2530
2531
4
        Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2532
4
                                              R.getNameLoc(), IsUnaligned);
2533
28
      } else {
2534
28
        Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2535
28
                                              R.getNameLoc());
2536
28
      }
2537
2538
32
      S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2539
32
          << R.getLookupName() << Range;
2540
32
      if (AlignedCandidates)
2541
4
        AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2542
4
                                          R.getNameLoc());
2543
32
      Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2544
32
    }
2545
39
    return true;
2546
2547
4
  case OR_Ambiguous:
2548
4
    if (Diagnose) {
2549
4
      Candidates.NoteCandidates(
2550
4
          PartialDiagnosticAt(R.getNameLoc(),
2551
4
                              S.PDiag(diag::err_ovl_ambiguous_call)
2552
4
                                  << R.getLookupName() << Range),
2553
4
          S, OCD_AmbiguousCandidates, Args);
2554
4
    }
2555
4
    return true;
2556
2557
12
  case OR_Deleted: {
2558
12
    if (Diagnose) {
2559
12
      Candidates.NoteCandidates(
2560
12
          PartialDiagnosticAt(R.getNameLoc(),
2561
12
                              S.PDiag(diag::err_ovl_deleted_call)
2562
12
                                  << R.getLookupName() << Range),
2563
12
          S, OCD_AllCandidates, Args);
2564
12
    }
2565
12
    return true;
2566
55
  }
2567
6.71k
  }
2568
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2569
0
}
2570
2571
bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2572
                                   AllocationFunctionScope NewScope,
2573
                                   AllocationFunctionScope DeleteScope,
2574
                                   QualType AllocType, bool IsArray,
2575
                                   bool &PassAlignment, MultiExprArg PlaceArgs,
2576
                                   FunctionDecl *&OperatorNew,
2577
                                   FunctionDecl *&OperatorDelete,
2578
7.66k
                                   bool Diagnose) {
2579
  // --- Choosing an allocation function ---
2580
  // C++ 5.3.4p8 - 14 & 18
2581
  // 1) If looking in AFS_Global scope for allocation functions, only look in
2582
  //    the global scope. Else, if AFS_Class, only look in the scope of the
2583
  //    allocated class. If AFS_Both, look in both.
2584
  // 2) If an array size is given, look for operator new[], else look for
2585
  //   operator new.
2586
  // 3) The first argument is always size_t. Append the arguments from the
2587
  //   placement form.
2588
2589
7.66k
  SmallVector<Expr*, 8> AllocArgs;
2590
7.66k
  AllocArgs.reserve((PassAlignment ? 
2216
:
17.45k
) + PlaceArgs.size());
2591
2592
  // We don't care about the actual value of these arguments.
2593
  // FIXME: Should the Sema create the expression and embed it in the syntax
2594
  // tree? Or should the consumer just recalculate the value?
2595
  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2596
7.66k
  IntegerLiteral Size(
2597
7.66k
      Context, llvm::APInt::getZero(Context.getTargetInfo().getPointerWidth(0)),
2598
7.66k
      Context.getSizeType(), SourceLocation());
2599
7.66k
  AllocArgs.push_back(&Size);
2600
2601
7.66k
  QualType AlignValT = Context.VoidTy;
2602
7.66k
  if (PassAlignment) {
2603
216
    DeclareGlobalNewDelete();
2604
216
    AlignValT = Context.getTypeDeclType(getStdAlignValT());
2605
216
  }
2606
7.66k
  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2607
7.66k
  if (PassAlignment)
2608
216
    AllocArgs.push_back(&Align);
2609
2610
7.66k
  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2611
2612
  // C++ [expr.new]p8:
2613
  //   If the allocated type is a non-array type, the allocation
2614
  //   function's name is operator new and the deallocation function's
2615
  //   name is operator delete. If the allocated type is an array
2616
  //   type, the allocation function's name is operator new[] and the
2617
  //   deallocation function's name is operator delete[].
2618
7.66k
  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2619
7.66k
      IsArray ? 
OO_Array_New1.69k
:
OO_New5.97k
);
2620
2621
7.66k
  QualType AllocElemType = Context.getBaseElementType(AllocType);
2622
2623
  // Find the allocation function.
2624
7.66k
  {
2625
7.66k
    LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2626
2627
    // C++1z [expr.new]p9:
2628
    //   If the new-expression begins with a unary :: operator, the allocation
2629
    //   function's name is looked up in the global scope. Otherwise, if the
2630
    //   allocated type is a class type T or array thereof, the allocation
2631
    //   function's name is looked up in the scope of T.
2632
7.66k
    if (AllocElemType->isRecordType() && 
NewScope != AFS_Global5.30k
)
2633
3.78k
      LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2634
2635
    // We can see ambiguity here if the allocation function is found in
2636
    // multiple base classes.
2637
7.66k
    if (R.isAmbiguous())
2638
0
      return true;
2639
2640
    //   If this lookup fails to find the name, or if the allocated type is not
2641
    //   a class type, the allocation function's name is looked up in the
2642
    //   global scope.
2643
7.66k
    if (R.empty()) {
2644
7.38k
      if (NewScope == AFS_Class)
2645
1.04k
        return true;
2646
2647
6.33k
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
2648
6.33k
    }
2649
2650
6.62k
    if (getLangOpts().OpenCLCPlusPlus && 
R.empty()8
) {
2651
2
      if (PlaceArgs.empty()) {
2652
1
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2653
1
      } else {
2654
1
        Diag(StartLoc, diag::err_openclcxx_placement_new);
2655
1
      }
2656
2
      return true;
2657
2
    }
2658
2659
6.62k
    assert(!R.empty() && "implicitly declared allocation functions not found");
2660
0
    assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2661
2662
    // We do our own custom access checks below.
2663
0
    R.suppressDiagnostics();
2664
2665
6.62k
    if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2666
6.62k
                                  OperatorNew, /*Candidates=*/nullptr,
2667
6.62k
                                  /*AlignArg=*/nullptr, Diagnose))
2668
79
      return true;
2669
6.62k
  }
2670
2671
  // We don't need an operator delete if we're running under -fno-exceptions.
2672
6.54k
  if (!getLangOpts().Exceptions) {
2673
2.71k
    OperatorDelete = nullptr;
2674
2.71k
    return false;
2675
2.71k
  }
2676
2677
  // Note, the name of OperatorNew might have been changed from array to
2678
  // non-array by resolveAllocationOverload.
2679
3.82k
  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2680
3.82k
      OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2681
3.82k
          ? 
OO_Array_Delete1.05k
2682
3.82k
          : 
OO_Delete2.77k
);
2683
2684
  // C++ [expr.new]p19:
2685
  //
2686
  //   If the new-expression begins with a unary :: operator, the
2687
  //   deallocation function's name is looked up in the global
2688
  //   scope. Otherwise, if the allocated type is a class type T or an
2689
  //   array thereof, the deallocation function's name is looked up in
2690
  //   the scope of T. If this lookup fails to find the name, or if
2691
  //   the allocated type is not a class type or array thereof, the
2692
  //   deallocation function's name is looked up in the global scope.
2693
3.82k
  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2694
3.82k
  if (AllocElemType->isRecordType() && 
DeleteScope != AFS_Global2.64k
) {
2695
1.86k
    auto *RD =
2696
1.86k
        cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2697
1.86k
    LookupQualifiedName(FoundDelete, RD);
2698
1.86k
  }
2699
3.82k
  if (FoundDelete.isAmbiguous())
2700
0
    return true; // FIXME: clean up expressions?
2701
2702
  // Filter out any destroying operator deletes. We can't possibly call such a
2703
  // function in this context, because we're handling the case where the object
2704
  // was not successfully constructed.
2705
  // FIXME: This is not covered by the language rules yet.
2706
3.82k
  {
2707
3.82k
    LookupResult::Filter Filter = FoundDelete.makeFilter();
2708
4.01k
    while (Filter.hasNext()) {
2709
194
      auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2710
194
      if (FD && 
FD->isDestroyingOperatorDelete()193
)
2711
16
        Filter.erase();
2712
194
    }
2713
3.82k
    Filter.done();
2714
3.82k
  }
2715
2716
3.82k
  bool FoundGlobalDelete = FoundDelete.empty();
2717
3.82k
  if (FoundDelete.empty()) {
2718
3.69k
    FoundDelete.clear(LookupOrdinaryName);
2719
2720
3.69k
    if (DeleteScope == AFS_Class)
2721
0
      return true;
2722
2723
3.69k
    DeclareGlobalNewDelete();
2724
3.69k
    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2725
3.69k
  }
2726
2727
3.82k
  FoundDelete.suppressDiagnostics();
2728
2729
3.82k
  SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2730
2731
  // Whether we're looking for a placement operator delete is dictated
2732
  // by whether we selected a placement operator new, not by whether
2733
  // we had explicit placement arguments.  This matters for things like
2734
  //   struct A { void *operator new(size_t, int = 0); ... };
2735
  //   A *a = new A()
2736
  //
2737
  // We don't have any definition for what a "placement allocation function"
2738
  // is, but we assume it's any allocation function whose
2739
  // parameter-declaration-clause is anything other than (size_t).
2740
  //
2741
  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2742
  // This affects whether an exception from the constructor of an overaligned
2743
  // type uses the sized or non-sized form of aligned operator delete.
2744
3.82k
  bool isPlacementNew = !PlaceArgs.empty() || 
OperatorNew->param_size() != 12.60k
||
2745
3.82k
                        
OperatorNew->isVariadic()2.53k
;
2746
2747
3.82k
  if (isPlacementNew) {
2748
    // C++ [expr.new]p20:
2749
    //   A declaration of a placement deallocation function matches the
2750
    //   declaration of a placement allocation function if it has the
2751
    //   same number of parameters and, after parameter transformations
2752
    //   (8.3.5), all parameter types except the first are
2753
    //   identical. [...]
2754
    //
2755
    // To perform this comparison, we compute the function type that
2756
    // the deallocation function should have, and use that type both
2757
    // for template argument deduction and for comparison purposes.
2758
1.29k
    QualType ExpectedFunctionType;
2759
1.29k
    {
2760
1.29k
      auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2761
2762
1.29k
      SmallVector<QualType, 4> ArgTypes;
2763
1.29k
      ArgTypes.push_back(Context.VoidPtrTy);
2764
2.66k
      for (unsigned I = 1, N = Proto->getNumParams(); I < N; 
++I1.36k
)
2765
1.36k
        ArgTypes.push_back(Proto->getParamType(I));
2766
2767
1.29k
      FunctionProtoType::ExtProtoInfo EPI;
2768
      // FIXME: This is not part of the standard's rule.
2769
1.29k
      EPI.Variadic = Proto->isVariadic();
2770
2771
1.29k
      ExpectedFunctionType
2772
1.29k
        = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2773
1.29k
    }
2774
2775
1.29k
    for (LookupResult::iterator D = FoundDelete.begin(),
2776
1.29k
                             DEnd = FoundDelete.end();
2777
7.38k
         D != DEnd; 
++D6.08k
) {
2778
6.08k
      FunctionDecl *Fn = nullptr;
2779
6.08k
      if (FunctionTemplateDecl *FnTmpl =
2780
6.08k
              dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2781
        // Perform template argument deduction to try to match the
2782
        // expected function type.
2783
36
        TemplateDeductionInfo Info(StartLoc);
2784
36
        if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2785
36
                                    Info))
2786
17
          continue;
2787
36
      } else
2788
6.05k
        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2789
2790
6.06k
      if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2791
6.06k
                                                  ExpectedFunctionType,
2792
6.06k
                                                  /*AdjustExcpetionSpec*/true),
2793
6.06k
                              ExpectedFunctionType))
2794
1.21k
        Matches.push_back(std::make_pair(D.getPair(), Fn));
2795
6.06k
    }
2796
2797
1.29k
    if (getLangOpts().CUDA)
2798
0
      EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2799
2.52k
  } else {
2800
    // C++1y [expr.new]p22:
2801
    //   For a non-placement allocation function, the normal deallocation
2802
    //   function lookup is used
2803
    //
2804
    // Per [expr.delete]p10, this lookup prefers a member operator delete
2805
    // without a size_t argument, but prefers a non-member operator delete
2806
    // with a size_t where possible (which it always is in this case).
2807
2.52k
    llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2808
2.52k
    UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2809
2.52k
        *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2810
2.52k
        /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2811
2.52k
        &BestDeallocFns);
2812
2.52k
    if (Selected)
2813
2.52k
      Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2814
1
    else {
2815
      // If we failed to select an operator, all remaining functions are viable
2816
      // but ambiguous.
2817
1
      for (auto Fn : BestDeallocFns)
2818
0
        Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2819
1
    }
2820
2.52k
  }
2821
2822
  // C++ [expr.new]p20:
2823
  //   [...] If the lookup finds a single matching deallocation
2824
  //   function, that function will be called; otherwise, no
2825
  //   deallocation function will be called.
2826
3.82k
  if (Matches.size() == 1) {
2827
3.74k
    OperatorDelete = Matches[0].second;
2828
2829
    // C++1z [expr.new]p23:
2830
    //   If the lookup finds a usual deallocation function (3.7.4.2)
2831
    //   with a parameter of type std::size_t and that function, considered
2832
    //   as a placement deallocation function, would have been
2833
    //   selected as a match for the allocation function, the program
2834
    //   is ill-formed.
2835
3.74k
    if (getLangOpts().CPlusPlus11 && 
isPlacementNew3.65k
&&
2836
3.74k
        
isNonPlacementDeallocationFunction(*this, OperatorDelete)1.20k
) {
2837
132
      UsualDeallocFnInfo Info(*this,
2838
132
                              DeclAccessPair::make(OperatorDelete, AS_public));
2839
      // Core issue, per mail to core reflector, 2016-10-09:
2840
      //   If this is a member operator delete, and there is a corresponding
2841
      //   non-sized member operator delete, this isn't /really/ a sized
2842
      //   deallocation function, it just happens to have a size_t parameter.
2843
132
      bool IsSizedDelete = Info.HasSizeT;
2844
132
      if (IsSizedDelete && 
!FoundGlobalDelete12
) {
2845
11
        auto NonSizedDelete =
2846
11
            resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2847
11
                                        /*WantAlign*/Info.HasAlignValT);
2848
11
        if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2849
11
            
NonSizedDelete.HasAlignValT == Info.HasAlignValT3
)
2850
3
          IsSizedDelete = false;
2851
11
      }
2852
2853
132
      if (IsSizedDelete) {
2854
9
        SourceRange R = PlaceArgs.empty()
2855
9
                            ? 
SourceRange()0
2856
9
                            : SourceRange(PlaceArgs.front()->getBeginLoc(),
2857
9
                                          PlaceArgs.back()->getEndLoc());
2858
9
        Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2859
9
        if (!OperatorDelete->isImplicit())
2860
9
          Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2861
9
              << DeleteName;
2862
9
      }
2863
132
    }
2864
2865
3.74k
    CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2866
3.74k
                          Matches[0].first);
2867
3.74k
  } else 
if (81
!Matches.empty()81
) {
2868
    // We found multiple suitable operators. Per [expr.new]p20, that means we
2869
    // call no 'operator delete' function, but we should at least warn the user.
2870
    // FIXME: Suppress this warning if the construction cannot throw.
2871
0
    Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2872
0
      << DeleteName << AllocElemType;
2873
2874
0
    for (auto &Match : Matches)
2875
0
      Diag(Match.second->getLocation(),
2876
0
           diag::note_member_declared_here) << DeleteName;
2877
0
  }
2878
2879
3.82k
  return false;
2880
3.82k
}
2881
2882
/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2883
/// delete. These are:
2884
/// @code
2885
///   // C++03:
2886
///   void* operator new(std::size_t) throw(std::bad_alloc);
2887
///   void* operator new[](std::size_t) throw(std::bad_alloc);
2888
///   void operator delete(void *) throw();
2889
///   void operator delete[](void *) throw();
2890
///   // C++11:
2891
///   void* operator new(std::size_t);
2892
///   void* operator new[](std::size_t);
2893
///   void operator delete(void *) noexcept;
2894
///   void operator delete[](void *) noexcept;
2895
///   // C++1y:
2896
///   void* operator new(std::size_t);
2897
///   void* operator new[](std::size_t);
2898
///   void operator delete(void *) noexcept;
2899
///   void operator delete[](void *) noexcept;
2900
///   void operator delete(void *, std::size_t) noexcept;
2901
///   void operator delete[](void *, std::size_t) noexcept;
2902
/// @endcode
2903
/// Note that the placement and nothrow forms of new are *not* implicitly
2904
/// declared. Their use requires including \<new\>.
2905
55.6k
void Sema::DeclareGlobalNewDelete() {
2906
55.6k
  if (GlobalNewDeleteDeclared)
2907
53.1k
    return;
2908
2909
  // The implicitly declared new and delete operators
2910
  // are not supported in OpenCL.
2911
2.42k
  if (getLangOpts().OpenCLCPlusPlus)
2912
19
    return;
2913
2914
  // C++ [basic.std.dynamic]p2:
2915
  //   [...] The following allocation and deallocation functions (18.4) are
2916
  //   implicitly declared in global scope in each translation unit of a
2917
  //   program
2918
  //
2919
  //     C++03:
2920
  //     void* operator new(std::size_t) throw(std::bad_alloc);
2921
  //     void* operator new[](std::size_t) throw(std::bad_alloc);
2922
  //     void  operator delete(void*) throw();
2923
  //     void  operator delete[](void*) throw();
2924
  //     C++11:
2925
  //     void* operator new(std::size_t);
2926
  //     void* operator new[](std::size_t);
2927
  //     void  operator delete(void*) noexcept;
2928
  //     void  operator delete[](void*) noexcept;
2929
  //     C++1y:
2930
  //     void* operator new(std::size_t);
2931
  //     void* operator new[](std::size_t);
2932
  //     void  operator delete(void*) noexcept;
2933
  //     void  operator delete[](void*) noexcept;
2934
  //     void  operator delete(void*, std::size_t) noexcept;
2935
  //     void  operator delete[](void*, std::size_t) noexcept;
2936
  //
2937
  //   These implicit declarations introduce only the function names operator
2938
  //   new, operator new[], operator delete, operator delete[].
2939
  //
2940
  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2941
  // "std" or "bad_alloc" as necessary to form the exception specification.
2942
  // However, we do not make these implicit declarations visible to name
2943
  // lookup.
2944
2.41k
  if (!StdBadAlloc && 
!getLangOpts().CPlusPlus111.69k
) {
2945
    // The "std::bad_alloc" class has not yet been declared, so build it
2946
    // implicitly.
2947
131
    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2948
131
                                        getOrCreateStdNamespace(),
2949
131
                                        SourceLocation(), SourceLocation(),
2950
131
                                      &PP.getIdentifierTable().get("bad_alloc"),
2951
131
                                        nullptr);
2952
131
    getStdBadAlloc()->setImplicit(true);
2953
131
  }
2954
2.41k
  if (!StdAlignValT && 
getLangOpts().AlignedAllocation1.77k
) {
2955
    // The "std::align_val_t" enum class has not yet been declared, so build it
2956
    // implicitly.
2957
261
    auto *AlignValT = EnumDecl::Create(
2958
261
        Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2959
261
        &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2960
261
    AlignValT->setIntegerType(Context.getSizeType());
2961
261
    AlignValT->setPromotionType(Context.getSizeType());
2962
261
    AlignValT->setImplicit(true);
2963
261
    StdAlignValT = AlignValT;
2964
261
  }
2965
2966
2.41k
  GlobalNewDeleteDeclared = true;
2967
2968
2.41k
  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2969
2.41k
  QualType SizeT = Context.getSizeType();
2970
2971
2.41k
  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2972
9.64k
                                              QualType Return, QualType Param) {
2973
9.64k
    llvm::SmallVector<QualType, 3> Params;
2974
9.64k
    Params.push_back(Param);
2975
2976
    // Create up to four variants of the function (sized/aligned).
2977
9.64k
    bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2978
9.64k
                           
(116
Kind == OO_Delete116
||
Kind == OO_Array_Delete87
);
2979
9.64k
    bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2980
2981
9.64k
    int NumSizeVariants = (HasSizedVariant ? 
258
:
19.58k
);
2982
9.64k
    int NumAlignVariants = (HasAlignedVariant ? 
21.24k
:
18.40k
);
2983
19.3k
    for (int Sized = 0; Sized < NumSizeVariants; 
++Sized9.69k
) {
2984
9.69k
      if (Sized)
2985
58
        Params.push_back(SizeT);
2986
2987
20.6k
      for (int Aligned = 0; Aligned < NumAlignVariants; 
++Aligned10.9k
) {
2988
10.9k
        if (Aligned)
2989
1.27k
          Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2990
2991
10.9k
        DeclareGlobalAllocationFunction(
2992
10.9k
            Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2993
2994
10.9k
        if (Aligned)
2995
1.27k
          Params.pop_back();
2996
10.9k
      }
2997
9.69k
    }
2998
9.64k
  };
2999
3000
2.41k
  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3001
2.41k
  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3002
2.41k
  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3003
2.41k
  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3004
2.41k
}
3005
3006
/// DeclareGlobalAllocationFunction - Declares a single implicit global
3007
/// allocation function if it doesn't already exist.
3008
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3009
                                           QualType Return,
3010
10.9k
                                           ArrayRef<QualType> Params) {
3011
10.9k
  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3012
3013
  // Check if this function is already declared.
3014
10.9k
  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3015
10.9k
  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3016
12.5k
       Alloc != AllocEnd; 
++Alloc1.55k
) {
3017
    // Only look at non-template functions, as it is the predefined,
3018
    // non-templated allocation function we are trying to declare here.
3019
2.23k
    if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3020
2.23k
      if (Func->getNumParams() == Params.size()) {
3021
708
        llvm::SmallVector<QualType, 3> FuncParams;
3022
708
        for (auto *P : Func->parameters())
3023
774
          FuncParams.push_back(
3024
774
              Context.getCanonicalType(P->getType().getUnqualifiedType()));
3025
708
        if (llvm::makeArrayRef(FuncParams) == Params) {
3026
          // Make the function visible to name lookup, even if we found it in
3027
          // an unimported module. It either is an implicitly-declared global
3028
          // allocation function, or is suppressing that function.
3029
674
          Func->setVisibleDespiteOwningModule();
3030
674
          return;
3031
674
        }
3032
708
      }
3033
2.23k
    }
3034
2.23k
  }
3035
3036
10.2k
  FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3037
10.2k
      /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3038
3039
10.2k
  QualType BadAllocType;
3040
10.2k
  bool HasBadAllocExceptionSpec
3041
10.2k
    = (Name.getCXXOverloadedOperator() == OO_New ||
3042
10.2k
       
Name.getCXXOverloadedOperator() == OO_Array_New7.74k
);
3043
10.2k
  if (HasBadAllocExceptionSpec) {
3044
5.10k
    if (!getLangOpts().CPlusPlus11) {
3045
272
      BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3046
272
      assert(StdBadAlloc && "Must have std::bad_alloc declared");
3047
0
      EPI.ExceptionSpec.Type = EST_Dynamic;
3048
272
      EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
3049
272
    }
3050
5.10k
    if (getLangOpts().NewInfallible) {
3051
4
      EPI.ExceptionSpec.Type = EST_DynamicNone;
3052
4
    }
3053
5.19k
  } else {
3054
5.19k
    EPI.ExceptionSpec =
3055
5.19k
        getLangOpts().CPlusPlus11 ? 
EST_BasicNoexcept4.92k
:
EST_DynamicNone272
;
3056
5.19k
  }
3057
3058
10.7k
  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3059
10.7k
    QualType FnType = Context.getFunctionType(Return, Params, EPI);
3060
10.7k
    FunctionDecl *Alloc = FunctionDecl::Create(
3061
10.7k
        Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3062
10.7k
        /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3063
10.7k
        true);
3064
10.7k
    Alloc->setImplicit();
3065
    // Global allocation functions should always be visible.
3066
10.7k
    Alloc->setVisibleDespiteOwningModule();
3067
3068
10.7k
    if (HasBadAllocExceptionSpec && 
getLangOpts().NewInfallible5.33k
)
3069
4
      Alloc->addAttr(
3070
4
          ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3071
3072
10.7k
    Alloc->addAttr(VisibilityAttr::CreateImplicit(
3073
10.7k
        Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3074
10.7k
                     ? 
VisibilityAttr::Hidden0
3075
10.7k
                     : VisibilityAttr::Default));
3076
3077
10.7k
    llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3078
12.1k
    for (QualType T : Params) {
3079
12.1k
      ParamDecls.push_back(ParmVarDecl::Create(
3080
12.1k
          Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3081
12.1k
          /*TInfo=*/nullptr, SC_None, nullptr));
3082
12.1k
      ParamDecls.back()->setImplicit();
3083
12.1k
    }
3084
10.7k
    Alloc->setParams(ParamDecls);
3085
10.7k
    if (ExtraAttr)
3086
904
      Alloc->addAttr(ExtraAttr);
3087
10.7k
    AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3088
10.7k
    Context.getTranslationUnitDecl()->addDecl(Alloc);
3089
10.7k
    IdResolver.tryAddTopLevelDecl(Alloc, Name);
3090
10.7k
  };
3091
3092
10.2k
  if (!LangOpts.CUDA)
3093
9.84k
    CreateAllocationFunctionDecl(nullptr);
3094
452
  else {
3095
    // Host and device get their own declaration so each can be
3096
    // defined or re-declared independently.
3097
452
    CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3098
452
    CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3099
452
  }
3100
10.2k
}
3101
3102
FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3103
                                                  bool CanProvideSize,
3104
                                                  bool Overaligned,
3105
5.24k
                                                  DeclarationName Name) {
3106
5.24k
  DeclareGlobalNewDelete();
3107
3108
5.24k
  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3109
5.24k
  LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3110
3111
  // FIXME: It's possible for this to result in ambiguity, through a
3112
  // user-declared variadic operator delete or the enable_if attribute. We
3113
  // should probably not consider those cases to be usual deallocation
3114
  // functions. But for now we just make an arbitrary choice in that case.
3115
5.24k
  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3116
5.24k
                                            Overaligned);
3117
5.24k
  assert(Result.FD && "operator delete missing from global scope?");
3118
0
  return Result.FD;
3119
5.24k
}
3120
3121
FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3122
1.96k
                                                          CXXRecordDecl *RD) {
3123
1.96k
  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3124
3125
1.96k
  FunctionDecl *OperatorDelete = nullptr;
3126
1.96k
  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3127
49
    return nullptr;
3128
1.91k
  if (OperatorDelete)
3129
62
    return OperatorDelete;
3130
3131
  // If there's no class-specific operator delete, look up the global
3132
  // non-array delete.
3133
1.85k
  return FindUsualDeallocationFunction(
3134
1.85k
      Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3135
1.85k
      Name);
3136
1.91k
}
3137
3138
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3139
                                    DeclarationName Name,
3140
5.72k
                                    FunctionDecl *&Operator, bool Diagnose) {
3141
5.72k
  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3142
  // Try to find operator delete/operator delete[] in class scope.
3143
5.72k
  LookupQualifiedName(Found, RD);
3144
3145
5.72k
  if (Found.isAmbiguous())
3146
10
    return true;
3147
3148
5.71k
  Found.suppressDiagnostics();
3149
3150
5.71k
  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3151
3152
  // C++17 [expr.delete]p10:
3153
  //   If the deallocation functions have class scope, the one without a
3154
  //   parameter of type std::size_t is selected.
3155
5.71k
  llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3156
5.71k
  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3157
5.71k
                              /*WantAlign*/ Overaligned, &Matches);
3158
3159
  // If we could find an overload, use it.
3160
5.71k
  if (Matches.size() == 1) {
3161
362
    Operator = cast<CXXMethodDecl>(Matches[0].FD);
3162
3163
    // FIXME: DiagnoseUseOfDecl?
3164
362
    if (Operator->isDeleted()) {
3165
69
      if (Diagnose) {
3166
66
        Diag(StartLoc, diag::err_deleted_function_use);
3167
66
        NoteDeletedFunction(Operator);
3168
66
      }
3169
69
      return true;
3170
69
    }
3171
3172
293
    if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3173
293
                              Matches[0].Found, Diagnose) == AR_inaccessible)
3174
8
      return true;
3175
3176
285
    return false;
3177
293
  }
3178
3179
  // We found multiple suitable operators; complain about the ambiguity.
3180
  // FIXME: The standard doesn't say to do this; it appears that the intent
3181
  // is that this should never happen.
3182
5.34k
  if (!Matches.empty()) {
3183
4
    if (Diagnose) {
3184
4
      Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3185
4
        << Name << RD;
3186
4
      for (auto &Match : Matches)
3187
8
        Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3188
4
    }
3189
4
    return true;
3190
4
  }
3191
3192
  // We did find operator delete/operator delete[] declarations, but
3193
  // none of them were suitable.
3194
5.34k
  if (!Found.empty()) {
3195
81
    if (Diagnose) {
3196
26
      Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3197
26
        << Name << RD;
3198
3199
26
      for (NamedDecl *D : Found)
3200
30
        Diag(D->getUnderlyingDecl()->getLocation(),
3201
30
             diag::note_member_declared_here) << Name;
3202
26
    }
3203
81
    return true;
3204
81
  }
3205
3206
5.26k
  Operator = nullptr;
3207
5.26k
  return false;
3208
5.34k
}
3209
3210
namespace {
3211
/// Checks whether delete-expression, and new-expression used for
3212
///  initializing deletee have the same array form.
3213
class MismatchingNewDeleteDetector {
3214
public:
3215
  enum MismatchResult {
3216
    /// Indicates that there is no mismatch or a mismatch cannot be proven.
3217
    NoMismatch,
3218
    /// Indicates that variable is initialized with mismatching form of \a new.
3219
    VarInitMismatches,
3220
    /// Indicates that member is initialized with mismatching form of \a new.
3221
    MemberInitMismatches,
3222
    /// Indicates that 1 or more constructors' definitions could not been
3223
    /// analyzed, and they will be checked again at the end of translation unit.
3224
    AnalyzeLater
3225
  };
3226
3227
  /// \param EndOfTU True, if this is the final analysis at the end of
3228
  /// translation unit. False, if this is the initial analysis at the point
3229
  /// delete-expression was encountered.
3230
  explicit MismatchingNewDeleteDetector(bool EndOfTU)
3231
      : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3232
7.74k
        HasUndefinedConstructors(false) {}
3233
3234
  /// Checks whether pointee of a delete-expression is initialized with
3235
  /// matching form of new-expression.
3236
  ///
3237
  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3238
  /// point where delete-expression is encountered, then a warning will be
3239
  /// issued immediately. If return value is \c AnalyzeLater at the point where
3240
  /// delete-expression is seen, then member will be analyzed at the end of
3241
  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3242
  /// couldn't be analyzed. If at least one constructor initializes the member
3243
  /// with matching type of new, the return value is \c NoMismatch.
3244
  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3245
  /// Analyzes a class member.
3246
  /// \param Field Class member to analyze.
3247
  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3248
  /// for deleting the \p Field.
3249
  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3250
  FieldDecl *Field;
3251
  /// List of mismatching new-expressions used for initialization of the pointee
3252
  llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3253
  /// Indicates whether delete-expression was in array form.
3254
  bool IsArrayForm;
3255
3256
private:
3257
  const bool EndOfTU;
3258
  /// Indicates that there is at least one constructor without body.
3259
  bool HasUndefinedConstructors;
3260
  /// Returns \c CXXNewExpr from given initialization expression.
3261
  /// \param E Expression used for initializing pointee in delete-expression.
3262
  /// E can be a single-element \c InitListExpr consisting of new-expression.
3263
  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3264
  /// Returns whether member is initialized with mismatching form of
3265
  /// \c new either by the member initializer or in-class initialization.
3266
  ///
3267
  /// If bodies of all constructors are not visible at the end of translation
3268
  /// unit or at least one constructor initializes member with the matching
3269
  /// form of \c new, mismatch cannot be proven, and this function will return
3270
  /// \c NoMismatch.
3271
  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3272
  /// Returns whether variable is initialized with mismatching form of
3273
  /// \c new.
3274
  ///
3275
  /// If variable is initialized with matching form of \c new or variable is not
3276
  /// initialized with a \c new expression, this function will return true.
3277
  /// If variable is initialized with mismatching form of \c new, returns false.
3278
  /// \param D Variable to analyze.
3279
  bool hasMatchingVarInit(const DeclRefExpr *D);
3280
  /// Checks whether the constructor initializes pointee with mismatching
3281
  /// form of \c new.
3282
  ///
3283
  /// Returns true, if member is initialized with matching form of \c new in
3284
  /// member initializer list. Returns false, if member is initialized with the
3285
  /// matching form of \c new in this constructor's initializer or given
3286
  /// constructor isn't defined at the point where delete-expression is seen, or
3287
  /// member isn't initialized by the constructor.
3288
  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3289
  /// Checks whether member is initialized with matching form of
3290
  /// \c new in member initializer list.
3291
  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3292
  /// Checks whether member is initialized with mismatching form of \c new by
3293
  /// in-class initializer.
3294
  MismatchResult analyzeInClassInitializer();
3295
};
3296
}
3297
3298
MismatchingNewDeleteDetector::MismatchResult
3299
7.17k
MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3300
7.17k
  NewExprs.clear();
3301
7.17k
  assert(DE && "Expected delete-expression");
3302
0
  IsArrayForm = DE->isArrayForm();
3303
7.17k
  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3304
7.17k
  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3305
1.71k
    return analyzeMemberExpr(ME);
3306
5.45k
  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3307
3.20k
    if (!hasMatchingVarInit(D))
3308
16
      return VarInitMismatches;
3309
3.20k
  }
3310
5.44k
  return NoMismatch;
3311
7.17k
}
3312
3313
const CXXNewExpr *
3314
4.28k
MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3315
4.28k
  assert(E != nullptr && "Expected a valid initializer expression");
3316
0
  E = E->IgnoreParenImpCasts();
3317
4.28k
  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3318
18
    if (ILE->getNumInits() == 1)
3319
18
      E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3320
18
  }
3321
3322
4.28k
  return dyn_cast_or_null<const CXXNewExpr>(E);
3323
4.28k
}
3324
3325
bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3326
12.7k
    const CXXCtorInitializer *CI) {
3327
12.7k
  const CXXNewExpr *NE = nullptr;
3328
12.7k
  if (Field == CI->getMember() &&
3329
12.7k
      
(NE = getNewExprFromInitListOrExpr(CI->getInit()))2.77k
) {
3330
60
    if (NE->isArray() == IsArrayForm)
3331
28
      return true;
3332
32
    else
3333
32
      NewExprs.push_back(NE);
3334
60
  }
3335
12.7k
  return false;
3336
12.7k
}
3337
3338
bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3339
5.63k
    const CXXConstructorDecl *CD) {
3340
5.63k
  if (CD->isImplicit())
3341
106
    return false;
3342
5.52k
  const FunctionDecl *Definition = CD;
3343
5.52k
  if (!CD->isThisDeclarationADefinition() && 
!CD->isDefined(Definition)2.16k
) {
3344
1.14k
    HasUndefinedConstructors = true;
3345
1.14k
    return EndOfTU;
3346
1.14k
  }
3347
12.7k
  
for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits())4.38k
{
3348
12.7k
    if (hasMatchingNewInCtorInit(CI))
3349
28
      return true;
3350
12.7k
  }
3351
4.35k
  return false;
3352
4.38k
}
3353
3354
MismatchingNewDeleteDetector::MismatchResult
3355
24
MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3356
24
  assert(Field != nullptr && "This should be called only for members");
3357
0
  const Expr *InitExpr = Field->getInClassInitializer();
3358
24
  if (!InitExpr)
3359
8
    return EndOfTU ? 
NoMismatch4
:
AnalyzeLater4
;
3360
16
  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3361
10
    if (NE->isArray() != IsArrayForm) {
3362
8
      NewExprs.push_back(NE);
3363
8
      return MemberInitMismatches;
3364
8
    }
3365
10
  }
3366
8
  return NoMismatch;
3367
16
}
3368
3369
MismatchingNewDeleteDetector::MismatchResult
3370
MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3371
2.28k
                                           bool DeleteWasArrayForm) {
3372
2.28k
  assert(Field != nullptr && "Analysis requires a valid class member.");
3373
0
  this->Field = Field;
3374
2.28k
  IsArrayForm = DeleteWasArrayForm;
3375
2.28k
  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3376
5.63k
  for (const auto *CD : RD->ctors()) {
3377
5.63k
    if (hasMatchingNewInCtor(CD))
3378
577
      return NoMismatch;
3379
5.63k
  }
3380
1.70k
  if (HasUndefinedConstructors)
3381
569
    return EndOfTU ? 
NoMismatch0
: AnalyzeLater;
3382
1.14k
  if (!NewExprs.empty())
3383
12
    return MemberInitMismatches;
3384
1.12k
  return Field->hasInClassInitializer() ? 
analyzeInClassInitializer()24
3385
1.12k
                                        : 
NoMismatch1.10k
;
3386
1.14k
}
3387
3388
MismatchingNewDeleteDetector::MismatchResult
3389
1.71k
MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3390
1.71k
  assert(ME != nullptr && "Expected a member expression");
3391
1.71k
  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3392
1.71k
    return analyzeField(F, IsArrayForm);
3393
2
  return NoMismatch;
3394
1.71k
}
3395
3396
3.20k
bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3397
3.20k
  const CXXNewExpr *NE = nullptr;
3398
3.20k
  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3399
3.20k
    if (VD->hasInit() && 
(NE = getNewExprFromInitListOrExpr(VD->getInit()))1.49k
&&
3400
3.20k
        
NE->isArray() != IsArrayForm1.32k
) {
3401
16
      NewExprs.push_back(NE);
3402
16
    }
3403
3.20k
  }
3404
3.20k
  return NewExprs.empty();
3405
3.20k
}
3406
3407
static void
3408
DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3409
36
                            const MismatchingNewDeleteDetector &Detector) {
3410
36
  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3411
36
  FixItHint H;
3412
36
  if (!Detector.IsArrayForm)
3413
27
    H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3414
9
  else {
3415
9
    SourceLocation RSquare = Lexer::findLocationAfterToken(
3416
9
        DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3417
9
        SemaRef.getLangOpts(), true);
3418
9
    if (RSquare.isValid())
3419
7
      H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3420
9
  }
3421
36
  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3422
36
      << Detector.IsArrayForm << H;
3423
3424
36
  for (const auto *NE : Detector.NewExprs)
3425
48
    SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3426
48
        << Detector.IsArrayForm;
3427
36
}
3428
3429
7.28k
void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3430
7.28k
  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3431
110
    return;
3432
7.17k
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3433
7.17k
  switch (Detector.analyzeDeleteExpr(DE)) {
3434
16
  case MismatchingNewDeleteDetector::VarInitMismatches:
3435
24
  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3436
24
    DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3437
24
    break;
3438
16
  }
3439
573
  case MismatchingNewDeleteDetector::AnalyzeLater: {
3440
573
    DeleteExprs[Detector.Field].push_back(
3441
573
        std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3442
573
    break;
3443
16
  }
3444
6.57k
  case MismatchingNewDeleteDetector::NoMismatch:
3445
6.57k
    break;
3446
7.17k
  }
3447
7.17k
}
3448
3449
void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3450
573
                                     bool DeleteWasArrayForm) {
3451
573
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3452
573
  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3453
0
  case MismatchingNewDeleteDetector::VarInitMismatches:
3454
0
    llvm_unreachable("This analysis should have been done for class members.");
3455
0
  case MismatchingNewDeleteDetector::AnalyzeLater:
3456
0
    llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3457
0
                     "translation unit.");
3458
12
  case MismatchingNewDeleteDetector::MemberInitMismatches:
3459
12
    DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3460
12
    break;
3461
561
  case MismatchingNewDeleteDetector::NoMismatch:
3462
561
    break;
3463
573
  }
3464
573
}
3465
3466
/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3467
/// @code ::delete ptr; @endcode
3468
/// or
3469
/// @code delete [] ptr; @endcode
3470
ExprResult
3471
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3472
7.41k
                     bool ArrayForm, Expr *ExE) {
3473
  // C++ [expr.delete]p1:
3474
  //   The operand shall have a pointer type, or a class type having a single
3475
  //   non-explicit conversion function to a pointer type. The result has type
3476
  //   void.
3477
  //
3478
  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3479
3480
7.41k
  ExprResult Ex = ExE;
3481
7.41k
  FunctionDecl *OperatorDelete = nullptr;
3482
7.41k
  bool ArrayFormAsWritten = ArrayForm;
3483
7.41k
  bool UsualArrayDeleteWantsSize = false;
3484
3485
7.41k
  if (!Ex.get()->isTypeDependent()) {
3486
    // Perform lvalue-to-rvalue cast, if needed.
3487
3.03k
    Ex = DefaultLvalueConversion(Ex.get());
3488
3.03k
    if (Ex.isInvalid())
3489
4
      return ExprError();
3490
3491
3.03k
    QualType Type = Ex.get()->getType();
3492
3493
3.03k
    class DeleteConverter : public ContextualImplicitConverter {
3494
3.03k
    public:
3495
3.03k
      DeleteConverter() : ContextualImplicitConverter(false, true) {}
3496
3497
6.19k
      bool match(QualType ConvType) override {
3498
        // FIXME: If we have an operator T* and an operator void*, we must pick
3499
        // the operator T*.
3500
6.19k
        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3501
6.06k
          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3502
6.04k
            return true;
3503
143
        return false;
3504
6.19k
      }
3505
3506
3.03k
      SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3507
3.03k
                                            QualType T) override {
3508
24
        return S.Diag(Loc, diag::err_delete_operand) << T;
3509
24
      }
3510
3511
3.03k
      SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3512
3.03k
                                               QualType T) override {
3513
4
        return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3514
4
      }
3515
3516
3.03k
      SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3517
3.03k
                                                 QualType T,
3518
3.03k
                                                 QualType ConvTy) override {
3519
2
        return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3520
2
      }
3521
3522
3.03k
      SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3523
3.03k
                                             QualType ConvTy) override {
3524
2
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3525
2
          << ConvTy;
3526
2
      }
3527
3528
3.03k
      SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3529
3.03k
                                              QualType T) override {
3530
12
        return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3531
12
      }
3532
3533
3.03k
      SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3534
3.03k
                                          QualType ConvTy) override {
3535
24
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3536
24
          << ConvTy;
3537
24
      }
3538
3539
3.03k
      SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3540
3.03k
                                               QualType T,
3541
3.03k
                                               QualType ConvTy) override {
3542
0
        llvm_unreachable("conversion functions are permitted");
3543
0
      }
3544
3.03k
    } Converter;
3545
3546
3.03k
    Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3547
3.03k
    if (Ex.isInvalid())
3548
0
      return ExprError();
3549
3.03k
    Type = Ex.get()->getType();
3550
3.03k
    if (!Converter.match(Type))
3551
      // FIXME: PerformContextualImplicitConversion should return ExprError
3552
      //        itself in this case.
3553
40
      return ExprError();
3554
3555
2.99k
    QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3556
2.99k
    QualType PointeeElem = Context.getBaseElementType(Pointee);
3557
3558
2.99k
    if (Pointee.getAddressSpace() != LangAS::Default &&
3559
2.99k
        
!getLangOpts().OpenCLCPlusPlus7
)
3560
2
      return Diag(Ex.get()->getBeginLoc(),
3561
2
                  diag::err_address_space_qualified_delete)
3562
2
             << Pointee.getUnqualifiedType()
3563
2
             << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3564
3565
2.98k
    CXXRecordDecl *PointeeRD = nullptr;
3566
2.98k
    if (Pointee->isVoidType() && 
!isSFINAEContext()24
) {
3567
      // The C++ standard bans deleting a pointer to a non-object type, which
3568
      // effectively bans deletion of "void*". However, most compilers support
3569
      // this, so we treat it as a warning unless we're in a SFINAE context.
3570
24
      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3571
24
        << Type << Ex.get()->getSourceRange();
3572
2.96k
    } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3573
2.96k
               Pointee->isSizelessType()) {
3574
8
      return ExprError(Diag(StartLoc, diag::err_delete_operand)
3575
8
        << Type << Ex.get()->getSourceRange());
3576
2.95k
    } else if (!Pointee->isDependentType()) {
3577
      // FIXME: This can result in errors if the definition was imported from a
3578
      // module but is hidden.
3579
2.95k
      if (!RequireCompleteType(StartLoc, Pointee,
3580
2.95k
                               diag::warn_delete_incomplete, Ex.get())) {
3581
2.93k
        if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3582
1.22k
          PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3583
2.93k
      }
3584
2.95k
    }
3585
3586
2.98k
    if (Pointee->isArrayType() && 
!ArrayForm18
) {
3587
4
      Diag(StartLoc, diag::warn_delete_array_type)
3588
4
          << Type << Ex.get()->getSourceRange()
3589
4
          << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3590
4
      ArrayForm = true;
3591
4
    }
3592
3593
2.98k
    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3594
2.98k
                                      ArrayForm ? 
OO_Array_Delete1.38k
:
OO_Delete1.59k
);
3595
3596
2.98k
    if (PointeeRD) {
3597
1.22k
      if (!UseGlobal &&
3598
1.22k
          FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3599
1.17k
                                   OperatorDelete))
3600
62
        return ExprError();
3601
3602
      // If we're allocating an array of records, check whether the
3603
      // usual operator delete[] has a size_t parameter.
3604
1.16k
      if (ArrayForm) {
3605
        // If the user specifically asked to use the global allocator,
3606
        // we'll need to do the lookup into the class.
3607
173
        if (UseGlobal)
3608
24
          UsualArrayDeleteWantsSize =
3609
24
            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3610
3611
        // Otherwise, the usual operator delete[] should be the
3612
        // function we just found.
3613
149
        else if (OperatorDelete && 
isa<CXXMethodDecl>(OperatorDelete)39
)
3614
39
          UsualArrayDeleteWantsSize =
3615
39
            UsualDeallocFnInfo(*this,
3616
39
                               DeclAccessPair::make(OperatorDelete, AS_public))
3617
39
              .HasSizeT;
3618
173
      }
3619
3620
1.16k
      if (!PointeeRD->hasIrrelevantDestructor())
3621
689
        if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3622
689
          MarkFunctionReferenced(StartLoc,
3623
689
                                    const_cast<CXXDestructorDecl*>(Dtor));
3624
689
          if (DiagnoseUseOfDecl(Dtor, StartLoc))
3625
6
            return ExprError();
3626
689
        }
3627
3628
1.16k
      CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3629
1.16k
                           /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3630
1.16k
                           /*WarnOnNonAbstractTypes=*/!ArrayForm,
3631
1.16k
                           SourceLocation());
3632
1.16k
    }
3633
3634
2.91k
    if (!OperatorDelete) {
3635
2.70k
      if (getLangOpts().OpenCLCPlusPlus) {
3636
3
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3637
3
        return ExprError();
3638
3
      }
3639
3640
2.70k
      bool IsComplete = isCompleteType(StartLoc, Pointee);
3641
2.70k
      bool CanProvideSize =
3642
2.70k
          IsComplete && 
(2.66k
!ArrayForm2.66k
||
UsualArrayDeleteWantsSize1.34k
||
3643
2.66k
                         
Pointee.isDestructedType()1.33k
);
3644
2.70k
      bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3645
3646
      // Look for a global declaration.
3647
2.70k
      OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3648
2.70k
                                                     Overaligned, DeleteName);
3649
2.70k
    }
3650
3651
2.91k
    MarkFunctionReferenced(StartLoc, OperatorDelete);
3652
3653
    // Check access and ambiguity of destructor if we're going to call it.
3654
    // Note that this is required even for a virtual delete.
3655
2.91k
    bool IsVirtualDelete = false;
3656
2.91k
    if (PointeeRD) {
3657
1.15k
      if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3658
1.15k
        CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3659
1.15k
                              PDiag(diag::err_access_dtor) << PointeeElem);
3660
1.15k
        IsVirtualDelete = Dtor->isVirtual();
3661
1.15k
      }
3662
1.15k
    }
3663
3664
2.91k
    DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3665
3666
    // Convert the operand to the type of the first parameter of operator
3667
    // delete. This is only necessary if we selected a destroying operator
3668
    // delete that we are going to call (non-virtually); converting to void*
3669
    // is trivial and left to AST consumers to handle.
3670
2.91k
    QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3671
2.91k
    if (!IsVirtualDelete && 
!ParamType->getPointeeType()->isVoidType()2.77k
) {
3672
29
      Qualifiers Qs = Pointee.getQualifiers();
3673
29
      if (Qs.hasCVRQualifiers()) {
3674
        // Qualifiers are irrelevant to this conversion; we're only looking
3675
        // for access and ambiguity.
3676
2
        Qs.removeCVRQualifiers();
3677
2
        QualType Unqual = Context.getPointerType(
3678
2
            Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3679
2
        Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3680
2
      }
3681
29
      Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3682
29
      if (Ex.isInvalid())
3683
4
        return ExprError();
3684
29
    }
3685
2.91k
  }
3686
3687
7.28k
  CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3688
7.28k
      Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3689
7.28k
      UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3690
7.28k
  AnalyzeDeleteExprMismatch(Result);
3691
7.28k
  return Result;
3692
7.41k
}
3693
3694
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3695
                                            bool IsDelete,
3696
1.03k
                                            FunctionDecl *&Operator) {
3697
3698
1.03k
  DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3699
1.03k
      IsDelete ? 
OO_Delete510
:
OO_New525
);
3700
3701
1.03k
  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3702
1.03k
  S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3703
1.03k
  assert(!R.empty() && "implicitly declared allocation functions not found");
3704
0
  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3705
3706
  // We do our own custom access checks below.
3707
0
  R.suppressDiagnostics();
3708
3709
1.03k
  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3710
1.03k
  OverloadCandidateSet Candidates(R.getNameLoc(),
3711
1.03k
                                  OverloadCandidateSet::CSK_Normal);
3712
1.03k
  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3713
6.29k
       FnOvl != FnOvlEnd; 
++FnOvl5.25k
) {
3714
    // Even member operator new/delete are implicitly treated as
3715
    // static, so don't use AddMemberCandidate.
3716
5.25k
    NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3717
3718
5.25k
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3719
4
      S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3720
4
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
3721
4
                                     Candidates,
3722
4
                                     /*SuppressUserConversions=*/false);
3723
4
      continue;
3724
4
    }
3725
3726
5.25k
    FunctionDecl *Fn = cast<FunctionDecl>(D);
3727
5.25k
    S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3728
5.25k
                           /*SuppressUserConversions=*/false);
3729
5.25k
  }
3730
3731
1.03k
  SourceRange Range = TheCall->getSourceRange();
3732
3733
  // Do the resolution.
3734
1.03k
  OverloadCandidateSet::iterator Best;
3735
1.03k
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3736
1.00k
  case OR_Success: {
3737
    // Got one!
3738
1.00k
    FunctionDecl *FnDecl = Best->Function;
3739
1.00k
    assert(R.getNamingClass() == nullptr &&
3740
1.00k
           "class members should not be considered");
3741
3742
1.00k
    if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3743
20
      S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3744
20
          << (IsDelete ? 
112
:
08
) << Range;
3745
20
      S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3746
20
          << R.getLookupName() << FnDecl->getSourceRange();
3747
20
      return true;
3748
20
    }
3749
3750
981
    Operator = FnDecl;
3751
981
    return false;
3752
1.00k
  }
3753
3754
30
  case OR_No_Viable_Function:
3755
30
    Candidates.NoteCandidates(
3756
30
        PartialDiagnosticAt(R.getNameLoc(),
3757
30
                            S.PDiag(diag::err_ovl_no_viable_function_in_call)
3758
30
                                << R.getLookupName() << Range),
3759
30
        S, OCD_AllCandidates, Args);
3760
30
    return true;
3761
3762
4
  case OR_Ambiguous:
3763
4
    Candidates.NoteCandidates(
3764
4
        PartialDiagnosticAt(R.getNameLoc(),
3765
4
                            S.PDiag(diag::err_ovl_ambiguous_call)
3766
4
                                << R.getLookupName() << Range),
3767
4
        S, OCD_AmbiguousCandidates, Args);
3768
4
    return true;
3769
3770
0
  case OR_Deleted: {
3771
0
    Candidates.NoteCandidates(
3772
0
        PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3773
0
                                                << R.getLookupName() << Range),
3774
0
        S, OCD_AllCandidates, Args);
3775
0
    return true;
3776
1.00k
  }
3777
1.03k
  }
3778
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3779
0
}
3780
3781
ExprResult
3782
Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3783
1.03k
                                             bool IsDelete) {
3784
1.03k
  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3785
1.03k
  if (!getLangOpts().CPlusPlus) {
3786
2
    Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3787
2
        << (IsDelete ? 
"__builtin_operator_delete"1
:
"__builtin_operator_new"1
)
3788
2
        << "C++";
3789
2
    return ExprError();
3790
2
  }
3791
  // CodeGen assumes it can find the global new and delete to call,
3792
  // so ensure that they are declared.
3793
1.03k
  DeclareGlobalNewDelete();
3794
3795
1.03k
  FunctionDecl *OperatorNewOrDelete = nullptr;
3796
1.03k
  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3797
1.03k
                                      OperatorNewOrDelete))
3798
54
    return ExprError();
3799
981
  assert(OperatorNewOrDelete && "should be found");
3800
3801
0
  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3802
981
  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3803
3804
981
  TheCall->setType(OperatorNewOrDelete->getReturnType());
3805
2.00k
  for (unsigned i = 0; i != TheCall->getNumArgs(); 
++i1.02k
) {
3806
1.02k
    QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3807
1.02k
    InitializedEntity Entity =
3808
1.02k
        InitializedEntity::InitializeParameter(Context, ParamTy, false);
3809
1.02k
    ExprResult Arg = PerformCopyInitialization(
3810
1.02k
        Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3811
1.02k
    if (Arg.isInvalid())
3812
0
      return ExprError();
3813
1.02k
    TheCall->setArg(i, Arg.get());
3814
1.02k
  }
3815
981
  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3816
981
  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3817
981
         "Callee expected to be implicit cast to a builtin function pointer");
3818
0
  Callee->setType(OperatorNewOrDelete->getType());
3819
3820
981
  return TheCallResult;
3821
981
}
3822
3823
void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3824
                                bool IsDelete, bool CallCanBeVirtual,
3825
                                bool WarnOnNonAbstractTypes,
3826
2.33k
                                SourceLocation DtorLoc) {
3827
2.33k
  if (!dtor || 
dtor->isVirtual()2.09k
||
!CallCanBeVirtual1.91k
||
isUnevaluatedContext()1.73k
)
3828
658
    return;
3829
3830
  // C++ [expr.delete]p3:
3831
  //   In the first alternative (delete object), if the static type of the
3832
  //   object to be deleted is different from its dynamic type, the static
3833
  //   type shall be a base class of the dynamic type of the object to be
3834
  //   deleted and the static type shall have a virtual destructor or the
3835
  //   behavior is undefined.
3836
  //
3837
1.68k
  const CXXRecordDecl *PointeeRD = dtor->getParent();
3838
  // Note: a final class cannot be derived from, no issue there
3839
1.68k
  if (!PointeeRD->isPolymorphic() || 
PointeeRD->hasAttr<FinalAttr>()74
)
3840
1.61k
    return;
3841
3842
  // If the superclass is in a system header, there's nothing that can be done.
3843
  // The `delete` (where we emit the warning) can be in a system header,
3844
  // what matters for this warning is where the deleted type is defined.
3845
65
  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3846
2
    return;
3847
3848
63
  QualType ClassType = dtor->getThisType()->getPointeeType();
3849
63
  if (PointeeRD->isAbstract()) {
3850
    // If the class is abstract, we warn by default, because we're
3851
    // sure the code has undefined behavior.
3852
9
    Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 
10
)
3853
9
                                                           << ClassType;
3854
54
  } else if (WarnOnNonAbstractTypes) {
3855
    // Otherwise, if this is not an array delete, it's a bit suspect,
3856
    // but not necessarily wrong.
3857
50
    Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 
042
:
18
)
3858
50
                                                  << ClassType;
3859
50
  }
3860
63
  if (!IsDelete) {
3861
8
    std::string TypeStr;
3862
8
    ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3863
8
    Diag(DtorLoc, diag::note_delete_non_virtual)
3864
8
        << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3865
8
  }
3866
63
}
3867
3868
Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3869
                                                   SourceLocation StmtLoc,
3870
1.09k
                                                   ConditionKind CK) {
3871
1.09k
  ExprResult E =
3872
1.09k
      CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3873
1.09k
  if (E.isInvalid())
3874
78
    return ConditionError();
3875
1.01k
  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3876
1.01k
                         CK == ConditionKind::ConstexprIf);
3877
1.09k
}
3878
3879
/// Check the use of the given variable as a C++ condition in an if,
3880
/// while, do-while, or switch statement.
3881
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3882
                                        SourceLocation StmtLoc,
3883
1.09k
                                        ConditionKind CK) {
3884
1.09k
  if (ConditionVar->isInvalidDecl())
3885
57
    return ExprError();
3886
3887
1.03k
  QualType T = ConditionVar->getType();
3888
3889
  // C++ [stmt.select]p2:
3890
  //   The declarator shall not specify a function or an array.
3891
1.03k
  if (T->isFunctionType())
3892
0
    return ExprError(Diag(ConditionVar->getLocation(),
3893
0
                          diag::err_invalid_use_of_function_type)
3894
0
                       << ConditionVar->getSourceRange());
3895
1.03k
  else if (T->isArrayType())
3896
2
    return ExprError(Diag(ConditionVar->getLocation(),
3897
2
                          diag::err_invalid_use_of_array_type)
3898
2
                     << ConditionVar->getSourceRange());
3899
3900
1.03k
  ExprResult Condition = BuildDeclRefExpr(
3901
1.03k
      ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3902
1.03k
      ConditionVar->getLocation());
3903
3904
1.03k
  switch (CK) {
3905
970
  case ConditionKind::Boolean:
3906
970
    return CheckBooleanCondition(StmtLoc, Condition.get());
3907
3908
0
  case ConditionKind::ConstexprIf:
3909
0
    return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3910
3911
61
  case ConditionKind::Switch:
3912
61
    return CheckSwitchCondition(StmtLoc, Condition.get());
3913
1.03k
  }
3914
3915
0
  llvm_unreachable("unexpected condition kind");
3916
0
}
3917
3918
/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3919
655k
ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3920
  // C++11 6.4p4:
3921
  // The value of a condition that is an initialized declaration in a statement
3922
  // other than a switch statement is the value of the declared variable
3923
  // implicitly converted to type bool. If that conversion is ill-formed, the
3924
  // program is ill-formed.
3925
  // The value of a condition that is an expression is the value of the
3926
  // expression, implicitly converted to bool.
3927
  //
3928
  // C++2b 8.5.2p2
3929
  // If the if statement is of the form if constexpr, the value of the condition
3930
  // is contextually converted to bool and the converted expression shall be
3931
  // a constant expression.
3932
  //
3933
3934
655k
  ExprResult E = PerformContextuallyConvertToBool(CondExpr);
3935
655k
  if (!IsConstexpr || 
E.isInvalid()146
||
E.get()->isValueDependent()144
)
3936
655k
    return E;
3937
3938
  // FIXME: Return this value to the caller so they don't need to recompute it.
3939
125
  llvm::APSInt Cond;
3940
125
  E = VerifyIntegerConstantExpression(
3941
125
      E.get(), &Cond,
3942
125
      diag::err_constexpr_if_condition_expression_is_not_constant);
3943
125
  return E;
3944
655k
}
3945
3946
/// Helper function to determine whether this is the (deprecated) C++
3947
/// conversion from a string literal to a pointer to non-const char or
3948
/// non-const wchar_t (for narrow and wide string literals,
3949
/// respectively).
3950
bool
3951
208k
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3952
  // Look inside the implicit cast, if it exists.
3953
208k
  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3954
1
    From = Cast->getSubExpr();
3955
3956
  // A string literal (2.13.4) that is not a wide string literal can
3957
  // be converted to an rvalue of type "pointer to char"; a wide
3958
  // string literal can be converted to an rvalue of type "pointer
3959
  // to wchar_t" (C++ 4.2p2).
3960
208k
  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3961
191k
    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3962
188k
      if (const BuiltinType *ToPointeeType
3963
188k
          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3964
        // This conversion is considered only when there is an
3965
        // explicit appropriate pointer target type (C++ 4.2p2).
3966
187k
        if (!ToPtrType->getPointeeType().hasQualifiers()) {
3967
881
          switch (StrLit->getKind()) {
3968
2
            case StringLiteral::UTF8:
3969
4
            case StringLiteral::UTF16:
3970
6
            case StringLiteral::UTF32:
3971
              // We don't allow UTF literals to be implicitly converted
3972
6
              break;
3973
849
            case StringLiteral::Ascii:
3974
849
              return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3975
849
                      ToPointeeType->getKind() == BuiltinType::Char_S);
3976
26
            case StringLiteral::Wide:
3977
26
              return Context.typesAreCompatible(Context.getWideCharType(),
3978
26
                                                QualType(ToPointeeType, 0));
3979
881
          }
3980
881
        }
3981
187k
      }
3982
3983
207k
  return false;
3984
208k
}
3985
3986
static ExprResult BuildCXXCastArgument(Sema &S,
3987
                                       SourceLocation CastLoc,
3988
                                       QualType Ty,
3989
                                       CastKind Kind,
3990
                                       CXXMethodDecl *Method,
3991
                                       DeclAccessPair FoundDecl,
3992
                                       bool HadMultipleCandidates,
3993
6.97k
                                       Expr *From) {
3994
6.97k
  switch (Kind) {
3995
0
  default: llvm_unreachable("Unhandled cast kind!");
3996
1.76k
  case CK_ConstructorConversion: {
3997
1.76k
    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3998
1.76k
    SmallVector<Expr*, 8> ConstructorArgs;
3999
4000
1.76k
    if (S.RequireNonAbstractType(CastLoc, Ty,
4001
1.76k
                                 diag::err_allocation_of_abstract_type))
4002
4
      return ExprError();
4003
4004
1.75k
    if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4005
1.75k
                                  ConstructorArgs))
4006
0
      return ExprError();
4007
4008
1.75k
    S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4009
1.75k
                             InitializedEntity::InitializeTemporary(Ty));
4010
1.75k
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
4011
2
      return ExprError();
4012
4013
1.75k
    ExprResult Result = S.BuildCXXConstructExpr(
4014
1.75k
        CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4015
1.75k
        ConstructorArgs, HadMultipleCandidates,
4016
1.75k
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4017
1.75k
        CXXConstructExpr::CK_Complete, SourceRange());
4018
1.75k
    if (Result.isInvalid())
4019
0
      return ExprError();
4020
4021
1.75k
    return S.MaybeBindToTemporary(Result.getAs<Expr>());
4022
1.75k
  }
4023
4024
5.21k
  case CK_UserDefinedConversion: {
4025
5.21k
    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4026
4027
0
    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4028
5.21k
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
4029
0
      return ExprError();
4030
4031
    // Create an implicit call expr that calls it.
4032
5.21k
    CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4033
5.21k
    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4034
5.21k
                                                 HadMultipleCandidates);
4035
5.21k
    if (Result.isInvalid())
4036
1
      return ExprError();
4037
    // Record usage of conversion in an implicit cast.
4038
5.21k
    Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4039
5.21k
                                      CK_UserDefinedConversion, Result.get(),
4040
5.21k
                                      nullptr, Result.get()->getValueKind(),
4041
5.21k
                                      S.CurFPFeatureOverrides());
4042
4043
5.21k
    return S.MaybeBindToTemporary(Result.get());
4044
5.21k
  }
4045
6.97k
  }
4046
6.97k
}
4047
4048
/// PerformImplicitConversion - Perform an implicit conversion of the
4049
/// expression From to the type ToType using the pre-computed implicit
4050
/// conversion sequence ICS. Returns the converted
4051
/// expression. Action is the kind of conversion we're performing,
4052
/// used in the error message.
4053
ExprResult
4054
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4055
                                const ImplicitConversionSequence &ICS,
4056
                                AssignmentAction Action,
4057
10.9M
                                CheckedConversionKind CCK) {
4058
  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4059
10.9M
  if (CCK == CCK_ForBuiltinOverloadedOp && 
!From->getType()->isRecordType()86.2k
)
4060
81.8k
    return From;
4061
4062
10.8M
  switch (ICS.getKind()) {
4063
10.8M
  case ImplicitConversionSequence::StandardConversion: {
4064
10.8M
    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4065
10.8M
                                               Action, CCK);
4066
10.8M
    if (Res.isInvalid())
4067
115
      return ExprError();
4068
10.8M
    From = Res.get();
4069
10.8M
    break;
4070
10.8M
  }
4071
4072
6.97k
  case ImplicitConversionSequence::UserDefinedConversion: {
4073
4074
6.97k
      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4075
6.97k
      CastKind CastKind;
4076
6.97k
      QualType BeforeToType;
4077
6.97k
      assert(FD && "no conversion function for user-defined conversion seq");
4078
6.97k
      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4079
5.21k
        CastKind = CK_UserDefinedConversion;
4080
4081
        // If the user-defined conversion is specified by a conversion function,
4082
        // the initial standard conversion sequence converts the source type to
4083
        // the implicit object parameter of the conversion function.
4084
5.21k
        BeforeToType = Context.getTagDeclType(Conv->getParent());
4085
5.21k
      } else {
4086
1.76k
        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4087
1.76k
        CastKind = CK_ConstructorConversion;
4088
        // Do no conversion if dealing with ... for the first conversion.
4089
1.76k
        if (!ICS.UserDefined.EllipsisConversion) {
4090
          // If the user-defined conversion is specified by a constructor, the
4091
          // initial standard conversion sequence converts the source type to
4092
          // the type required by the argument of the constructor
4093
1.76k
          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4094
1.76k
        }
4095
1.76k
      }
4096
      // Watch out for ellipsis conversion.
4097
6.97k
      if (!ICS.UserDefined.EllipsisConversion) {
4098
6.97k
        ExprResult Res =
4099
6.97k
          PerformImplicitConversion(From, BeforeToType,
4100
6.97k
                                    ICS.UserDefined.Before, AA_Converting,
4101
6.97k
                                    CCK);
4102
6.97k
        if (Res.isInvalid())
4103
0
          return ExprError();
4104
6.97k
        From = Res.get();
4105
6.97k
      }
4106
4107
6.97k
      ExprResult CastArg = BuildCXXCastArgument(
4108
6.97k
          *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4109
6.97k
          cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4110
6.97k
          ICS.UserDefined.HadMultipleCandidates, From);
4111
4112
6.97k
      if (CastArg.isInvalid())
4113
7
        return ExprError();
4114
4115
6.96k
      From = CastArg.get();
4116
4117
      // C++ [over.match.oper]p7:
4118
      //   [...] the second standard conversion sequence of a user-defined
4119
      //   conversion sequence is not applied.
4120
6.96k
      if (CCK == CCK_ForBuiltinOverloadedOp)
4121
4.38k
        return From;
4122
4123
2.58k
      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4124
2.58k
                                       AA_Converting, CCK);
4125
6.96k
  }
4126
4127
12
  case ImplicitConversionSequence::AmbiguousConversion:
4128
12
    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4129
12
                          PDiag(diag::err_typecheck_ambiguous_condition)
4130
12
                            << From->getSourceRange());
4131
12
    return ExprError();
4132
4133
0
  case ImplicitConversionSequence::EllipsisConversion:
4134
0
    llvm_unreachable("Cannot perform an ellipsis conversion");
4135
4136
545
  case ImplicitConversionSequence::BadConversion:
4137
545
    Sema::AssignConvertType ConvTy =
4138
545
        CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4139
545
    bool Diagnosed = DiagnoseAssignmentResult(
4140
545
        ConvTy == Compatible ? 
Incompatible5
:
ConvTy540
, From->getExprLoc(),
4141
545
        ToType, From->getType(), From, Action);
4142
545
    assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4143
545
    return ExprError();
4144
10.8M
  }
4145
4146
  // Everything went well.
4147
10.8M
  return From;
4148
10.8M
}
4149
4150
/// PerformImplicitConversion - Perform an implicit conversion of the
4151
/// expression From to the type ToType by following the standard
4152
/// conversion sequence SCS. Returns the converted
4153
/// expression. Flavor is the context in which we're performing this
4154
/// conversion, for use in error messages.
4155
ExprResult
4156
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4157
                                const StandardConversionSequence& SCS,
4158
                                AssignmentAction Action,
4159
10.8M
                                CheckedConversionKind CCK) {
4160
10.8M
  bool CStyle = (CCK == CCK_CStyleCast || 
CCK == CCK_FunctionalCast10.3M
);
4161
4162
  // Overall FIXME: we are recomputing too many types here and doing far too
4163
  // much extra work. What this means is that we need to keep track of more
4164
  // information that is computed when we try the implicit conversion initially,
4165
  // so that we don't need to recompute anything here.
4166
10.8M
  QualType FromType = From->getType();
4167
4168
10.8M
  if (SCS.CopyConstructor) {
4169
    // FIXME: When can ToType be a reference type?
4170
0
    assert(!ToType->isReferenceType());
4171
0
    if (SCS.Second == ICK_Derived_To_Base) {
4172
0
      SmallVector<Expr*, 8> ConstructorArgs;
4173
0
      if (CompleteConstructorCall(
4174
0
              cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4175
0
              /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4176
0
        return ExprError();
4177
0
      return BuildCXXConstructExpr(
4178
0
          /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4179
0
          SCS.FoundCopyConstructor, SCS.CopyConstructor,
4180
0
          ConstructorArgs, /*HadMultipleCandidates*/ false,
4181
0
          /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4182
0
          CXXConstructExpr::CK_Complete, SourceRange());
4183
0
    }
4184
0
    return BuildCXXConstructExpr(
4185
0
        /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4186
0
        SCS.FoundCopyConstructor, SCS.CopyConstructor,
4187
0
        From, /*HadMultipleCandidates*/ false,
4188
0
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4189
0
        CXXConstructExpr::CK_Complete, SourceRange());
4190
0
  }
4191
4192
  // Resolve overloaded function references.
4193
10.8M
  if (Context.hasSameType(FromType, Context.OverloadTy)) {
4194
1.26k
    DeclAccessPair Found;
4195
1.26k
    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4196
1.26k
                                                          true, Found);
4197
1.26k
    if (!Fn)
4198
0
      return ExprError();
4199
4200
1.26k
    if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4201
22
      return ExprError();
4202
4203
1.24k
    From = FixOverloadedFunctionReference(From, Found, Fn);
4204
1.24k
    FromType = From->getType();
4205
1.24k
  }
4206
4207
  // If we're converting to an atomic type, first convert to the corresponding
4208
  // non-atomic type.
4209
10.8M
  QualType ToAtomicType;
4210
10.8M
  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4211
549
    ToAtomicType = ToType;
4212
549
    ToType = ToAtomic->getValueType();
4213
549
  }
4214
4215
10.8M
  QualType InitialFromType = FromType;
4216
  // Perform the first implicit conversion.
4217
10.8M
  switch (SCS.First) {
4218
8.82M
  case ICK_Identity:
4219
8.82M
    if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4220
1
      FromType = FromAtomic->getValueType().getUnqualifiedType();
4221
1
      From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4222
1
                                      From, /*BasePath=*/nullptr, VK_PRValue,
4223
1
                                      FPOptionsOverride());
4224
1
    }
4225
8.82M
    break;
4226
4227
1.89M
  case ICK_Lvalue_To_Rvalue: {
4228
1.89M
    assert(From->getObjectKind() != OK_ObjCProperty);
4229
0
    ExprResult FromRes = DefaultLvalueConversion(From);
4230
1.89M
    if (FromRes.isInvalid())
4231
1
      return ExprError();
4232
4233
1.89M
    From = FromRes.get();
4234
1.89M
    FromType = From->getType();
4235
1.89M
    break;
4236
1.89M
  }
4237
4238
108k
  case ICK_Array_To_Pointer:
4239
108k
    FromType = Context.getArrayDecayedType(FromType);
4240
108k
    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4241
108k
                             /*BasePath=*/nullptr, CCK)
4242
108k
               .get();
4243
108k
    break;
4244
4245
5.40k
  case ICK_Function_To_Pointer:
4246
5.40k
    FromType = Context.getPointerType(FromType);
4247
5.40k
    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4248
5.40k
                             VK_PRValue, /*BasePath=*/nullptr, CCK)
4249
5.40k
               .get();
4250
5.40k
    break;
4251
4252
0
  default:
4253
0
    llvm_unreachable("Improper first standard conversion");
4254
10.8M
  }
4255
4256
  // Perform the second implicit conversion
4257
10.8M
  switch (SCS.Second) {
4258
9.54M
  case ICK_Identity:
4259
    // C++ [except.spec]p5:
4260
    //   [For] assignment to and initialization of pointers to functions,
4261
    //   pointers to member functions, and references to functions: the
4262
    //   target entity shall allow at least the exceptions allowed by the
4263
    //   source value in the assignment or initialization.
4264
9.54M
    switch (Action) {
4265
1.13M
    case AA_Assigning:
4266
2.35M
    case AA_Initializing:
4267
      // Note, function argument passing and returning are initialization.
4268
3.62M
    case AA_Passing:
4269
4.32M
    case AA_Returning:
4270
4.32M
    case AA_Sending:
4271
4.32M
    case AA_Passing_CFAudited:
4272
4.32M
      if (CheckExceptionSpecCompatibility(From, ToType))
4273
55
        return ExprError();
4274
4.32M
      break;
4275
4276
4.32M
    case AA_Casting:
4277
5.21M
    case AA_Converting:
4278
      // Casts and implicit conversions are not initialization, so are not
4279
      // checked for exception specification mismatches.
4280
5.21M
      break;
4281
9.54M
    }
4282
    // Nothing else to do.
4283
9.54M
    break;
4284
4285
9.54M
  case ICK_Integral_Promotion:
4286
742k
  case ICK_Integral_Conversion:
4287
742k
    if (ToType->isBooleanType()) {
4288
4
      assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4289
4
             SCS.Second == ICK_Integral_Promotion &&
4290
4
             "only enums with fixed underlying type can promote to bool");
4291
0
      From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4292
4
                               /*BasePath=*/nullptr, CCK)
4293
4
                 .get();
4294
742k
    } else {
4295
742k
      From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4296
742k
                               /*BasePath=*/nullptr, CCK)
4297
742k
                 .get();
4298
742k
    }
4299
0
    break;
4300
4301
1.29k
  case ICK_Floating_Promotion:
4302
5.88k
  case ICK_Floating_Conversion:
4303
5.88k
    From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4304
5.88k
                             /*BasePath=*/nullptr, CCK)
4305
5.88k
               .get();
4306
5.88k
    break;
4307
4308
7
  case ICK_Complex_Promotion:
4309
63
  case ICK_Complex_Conversion: {
4310
63
    QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4311
63
    QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4312
63
    CastKind CK;
4313
63
    if (FromEl->isRealFloatingType()) {
4314
45
      if (ToEl->isRealFloatingType())
4315
33
        CK = CK_FloatingComplexCast;
4316
12
      else
4317
12
        CK = CK_FloatingComplexToIntegralComplex;
4318
45
    } else 
if (18
ToEl->isRealFloatingType()18
) {
4319
4
      CK = CK_IntegralComplexToFloatingComplex;
4320
14
    } else {
4321
14
      CK = CK_IntegralComplexCast;
4322
14
    }
4323
63
    From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4324
63
                             CCK)
4325
63
               .get();
4326
63
    break;
4327
7
  }
4328
4329
21.1k
  case ICK_Floating_Integral:
4330
21.1k
    if (ToType->isRealFloatingType())
4331
15.4k
      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4332
15.4k
                               /*BasePath=*/nullptr, CCK)
4333
15.4k
                 .get();
4334
5.67k
    else
4335
5.67k
      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4336
5.67k
                               /*BasePath=*/nullptr, CCK)
4337
5.67k
                 .get();
4338
21.1k
    break;
4339
4340
0
  case ICK_Compatible_Conversion:
4341
0
    From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4342
0
                             /*BasePath=*/nullptr, CCK).get();
4343
0
    break;
4344
4345
0
  case ICK_Writeback_Conversion:
4346
102k
  case ICK_Pointer_Conversion: {
4347
102k
    if (SCS.IncompatibleObjC && 
Action != AA_Casting18
) {
4348
      // Diagnose incompatible Objective-C conversions
4349
13
      if (Action == AA_Initializing || 
Action == AA_Assigning9
)
4350
10
        Diag(From->getBeginLoc(),
4351
10
             diag::ext_typecheck_convert_incompatible_pointer)
4352
10
            << ToType << From->getType() << Action << From->getSourceRange()
4353
10
            << 0;
4354
3
      else
4355
3
        Diag(From->getBeginLoc(),
4356
3
             diag::ext_typecheck_convert_incompatible_pointer)
4357
3
            << From->getType() << ToType << Action << From->getSourceRange()
4358
3
            << 0;
4359
4360
13
      if (From->getType()->isObjCObjectPointerType() &&
4361
13
          
ToType->isObjCObjectPointerType()9
)
4362
9
        EmitRelatedResultTypeNote(From);
4363
102k
    } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4364
102k
               !CheckObjCARCUnavailableWeakConversion(ToType,
4365
683
                                                      From->getType())) {
4366
10
      if (Action == AA_Initializing)
4367
6
        Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4368
4
      else
4369
4
        Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4370
4
            << (Action == AA_Casting) << From->getType() << ToType
4371
4
            << From->getSourceRange();
4372
10
    }
4373
4374
    // Defer address space conversion to the third conversion.
4375
102k
    QualType FromPteeType = From->getType()->getPointeeType();
4376
102k
    QualType ToPteeType = ToType->getPointeeType();
4377
102k
    QualType NewToType = ToType;
4378
102k
    if (!FromPteeType.isNull() && 
!ToPteeType.isNull()58.0k
&&
4379
102k
        
FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()58.0k
) {
4380
7
      NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4381
7
      NewToType = Context.getAddrSpaceQualType(NewToType,
4382
7
                                               FromPteeType.getAddressSpace());
4383
7
      if (ToType->isObjCObjectPointerType())
4384
0
        NewToType = Context.getObjCObjectPointerType(NewToType);
4385
7
      else if (ToType->isBlockPointerType())
4386
0
        NewToType = Context.getBlockPointerType(NewToType);
4387
7
      else
4388
7
        NewToType = Context.getPointerType(NewToType);
4389
7
    }
4390
4391
102k
    CastKind Kind;
4392
102k
    CXXCastPath BasePath;
4393
102k
    if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4394
13
      return ExprError();
4395
4396
    // Make sure we extend blocks if necessary.
4397
    // FIXME: doing this here is really ugly.
4398
102k
    if (Kind == CK_BlockPointerToObjCPointerCast) {
4399
28
      ExprResult E = From;
4400
28
      (void) PrepareCastToObjCObjectPointer(E);
4401
28
      From = E.get();
4402
28
    }
4403
102k
    if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4404
683
      CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4405
102k
    From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4406
102k
               .get();
4407
102k
    break;
4408
102k
  }
4409
4410
684
  case ICK_Pointer_Member: {
4411
684
    CastKind Kind;
4412
684
    CXXCastPath BasePath;
4413
684
    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4414
24
      return ExprError();
4415
660
    if (CheckExceptionSpecCompatibility(From, ToType))
4416
0
      return ExprError();
4417
4418
    // We may not have been able to figure out what this member pointer resolved
4419
    // to up until this exact point.  Attempt to lock-in it's inheritance model.
4420
660
    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4421
127
      (void)isCompleteType(From->getExprLoc(), From->getType());
4422
127
      (void)isCompleteType(From->getExprLoc(), ToType);
4423
127
    }
4424
4425
660
    From =
4426
660
        ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4427
660
    break;
4428
660
  }
4429
4430
144k
  case ICK_Boolean_Conversion:
4431
    // Perform half-to-boolean conversion via float.
4432
144k
    if (From->getType()->isHalfType()) {
4433
0
      From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4434
0
      FromType = Context.FloatTy;
4435
0
    }
4436
4437
144k
    From = ImpCastExprToType(From, Context.BoolTy,
4438
144k
                             ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
4439
144k
                             /*BasePath=*/nullptr, CCK)
4440
144k
               .get();
4441
144k
    break;
4442
4443
0
  case ICK_Derived_To_Base: {
4444
0
    CXXCastPath BasePath;
4445
0
    if (CheckDerivedToBaseConversion(
4446
0
            From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4447
0
            From->getSourceRange(), &BasePath, CStyle))
4448
0
      return ExprError();
4449
4450
0
    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4451
0
                      CK_DerivedToBase, From->getValueKind(),
4452
0
                      &BasePath, CCK).get();
4453
0
    break;
4454
0
  }
4455
4456
271k
  case ICK_Vector_Conversion:
4457
271k
    From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4458
271k
                             /*BasePath=*/nullptr, CCK)
4459
271k
               .get();
4460
271k
    break;
4461
4462
70
  case ICK_SVE_Vector_Conversion:
4463
70
    From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4464
70
                             /*BasePath=*/nullptr, CCK)
4465
70
               .get();
4466
70
    break;
4467
4468
56
  case ICK_Vector_Splat: {
4469
    // Vector splat from any arithmetic type to a vector.
4470
56
    Expr *Elem = prepareVectorSplat(ToType, From).get();
4471
56
    From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4472
56
                             /*BasePath=*/nullptr, CCK)
4473
56
               .get();
4474
56
    break;
4475
0
  }
4476
4477
196
  case ICK_Complex_Real:
4478
    // Case 1.  x -> _Complex y
4479
196
    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4480
178
      QualType ElType = ToComplex->getElementType();
4481
178
      bool isFloatingComplex = ElType->isRealFloatingType();
4482
4483
      // x -> y
4484
178
      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4485
        // do nothing
4486
98
      } else if (From->getType()->isRealFloatingType()) {
4487
26
        From = ImpCastExprToType(From, ElType,
4488
26
                isFloatingComplex ? CK_FloatingCast : 
CK_FloatingToIntegral0
).get();
4489
72
      } else {
4490
72
        assert(From->getType()->isIntegerType());
4491
0
        From = ImpCastExprToType(From, ElType,
4492
72
                isFloatingComplex ? 
CK_IntegralToFloating70
:
CK_IntegralCast2
).get();
4493
72
      }
4494
      // y -> _Complex y
4495
0
      From = ImpCastExprToType(From, ToType,
4496
178
                   isFloatingComplex ? 
CK_FloatingRealToComplex165
4497
178
                                     : 
CK_IntegralRealToComplex13
).get();
4498
4499
    // Case 2.  _Complex x -> y
4500
178
    } else {
4501
18
      auto *FromComplex = From->getType()->castAs<ComplexType>();
4502
18
      QualType ElType = FromComplex->getElementType();
4503
18
      bool isFloatingComplex = ElType->isRealFloatingType();
4504
4505
      // _Complex x -> x
4506
18
      From = ImpCastExprToType(From, ElType,
4507
18
                               isFloatingComplex ? 
CK_FloatingComplexToReal8
4508
18
                                                 : 
CK_IntegralComplexToReal10
,
4509
18
                               VK_PRValue, /*BasePath=*/nullptr, CCK)
4510
18
                 .get();
4511
4512
      // x -> y
4513
18
      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4514
        // do nothing
4515
11
      } else 
if (7
ToType->isRealFloatingType()7
) {
4516
5
        From = ImpCastExprToType(From, ToType,
4517
5
                                 isFloatingComplex ? 
CK_FloatingCast1
4518
5
                                                   : 
CK_IntegralToFloating4
,
4519
5
                                 VK_PRValue, /*BasePath=*/nullptr, CCK)
4520
5
                   .get();
4521
5
      } else {
4522
2
        assert(ToType->isIntegerType());
4523
0
        From = ImpCastExprToType(From, ToType,
4524
2
                                 isFloatingComplex ? 
CK_FloatingToIntegral0
4525
2
                                                   : CK_IntegralCast,
4526
2
                                 VK_PRValue, /*BasePath=*/nullptr, CCK)
4527
2
                   .get();
4528
2
      }
4529
18
    }
4530
0
    break;
4531
4532
5
  case ICK_Block_Pointer_Conversion: {
4533
5
    LangAS AddrSpaceL =
4534
5
        ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4535
5
    LangAS AddrSpaceR =
4536
5
        FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4537
5
    assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4538
5
           "Invalid cast");
4539
0
    CastKind Kind =
4540
5
        AddrSpaceL != AddrSpaceR ? 
CK_AddressSpaceConversion0
: CK_BitCast;
4541
5
    From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4542
5
                             VK_PRValue, /*BasePath=*/nullptr, CCK)
4543
5
               .get();
4544
5
    break;
4545
0
  }
4546
4547
0
  case ICK_TransparentUnionConversion: {
4548
0
    ExprResult FromRes = From;
4549
0
    Sema::AssignConvertType ConvTy =
4550
0
      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4551
0
    if (FromRes.isInvalid())
4552
0
      return ExprError();
4553
0
    From = FromRes.get();
4554
0
    assert ((ConvTy == Sema::Compatible) &&
4555
0
            "Improper transparent union conversion");
4556
0
    (void)ConvTy;
4557
0
    break;
4558
0
  }
4559
4560
0
  case ICK_Zero_Event_Conversion:
4561
0
  case ICK_Zero_Queue_Conversion:
4562
0
    From = ImpCastExprToType(From, ToType,
4563
0
                             CK_ZeroToOCLOpaqueType,
4564
0
                             From->getValueKind()).get();
4565
0
    break;
4566
4567
0
  case ICK_Lvalue_To_Rvalue:
4568
0
  case ICK_Array_To_Pointer:
4569
0
  case ICK_Function_To_Pointer:
4570
0
  case ICK_Function_Conversion:
4571
0
  case ICK_Qualification:
4572
0
  case ICK_Num_Conversion_Kinds:
4573
0
  case ICK_C_Only_Conversion:
4574
0
  case ICK_Incompatible_Pointer_Conversion:
4575
0
    llvm_unreachable("Improper second standard conversion");
4576
10.8M
  }
4577
4578
10.8M
  switch (SCS.Third) {
4579
10.7M
  case ICK_Identity:
4580
    // Nothing to do.
4581
10.7M
    break;
4582
4583
126
  case ICK_Function_Conversion:
4584
    // If both sides are functions (or pointers/references to them), there could
4585
    // be incompatible exception declarations.
4586
126
    if (CheckExceptionSpecCompatibility(From, ToType))
4587
0
      return ExprError();
4588
4589
126
    From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4590
126
                             /*BasePath=*/nullptr, CCK)
4591
126
               .get();
4592
126
    break;
4593
4594
38.2k
  case ICK_Qualification: {
4595
38.2k
    ExprValueKind VK = From->getValueKind();
4596
38.2k
    CastKind CK = CK_NoOp;
4597
4598
38.2k
    if (ToType->isReferenceType() &&
4599
38.2k
        ToType->getPointeeType().getAddressSpace() !=
4600
0
            From->getType().getAddressSpace())
4601
0
      CK = CK_AddressSpaceConversion;
4602
4603
38.2k
    if (ToType->isPointerType() &&
4604
38.2k
        ToType->getPointeeType().getAddressSpace() !=
4605
38.2k
            From->getType()->getPointeeType().getAddressSpace())
4606
102
      CK = CK_AddressSpaceConversion;
4607
4608
38.2k
    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4609
38.2k
                             /*BasePath=*/nullptr, CCK)
4610
38.2k
               .get();
4611
4612
38.2k
    if (SCS.DeprecatedStringLiteralToCharPtr &&
4613
38.2k
        
!getLangOpts().WritableStrings321
) {
4614
320
      Diag(From->getBeginLoc(),
4615
320
           getLangOpts().CPlusPlus11
4616
320
               ? 
diag::ext_deprecated_string_literal_conversion157
4617
320
               : 
diag::warn_deprecated_string_literal_conversion163
)
4618
320
          << ToType.getNonReferenceType();
4619
320
    }
4620
4621
38.2k
    break;
4622
126
  }
4623
4624
0
  default:
4625
0
    llvm_unreachable("Improper third standard conversion");
4626
10.8M
  }
4627
4628
  // If this conversion sequence involved a scalar -> atomic conversion, perform
4629
  // that conversion now.
4630
10.8M
  if (!ToAtomicType.isNull()) {
4631
549
    assert(Context.hasSameType(
4632
549
        ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4633
0
    From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4634
549
                             VK_PRValue, nullptr, CCK)
4635
549
               .get();
4636
549
  }
4637
4638
  // Materialize a temporary if we're implicitly converting to a reference
4639
  // type. This is not required by the C++ rules but is necessary to maintain
4640
  // AST invariants.
4641
10.8M
  if (ToType->isReferenceType() && 
From->isPRValue()213
) {
4642
2
    ExprResult Res = TemporaryMaterializationConversion(From);
4643
2
    if (Res.isInvalid())
4644
0
      return ExprError();
4645
2
    From = Res.get();
4646
2
  }
4647
4648
  // If this conversion sequence succeeded and involved implicitly converting a
4649
  // _Nullable type to a _Nonnull one, complain.
4650
10.8M
  if (!isCast(CCK))
4651
10.2M
    diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4652
10.2M
                                        From->getBeginLoc());
4653
4654
10.8M
  return From;
4655
10.8M
}
4656
4657
/// Check the completeness of a type in a unary type trait.
4658
///
4659
/// If the particular type trait requires a complete type, tries to complete
4660
/// it. If completing the type fails, a diagnostic is emitted and false
4661
/// returned. If completing the type succeeds or no completion was required,
4662
/// returns true.
4663
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4664
                                                SourceLocation Loc,
4665
105k
                                                QualType ArgTy) {
4666
  // C++0x [meta.unary.prop]p3:
4667
  //   For all of the class templates X declared in this Clause, instantiating
4668
  //   that template with a template argument that is a class template
4669
  //   specialization may result in the implicit instantiation of the template
4670
  //   argument if and only if the semantics of X require that the argument
4671
  //   must be a complete type.
4672
  // We apply this rule to all the type trait expressions used to implement
4673
  // these class templates. We also try to follow any GCC documented behavior
4674
  // in these expressions to ensure portability of standard libraries.
4675
105k
  switch (UTT) {
4676
0
  default: llvm_unreachable("not a UTT");
4677
    // is_complete_type somewhat obviously cannot require a complete type.
4678
50
  case UTT_IsCompleteType:
4679
    // Fall-through
4680
4681
    // These traits are modeled on the type predicates in C++0x
4682
    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4683
    // requiring a complete type, as whether or not they return true cannot be
4684
    // impacted by the completeness of the type.
4685
4.12k
  case UTT_IsVoid:
4686
8.47k
  case UTT_IsIntegral:
4687
8.55k
  case UTT_IsFloatingPoint:
4688
31.2k
  case UTT_IsArray:
4689
35.1k
  case UTT_IsPointer:
4690
36.0k
  case UTT_IsLvalueReference:
4691
38.2k
  case UTT_IsRvalueReference:
4692
39.0k
  case UTT_IsMemberFunctionPointer:
4693
39.7k
  case UTT_IsMemberObjectPointer:
4694
41.5k
  case UTT_IsEnum:
4695
42.0k
  case UTT_IsUnion:
4696
42.5k
  case UTT_IsClass:
4697
65.5k
  case UTT_IsFunction:
4698
67.9k
  case UTT_IsReference:
4699
68.0k
  case UTT_IsArithmetic:
4700
68.5k
  case UTT_IsFundamental:
4701
69.1k
  case UTT_IsObject:
4702
69.6k
  case UTT_IsScalar:
4703
70.2k
  case UTT_IsCompound:
4704
70.8k
  case UTT_IsMemberPointer:
4705
    // Fall-through
4706
4707
    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4708
    // which requires some of its traits to have the complete type. However,
4709
    // the completeness of the type cannot impact these traits' semantics, and
4710
    // so they don't require it. This matches the comments on these traits in
4711
    // Table 49.
4712
71.9k
  case UTT_IsConst:
4713
75.5k
  case UTT_IsVolatile:
4714
78.1k
  case UTT_IsSigned:
4715
78.6k
  case UTT_IsUnsigned:
4716
4717
  // This type trait always returns false, checking the type is moot.
4718
78.7k
  case UTT_IsInterfaceClass:
4719
78.7k
    return true;
4720
4721
  // C++14 [meta.unary.prop]:
4722
  //   If T is a non-union class type, T shall be a complete type.
4723
8.90k
  case UTT_IsEmpty:
4724
9.41k
  case UTT_IsPolymorphic:
4725
9.90k
  case UTT_IsAbstract:
4726
9.90k
    if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4727
4.81k
      if (!RD->isUnion())
4728
4.80k
        return !S.RequireCompleteType(
4729
4.80k
            Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4730
5.10k
    return true;
4731
4732
  // C++14 [meta.unary.prop]:
4733
  //   If T is a class type, T shall be a complete type.
4734
8.88k
  case UTT_IsFinal:
4735
8.94k
  case UTT_IsSealed:
4736
8.94k
    if (ArgTy->getAsCXXRecordDecl())
4737
4.79k
      return !S.RequireCompleteType(
4738
4.79k
          Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4739
4.14k
    return true;
4740
4741
  // C++1z [meta.unary.prop]:
4742
  //   remove_all_extents_t<T> shall be a complete type or cv void.
4743
180
  case UTT_IsAggregate:
4744
1.62k
  case UTT_IsTrivial:
4745
2.98k
  case UTT_IsTriviallyCopyable:
4746
4.40k
  case UTT_IsStandardLayout:
4747
5.10k
  case UTT_IsPOD:
4748
5.67k
  case UTT_IsLiteral:
4749
  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4750
  // or an array of unknown bound. But GCC actually imposes the same constraints
4751
  // as above.
4752
5.78k
  case UTT_HasNothrowAssign:
4753
5.85k
  case UTT_HasNothrowMoveAssign:
4754
5.96k
  case UTT_HasNothrowConstructor:
4755
6.07k
  case UTT_HasNothrowCopy:
4756
6.19k
  case UTT_HasTrivialAssign:
4757
6.22k
  case UTT_HasTrivialMoveAssign:
4758
6.39k
  case UTT_HasTrivialDefaultConstructor:
4759
6.43k
  case UTT_HasTrivialMoveConstructor:
4760
6.55k
  case UTT_HasTrivialCopy:
4761
6.67k
  case UTT_HasTrivialDestructor:
4762
7.23k
  case UTT_HasVirtualDestructor:
4763
7.23k
    ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4764
7.23k
    LLVM_FALLTHROUGH;
4765
4766
  // C++1z [meta.unary.prop]:
4767
  //   T shall be a complete type, cv void, or an array of unknown bound.
4768
7.29k
  case UTT_IsDestructible:
4769
7.34k
  case UTT_IsNothrowDestructible:
4770
7.95k
  case UTT_IsTriviallyDestructible:
4771
8.32k
  case UTT_HasUniqueObjectRepresentations:
4772
8.32k
    if (ArgTy->isIncompleteArrayType() || 
ArgTy->isVoidType()8.29k
)
4773
165
      return true;
4774
4775
8.16k
    return !S.RequireCompleteType(
4776
8.16k
        Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4777
105k
  }
4778
105k
}
4779
4780
static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4781
                               Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4782
                               bool (CXXRecordDecl::*HasTrivial)() const,
4783
                               bool (CXXRecordDecl::*HasNonTrivial)() const,
4784
                               bool (CXXMethodDecl::*IsDesiredOp)() const)
4785
81
{
4786
81
  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4787
81
  if ((RD->*HasTrivial)() && 
!(RD->*HasNonTrivial)()18
)
4788
18
    return true;
4789
4790
63
  DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4791
63
  DeclarationNameInfo NameInfo(Name, KeyLoc);
4792
63
  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4793
63
  if (Self.LookupQualifiedName(Res, RD)) {
4794
63
    bool FoundOperator = false;
4795
63
    Res.suppressDiagnostics();
4796
63
    for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4797
135
         Op != OpEnd; 
++Op72
) {
4798
93
      if (isa<FunctionTemplateDecl>(*Op))
4799
3
        continue;
4800
4801
90
      CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4802
90
      if((Operator->*IsDesiredOp)()) {
4803
54
        FoundOperator = true;
4804
54
        auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4805
54
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4806
54
        if (!CPT || !CPT->isNothrow())
4807
21
          return false;
4808
54
      }
4809
90
    }
4810
42
    return FoundOperator;
4811
63
  }
4812
0
  return false;
4813
63
}
4814
4815
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4816
89.9k
                                   SourceLocation KeyLoc, QualType T) {
4817
89.9k
  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4818
4819
0
  ASTContext &C = Self.Context;
4820
89.9k
  switch(UTT) {
4821
0
  default: llvm_unreachable("not a UTT");
4822
    // Type trait expressions corresponding to the primary type category
4823
    // predicates in C++0x [meta.unary.cat].
4824
3.59k
  case UTT_IsVoid:
4825
3.59k
    return T->isVoidType();
4826
3.86k
  case UTT_IsIntegral:
4827
3.86k
    return T->isIntegralType(C);
4828
72
  case UTT_IsFloatingPoint:
4829
72
    return T->isFloatingType();
4830
22.2k
  case UTT_IsArray:
4831
22.2k
    return T->isArrayType();
4832
3.40k
  case UTT_IsPointer:
4833
3.40k
    return T->isAnyPointerType();
4834
425
  case UTT_IsLvalueReference:
4835
425
    return T->isLValueReferenceType();
4836
1.71k
  case UTT_IsRvalueReference:
4837
1.71k
    return T->isRValueReferenceType();
4838
295
  case UTT_IsMemberFunctionPointer:
4839
295
    return T->isMemberFunctionPointerType();
4840
222
  case UTT_IsMemberObjectPointer:
4841
222
    return T->isMemberDataPointerType();
4842
1.34k
  case UTT_IsEnum:
4843
1.34k
    return T->isEnumeralType();
4844
32
  case UTT_IsUnion:
4845
32
    return T->isUnionType();
4846
42
  case UTT_IsClass:
4847
42
    return T->isClassType() || 
T->isStructureType()39
||
T->isInterfaceType()30
;
4848
22.5k
  case UTT_IsFunction:
4849
22.5k
    return T->isFunctionType();
4850
4851
    // Type trait expressions which correspond to the convenient composition
4852
    // predicates in C++0x [meta.unary.comp].
4853
1.92k
  case UTT_IsReference:
4854
1.92k
    return T->isReferenceType();
4855
72
  case UTT_IsArithmetic:
4856
72
    return T->isArithmeticType() && 
!T->isEnumeralType()47
;
4857
75
  case UTT_IsFundamental:
4858
75
    return T->isFundamentalType();
4859
49
  case UTT_IsObject:
4860
49
    return T->isObjectType();
4861
87
  case UTT_IsScalar:
4862
    // Note: semantic analysis depends on Objective-C lifetime types to be
4863
    // considered scalar types. However, such types do not actually behave
4864
    // like scalar types at run time (since they may require retain/release
4865
    // operations), so we report them as non-scalar.
4866
87
    if (T->isObjCLifetimeType()) {
4867
8
      switch (T.getObjCLifetime()) {
4868
3
      case Qualifiers::OCL_None:
4869
4
      case Qualifiers::OCL_ExplicitNone:
4870
4
        return true;
4871
4872
1
      case Qualifiers::OCL_Strong:
4873
3
      case Qualifiers::OCL_Weak:
4874
4
      case Qualifiers::OCL_Autoreleasing:
4875
4
        return false;
4876
8
      }
4877
8
    }
4878
4879
79
    return T->isScalarType();
4880
90
  case UTT_IsCompound:
4881
90
    return T->isCompoundType();
4882
93
  case UTT_IsMemberPointer:
4883
93
    return T->isMemberPointerType();
4884
4885
    // Type trait expressions which correspond to the type property predicates
4886
    // in C++0x [meta.unary.prop].
4887
656
  case UTT_IsConst:
4888
656
    return T.isConstQualified();
4889
3.16k
  case UTT_IsVolatile:
4890
3.16k
    return T.isVolatileQualified();
4891
965
  case UTT_IsTrivial:
4892
965
    return T.isTrivialType(C);
4893
873
  case UTT_IsTriviallyCopyable:
4894
873
    return T.isTriviallyCopyableType(C);
4895
940
  case UTT_IsStandardLayout:
4896
940
    return T->isStandardLayoutType();
4897
210
  case UTT_IsPOD:
4898
210
    return T.isPODType(C);
4899
95
  case UTT_IsLiteral:
4900
95
    return T->isLiteralType(C);
4901
8.42k
  case UTT_IsEmpty:
4902
8.42k
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4903
4.78k
      return !RD->isUnion() && 
RD->isEmpty()4.78k
;
4904
3.63k
    return false;
4905
46
  case UTT_IsPolymorphic:
4906
46
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4907
19
      return !RD->isUnion() && 
RD->isPolymorphic()13
;
4908
27
    return false;
4909
14
  case UTT_IsAbstract:
4910
14
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4911
8
      return !RD->isUnion() && 
RD->isAbstract()7
;
4912
6
    return false;
4913
153
  case UTT_IsAggregate:
4914
    // Report vector extensions and complex types as aggregates because they
4915
    // support aggregate initialization. GCC mirrors this behavior for vectors
4916
    // but not _Complex.
4917
153
    return T->isAggregateType() || 
T->isVectorType()71
||
T->isExtVectorType()65
||
4918
153
           
T->isAnyComplexType()65
;
4919
  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4920
  // even then only when it is used with the 'interface struct ...' syntax
4921
  // Clang doesn't support /CLR which makes this type trait moot.
4922
10
  case UTT_IsInterfaceClass:
4923
10
    return false;
4924
8.39k
  case UTT_IsFinal:
4925
8.45k
  case UTT_IsSealed:
4926
8.45k
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4927
4.79k
      return RD->hasAttr<FinalAttr>();
4928
3.65k
    return false;
4929
2.04k
  case UTT_IsSigned:
4930
    // Enum types should always return false.
4931
    // Floating points should always return true.
4932
2.04k
    return T->isFloatingType() ||
4933
2.04k
           
(2.04k
T->isSignedIntegerType()2.04k
&&
!T->isEnumeralType()790
);
4934
96
  case UTT_IsUnsigned:
4935
    // Enum types should always return false.
4936
96
    return T->isUnsignedIntegerType() && 
!T->isEnumeralType()39
;
4937
4938
    // Type trait expressions which query classes regarding their construction,
4939
    // destruction, and copying. Rather than being based directly on the
4940
    // related type predicates in the standard, they are specified by both
4941
    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4942
    // specifications.
4943
    //
4944
    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4945
    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4946
    //
4947
    // Note that these builtins do not behave as documented in g++: if a class
4948
    // has both a trivial and a non-trivial special member of a particular kind,
4949
    // they return false! For now, we emulate this behavior.
4950
    // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4951
    // does not correctly compute triviality in the presence of multiple special
4952
    // members of the same kind. Revisit this once the g++ bug is fixed.
4953
159
  case UTT_HasTrivialDefaultConstructor:
4954
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4955
    //   If __is_pod (type) is true then the trait is true, else if type is
4956
    //   a cv class or union type (or array thereof) with a trivial default
4957
    //   constructor ([class.ctor]) then the trait is true, else it is false.
4958
159
    if (T.isPODType(C))
4959
64
      return true;
4960
95
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4961
82
      return RD->hasTrivialDefaultConstructor() &&
4962
82
             
!RD->hasNonTrivialDefaultConstructor()21
;
4963
13
    return false;
4964
37
  case UTT_HasTrivialMoveConstructor:
4965
    //  This trait is implemented by MSVC 2012 and needed to parse the
4966
    //  standard library headers. Specifically this is used as the logic
4967
    //  behind std::is_trivially_move_constructible (20.9.4.3).
4968
37
    if (T.isPODType(C))
4969
19
      return true;
4970
18
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4971
18
      return RD->hasTrivialMoveConstructor() && 
!RD->hasNonTrivialMoveConstructor()3
;
4972
0
    return false;
4973
119
  case UTT_HasTrivialCopy:
4974
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4975
    //   If __is_pod (type) is true or type is a reference type then
4976
    //   the trait is true, else if type is a cv class or union type
4977
    //   with a trivial copy constructor ([class.copy]) then the trait
4978
    //   is true, else it is false.
4979
119
    if (T.isPODType(C) || 
T->isReferenceType()65
)
4980
57
      return true;
4981
62
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4982
49
      return RD->hasTrivialCopyConstructor() &&
4983
49
             
!RD->hasNonTrivialCopyConstructor()28
;
4984
13
    return false;
4985
31
  case UTT_HasTrivialMoveAssign:
4986
    //  This trait is implemented by MSVC 2012 and needed to parse the
4987
    //  standard library headers. Specifically it is used as the logic
4988
    //  behind std::is_trivially_move_assignable (20.9.4.3)
4989
31
    if (T.isPODType(C))
4990
16
      return true;
4991
15
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4992
15
      return RD->hasTrivialMoveAssignment() && 
!RD->hasNonTrivialMoveAssignment()0
;
4993
0
    return false;
4994
115
  case UTT_HasTrivialAssign:
4995
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4996
    //   If type is const qualified or is a reference type then the
4997
    //   trait is false. Otherwise if __is_pod (type) is true then the
4998
    //   trait is true, else if type is a cv class or union type with
4999
    //   a trivial copy assignment ([class.copy]) then the trait is
5000
    //   true, else it is false.
5001
    // Note: the const and reference restrictions are interesting,
5002
    // given that const and reference members don't prevent a class
5003
    // from having a trivial copy assignment operator (but do cause
5004
    // errors if the copy assignment operator is actually used, q.v.
5005
    // [class.copy]p12).
5006
5007
115
    if (T.isConstQualified())
5008
12
      return false;
5009
103
    if (T.isPODType(C))
5010
50
      return true;
5011
53
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5012
40
      return RD->hasTrivialCopyAssignment() &&
5013
40
             
!RD->hasNonTrivialCopyAssignment()22
;
5014
13
    return false;
5015
50
  case UTT_IsDestructible:
5016
175
  case UTT_IsTriviallyDestructible:
5017
228
  case UTT_IsNothrowDestructible:
5018
    // C++14 [meta.unary.prop]:
5019
    //   For reference types, is_destructible<T>::value is true.
5020
228
    if (T->isReferenceType())
5021
9
      return true;
5022
5023
    // Objective-C++ ARC: autorelease types don't require destruction.
5024
219
    if (T->isObjCLifetimeType() &&
5025
219
        
T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing0
)
5026
0
      return true;
5027
5028
    // C++14 [meta.unary.prop]:
5029
    //   For incomplete types and function types, is_destructible<T>::value is
5030
    //   false.
5031
219
    if (T->isIncompleteType() || 
T->isFunctionType()174
)
5032
45
      return false;
5033
5034
    // A type that requires destruction (via a non-trivial destructor or ARC
5035
    // lifetime semantics) is not trivially-destructible.
5036
174
    if (UTT == UTT_IsTriviallyDestructible && 
T.isDestructedType()107
)
5037
21
      return false;
5038
5039
    // C++14 [meta.unary.prop]:
5040
    //   For object types and given U equal to remove_all_extents_t<T>, if the
5041
    //   expression std::declval<U&>().~U() is well-formed when treated as an
5042
    //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
5043
153
    if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5044
67
      CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5045
67
      if (!Destructor)
5046
0
        return false;
5047
      //  C++14 [dcl.fct.def.delete]p2:
5048
      //    A program that refers to a deleted function implicitly or
5049
      //    explicitly, other than to declare it, is ill-formed.
5050
67
      if (Destructor->isDeleted())
5051
13
        return false;
5052
54
      if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5053
6
        return false;
5054
48
      if (UTT == UTT_IsNothrowDestructible) {
5055
21
        auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5056
21
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5057
21
        if (!CPT || !CPT->isNothrow())
5058
3
          return false;
5059
21
      }
5060
48
    }
5061
131
    return true;
5062
5063
117
  case UTT_HasTrivialDestructor:
5064
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5065
    //   If __is_pod (type) is true or type is a reference type
5066
    //   then the trait is true, else if type is a cv class or union
5067
    //   type (or array thereof) with a trivial destructor
5068
    //   ([class.dtor]) then the trait is true, else it is
5069
    //   false.
5070
117
    if (T.isPODType(C) || 
T->isReferenceType()61
)
5071
59
      return true;
5072
5073
    // Objective-C++ ARC: autorelease types don't require destruction.
5074
58
    if (T->isObjCLifetimeType() &&
5075
58
        
T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing4
)
5076
1
      return true;
5077
5078
57
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5079
48
      return RD->hasTrivialDestructor();
5080
9
    return false;
5081
  // TODO: Propagate nothrowness for implicitly declared special members.
5082
108
  case UTT_HasNothrowAssign:
5083
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5084
    //   If type is const qualified or is a reference type then the
5085
    //   trait is false. Otherwise if __has_trivial_assign (type)
5086
    //   is true then the trait is true, else if type is a cv class
5087
    //   or union type with copy assignment operators that are known
5088
    //   not to throw an exception then the trait is true, else it is
5089
    //   false.
5090
108
    if (C.getBaseElementType(T).isConstQualified())
5091
12
      return false;
5092
96
    if (T->isReferenceType())
5093
3
      return false;
5094
93