Coverage Report

Created: 2019-07-24 05:18

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