Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaExpr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExpr.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
//  This file implements semantic analysis for expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TreeTransform.h"
14
#include "UsedDeclVisitor.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/ASTMutationListener.h"
19
#include "clang/AST/CXXInheritance.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/EvaluatedExprVisitor.h"
23
#include "clang/AST/Expr.h"
24
#include "clang/AST/ExprCXX.h"
25
#include "clang/AST/ExprObjC.h"
26
#include "clang/AST/ExprOpenMP.h"
27
#include "clang/AST/OperationKinds.h"
28
#include "clang/AST/ParentMapContext.h"
29
#include "clang/AST/RecursiveASTVisitor.h"
30
#include "clang/AST/Type.h"
31
#include "clang/AST/TypeLoc.h"
32
#include "clang/Basic/Builtins.h"
33
#include "clang/Basic/DiagnosticSema.h"
34
#include "clang/Basic/PartialDiagnostic.h"
35
#include "clang/Basic/SourceManager.h"
36
#include "clang/Basic/Specifiers.h"
37
#include "clang/Basic/TargetInfo.h"
38
#include "clang/Basic/TypeTraits.h"
39
#include "clang/Lex/LiteralSupport.h"
40
#include "clang/Lex/Preprocessor.h"
41
#include "clang/Sema/AnalysisBasedWarnings.h"
42
#include "clang/Sema/DeclSpec.h"
43
#include "clang/Sema/DelayedDiagnostic.h"
44
#include "clang/Sema/Designator.h"
45
#include "clang/Sema/EnterExpressionEvaluationContext.h"
46
#include "clang/Sema/Initialization.h"
47
#include "clang/Sema/Lookup.h"
48
#include "clang/Sema/Overload.h"
49
#include "clang/Sema/ParsedTemplate.h"
50
#include "clang/Sema/Scope.h"
51
#include "clang/Sema/ScopeInfo.h"
52
#include "clang/Sema/SemaFixItUtils.h"
53
#include "clang/Sema/SemaInternal.h"
54
#include "clang/Sema/Template.h"
55
#include "llvm/ADT/STLExtras.h"
56
#include "llvm/ADT/StringExtras.h"
57
#include "llvm/Support/Casting.h"
58
#include "llvm/Support/ConvertUTF.h"
59
#include "llvm/Support/SaveAndRestore.h"
60
#include "llvm/Support/TypeSize.h"
61
#include <optional>
62
63
using namespace clang;
64
using namespace sema;
65
66
/// Determine whether the use of this declaration is valid, without
67
/// emitting diagnostics.
68
0
bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
69
  // See if this is an auto-typed variable whose initializer we are parsing.
70
0
  if (ParsingInitForAutoVars.count(D))
71
0
    return false;
72
73
  // See if this is a deleted function.
74
0
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75
0
    if (FD->isDeleted())
76
0
      return false;
77
78
    // If the function has a deduced return type, and we can't deduce it,
79
    // then we can't use it either.
80
0
    if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
81
0
        DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
82
0
      return false;
83
84
    // See if this is an aligned allocation/deallocation function that is
85
    // unavailable.
86
0
    if (TreatUnavailableAsInvalid &&
87
0
        isUnavailableAlignedAllocationFunction(*FD))
88
0
      return false;
89
0
  }
90
91
  // See if this function is unavailable.
92
0
  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
93
0
      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
94
0
    return false;
95
96
0
  if (isa<UnresolvedUsingIfExistsDecl>(D))
97
0
    return false;
98
99
0
  return true;
100
0
}
101
102
59
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
103
  // Warn if this is used but marked unused.
104
59
  if (const auto *A = D->getAttr<UnusedAttr>()) {
105
    // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
106
    // should diagnose them.
107
0
    if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
108
0
        A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
109
0
      const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
110
0
      if (DC && !DC->hasAttr<UnusedAttr>())
111
0
        S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
112
0
    }
113
0
  }
114
59
}
115
116
/// Emit a note explaining that this function is deleted.
117
0
void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
118
0
  assert(Decl && Decl->isDeleted());
119
120
0
  if (Decl->isDefaulted()) {
121
    // If the method was explicitly defaulted, point at that declaration.
122
0
    if (!Decl->isImplicit())
123
0
      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
124
125
    // Try to diagnose why this special member function was implicitly
126
    // deleted. This might fail, if that reason no longer applies.
127
0
    DiagnoseDeletedDefaultedFunction(Decl);
128
0
    return;
129
0
  }
130
131
0
  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
132
0
  if (Ctor && Ctor->isInheritingConstructor())
133
0
    return NoteDeletedInheritingConstructor(Ctor);
134
135
0
  Diag(Decl->getLocation(), diag::note_availability_specified_here)
136
0
    << Decl << 1;
137
0
}
138
139
/// Determine whether a FunctionDecl was ever declared with an
140
/// explicit storage class.
141
0
static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
142
0
  for (auto *I : D->redecls()) {
143
0
    if (I->getStorageClass() != SC_None)
144
0
      return true;
145
0
  }
146
0
  return false;
147
0
}
148
149
/// Check whether we're in an extern inline function and referring to a
150
/// variable or function with internal linkage (C11 6.7.4p3).
151
///
152
/// This is only a warning because we used to silently accept this code, but
153
/// in many cases it will not behave correctly. This is not enabled in C++ mode
154
/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
155
/// and so while there may still be user mistakes, most of the time we can't
156
/// prove that there are errors.
157
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
158
                                                      const NamedDecl *D,
159
59
                                                      SourceLocation Loc) {
160
  // This is disabled under C++; there are too many ways for this to fire in
161
  // contexts where the warning is a false positive, or where it is technically
162
  // correct but benign.
163
59
  if (S.getLangOpts().CPlusPlus)
164
42
    return;
165
166
  // Check if this is an inlined function or method.
167
17
  FunctionDecl *Current = S.getCurFunctionDecl();
168
17
  if (!Current)
169
17
    return;
170
0
  if (!Current->isInlined())
171
0
    return;
172
0
  if (!Current->isExternallyVisible())
173
0
    return;
174
175
  // Check if the decl has internal linkage.
176
0
  if (D->getFormalLinkage() != Linkage::Internal)
177
0
    return;
178
179
  // Downgrade from ExtWarn to Extension if
180
  //  (1) the supposedly external inline function is in the main file,
181
  //      and probably won't be included anywhere else.
182
  //  (2) the thing we're referencing is a pure function.
183
  //  (3) the thing we're referencing is another inline function.
184
  // This last can give us false negatives, but it's better than warning on
185
  // wrappers for simple C library functions.
186
0
  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
187
0
  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
188
0
  if (!DowngradeWarning && UsedFn)
189
0
    DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
190
191
0
  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
192
0
                               : diag::ext_internal_in_extern_inline)
193
0
    << /*IsVar=*/!UsedFn << D;
194
195
0
  S.MaybeSuggestAddingStaticToDecl(Current);
196
197
0
  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
198
0
      << D;
199
0
}
200
201
0
void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
202
0
  const FunctionDecl *First = Cur->getFirstDecl();
203
204
  // Suggest "static" on the function, if possible.
205
0
  if (!hasAnyExplicitStorageClass(First)) {
206
0
    SourceLocation DeclBegin = First->getSourceRange().getBegin();
207
0
    Diag(DeclBegin, diag::note_convert_inline_to_static)
208
0
      << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
209
0
  }
210
0
}
211
212
/// Determine whether the use of this declaration is valid, and
213
/// emit any corresponding diagnostics.
214
///
215
/// This routine diagnoses various problems with referencing
216
/// declarations that can occur when using a declaration. For example,
217
/// it might warn if a deprecated or unavailable declaration is being
218
/// used, or produce an error (and return true) if a C++0x deleted
219
/// function is being used.
220
///
221
/// \returns true if there was an error (this declaration cannot be
222
/// referenced), false otherwise.
223
///
224
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
225
                             const ObjCInterfaceDecl *UnknownObjCClass,
226
                             bool ObjCPropertyAccess,
227
                             bool AvoidPartialAvailabilityChecks,
228
                             ObjCInterfaceDecl *ClassReceiver,
229
59
                             bool SkipTrailingRequiresClause) {
230
59
  SourceLocation Loc = Locs.front();
231
59
  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
232
    // If there were any diagnostics suppressed by template argument deduction,
233
    // emit them now.
234
0
    auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235
0
    if (Pos != SuppressedDiagnostics.end()) {
236
0
      for (const PartialDiagnosticAt &Suppressed : Pos->second)
237
0
        Diag(Suppressed.first, Suppressed.second);
238
239
      // Clear out the list of suppressed diagnostics, so that we don't emit
240
      // them again for this specialization. However, we don't obsolete this
241
      // entry from the table, because we want to avoid ever emitting these
242
      // diagnostics again.
243
0
      Pos->second.clear();
244
0
    }
245
246
    // C++ [basic.start.main]p3:
247
    //   The function 'main' shall not be used within a program.
248
0
    if (cast<FunctionDecl>(D)->isMain())
249
0
      Diag(Loc, diag::ext_main_used);
250
251
0
    diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
252
0
  }
253
254
  // See if this is an auto-typed variable whose initializer we are parsing.
255
59
  if (ParsingInitForAutoVars.count(D)) {
256
0
    if (isa<BindingDecl>(D)) {
257
0
      Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
258
0
        << D->getDeclName();
259
0
    } else {
260
0
      Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
261
0
        << D->getDeclName() << cast<VarDecl>(D)->getType();
262
0
    }
263
0
    return true;
264
0
  }
265
266
59
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
267
    // See if this is a deleted function.
268
0
    if (FD->isDeleted()) {
269
0
      auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
270
0
      if (Ctor && Ctor->isInheritingConstructor())
271
0
        Diag(Loc, diag::err_deleted_inherited_ctor_use)
272
0
            << Ctor->getParent()
273
0
            << Ctor->getInheritedConstructor().getConstructor()->getParent();
274
0
      else
275
0
        Diag(Loc, diag::err_deleted_function_use);
276
0
      NoteDeletedFunction(FD);
277
0
      return true;
278
0
    }
279
280
    // [expr.prim.id]p4
281
    //   A program that refers explicitly or implicitly to a function with a
282
    //   trailing requires-clause whose constraint-expression is not satisfied,
283
    //   other than to declare it, is ill-formed. [...]
284
    //
285
    // See if this is a function with constraints that need to be satisfied.
286
    // Check this before deducing the return type, as it might instantiate the
287
    // definition.
288
0
    if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
289
0
      ConstraintSatisfaction Satisfaction;
290
0
      if (CheckFunctionConstraints(FD, Satisfaction, Loc,
291
0
                                   /*ForOverloadResolution*/ true))
292
        // A diagnostic will have already been generated (non-constant
293
        // constraint expression, for example)
294
0
        return true;
295
0
      if (!Satisfaction.IsSatisfied) {
296
0
        Diag(Loc,
297
0
             diag::err_reference_to_function_with_unsatisfied_constraints)
298
0
            << D;
299
0
        DiagnoseUnsatisfiedConstraint(Satisfaction);
300
0
        return true;
301
0
      }
302
0
    }
303
304
    // If the function has a deduced return type, and we can't deduce it,
305
    // then we can't use it either.
306
0
    if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307
0
        DeduceReturnType(FD, Loc))
308
0
      return true;
309
310
0
    if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
311
0
      return true;
312
313
0
  }
314
315
59
  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
316
    // Lambdas are only default-constructible or assignable in C++2a onwards.
317
0
    if (MD->getParent()->isLambda() &&
318
0
        ((isa<CXXConstructorDecl>(MD) &&
319
0
          cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
320
0
         MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321
0
      Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322
0
        << !isa<CXXConstructorDecl>(MD);
323
0
    }
324
0
  }
325
326
59
  auto getReferencedObjCProp = [](const NamedDecl *D) ->
327
59
                                      const ObjCPropertyDecl * {
328
59
    if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
329
0
      return MD->findPropertyDecl();
330
59
    return nullptr;
331
59
  };
332
59
  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333
0
    if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334
0
      return true;
335
59
  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
336
0
      return true;
337
0
  }
338
339
  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340
  // Only the variables omp_in and omp_out are allowed in the combiner.
341
  // Only the variables omp_priv and omp_orig are allowed in the
342
  // initializer-clause.
343
59
  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
344
59
  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345
59
      isa<VarDecl>(D)) {
346
0
    Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347
0
        << getCurFunction()->HasOMPDeclareReductionCombiner;
348
0
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349
0
    return true;
350
0
  }
351
352
  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353
  //  List-items in map clauses on this construct may only refer to the declared
354
  //  variable var and entities that could be referenced by a procedure defined
355
  //  at the same location.
356
  // [OpenMP 5.2] Also allow iterator declared variables.
357
59
  if (LangOpts.OpenMP && isa<VarDecl>(D) &&
358
59
      !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
359
0
    Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360
0
        << getOpenMPDeclareMapperVarName();
361
0
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362
0
    return true;
363
0
  }
364
365
59
  if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
366
0
    Diag(Loc, diag::err_use_of_empty_using_if_exists);
367
0
    Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368
0
    return true;
369
0
  }
370
371
59
  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372
59
                             AvoidPartialAvailabilityChecks, ClassReceiver);
373
374
59
  DiagnoseUnusedOfDecl(*this, D, Loc);
375
376
59
  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
377
378
59
  if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
379
0
    if (getLangOpts().getFPEvalMethod() !=
380
0
            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
381
0
        PP.getLastFPEvalPragmaLocation().isValid() &&
382
0
        PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
383
0
      Diag(D->getLocation(),
384
0
           diag::err_type_available_only_in_default_eval_method)
385
0
          << D->getName();
386
0
  }
387
388
59
  if (auto *VD = dyn_cast<ValueDecl>(D))
389
59
    checkTypeSupport(VD->getType(), Loc, VD);
390
391
59
  if (LangOpts.SYCLIsDevice ||
392
59
      (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393
0
    if (!Context.getTargetInfo().isTLSSupported())
394
0
      if (const auto *VD = dyn_cast<VarDecl>(D))
395
0
        if (VD->getTLSKind() != VarDecl::TLS_None)
396
0
          targetDiag(*Locs.begin(), diag::err_thread_unsupported);
397
0
  }
398
399
59
  if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400
59
      !isUnevaluatedContext()) {
401
    // C++ [expr.prim.req.nested] p3
402
    //   A local parameter shall only appear as an unevaluated operand
403
    //   (Clause 8) within the constraint-expression.
404
0
    Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
405
0
        << D;
406
0
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
407
0
    return true;
408
0
  }
409
410
59
  return false;
411
59
}
412
413
/// DiagnoseSentinelCalls - This routine checks whether a call or
414
/// message-send is to a declaration with the sentinel attribute, and
415
/// if so, it checks that the requirements of the sentinel are
416
/// satisfied.
417
void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
418
0
                                 ArrayRef<Expr *> Args) {
419
0
  const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420
0
  if (!Attr)
421
0
    return;
422
423
  // The number of formal parameters of the declaration.
424
0
  unsigned NumFormalParams;
425
426
  // The kind of declaration.  This is also an index into a %select in
427
  // the diagnostic.
428
0
  enum { CK_Function, CK_Method, CK_Block } CalleeKind;
429
430
0
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
431
0
    NumFormalParams = MD->param_size();
432
0
    CalleeKind = CK_Method;
433
0
  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
434
0
    NumFormalParams = FD->param_size();
435
0
    CalleeKind = CK_Function;
436
0
  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
437
0
    QualType Ty = VD->getType();
438
0
    const FunctionType *Fn = nullptr;
439
0
    if (const auto *PtrTy = Ty->getAs<PointerType>()) {
440
0
      Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
441
0
      if (!Fn)
442
0
        return;
443
0
      CalleeKind = CK_Function;
444
0
    } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
445
0
      Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
446
0
      CalleeKind = CK_Block;
447
0
    } else {
448
0
      return;
449
0
    }
450
451
0
    if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
452
0
      NumFormalParams = proto->getNumParams();
453
0
    else
454
0
      NumFormalParams = 0;
455
0
  } else {
456
0
    return;
457
0
  }
458
459
  // "NullPos" is the number of formal parameters at the end which
460
  // effectively count as part of the variadic arguments.  This is
461
  // useful if you would prefer to not have *any* formal parameters,
462
  // but the language forces you to have at least one.
463
0
  unsigned NullPos = Attr->getNullPos();
464
0
  assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
465
0
  NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
466
467
  // The number of arguments which should follow the sentinel.
468
0
  unsigned NumArgsAfterSentinel = Attr->getSentinel();
469
470
  // If there aren't enough arguments for all the formal parameters,
471
  // the sentinel, and the args after the sentinel, complain.
472
0
  if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
473
0
    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
474
0
    Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
475
0
    return;
476
0
  }
477
478
  // Otherwise, find the sentinel expression.
479
0
  const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
480
0
  if (!SentinelExpr)
481
0
    return;
482
0
  if (SentinelExpr->isValueDependent())
483
0
    return;
484
0
  if (Context.isSentinelNullExpr(SentinelExpr))
485
0
    return;
486
487
  // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
488
  // or 'NULL' if those are actually defined in the context.  Only use
489
  // 'nil' for ObjC methods, where it's much more likely that the
490
  // variadic arguments form a list of object pointers.
491
0
  SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
492
0
  std::string NullValue;
493
0
  if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
494
0
    NullValue = "nil";
495
0
  else if (getLangOpts().CPlusPlus11)
496
0
    NullValue = "nullptr";
497
0
  else if (PP.isMacroDefined("NULL"))
498
0
    NullValue = "NULL";
499
0
  else
500
0
    NullValue = "(void*) 0";
501
502
0
  if (MissingNilLoc.isInvalid())
503
0
    Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
504
0
  else
505
0
    Diag(MissingNilLoc, diag::warn_missing_sentinel)
506
0
        << int(CalleeKind)
507
0
        << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
508
0
  Diag(D->getLocation(), diag::note_sentinel_here)
509
0
      << int(CalleeKind) << Attr->getRange();
510
0
}
511
512
0
SourceRange Sema::getExprRange(Expr *E) const {
513
0
  return E ? E->getSourceRange() : SourceRange();
514
0
}
515
516
//===----------------------------------------------------------------------===//
517
//  Standard Promotions and Conversions
518
//===----------------------------------------------------------------------===//
519
520
/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521
12
ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
522
  // Handle any placeholder expressions which made it here.
523
12
  if (E->hasPlaceholderType()) {
524
0
    ExprResult result = CheckPlaceholderExpr(E);
525
0
    if (result.isInvalid()) return ExprError();
526
0
    E = result.get();
527
0
  }
528
529
12
  QualType Ty = E->getType();
530
12
  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
531
532
12
  if (Ty->isFunctionType()) {
533
0
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534
0
      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535
0
        if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
536
0
          return ExprError();
537
538
0
    E = ImpCastExprToType(E, Context.getPointerType(Ty),
539
0
                          CK_FunctionToPointerDecay).get();
540
12
  } else if (Ty->isArrayType()) {
541
    // In C90 mode, arrays only promote to pointers if the array expression is
542
    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543
    // type 'array of type' is converted to an expression that has type 'pointer
544
    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
545
    // that has type 'array of type' ...".  The relevant change is "an lvalue"
546
    // (C90) to "an expression" (C99).
547
    //
548
    // C++ 4.2p1:
549
    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550
    // T" can be converted to an rvalue of type "pointer to T".
551
    //
552
0
    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
553
0
      ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
554
0
                                         CK_ArrayToPointerDecay);
555
0
      if (Res.isInvalid())
556
0
        return ExprError();
557
0
      E = Res.get();
558
0
    }
559
0
  }
560
12
  return E;
561
12
}
562
563
27
static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564
  // Check to see if we are dereferencing a null pointer.  If so,
565
  // and if not volatile-qualified, this is undefined behavior that the
566
  // optimizer will delete, so warn about it.  People sometimes try to use this
567
  // to get a deterministic trap and are surprised by clang's behavior.  This
568
  // only handles the pattern "*null", which is a very syntactic check.
569
27
  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
570
27
  if (UO && UO->getOpcode() == UO_Deref &&
571
27
      UO->getSubExpr()->getType()->isPointerType()) {
572
0
    const LangAS AS =
573
0
        UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
574
0
    if ((!isTargetAddressSpace(AS) ||
575
0
         (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
576
0
        UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577
0
            S.Context, Expr::NPC_ValueDependentIsNotNull) &&
578
0
        !UO->getType().isVolatileQualified()) {
579
0
      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
580
0
                            S.PDiag(diag::warn_indirection_through_null)
581
0
                                << UO->getSubExpr()->getSourceRange());
582
0
      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
583
0
                            S.PDiag(diag::note_indirection_through_null));
584
0
    }
585
0
  }
586
27
}
587
588
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589
                                    SourceLocation AssignLoc,
590
0
                                    const Expr* RHS) {
591
0
  const ObjCIvarDecl *IV = OIRE->getDecl();
592
0
  if (!IV)
593
0
    return;
594
595
0
  DeclarationName MemberName = IV->getDeclName();
596
0
  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
597
0
  if (!Member || !Member->isStr("isa"))
598
0
    return;
599
600
0
  const Expr *Base = OIRE->getBase();
601
0
  QualType BaseType = Base->getType();
602
0
  if (OIRE->isArrow())
603
0
    BaseType = BaseType->getPointeeType();
604
0
  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605
0
    if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606
0
      ObjCInterfaceDecl *ClassDeclared = nullptr;
607
0
      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
608
0
      if (!ClassDeclared->getSuperClass()
609
0
          && (*ClassDeclared->ivar_begin()) == IV) {
610
0
        if (RHS) {
611
0
          NamedDecl *ObjectSetClass =
612
0
            S.LookupSingleName(S.TUScope,
613
0
                               &S.Context.Idents.get("object_setClass"),
614
0
                               SourceLocation(), S.LookupOrdinaryName);
615
0
          if (ObjectSetClass) {
616
0
            SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
617
0
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
618
0
                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
619
0
                                              "object_setClass(")
620
0
                << FixItHint::CreateReplacement(
621
0
                       SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
622
0
                << FixItHint::CreateInsertion(RHSLocEnd, ")");
623
0
          }
624
0
          else
625
0
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
626
0
        } else {
627
0
          NamedDecl *ObjectGetClass =
628
0
            S.LookupSingleName(S.TUScope,
629
0
                               &S.Context.Idents.get("object_getClass"),
630
0
                               SourceLocation(), S.LookupOrdinaryName);
631
0
          if (ObjectGetClass)
632
0
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
633
0
                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
634
0
                                              "object_getClass(")
635
0
                << FixItHint::CreateReplacement(
636
0
                       SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
637
0
          else
638
0
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
639
0
        }
640
0
        S.Diag(IV->getLocation(), diag::note_ivar_decl);
641
0
      }
642
0
    }
643
0
}
644
645
59
ExprResult Sema::DefaultLvalueConversion(Expr *E) {
646
  // Handle any placeholder expressions which made it here.
647
59
  if (E->hasPlaceholderType()) {
648
0
    ExprResult result = CheckPlaceholderExpr(E);
649
0
    if (result.isInvalid()) return ExprError();
650
0
    E = result.get();
651
0
  }
652
653
  // C++ [conv.lval]p1:
654
  //   A glvalue of a non-function, non-array type T can be
655
  //   converted to a prvalue.
656
59
  if (!E->isGLValue()) return E;
657
658
45
  QualType T = E->getType();
659
45
  assert(!T.isNull() && "r-value conversion on typeless expression?");
660
661
  // lvalue-to-rvalue conversion cannot be applied to function or array types.
662
45
  if (T->isFunctionType() || T->isArrayType())
663
1
    return E;
664
665
  // We don't want to throw lvalue-to-rvalue casts on top of
666
  // expressions of certain types in C++.
667
44
  if (getLangOpts().CPlusPlus &&
668
44
      (E->getType() == Context.OverloadTy ||
669
17
       T->isDependentType() ||
670
17
       T->isRecordType()))
671
17
    return E;
672
673
  // The C standard is actually really unclear on this point, and
674
  // DR106 tells us what the result should be but not why.  It's
675
  // generally best to say that void types just doesn't undergo
676
  // lvalue-to-rvalue at all.  Note that expressions of unqualified
677
  // 'void' type are never l-values, but qualified void can be.
678
27
  if (T->isVoidType())
679
0
    return E;
680
681
  // OpenCL usually rejects direct accesses to values of 'half' type.
682
27
  if (getLangOpts().OpenCL &&
683
27
      !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
684
27
      T->isHalfType()) {
685
0
    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
686
0
      << 0 << T;
687
0
    return ExprError();
688
0
  }
689
690
27
  CheckForNullPointerDereference(*this, E);
691
27
  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
692
0
    NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
693
0
                                     &Context.Idents.get("object_getClass"),
694
0
                                     SourceLocation(), LookupOrdinaryName);
695
0
    if (ObjectGetClass)
696
0
      Diag(E->getExprLoc(), diag::warn_objc_isa_use)
697
0
          << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
698
0
          << FixItHint::CreateReplacement(
699
0
                 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
700
0
    else
701
0
      Diag(E->getExprLoc(), diag::warn_objc_isa_use);
702
0
  }
703
27
  else if (const ObjCIvarRefExpr *OIRE =
704
27
            dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
705
0
    DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
706
707
  // C++ [conv.lval]p1:
708
  //   [...] If T is a non-class type, the type of the prvalue is the
709
  //   cv-unqualified version of T. Otherwise, the type of the
710
  //   rvalue is T.
711
  //
712
  // C99 6.3.2.1p2:
713
  //   If the lvalue has qualified type, the value has the unqualified
714
  //   version of the type of the lvalue; otherwise, the value has the
715
  //   type of the lvalue.
716
27
  if (T.hasQualifiers())
717
0
    T = T.getUnqualifiedType();
718
719
  // Under the MS ABI, lock down the inheritance model now.
720
27
  if (T->isMemberPointerType() &&
721
27
      Context.getTargetInfo().getCXXABI().isMicrosoft())
722
0
    (void)isCompleteType(E->getExprLoc(), T);
723
724
27
  ExprResult Res = CheckLValueToRValueConversionOperand(E);
725
27
  if (Res.isInvalid())
726
0
    return Res;
727
27
  E = Res.get();
728
729
  // Loading a __weak object implicitly retains the value, so we need a cleanup to
730
  // balance that.
731
27
  if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
732
0
    Cleanup.setExprNeedsCleanups(true);
733
734
27
  if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
735
0
    Cleanup.setExprNeedsCleanups(true);
736
737
  // C++ [conv.lval]p3:
738
  //   If T is cv std::nullptr_t, the result is a null pointer constant.
739
27
  CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
740
27
  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
741
27
                                 CurFPFeatureOverrides());
742
743
  // C11 6.3.2.1p2:
744
  //   ... if the lvalue has atomic type, the value has the non-atomic version
745
  //   of the type of the lvalue ...
746
27
  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
747
0
    T = Atomic->getValueType().getUnqualifiedType();
748
0
    Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
749
0
                                   nullptr, VK_PRValue, FPOptionsOverride());
750
0
  }
751
752
27
  return Res;
753
27
}
754
755
12
ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
756
12
  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
757
12
  if (Res.isInvalid())
758
0
    return ExprError();
759
12
  Res = DefaultLvalueConversion(Res.get());
760
12
  if (Res.isInvalid())
761
0
    return ExprError();
762
12
  return Res;
763
12
}
764
765
/// CallExprUnaryConversions - a special case of an unary conversion
766
/// performed on a function designator of a call expression.
767
0
ExprResult Sema::CallExprUnaryConversions(Expr *E) {
768
0
  QualType Ty = E->getType();
769
0
  ExprResult Res = E;
770
  // Only do implicit cast for a function type, but not for a pointer
771
  // to function type.
772
0
  if (Ty->isFunctionType()) {
773
0
    Res = ImpCastExprToType(E, Context.getPointerType(Ty),
774
0
                            CK_FunctionToPointerDecay);
775
0
    if (Res.isInvalid())
776
0
      return ExprError();
777
0
  }
778
0
  Res = DefaultLvalueConversion(Res.get());
779
0
  if (Res.isInvalid())
780
0
    return ExprError();
781
0
  return Res.get();
782
0
}
783
784
/// UsualUnaryConversions - Performs various conversions that are common to most
785
/// operators (C99 6.3). The conversions of array and function types are
786
/// sometimes suppressed. For example, the array->pointer conversion doesn't
787
/// apply if the array is an argument to the sizeof or address (&) operators.
788
/// In these instances, this routine should *not* be called.
789
2
ExprResult Sema::UsualUnaryConversions(Expr *E) {
790
  // First, convert to an r-value.
791
2
  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
792
2
  if (Res.isInvalid())
793
0
    return ExprError();
794
2
  E = Res.get();
795
796
2
  QualType Ty = E->getType();
797
2
  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
798
799
0
  LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
800
2
  if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
801
2
      (getLangOpts().getFPEvalMethod() !=
802
0
           LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
803
0
       PP.getLastFPEvalPragmaLocation().isValid())) {
804
0
    switch (EvalMethod) {
805
0
    default:
806
0
      llvm_unreachable("Unrecognized float evaluation method");
807
0
      break;
808
0
    case LangOptions::FEM_UnsetOnCommandLine:
809
0
      llvm_unreachable("Float evaluation method should be set by now");
810
0
      break;
811
0
    case LangOptions::FEM_Double:
812
0
      if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
813
        // Widen the expression to double.
814
0
        return Ty->isComplexType()
815
0
                   ? ImpCastExprToType(E,
816
0
                                       Context.getComplexType(Context.DoubleTy),
817
0
                                       CK_FloatingComplexCast)
818
0
                   : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
819
0
      break;
820
0
    case LangOptions::FEM_Extended:
821
0
      if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
822
        // Widen the expression to long double.
823
0
        return Ty->isComplexType()
824
0
                   ? ImpCastExprToType(
825
0
                         E, Context.getComplexType(Context.LongDoubleTy),
826
0
                         CK_FloatingComplexCast)
827
0
                   : ImpCastExprToType(E, Context.LongDoubleTy,
828
0
                                       CK_FloatingCast);
829
0
      break;
830
0
    }
831
0
  }
832
833
  // Half FP have to be promoted to float unless it is natively supported
834
2
  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
835
0
    return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
836
837
  // Try to perform integral promotions if the object has a theoretically
838
  // promotable type.
839
2
  if (Ty->isIntegralOrUnscopedEnumerationType()) {
840
    // C99 6.3.1.1p2:
841
    //
842
    //   The following may be used in an expression wherever an int or
843
    //   unsigned int may be used:
844
    //     - an object or expression with an integer type whose integer
845
    //       conversion rank is less than or equal to the rank of int
846
    //       and unsigned int.
847
    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
848
    //
849
    //   If an int can represent all values of the original type, the
850
    //   value is converted to an int; otherwise, it is converted to an
851
    //   unsigned int. These are called the integer promotions. All
852
    //   other types are unchanged by the integer promotions.
853
854
2
    QualType PTy = Context.isPromotableBitField(E);
855
2
    if (!PTy.isNull()) {
856
0
      E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
857
0
      return E;
858
0
    }
859
2
    if (Context.isPromotableIntegerType(Ty)) {
860
0
      QualType PT = Context.getPromotedIntegerType(Ty);
861
0
      E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
862
0
      return E;
863
0
    }
864
2
  }
865
2
  return E;
866
2
}
867
868
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
869
/// do not have a prototype. Arguments that have type float or __fp16
870
/// are promoted to double. All other argument types are converted by
871
/// UsualUnaryConversions().
872
0
ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
873
0
  QualType Ty = E->getType();
874
0
  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
875
876
0
  ExprResult Res = UsualUnaryConversions(E);
877
0
  if (Res.isInvalid())
878
0
    return ExprError();
879
0
  E = Res.get();
880
881
  // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
882
  // promote to double.
883
  // Note that default argument promotion applies only to float (and
884
  // half/fp16); it does not apply to _Float16.
885
0
  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
886
0
  if (BTy && (BTy->getKind() == BuiltinType::Half ||
887
0
              BTy->getKind() == BuiltinType::Float)) {
888
0
    if (getLangOpts().OpenCL &&
889
0
        !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
890
0
      if (BTy->getKind() == BuiltinType::Half) {
891
0
        E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
892
0
      }
893
0
    } else {
894
0
      E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
895
0
    }
896
0
  }
897
0
  if (BTy &&
898
0
      getLangOpts().getExtendIntArgs() ==
899
0
          LangOptions::ExtendArgsKind::ExtendTo64 &&
900
0
      Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
901
0
      Context.getTypeSizeInChars(BTy) <
902
0
          Context.getTypeSizeInChars(Context.LongLongTy)) {
903
0
    E = (Ty->isUnsignedIntegerType())
904
0
            ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
905
0
                  .get()
906
0
            : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
907
0
    assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
908
0
           "Unexpected typesize for LongLongTy");
909
0
  }
910
911
  // C++ performs lvalue-to-rvalue conversion as a default argument
912
  // promotion, even on class types, but note:
913
  //   C++11 [conv.lval]p2:
914
  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
915
  //     operand or a subexpression thereof the value contained in the
916
  //     referenced object is not accessed. Otherwise, if the glvalue
917
  //     has a class type, the conversion copy-initializes a temporary
918
  //     of type T from the glvalue and the result of the conversion
919
  //     is a prvalue for the temporary.
920
  // FIXME: add some way to gate this entire thing for correctness in
921
  // potentially potentially evaluated contexts.
922
0
  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
923
0
    ExprResult Temp = PerformCopyInitialization(
924
0
                       InitializedEntity::InitializeTemporary(E->getType()),
925
0
                                                E->getExprLoc(), E);
926
0
    if (Temp.isInvalid())
927
0
      return ExprError();
928
0
    E = Temp.get();
929
0
  }
930
931
0
  return E;
932
0
}
933
934
/// Determine the degree of POD-ness for an expression.
935
/// Incomplete types are considered POD, since this check can be performed
936
/// when we're in an unevaluated context.
937
0
Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
938
0
  if (Ty->isIncompleteType()) {
939
    // C++11 [expr.call]p7:
940
    //   After these conversions, if the argument does not have arithmetic,
941
    //   enumeration, pointer, pointer to member, or class type, the program
942
    //   is ill-formed.
943
    //
944
    // Since we've already performed array-to-pointer and function-to-pointer
945
    // decay, the only such type in C++ is cv void. This also handles
946
    // initializer lists as variadic arguments.
947
0
    if (Ty->isVoidType())
948
0
      return VAK_Invalid;
949
950
0
    if (Ty->isObjCObjectType())
951
0
      return VAK_Invalid;
952
0
    return VAK_Valid;
953
0
  }
954
955
0
  if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
956
0
    return VAK_Invalid;
957
958
0
  if (Context.getTargetInfo().getTriple().isWasm() &&
959
0
      Ty.isWebAssemblyReferenceType()) {
960
0
    return VAK_Invalid;
961
0
  }
962
963
0
  if (Ty.isCXX98PODType(Context))
964
0
    return VAK_Valid;
965
966
  // C++11 [expr.call]p7:
967
  //   Passing a potentially-evaluated argument of class type (Clause 9)
968
  //   having a non-trivial copy constructor, a non-trivial move constructor,
969
  //   or a non-trivial destructor, with no corresponding parameter,
970
  //   is conditionally-supported with implementation-defined semantics.
971
0
  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
972
0
    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
973
0
      if (!Record->hasNonTrivialCopyConstructor() &&
974
0
          !Record->hasNonTrivialMoveConstructor() &&
975
0
          !Record->hasNonTrivialDestructor())
976
0
        return VAK_ValidInCXX11;
977
978
0
  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
979
0
    return VAK_Valid;
980
981
0
  if (Ty->isObjCObjectType())
982
0
    return VAK_Invalid;
983
984
0
  if (getLangOpts().MSVCCompat)
985
0
    return VAK_MSVCUndefined;
986
987
  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
988
  // permitted to reject them. We should consider doing so.
989
0
  return VAK_Undefined;
990
0
}
991
992
0
void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
993
  // Don't allow one to pass an Objective-C interface to a vararg.
994
0
  const QualType &Ty = E->getType();
995
0
  VarArgKind VAK = isValidVarArgType(Ty);
996
997
  // Complain about passing non-POD types through varargs.
998
0
  switch (VAK) {
999
0
  case VAK_ValidInCXX11:
1000
0
    DiagRuntimeBehavior(
1001
0
        E->getBeginLoc(), nullptr,
1002
0
        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1003
0
    [[fallthrough]];
1004
0
  case VAK_Valid:
1005
0
    if (Ty->isRecordType()) {
1006
      // This is unlikely to be what the user intended. If the class has a
1007
      // 'c_str' member function, the user probably meant to call that.
1008
0
      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1009
0
                          PDiag(diag::warn_pass_class_arg_to_vararg)
1010
0
                              << Ty << CT << hasCStrMethod(E) << ".c_str()");
1011
0
    }
1012
0
    break;
1013
1014
0
  case VAK_Undefined:
1015
0
  case VAK_MSVCUndefined:
1016
0
    DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1017
0
                        PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1018
0
                            << getLangOpts().CPlusPlus11 << Ty << CT);
1019
0
    break;
1020
1021
0
  case VAK_Invalid:
1022
0
    if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1023
0
      Diag(E->getBeginLoc(),
1024
0
           diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1025
0
          << Ty << CT;
1026
0
    else if (Ty->isObjCObjectType())
1027
0
      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1028
0
                          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1029
0
                              << Ty << CT);
1030
0
    else
1031
0
      Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1032
0
          << isa<InitListExpr>(E) << Ty << CT;
1033
0
    break;
1034
0
  }
1035
0
}
1036
1037
/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1038
/// will create a trap if the resulting type is not a POD type.
1039
ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1040
0
                                                  FunctionDecl *FDecl) {
1041
0
  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1042
    // Strip the unbridged-cast placeholder expression off, if applicable.
1043
0
    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1044
0
        (CT == VariadicMethod ||
1045
0
         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1046
0
      E = stripARCUnbridgedCast(E);
1047
1048
    // Otherwise, do normal placeholder checking.
1049
0
    } else {
1050
0
      ExprResult ExprRes = CheckPlaceholderExpr(E);
1051
0
      if (ExprRes.isInvalid())
1052
0
        return ExprError();
1053
0
      E = ExprRes.get();
1054
0
    }
1055
0
  }
1056
1057
0
  ExprResult ExprRes = DefaultArgumentPromotion(E);
1058
0
  if (ExprRes.isInvalid())
1059
0
    return ExprError();
1060
1061
  // Copy blocks to the heap.
1062
0
  if (ExprRes.get()->getType()->isBlockPointerType())
1063
0
    maybeExtendBlockObject(ExprRes);
1064
1065
0
  E = ExprRes.get();
1066
1067
  // Diagnostics regarding non-POD argument types are
1068
  // emitted along with format string checking in Sema::CheckFunctionCall().
1069
0
  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1070
    // Turn this into a trap.
1071
0
    CXXScopeSpec SS;
1072
0
    SourceLocation TemplateKWLoc;
1073
0
    UnqualifiedId Name;
1074
0
    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1075
0
                       E->getBeginLoc());
1076
0
    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1077
0
                                          /*HasTrailingLParen=*/true,
1078
0
                                          /*IsAddressOfOperand=*/false);
1079
0
    if (TrapFn.isInvalid())
1080
0
      return ExprError();
1081
1082
0
    ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1083
0
                                    std::nullopt, E->getEndLoc());
1084
0
    if (Call.isInvalid())
1085
0
      return ExprError();
1086
1087
0
    ExprResult Comma =
1088
0
        ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1089
0
    if (Comma.isInvalid())
1090
0
      return ExprError();
1091
0
    return Comma.get();
1092
0
  }
1093
1094
0
  if (!getLangOpts().CPlusPlus &&
1095
0
      RequireCompleteType(E->getExprLoc(), E->getType(),
1096
0
                          diag::err_call_incomplete_argument))
1097
0
    return ExprError();
1098
1099
0
  return E;
1100
0
}
1101
1102
/// Converts an integer to complex float type.  Helper function of
1103
/// UsualArithmeticConversions()
1104
///
1105
/// \return false if the integer expression is an integer type and is
1106
/// successfully converted to the complex type.
1107
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1108
                                                  ExprResult &ComplexExpr,
1109
                                                  QualType IntTy,
1110
                                                  QualType ComplexTy,
1111
0
                                                  bool SkipCast) {
1112
0
  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1113
0
  if (SkipCast) return false;
1114
0
  if (IntTy->isIntegerType()) {
1115
0
    QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1116
0
    IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1117
0
    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1118
0
                                  CK_FloatingRealToComplex);
1119
0
  } else {
1120
0
    assert(IntTy->isComplexIntegerType());
1121
0
    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1122
0
                                  CK_IntegralComplexToFloatingComplex);
1123
0
  }
1124
0
  return false;
1125
0
}
1126
1127
// This handles complex/complex, complex/float, or float/complex.
1128
// When both operands are complex, the shorter operand is converted to the
1129
// type of the longer, and that is the type of the result. This corresponds
1130
// to what is done when combining two real floating-point operands.
1131
// The fun begins when size promotion occur across type domains.
1132
// From H&S 6.3.4: When one operand is complex and the other is a real
1133
// floating-point type, the less precise type is converted, within it's
1134
// real or complex domain, to the precision of the other type. For example,
1135
// when combining a "long double" with a "double _Complex", the
1136
// "double _Complex" is promoted to "long double _Complex".
1137
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1138
                                             QualType ShorterType,
1139
                                             QualType LongerType,
1140
0
                                             bool PromotePrecision) {
1141
0
  bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1142
0
  QualType Result =
1143
0
      LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1144
1145
0
  if (PromotePrecision) {
1146
0
    if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1147
0
      Shorter =
1148
0
          S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1149
0
    } else {
1150
0
      if (LongerIsComplex)
1151
0
        LongerType = LongerType->castAs<ComplexType>()->getElementType();
1152
0
      Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1153
0
    }
1154
0
  }
1155
0
  return Result;
1156
0
}
1157
1158
/// Handle arithmetic conversion with complex types.  Helper function of
1159
/// UsualArithmeticConversions()
1160
static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1161
                                        ExprResult &RHS, QualType LHSType,
1162
0
                                        QualType RHSType, bool IsCompAssign) {
1163
  // if we have an integer operand, the result is the complex type.
1164
0
  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1165
0
                                             /*SkipCast=*/false))
1166
0
    return LHSType;
1167
0
  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1168
0
                                             /*SkipCast=*/IsCompAssign))
1169
0
    return RHSType;
1170
1171
  // Compute the rank of the two types, regardless of whether they are complex.
1172
0
  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1173
0
  if (Order < 0)
1174
    // Promote the precision of the LHS if not an assignment.
1175
0
    return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1176
0
                                        /*PromotePrecision=*/!IsCompAssign);
1177
  // Promote the precision of the RHS unless it is already the same as the LHS.
1178
0
  return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1179
0
                                      /*PromotePrecision=*/Order > 0);
1180
0
}
1181
1182
/// Handle arithmetic conversion from integer to float.  Helper function
1183
/// of UsualArithmeticConversions()
1184
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1185
                                           ExprResult &IntExpr,
1186
                                           QualType FloatTy, QualType IntTy,
1187
0
                                           bool ConvertFloat, bool ConvertInt) {
1188
0
  if (IntTy->isIntegerType()) {
1189
0
    if (ConvertInt)
1190
      // Convert intExpr to the lhs floating point type.
1191
0
      IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1192
0
                                    CK_IntegralToFloating);
1193
0
    return FloatTy;
1194
0
  }
1195
1196
  // Convert both sides to the appropriate complex float.
1197
0
  assert(IntTy->isComplexIntegerType());
1198
0
  QualType result = S.Context.getComplexType(FloatTy);
1199
1200
  // _Complex int -> _Complex float
1201
0
  if (ConvertInt)
1202
0
    IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1203
0
                                  CK_IntegralComplexToFloatingComplex);
1204
1205
  // float -> _Complex float
1206
0
  if (ConvertFloat)
1207
0
    FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1208
0
                                    CK_FloatingRealToComplex);
1209
1210
0
  return result;
1211
0
}
1212
1213
/// Handle arithmethic conversion with floating point types.  Helper
1214
/// function of UsualArithmeticConversions()
1215
static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1216
                                      ExprResult &RHS, QualType LHSType,
1217
0
                                      QualType RHSType, bool IsCompAssign) {
1218
0
  bool LHSFloat = LHSType->isRealFloatingType();
1219
0
  bool RHSFloat = RHSType->isRealFloatingType();
1220
1221
  // N1169 4.1.4: If one of the operands has a floating type and the other
1222
  //              operand has a fixed-point type, the fixed-point operand
1223
  //              is converted to the floating type [...]
1224
0
  if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1225
0
    if (LHSFloat)
1226
0
      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1227
0
    else if (!IsCompAssign)
1228
0
      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1229
0
    return LHSFloat ? LHSType : RHSType;
1230
0
  }
1231
1232
  // If we have two real floating types, convert the smaller operand
1233
  // to the bigger result.
1234
0
  if (LHSFloat && RHSFloat) {
1235
0
    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1236
0
    if (order > 0) {
1237
0
      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1238
0
      return LHSType;
1239
0
    }
1240
1241
0
    assert(order < 0 && "illegal float comparison");
1242
0
    if (!IsCompAssign)
1243
0
      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1244
0
    return RHSType;
1245
0
  }
1246
1247
0
  if (LHSFloat) {
1248
    // Half FP has to be promoted to float unless it is natively supported
1249
0
    if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1250
0
      LHSType = S.Context.FloatTy;
1251
1252
0
    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1253
0
                                      /*ConvertFloat=*/!IsCompAssign,
1254
0
                                      /*ConvertInt=*/ true);
1255
0
  }
1256
0
  assert(RHSFloat);
1257
0
  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1258
0
                                    /*ConvertFloat=*/ true,
1259
0
                                    /*ConvertInt=*/!IsCompAssign);
1260
0
}
1261
1262
/// Diagnose attempts to convert between __float128, __ibm128 and
1263
/// long double if there is no support for such conversion.
1264
/// Helper function of UsualArithmeticConversions().
1265
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1266
1
                                      QualType RHSType) {
1267
  // No issue if either is not a floating point type.
1268
1
  if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1269
1
    return false;
1270
1271
  // No issue if both have the same 128-bit float semantics.
1272
0
  auto *LHSComplex = LHSType->getAs<ComplexType>();
1273
0
  auto *RHSComplex = RHSType->getAs<ComplexType>();
1274
1275
0
  QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1276
0
  QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1277
1278
0
  const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1279
0
  const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1280
1281
0
  if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1282
0
       &RHSSem != &llvm::APFloat::IEEEquad()) &&
1283
0
      (&LHSSem != &llvm::APFloat::IEEEquad() ||
1284
0
       &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1285
0
    return false;
1286
1287
0
  return true;
1288
0
}
1289
1290
typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1291
1292
namespace {
1293
/// These helper callbacks are placed in an anonymous namespace to
1294
/// permit their use as function template parameters.
1295
0
ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1296
0
  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1297
0
}
1298
1299
0
ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1300
0
  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1301
0
                             CK_IntegralComplexCast);
1302
0
}
1303
}
1304
1305
/// Handle integer arithmetic conversions.  Helper function of
1306
/// UsualArithmeticConversions()
1307
template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1308
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1309
                                        ExprResult &RHS, QualType LHSType,
1310
0
                                        QualType RHSType, bool IsCompAssign) {
1311
  // The rules for this case are in C99 6.3.1.8
1312
0
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1313
0
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1314
0
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1315
0
  if (LHSSigned == RHSSigned) {
1316
    // Same signedness; use the higher-ranked type
1317
0
    if (order >= 0) {
1318
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1319
0
      return LHSType;
1320
0
    } else if (!IsCompAssign)
1321
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1322
0
    return RHSType;
1323
0
  } else if (order != (LHSSigned ? 1 : -1)) {
1324
    // The unsigned type has greater than or equal rank to the
1325
    // signed type, so use the unsigned type
1326
0
    if (RHSSigned) {
1327
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1328
0
      return LHSType;
1329
0
    } else if (!IsCompAssign)
1330
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1331
0
    return RHSType;
1332
0
  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1333
    // The two types are different widths; if we are here, that
1334
    // means the signed type is larger than the unsigned type, so
1335
    // use the signed type.
1336
0
    if (LHSSigned) {
1337
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1338
0
      return LHSType;
1339
0
    } else if (!IsCompAssign)
1340
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1341
0
    return RHSType;
1342
0
  } else {
1343
    // The signed type is higher-ranked than the unsigned type,
1344
    // but isn't actually any bigger (like unsigned int and long
1345
    // on most 32-bit systems).  Use the unsigned type corresponding
1346
    // to the signed type.
1347
0
    QualType result =
1348
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1349
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1350
0
    if (!IsCompAssign)
1351
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1352
0
    return result;
1353
0
  }
1354
0
}
Unexecuted instantiation: SemaExpr.cpp:clang::QualType handleIntegerConversion<&(anonymous namespace)::doComplexIntegralCast, &(anonymous namespace)::doComplexIntegralCast>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Unexecuted instantiation: SemaExpr.cpp:clang::QualType handleIntegerConversion<&(anonymous namespace)::doComplexIntegralCast, &(anonymous namespace)::doIntegralCast>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Unexecuted instantiation: SemaExpr.cpp:clang::QualType handleIntegerConversion<&(anonymous namespace)::doIntegralCast, &(anonymous namespace)::doComplexIntegralCast>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Unexecuted instantiation: SemaExpr.cpp:clang::QualType handleIntegerConversion<&(anonymous namespace)::doIntegralCast, &(anonymous namespace)::doIntegralCast>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
1355
1356
/// Handle conversions with GCC complex int extension.  Helper function
1357
/// of UsualArithmeticConversions()
1358
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1359
                                           ExprResult &RHS, QualType LHSType,
1360
                                           QualType RHSType,
1361
0
                                           bool IsCompAssign) {
1362
0
  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1363
0
  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1364
1365
0
  if (LHSComplexInt && RHSComplexInt) {
1366
0
    QualType LHSEltType = LHSComplexInt->getElementType();
1367
0
    QualType RHSEltType = RHSComplexInt->getElementType();
1368
0
    QualType ScalarType =
1369
0
      handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1370
0
        (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1371
1372
0
    return S.Context.getComplexType(ScalarType);
1373
0
  }
1374
1375
0
  if (LHSComplexInt) {
1376
0
    QualType LHSEltType = LHSComplexInt->getElementType();
1377
0
    QualType ScalarType =
1378
0
      handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1379
0
        (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1380
0
    QualType ComplexType = S.Context.getComplexType(ScalarType);
1381
0
    RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1382
0
                              CK_IntegralRealToComplex);
1383
1384
0
    return ComplexType;
1385
0
  }
1386
1387
0
  assert(RHSComplexInt);
1388
1389
0
  QualType RHSEltType = RHSComplexInt->getElementType();
1390
0
  QualType ScalarType =
1391
0
    handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1392
0
      (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1393
0
  QualType ComplexType = S.Context.getComplexType(ScalarType);
1394
1395
0
  if (!IsCompAssign)
1396
0
    LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1397
0
                              CK_IntegralRealToComplex);
1398
0
  return ComplexType;
1399
0
}
1400
1401
/// Return the rank of a given fixed point or integer type. The value itself
1402
/// doesn't matter, but the values must be increasing with proper increasing
1403
/// rank as described in N1169 4.1.1.
1404
0
static unsigned GetFixedPointRank(QualType Ty) {
1405
0
  const auto *BTy = Ty->getAs<BuiltinType>();
1406
0
  assert(BTy && "Expected a builtin type.");
1407
1408
0
  switch (BTy->getKind()) {
1409
0
  case BuiltinType::ShortFract:
1410
0
  case BuiltinType::UShortFract:
1411
0
  case BuiltinType::SatShortFract:
1412
0
  case BuiltinType::SatUShortFract:
1413
0
    return 1;
1414
0
  case BuiltinType::Fract:
1415
0
  case BuiltinType::UFract:
1416
0
  case BuiltinType::SatFract:
1417
0
  case BuiltinType::SatUFract:
1418
0
    return 2;
1419
0
  case BuiltinType::LongFract:
1420
0
  case BuiltinType::ULongFract:
1421
0
  case BuiltinType::SatLongFract:
1422
0
  case BuiltinType::SatULongFract:
1423
0
    return 3;
1424
0
  case BuiltinType::ShortAccum:
1425
0
  case BuiltinType::UShortAccum:
1426
0
  case BuiltinType::SatShortAccum:
1427
0
  case BuiltinType::SatUShortAccum:
1428
0
    return 4;
1429
0
  case BuiltinType::Accum:
1430
0
  case BuiltinType::UAccum:
1431
0
  case BuiltinType::SatAccum:
1432
0
  case BuiltinType::SatUAccum:
1433
0
    return 5;
1434
0
  case BuiltinType::LongAccum:
1435
0
  case BuiltinType::ULongAccum:
1436
0
  case BuiltinType::SatLongAccum:
1437
0
  case BuiltinType::SatULongAccum:
1438
0
    return 6;
1439
0
  default:
1440
0
    if (BTy->isInteger())
1441
0
      return 0;
1442
0
    llvm_unreachable("Unexpected fixed point or integer type");
1443
0
  }
1444
0
}
1445
1446
/// handleFixedPointConversion - Fixed point operations between fixed
1447
/// point types and integers or other fixed point types do not fall under
1448
/// usual arithmetic conversion since these conversions could result in loss
1449
/// of precsision (N1169 4.1.4). These operations should be calculated with
1450
/// the full precision of their result type (N1169 4.1.6.2.1).
1451
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1452
0
                                           QualType RHSTy) {
1453
0
  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1454
0
         "Expected at least one of the operands to be a fixed point type");
1455
0
  assert((LHSTy->isFixedPointOrIntegerType() ||
1456
0
          RHSTy->isFixedPointOrIntegerType()) &&
1457
0
         "Special fixed point arithmetic operation conversions are only "
1458
0
         "applied to ints or other fixed point types");
1459
1460
  // If one operand has signed fixed-point type and the other operand has
1461
  // unsigned fixed-point type, then the unsigned fixed-point operand is
1462
  // converted to its corresponding signed fixed-point type and the resulting
1463
  // type is the type of the converted operand.
1464
0
  if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1465
0
    LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1466
0
  else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1467
0
    RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1468
1469
  // The result type is the type with the highest rank, whereby a fixed-point
1470
  // conversion rank is always greater than an integer conversion rank; if the
1471
  // type of either of the operands is a saturating fixedpoint type, the result
1472
  // type shall be the saturating fixed-point type corresponding to the type
1473
  // with the highest rank; the resulting value is converted (taking into
1474
  // account rounding and overflow) to the precision of the resulting type.
1475
  // Same ranks between signed and unsigned types are resolved earlier, so both
1476
  // types are either signed or both unsigned at this point.
1477
0
  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1478
0
  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1479
1480
0
  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1481
1482
0
  if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1483
0
    ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1484
1485
0
  return ResultTy;
1486
0
}
1487
1488
/// Check that the usual arithmetic conversions can be performed on this pair of
1489
/// expressions that might be of enumeration type.
1490
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1491
                                           SourceLocation Loc,
1492
0
                                           Sema::ArithConvKind ACK) {
1493
  // C++2a [expr.arith.conv]p1:
1494
  //   If one operand is of enumeration type and the other operand is of a
1495
  //   different enumeration type or a floating-point type, this behavior is
1496
  //   deprecated ([depr.arith.conv.enum]).
1497
  //
1498
  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1499
  // Eventually we will presumably reject these cases (in C++23 onwards?).
1500
0
  QualType L = LHS->getType(), R = RHS->getType();
1501
0
  bool LEnum = L->isUnscopedEnumerationType(),
1502
0
       REnum = R->isUnscopedEnumerationType();
1503
0
  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1504
0
  if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1505
0
      (REnum && L->isFloatingType())) {
1506
0
    S.Diag(Loc, S.getLangOpts().CPlusPlus26
1507
0
                    ? diag::err_arith_conv_enum_float_cxx26
1508
0
                : S.getLangOpts().CPlusPlus20
1509
0
                    ? diag::warn_arith_conv_enum_float_cxx20
1510
0
                    : diag::warn_arith_conv_enum_float)
1511
0
        << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1512
0
        << L << R;
1513
0
  } else if (!IsCompAssign && LEnum && REnum &&
1514
0
             !S.Context.hasSameUnqualifiedType(L, R)) {
1515
0
    unsigned DiagID;
1516
    // In C++ 26, usual arithmetic conversions between 2 different enum types
1517
    // are ill-formed.
1518
0
    if (S.getLangOpts().CPlusPlus26)
1519
0
      DiagID = diag::err_conv_mixed_enum_types_cxx26;
1520
0
    else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1521
0
             !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1522
      // If either enumeration type is unnamed, it's less likely that the
1523
      // user cares about this, but this situation is still deprecated in
1524
      // C++2a. Use a different warning group.
1525
0
      DiagID = S.getLangOpts().CPlusPlus20
1526
0
                    ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1527
0
                    : diag::warn_arith_conv_mixed_anon_enum_types;
1528
0
    } else if (ACK == Sema::ACK_Conditional) {
1529
      // Conditional expressions are separated out because they have
1530
      // historically had a different warning flag.
1531
0
      DiagID = S.getLangOpts().CPlusPlus20
1532
0
                   ? diag::warn_conditional_mixed_enum_types_cxx20
1533
0
                   : diag::warn_conditional_mixed_enum_types;
1534
0
    } else if (ACK == Sema::ACK_Comparison) {
1535
      // Comparison expressions are separated out because they have
1536
      // historically had a different warning flag.
1537
0
      DiagID = S.getLangOpts().CPlusPlus20
1538
0
                   ? diag::warn_comparison_mixed_enum_types_cxx20
1539
0
                   : diag::warn_comparison_mixed_enum_types;
1540
0
    } else {
1541
0
      DiagID = S.getLangOpts().CPlusPlus20
1542
0
                   ? diag::warn_arith_conv_mixed_enum_types_cxx20
1543
0
                   : diag::warn_arith_conv_mixed_enum_types;
1544
0
    }
1545
0
    S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1546
0
                        << (int)ACK << L << R;
1547
0
  }
1548
0
}
1549
1550
/// UsualArithmeticConversions - Performs various conversions that are common to
1551
/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1552
/// routine returns the first non-arithmetic type found. The client is
1553
/// responsible for emitting appropriate error diagnostics.
1554
QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1555
                                          SourceLocation Loc,
1556
0
                                          ArithConvKind ACK) {
1557
0
  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1558
1559
0
  if (ACK != ACK_CompAssign) {
1560
0
    LHS = UsualUnaryConversions(LHS.get());
1561
0
    if (LHS.isInvalid())
1562
0
      return QualType();
1563
0
  }
1564
1565
0
  RHS = UsualUnaryConversions(RHS.get());
1566
0
  if (RHS.isInvalid())
1567
0
    return QualType();
1568
1569
  // For conversion purposes, we ignore any qualifiers.
1570
  // For example, "const float" and "float" are equivalent.
1571
0
  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1572
0
  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1573
1574
  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1575
0
  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1576
0
    LHSType = AtomicLHS->getValueType();
1577
1578
  // If both types are identical, no conversion is needed.
1579
0
  if (Context.hasSameType(LHSType, RHSType))
1580
0
    return Context.getCommonSugaredType(LHSType, RHSType);
1581
1582
  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1583
  // The caller can deal with this (e.g. pointer + int).
1584
0
  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1585
0
    return QualType();
1586
1587
  // Apply unary and bitfield promotions to the LHS's type.
1588
0
  QualType LHSUnpromotedType = LHSType;
1589
0
  if (Context.isPromotableIntegerType(LHSType))
1590
0
    LHSType = Context.getPromotedIntegerType(LHSType);
1591
0
  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1592
0
  if (!LHSBitfieldPromoteTy.isNull())
1593
0
    LHSType = LHSBitfieldPromoteTy;
1594
0
  if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1595
0
    LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1596
1597
  // If both types are identical, no conversion is needed.
1598
0
  if (Context.hasSameType(LHSType, RHSType))
1599
0
    return Context.getCommonSugaredType(LHSType, RHSType);
1600
1601
  // At this point, we have two different arithmetic types.
1602
1603
  // Diagnose attempts to convert between __ibm128, __float128 and long double
1604
  // where such conversions currently can't be handled.
1605
0
  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1606
0
    return QualType();
1607
1608
  // Handle complex types first (C99 6.3.1.8p1).
1609
0
  if (LHSType->isComplexType() || RHSType->isComplexType())
1610
0
    return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1611
0
                                   ACK == ACK_CompAssign);
1612
1613
  // Now handle "real" floating types (i.e. float, double, long double).
1614
0
  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1615
0
    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1616
0
                                 ACK == ACK_CompAssign);
1617
1618
  // Handle GCC complex int extension.
1619
0
  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1620
0
    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1621
0
                                      ACK == ACK_CompAssign);
1622
1623
0
  if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1624
0
    return handleFixedPointConversion(*this, LHSType, RHSType);
1625
1626
  // Finally, we have two differing integer types.
1627
0
  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1628
0
           (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1629
0
}
1630
1631
//===----------------------------------------------------------------------===//
1632
//  Semantic Analysis for various Expression Types
1633
//===----------------------------------------------------------------------===//
1634
1635
1636
ExprResult Sema::ActOnGenericSelectionExpr(
1637
    SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1638
    bool PredicateIsExpr, void *ControllingExprOrType,
1639
0
    ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1640
0
  unsigned NumAssocs = ArgTypes.size();
1641
0
  assert(NumAssocs == ArgExprs.size());
1642
1643
0
  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1644
0
  for (unsigned i = 0; i < NumAssocs; ++i) {
1645
0
    if (ArgTypes[i])
1646
0
      (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1647
0
    else
1648
0
      Types[i] = nullptr;
1649
0
  }
1650
1651
  // If we have a controlling type, we need to convert it from a parsed type
1652
  // into a semantic type and then pass that along.
1653
0
  if (!PredicateIsExpr) {
1654
0
    TypeSourceInfo *ControllingType;
1655
0
    (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1656
0
                            &ControllingType);
1657
0
    assert(ControllingType && "couldn't get the type out of the parser");
1658
0
    ControllingExprOrType = ControllingType;
1659
0
  }
1660
1661
0
  ExprResult ER = CreateGenericSelectionExpr(
1662
0
      KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1663
0
      llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1664
0
  delete [] Types;
1665
0
  return ER;
1666
0
}
1667
1668
ExprResult Sema::CreateGenericSelectionExpr(
1669
    SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1670
    bool PredicateIsExpr, void *ControllingExprOrType,
1671
0
    ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1672
0
  unsigned NumAssocs = Types.size();
1673
0
  assert(NumAssocs == Exprs.size());
1674
0
  assert(ControllingExprOrType &&
1675
0
         "Must have either a controlling expression or a controlling type");
1676
1677
0
  Expr *ControllingExpr = nullptr;
1678
0
  TypeSourceInfo *ControllingType = nullptr;
1679
0
  if (PredicateIsExpr) {
1680
    // Decay and strip qualifiers for the controlling expression type, and
1681
    // handle placeholder type replacement. See committee discussion from WG14
1682
    // DR423.
1683
0
    EnterExpressionEvaluationContext Unevaluated(
1684
0
        *this, Sema::ExpressionEvaluationContext::Unevaluated);
1685
0
    ExprResult R = DefaultFunctionArrayLvalueConversion(
1686
0
        reinterpret_cast<Expr *>(ControllingExprOrType));
1687
0
    if (R.isInvalid())
1688
0
      return ExprError();
1689
0
    ControllingExpr = R.get();
1690
0
  } else {
1691
    // The extension form uses the type directly rather than converting it.
1692
0
    ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1693
0
    if (!ControllingType)
1694
0
      return ExprError();
1695
0
  }
1696
1697
0
  bool TypeErrorFound = false,
1698
0
       IsResultDependent = ControllingExpr
1699
0
                               ? ControllingExpr->isTypeDependent()
1700
0
                               : ControllingType->getType()->isDependentType(),
1701
0
       ContainsUnexpandedParameterPack =
1702
0
           ControllingExpr
1703
0
               ? ControllingExpr->containsUnexpandedParameterPack()
1704
0
               : ControllingType->getType()->containsUnexpandedParameterPack();
1705
1706
  // The controlling expression is an unevaluated operand, so side effects are
1707
  // likely unintended.
1708
0
  if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1709
0
      ControllingExpr->HasSideEffects(Context, false))
1710
0
    Diag(ControllingExpr->getExprLoc(),
1711
0
         diag::warn_side_effects_unevaluated_context);
1712
1713
0
  for (unsigned i = 0; i < NumAssocs; ++i) {
1714
0
    if (Exprs[i]->containsUnexpandedParameterPack())
1715
0
      ContainsUnexpandedParameterPack = true;
1716
1717
0
    if (Types[i]) {
1718
0
      if (Types[i]->getType()->containsUnexpandedParameterPack())
1719
0
        ContainsUnexpandedParameterPack = true;
1720
1721
0
      if (Types[i]->getType()->isDependentType()) {
1722
0
        IsResultDependent = true;
1723
0
      } else {
1724
        // We relax the restriction on use of incomplete types and non-object
1725
        // types with the type-based extension of _Generic. Allowing incomplete
1726
        // objects means those can be used as "tags" for a type-safe way to map
1727
        // to a value. Similarly, matching on function types rather than
1728
        // function pointer types can be useful. However, the restriction on VM
1729
        // types makes sense to retain as there are open questions about how
1730
        // the selection can be made at compile time.
1731
        //
1732
        // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1733
        // complete object type other than a variably modified type."
1734
0
        unsigned D = 0;
1735
0
        if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1736
0
          D = diag::err_assoc_type_incomplete;
1737
0
        else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1738
0
          D = diag::err_assoc_type_nonobject;
1739
0
        else if (Types[i]->getType()->isVariablyModifiedType())
1740
0
          D = diag::err_assoc_type_variably_modified;
1741
0
        else if (ControllingExpr) {
1742
          // Because the controlling expression undergoes lvalue conversion,
1743
          // array conversion, and function conversion, an association which is
1744
          // of array type, function type, or is qualified can never be
1745
          // reached. We will warn about this so users are less surprised by
1746
          // the unreachable association. However, we don't have to handle
1747
          // function types; that's not an object type, so it's handled above.
1748
          //
1749
          // The logic is somewhat different for C++ because C++ has different
1750
          // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1751
          // If T is a non-class type, the type of the prvalue is the cv-
1752
          // unqualified version of T. Otherwise, the type of the prvalue is T.
1753
          // The result of these rules is that all qualified types in an
1754
          // association in C are unreachable, and in C++, only qualified non-
1755
          // class types are unreachable.
1756
          //
1757
          // NB: this does not apply when the first operand is a type rather
1758
          // than an expression, because the type form does not undergo
1759
          // conversion.
1760
0
          unsigned Reason = 0;
1761
0
          QualType QT = Types[i]->getType();
1762
0
          if (QT->isArrayType())
1763
0
            Reason = 1;
1764
0
          else if (QT.hasQualifiers() &&
1765
0
                   (!LangOpts.CPlusPlus || !QT->isRecordType()))
1766
0
            Reason = 2;
1767
1768
0
          if (Reason)
1769
0
            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1770
0
                 diag::warn_unreachable_association)
1771
0
                << QT << (Reason - 1);
1772
0
        }
1773
1774
0
        if (D != 0) {
1775
0
          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1776
0
            << Types[i]->getTypeLoc().getSourceRange()
1777
0
            << Types[i]->getType();
1778
0
          TypeErrorFound = true;
1779
0
        }
1780
1781
        // C11 6.5.1.1p2 "No two generic associations in the same generic
1782
        // selection shall specify compatible types."
1783
0
        for (unsigned j = i+1; j < NumAssocs; ++j)
1784
0
          if (Types[j] && !Types[j]->getType()->isDependentType() &&
1785
0
              Context.typesAreCompatible(Types[i]->getType(),
1786
0
                                         Types[j]->getType())) {
1787
0
            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1788
0
                 diag::err_assoc_compatible_types)
1789
0
              << Types[j]->getTypeLoc().getSourceRange()
1790
0
              << Types[j]->getType()
1791
0
              << Types[i]->getType();
1792
0
            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1793
0
                 diag::note_compat_assoc)
1794
0
              << Types[i]->getTypeLoc().getSourceRange()
1795
0
              << Types[i]->getType();
1796
0
            TypeErrorFound = true;
1797
0
          }
1798
0
      }
1799
0
    }
1800
0
  }
1801
0
  if (TypeErrorFound)
1802
0
    return ExprError();
1803
1804
  // If we determined that the generic selection is result-dependent, don't
1805
  // try to compute the result expression.
1806
0
  if (IsResultDependent) {
1807
0
    if (ControllingExpr)
1808
0
      return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1809
0
                                          Types, Exprs, DefaultLoc, RParenLoc,
1810
0
                                          ContainsUnexpandedParameterPack);
1811
0
    return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1812
0
                                        Exprs, DefaultLoc, RParenLoc,
1813
0
                                        ContainsUnexpandedParameterPack);
1814
0
  }
1815
1816
0
  SmallVector<unsigned, 1> CompatIndices;
1817
0
  unsigned DefaultIndex = -1U;
1818
  // Look at the canonical type of the controlling expression in case it was a
1819
  // deduced type like __auto_type. However, when issuing diagnostics, use the
1820
  // type the user wrote in source rather than the canonical one.
1821
0
  for (unsigned i = 0; i < NumAssocs; ++i) {
1822
0
    if (!Types[i])
1823
0
      DefaultIndex = i;
1824
0
    else if (ControllingExpr &&
1825
0
             Context.typesAreCompatible(
1826
0
                 ControllingExpr->getType().getCanonicalType(),
1827
0
                 Types[i]->getType()))
1828
0
      CompatIndices.push_back(i);
1829
0
    else if (ControllingType &&
1830
0
             Context.typesAreCompatible(
1831
0
                 ControllingType->getType().getCanonicalType(),
1832
0
                 Types[i]->getType()))
1833
0
      CompatIndices.push_back(i);
1834
0
  }
1835
1836
0
  auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1837
0
                                       TypeSourceInfo *ControllingType) {
1838
    // We strip parens here because the controlling expression is typically
1839
    // parenthesized in macro definitions.
1840
0
    if (ControllingExpr)
1841
0
      ControllingExpr = ControllingExpr->IgnoreParens();
1842
1843
0
    SourceRange SR = ControllingExpr
1844
0
                         ? ControllingExpr->getSourceRange()
1845
0
                         : ControllingType->getTypeLoc().getSourceRange();
1846
0
    QualType QT = ControllingExpr ? ControllingExpr->getType()
1847
0
                                  : ControllingType->getType();
1848
1849
0
    return std::make_pair(SR, QT);
1850
0
  };
1851
1852
  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1853
  // type compatible with at most one of the types named in its generic
1854
  // association list."
1855
0
  if (CompatIndices.size() > 1) {
1856
0
    auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1857
0
    SourceRange SR = P.first;
1858
0
    Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1859
0
        << SR << P.second << (unsigned)CompatIndices.size();
1860
0
    for (unsigned I : CompatIndices) {
1861
0
      Diag(Types[I]->getTypeLoc().getBeginLoc(),
1862
0
           diag::note_compat_assoc)
1863
0
        << Types[I]->getTypeLoc().getSourceRange()
1864
0
        << Types[I]->getType();
1865
0
    }
1866
0
    return ExprError();
1867
0
  }
1868
1869
  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1870
  // its controlling expression shall have type compatible with exactly one of
1871
  // the types named in its generic association list."
1872
0
  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1873
0
    auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1874
0
    SourceRange SR = P.first;
1875
0
    Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1876
0
    return ExprError();
1877
0
  }
1878
1879
  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1880
  // type name that is compatible with the type of the controlling expression,
1881
  // then the result expression of the generic selection is the expression
1882
  // in that generic association. Otherwise, the result expression of the
1883
  // generic selection is the expression in the default generic association."
1884
0
  unsigned ResultIndex =
1885
0
    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1886
1887
0
  if (ControllingExpr) {
1888
0
    return GenericSelectionExpr::Create(
1889
0
        Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1890
0
        ContainsUnexpandedParameterPack, ResultIndex);
1891
0
  }
1892
0
  return GenericSelectionExpr::Create(
1893
0
      Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1894
0
      ContainsUnexpandedParameterPack, ResultIndex);
1895
0
}
1896
1897
0
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
1898
0
  switch (Kind) {
1899
0
  default:
1900
0
    llvm_unreachable("unexpected TokenKind");
1901
0
  case tok::kw___func__:
1902
0
    return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1903
0
  case tok::kw___FUNCTION__:
1904
0
    return PredefinedIdentKind::Function;
1905
0
  case tok::kw___FUNCDNAME__:
1906
0
    return PredefinedIdentKind::FuncDName; // [MS]
1907
0
  case tok::kw___FUNCSIG__:
1908
0
    return PredefinedIdentKind::FuncSig; // [MS]
1909
0
  case tok::kw_L__FUNCTION__:
1910
0
    return PredefinedIdentKind::LFunction; // [MS]
1911
0
  case tok::kw_L__FUNCSIG__:
1912
0
    return PredefinedIdentKind::LFuncSig; // [MS]
1913
0
  case tok::kw___PRETTY_FUNCTION__:
1914
0
    return PredefinedIdentKind::PrettyFunction; // [GNU]
1915
0
  }
1916
0
}
1917
1918
/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1919
/// to determine the value of a PredefinedExpr. This can be either a
1920
/// block, lambda, captured statement, function, otherwise a nullptr.
1921
0
static Decl *getPredefinedExprDecl(DeclContext *DC) {
1922
0
  while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1923
0
    DC = DC->getParent();
1924
0
  return cast_or_null<Decl>(DC);
1925
0
}
1926
1927
/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1928
/// location of the token and the offset of the ud-suffix within it.
1929
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1930
2
                                     unsigned Offset) {
1931
2
  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1932
2
                                        S.getLangOpts());
1933
2
}
1934
1935
/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1936
/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1937
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1938
                                                 IdentifierInfo *UDSuffix,
1939
                                                 SourceLocation UDSuffixLoc,
1940
                                                 ArrayRef<Expr*> Args,
1941
1
                                                 SourceLocation LitEndLoc) {
1942
1
  assert(Args.size() <= 2 && "too many arguments for literal operator");
1943
1944
0
  QualType ArgTy[2];
1945
2
  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1946
1
    ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1947
1
    if (ArgTy[ArgIdx]->isArrayType())
1948
0
      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1949
1
  }
1950
1951
1
  DeclarationName OpName =
1952
1
    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1953
1
  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1954
1
  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1955
1956
1
  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1957
1
  if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1958
1
                              /*AllowRaw*/ false, /*AllowTemplate*/ false,
1959
1
                              /*AllowStringTemplatePack*/ false,
1960
1
                              /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1961
1
    return ExprError();
1962
1963
0
  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1964
1
}
1965
1966
0
ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
1967
  // StringToks needs backing storage as it doesn't hold array elements itself
1968
0
  std::vector<Token> ExpandedToks;
1969
0
  if (getLangOpts().MicrosoftExt)
1970
0
    StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1971
1972
0
  StringLiteralParser Literal(StringToks, PP,
1973
0
                              StringLiteralEvalMethod::Unevaluated);
1974
0
  if (Literal.hadError)
1975
0
    return ExprError();
1976
1977
0
  SmallVector<SourceLocation, 4> StringTokLocs;
1978
0
  for (const Token &Tok : StringToks)
1979
0
    StringTokLocs.push_back(Tok.getLocation());
1980
1981
0
  StringLiteral *Lit = StringLiteral::Create(
1982
0
      Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1983
0
      &StringTokLocs[0], StringTokLocs.size());
1984
1985
0
  if (!Literal.getUDSuffix().empty()) {
1986
0
    SourceLocation UDSuffixLoc =
1987
0
        getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1988
0
                       Literal.getUDSuffixOffset());
1989
0
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1990
0
  }
1991
1992
0
  return Lit;
1993
0
}
1994
1995
std::vector<Token>
1996
0
Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
1997
  // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1998
  // local macros that expand to string literals that may be concatenated.
1999
  // These macros are expanded here (in Sema), because StringLiteralParser
2000
  // (in Lex) doesn't know the enclosing function (because it hasn't been
2001
  // parsed yet).
2002
0
  assert(getLangOpts().MicrosoftExt);
2003
2004
  // Note: Although function local macros are defined only inside functions,
2005
  // we ensure a valid `CurrentDecl` even outside of a function. This allows
2006
  // expansion of macros into empty string literals without additional checks.
2007
0
  Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2008
0
  if (!CurrentDecl)
2009
0
    CurrentDecl = Context.getTranslationUnitDecl();
2010
2011
0
  std::vector<Token> ExpandedToks;
2012
0
  ExpandedToks.reserve(Toks.size());
2013
0
  for (const Token &Tok : Toks) {
2014
0
    if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2015
0
      assert(tok::isStringLiteral(Tok.getKind()));
2016
0
      ExpandedToks.emplace_back(Tok);
2017
0
      continue;
2018
0
    }
2019
0
    if (isa<TranslationUnitDecl>(CurrentDecl))
2020
0
      Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2021
    // Stringify predefined expression
2022
0
    Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2023
0
        << Tok.getKind();
2024
0
    SmallString<64> Str;
2025
0
    llvm::raw_svector_ostream OS(Str);
2026
0
    Token &Exp = ExpandedToks.emplace_back();
2027
0
    Exp.startToken();
2028
0
    if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2029
0
        Tok.getKind() == tok::kw_L__FUNCSIG__) {
2030
0
      OS << 'L';
2031
0
      Exp.setKind(tok::wide_string_literal);
2032
0
    } else {
2033
0
      Exp.setKind(tok::string_literal);
2034
0
    }
2035
0
    OS << '"'
2036
0
       << Lexer::Stringify(PredefinedExpr::ComputeName(
2037
0
              getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2038
0
       << '"';
2039
0
    PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2040
0
  }
2041
0
  return ExpandedToks;
2042
0
}
2043
2044
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2045
/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
2046
/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2047
/// multiple tokens.  However, the common case is that StringToks points to one
2048
/// string.
2049
///
2050
ExprResult
2051
1
Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2052
1
  assert(!StringToks.empty() && "Must have at least one string!");
2053
2054
  // StringToks needs backing storage as it doesn't hold array elements itself
2055
0
  std::vector<Token> ExpandedToks;
2056
1
  if (getLangOpts().MicrosoftExt)
2057
0
    StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2058
2059
1
  StringLiteralParser Literal(StringToks, PP);
2060
1
  if (Literal.hadError)
2061
0
    return ExprError();
2062
2063
1
  SmallVector<SourceLocation, 4> StringTokLocs;
2064
1
  for (const Token &Tok : StringToks)
2065
1
    StringTokLocs.push_back(Tok.getLocation());
2066
2067
1
  QualType CharTy = Context.CharTy;
2068
1
  StringLiteralKind Kind = StringLiteralKind::Ordinary;
2069
1
  if (Literal.isWide()) {
2070
0
    CharTy = Context.getWideCharType();
2071
0
    Kind = StringLiteralKind::Wide;
2072
1
  } else if (Literal.isUTF8()) {
2073
0
    if (getLangOpts().Char8)
2074
0
      CharTy = Context.Char8Ty;
2075
0
    Kind = StringLiteralKind::UTF8;
2076
1
  } else if (Literal.isUTF16()) {
2077
0
    CharTy = Context.Char16Ty;
2078
0
    Kind = StringLiteralKind::UTF16;
2079
1
  } else if (Literal.isUTF32()) {
2080
0
    CharTy = Context.Char32Ty;
2081
0
    Kind = StringLiteralKind::UTF32;
2082
1
  } else if (Literal.isPascal()) {
2083
0
    CharTy = Context.UnsignedCharTy;
2084
0
  }
2085
2086
  // Warn on initializing an array of char from a u8 string literal; this
2087
  // becomes ill-formed in C++2a.
2088
1
  if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
2089
1
      !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2090
0
    Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2091
2092
    // Create removals for all 'u8' prefixes in the string literal(s). This
2093
    // ensures C++2a compatibility (but may change the program behavior when
2094
    // built by non-Clang compilers for which the execution character set is
2095
    // not always UTF-8).
2096
0
    auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2097
0
    SourceLocation RemovalDiagLoc;
2098
0
    for (const Token &Tok : StringToks) {
2099
0
      if (Tok.getKind() == tok::utf8_string_literal) {
2100
0
        if (RemovalDiagLoc.isInvalid())
2101
0
          RemovalDiagLoc = Tok.getLocation();
2102
0
        RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2103
0
            Tok.getLocation(),
2104
0
            Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2105
0
                                           getSourceManager(), getLangOpts())));
2106
0
      }
2107
0
    }
2108
0
    Diag(RemovalDiagLoc, RemovalDiag);
2109
0
  }
2110
2111
1
  QualType StrTy =
2112
1
      Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2113
2114
  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2115
1
  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2116
1
                                             Kind, Literal.Pascal, StrTy,
2117
1
                                             &StringTokLocs[0],
2118
1
                                             StringTokLocs.size());
2119
1
  if (Literal.getUDSuffix().empty())
2120
1
    return Lit;
2121
2122
  // We're building a user-defined literal.
2123
0
  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2124
0
  SourceLocation UDSuffixLoc =
2125
0
    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2126
0
                   Literal.getUDSuffixOffset());
2127
2128
  // Make sure we're allowed user-defined literals here.
2129
0
  if (!UDLScope)
2130
0
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2131
2132
  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2133
  //   operator "" X (str, len)
2134
0
  QualType SizeType = Context.getSizeType();
2135
2136
0
  DeclarationName OpName =
2137
0
    Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2138
0
  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2139
0
  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2140
2141
0
  QualType ArgTy[] = {
2142
0
    Context.getArrayDecayedType(StrTy), SizeType
2143
0
  };
2144
2145
0
  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2146
0
  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2147
0
                                /*AllowRaw*/ false, /*AllowTemplate*/ true,
2148
0
                                /*AllowStringTemplatePack*/ true,
2149
0
                                /*DiagnoseMissing*/ true, Lit)) {
2150
2151
0
  case LOLR_Cooked: {
2152
0
    llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2153
0
    IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2154
0
                                                    StringTokLocs[0]);
2155
0
    Expr *Args[] = { Lit, LenArg };
2156
2157
0
    return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2158
0
  }
2159
2160
0
  case LOLR_Template: {
2161
0
    TemplateArgumentListInfo ExplicitArgs;
2162
0
    TemplateArgument Arg(Lit);
2163
0
    TemplateArgumentLocInfo ArgInfo(Lit);
2164
0
    ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2165
0
    return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2166
0
                                    StringTokLocs.back(), &ExplicitArgs);
2167
0
  }
2168
2169
0
  case LOLR_StringTemplatePack: {
2170
0
    TemplateArgumentListInfo ExplicitArgs;
2171
2172
0
    unsigned CharBits = Context.getIntWidth(CharTy);
2173
0
    bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2174
0
    llvm::APSInt Value(CharBits, CharIsUnsigned);
2175
2176
0
    TemplateArgument TypeArg(CharTy);
2177
0
    TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2178
0
    ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2179
2180
0
    for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2181
0
      Value = Lit->getCodeUnit(I);
2182
0
      TemplateArgument Arg(Context, Value, CharTy);
2183
0
      TemplateArgumentLocInfo ArgInfo;
2184
0
      ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2185
0
    }
2186
0
    return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2187
0
                                    StringTokLocs.back(), &ExplicitArgs);
2188
0
  }
2189
0
  case LOLR_Raw:
2190
0
  case LOLR_ErrorNoDiagnostic:
2191
0
    llvm_unreachable("unexpected literal operator lookup result");
2192
0
  case LOLR_Error:
2193
0
    return ExprError();
2194
0
  }
2195
0
  llvm_unreachable("unexpected literal operator lookup result");
2196
0
}
2197
2198
DeclRefExpr *
2199
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2200
                       SourceLocation Loc,
2201
0
                       const CXXScopeSpec *SS) {
2202
0
  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2203
0
  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2204
0
}
2205
2206
DeclRefExpr *
2207
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2208
                       const DeclarationNameInfo &NameInfo,
2209
                       const CXXScopeSpec *SS, NamedDecl *FoundD,
2210
                       SourceLocation TemplateKWLoc,
2211
59
                       const TemplateArgumentListInfo *TemplateArgs) {
2212
59
  NestedNameSpecifierLoc NNS =
2213
59
      SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2214
59
  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2215
59
                          TemplateArgs);
2216
59
}
2217
2218
// CUDA/HIP: Check whether a captured reference variable is referencing a
2219
// host variable in a device or host device lambda.
2220
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2221
1
                                                            VarDecl *VD) {
2222
1
  if (!S.getLangOpts().CUDA || !VD->hasInit())
2223
1
    return false;
2224
0
  assert(VD->getType()->isReferenceType());
2225
2226
  // Check whether the reference variable is referencing a host variable.
2227
0
  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2228
0
  if (!DRE)
2229
0
    return false;
2230
0
  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2231
0
  if (!Referee || !Referee->hasGlobalStorage() ||
2232
0
      Referee->hasAttr<CUDADeviceAttr>())
2233
0
    return false;
2234
2235
  // Check whether the current function is a device or host device lambda.
2236
  // Check whether the reference variable is a capture by getDeclContext()
2237
  // since refersToEnclosingVariableOrCapture() is not ready at this point.
2238
0
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2239
0
  if (MD && MD->getParent()->isLambda() &&
2240
0
      MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2241
0
      VD->getDeclContext() != MD)
2242
0
    return true;
2243
2244
0
  return false;
2245
0
}
2246
2247
59
NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2248
  // A declaration named in an unevaluated operand never constitutes an odr-use.
2249
59
  if (isUnevaluatedContext())
2250
0
    return NOUR_Unevaluated;
2251
2252
  // C++2a [basic.def.odr]p4:
2253
  //   A variable x whose name appears as a potentially-evaluated expression e
2254
  //   is odr-used by e unless [...] x is a reference that is usable in
2255
  //   constant expressions.
2256
  // CUDA/HIP:
2257
  //   If a reference variable referencing a host variable is captured in a
2258
  //   device or host device lambda, the value of the referee must be copied
2259
  //   to the capture and the reference variable must be treated as odr-use
2260
  //   since the value of the referee is not known at compile time and must
2261
  //   be loaded from the captured.
2262
59
  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2263
59
    if (VD->getType()->isReferenceType() &&
2264
59
        !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2265
59
        !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2266
59
        VD->isUsableInConstantExpressions(Context))
2267
0
      return NOUR_Constant;
2268
59
  }
2269
2270
  // All remaining non-variable cases constitute an odr-use. For variables, we
2271
  // need to wait and see how the expression is used.
2272
59
  return NOUR_None;
2273
59
}
2274
2275
/// BuildDeclRefExpr - Build an expression that references a
2276
/// declaration that does not require a closure capture.
2277
DeclRefExpr *
2278
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2279
                       const DeclarationNameInfo &NameInfo,
2280
                       NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2281
                       SourceLocation TemplateKWLoc,
2282
59
                       const TemplateArgumentListInfo *TemplateArgs) {
2283
59
  bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2284
59
                                  NeedToCaptureVariable(D, NameInfo.getLoc());
2285
2286
59
  DeclRefExpr *E = DeclRefExpr::Create(
2287
59
      Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2288
59
      VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2289
59
  MarkDeclRefReferenced(E);
2290
2291
  // C++ [except.spec]p17:
2292
  //   An exception-specification is considered to be needed when:
2293
  //   - in an expression, the function is the unique lookup result or
2294
  //     the selected member of a set of overloaded functions.
2295
  //
2296
  // We delay doing this until after we've built the function reference and
2297
  // marked it as used so that:
2298
  //  a) if the function is defaulted, we get errors from defining it before /
2299
  //     instead of errors from computing its exception specification, and
2300
  //  b) if the function is a defaulted comparison, we can use the body we
2301
  //     build when defining it as input to the exception specification
2302
  //     computation rather than computing a new body.
2303
59
  if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2304
0
    if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2305
0
      if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2306
0
        E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2307
0
    }
2308
0
  }
2309
2310
59
  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2311
59
      Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2312
59
      !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2313
0
    getCurFunction()->recordUseOfWeak(E);
2314
2315
59
  const auto *FD = dyn_cast<FieldDecl>(D);
2316
59
  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2317
0
    FD = IFD->getAnonField();
2318
59
  if (FD) {
2319
0
    UnusedPrivateFields.remove(FD);
2320
    // Just in case we're building an illegal pointer-to-member.
2321
0
    if (FD->isBitField())
2322
0
      E->setObjectKind(OK_BitField);
2323
0
  }
2324
2325
  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2326
  // designates a bit-field.
2327
59
  if (const auto *BD = dyn_cast<BindingDecl>(D))
2328
0
    if (const auto *BE = BD->getBinding())
2329
0
      E->setObjectKind(BE->getObjectKind());
2330
2331
59
  return E;
2332
59
}
2333
2334
/// Decomposes the given name into a DeclarationNameInfo, its location, and
2335
/// possibly a list of template arguments.
2336
///
2337
/// If this produces template arguments, it is permitted to call
2338
/// DecomposeTemplateName.
2339
///
2340
/// This actually loses a lot of source location information for
2341
/// non-standard name kinds; we should consider preserving that in
2342
/// some way.
2343
void
2344
Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2345
                             TemplateArgumentListInfo &Buffer,
2346
                             DeclarationNameInfo &NameInfo,
2347
585
                             const TemplateArgumentListInfo *&TemplateArgs) {
2348
585
  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2349
0
    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2350
0
    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2351
2352
0
    ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2353
0
                                       Id.TemplateId->NumArgs);
2354
0
    translateTemplateArguments(TemplateArgsPtr, Buffer);
2355
2356
0
    TemplateName TName = Id.TemplateId->Template.get();
2357
0
    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2358
0
    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2359
0
    TemplateArgs = &Buffer;
2360
585
  } else {
2361
585
    NameInfo = GetNameFromUnqualifiedId(Id);
2362
585
    TemplateArgs = nullptr;
2363
585
  }
2364
585
}
2365
2366
static void emitEmptyLookupTypoDiagnostic(
2367
    const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2368
    DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2369
68
    unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2370
68
  DeclContext *Ctx =
2371
68
      SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2372
68
  if (!TC) {
2373
    // Emit a special diagnostic for failed member lookups.
2374
    // FIXME: computing the declaration context might fail here (?)
2375
68
    if (Ctx)
2376
0
      SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2377
0
                                                 << SS.getRange();
2378
68
    else
2379
68
      SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2380
68
    return;
2381
68
  }
2382
2383
0
  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2384
0
  bool DroppedSpecifier =
2385
0
      TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2386
0
  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2387
0
                        ? diag::note_implicit_param_decl
2388
0
                        : diag::note_previous_decl;
2389
0
  if (!Ctx)
2390
0
    SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2391
0
                         SemaRef.PDiag(NoteID));
2392
0
  else
2393
0
    SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2394
0
                                 << Typo << Ctx << DroppedSpecifier
2395
0
                                 << SS.getRange(),
2396
0
                         SemaRef.PDiag(NoteID));
2397
0
}
2398
2399
/// Diagnose a lookup that found results in an enclosing class during error
2400
/// recovery. This usually indicates that the results were found in a dependent
2401
/// base class that could not be searched as part of a template definition.
2402
/// Always issues a diagnostic (though this may be only a warning in MS
2403
/// compatibility mode).
2404
///
2405
/// Return \c true if the error is unrecoverable, or \c false if the caller
2406
/// should attempt to recover using these lookup results.
2407
0
bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2408
  // During a default argument instantiation the CurContext points
2409
  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2410
  // function parameter list, hence add an explicit check.
2411
0
  bool isDefaultArgument =
2412
0
      !CodeSynthesisContexts.empty() &&
2413
0
      CodeSynthesisContexts.back().Kind ==
2414
0
          CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2415
0
  const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2416
0
  bool isInstance = CurMethod && CurMethod->isInstance() &&
2417
0
                    R.getNamingClass() == CurMethod->getParent() &&
2418
0
                    !isDefaultArgument;
2419
2420
  // There are two ways we can find a class-scope declaration during template
2421
  // instantiation that we did not find in the template definition: if it is a
2422
  // member of a dependent base class, or if it is declared after the point of
2423
  // use in the same class. Distinguish these by comparing the class in which
2424
  // the member was found to the naming class of the lookup.
2425
0
  unsigned DiagID = diag::err_found_in_dependent_base;
2426
0
  unsigned NoteID = diag::note_member_declared_at;
2427
0
  if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2428
0
    DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2429
0
                                      : diag::err_found_later_in_class;
2430
0
  } else if (getLangOpts().MSVCCompat) {
2431
0
    DiagID = diag::ext_found_in_dependent_base;
2432
0
    NoteID = diag::note_dependent_member_use;
2433
0
  }
2434
2435
0
  if (isInstance) {
2436
    // Give a code modification hint to insert 'this->'.
2437
0
    Diag(R.getNameLoc(), DiagID)
2438
0
        << R.getLookupName()
2439
0
        << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2440
0
    CheckCXXThisCapture(R.getNameLoc());
2441
0
  } else {
2442
    // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2443
    // they're not shadowed).
2444
0
    Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2445
0
  }
2446
2447
0
  for (const NamedDecl *D : R)
2448
0
    Diag(D->getLocation(), NoteID);
2449
2450
  // Return true if we are inside a default argument instantiation
2451
  // and the found name refers to an instance member function, otherwise
2452
  // the caller will try to create an implicit member call and this is wrong
2453
  // for default arguments.
2454
  //
2455
  // FIXME: Is this special case necessary? We could allow the caller to
2456
  // diagnose this.
2457
0
  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2458
0
    Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2459
0
    return true;
2460
0
  }
2461
2462
  // Tell the callee to try to recover.
2463
0
  return false;
2464
0
}
2465
2466
/// Diagnose an empty lookup.
2467
///
2468
/// \return false if new lookup candidates were found
2469
bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2470
                               CorrectionCandidateCallback &CCC,
2471
                               TemplateArgumentListInfo *ExplicitTemplateArgs,
2472
                               ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2473
356
                               TypoExpr **Out) {
2474
356
  DeclarationName Name = R.getLookupName();
2475
2476
356
  unsigned diagnostic = diag::err_undeclared_var_use;
2477
356
  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2478
356
  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2479
356
      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2480
356
      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2481
0
    diagnostic = diag::err_undeclared_use;
2482
0
    diagnostic_suggest = diag::err_undeclared_use_suggest;
2483
0
  }
2484
2485
  // If the original lookup was an unqualified lookup, fake an
2486
  // unqualified lookup.  This is useful when (for example) the
2487
  // original lookup would not have found something because it was a
2488
  // dependent name.
2489
356
  DeclContext *DC =
2490
356
      LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2491
712
  while (DC) {
2492
356
    if (isa<CXXRecordDecl>(DC)) {
2493
0
      LookupQualifiedName(R, DC);
2494
2495
0
      if (!R.empty()) {
2496
        // Don't give errors about ambiguities in this lookup.
2497
0
        R.suppressDiagnostics();
2498
2499
        // If there's a best viable function among the results, only mention
2500
        // that one in the notes.
2501
0
        OverloadCandidateSet Candidates(R.getNameLoc(),
2502
0
                                        OverloadCandidateSet::CSK_Normal);
2503
0
        AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2504
0
        OverloadCandidateSet::iterator Best;
2505
0
        if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2506
0
            OR_Success) {
2507
0
          R.clear();
2508
0
          R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2509
0
          R.resolveKind();
2510
0
        }
2511
2512
0
        return DiagnoseDependentMemberLookup(R);
2513
0
      }
2514
2515
0
      R.clear();
2516
0
    }
2517
2518
356
    DC = DC->getLookupParent();
2519
356
  }
2520
2521
  // We didn't find anything, so try to correct for a typo.
2522
356
  TypoCorrection Corrected;
2523
356
  if (S && Out) {
2524
356
    SourceLocation TypoLoc = R.getNameLoc();
2525
356
    assert(!ExplicitTemplateArgs &&
2526
356
           "Diagnosing an empty lookup with explicit template args!");
2527
0
    *Out = CorrectTypoDelayed(
2528
356
        R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2529
356
        [=](const TypoCorrection &TC) {
2530
68
          emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2531
68
                                        diagnostic, diagnostic_suggest);
2532
68
        },
2533
356
        nullptr, CTK_ErrorRecovery, LookupCtx);
2534
356
    if (*Out)
2535
68
      return true;
2536
356
  } else if (S && (Corrected =
2537
0
                       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
2538
0
                                   &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2539
0
    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2540
0
    bool DroppedSpecifier =
2541
0
        Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2542
0
    R.setLookupName(Corrected.getCorrection());
2543
2544
0
    bool AcceptableWithRecovery = false;
2545
0
    bool AcceptableWithoutRecovery = false;
2546
0
    NamedDecl *ND = Corrected.getFoundDecl();
2547
0
    if (ND) {
2548
0
      if (Corrected.isOverloaded()) {
2549
0
        OverloadCandidateSet OCS(R.getNameLoc(),
2550
0
                                 OverloadCandidateSet::CSK_Normal);
2551
0
        OverloadCandidateSet::iterator Best;
2552
0
        for (NamedDecl *CD : Corrected) {
2553
0
          if (FunctionTemplateDecl *FTD =
2554
0
                   dyn_cast<FunctionTemplateDecl>(CD))
2555
0
            AddTemplateOverloadCandidate(
2556
0
                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2557
0
                Args, OCS);
2558
0
          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2559
0
            if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2560
0
              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2561
0
                                   Args, OCS);
2562
0
        }
2563
0
        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2564
0
        case OR_Success:
2565
0
          ND = Best->FoundDecl;
2566
0
          Corrected.setCorrectionDecl(ND);
2567
0
          break;
2568
0
        default:
2569
          // FIXME: Arbitrarily pick the first declaration for the note.
2570
0
          Corrected.setCorrectionDecl(ND);
2571
0
          break;
2572
0
        }
2573
0
      }
2574
0
      R.addDecl(ND);
2575
0
      if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2576
0
        CXXRecordDecl *Record = nullptr;
2577
0
        if (Corrected.getCorrectionSpecifier()) {
2578
0
          const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2579
0
          Record = Ty->getAsCXXRecordDecl();
2580
0
        }
2581
0
        if (!Record)
2582
0
          Record = cast<CXXRecordDecl>(
2583
0
              ND->getDeclContext()->getRedeclContext());
2584
0
        R.setNamingClass(Record);
2585
0
      }
2586
2587
0
      auto *UnderlyingND = ND->getUnderlyingDecl();
2588
0
      AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2589
0
                               isa<FunctionTemplateDecl>(UnderlyingND);
2590
      // FIXME: If we ended up with a typo for a type name or
2591
      // Objective-C class name, we're in trouble because the parser
2592
      // is in the wrong place to recover. Suggest the typo
2593
      // correction, but don't make it a fix-it since we're not going
2594
      // to recover well anyway.
2595
0
      AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2596
0
                                  getAsTypeTemplateDecl(UnderlyingND) ||
2597
0
                                  isa<ObjCInterfaceDecl>(UnderlyingND);
2598
0
    } else {
2599
      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2600
      // because we aren't able to recover.
2601
0
      AcceptableWithoutRecovery = true;
2602
0
    }
2603
2604
0
    if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2605
0
      unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2606
0
                            ? diag::note_implicit_param_decl
2607
0
                            : diag::note_previous_decl;
2608
0
      if (SS.isEmpty())
2609
0
        diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2610
0
                     PDiag(NoteID), AcceptableWithRecovery);
2611
0
      else
2612
0
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2613
0
                                  << Name << computeDeclContext(SS, false)
2614
0
                                  << DroppedSpecifier << SS.getRange(),
2615
0
                     PDiag(NoteID), AcceptableWithRecovery);
2616
2617
      // Tell the callee whether to try to recover.
2618
0
      return !AcceptableWithRecovery;
2619
0
    }
2620
0
  }
2621
288
  R.clear();
2622
2623
  // Emit a special diagnostic for failed member lookups.
2624
  // FIXME: computing the declaration context might fail here (?)
2625
288
  if (!SS.isEmpty()) {
2626
0
    Diag(R.getNameLoc(), diag::err_no_member)
2627
0
      << Name << computeDeclContext(SS, false)
2628
0
      << SS.getRange();
2629
0
    return true;
2630
0
  }
2631
2632
  // Give up, we can't recover.
2633
288
  Diag(R.getNameLoc(), diagnostic) << Name;
2634
288
  return true;
2635
288
}
2636
2637
/// In Microsoft mode, if we are inside a template class whose parent class has
2638
/// dependent base classes, and we can't resolve an unqualified identifier, then
2639
/// assume the identifier is a member of a dependent base class.  We can only
2640
/// recover successfully in static methods, instance methods, and other contexts
2641
/// where 'this' is available.  This doesn't precisely match MSVC's
2642
/// instantiation model, but it's close enough.
2643
static Expr *
2644
recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2645
                               DeclarationNameInfo &NameInfo,
2646
                               SourceLocation TemplateKWLoc,
2647
0
                               const TemplateArgumentListInfo *TemplateArgs) {
2648
  // Only try to recover from lookup into dependent bases in static methods or
2649
  // contexts where 'this' is available.
2650
0
  QualType ThisType = S.getCurrentThisType();
2651
0
  const CXXRecordDecl *RD = nullptr;
2652
0
  if (!ThisType.isNull())
2653
0
    RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2654
0
  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2655
0
    RD = MD->getParent();
2656
0
  if (!RD || !RD->hasAnyDependentBases())
2657
0
    return nullptr;
2658
2659
  // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2660
  // is available, suggest inserting 'this->' as a fixit.
2661
0
  SourceLocation Loc = NameInfo.getLoc();
2662
0
  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2663
0
  DB << NameInfo.getName() << RD;
2664
2665
0
  if (!ThisType.isNull()) {
2666
0
    DB << FixItHint::CreateInsertion(Loc, "this->");
2667
0
    return CXXDependentScopeMemberExpr::Create(
2668
0
        Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2669
0
        /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2670
0
        /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2671
0
  }
2672
2673
  // Synthesize a fake NNS that points to the derived class.  This will
2674
  // perform name lookup during template instantiation.
2675
0
  CXXScopeSpec SS;
2676
0
  auto *NNS =
2677
0
      NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2678
0
  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2679
0
  return DependentScopeDeclRefExpr::Create(
2680
0
      Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2681
0
      TemplateArgs);
2682
0
}
2683
2684
ExprResult
2685
Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2686
                        SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2687
                        bool HasTrailingLParen, bool IsAddressOfOperand,
2688
                        CorrectionCandidateCallback *CCC,
2689
583
                        bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2690
583
  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2691
583
         "cannot be direct & operand and have a trailing lparen");
2692
583
  if (SS.isInvalid())
2693
0
    return ExprError();
2694
2695
583
  TemplateArgumentListInfo TemplateArgsBuffer;
2696
2697
  // Decompose the UnqualifiedId into the following data.
2698
583
  DeclarationNameInfo NameInfo;
2699
583
  const TemplateArgumentListInfo *TemplateArgs;
2700
583
  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2701
2702
583
  DeclarationName Name = NameInfo.getName();
2703
583
  IdentifierInfo *II = Name.getAsIdentifierInfo();
2704
583
  SourceLocation NameLoc = NameInfo.getLoc();
2705
2706
583
  if (II && II->isEditorPlaceholder()) {
2707
    // FIXME: When typed placeholders are supported we can create a typed
2708
    // placeholder expression node.
2709
0
    return ExprError();
2710
0
  }
2711
2712
  // C++ [temp.dep.expr]p3:
2713
  //   An id-expression is type-dependent if it contains:
2714
  //     -- an identifier that was declared with a dependent type,
2715
  //        (note: handled after lookup)
2716
  //     -- a template-id that is dependent,
2717
  //        (note: handled in BuildTemplateIdExpr)
2718
  //     -- a conversion-function-id that specifies a dependent type,
2719
  //     -- a nested-name-specifier that contains a class-name that
2720
  //        names a dependent type.
2721
  // Determine whether this is a member of an unknown specialization;
2722
  // we need to handle these differently.
2723
583
  bool DependentID = false;
2724
583
  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2725
583
      Name.getCXXNameType()->isDependentType()) {
2726
0
    DependentID = true;
2727
583
  } else if (SS.isSet()) {
2728
0
    if (DeclContext *DC = computeDeclContext(SS, false)) {
2729
0
      if (RequireCompleteDeclContext(SS, DC))
2730
0
        return ExprError();
2731
0
    } else {
2732
0
      DependentID = true;
2733
0
    }
2734
0
  }
2735
2736
583
  if (DependentID)
2737
0
    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2738
0
                                      IsAddressOfOperand, TemplateArgs);
2739
2740
  // Perform the required lookup.
2741
583
  LookupResult R(*this, NameInfo,
2742
583
                 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2743
583
                     ? LookupObjCImplicitSelfParam
2744
583
                     : LookupOrdinaryName);
2745
583
  if (TemplateKWLoc.isValid() || TemplateArgs) {
2746
    // Lookup the template name again to correctly establish the context in
2747
    // which it was found. This is really unfortunate as we already did the
2748
    // lookup to determine that it was a template name in the first place. If
2749
    // this becomes a performance hit, we can work harder to preserve those
2750
    // results until we get here but it's likely not worth it.
2751
0
    bool MemberOfUnknownSpecialization;
2752
0
    AssumedTemplateKind AssumedTemplate;
2753
0
    if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2754
0
                           MemberOfUnknownSpecialization, TemplateKWLoc,
2755
0
                           &AssumedTemplate))
2756
0
      return ExprError();
2757
2758
0
    if (MemberOfUnknownSpecialization ||
2759
0
        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2760
0
      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2761
0
                                        IsAddressOfOperand, TemplateArgs);
2762
583
  } else {
2763
583
    bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2764
583
    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2765
2766
    // If the result might be in a dependent base class, this is a dependent
2767
    // id-expression.
2768
583
    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2769
0
      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2770
0
                                        IsAddressOfOperand, TemplateArgs);
2771
2772
    // If this reference is in an Objective-C method, then we need to do
2773
    // some special Objective-C lookup, too.
2774
583
    if (IvarLookupFollowUp) {
2775
0
      ExprResult E(LookupInObjCMethod(R, S, II, true));
2776
0
      if (E.isInvalid())
2777
0
        return ExprError();
2778
2779
0
      if (Expr *Ex = E.getAs<Expr>())
2780
0
        return Ex;
2781
0
    }
2782
583
  }
2783
2784
583
  if (R.isAmbiguous())
2785
0
    return ExprError();
2786
2787
  // This could be an implicitly declared function reference if the language
2788
  // mode allows it as a feature.
2789
583
  if (R.empty() && HasTrailingLParen && II &&
2790
583
      getLangOpts().implicitFunctionsAllowed()) {
2791
0
    NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2792
0
    if (D) R.addDecl(D);
2793
0
  }
2794
2795
  // Determine whether this name might be a candidate for
2796
  // argument-dependent lookup.
2797
583
  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2798
2799
583
  if (R.empty() && !ADL) {
2800
356
    if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2801
0
      if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2802
0
                                                   TemplateKWLoc, TemplateArgs))
2803
0
        return E;
2804
0
    }
2805
2806
    // Don't diagnose an empty lookup for inline assembly.
2807
356
    if (IsInlineAsmIdentifier)
2808
0
      return ExprError();
2809
2810
    // If this name wasn't predeclared and if this is not a function
2811
    // call, diagnose the problem.
2812
356
    TypoExpr *TE = nullptr;
2813
356
    DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2814
356
                                                       : nullptr);
2815
356
    DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2816
356
    assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2817
356
           "Typo correction callback misconfigured");
2818
356
    if (CCC) {
2819
      // Make sure the callback knows what the typo being diagnosed is.
2820
356
      CCC->setTypoName(II);
2821
356
      if (SS.isValid())
2822
0
        CCC->setTypoNNS(SS.getScopeRep());
2823
356
    }
2824
    // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2825
    // a template name, but we happen to have always already looked up the name
2826
    // before we get here if it must be a template name.
2827
356
    if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2828
356
                            std::nullopt, nullptr, &TE)) {
2829
356
      if (TE && KeywordReplacement) {
2830
68
        auto &State = getTypoExprState(TE);
2831
68
        auto BestTC = State.Consumer->getNextCorrection();
2832
68
        if (BestTC.isKeyword()) {
2833
0
          auto *II = BestTC.getCorrectionAsIdentifierInfo();
2834
0
          if (State.DiagHandler)
2835
0
            State.DiagHandler(BestTC);
2836
0
          KeywordReplacement->startToken();
2837
0
          KeywordReplacement->setKind(II->getTokenID());
2838
0
          KeywordReplacement->setIdentifierInfo(II);
2839
0
          KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2840
          // Clean up the state associated with the TypoExpr, since it has
2841
          // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2842
0
          clearDelayedTypo(TE);
2843
          // Signal that a correction to a keyword was performed by returning a
2844
          // valid-but-null ExprResult.
2845
0
          return (Expr*)nullptr;
2846
0
        }
2847
68
        State.Consumer->resetCorrectionStream();
2848
68
      }
2849
356
      return TE ? TE : ExprError();
2850
356
    }
2851
2852
0
    assert(!R.empty() &&
2853
0
           "DiagnoseEmptyLookup returned false but added no results");
2854
2855
    // If we found an Objective-C instance variable, let
2856
    // LookupInObjCMethod build the appropriate expression to
2857
    // reference the ivar.
2858
0
    if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2859
0
      R.clear();
2860
0
      ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2861
      // In a hopelessly buggy code, Objective-C instance variable
2862
      // lookup fails and no expression will be built to reference it.
2863
0
      if (!E.isInvalid() && !E.get())
2864
0
        return ExprError();
2865
0
      return E;
2866
0
    }
2867
0
  }
2868
2869
  // This is guaranteed from this point on.
2870
227
  assert(!R.empty() || ADL);
2871
2872
  // Check whether this might be a C++ implicit instance member access.
2873
  // C++ [class.mfct.non-static]p3:
2874
  //   When an id-expression that is not part of a class member access
2875
  //   syntax and not used to form a pointer to member is used in the
2876
  //   body of a non-static member function of class X, if name lookup
2877
  //   resolves the name in the id-expression to a non-static non-type
2878
  //   member of some class C, the id-expression is transformed into a
2879
  //   class member access expression using (*this) as the
2880
  //   postfix-expression to the left of the . operator.
2881
  //
2882
  // But we don't actually need to do this for '&' operands if R
2883
  // resolved to a function or overloaded function set, because the
2884
  // expression is ill-formed if it actually works out to be a
2885
  // non-static member function:
2886
  //
2887
  // C++ [expr.ref]p4:
2888
  //   Otherwise, if E1.E2 refers to a non-static member function. . .
2889
  //   [t]he expression can be used only as the left-hand operand of a
2890
  //   member function call.
2891
  //
2892
  // There are other safeguards against such uses, but it's important
2893
  // to get this right here so that we don't end up making a
2894
  // spuriously dependent expression if we're inside a dependent
2895
  // instance method.
2896
227
  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2897
0
    bool MightBeImplicitMember;
2898
0
    if (!IsAddressOfOperand)
2899
0
      MightBeImplicitMember = true;
2900
0
    else if (!SS.isEmpty())
2901
0
      MightBeImplicitMember = false;
2902
0
    else if (R.isOverloadedResult())
2903
0
      MightBeImplicitMember = false;
2904
0
    else if (R.isUnresolvableResult())
2905
0
      MightBeImplicitMember = true;
2906
0
    else
2907
0
      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2908
0
                              isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2909
0
                              isa<MSPropertyDecl>(R.getFoundDecl());
2910
2911
0
    if (MightBeImplicitMember)
2912
0
      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2913
0
                                             R, TemplateArgs, S);
2914
0
  }
2915
2916
227
  if (TemplateArgs || TemplateKWLoc.isValid()) {
2917
2918
    // In C++1y, if this is a variable template id, then check it
2919
    // in BuildTemplateIdExpr().
2920
    // The single lookup result must be a variable template declaration.
2921
0
    if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2922
0
        Id.TemplateId->Kind == TNK_Var_template) {
2923
0
      assert(R.getAsSingle<VarTemplateDecl>() &&
2924
0
             "There should only be one declaration found.");
2925
0
    }
2926
2927
0
    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2928
0
  }
2929
2930
227
  return BuildDeclarationNameExpr(SS, R, ADL);
2931
227
}
2932
2933
/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2934
/// declaration name, generally during template instantiation.
2935
/// There's a large number of things which don't need to be done along
2936
/// this path.
2937
ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2938
    CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2939
0
    bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2940
0
  if (NameInfo.getName().isDependentName())
2941
0
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2942
0
                                     NameInfo, /*TemplateArgs=*/nullptr);
2943
2944
0
  DeclContext *DC = computeDeclContext(SS, false);
2945
0
  if (!DC)
2946
0
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2947
0
                                     NameInfo, /*TemplateArgs=*/nullptr);
2948
2949
0
  if (RequireCompleteDeclContext(SS, DC))
2950
0
    return ExprError();
2951
2952
0
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2953
0
  LookupQualifiedName(R, DC);
2954
2955
0
  if (R.isAmbiguous())
2956
0
    return ExprError();
2957
2958
0
  if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2959
0
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2960
0
                                     NameInfo, /*TemplateArgs=*/nullptr);
2961
2962
0
  if (R.empty()) {
2963
    // Don't diagnose problems with invalid record decl, the secondary no_member
2964
    // diagnostic during template instantiation is likely bogus, e.g. if a class
2965
    // is invalid because it's derived from an invalid base class, then missing
2966
    // members were likely supposed to be inherited.
2967
0
    if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2968
0
      if (CD->isInvalidDecl())
2969
0
        return ExprError();
2970
0
    Diag(NameInfo.getLoc(), diag::err_no_member)
2971
0
      << NameInfo.getName() << DC << SS.getRange();
2972
0
    return ExprError();
2973
0
  }
2974
2975
0
  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2976
    // Diagnose a missing typename if this resolved unambiguously to a type in
2977
    // a dependent context.  If we can recover with a type, downgrade this to
2978
    // a warning in Microsoft compatibility mode.
2979
0
    unsigned DiagID = diag::err_typename_missing;
2980
0
    if (RecoveryTSI && getLangOpts().MSVCCompat)
2981
0
      DiagID = diag::ext_typename_missing;
2982
0
    SourceLocation Loc = SS.getBeginLoc();
2983
0
    auto D = Diag(Loc, DiagID);
2984
0
    D << SS.getScopeRep() << NameInfo.getName().getAsString()
2985
0
      << SourceRange(Loc, NameInfo.getEndLoc());
2986
2987
    // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2988
    // context.
2989
0
    if (!RecoveryTSI)
2990
0
      return ExprError();
2991
2992
    // Only issue the fixit if we're prepared to recover.
2993
0
    D << FixItHint::CreateInsertion(Loc, "typename ");
2994
2995
    // Recover by pretending this was an elaborated type.
2996
0
    QualType Ty = Context.getTypeDeclType(TD);
2997
0
    TypeLocBuilder TLB;
2998
0
    TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2999
3000
0
    QualType ET = getElaboratedType(ElaboratedTypeKeyword::None, SS, Ty);
3001
0
    ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
3002
0
    QTL.setElaboratedKeywordLoc(SourceLocation());
3003
0
    QTL.setQualifierLoc(SS.getWithLocInContext(Context));
3004
3005
0
    *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3006
3007
0
    return ExprEmpty();
3008
0
  }
3009
3010
  // Defend against this resolving to an implicit member access. We usually
3011
  // won't get here if this might be a legitimate a class member (we end up in
3012
  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3013
  // a pointer-to-member or in an unevaluated context in C++11.
3014
0
  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3015
0
    return BuildPossibleImplicitMemberExpr(SS,
3016
0
                                           /*TemplateKWLoc=*/SourceLocation(),
3017
0
                                           R, /*TemplateArgs=*/nullptr, S);
3018
3019
0
  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3020
0
}
3021
3022
/// The parser has read a name in, and Sema has detected that we're currently
3023
/// inside an ObjC method. Perform some additional checks and determine if we
3024
/// should form a reference to an ivar.
3025
///
3026
/// Ideally, most of this would be done by lookup, but there's
3027
/// actually quite a lot of extra work involved.
3028
DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
3029
0
                                        IdentifierInfo *II) {
3030
0
  SourceLocation Loc = Lookup.getNameLoc();
3031
0
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
3032
3033
  // Check for error condition which is already reported.
3034
0
  if (!CurMethod)
3035
0
    return DeclResult(true);
3036
3037
  // There are two cases to handle here.  1) scoped lookup could have failed,
3038
  // in which case we should look for an ivar.  2) scoped lookup could have
3039
  // found a decl, but that decl is outside the current instance method (i.e.
3040
  // a global variable).  In these two cases, we do a lookup for an ivar with
3041
  // this name, if the lookup sucedes, we replace it our current decl.
3042
3043
  // If we're in a class method, we don't normally want to look for
3044
  // ivars.  But if we don't find anything else, and there's an
3045
  // ivar, that's an error.
3046
0
  bool IsClassMethod = CurMethod->isClassMethod();
3047
3048
0
  bool LookForIvars;
3049
0
  if (Lookup.empty())
3050
0
    LookForIvars = true;
3051
0
  else if (IsClassMethod)
3052
0
    LookForIvars = false;
3053
0
  else
3054
0
    LookForIvars = (Lookup.isSingleResult() &&
3055
0
                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
3056
0
  ObjCInterfaceDecl *IFace = nullptr;
3057
0
  if (LookForIvars) {
3058
0
    IFace = CurMethod->getClassInterface();
3059
0
    ObjCInterfaceDecl *ClassDeclared;
3060
0
    ObjCIvarDecl *IV = nullptr;
3061
0
    if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3062
      // Diagnose using an ivar in a class method.
3063
0
      if (IsClassMethod) {
3064
0
        Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3065
0
        return DeclResult(true);
3066
0
      }
3067
3068
      // Diagnose the use of an ivar outside of the declaring class.
3069
0
      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
3070
0
          !declaresSameEntity(ClassDeclared, IFace) &&
3071
0
          !getLangOpts().DebuggerSupport)
3072
0
        Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3073
3074
      // Success.
3075
0
      return IV;
3076
0
    }
3077
0
  } else if (CurMethod->isInstanceMethod()) {
3078
    // We should warn if a local variable hides an ivar.
3079
0
    if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3080
0
      ObjCInterfaceDecl *ClassDeclared;
3081
0
      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3082
0
        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3083
0
            declaresSameEntity(IFace, ClassDeclared))
3084
0
          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3085
0
      }
3086
0
    }
3087
0
  } else if (Lookup.isSingleResult() &&
3088
0
             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
3089
    // If accessing a stand-alone ivar in a class method, this is an error.
3090
0
    if (const ObjCIvarDecl *IV =
3091
0
            dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3092
0
      Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3093
0
      return DeclResult(true);
3094
0
    }
3095
0
  }
3096
3097
  // Didn't encounter an error, didn't find an ivar.
3098
0
  return DeclResult(false);
3099
0
}
3100
3101
ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
3102
0
                                  ObjCIvarDecl *IV) {
3103
0
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
3104
0
  assert(CurMethod && CurMethod->isInstanceMethod() &&
3105
0
         "should not reference ivar from this context");
3106
3107
0
  ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3108
0
  assert(IFace && "should not reference ivar from this context");
3109
3110
  // If we're referencing an invalid decl, just return this as a silent
3111
  // error node.  The error diagnostic was already emitted on the decl.
3112
0
  if (IV->isInvalidDecl())
3113
0
    return ExprError();
3114
3115
  // Check if referencing a field with __attribute__((deprecated)).
3116
0
  if (DiagnoseUseOfDecl(IV, Loc))
3117
0
    return ExprError();
3118
3119
  // FIXME: This should use a new expr for a direct reference, don't
3120
  // turn this into Self->ivar, just return a BareIVarExpr or something.
3121
0
  IdentifierInfo &II = Context.Idents.get("self");
3122
0
  UnqualifiedId SelfName;
3123
0
  SelfName.setImplicitSelfParam(&II);
3124
0
  CXXScopeSpec SelfScopeSpec;
3125
0
  SourceLocation TemplateKWLoc;
3126
0
  ExprResult SelfExpr =
3127
0
      ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3128
0
                        /*HasTrailingLParen=*/false,
3129
0
                        /*IsAddressOfOperand=*/false);
3130
0
  if (SelfExpr.isInvalid())
3131
0
    return ExprError();
3132
3133
0
  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3134
0
  if (SelfExpr.isInvalid())
3135
0
    return ExprError();
3136
3137
0
  MarkAnyDeclReferenced(Loc, IV, true);
3138
3139
0
  ObjCMethodFamily MF = CurMethod->getMethodFamily();
3140
0
  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3141
0
      !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3142
0
    Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3143
3144
0
  ObjCIvarRefExpr *Result = new (Context)
3145
0
      ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3146
0
                      IV->getLocation(), SelfExpr.get(), true, true);
3147
3148
0
  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3149
0
    if (!isUnevaluatedContext() &&
3150
0
        !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3151
0
      getCurFunction()->recordUseOfWeak(Result);
3152
0
  }
3153
0
  if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3154
0
    if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3155
0
      ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3156
3157
0
  return Result;
3158
0
}
3159
3160
/// The parser has read a name in, and Sema has detected that we're currently
3161
/// inside an ObjC method. Perform some additional checks and determine if we
3162
/// should form a reference to an ivar. If so, build an expression referencing
3163
/// that ivar.
3164
ExprResult
3165
Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
3166
0
                         IdentifierInfo *II, bool AllowBuiltinCreation) {
3167
  // FIXME: Integrate this lookup step into LookupParsedName.
3168
0
  DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3169
0
  if (Ivar.isInvalid())
3170
0
    return ExprError();
3171
0
  if (Ivar.isUsable())
3172
0
    return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3173
0
                            cast<ObjCIvarDecl>(Ivar.get()));
3174
3175
0
  if (Lookup.empty() && II && AllowBuiltinCreation)
3176
0
    LookupBuiltin(Lookup);
3177
3178
  // Sentinel value saying that we didn't do anything special.
3179
0
  return ExprResult(false);
3180
0
}
3181
3182
/// Cast a base object to a member's actual type.
3183
///
3184
/// There are two relevant checks:
3185
///
3186
/// C++ [class.access.base]p7:
3187
///
3188
///   If a class member access operator [...] is used to access a non-static
3189
///   data member or non-static member function, the reference is ill-formed if
3190
///   the left operand [...] cannot be implicitly converted to a pointer to the
3191
///   naming class of the right operand.
3192
///
3193
/// C++ [expr.ref]p7:
3194
///
3195
///   If E2 is a non-static data member or a non-static member function, the
3196
///   program is ill-formed if the class of which E2 is directly a member is an
3197
///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
3198
///
3199
/// Note that the latter check does not consider access; the access of the
3200
/// "real" base class is checked as appropriate when checking the access of the
3201
/// member name.
3202
ExprResult
3203
Sema::PerformObjectMemberConversion(Expr *From,
3204
                                    NestedNameSpecifier *Qualifier,
3205
                                    NamedDecl *FoundDecl,
3206
0
                                    NamedDecl *Member) {
3207
0
  const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3208
0
  if (!RD)
3209
0
    return From;
3210
3211
0
  QualType DestRecordType;
3212
0
  QualType DestType;
3213
0
  QualType FromRecordType;
3214
0
  QualType FromType = From->getType();
3215
0
  bool PointerConversions = false;
3216
0
  if (isa<FieldDecl>(Member)) {
3217
0
    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3218
0
    auto FromPtrType = FromType->getAs<PointerType>();
3219
0
    DestRecordType = Context.getAddrSpaceQualType(
3220
0
        DestRecordType, FromPtrType
3221
0
                            ? FromType->getPointeeType().getAddressSpace()
3222
0
                            : FromType.getAddressSpace());
3223
3224
0
    if (FromPtrType) {
3225
0
      DestType = Context.getPointerType(DestRecordType);
3226
0
      FromRecordType = FromPtrType->getPointeeType();
3227
0
      PointerConversions = true;
3228
0
    } else {
3229
0
      DestType = DestRecordType;
3230
0
      FromRecordType = FromType;
3231
0
    }
3232
0
  } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3233
0
    if (!Method->isImplicitObjectMemberFunction())
3234
0
      return From;
3235
3236
0
    DestType = Method->getThisType().getNonReferenceType();
3237
0
    DestRecordType = Method->getFunctionObjectParameterType();
3238
3239
0
    if (FromType->getAs<PointerType>()) {
3240
0
      FromRecordType = FromType->getPointeeType();
3241
0
      PointerConversions = true;
3242
0
    } else {
3243
0
      FromRecordType = FromType;
3244
0
      DestType = DestRecordType;
3245
0
    }
3246
3247
0
    LangAS FromAS = FromRecordType.getAddressSpace();
3248
0
    LangAS DestAS = DestRecordType.getAddressSpace();
3249
0
    if (FromAS != DestAS) {
3250
0
      QualType FromRecordTypeWithoutAS =
3251
0
          Context.removeAddrSpaceQualType(FromRecordType);
3252
0
      QualType FromTypeWithDestAS =
3253
0
          Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3254
0
      if (PointerConversions)
3255
0
        FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3256
0
      From = ImpCastExprToType(From, FromTypeWithDestAS,
3257
0
                               CK_AddressSpaceConversion, From->getValueKind())
3258
0
                 .get();
3259
0
    }
3260
0
  } else {
3261
    // No conversion necessary.
3262
0
    return From;
3263
0
  }
3264
3265
0
  if (DestType->isDependentType() || FromType->isDependentType())
3266
0
    return From;
3267
3268
  // If the unqualified types are the same, no conversion is necessary.
3269
0
  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3270
0
    return From;
3271
3272
0
  SourceRange FromRange = From->getSourceRange();
3273
0
  SourceLocation FromLoc = FromRange.getBegin();
3274
3275
0
  ExprValueKind VK = From->getValueKind();
3276
3277
  // C++ [class.member.lookup]p8:
3278
  //   [...] Ambiguities can often be resolved by qualifying a name with its
3279
  //   class name.
3280
  //
3281
  // If the member was a qualified name and the qualified referred to a
3282
  // specific base subobject type, we'll cast to that intermediate type
3283
  // first and then to the object in which the member is declared. That allows
3284
  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3285
  //
3286
  //   class Base { public: int x; };
3287
  //   class Derived1 : public Base { };
3288
  //   class Derived2 : public Base { };
3289
  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3290
  //
3291
  //   void VeryDerived::f() {
3292
  //     x = 17; // error: ambiguous base subobjects
3293
  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3294
  //   }
3295
0
  if (Qualifier && Qualifier->getAsType()) {
3296
0
    QualType QType = QualType(Qualifier->getAsType(), 0);
3297
0
    assert(QType->isRecordType() && "lookup done with non-record type");
3298
3299
0
    QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3300
3301
    // In C++98, the qualifier type doesn't actually have to be a base
3302
    // type of the object type, in which case we just ignore it.
3303
    // Otherwise build the appropriate casts.
3304
0
    if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3305
0
      CXXCastPath BasePath;
3306
0
      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3307
0
                                       FromLoc, FromRange, &BasePath))
3308
0
        return ExprError();
3309
3310
0
      if (PointerConversions)
3311
0
        QType = Context.getPointerType(QType);
3312
0
      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3313
0
                               VK, &BasePath).get();
3314
3315
0
      FromType = QType;
3316
0
      FromRecordType = QRecordType;
3317
3318
      // If the qualifier type was the same as the destination type,
3319
      // we're done.
3320
0
      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3321
0
        return From;
3322
0
    }
3323
0
  }
3324
3325
0
  CXXCastPath BasePath;
3326
0
  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3327
0
                                   FromLoc, FromRange, &BasePath,
3328
0
                                   /*IgnoreAccess=*/true))
3329
0
    return ExprError();
3330
3331
0
  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3332
0
                           VK, &BasePath);
3333
0
}
3334
3335
bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3336
                                      const LookupResult &R,
3337
668
                                      bool HasTrailingLParen) {
3338
  // Only when used directly as the postfix-expression of a call.
3339
668
  if (!HasTrailingLParen)
3340
665
    return false;
3341
3342
  // Never if a scope specifier was provided.
3343
3
  if (SS.isSet())
3344
0
    return false;
3345
3346
  // Only in C++ or ObjC++.
3347
3
  if (!getLangOpts().CPlusPlus)
3348
0
    return false;
3349
3350
  // Turn off ADL when we find certain kinds of declarations during
3351
  // normal lookup:
3352
3
  for (const NamedDecl *D : R) {
3353
    // C++0x [basic.lookup.argdep]p3:
3354
    //     -- a declaration of a class member
3355
    // Since using decls preserve this property, we check this on the
3356
    // original decl.
3357
2
    if (D->isCXXClassMember())
3358
0
      return false;
3359
3360
    // C++0x [basic.lookup.argdep]p3:
3361
    //     -- a block-scope function declaration that is not a
3362
    //        using-declaration
3363
    // NOTE: we also trigger this for function templates (in fact, we
3364
    // don't check the decl type at all, since all other decl types
3365
    // turn off ADL anyway).
3366
2
    if (isa<UsingShadowDecl>(D))
3367
0
      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3368
2
    else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3369
0
      return false;
3370
3371
    // C++0x [basic.lookup.argdep]p3:
3372
    //     -- a declaration that is neither a function or a function
3373
    //        template
3374
    // And also for builtin functions.
3375
2
    if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3376
      // But also builtin functions.
3377
0
      if (FDecl->getBuiltinID() && FDecl->isImplicit())
3378
0
        return false;
3379
2
    } else if (!isa<FunctionTemplateDecl>(D))
3380
2
      return false;
3381
2
  }
3382
3383
1
  return true;
3384
3
}
3385
3386
3387
/// Diagnoses obvious problems with the use of the given declaration
3388
/// as an expression.  This is only actually called for lookups that
3389
/// were not overloaded, and it doesn't promise that the declaration
3390
/// will in fact be used.
3391
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3392
268
                            bool AcceptInvalid) {
3393
268
  if (D->isInvalidDecl() && !AcceptInvalid)
3394
209
    return true;
3395
3396
59
  if (isa<TypedefNameDecl>(D)) {
3397
0
    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3398
0
    return true;
3399
0
  }
3400
3401
59
  if (isa<ObjCInterfaceDecl>(D)) {
3402
0
    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3403
0
    return true;
3404
0
  }
3405
3406
59
  if (isa<NamespaceDecl>(D)) {
3407
0
    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3408
0
    return true;
3409
0
  }
3410
3411
59
  return false;
3412
59
}
3413
3414
// Certain multiversion types should be treated as overloaded even when there is
3415
// only one result.
3416
268
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3417
268
  assert(R.isSingleResult() && "Expected only a single result");
3418
0
  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3419
268
  return FD &&
3420
268
         (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3421
268
}
3422
3423
ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3424
                                          LookupResult &R, bool NeedsADL,
3425
269
                                          bool AcceptInvalidDecl) {
3426
  // If this is a single, fully-resolved result and we don't need ADL,
3427
  // just build an ordinary singleton decl ref.
3428
269
  if (!NeedsADL && R.isSingleResult() &&
3429
269
      !R.getAsSingle<FunctionTemplateDecl>() &&
3430
269
      !ShouldLookupResultBeMultiVersionOverload(R))
3431
268
    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3432
268
                                    R.getRepresentativeDecl(), nullptr,
3433
268
                                    AcceptInvalidDecl);
3434
3435
  // We only need to check the declaration if there's exactly one
3436
  // result, because in the overloaded case the results can only be
3437
  // functions and function templates.
3438
1
  if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3439
1
      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3440
0
                      AcceptInvalidDecl))
3441
0
    return ExprError();
3442
3443
  // Otherwise, just build an unresolved lookup expression.  Suppress
3444
  // any lookup-related diagnostics; we'll hash these out later, when
3445
  // we've picked a target.
3446
1
  R.suppressDiagnostics();
3447
3448
1
  UnresolvedLookupExpr *ULE
3449
1
    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3450
1
                                   SS.getWithLocInContext(Context),
3451
1
                                   R.getLookupNameInfo(),
3452
1
                                   NeedsADL, R.isOverloadedResult(),
3453
1
                                   R.begin(), R.end());
3454
3455
1
  return ULE;
3456
1
}
3457
3458
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3459
                                                        SourceLocation loc,
3460
                                                        ValueDecl *var);
3461
3462
/// Complete semantic analysis for a reference to the given declaration.
3463
ExprResult Sema::BuildDeclarationNameExpr(
3464
    const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3465
    NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3466
268
    bool AcceptInvalidDecl) {
3467
268
  assert(D && "Cannot refer to a NULL declaration");
3468
0
  assert(!isa<FunctionTemplateDecl>(D) &&
3469
268
         "Cannot refer unambiguously to a function template");
3470
3471
0
  SourceLocation Loc = NameInfo.getLoc();
3472
268
  if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3473
    // Recovery from invalid cases (e.g. D is an invalid Decl).
3474
    // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3475
    // diagnostics, as invalid decls use int as a fallback type.
3476
209
    return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3477
209
  }
3478
3479
59
  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3480
    // Specifically diagnose references to class templates that are missing
3481
    // a template argument list.
3482
0
    diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3483
0
    return ExprError();
3484
0
  }
3485
3486
  // Make sure that we're referring to a value.
3487
59
  if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3488
0
    Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3489
0
    Diag(D->getLocation(), diag::note_declared_at);
3490
0
    return ExprError();
3491
0
  }
3492
3493
  // Check whether this declaration can be used. Note that we suppress
3494
  // this check when we're going to perform argument-dependent lookup
3495
  // on this function name, because this might not be the function
3496
  // that overload resolution actually selects.
3497
59
  if (DiagnoseUseOfDecl(D, Loc))
3498
0
    return ExprError();
3499
3500
59
  auto *VD = cast<ValueDecl>(D);
3501
3502
  // Only create DeclRefExpr's for valid Decl's.
3503
59
  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3504
0
    return ExprError();
3505
3506
  // Handle members of anonymous structs and unions.  If we got here,
3507
  // and the reference is to a class member indirect field, then this
3508
  // must be the subject of a pointer-to-member expression.
3509
59
  if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3510
59
      IndirectField && !IndirectField->isCXXClassMember())
3511
0
    return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3512
0
                                                    IndirectField);
3513
3514
59
  QualType type = VD->getType();
3515
59
  if (type.isNull())
3516
0
    return ExprError();
3517
59
  ExprValueKind valueKind = VK_PRValue;
3518
3519
  // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3520
  // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3521
  // is expanded by some outer '...' in the context of the use.
3522
59
  type = type.getNonPackExpansionType();
3523
3524
59
  switch (D->getKind()) {
3525
    // Ignore all the non-ValueDecl kinds.
3526
0
#define ABSTRACT_DECL(kind)
3527
0
#define VALUE(type, base)
3528
0
#define DECL(type, base) case Decl::type:
3529
0
#include "clang/AST/DeclNodes.inc"
3530
0
    llvm_unreachable("invalid value decl kind");
3531
3532
  // These shouldn't make it here.
3533
0
  case Decl::ObjCAtDefsField:
3534
0
    llvm_unreachable("forming non-member reference to ivar?");
3535
3536
  // Enum constants are always r-values and never references.
3537
  // Unresolved using declarations are dependent.
3538
0
  case Decl::EnumConstant:
3539
0
  case Decl::UnresolvedUsingValue:
3540
0
  case Decl::OMPDeclareReduction:
3541
0
  case Decl::OMPDeclareMapper:
3542
0
    valueKind = VK_PRValue;
3543
0
    break;
3544
3545
  // Fields and indirect fields that got here must be for
3546
  // pointer-to-member expressions; we just call them l-values for
3547
  // internal consistency, because this subexpression doesn't really
3548
  // exist in the high-level semantics.
3549
0
  case Decl::Field:
3550
0
  case Decl::IndirectField:
3551
0
  case Decl::ObjCIvar:
3552
0
    assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3553
3554
    // These can't have reference type in well-formed programs, but
3555
    // for internal consistency we do this anyway.
3556
0
    type = type.getNonReferenceType();
3557
0
    valueKind = VK_LValue;
3558
0
    break;
3559
3560
  // Non-type template parameters are either l-values or r-values
3561
  // depending on the type.
3562
0
  case Decl::NonTypeTemplateParm: {
3563
0
    if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3564
0
      type = reftype->getPointeeType();
3565
0
      valueKind = VK_LValue; // even if the parameter is an r-value reference
3566
0
      break;
3567
0
    }
3568
3569
    // [expr.prim.id.unqual]p2:
3570
    //   If the entity is a template parameter object for a template
3571
    //   parameter of type T, the type of the expression is const T.
3572
    //   [...] The expression is an lvalue if the entity is a [...] template
3573
    //   parameter object.
3574
0
    if (type->isRecordType()) {
3575
0
      type = type.getUnqualifiedType().withConst();
3576
0
      valueKind = VK_LValue;
3577
0
      break;
3578
0
    }
3579
3580
    // For non-references, we need to strip qualifiers just in case
3581
    // the template parameter was declared as 'const int' or whatever.
3582
0
    valueKind = VK_PRValue;
3583
0
    type = type.getUnqualifiedType();
3584
0
    break;
3585
0
  }
3586
3587
59
  case Decl::Var:
3588
59
  case Decl::VarTemplateSpecialization:
3589
59
  case Decl::VarTemplatePartialSpecialization:
3590
59
  case Decl::Decomposition:
3591
59
  case Decl::OMPCapturedExpr:
3592
    // In C, "extern void blah;" is valid and is an r-value.
3593
59
    if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3594
59
        type->isVoidType()) {
3595
0
      valueKind = VK_PRValue;
3596
0
      break;
3597
0
    }
3598
59
    [[fallthrough]];
3599
3600
59
  case Decl::ImplicitParam:
3601
59
  case Decl::ParmVar: {
3602
    // These are always l-values.
3603
59
    valueKind = VK_LValue;
3604
59
    type = type.getNonReferenceType();
3605
3606
    // FIXME: Does the addition of const really only apply in
3607
    // potentially-evaluated contexts? Since the variable isn't actually
3608
    // captured in an unevaluated context, it seems that the answer is no.
3609
59
    if (!isUnevaluatedContext()) {
3610
59
      QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3611
59
      if (!CapturedType.isNull())
3612
0
        type = CapturedType;
3613
59
    }
3614
3615
59
    break;
3616
59
  }
3617
3618
0
  case Decl::Binding:
3619
    // These are always lvalues.
3620
0
    valueKind = VK_LValue;
3621
0
    type = type.getNonReferenceType();
3622
0
    break;
3623
3624
0
  case Decl::Function: {
3625
0
    if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3626
0
      if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3627
0
        type = Context.BuiltinFnTy;
3628
0
        valueKind = VK_PRValue;
3629
0
        break;
3630
0
      }
3631
0
    }
3632
3633
0
    const FunctionType *fty = type->castAs<FunctionType>();
3634
3635
    // If we're referring to a function with an __unknown_anytype
3636
    // result type, make the entire expression __unknown_anytype.
3637
0
    if (fty->getReturnType() == Context.UnknownAnyTy) {
3638
0
      type = Context.UnknownAnyTy;
3639
0
      valueKind = VK_PRValue;
3640
0
      break;
3641
0
    }
3642
3643
    // Functions are l-values in C++.
3644
0
    if (getLangOpts().CPlusPlus) {
3645
0
      valueKind = VK_LValue;
3646
0
      break;
3647
0
    }
3648
3649
    // C99 DR 316 says that, if a function type comes from a
3650
    // function definition (without a prototype), that type is only
3651
    // used for checking compatibility. Therefore, when referencing
3652
    // the function, we pretend that we don't have the full function
3653
    // type.
3654
0
    if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3655
0
      type = Context.getFunctionNoProtoType(fty->getReturnType(),
3656
0
                                            fty->getExtInfo());
3657
3658
    // Functions are r-values in C.
3659
0
    valueKind = VK_PRValue;
3660
0
    break;
3661
0
  }
3662
3663
0
  case Decl::CXXDeductionGuide:
3664
0
    llvm_unreachable("building reference to deduction guide");
3665
3666
0
  case Decl::MSProperty:
3667
0
  case Decl::MSGuid:
3668
0
  case Decl::TemplateParamObject:
3669
    // FIXME: Should MSGuidDecl and template parameter objects be subject to
3670
    // capture in OpenMP, or duplicated between host and device?
3671
0
    valueKind = VK_LValue;
3672
0
    break;
3673
3674
0
  case Decl::UnnamedGlobalConstant:
3675
0
    valueKind = VK_LValue;
3676
0
    break;
3677
3678
0
  case Decl::CXXMethod:
3679
    // If we're referring to a method with an __unknown_anytype
3680
    // result type, make the entire expression __unknown_anytype.
3681
    // This should only be possible with a type written directly.
3682
0
    if (const FunctionProtoType *proto =
3683
0
            dyn_cast<FunctionProtoType>(VD->getType()))
3684
0
      if (proto->getReturnType() == Context.UnknownAnyTy) {
3685
0
        type = Context.UnknownAnyTy;
3686
0
        valueKind = VK_PRValue;
3687
0
        break;
3688
0
      }
3689
3690
    // C++ methods are l-values if static, r-values if non-static.
3691
0
    if (cast<CXXMethodDecl>(VD)->isStatic()) {
3692
0
      valueKind = VK_LValue;
3693
0
      break;
3694
0
    }
3695
0
    [[fallthrough]];
3696
3697
0
  case Decl::CXXConversion:
3698
0
  case Decl::CXXDestructor:
3699
0
  case Decl::CXXConstructor:
3700
0
    valueKind = VK_PRValue;
3701
0
    break;
3702
59
  }
3703
3704
59
  auto *E =
3705
59
      BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3706
59
                       /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3707
  // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3708
  // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3709
  // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3710
  // diagnostics).
3711
59
  if (VD->isInvalidDecl() && E)
3712
42
    return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3713
17
  return E;
3714
59
}
3715
3716
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3717
0
                                    SmallString<32> &Target) {
3718
0
  Target.resize(CharByteWidth * (Source.size() + 1));
3719
0
  char *ResultPtr = &Target[0];
3720
0
  const llvm::UTF8 *ErrorPtr;
3721
0
  bool success =
3722
0
      llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3723
0
  (void)success;
3724
0
  assert(success);
3725
0
  Target.resize(ResultPtr - &Target[0]);
3726
0
}
3727
3728
ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3729
0
                                     PredefinedIdentKind IK) {
3730
0
  Decl *currentDecl = getPredefinedExprDecl(CurContext);
3731
0
  if (!currentDecl) {
3732
0
    Diag(Loc, diag::ext_predef_outside_function);
3733
0
    currentDecl = Context.getTranslationUnitDecl();
3734
0
  }
3735
3736
0
  QualType ResTy;
3737
0
  StringLiteral *SL = nullptr;
3738
0
  if (cast<DeclContext>(currentDecl)->isDependentContext())
3739
0
    ResTy = Context.DependentTy;
3740
0
  else {
3741
    // Pre-defined identifiers are of type char[x], where x is the length of
3742
    // the string.
3743
0
    auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3744
0
    unsigned Length = Str.length();
3745
3746
0
    llvm::APInt LengthI(32, Length + 1);
3747
0
    if (IK == PredefinedIdentKind::LFunction ||
3748
0
        IK == PredefinedIdentKind::LFuncSig) {
3749
0
      ResTy =
3750
0
          Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3751
0
      SmallString<32> RawChars;
3752
0
      ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3753
0
                              Str, RawChars);
3754
0
      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3755
0
                                           ArraySizeModifier::Normal,
3756
0
                                           /*IndexTypeQuals*/ 0);
3757
0
      SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,
3758
0
                                 /*Pascal*/ false, ResTy, Loc);
3759
0
    } else {
3760
0
      ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3761
0
      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3762
0
                                           ArraySizeModifier::Normal,
3763
0
                                           /*IndexTypeQuals*/ 0);
3764
0
      SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary,
3765
0
                                 /*Pascal*/ false, ResTy, Loc);
3766
0
    }
3767
0
  }
3768
3769
0
  return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3770
0
                                SL);
3771
0
}
3772
3773
ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3774
                                               SourceLocation LParen,
3775
                                               SourceLocation RParen,
3776
0
                                               TypeSourceInfo *TSI) {
3777
0
  return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3778
0
}
3779
3780
ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3781
                                               SourceLocation LParen,
3782
                                               SourceLocation RParen,
3783
0
                                               ParsedType ParsedTy) {
3784
0
  TypeSourceInfo *TSI = nullptr;
3785
0
  QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3786
3787
0
  if (Ty.isNull())
3788
0
    return ExprError();
3789
0
  if (!TSI)
3790
0
    TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3791
3792
0
  return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3793
0
}
3794
3795
0
ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3796
0
  return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3797
0
}
3798
3799
3
ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3800
3
  SmallString<16> CharBuffer;
3801
3
  bool Invalid = false;
3802
3
  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3803
3
  if (Invalid)
3804
0
    return ExprError();
3805
3806
3
  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3807
3
                            PP, Tok.getKind());
3808
3
  if (Literal.hadError())
3809
0
    return ExprError();
3810
3811
3
  QualType Ty;
3812
3
  if (Literal.isWide())
3813
0
    Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3814
3
  else if (Literal.isUTF8() && getLangOpts().C23)
3815
0
    Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3816
3
  else if (Literal.isUTF8() && getLangOpts().Char8)
3817
0
    Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3818
3
  else if (Literal.isUTF16())
3819
0
    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3820
3
  else if (Literal.isUTF32())
3821
0
    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3822
3
  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3823
3
    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3824
0
  else
3825
0
    Ty = Context.CharTy; // 'x' -> char in C++;
3826
                         // u8'x' -> char in C11-C17 and in C++ without char8_t.
3827
3828
3
  CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3829
3
  if (Literal.isWide())
3830
0
    Kind = CharacterLiteralKind::Wide;
3831
3
  else if (Literal.isUTF16())
3832
0
    Kind = CharacterLiteralKind::UTF16;
3833
3
  else if (Literal.isUTF32())
3834
0
    Kind = CharacterLiteralKind::UTF32;
3835
3
  else if (Literal.isUTF8())
3836
0
    Kind = CharacterLiteralKind::UTF8;
3837
3838
3
  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3839
3
                                             Tok.getLocation());
3840
3841
3
  if (Literal.getUDSuffix().empty())
3842
2
    return Lit;
3843
3844
  // We're building a user-defined literal.
3845
1
  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3846
1
  SourceLocation UDSuffixLoc =
3847
1
    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3848
3849
  // Make sure we're allowed user-defined literals here.
3850
1
  if (!UDLScope)
3851
0
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3852
3853
  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3854
  //   operator "" X (ch)
3855
1
  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3856
1
                                        Lit, Tok.getLocation());
3857
1
}
3858
3859
42
ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3860
42
  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3861
42
  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3862
42
                                Context.IntTy, Loc);
3863
42
}
3864
3865
static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3866
1
                                  QualType Ty, SourceLocation Loc) {
3867
1
  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3868
3869
1
  using llvm::APFloat;
3870
1
  APFloat Val(Format);
3871
3872
1
  APFloat::opStatus result = Literal.GetFloatValue(Val);
3873
3874
  // Overflow is always an error, but underflow is only an error if
3875
  // we underflowed to zero (APFloat reports denormals as underflow).
3876
1
  if ((result & APFloat::opOverflow) ||
3877
1
      ((result & APFloat::opUnderflow) && Val.isZero())) {
3878
0
    unsigned diagnostic;
3879
0
    SmallString<20> buffer;
3880
0
    if (result & APFloat::opOverflow) {
3881
0
      diagnostic = diag::warn_float_overflow;
3882
0
      APFloat::getLargest(Format).toString(buffer);
3883
0
    } else {
3884
0
      diagnostic = diag::warn_float_underflow;
3885
0
      APFloat::getSmallest(Format).toString(buffer);
3886
0
    }
3887
3888
0
    S.Diag(Loc, diagnostic)
3889
0
      << Ty
3890
0
      << StringRef(buffer.data(), buffer.size());
3891
0
  }
3892
3893
1
  bool isExact = (result == APFloat::opOK);
3894
1
  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3895
1
}
3896
3897
0
bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3898
0
  assert(E && "Invalid expression");
3899
3900
0
  if (E->isValueDependent())
3901
0
    return false;
3902
3903
0
  QualType QT = E->getType();
3904
0
  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3905
0
    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3906
0
    return true;
3907
0
  }
3908
3909
0
  llvm::APSInt ValueAPS;
3910
0
  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3911
3912
0
  if (R.isInvalid())
3913
0
    return true;
3914
3915
0
  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3916
0
  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3917
0
    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3918
0
        << toString(ValueAPS, 10) << ValueIsPositive;
3919
0
    return true;
3920
0
  }
3921
3922
0
  return false;
3923
0
}
3924
3925
75
ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3926
  // Fast path for a single digit (which is quite common).  A single digit
3927
  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3928
75
  if (Tok.getLength() == 1) {
3929
42
    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3930
42
    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3931
42
  }
3932
3933
33
  SmallString<128> SpellingBuffer;
3934
  // NumericLiteralParser wants to overread by one character.  Add padding to
3935
  // the buffer in case the token is copied to the buffer.  If getSpelling()
3936
  // returns a StringRef to the memory buffer, it should have a null char at
3937
  // the EOF, so it is also safe.
3938
33
  SpellingBuffer.resize(Tok.getLength() + 1);
3939
3940
  // Get the spelling of the token, which eliminates trigraphs, etc.
3941
33
  bool Invalid = false;
3942
33
  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3943
33
  if (Invalid)
3944
0
    return ExprError();
3945
3946
33
  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3947
33
                               PP.getSourceManager(), PP.getLangOpts(),
3948
33
                               PP.getTargetInfo(), PP.getDiagnostics());
3949
33
  if (Literal.hadError)
3950
26
    return ExprError();
3951
3952
7
  if (Literal.hasUDSuffix()) {
3953
    // We're building a user-defined literal.
3954
1
    const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3955
1
    SourceLocation UDSuffixLoc =
3956
1
      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3957
3958
    // Make sure we're allowed user-defined literals here.
3959
1
    if (!UDLScope)
3960
0
      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3961
3962
1
    QualType CookedTy;
3963
1
    if (Literal.isFloatingLiteral()) {
3964
      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3965
      // long double, the literal is treated as a call of the form
3966
      //   operator "" X (f L)
3967
0
      CookedTy = Context.LongDoubleTy;
3968
1
    } else {
3969
      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3970
      // unsigned long long, the literal is treated as a call of the form
3971
      //   operator "" X (n ULL)
3972
1
      CookedTy = Context.UnsignedLongLongTy;
3973
1
    }
3974
3975
1
    DeclarationName OpName =
3976
1
      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3977
1
    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3978
1
    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3979
3980
1
    SourceLocation TokLoc = Tok.getLocation();
3981
3982
    // Perform literal operator lookup to determine if we're building a raw
3983
    // literal or a cooked one.
3984
1
    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3985
1
    switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3986
1
                                  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3987
1
                                  /*AllowStringTemplatePack*/ false,
3988
1
                                  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3989
0
    case LOLR_ErrorNoDiagnostic:
3990
      // Lookup failure for imaginary constants isn't fatal, there's still the
3991
      // GNU extension producing _Complex types.
3992
0
      break;
3993
1
    case LOLR_Error:
3994
1
      return ExprError();
3995
0
    case LOLR_Cooked: {
3996
0
      Expr *Lit;
3997
0
      if (Literal.isFloatingLiteral()) {
3998
0
        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3999
0
      } else {
4000
0
        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
4001
0
        if (Literal.GetIntegerValue(ResultVal))
4002
0
          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4003
0
              << /* Unsigned */ 1;
4004
0
        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
4005
0
                                     Tok.getLocation());
4006
0
      }
4007
0
      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4008
0
    }
4009
4010
0
    case LOLR_Raw: {
4011
      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4012
      // literal is treated as a call of the form
4013
      //   operator "" X ("n")
4014
0
      unsigned Length = Literal.getUDSuffixOffset();
4015
0
      QualType StrTy = Context.getConstantArrayType(
4016
0
          Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
4017
0
          llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
4018
0
      Expr *Lit =
4019
0
          StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4020
0
                                StringLiteralKind::Ordinary,
4021
0
                                /*Pascal*/ false, StrTy, &TokLoc, 1);
4022
0
      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4023
0
    }
4024
4025
0
    case LOLR_Template: {
4026
      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4027
      // template), L is treated as a call fo the form
4028
      //   operator "" X <'c1', 'c2', ... 'ck'>()
4029
      // where n is the source character sequence c1 c2 ... ck.
4030
0
      TemplateArgumentListInfo ExplicitArgs;
4031
0
      unsigned CharBits = Context.getIntWidth(Context.CharTy);
4032
0
      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4033
0
      llvm::APSInt Value(CharBits, CharIsUnsigned);
4034
0
      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4035
0
        Value = TokSpelling[I];
4036
0
        TemplateArgument Arg(Context, Value, Context.CharTy);
4037
0
        TemplateArgumentLocInfo ArgInfo;
4038
0
        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4039
0
      }
4040
0
      return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4041
0
                                      &ExplicitArgs);
4042
0
    }
4043
0
    case LOLR_StringTemplatePack:
4044
0
      llvm_unreachable("unexpected literal operator lookup result");
4045
1
    }
4046
1
  }
4047
4048
6
  Expr *Res;
4049
4050
6
  if (Literal.isFixedPointLiteral()) {
4051
0
    QualType Ty;
4052
4053
0
    if (Literal.isAccum) {
4054
0
      if (Literal.isHalf) {
4055
0
        Ty = Context.ShortAccumTy;
4056
0
      } else if (Literal.isLong) {
4057
0
        Ty = Context.LongAccumTy;
4058
0
      } else {
4059
0
        Ty = Context.AccumTy;
4060
0
      }
4061
0
    } else if (Literal.isFract) {
4062
0
      if (Literal.isHalf) {
4063
0
        Ty = Context.ShortFractTy;
4064
0
      } else if (Literal.isLong) {
4065
0
        Ty = Context.LongFractTy;
4066
0
      } else {
4067
0
        Ty = Context.FractTy;
4068
0
      }
4069
0
    }
4070
4071
0
    if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4072
4073
0
    bool isSigned = !Literal.isUnsigned;
4074
0
    unsigned scale = Context.getFixedPointScale(Ty);
4075
0
    unsigned bit_width = Context.getTypeInfo(Ty).Width;
4076
4077
0
    llvm::APInt Val(bit_width, 0, isSigned);
4078
0
    bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4079
0
    bool ValIsZero = Val.isZero() && !Overflowed;
4080
4081
0
    auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4082
0
    if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4083
      // Clause 6.4.4 - The value of a constant shall be in the range of
4084
      // representable values for its type, with exception for constants of a
4085
      // fract type with a value of exactly 1; such a constant shall denote
4086
      // the maximal value for the type.
4087
0
      --Val;
4088
0
    else if (Val.ugt(MaxVal) || Overflowed)
4089
0
      Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4090
4091
0
    Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
4092
0
                                              Tok.getLocation(), scale);
4093
6
  } else if (Literal.isFloatingLiteral()) {
4094
1
    QualType Ty;
4095
1
    if (Literal.isHalf){
4096
0
      if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4097
0
        Ty = Context.HalfTy;
4098
0
      else {
4099
0
        Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4100
0
        return ExprError();
4101
0
      }
4102
1
    } else if (Literal.isFloat)
4103
0
      Ty = Context.FloatTy;
4104
1
    else if (Literal.isLong)
4105
0
      Ty = Context.LongDoubleTy;
4106
1
    else if (Literal.isFloat16)
4107
0
      Ty = Context.Float16Ty;
4108
1
    else if (Literal.isFloat128)
4109
0
      Ty = Context.Float128Ty;
4110
1
    else
4111
1
      Ty = Context.DoubleTy;
4112
4113
1
    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4114
4115
1
    if (Ty == Context.DoubleTy) {
4116
1
      if (getLangOpts().SinglePrecisionConstants) {
4117
0
        if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4118
0
          Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4119
0
        }
4120
1
      } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4121
0
                                             "cl_khr_fp64", getLangOpts())) {
4122
        // Impose single-precision float type when cl_khr_fp64 is not enabled.
4123
0
        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4124
0
            << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4125
0
        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4126
0
      }
4127
1
    }
4128
5
  } else if (!Literal.isIntegerLiteral()) {
4129
0
    return ExprError();
4130
5
  } else {
4131
5
    QualType Ty;
4132
4133
    // 'z/uz' literals are a C++23 feature.
4134
5
    if (Literal.isSizeT)
4135
2
      Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4136
2
                                  ? getLangOpts().CPlusPlus23
4137
1
                                        ? diag::warn_cxx20_compat_size_t_suffix
4138
1
                                        : diag::ext_cxx23_size_t_suffix
4139
2
                                  : diag::err_cxx23_size_t_suffix);
4140
4141
    // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4142
    // but we do not currently support the suffix in C++ mode because it's not
4143
    // entirely clear whether WG21 will prefer this suffix to return a library
4144
    // type such as std::bit_int instead of returning a _BitInt.
4145
5
    if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4146
0
      PP.Diag(Tok.getLocation(), getLangOpts().C23
4147
0
                                     ? diag::warn_c23_compat_bitint_suffix
4148
0
                                     : diag::ext_c23_bitint_suffix);
4149
4150
    // Get the value in the widest-possible width. What is "widest" depends on
4151
    // whether the literal is a bit-precise integer or not. For a bit-precise
4152
    // integer type, try to scan the source to determine how many bits are
4153
    // needed to represent the value. This may seem a bit expensive, but trying
4154
    // to get the integer value from an overly-wide APInt is *extremely*
4155
    // expensive, so the naive approach of assuming
4156
    // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4157
5
    unsigned BitsNeeded =
4158
5
        Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4159
0
                               Literal.getLiteralDigits(), Literal.getRadix())
4160
5
                         : Context.getTargetInfo().getIntMaxTWidth();
4161
5
    llvm::APInt ResultVal(BitsNeeded, 0);
4162
4163
5
    if (Literal.GetIntegerValue(ResultVal)) {
4164
      // If this value didn't fit into uintmax_t, error and force to ull.
4165
0
      Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4166
0
          << /* Unsigned */ 1;
4167
0
      Ty = Context.UnsignedLongLongTy;
4168
0
      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4169
0
             "long long is not intmax_t?");
4170
5
    } else {
4171
      // If this value fits into a ULL, try to figure out what else it fits into
4172
      // according to the rules of C99 6.4.4.1p5.
4173
4174
      // Octal, Hexadecimal, and integers with a U suffix are allowed to
4175
      // be an unsigned int.
4176
5
      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4177
4178
      // Check from smallest to largest, picking the smallest type we can.
4179
5
      unsigned Width = 0;
4180
4181
      // Microsoft specific integer suffixes are explicitly sized.
4182
5
      if (Literal.MicrosoftInteger) {
4183
0
        if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4184
0
          Width = 8;
4185
0
          Ty = Context.CharTy;
4186
0
        } else {
4187
0
          Width = Literal.MicrosoftInteger;
4188
0
          Ty = Context.getIntTypeForBitwidth(Width,
4189
0
                                             /*Signed=*/!Literal.isUnsigned);
4190
0
        }
4191
0
      }
4192
4193
      // Bit-precise integer literals are automagically-sized based on the
4194
      // width required by the literal.
4195
5
      if (Literal.isBitInt) {
4196
        // The signed version has one more bit for the sign value. There are no
4197
        // zero-width bit-precise integers, even if the literal value is 0.
4198
0
        Width = std::max(ResultVal.getActiveBits(), 1u) +
4199
0
                (Literal.isUnsigned ? 0u : 1u);
4200
4201
        // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4202
        // and reset the type to the largest supported width.
4203
0
        unsigned int MaxBitIntWidth =
4204
0
            Context.getTargetInfo().getMaxBitIntWidth();
4205
0
        if (Width > MaxBitIntWidth) {
4206
0
          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4207
0
              << Literal.isUnsigned;
4208
0
          Width = MaxBitIntWidth;
4209
0
        }
4210
4211
        // Reset the result value to the smaller APInt and select the correct
4212
        // type to be used. Note, we zext even for signed values because the
4213
        // literal itself is always an unsigned value (a preceeding - is a
4214
        // unary operator, not part of the literal).
4215
0
        ResultVal = ResultVal.zextOrTrunc(Width);
4216
0
        Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4217
0
      }
4218
4219
      // Check C++23 size_t literals.
4220
5
      if (Literal.isSizeT) {
4221
2
        assert(!Literal.MicrosoftInteger &&
4222
2
               "size_t literals can't be Microsoft literals");
4223
0
        unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4224
2
            Context.getTargetInfo().getSizeType());
4225
4226
        // Does it fit in size_t?
4227
2
        if (ResultVal.isIntN(SizeTSize)) {
4228
          // Does it fit in ssize_t?
4229
2
          if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4230
2
            Ty = Context.getSignedSizeType();
4231
0
          else if (AllowUnsigned)
4232
0
            Ty = Context.getSizeType();
4233
2
          Width = SizeTSize;
4234
2
        }
4235
2
      }
4236
4237
5
      if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4238
5
          !Literal.isSizeT) {
4239
        // Are int/unsigned possibilities?
4240
2
        unsigned IntSize = Context.getTargetInfo().getIntWidth();
4241
4242
        // Does it fit in a unsigned int?
4243
2
        if (ResultVal.isIntN(IntSize)) {
4244
          // Does it fit in a signed int?
4245
2
          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4246
2
            Ty = Context.IntTy;
4247
0
          else if (AllowUnsigned)
4248
0
            Ty = Context.UnsignedIntTy;
4249
2
          Width = IntSize;
4250
2
        }
4251
2
      }
4252
4253
      // Are long/unsigned long possibilities?
4254
5
      if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4255
1
        unsigned LongSize = Context.getTargetInfo().getLongWidth();
4256
4257
        // Does it fit in a unsigned long?
4258
1
        if (ResultVal.isIntN(LongSize)) {
4259
          // Does it fit in a signed long?
4260
1
          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4261
1
            Ty = Context.LongTy;
4262
0
          else if (AllowUnsigned)
4263
0
            Ty = Context.UnsignedLongTy;
4264
          // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4265
          // is compatible.
4266
0
          else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4267
0
            const unsigned LongLongSize =
4268
0
                Context.getTargetInfo().getLongLongWidth();
4269
0
            Diag(Tok.getLocation(),
4270
0
                 getLangOpts().CPlusPlus
4271
0
                     ? Literal.isLong
4272
0
                           ? diag::warn_old_implicitly_unsigned_long_cxx
4273
0
                           : /*C++98 UB*/ diag::
4274
0
                                 ext_old_implicitly_unsigned_long_cxx
4275
0
                     : diag::warn_old_implicitly_unsigned_long)
4276
0
                << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4277
0
                                            : /*will be ill-formed*/ 1);
4278
0
            Ty = Context.UnsignedLongTy;
4279
0
          }
4280
1
          Width = LongSize;
4281
1
        }
4282
1
      }
4283
4284
      // Check long long if needed.
4285
5
      if (Ty.isNull() && !Literal.isSizeT) {
4286
0
        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4287
4288
        // Does it fit in a unsigned long long?
4289
0
        if (ResultVal.isIntN(LongLongSize)) {
4290
          // Does it fit in a signed long long?
4291
          // To be compatible with MSVC, hex integer literals ending with the
4292
          // LL or i64 suffix are always signed in Microsoft mode.
4293
0
          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4294
0
              (getLangOpts().MSVCCompat && Literal.isLongLong)))
4295
0
            Ty = Context.LongLongTy;
4296
0
          else if (AllowUnsigned)
4297
0
            Ty = Context.UnsignedLongLongTy;
4298
0
          Width = LongLongSize;
4299
4300
          // 'long long' is a C99 or C++11 feature, whether the literal
4301
          // explicitly specified 'long long' or we needed the extra width.
4302
0
          if (getLangOpts().CPlusPlus)
4303
0
            Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4304
0
                                        ? diag::warn_cxx98_compat_longlong
4305
0
                                        : diag::ext_cxx11_longlong);
4306
0
          else if (!getLangOpts().C99)
4307
0
            Diag(Tok.getLocation(), diag::ext_c99_longlong);
4308
0
        }
4309
0
      }
4310
4311
      // If we still couldn't decide a type, we either have 'size_t' literal
4312
      // that is out of range, or a decimal literal that does not fit in a
4313
      // signed long long and has no U suffix.
4314
5
      if (Ty.isNull()) {
4315
0
        if (Literal.isSizeT)
4316
0
          Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4317
0
              << Literal.isUnsigned;
4318
0
        else
4319
0
          Diag(Tok.getLocation(),
4320
0
               diag::ext_integer_literal_too_large_for_signed);
4321
0
        Ty = Context.UnsignedLongLongTy;
4322
0
        Width = Context.getTargetInfo().getLongLongWidth();
4323
0
      }
4324
4325
5
      if (ResultVal.getBitWidth() != Width)
4326
2
        ResultVal = ResultVal.trunc(Width);
4327
5
    }
4328
0
    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4329
5
  }
4330
4331
  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4332
6
  if (Literal.isImaginary) {
4333
0
    Res = new (Context) ImaginaryLiteral(Res,
4334
0
                                        Context.getComplexType(Res->getType()));
4335
4336
0
    Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4337
0
  }
4338
6
  return Res;
4339
6
}
4340
4341
0
ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4342
0
  assert(E && "ActOnParenExpr() missing expr");
4343
0
  QualType ExprTy = E->getType();
4344
0
  if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4345
0
      !E->isLValue() && ExprTy->hasFloatingRepresentation())
4346
0
    return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4347
0
  return new (Context) ParenExpr(L, R, E);
4348
0
}
4349
4350
static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4351
                                         SourceLocation Loc,
4352
0
                                         SourceRange ArgRange) {
4353
  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4354
  // scalar or vector data type argument..."
4355
  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4356
  // type (C99 6.2.5p18) or void.
4357
0
  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4358
0
    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4359
0
      << T << ArgRange;
4360
0
    return true;
4361
0
  }
4362
4363
0
  assert((T->isVoidType() || !T->isIncompleteType()) &&
4364
0
         "Scalar types should always be complete");
4365
0
  return false;
4366
0
}
4367
4368
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4369
                                                SourceLocation Loc,
4370
0
                                                SourceRange ArgRange) {
4371
  // builtin_vectorelements supports both fixed-sized and scalable vectors.
4372
0
  if (!T->isVectorType() && !T->isSizelessVectorType())
4373
0
    return S.Diag(Loc, diag::err_builtin_non_vector_type)
4374
0
           << ""
4375
0
           << "__builtin_vectorelements" << T << ArgRange;
4376
4377
0
  return false;
4378
0
}
4379
4380
static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4381
                                           SourceLocation Loc,
4382
                                           SourceRange ArgRange,
4383
0
                                           UnaryExprOrTypeTrait TraitKind) {
4384
  // Invalid types must be hard errors for SFINAE in C++.
4385
0
  if (S.LangOpts.CPlusPlus)
4386
0
    return true;
4387
4388
  // C99 6.5.3.4p1:
4389
0
  if (T->isFunctionType() &&
4390
0
      (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4391
0
       TraitKind == UETT_PreferredAlignOf)) {
4392
    // sizeof(function)/alignof(function) is allowed as an extension.
4393
0
    S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4394
0
        << getTraitSpelling(TraitKind) << ArgRange;
4395
0
    return false;
4396
0
  }
4397
4398
  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4399
  // this is an error (OpenCL v1.1 s6.3.k)
4400
0
  if (T->isVoidType()) {
4401
0
    unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4402
0
                                        : diag::ext_sizeof_alignof_void_type;
4403
0
    S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4404
0
    return false;
4405
0
  }
4406
4407
0
  return true;
4408
0
}
4409
4410
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4411
                                             SourceLocation Loc,
4412
                                             SourceRange ArgRange,
4413
0
                                             UnaryExprOrTypeTrait TraitKind) {
4414
  // Reject sizeof(interface) and sizeof(interface<proto>) if the
4415
  // runtime doesn't allow it.
4416
0
  if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4417
0
    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4418
0
      << T << (TraitKind == UETT_SizeOf)
4419
0
      << ArgRange;
4420
0
    return true;
4421
0
  }
4422
4423
0
  return false;
4424
0
}
4425
4426
/// Check whether E is a pointer from a decayed array type (the decayed
4427
/// pointer type is equal to T) and emit a warning if it is.
4428
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4429
0
                                     const Expr *E) {
4430
  // Don't warn if the operation changed the type.
4431
0
  if (T != E->getType())
4432
0
    return;
4433
4434
  // Now look for array decays.
4435
0
  const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4436
0
  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4437
0
    return;
4438
4439
0
  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4440
0
                                             << ICE->getType()
4441
0
                                             << ICE->getSubExpr()->getType();
4442
0
}
4443
4444
/// Check the constraints on expression operands to unary type expression
4445
/// and type traits.
4446
///
4447
/// Completes any types necessary and validates the constraints on the operand
4448
/// expression. The logic mostly mirrors the type-based overload, but may modify
4449
/// the expression as it completes the type for that expression through template
4450
/// instantiation, etc.
4451
bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4452
0
                                            UnaryExprOrTypeTrait ExprKind) {
4453
0
  QualType ExprTy = E->getType();
4454
0
  assert(!ExprTy->isReferenceType());
4455
4456
0
  bool IsUnevaluatedOperand =
4457
0
      (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4458
0
       ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4459
0
       ExprKind == UETT_VecStep);
4460
0
  if (IsUnevaluatedOperand) {
4461
0
    ExprResult Result = CheckUnevaluatedOperand(E);
4462
0
    if (Result.isInvalid())
4463
0
      return true;
4464
0
    E = Result.get();
4465
0
  }
4466
4467
  // The operand for sizeof and alignof is in an unevaluated expression context,
4468
  // so side effects could result in unintended consequences.
4469
  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4470
  // used to build SFINAE gadgets.
4471
  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4472
0
  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4473
0
      !E->isInstantiationDependent() &&
4474
0
      !E->getType()->isVariableArrayType() &&
4475
0
      E->HasSideEffects(Context, false))
4476
0
    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4477
4478
0
  if (ExprKind == UETT_VecStep)
4479
0
    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4480
0
                                        E->getSourceRange());
4481
4482
0
  if (ExprKind == UETT_VectorElements)
4483
0
    return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4484
0
                                               E->getSourceRange());
4485
4486
  // Explicitly list some types as extensions.
4487
0
  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4488
0
                                      E->getSourceRange(), ExprKind))
4489
0
    return false;
4490
4491
  // WebAssembly tables are always illegal operands to unary expressions and
4492
  // type traits.
4493
0
  if (Context.getTargetInfo().getTriple().isWasm() &&
4494
0
      E->getType()->isWebAssemblyTableType()) {
4495
0
    Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4496
0
        << getTraitSpelling(ExprKind);
4497
0
    return true;
4498
0
  }
4499
4500
  // 'alignof' applied to an expression only requires the base element type of
4501
  // the expression to be complete. 'sizeof' requires the expression's type to
4502
  // be complete (and will attempt to complete it if it's an array of unknown
4503
  // bound).
4504
0
  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4505
0
    if (RequireCompleteSizedType(
4506
0
            E->getExprLoc(), Context.getBaseElementType(E->getType()),
4507
0
            diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4508
0
            getTraitSpelling(ExprKind), E->getSourceRange()))
4509
0
      return true;
4510
0
  } else {
4511
0
    if (RequireCompleteSizedExprType(
4512
0
            E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4513
0
            getTraitSpelling(ExprKind), E->getSourceRange()))
4514
0
      return true;
4515
0
  }
4516
4517
  // Completing the expression's type may have changed it.
4518
0
  ExprTy = E->getType();
4519
0
  assert(!ExprTy->isReferenceType());
4520
4521
0
  if (ExprTy->isFunctionType()) {
4522
0
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4523
0
        << getTraitSpelling(ExprKind) << E->getSourceRange();
4524
0
    return true;
4525
0
  }
4526
4527
0
  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4528
0
                                       E->getSourceRange(), ExprKind))
4529
0
    return true;
4530
4531
0
  if (ExprKind == UETT_SizeOf) {
4532
0
    if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4533
0
      if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4534
0
        QualType OType = PVD->getOriginalType();
4535
0
        QualType Type = PVD->getType();
4536
0
        if (Type->isPointerType() && OType->isArrayType()) {
4537
0
          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4538
0
            << Type << OType;
4539
0
          Diag(PVD->getLocation(), diag::note_declared_at);
4540
0
        }
4541
0
      }
4542
0
    }
4543
4544
    // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4545
    // decays into a pointer and returns an unintended result. This is most
4546
    // likely a typo for "sizeof(array) op x".
4547
0
    if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4548
0
      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4549
0
                               BO->getLHS());
4550
0
      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4551
0
                               BO->getRHS());
4552
0
    }
4553
0
  }
4554
4555
0
  return false;
4556
0
}
4557
4558
0
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4559
  // Cannot know anything else if the expression is dependent.
4560
0
  if (E->isTypeDependent())
4561
0
    return false;
4562
4563
0
  if (E->getObjectKind() == OK_BitField) {
4564
0
    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4565
0
       << 1 << E->getSourceRange();
4566
0
    return true;
4567
0
  }
4568
4569
0
  ValueDecl *D = nullptr;
4570
0
  Expr *Inner = E->IgnoreParens();
4571
0
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4572
0
    D = DRE->getDecl();
4573
0
  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4574
0
    D = ME->getMemberDecl();
4575
0
  }
4576
4577
  // If it's a field, require the containing struct to have a
4578
  // complete definition so that we can compute the layout.
4579
  //
4580
  // This can happen in C++11 onwards, either by naming the member
4581
  // in a way that is not transformed into a member access expression
4582
  // (in an unevaluated operand, for instance), or by naming the member
4583
  // in a trailing-return-type.
4584
  //
4585
  // For the record, since __alignof__ on expressions is a GCC
4586
  // extension, GCC seems to permit this but always gives the
4587
  // nonsensical answer 0.
4588
  //
4589
  // We don't really need the layout here --- we could instead just
4590
  // directly check for all the appropriate alignment-lowing
4591
  // attributes --- but that would require duplicating a lot of
4592
  // logic that just isn't worth duplicating for such a marginal
4593
  // use-case.
4594
0
  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4595
    // Fast path this check, since we at least know the record has a
4596
    // definition if we can find a member of it.
4597
0
    if (!FD->getParent()->isCompleteDefinition()) {
4598
0
      S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4599
0
        << E->getSourceRange();
4600
0
      return true;
4601
0
    }
4602
4603
    // Otherwise, if it's a field, and the field doesn't have
4604
    // reference type, then it must have a complete type (or be a
4605
    // flexible array member, which we explicitly want to
4606
    // white-list anyway), which makes the following checks trivial.
4607
0
    if (!FD->getType()->isReferenceType())
4608
0
      return false;
4609
0
  }
4610
4611
0
  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4612
0
}
4613
4614
0
bool Sema::CheckVecStepExpr(Expr *E) {
4615
0
  E = E->IgnoreParens();
4616
4617
  // Cannot know anything else if the expression is dependent.
4618
0
  if (E->isTypeDependent())
4619
0
    return false;
4620
4621
0
  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4622
0
}
4623
4624
static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4625
0
                                        CapturingScopeInfo *CSI) {
4626
0
  assert(T->isVariablyModifiedType());
4627
0
  assert(CSI != nullptr);
4628
4629
  // We're going to walk down into the type and look for VLA expressions.
4630
0
  do {
4631
0
    const Type *Ty = T.getTypePtr();
4632
0
    switch (Ty->getTypeClass()) {
4633
0
#define TYPE(Class, Base)
4634
0
#define ABSTRACT_TYPE(Class, Base)
4635
0
#define NON_CANONICAL_TYPE(Class, Base)
4636
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4637
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4638
0
#include "clang/AST/TypeNodes.inc"
4639
0
      T = QualType();
4640
0
      break;
4641
    // These types are never variably-modified.
4642
0
    case Type::Builtin:
4643
0
    case Type::Complex:
4644
0
    case Type::Vector:
4645
0
    case Type::ExtVector:
4646
0
    case Type::ConstantMatrix:
4647
0
    case Type::Record:
4648
0
    case Type::Enum:
4649
0
    case Type::TemplateSpecialization:
4650
0
    case Type::ObjCObject:
4651
0
    case Type::ObjCInterface:
4652
0
    case Type::ObjCObjectPointer:
4653
0
    case Type::ObjCTypeParam:
4654
0
    case Type::Pipe:
4655
0
    case Type::BitInt:
4656
0
      llvm_unreachable("type class is never variably-modified!");
4657
0
    case Type::Elaborated:
4658
0
      T = cast<ElaboratedType>(Ty)->getNamedType();
4659
0
      break;
4660
0
    case Type::Adjusted:
4661
0
      T = cast<AdjustedType>(Ty)->getOriginalType();
4662
0
      break;
4663
0
    case Type::Decayed:
4664
0
      T = cast<DecayedType>(Ty)->getPointeeType();
4665
0
      break;
4666
0
    case Type::Pointer:
4667
0
      T = cast<PointerType>(Ty)->getPointeeType();
4668
0
      break;
4669
0
    case Type::BlockPointer:
4670
0
      T = cast<BlockPointerType>(Ty)->getPointeeType();
4671
0
      break;
4672
0
    case Type::LValueReference:
4673
0
    case Type::RValueReference:
4674
0
      T = cast<ReferenceType>(Ty)->getPointeeType();
4675
0
      break;
4676
0
    case Type::MemberPointer:
4677
0
      T = cast<MemberPointerType>(Ty)->getPointeeType();
4678
0
      break;
4679
0
    case Type::ConstantArray:
4680
0
    case Type::IncompleteArray:
4681
      // Losing element qualification here is fine.
4682
0
      T = cast<ArrayType>(Ty)->getElementType();
4683
0
      break;
4684
0
    case Type::VariableArray: {
4685
      // Losing element qualification here is fine.
4686
0
      const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4687
4688
      // Unknown size indication requires no size computation.
4689
      // Otherwise, evaluate and record it.
4690
0
      auto Size = VAT->getSizeExpr();
4691
0
      if (Size && !CSI->isVLATypeCaptured(VAT) &&
4692
0
          (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4693
0
        CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4694
4695
0
      T = VAT->getElementType();
4696
0
      break;
4697
0
    }
4698
0
    case Type::FunctionProto:
4699
0
    case Type::FunctionNoProto:
4700
0
      T = cast<FunctionType>(Ty)->getReturnType();
4701
0
      break;
4702
0
    case Type::Paren:
4703
0
    case Type::TypeOf:
4704
0
    case Type::UnaryTransform:
4705
0
    case Type::Attributed:
4706
0
    case Type::BTFTagAttributed:
4707
0
    case Type::SubstTemplateTypeParm:
4708
0
    case Type::MacroQualified:
4709
      // Keep walking after single level desugaring.
4710
0
      T = T.getSingleStepDesugaredType(Context);
4711
0
      break;
4712
0
    case Type::Typedef:
4713
0
      T = cast<TypedefType>(Ty)->desugar();
4714
0
      break;
4715
0
    case Type::Decltype:
4716
0
      T = cast<DecltypeType>(Ty)->desugar();
4717
0
      break;
4718
0
    case Type::Using:
4719
0
      T = cast<UsingType>(Ty)->desugar();
4720
0
      break;
4721
0
    case Type::Auto:
4722
0
    case Type::DeducedTemplateSpecialization:
4723
0
      T = cast<DeducedType>(Ty)->getDeducedType();
4724
0
      break;
4725
0
    case Type::TypeOfExpr:
4726
0
      T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4727
0
      break;
4728
0
    case Type::Atomic:
4729
0
      T = cast<AtomicType>(Ty)->getValueType();
4730
0
      break;
4731
0
    }
4732
0
  } while (!T.isNull() && T->isVariablyModifiedType());
4733
0
}
4734
4735
/// Check the constraints on operands to unary expression and type
4736
/// traits.
4737
///
4738
/// This will complete any types necessary, and validate the various constraints
4739
/// on those operands.
4740
///
4741
/// The UsualUnaryConversions() function is *not* called by this routine.
4742
/// C99 6.3.2.1p[2-4] all state:
4743
///   Except when it is the operand of the sizeof operator ...
4744
///
4745
/// C++ [expr.sizeof]p4
4746
///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4747
///   standard conversions are not applied to the operand of sizeof.
4748
///
4749
/// This policy is followed for all of the unary trait expressions.
4750
bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4751
                                            SourceLocation OpLoc,
4752
                                            SourceRange ExprRange,
4753
                                            UnaryExprOrTypeTrait ExprKind,
4754
0
                                            StringRef KWName) {
4755
0
  if (ExprType->isDependentType())
4756
0
    return false;
4757
4758
  // C++ [expr.sizeof]p2:
4759
  //     When applied to a reference or a reference type, the result
4760
  //     is the size of the referenced type.
4761
  // C++11 [expr.alignof]p3:
4762
  //     When alignof is applied to a reference type, the result
4763
  //     shall be the alignment of the referenced type.
4764
0
  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4765
0
    ExprType = Ref->getPointeeType();
4766
4767
  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4768
  //   When alignof or _Alignof is applied to an array type, the result
4769
  //   is the alignment of the element type.
4770
0
  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4771
0
      ExprKind == UETT_OpenMPRequiredSimdAlign)
4772
0
    ExprType = Context.getBaseElementType(ExprType);
4773
4774
0
  if (ExprKind == UETT_VecStep)
4775
0
    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4776
4777
0
  if (ExprKind == UETT_VectorElements)
4778
0
    return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4779
0
                                               ExprRange);
4780
4781
  // Explicitly list some types as extensions.
4782
0
  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4783
0
                                      ExprKind))
4784
0
    return false;
4785
4786
0
  if (RequireCompleteSizedType(
4787
0
          OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4788
0
          KWName, ExprRange))
4789
0
    return true;
4790
4791
0
  if (ExprType->isFunctionType()) {
4792
0
    Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4793
0
    return true;
4794
0
  }
4795
4796
  // WebAssembly tables are always illegal operands to unary expressions and
4797
  // type traits.
4798
0
  if (Context.getTargetInfo().getTriple().isWasm() &&
4799
0
      ExprType->isWebAssemblyTableType()) {
4800
0
    Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4801
0
        << getTraitSpelling(ExprKind);
4802
0
    return true;
4803
0
  }
4804
4805
0
  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4806
0
                                       ExprKind))
4807
0
    return true;
4808
4809
0
  if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4810
0
    if (auto *TT = ExprType->getAs<TypedefType>()) {
4811
0
      for (auto I = FunctionScopes.rbegin(),
4812
0
                E = std::prev(FunctionScopes.rend());
4813
0
           I != E; ++I) {
4814
0
        auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4815
0
        if (CSI == nullptr)
4816
0
          break;
4817
0
        DeclContext *DC = nullptr;
4818
0
        if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4819
0
          DC = LSI->CallOperator;
4820
0
        else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4821
0
          DC = CRSI->TheCapturedDecl;
4822
0
        else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4823
0
          DC = BSI->TheDecl;
4824
0
        if (DC) {
4825
0
          if (DC->containsDecl(TT->getDecl()))
4826
0
            break;
4827
0
          captureVariablyModifiedType(Context, ExprType, CSI);
4828
0
        }
4829
0
      }
4830
0
    }
4831
0
  }
4832
4833
0
  return false;
4834
0
}
4835
4836
/// Build a sizeof or alignof expression given a type operand.
4837
ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4838
                                                SourceLocation OpLoc,
4839
                                                UnaryExprOrTypeTrait ExprKind,
4840
0
                                                SourceRange R) {
4841
0
  if (!TInfo)
4842
0
    return ExprError();
4843
4844
0
  QualType T = TInfo->getType();
4845
4846
0
  if (!T->isDependentType() &&
4847
0
      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4848
0
                                       getTraitSpelling(ExprKind)))
4849
0
    return ExprError();
4850
4851
  // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4852
  // properly deal with VLAs in nested calls of sizeof and typeof.
4853
0
  if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4854
0
      TInfo->getType()->isVariablyModifiedType())
4855
0
    TInfo = TransformToPotentiallyEvaluated(TInfo);
4856
4857
  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4858
0
  return new (Context) UnaryExprOrTypeTraitExpr(
4859
0
      ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4860
0
}
4861
4862
/// Build a sizeof or alignof expression given an expression
4863
/// operand.
4864
ExprResult
4865
Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4866
0
                                     UnaryExprOrTypeTrait ExprKind) {
4867
0
  ExprResult PE = CheckPlaceholderExpr(E);
4868
0
  if (PE.isInvalid())
4869
0
    return ExprError();
4870
4871
0
  E = PE.get();
4872
4873
  // Verify that the operand is valid.
4874
0
  bool isInvalid = false;
4875
0
  if (E->isTypeDependent()) {
4876
    // Delay type-checking for type-dependent expressions.
4877
0
  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4878
0
    isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4879
0
  } else if (ExprKind == UETT_VecStep) {
4880
0
    isInvalid = CheckVecStepExpr(E);
4881
0
  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4882
0
      Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4883
0
      isInvalid = true;
4884
0
  } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4885
0
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4886
0
    isInvalid = true;
4887
0
  } else if (ExprKind == UETT_VectorElements) {
4888
0
    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4889
0
  } else {
4890
0
    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4891
0
  }
4892
4893
0
  if (isInvalid)
4894
0
    return ExprError();
4895
4896
0
  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4897
0
    PE = TransformToPotentiallyEvaluated(E);
4898
0
    if (PE.isInvalid()) return ExprError();
4899
0
    E = PE.get();
4900
0
  }
4901
4902
  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4903
0
  return new (Context) UnaryExprOrTypeTraitExpr(
4904
0
      ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4905
0
}
4906
4907
/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4908
/// expr and the same for @c alignof and @c __alignof
4909
/// Note that the ArgRange is invalid if isType is false.
4910
ExprResult
4911
Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4912
                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
4913
0
                                    void *TyOrEx, SourceRange ArgRange) {
4914
  // If error parsing type, ignore.
4915
0
  if (!TyOrEx) return ExprError();
4916
4917
0
  if (IsType) {
4918
0
    TypeSourceInfo *TInfo;
4919
0
    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4920
0
    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4921
0
  }
4922
4923
0
  Expr *ArgEx = (Expr *)TyOrEx;
4924
0
  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4925
0
  return Result;
4926
0
}
4927
4928
bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4929
0
                                    SourceLocation OpLoc, SourceRange R) {
4930
0
  if (!TInfo)
4931
0
    return true;
4932
0
  return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4933
0
                                          UETT_AlignOf, KWName);
4934
0
}
4935
4936
/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4937
/// _Alignas(type-name) .
4938
/// [dcl.align] An alignment-specifier of the form
4939
/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4940
///
4941
/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4942
/// _Alignas(_Alignof(type-name)).
4943
bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4944
0
                                    SourceLocation OpLoc, SourceRange R) {
4945
0
  TypeSourceInfo *TInfo;
4946
0
  (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4947
0
                          &TInfo);
4948
0
  return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4949
0
}
4950
4951
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4952
0
                                     bool IsReal) {
4953
0
  if (V.get()->isTypeDependent())
4954
0
    return S.Context.DependentTy;
4955
4956
  // _Real and _Imag are only l-values for normal l-values.
4957
0
  if (V.get()->getObjectKind() != OK_Ordinary) {
4958
0
    V = S.DefaultLvalueConversion(V.get());
4959
0
    if (V.isInvalid())
4960
0
      return QualType();
4961
0
  }
4962
4963
  // These operators return the element type of a complex type.
4964
0
  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4965
0
    return CT->getElementType();
4966
4967
  // Otherwise they pass through real integer and floating point types here.
4968
0
  if (V.get()->getType()->isArithmeticType())
4969
0
    return V.get()->getType();
4970
4971
  // Test for placeholders.
4972
0
  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4973
0
  if (PR.isInvalid()) return QualType();
4974
0
  if (PR.get() != V.get()) {
4975
0
    V = PR;
4976
0
    return CheckRealImagOperand(S, V, Loc, IsReal);
4977
0
  }
4978
4979
  // Reject anything else.
4980
0
  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4981
0
    << (IsReal ? "__real" : "__imag");
4982
0
  return QualType();
4983
0
}
4984
4985
4986
4987
ExprResult
4988
Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4989
0
                          tok::TokenKind Kind, Expr *Input) {
4990
0
  UnaryOperatorKind Opc;
4991
0
  switch (Kind) {
4992
0
  default: llvm_unreachable("Unknown unary op!");
4993
0
  case tok::plusplus:   Opc = UO_PostInc; break;
4994
0
  case tok::minusminus: Opc = UO_PostDec; break;
4995
0
  }
4996
4997
  // Since this might is a postfix expression, get rid of ParenListExprs.
4998
0
  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4999
0
  if (Result.isInvalid()) return ExprError();
5000
0
  Input = Result.get();
5001
5002
0
  return BuildUnaryOp(S, OpLoc, Opc, Input);
5003
0
}
5004
5005
/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5006
///
5007
/// \return true on error
5008
static bool checkArithmeticOnObjCPointer(Sema &S,
5009
                                         SourceLocation opLoc,
5010
0
                                         Expr *op) {
5011
0
  assert(op->getType()->isObjCObjectPointerType());
5012
0
  if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5013
0
      !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5014
0
    return false;
5015
5016
0
  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5017
0
    << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5018
0
    << op->getSourceRange();
5019
0
  return true;
5020
0
}
5021
5022
0
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5023
0
  auto *BaseNoParens = Base->IgnoreParens();
5024
0
  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5025
0
    return MSProp->getPropertyDecl()->getType()->isArrayType();
5026
0
  return isa<MSPropertySubscriptExpr>(BaseNoParens);
5027
0
}
5028
5029
// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5030
// Typically this is DependentTy, but can sometimes be more precise.
5031
//
5032
// There are cases when we could determine a non-dependent type:
5033
//  - LHS and RHS may have non-dependent types despite being type-dependent
5034
//    (e.g. unbounded array static members of the current instantiation)
5035
//  - one may be a dependent-sized array with known element type
5036
//  - one may be a dependent-typed valid index (enum in current instantiation)
5037
//
5038
// We *always* return a dependent type, in such cases it is DependentTy.
5039
// This avoids creating type-dependent expressions with non-dependent types.
5040
// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5041
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5042
0
                                               const ASTContext &Ctx) {
5043
0
  assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5044
0
  QualType LTy = LHS->getType(), RTy = RHS->getType();
5045
0
  QualType Result = Ctx.DependentTy;
5046
0
  if (RTy->isIntegralOrUnscopedEnumerationType()) {
5047
0
    if (const PointerType *PT = LTy->getAs<PointerType>())
5048
0
      Result = PT->getPointeeType();
5049
0
    else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5050
0
      Result = AT->getElementType();
5051
0
  } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5052
0
    if (const PointerType *PT = RTy->getAs<PointerType>())
5053
0
      Result = PT->getPointeeType();
5054
0
    else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5055
0
      Result = AT->getElementType();
5056
0
  }
5057
  // Ensure we return a dependent type.
5058
0
  return Result->isDependentType() ? Result : Ctx.DependentTy;
5059
0
}
5060
5061
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
5062
5063
ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5064
                                         SourceLocation lbLoc,
5065
                                         MultiExprArg ArgExprs,
5066
0
                                         SourceLocation rbLoc) {
5067
5068
0
  if (base && !base->getType().isNull() &&
5069
0
      base->hasPlaceholderType(BuiltinType::OMPArraySection))
5070
0
    return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
5071
0
                                    SourceLocation(), /*Length*/ nullptr,
5072
0
                                    /*Stride=*/nullptr, rbLoc);
5073
5074
  // Since this might be a postfix expression, get rid of ParenListExprs.
5075
0
  if (isa<ParenListExpr>(base)) {
5076
0
    ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
5077
0
    if (result.isInvalid())
5078
0
      return ExprError();
5079
0
    base = result.get();
5080
0
  }
5081
5082
  // Check if base and idx form a MatrixSubscriptExpr.
5083
  //
5084
  // Helper to check for comma expressions, which are not allowed as indices for
5085
  // matrix subscript expressions.
5086
0
  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5087
0
    if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
5088
0
      Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5089
0
          << SourceRange(base->getBeginLoc(), rbLoc);
5090
0
      return true;
5091
0
    }
5092
0
    return false;
5093
0
  };
5094
  // The matrix subscript operator ([][])is considered a single operator.
5095
  // Separating the index expressions by parenthesis is not allowed.
5096
0
  if (base && !base->getType().isNull() &&
5097
0
      base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5098
0
      !isa<MatrixSubscriptExpr>(base)) {
5099
0
    Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5100
0
        << SourceRange(base->getBeginLoc(), rbLoc);
5101
0
    return ExprError();
5102
0
  }
5103
  // If the base is a MatrixSubscriptExpr, try to create a new
5104
  // MatrixSubscriptExpr.
5105
0
  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5106
0
  if (matSubscriptE) {
5107
0
    assert(ArgExprs.size() == 1);
5108
0
    if (CheckAndReportCommaError(ArgExprs.front()))
5109
0
      return ExprError();
5110
5111
0
    assert(matSubscriptE->isIncomplete() &&
5112
0
           "base has to be an incomplete matrix subscript");
5113
0
    return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5114
0
                                            matSubscriptE->getRowIdx(),
5115
0
                                            ArgExprs.front(), rbLoc);
5116
0
  }
5117
0
  if (base->getType()->isWebAssemblyTableType()) {
5118
0
    Diag(base->getExprLoc(), diag::err_wasm_table_art)
5119
0
        << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5120
0
    return ExprError();
5121
0
  }
5122
5123
  // Handle any non-overload placeholder types in the base and index
5124
  // expressions.  We can't handle overloads here because the other
5125
  // operand might be an overloadable type, in which case the overload
5126
  // resolution for the operator overload should get the first crack
5127
  // at the overload.
5128
0
  bool IsMSPropertySubscript = false;
5129
0
  if (base->getType()->isNonOverloadPlaceholderType()) {
5130
0
    IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5131
0
    if (!IsMSPropertySubscript) {
5132
0
      ExprResult result = CheckPlaceholderExpr(base);
5133
0
      if (result.isInvalid())
5134
0
        return ExprError();
5135
0
      base = result.get();
5136
0
    }
5137
0
  }
5138
5139
  // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5140
0
  if (base->getType()->isMatrixType()) {
5141
0
    assert(ArgExprs.size() == 1);
5142
0
    if (CheckAndReportCommaError(ArgExprs.front()))
5143
0
      return ExprError();
5144
5145
0
    return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5146
0
                                            rbLoc);
5147
0
  }
5148
5149
0
  if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5150
0
    Expr *idx = ArgExprs[0];
5151
0
    if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5152
0
        (isa<CXXOperatorCallExpr>(idx) &&
5153
0
         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5154
0
      Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5155
0
          << SourceRange(base->getBeginLoc(), rbLoc);
5156
0
    }
5157
0
  }
5158
5159
0
  if (ArgExprs.size() == 1 &&
5160
0
      ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5161
0
    ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5162
0
    if (result.isInvalid())
5163
0
      return ExprError();
5164
0
    ArgExprs[0] = result.get();
5165
0
  } else {
5166
0
    if (checkArgsForPlaceholders(*this, ArgExprs))
5167
0
      return ExprError();
5168
0
  }
5169
5170
  // Build an unanalyzed expression if either operand is type-dependent.
5171
0
  if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5172
0
      (base->isTypeDependent() ||
5173
0
       Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
5174
0
      !isa<PackExpansionExpr>(ArgExprs[0])) {
5175
0
    return new (Context) ArraySubscriptExpr(
5176
0
        base, ArgExprs.front(),
5177
0
        getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5178
0
        VK_LValue, OK_Ordinary, rbLoc);
5179
0
  }
5180
5181
  // MSDN, property (C++)
5182
  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5183
  // This attribute can also be used in the declaration of an empty array in a
5184
  // class or structure definition. For example:
5185
  // __declspec(property(get=GetX, put=PutX)) int x[];
5186
  // The above statement indicates that x[] can be used with one or more array
5187
  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5188
  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5189
0
  if (IsMSPropertySubscript) {
5190
0
    assert(ArgExprs.size() == 1);
5191
    // Build MS property subscript expression if base is MS property reference
5192
    // or MS property subscript.
5193
0
    return new (Context)
5194
0
        MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5195
0
                                VK_LValue, OK_Ordinary, rbLoc);
5196
0
  }
5197
5198
  // Use C++ overloaded-operator rules if either operand has record
5199
  // type.  The spec says to do this if either type is *overloadable*,
5200
  // but enum types can't declare subscript operators or conversion
5201
  // operators, so there's nothing interesting for overload resolution
5202
  // to do if there aren't any record types involved.
5203
  //
5204
  // ObjC pointers have their own subscripting logic that is not tied
5205
  // to overload resolution and so should not take this path.
5206
0
  if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5207
0
      ((base->getType()->isRecordType() ||
5208
0
        (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5209
0
         ArgExprs[0]->getType()->isRecordType())))) {
5210
0
    return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5211
0
  }
5212
5213
0
  ExprResult Res =
5214
0
      CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5215
5216
0
  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5217
0
    CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5218
5219
0
  return Res;
5220
0
}
5221
5222
0
ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5223
0
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
5224
0
  InitializationKind Kind =
5225
0
      InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
5226
0
  InitializationSequence InitSeq(*this, Entity, Kind, E);
5227
0
  return InitSeq.Perform(*this, Entity, Kind, E);
5228
0
}
5229
5230
ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5231
                                                  Expr *ColumnIdx,
5232
0
                                                  SourceLocation RBLoc) {
5233
0
  ExprResult BaseR = CheckPlaceholderExpr(Base);
5234
0
  if (BaseR.isInvalid())
5235
0
    return BaseR;
5236
0
  Base = BaseR.get();
5237
5238
0
  ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5239
0
  if (RowR.isInvalid())
5240
0
    return RowR;
5241
0
  RowIdx = RowR.get();
5242
5243
0
  if (!ColumnIdx)
5244
0
    return new (Context) MatrixSubscriptExpr(
5245
0
        Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5246
5247
  // Build an unanalyzed expression if any of the operands is type-dependent.
5248
0
  if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5249
0
      ColumnIdx->isTypeDependent())
5250
0
    return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5251
0
                                             Context.DependentTy, RBLoc);
5252
5253
0
  ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5254
0
  if (ColumnR.isInvalid())
5255
0
    return ColumnR;
5256
0
  ColumnIdx = ColumnR.get();
5257
5258
  // Check that IndexExpr is an integer expression. If it is a constant
5259
  // expression, check that it is less than Dim (= the number of elements in the
5260
  // corresponding dimension).
5261
0
  auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5262
0
                          bool IsColumnIdx) -> Expr * {
5263
0
    if (!IndexExpr->getType()->isIntegerType() &&
5264
0
        !IndexExpr->isTypeDependent()) {
5265
0
      Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5266
0
          << IsColumnIdx;
5267
0
      return nullptr;
5268
0
    }
5269
5270
0
    if (std::optional<llvm::APSInt> Idx =
5271
0
            IndexExpr->getIntegerConstantExpr(Context)) {
5272
0
      if ((*Idx < 0 || *Idx >= Dim)) {
5273
0
        Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5274
0
            << IsColumnIdx << Dim;
5275
0
        return nullptr;
5276
0
      }
5277
0
    }
5278
5279
0
    ExprResult ConvExpr =
5280
0
        tryConvertExprToType(IndexExpr, Context.getSizeType());
5281
0
    assert(!ConvExpr.isInvalid() &&
5282
0
           "should be able to convert any integer type to size type");
5283
0
    return ConvExpr.get();
5284
0
  };
5285
5286
0
  auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5287
0
  RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5288
0
  ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5289
0
  if (!RowIdx || !ColumnIdx)
5290
0
    return ExprError();
5291
5292
0
  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5293
0
                                           MTy->getElementType(), RBLoc);
5294
0
}
5295
5296
0
void Sema::CheckAddressOfNoDeref(const Expr *E) {
5297
0
  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5298
0
  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5299
5300
  // For expressions like `&(*s).b`, the base is recorded and what should be
5301
  // checked.
5302
0
  const MemberExpr *Member = nullptr;
5303
0
  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5304
0
    StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5305
5306
0
  LastRecord.PossibleDerefs.erase(StrippedExpr);
5307
0
}
5308
5309
0
void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5310
0
  if (isUnevaluatedContext())
5311
0
    return;
5312
5313
0
  QualType ResultTy = E->getType();
5314
0
  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5315
5316
  // Bail if the element is an array since it is not memory access.
5317
0
  if (isa<ArrayType>(ResultTy))
5318
0
    return;
5319
5320
0
  if (ResultTy->hasAttr(attr::NoDeref)) {
5321
0
    LastRecord.PossibleDerefs.insert(E);
5322
0
    return;
5323
0
  }
5324
5325
  // Check if the base type is a pointer to a member access of a struct
5326
  // marked with noderef.
5327
0
  const Expr *Base = E->getBase();
5328
0
  QualType BaseTy = Base->getType();
5329
0
  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5330
    // Not a pointer access
5331
0
    return;
5332
5333
0
  const MemberExpr *Member = nullptr;
5334
0
  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5335
0
         Member->isArrow())
5336
0
    Base = Member->getBase();
5337
5338
0
  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5339
0
    if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5340
0
      LastRecord.PossibleDerefs.insert(E);
5341
0
  }
5342
0
}
5343
5344
ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5345
                                          Expr *LowerBound,
5346
                                          SourceLocation ColonLocFirst,
5347
                                          SourceLocation ColonLocSecond,
5348
                                          Expr *Length, Expr *Stride,
5349
0
                                          SourceLocation RBLoc) {
5350
0
  if (Base->hasPlaceholderType() &&
5351
0
      !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5352
0
    ExprResult Result = CheckPlaceholderExpr(Base);
5353
0
    if (Result.isInvalid())
5354
0
      return ExprError();
5355
0
    Base = Result.get();
5356
0
  }
5357
0
  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5358
0
    ExprResult Result = CheckPlaceholderExpr(LowerBound);
5359
0
    if (Result.isInvalid())
5360
0
      return ExprError();
5361
0
    Result = DefaultLvalueConversion(Result.get());
5362
0
    if (Result.isInvalid())
5363
0
      return ExprError();
5364
0
    LowerBound = Result.get();
5365
0
  }
5366
0
  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5367
0
    ExprResult Result = CheckPlaceholderExpr(Length);
5368
0
    if (Result.isInvalid())
5369
0
      return ExprError();
5370
0
    Result = DefaultLvalueConversion(Result.get());
5371
0
    if (Result.isInvalid())
5372
0
      return ExprError();
5373
0
    Length = Result.get();
5374
0
  }
5375
0
  if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5376
0
    ExprResult Result = CheckPlaceholderExpr(Stride);
5377
0
    if (Result.isInvalid())
5378
0
      return ExprError();
5379
0
    Result = DefaultLvalueConversion(Result.get());
5380
0
    if (Result.isInvalid())
5381
0
      return ExprError();
5382
0
    Stride = Result.get();
5383
0
  }
5384
5385
  // Build an unanalyzed expression if either operand is type-dependent.
5386
0
  if (Base->isTypeDependent() ||
5387
0
      (LowerBound &&
5388
0
       (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5389
0
      (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5390
0
      (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5391
0
    return new (Context) OMPArraySectionExpr(
5392
0
        Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5393
0
        OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5394
0
  }
5395
5396
  // Perform default conversions.
5397
0
  QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5398
0
  QualType ResultTy;
5399
0
  if (OriginalTy->isAnyPointerType()) {
5400
0
    ResultTy = OriginalTy->getPointeeType();
5401
0
  } else if (OriginalTy->isArrayType()) {
5402
0
    ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5403
0
  } else {
5404
0
    return ExprError(
5405
0
        Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5406
0
        << Base->getSourceRange());
5407
0
  }
5408
  // C99 6.5.2.1p1
5409
0
  if (LowerBound) {
5410
0
    auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5411
0
                                                      LowerBound);
5412
0
    if (Res.isInvalid())
5413
0
      return ExprError(Diag(LowerBound->getExprLoc(),
5414
0
                            diag::err_omp_typecheck_section_not_integer)
5415
0
                       << 0 << LowerBound->getSourceRange());
5416
0
    LowerBound = Res.get();
5417
5418
0
    if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5419
0
        LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5420
0
      Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5421
0
          << 0 << LowerBound->getSourceRange();
5422
0
  }
5423
0
  if (Length) {
5424
0
    auto Res =
5425
0
        PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5426
0
    if (Res.isInvalid())
5427
0
      return ExprError(Diag(Length->getExprLoc(),
5428
0
                            diag::err_omp_typecheck_section_not_integer)
5429
0
                       << 1 << Length->getSourceRange());
5430
0
    Length = Res.get();
5431
5432
0
    if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5433
0
        Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5434
0
      Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5435
0
          << 1 << Length->getSourceRange();
5436
0
  }
5437
0
  if (Stride) {
5438
0
    ExprResult Res =
5439
0
        PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5440
0
    if (Res.isInvalid())
5441
0
      return ExprError(Diag(Stride->getExprLoc(),
5442
0
                            diag::err_omp_typecheck_section_not_integer)
5443
0
                       << 1 << Stride->getSourceRange());
5444
0
    Stride = Res.get();
5445
5446
0
    if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5447
0
        Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5448
0
      Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5449
0
          << 1 << Stride->getSourceRange();
5450
0
  }
5451
5452
  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5453
  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5454
  // type. Note that functions are not objects, and that (in C99 parlance)
5455
  // incomplete types are not object types.
5456
0
  if (ResultTy->isFunctionType()) {
5457
0
    Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5458
0
        << ResultTy << Base->getSourceRange();
5459
0
    return ExprError();
5460
0
  }
5461
5462
0
  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5463
0
                          diag::err_omp_section_incomplete_type, Base))
5464
0
    return ExprError();
5465
5466
0
  if (LowerBound && !OriginalTy->isAnyPointerType()) {
5467
0
    Expr::EvalResult Result;
5468
0
    if (LowerBound->EvaluateAsInt(Result, Context)) {
5469
      // OpenMP 5.0, [2.1.5 Array Sections]
5470
      // The array section must be a subset of the original array.
5471
0
      llvm::APSInt LowerBoundValue = Result.Val.getInt();
5472
0
      if (LowerBoundValue.isNegative()) {
5473
0
        Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5474
0
            << LowerBound->getSourceRange();
5475
0
        return ExprError();
5476
0
      }
5477
0
    }
5478
0
  }
5479
5480
0
  if (Length) {
5481
0
    Expr::EvalResult Result;
5482
0
    if (Length->EvaluateAsInt(Result, Context)) {
5483
      // OpenMP 5.0, [2.1.5 Array Sections]
5484
      // The length must evaluate to non-negative integers.
5485
0
      llvm::APSInt LengthValue = Result.Val.getInt();
5486
0
      if (LengthValue.isNegative()) {
5487
0
        Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5488
0
            << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5489
0
            << Length->getSourceRange();
5490
0
        return ExprError();
5491
0
      }
5492
0
    }
5493
0
  } else if (ColonLocFirst.isValid() &&
5494
0
             (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5495
0
                                      !OriginalTy->isVariableArrayType()))) {
5496
    // OpenMP 5.0, [2.1.5 Array Sections]
5497
    // When the size of the array dimension is not known, the length must be
5498
    // specified explicitly.
5499
0
    Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5500
0
        << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5501
0
    return ExprError();
5502
0
  }
5503
5504
0
  if (Stride) {
5505
0
    Expr::EvalResult Result;
5506
0
    if (Stride->EvaluateAsInt(Result, Context)) {
5507
      // OpenMP 5.0, [2.1.5 Array Sections]
5508
      // The stride must evaluate to a positive integer.
5509
0
      llvm::APSInt StrideValue = Result.Val.getInt();
5510
0
      if (!StrideValue.isStrictlyPositive()) {
5511
0
        Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5512
0
            << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5513
0
            << Stride->getSourceRange();
5514
0
        return ExprError();
5515
0
      }
5516
0
    }
5517
0
  }
5518
5519
0
  if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5520
0
    ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5521
0
    if (Result.isInvalid())
5522
0
      return ExprError();
5523
0
    Base = Result.get();
5524
0
  }
5525
0
  return new (Context) OMPArraySectionExpr(
5526
0
      Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5527
0
      OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5528
0
}
5529
5530
ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5531
                                          SourceLocation RParenLoc,
5532
                                          ArrayRef<Expr *> Dims,
5533
0
                                          ArrayRef<SourceRange> Brackets) {
5534
0
  if (Base->hasPlaceholderType()) {
5535
0
    ExprResult Result = CheckPlaceholderExpr(Base);
5536
0
    if (Result.isInvalid())
5537
0
      return ExprError();
5538
0
    Result = DefaultLvalueConversion(Result.get());
5539
0
    if (Result.isInvalid())
5540
0
      return ExprError();
5541
0
    Base = Result.get();
5542
0
  }
5543
0
  QualType BaseTy = Base->getType();
5544
  // Delay analysis of the types/expressions if instantiation/specialization is
5545
  // required.
5546
0
  if (!BaseTy->isPointerType() && Base->isTypeDependent())
5547
0
    return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5548
0
                                       LParenLoc, RParenLoc, Dims, Brackets);
5549
0
  if (!BaseTy->isPointerType() ||
5550
0
      (!Base->isTypeDependent() &&
5551
0
       BaseTy->getPointeeType()->isIncompleteType()))
5552
0
    return ExprError(Diag(Base->getExprLoc(),
5553
0
                          diag::err_omp_non_pointer_type_array_shaping_base)
5554
0
                     << Base->getSourceRange());
5555
5556
0
  SmallVector<Expr *, 4> NewDims;
5557
0
  bool ErrorFound = false;
5558
0
  for (Expr *Dim : Dims) {
5559
0
    if (Dim->hasPlaceholderType()) {
5560
0
      ExprResult Result = CheckPlaceholderExpr(Dim);
5561
0
      if (Result.isInvalid()) {
5562
0
        ErrorFound = true;
5563
0
        continue;
5564
0
      }
5565
0
      Result = DefaultLvalueConversion(Result.get());
5566
0
      if (Result.isInvalid()) {
5567
0
        ErrorFound = true;
5568
0
        continue;
5569
0
      }
5570
0
      Dim = Result.get();
5571
0
    }
5572
0
    if (!Dim->isTypeDependent()) {
5573
0
      ExprResult Result =
5574
0
          PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5575
0
      if (Result.isInvalid()) {
5576
0
        ErrorFound = true;
5577
0
        Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5578
0
            << Dim->getSourceRange();
5579
0
        continue;
5580
0
      }
5581
0
      Dim = Result.get();
5582
0
      Expr::EvalResult EvResult;
5583
0
      if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5584
        // OpenMP 5.0, [2.1.4 Array Shaping]
5585
        // Each si is an integral type expression that must evaluate to a
5586
        // positive integer.
5587
0
        llvm::APSInt Value = EvResult.Val.getInt();
5588
0
        if (!Value.isStrictlyPositive()) {
5589
0
          Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5590
0
              << toString(Value, /*Radix=*/10, /*Signed=*/true)
5591
0
              << Dim->getSourceRange();
5592
0
          ErrorFound = true;
5593
0
          continue;
5594
0
        }
5595
0
      }
5596
0
    }
5597
0
    NewDims.push_back(Dim);
5598
0
  }
5599
0
  if (ErrorFound)
5600
0
    return ExprError();
5601
0
  return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5602
0
                                     LParenLoc, RParenLoc, NewDims, Brackets);
5603
0
}
5604
5605
ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5606
                                      SourceLocation LLoc, SourceLocation RLoc,
5607
0
                                      ArrayRef<OMPIteratorData> Data) {
5608
0
  SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5609
0
  bool IsCorrect = true;
5610
0
  for (const OMPIteratorData &D : Data) {
5611
0
    TypeSourceInfo *TInfo = nullptr;
5612
0
    SourceLocation StartLoc;
5613
0
    QualType DeclTy;
5614
0
    if (!D.Type.getAsOpaquePtr()) {
5615
      // OpenMP 5.0, 2.1.6 Iterators
5616
      // In an iterator-specifier, if the iterator-type is not specified then
5617
      // the type of that iterator is of int type.
5618
0
      DeclTy = Context.IntTy;
5619
0
      StartLoc = D.DeclIdentLoc;
5620
0
    } else {
5621
0
      DeclTy = GetTypeFromParser(D.Type, &TInfo);
5622
0
      StartLoc = TInfo->getTypeLoc().getBeginLoc();
5623
0
    }
5624
5625
0
    bool IsDeclTyDependent = DeclTy->isDependentType() ||
5626
0
                             DeclTy->containsUnexpandedParameterPack() ||
5627
0
                             DeclTy->isInstantiationDependentType();
5628
0
    if (!IsDeclTyDependent) {
5629
0
      if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5630
        // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5631
        // The iterator-type must be an integral or pointer type.
5632
0
        Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5633
0
            << DeclTy;
5634
0
        IsCorrect = false;
5635
0
        continue;
5636
0
      }
5637
0
      if (DeclTy.isConstant(Context)) {
5638
        // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5639
        // The iterator-type must not be const qualified.
5640
0
        Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5641
0
            << DeclTy;
5642
0
        IsCorrect = false;
5643
0
        continue;
5644
0
      }
5645
0
    }
5646
5647
    // Iterator declaration.
5648
0
    assert(D.DeclIdent && "Identifier expected.");
5649
    // Always try to create iterator declarator to avoid extra error messages
5650
    // about unknown declarations use.
5651
0
    auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5652
0
                               D.DeclIdent, DeclTy, TInfo, SC_None);
5653
0
    VD->setImplicit();
5654
0
    if (S) {
5655
      // Check for conflicting previous declaration.
5656
0
      DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5657
0
      LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5658
0
                            ForVisibleRedeclaration);
5659
0
      Previous.suppressDiagnostics();
5660
0
      LookupName(Previous, S);
5661
5662
0
      FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5663
0
                           /*AllowInlineNamespace=*/false);
5664
0
      if (!Previous.empty()) {
5665
0
        NamedDecl *Old = Previous.getRepresentativeDecl();
5666
0
        Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5667
0
        Diag(Old->getLocation(), diag::note_previous_definition);
5668
0
      } else {
5669
0
        PushOnScopeChains(VD, S);
5670
0
      }
5671
0
    } else {
5672
0
      CurContext->addDecl(VD);
5673
0
    }
5674
5675
    /// Act on the iterator variable declaration.
5676
0
    ActOnOpenMPIteratorVarDecl(VD);
5677
5678
0
    Expr *Begin = D.Range.Begin;
5679
0
    if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5680
0
      ExprResult BeginRes =
5681
0
          PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5682
0
      Begin = BeginRes.get();
5683
0
    }
5684
0
    Expr *End = D.Range.End;
5685
0
    if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5686
0
      ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5687
0
      End = EndRes.get();
5688
0
    }
5689
0
    Expr *Step = D.Range.Step;
5690
0
    if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5691
0
      if (!Step->getType()->isIntegralType(Context)) {
5692
0
        Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5693
0
            << Step << Step->getSourceRange();
5694
0
        IsCorrect = false;
5695
0
        continue;
5696
0
      }
5697
0
      std::optional<llvm::APSInt> Result =
5698
0
          Step->getIntegerConstantExpr(Context);
5699
      // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5700
      // If the step expression of a range-specification equals zero, the
5701
      // behavior is unspecified.
5702
0
      if (Result && Result->isZero()) {
5703
0
        Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5704
0
            << Step << Step->getSourceRange();
5705
0
        IsCorrect = false;
5706
0
        continue;
5707
0
      }
5708
0
    }
5709
0
    if (!Begin || !End || !IsCorrect) {
5710
0
      IsCorrect = false;
5711
0
      continue;
5712
0
    }
5713
0
    OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5714
0
    IDElem.IteratorDecl = VD;
5715
0
    IDElem.AssignmentLoc = D.AssignLoc;
5716
0
    IDElem.Range.Begin = Begin;
5717
0
    IDElem.Range.End = End;
5718
0
    IDElem.Range.Step = Step;
5719
0
    IDElem.ColonLoc = D.ColonLoc;
5720
0
    IDElem.SecondColonLoc = D.SecColonLoc;
5721
0
  }
5722
0
  if (!IsCorrect) {
5723
    // Invalidate all created iterator declarations if error is found.
5724
0
    for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5725
0
      if (Decl *ID = D.IteratorDecl)
5726
0
        ID->setInvalidDecl();
5727
0
    }
5728
0
    return ExprError();
5729
0
  }
5730
0
  SmallVector<OMPIteratorHelperData, 4> Helpers;
5731
0
  if (!CurContext->isDependentContext()) {
5732
    // Build number of ityeration for each iteration range.
5733
    // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5734
    // ((Begini-Stepi-1-Endi) / -Stepi);
5735
0
    for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5736
      // (Endi - Begini)
5737
0
      ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5738
0
                                          D.Range.Begin);
5739
0
      if(!Res.isUsable()) {
5740
0
        IsCorrect = false;
5741
0
        continue;
5742
0
      }
5743
0
      ExprResult St, St1;
5744
0
      if (D.Range.Step) {
5745
0
        St = D.Range.Step;
5746
        // (Endi - Begini) + Stepi
5747
0
        Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5748
0
        if (!Res.isUsable()) {
5749
0
          IsCorrect = false;
5750
0
          continue;
5751
0
        }
5752
        // (Endi - Begini) + Stepi - 1
5753
0
        Res =
5754
0
            CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5755
0
                               ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5756
0
        if (!Res.isUsable()) {
5757
0
          IsCorrect = false;
5758
0
          continue;
5759
0
        }
5760
        // ((Endi - Begini) + Stepi - 1) / Stepi
5761
0
        Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5762
0
        if (!Res.isUsable()) {
5763
0
          IsCorrect = false;
5764
0
          continue;
5765
0
        }
5766
0
        St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5767
        // (Begini - Endi)
5768
0
        ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5769
0
                                             D.Range.Begin, D.Range.End);
5770
0
        if (!Res1.isUsable()) {
5771
0
          IsCorrect = false;
5772
0
          continue;
5773
0
        }
5774
        // (Begini - Endi) - Stepi
5775
0
        Res1 =
5776
0
            CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5777
0
        if (!Res1.isUsable()) {
5778
0
          IsCorrect = false;
5779
0
          continue;
5780
0
        }
5781
        // (Begini - Endi) - Stepi - 1
5782
0
        Res1 =
5783
0
            CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5784
0
                               ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5785
0
        if (!Res1.isUsable()) {
5786
0
          IsCorrect = false;
5787
0
          continue;
5788
0
        }
5789
        // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5790
0
        Res1 =
5791
0
            CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5792
0
        if (!Res1.isUsable()) {
5793
0
          IsCorrect = false;
5794
0
          continue;
5795
0
        }
5796
        // Stepi > 0.
5797
0
        ExprResult CmpRes =
5798
0
            CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5799
0
                               ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5800
0
        if (!CmpRes.isUsable()) {
5801
0
          IsCorrect = false;
5802
0
          continue;
5803
0
        }
5804
0
        Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5805
0
                                 Res.get(), Res1.get());
5806
0
        if (!Res.isUsable()) {
5807
0
          IsCorrect = false;
5808
0
          continue;
5809
0
        }
5810
0
      }
5811
0
      Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5812
0
      if (!Res.isUsable()) {
5813
0
        IsCorrect = false;
5814
0
        continue;
5815
0
      }
5816
5817
      // Build counter update.
5818
      // Build counter.
5819
0
      auto *CounterVD =
5820
0
          VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5821
0
                          D.IteratorDecl->getBeginLoc(), nullptr,
5822
0
                          Res.get()->getType(), nullptr, SC_None);
5823
0
      CounterVD->setImplicit();
5824
0
      ExprResult RefRes =
5825
0
          BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5826
0
                           D.IteratorDecl->getBeginLoc());
5827
      // Build counter update.
5828
      // I = Begini + counter * Stepi;
5829
0
      ExprResult UpdateRes;
5830
0
      if (D.Range.Step) {
5831
0
        UpdateRes = CreateBuiltinBinOp(
5832
0
            D.AssignmentLoc, BO_Mul,
5833
0
            DefaultLvalueConversion(RefRes.get()).get(), St.get());
5834
0
      } else {
5835
0
        UpdateRes = DefaultLvalueConversion(RefRes.get());
5836
0
      }
5837
0
      if (!UpdateRes.isUsable()) {
5838
0
        IsCorrect = false;
5839
0
        continue;
5840
0
      }
5841
0
      UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5842
0
                                     UpdateRes.get());
5843
0
      if (!UpdateRes.isUsable()) {
5844
0
        IsCorrect = false;
5845
0
        continue;
5846
0
      }
5847
0
      ExprResult VDRes =
5848
0
          BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5849
0
                           cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5850
0
                           D.IteratorDecl->getBeginLoc());
5851
0
      UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5852
0
                                     UpdateRes.get());
5853
0
      if (!UpdateRes.isUsable()) {
5854
0
        IsCorrect = false;
5855
0
        continue;
5856
0
      }
5857
0
      UpdateRes =
5858
0
          ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5859
0
      if (!UpdateRes.isUsable()) {
5860
0
        IsCorrect = false;
5861
0
        continue;
5862
0
      }
5863
0
      ExprResult CounterUpdateRes =
5864
0
          CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5865
0
      if (!CounterUpdateRes.isUsable()) {
5866
0
        IsCorrect = false;
5867
0
        continue;
5868
0
      }
5869
0
      CounterUpdateRes =
5870
0
          ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5871
0
      if (!CounterUpdateRes.isUsable()) {
5872
0
        IsCorrect = false;
5873
0
        continue;
5874
0
      }
5875
0
      OMPIteratorHelperData &HD = Helpers.emplace_back();
5876
0
      HD.CounterVD = CounterVD;
5877
0
      HD.Upper = Res.get();
5878
0
      HD.Update = UpdateRes.get();
5879
0
      HD.CounterUpdate = CounterUpdateRes.get();
5880
0
    }
5881
0
  } else {
5882
0
    Helpers.assign(ID.size(), {});
5883
0
  }
5884
0
  if (!IsCorrect) {
5885
    // Invalidate all created iterator declarations if error is found.
5886
0
    for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5887
0
      if (Decl *ID = D.IteratorDecl)
5888
0
        ID->setInvalidDecl();
5889
0
    }
5890
0
    return ExprError();
5891
0
  }
5892
0
  return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5893
0
                                 LLoc, RLoc, ID, Helpers);
5894
0
}
5895
5896
ExprResult
5897
Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5898
0
                                      Expr *Idx, SourceLocation RLoc) {
5899
0
  Expr *LHSExp = Base;
5900
0
  Expr *RHSExp = Idx;
5901
5902
0
  ExprValueKind VK = VK_LValue;
5903
0
  ExprObjectKind OK = OK_Ordinary;
5904
5905
  // Per C++ core issue 1213, the result is an xvalue if either operand is
5906
  // a non-lvalue array, and an lvalue otherwise.
5907
0
  if (getLangOpts().CPlusPlus11) {
5908
0
    for (auto *Op : {LHSExp, RHSExp}) {
5909
0
      Op = Op->IgnoreImplicit();
5910
0
      if (Op->getType()->isArrayType() && !Op->isLValue())
5911
0
        VK = VK_XValue;
5912
0
    }
5913
0
  }
5914
5915
  // Perform default conversions.
5916
0
  if (!LHSExp->getType()->getAs<VectorType>()) {
5917
0
    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5918
0
    if (Result.isInvalid())
5919
0
      return ExprError();
5920
0
    LHSExp = Result.get();
5921
0
  }
5922
0
  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5923
0
  if (Result.isInvalid())
5924
0
    return ExprError();
5925
0
  RHSExp = Result.get();
5926
5927
0
  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5928
5929
  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5930
  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5931
  // in the subscript position. As a result, we need to derive the array base
5932
  // and index from the expression types.
5933
0
  Expr *BaseExpr, *IndexExpr;
5934
0
  QualType ResultType;
5935
0
  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5936
0
    BaseExpr = LHSExp;
5937
0
    IndexExpr = RHSExp;
5938
0
    ResultType =
5939
0
        getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5940
0
  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5941
0
    BaseExpr = LHSExp;
5942
0
    IndexExpr = RHSExp;
5943
0
    ResultType = PTy->getPointeeType();
5944
0
  } else if (const ObjCObjectPointerType *PTy =
5945
0
               LHSTy->getAs<ObjCObjectPointerType>()) {
5946
0
    BaseExpr = LHSExp;
5947
0
    IndexExpr = RHSExp;
5948
5949
    // Use custom logic if this should be the pseudo-object subscript
5950
    // expression.
5951
0
    if (!LangOpts.isSubscriptPointerArithmetic())
5952
0
      return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5953
0
                                          nullptr);
5954
5955
0
    ResultType = PTy->getPointeeType();
5956
0
  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5957
     // Handle the uncommon case of "123[Ptr]".
5958
0
    BaseExpr = RHSExp;
5959
0
    IndexExpr = LHSExp;
5960
0
    ResultType = PTy->getPointeeType();
5961
0
  } else if (const ObjCObjectPointerType *PTy =
5962
0
               RHSTy->getAs<ObjCObjectPointerType>()) {
5963
     // Handle the uncommon case of "123[Ptr]".
5964
0
    BaseExpr = RHSExp;
5965
0
    IndexExpr = LHSExp;
5966
0
    ResultType = PTy->getPointeeType();
5967
0
    if (!LangOpts.isSubscriptPointerArithmetic()) {
5968
0
      Diag(LLoc, diag::err_subscript_nonfragile_interface)
5969
0
        << ResultType << BaseExpr->getSourceRange();
5970
0
      return ExprError();
5971
0
    }
5972
0
  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5973
0
    BaseExpr = LHSExp;    // vectors: V[123]
5974
0
    IndexExpr = RHSExp;
5975
    // We apply C++ DR1213 to vector subscripting too.
5976
0
    if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5977
0
      ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5978
0
      if (Materialized.isInvalid())
5979
0
        return ExprError();
5980
0
      LHSExp = Materialized.get();
5981
0
    }
5982
0
    VK = LHSExp->getValueKind();
5983
0
    if (VK != VK_PRValue)
5984
0
      OK = OK_VectorComponent;
5985
5986
0
    ResultType = VTy->getElementType();
5987
0
    QualType BaseType = BaseExpr->getType();
5988
0
    Qualifiers BaseQuals = BaseType.getQualifiers();
5989
0
    Qualifiers MemberQuals = ResultType.getQualifiers();
5990
0
    Qualifiers Combined = BaseQuals + MemberQuals;
5991
0
    if (Combined != MemberQuals)
5992
0
      ResultType = Context.getQualifiedType(ResultType, Combined);
5993
0
  } else if (LHSTy->isBuiltinType() &&
5994
0
             LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5995
0
    const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5996
0
    if (BTy->isSVEBool())
5997
0
      return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5998
0
                       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5999
6000
0
    BaseExpr = LHSExp;
6001
0
    IndexExpr = RHSExp;
6002
0
    if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
6003
0
      ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
6004
0
      if (Materialized.isInvalid())
6005
0
        return ExprError();
6006
0
      LHSExp = Materialized.get();
6007
0
    }
6008
0
    VK = LHSExp->getValueKind();
6009
0
    if (VK != VK_PRValue)
6010
0
      OK = OK_VectorComponent;
6011
6012
0
    ResultType = BTy->getSveEltType(Context);
6013
6014
0
    QualType BaseType = BaseExpr->getType();
6015
0
    Qualifiers BaseQuals = BaseType.getQualifiers();
6016
0
    Qualifiers MemberQuals = ResultType.getQualifiers();
6017
0
    Qualifiers Combined = BaseQuals + MemberQuals;
6018
0
    if (Combined != MemberQuals)
6019
0
      ResultType = Context.getQualifiedType(ResultType, Combined);
6020
0
  } else if (LHSTy->isArrayType()) {
6021
    // If we see an array that wasn't promoted by
6022
    // DefaultFunctionArrayLvalueConversion, it must be an array that
6023
    // wasn't promoted because of the C90 rule that doesn't
6024
    // allow promoting non-lvalue arrays.  Warn, then
6025
    // force the promotion here.
6026
0
    Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
6027
0
        << LHSExp->getSourceRange();
6028
0
    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
6029
0
                               CK_ArrayToPointerDecay).get();
6030
0
    LHSTy = LHSExp->getType();
6031
6032
0
    BaseExpr = LHSExp;
6033
0
    IndexExpr = RHSExp;
6034
0
    ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
6035
0
  } else if (RHSTy->isArrayType()) {
6036
    // Same as previous, except for 123[f().a] case
6037
0
    Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
6038
0
        << RHSExp->getSourceRange();
6039
0
    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
6040
0
                               CK_ArrayToPointerDecay).get();
6041
0
    RHSTy = RHSExp->getType();
6042
6043
0
    BaseExpr = RHSExp;
6044
0
    IndexExpr = LHSExp;
6045
0
    ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
6046
0
  } else {
6047
0
    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
6048
0
       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
6049
0
  }
6050
  // C99 6.5.2.1p1
6051
0
  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
6052
0
    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
6053
0
                     << IndexExpr->getSourceRange());
6054
6055
0
  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
6056
0
       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
6057
0
      !IndexExpr->isTypeDependent()) {
6058
0
    std::optional<llvm::APSInt> IntegerContantExpr =
6059
0
        IndexExpr->getIntegerConstantExpr(getASTContext());
6060
0
    if (!IntegerContantExpr.has_value() ||
6061
0
        IntegerContantExpr.value().isNegative())
6062
0
      Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
6063
0
  }
6064
6065
  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
6066
  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
6067
  // type. Note that Functions are not objects, and that (in C99 parlance)
6068
  // incomplete types are not object types.
6069
0
  if (ResultType->isFunctionType()) {
6070
0
    Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
6071
0
        << ResultType << BaseExpr->getSourceRange();
6072
0
    return ExprError();
6073
0
  }
6074
6075
0
  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
6076
    // GNU extension: subscripting on pointer to void
6077
0
    Diag(LLoc, diag::ext_gnu_subscript_void_type)
6078
0
      << BaseExpr->getSourceRange();
6079
6080
    // C forbids expressions of unqualified void type from being l-values.
6081
    // See IsCForbiddenLValueType.
6082
0
    if (!ResultType.hasQualifiers())
6083
0
      VK = VK_PRValue;
6084
0
  } else if (!ResultType->isDependentType() &&
6085
0
             !ResultType.isWebAssemblyReferenceType() &&
6086
0
             RequireCompleteSizedType(
6087
0
                 LLoc, ResultType,
6088
0
                 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
6089
0
    return ExprError();
6090
6091
0
  assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
6092
0
         !ResultType.isCForbiddenLValueType());
6093
6094
0
  if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
6095
0
      FunctionScopes.size() > 1) {
6096
0
    if (auto *TT =
6097
0
            LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
6098
0
      for (auto I = FunctionScopes.rbegin(),
6099
0
                E = std::prev(FunctionScopes.rend());
6100
0
           I != E; ++I) {
6101
0
        auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
6102
0
        if (CSI == nullptr)
6103
0
          break;
6104
0
        DeclContext *DC = nullptr;
6105
0
        if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
6106
0
          DC = LSI->CallOperator;
6107
0
        else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
6108
0
          DC = CRSI->TheCapturedDecl;
6109
0
        else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
6110
0
          DC = BSI->TheDecl;
6111
0
        if (DC) {
6112
0
          if (DC->containsDecl(TT->getDecl()))
6113
0
            break;
6114
0
          captureVariablyModifiedType(
6115
0
              Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
6116
0
        }
6117
0
      }
6118
0
    }
6119
0
  }
6120
6121
0
  return new (Context)
6122
0
      ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
6123
0
}
6124
6125
bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6126
                                  ParmVarDecl *Param, Expr *RewrittenInit,
6127
0
                                  bool SkipImmediateInvocations) {
6128
0
  if (Param->hasUnparsedDefaultArg()) {
6129
0
    assert(!RewrittenInit && "Should not have a rewritten init expression yet");
6130
    // If we've already cleared out the location for the default argument,
6131
    // that means we're parsing it right now.
6132
0
    if (!UnparsedDefaultArgLocs.count(Param)) {
6133
0
      Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
6134
0
      Diag(CallLoc, diag::note_recursive_default_argument_used_here);
6135
0
      Param->setInvalidDecl();
6136
0
      return true;
6137
0
    }
6138
6139
0
    Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
6140
0
        << FD << cast<CXXRecordDecl>(FD->getDeclContext());
6141
0
    Diag(UnparsedDefaultArgLocs[Param],
6142
0
         diag::note_default_argument_declared_here);
6143
0
    return true;
6144
0
  }
6145
6146
0
  if (Param->hasUninstantiatedDefaultArg()) {
6147
0
    assert(!RewrittenInit && "Should not have a rewitten init expression yet");
6148
0
    if (InstantiateDefaultArgument(CallLoc, FD, Param))
6149
0
      return true;
6150
0
  }
6151
6152
0
  Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
6153
0
  assert(Init && "default argument but no initializer?");
6154
6155
  // If the default expression creates temporaries, we need to
6156
  // push them to the current stack of expression temporaries so they'll
6157
  // be properly destroyed.
6158
  // FIXME: We should really be rebuilding the default argument with new
6159
  // bound temporaries; see the comment in PR5810.
6160
  // We don't need to do that with block decls, though, because
6161
  // blocks in default argument expression can never capture anything.
6162
0
  if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
6163
    // Set the "needs cleanups" bit regardless of whether there are
6164
    // any explicit objects.
6165
0
    Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
6166
    // Append all the objects to the cleanup list.  Right now, this
6167
    // should always be a no-op, because blocks in default argument
6168
    // expressions should never be able to capture anything.
6169
0
    assert(!InitWithCleanup->getNumObjects() &&
6170
0
           "default argument expression has capturing blocks?");
6171
0
  }
6172
  // C++ [expr.const]p15.1:
6173
  //   An expression or conversion is in an immediate function context if it is
6174
  //   potentially evaluated and [...] its innermost enclosing non-block scope
6175
  //   is a function parameter scope of an immediate function.
6176
0
  EnterExpressionEvaluationContext EvalContext(
6177
0
      *this,
6178
0
      FD->isImmediateFunction()
6179
0
          ? ExpressionEvaluationContext::ImmediateFunctionContext
6180
0
          : ExpressionEvaluationContext::PotentiallyEvaluated,
6181
0
      Param);
6182
0
  ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6183
0
      SkipImmediateInvocations;
6184
0
  runWithSufficientStackSpace(CallLoc, [&] {
6185
0
    MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
6186
0
  });
6187
0
  return false;
6188
0
}
6189
6190
struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
6191
  const ASTContext &Context;
6192
0
  ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
6193
6194
  bool HasImmediateCalls = false;
6195
0
  bool shouldVisitImplicitCode() const { return true; }
6196
6197
0
  bool VisitCallExpr(CallExpr *E) {
6198
0
    if (const FunctionDecl *FD = E->getDirectCallee())
6199
0
      HasImmediateCalls |= FD->isImmediateFunction();
6200
0
    return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6201
0
  }
6202
6203
  // SourceLocExpr are not immediate invocations
6204
  // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
6205
  // need to be rebuilt so that they refer to the correct SourceLocation and
6206
  // DeclContext.
6207
0
  bool VisitSourceLocExpr(SourceLocExpr *E) {
6208
0
    HasImmediateCalls = true;
6209
0
    return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6210
0
  }
6211
6212
  // A nested lambda might have parameters with immediate invocations
6213
  // in their default arguments.
6214
  // The compound statement is not visited (as it does not constitute a
6215
  // subexpression).
6216
  // FIXME: We should consider visiting and transforming captures
6217
  // with init expressions.
6218
0
  bool VisitLambdaExpr(LambdaExpr *E) {
6219
0
    return VisitCXXMethodDecl(E->getCallOperator());
6220
0
  }
6221
6222
  // Blocks don't support default parameters, and, as for lambdas,
6223
  // we don't consider their body a subexpression.
6224
0
  bool VisitBlockDecl(BlockDecl *B) { return false; }
6225
6226
0
  bool VisitCompoundStmt(CompoundStmt *B) { return false; }
6227
6228
0
  bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6229
0
    return TraverseStmt(E->getExpr());
6230
0
  }
6231
6232
0
  bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
6233
0
    return TraverseStmt(E->getExpr());
6234
0
  }
6235
};
6236
6237
struct EnsureImmediateInvocationInDefaultArgs
6238
    : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
6239
  EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
6240
0
      : TreeTransform(SemaRef) {}
6241
6242
  // Lambda can only have immediate invocations in the default
6243
  // args of their parameters, which is transformed upon calling the closure.
6244
  // The body is not a subexpression, so we have nothing to do.
6245
  // FIXME: Immediate calls in capture initializers should be transformed.
6246
0
  ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
6247
0
  ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
6248
6249
  // Make sure we don't rebuild the this pointer as it would
6250
  // cause it to incorrectly point it to the outermost class
6251
  // in the case of nested struct initialization.
6252
0
  ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
6253
};
6254
6255
ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6256
                                        FunctionDecl *FD, ParmVarDecl *Param,
6257
0
                                        Expr *Init) {
6258
0
  assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
6259
6260
0
  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6261
6262
0
  std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6263
0
      InitializationContext =
6264
0
          OutermostDeclarationWithDelayedImmediateInvocations();
6265
0
  if (!InitializationContext.has_value())
6266
0
    InitializationContext.emplace(CallLoc, Param, CurContext);
6267
6268
0
  if (!Init && !Param->hasUnparsedDefaultArg()) {
6269
    // Mark that we are replacing a default argument first.
6270
    // If we are instantiating a template we won't have to
6271
    // retransform immediate calls.
6272
    // C++ [expr.const]p15.1:
6273
    //   An expression or conversion is in an immediate function context if it
6274
    //   is potentially evaluated and [...] its innermost enclosing non-block
6275
    //   scope is a function parameter scope of an immediate function.
6276
0
    EnterExpressionEvaluationContext EvalContext(
6277
0
        *this,
6278
0
        FD->isImmediateFunction()
6279
0
            ? ExpressionEvaluationContext::ImmediateFunctionContext
6280
0
            : ExpressionEvaluationContext::PotentiallyEvaluated,
6281
0
        Param);
6282
6283
0
    if (Param->hasUninstantiatedDefaultArg()) {
6284
0
      if (InstantiateDefaultArgument(CallLoc, FD, Param))
6285
0
        return ExprError();
6286
0
    }
6287
    // CWG2631
6288
    // An immediate invocation that is not evaluated where it appears is
6289
    // evaluated and checked for whether it is a constant expression at the
6290
    // point where the enclosing initializer is used in a function call.
6291
0
    ImmediateCallVisitor V(getASTContext());
6292
0
    if (!NestedDefaultChecking)
6293
0
      V.TraverseDecl(Param);
6294
0
    if (V.HasImmediateCalls) {
6295
0
      ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6296
0
          CallLoc, Param, CurContext};
6297
0
      EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6298
0
      ExprResult Res;
6299
0
      runWithSufficientStackSpace(CallLoc, [&] {
6300
0
        Res = Immediate.TransformInitializer(Param->getInit(),
6301
0
                                             /*NotCopy=*/false);
6302
0
      });
6303
0
      if (Res.isInvalid())
6304
0
        return ExprError();
6305
0
      Res = ConvertParamDefaultArgument(Param, Res.get(),
6306
0
                                        Res.get()->getBeginLoc());
6307
0
      if (Res.isInvalid())
6308
0
        return ExprError();
6309
0
      Init = Res.get();
6310
0
    }
6311
0
  }
6312
6313
0
  if (CheckCXXDefaultArgExpr(
6314
0
          CallLoc, FD, Param, Init,
6315
0
          /*SkipImmediateInvocations=*/NestedDefaultChecking))
6316
0
    return ExprError();
6317
6318
0
  return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6319
0
                                   Init, InitializationContext->Context);
6320
0
}
6321
6322
0
ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6323
0
  assert(Field->hasInClassInitializer());
6324
6325
  // If we might have already tried and failed to instantiate, don't try again.
6326
0
  if (Field->isInvalidDecl())
6327
0
    return ExprError();
6328
6329
0
  CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6330
6331
0
  auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6332
6333
0
  std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6334
0
      InitializationContext =
6335
0
          OutermostDeclarationWithDelayedImmediateInvocations();
6336
0
  if (!InitializationContext.has_value())
6337
0
    InitializationContext.emplace(Loc, Field, CurContext);
6338
6339
0
  Expr *Init = nullptr;
6340
6341
0
  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6342
6343
0
  EnterExpressionEvaluationContext EvalContext(
6344
0
      *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6345
6346
0
  if (!Field->getInClassInitializer()) {
6347
    // Maybe we haven't instantiated the in-class initializer. Go check the
6348
    // pattern FieldDecl to see if it has one.
6349
0
    if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6350
0
      CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6351
0
      DeclContext::lookup_result Lookup =
6352
0
          ClassPattern->lookup(Field->getDeclName());
6353
6354
0
      FieldDecl *Pattern = nullptr;
6355
0
      for (auto *L : Lookup) {
6356
0
        if ((Pattern = dyn_cast<FieldDecl>(L)))
6357
0
          break;
6358
0
      }
6359
0
      assert(Pattern && "We must have set the Pattern!");
6360
0
      if (!Pattern->hasInClassInitializer() ||
6361
0
          InstantiateInClassInitializer(Loc, Field, Pattern,
6362
0
                                        getTemplateInstantiationArgs(Field))) {
6363
0
        Field->setInvalidDecl();
6364
0
        return ExprError();
6365
0
      }
6366
0
    }
6367
0
  }
6368
6369
  // CWG2631
6370
  // An immediate invocation that is not evaluated where it appears is
6371
  // evaluated and checked for whether it is a constant expression at the
6372
  // point where the enclosing initializer is used in a [...] a constructor
6373
  // definition, or an aggregate initialization.
6374
0
  ImmediateCallVisitor V(getASTContext());
6375
0
  if (!NestedDefaultChecking)
6376
0
    V.TraverseDecl(Field);
6377
0
  if (V.HasImmediateCalls) {
6378
0
    ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6379
0
                                                                   CurContext};
6380
0
    ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6381
0
        NestedDefaultChecking;
6382
6383
0
    EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6384
0
    ExprResult Res;
6385
0
    runWithSufficientStackSpace(Loc, [&] {
6386
0
      Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6387
0
                                           /*CXXDirectInit=*/false);
6388
0
    });
6389
0
    if (!Res.isInvalid())
6390
0
      Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6391
0
    if (Res.isInvalid()) {
6392
0
      Field->setInvalidDecl();
6393
0
      return ExprError();
6394
0
    }
6395
0
    Init = Res.get();
6396
0
  }
6397
6398
0
  if (Field->getInClassInitializer()) {
6399
0
    Expr *E = Init ? Init : Field->getInClassInitializer();
6400
0
    if (!NestedDefaultChecking)
6401
0
      runWithSufficientStackSpace(Loc, [&] {
6402
0
        MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6403
0
      });
6404
    // C++11 [class.base.init]p7:
6405
    //   The initialization of each base and member constitutes a
6406
    //   full-expression.
6407
0
    ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6408
0
    if (Res.isInvalid()) {
6409
0
      Field->setInvalidDecl();
6410
0
      return ExprError();
6411
0
    }
6412
0
    Init = Res.get();
6413
6414
0
    return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6415
0
                                      Field, InitializationContext->Context,
6416
0
                                      Init);
6417
0
  }
6418
6419
  // DR1351:
6420
  //   If the brace-or-equal-initializer of a non-static data member
6421
  //   invokes a defaulted default constructor of its class or of an
6422
  //   enclosing class in a potentially evaluated subexpression, the
6423
  //   program is ill-formed.
6424
  //
6425
  // This resolution is unworkable: the exception specification of the
6426
  // default constructor can be needed in an unevaluated context, in
6427
  // particular, in the operand of a noexcept-expression, and we can be
6428
  // unable to compute an exception specification for an enclosed class.
6429
  //
6430
  // Any attempt to resolve the exception specification of a defaulted default
6431
  // constructor before the initializer is lexically complete will ultimately
6432
  // come here at which point we can diagnose it.
6433
0
  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6434
0
  Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6435
0
      << OutermostClass << Field;
6436
0
  Diag(Field->getEndLoc(),
6437
0
       diag::note_default_member_initializer_not_yet_parsed);
6438
  // Recover by marking the field invalid, unless we're in a SFINAE context.
6439
0
  if (!isSFINAEContext())
6440
0
    Field->setInvalidDecl();
6441
0
  return ExprError();
6442
0
}
6443
6444
Sema::VariadicCallType
6445
Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6446
0
                          Expr *Fn) {
6447
0
  if (Proto && Proto->isVariadic()) {
6448
0
    if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6449
0
      return VariadicConstructor;
6450
0
    else if (Fn && Fn->getType()->isBlockPointerType())
6451
0
      return VariadicBlock;
6452
0
    else if (FDecl) {
6453
0
      if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6454
0
        if (Method->isInstance())
6455
0
          return VariadicMethod;
6456
0
    } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6457
0
      return VariadicMethod;
6458
0
    return VariadicFunction;
6459
0
  }
6460
0
  return VariadicDoesNotApply;
6461
0
}
6462
6463
namespace {
6464
class FunctionCallCCC final : public FunctionCallFilterCCC {
6465
public:
6466
  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6467
                  unsigned NumArgs, MemberExpr *ME)
6468
      : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6469
0
        FunctionName(FuncName) {}
6470
6471
0
  bool ValidateCandidate(const TypoCorrection &candidate) override {
6472
0
    if (!candidate.getCorrectionSpecifier() ||
6473
0
        candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6474
0
      return false;
6475
0
    }
6476
6477
0
    return FunctionCallFilterCCC::ValidateCandidate(candidate);
6478
0
  }
6479
6480
0
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
6481
0
    return std::make_unique<FunctionCallCCC>(*this);
6482
0
  }
6483
6484
private:
6485
  const IdentifierInfo *const FunctionName;
6486
};
6487
}
6488
6489
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6490
                                               FunctionDecl *FDecl,
6491
0
                                               ArrayRef<Expr *> Args) {
6492
0
  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6493
0
  DeclarationName FuncName = FDecl->getDeclName();
6494
0
  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6495
6496
0
  FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6497
0
  if (TypoCorrection Corrected = S.CorrectTypo(
6498
0
          DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6499
0
          S.getScopeForContext(S.CurContext), nullptr, CCC,
6500
0
          Sema::CTK_ErrorRecovery)) {
6501
0
    if (NamedDecl *ND = Corrected.getFoundDecl()) {
6502
0
      if (Corrected.isOverloaded()) {
6503
0
        OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6504
0
        OverloadCandidateSet::iterator Best;
6505
0
        for (NamedDecl *CD : Corrected) {
6506
0
          if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6507
0
            S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6508
0
                                   OCS);
6509
0
        }
6510
0
        switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6511
0
        case OR_Success:
6512
0
          ND = Best->FoundDecl;
6513
0
          Corrected.setCorrectionDecl(ND);
6514
0
          break;
6515
0
        default:
6516
0
          break;
6517
0
        }
6518
0
      }
6519
0
      ND = ND->getUnderlyingDecl();
6520
0
      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6521
0
        return Corrected;
6522
0
    }
6523
0
  }
6524
0
  return TypoCorrection();
6525
0
}
6526
6527
/// ConvertArgumentsForCall - Converts the arguments specified in
6528
/// Args/NumArgs to the parameter types of the function FDecl with
6529
/// function prototype Proto. Call is the call expression itself, and
6530
/// Fn is the function expression. For a C++ member function, this
6531
/// routine does not attempt to convert the object argument. Returns
6532
/// true if the call is ill-formed.
6533
bool
6534
Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6535
                              FunctionDecl *FDecl,
6536
                              const FunctionProtoType *Proto,
6537
                              ArrayRef<Expr *> Args,
6538
                              SourceLocation RParenLoc,
6539
0
                              bool IsExecConfig) {
6540
  // Bail out early if calling a builtin with custom typechecking.
6541
0
  if (FDecl)
6542
0
    if (unsigned ID = FDecl->getBuiltinID())
6543
0
      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6544
0
        return false;
6545
6546
  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6547
  // assignment, to the types of the corresponding parameter, ...
6548
0
  bool HasExplicitObjectParameter =
6549
0
      FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6550
0
  unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6551
0
  unsigned NumParams = Proto->getNumParams();
6552
0
  bool Invalid = false;
6553
0
  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6554
0
  unsigned FnKind = Fn->getType()->isBlockPointerType()
6555
0
                       ? 1 /* block */
6556
0
                       : (IsExecConfig ? 3 /* kernel function (exec config) */
6557
0
                                       : 0 /* function */);
6558
6559
  // If too few arguments are available (and we don't have default
6560
  // arguments for the remaining parameters), don't make the call.
6561
0
  if (Args.size() < NumParams) {
6562
0
    if (Args.size() < MinArgs) {
6563
0
      TypoCorrection TC;
6564
0
      if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6565
0
        unsigned diag_id =
6566
0
            MinArgs == NumParams && !Proto->isVariadic()
6567
0
                ? diag::err_typecheck_call_too_few_args_suggest
6568
0
                : diag::err_typecheck_call_too_few_args_at_least_suggest;
6569
0
        diagnoseTypo(
6570
0
            TC, PDiag(diag_id)
6571
0
                    << FnKind << MinArgs - ExplicitObjectParameterOffset
6572
0
                    << static_cast<unsigned>(Args.size()) -
6573
0
                           ExplicitObjectParameterOffset
6574
0
                    << HasExplicitObjectParameter << TC.getCorrectionRange());
6575
0
      } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6576
0
                 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6577
0
                     ->getDeclName())
6578
0
        Diag(RParenLoc,
6579
0
             MinArgs == NumParams && !Proto->isVariadic()
6580
0
                 ? diag::err_typecheck_call_too_few_args_one
6581
0
                 : diag::err_typecheck_call_too_few_args_at_least_one)
6582
0
            << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6583
0
            << HasExplicitObjectParameter << Fn->getSourceRange();
6584
0
      else
6585
0
        Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6586
0
                            ? diag::err_typecheck_call_too_few_args
6587
0
                            : diag::err_typecheck_call_too_few_args_at_least)
6588
0
            << FnKind << MinArgs - ExplicitObjectParameterOffset
6589
0
            << static_cast<unsigned>(Args.size()) -
6590
0
                   ExplicitObjectParameterOffset
6591
0
            << HasExplicitObjectParameter << Fn->getSourceRange();
6592
6593
      // Emit the location of the prototype.
6594
0
      if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6595
0
        Diag(FDecl->getLocation(), diag::note_callee_decl)
6596
0
            << FDecl << FDecl->getParametersSourceRange();
6597
6598
0
      return true;
6599
0
    }
6600
    // We reserve space for the default arguments when we create
6601
    // the call expression, before calling ConvertArgumentsForCall.
6602
0
    assert((Call->getNumArgs() == NumParams) &&
6603
0
           "We should have reserved space for the default arguments before!");
6604
0
  }
6605
6606
  // If too many are passed and not variadic, error on the extras and drop
6607
  // them.
6608
0
  if (Args.size() > NumParams) {
6609
0
    if (!Proto->isVariadic()) {
6610
0
      TypoCorrection TC;
6611
0
      if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6612
0
        unsigned diag_id =
6613
0
            MinArgs == NumParams && !Proto->isVariadic()
6614
0
                ? diag::err_typecheck_call_too_many_args_suggest
6615
0
                : diag::err_typecheck_call_too_many_args_at_most_suggest;
6616
0
        diagnoseTypo(
6617
0
            TC, PDiag(diag_id)
6618
0
                    << FnKind << NumParams - ExplicitObjectParameterOffset
6619
0
                    << static_cast<unsigned>(Args.size()) -
6620
0
                           ExplicitObjectParameterOffset
6621
0
                    << HasExplicitObjectParameter << TC.getCorrectionRange());
6622
0
      } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6623
0
                 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6624
0
                     ->getDeclName())
6625
0
        Diag(Args[NumParams]->getBeginLoc(),
6626
0
             MinArgs == NumParams
6627
0
                 ? diag::err_typecheck_call_too_many_args_one
6628
0
                 : diag::err_typecheck_call_too_many_args_at_most_one)
6629
0
            << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6630
0
            << static_cast<unsigned>(Args.size()) -
6631
0
                   ExplicitObjectParameterOffset
6632
0
            << HasExplicitObjectParameter << Fn->getSourceRange()
6633
0
            << SourceRange(Args[NumParams]->getBeginLoc(),
6634
0
                           Args.back()->getEndLoc());
6635
0
      else
6636
0
        Diag(Args[NumParams]->getBeginLoc(),
6637
0
             MinArgs == NumParams
6638
0
                 ? diag::err_typecheck_call_too_many_args
6639
0
                 : diag::err_typecheck_call_too_many_args_at_most)
6640
0
            << FnKind << NumParams - ExplicitObjectParameterOffset
6641
0
            << static_cast<unsigned>(Args.size()) -
6642
0
                   ExplicitObjectParameterOffset
6643
0
            << HasExplicitObjectParameter << Fn->getSourceRange()
6644
0
            << SourceRange(Args[NumParams]->getBeginLoc(),
6645
0
                           Args.back()->getEndLoc());
6646
6647
      // Emit the location of the prototype.
6648
0
      if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6649
0
        Diag(FDecl->getLocation(), diag::note_callee_decl)
6650
0
            << FDecl << FDecl->getParametersSourceRange();
6651
6652
      // This deletes the extra arguments.
6653
0
      Call->shrinkNumArgs(NumParams);
6654
0
      return true;
6655
0
    }
6656
0
  }
6657
0
  SmallVector<Expr *, 8> AllArgs;
6658
0
  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6659
6660
0
  Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6661
0
                                   AllArgs, CallType);
6662
0
  if (Invalid)
6663
0
    return true;
6664
0
  unsigned TotalNumArgs = AllArgs.size();
6665
0
  for (unsigned i = 0; i < TotalNumArgs; ++i)
6666
0
    Call->setArg(i, AllArgs[i]);
6667
6668
0
  Call->computeDependence();
6669
0
  return false;
6670
0
}
6671
6672
bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6673
                                  const FunctionProtoType *Proto,
6674
                                  unsigned FirstParam, ArrayRef<Expr *> Args,
6675
                                  SmallVectorImpl<Expr *> &AllArgs,
6676
                                  VariadicCallType CallType, bool AllowExplicit,
6677
0
                                  bool IsListInitialization) {
6678
0
  unsigned NumParams = Proto->getNumParams();
6679
0
  bool Invalid = false;
6680
0
  size_t ArgIx = 0;
6681
  // Continue to check argument types (even if we have too few/many args).
6682
0
  for (unsigned i = FirstParam; i < NumParams; i++) {
6683
0
    QualType ProtoArgType = Proto->getParamType(i);
6684
6685
0
    Expr *Arg;
6686
0
    ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6687
0
    if (ArgIx < Args.size()) {
6688
0
      Arg = Args[ArgIx++];
6689
6690
0
      if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6691
0
                              diag::err_call_incomplete_argument, Arg))
6692
0
        return true;
6693
6694
      // Strip the unbridged-cast placeholder expression off, if applicable.
6695
0
      bool CFAudited = false;
6696
0
      if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6697
0
          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6698
0
          (!Param || !Param->hasAttr<CFConsumedAttr>()))
6699
0
        Arg = stripARCUnbridgedCast(Arg);
6700
0
      else if (getLangOpts().ObjCAutoRefCount &&
6701
0
               FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6702
0
               (!Param || !Param->hasAttr<CFConsumedAttr>()))
6703
0
        CFAudited = true;
6704
6705
0
      if (Proto->getExtParameterInfo(i).isNoEscape() &&
6706
0
          ProtoArgType->isBlockPointerType())
6707
0
        if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6708
0
          BE->getBlockDecl()->setDoesNotEscape();
6709
6710
0
      InitializedEntity Entity =
6711
0
          Param ? InitializedEntity::InitializeParameter(Context, Param,
6712
0
                                                         ProtoArgType)
6713
0
                : InitializedEntity::InitializeParameter(
6714
0
                      Context, ProtoArgType, Proto->isParamConsumed(i));
6715
6716
      // Remember that parameter belongs to a CF audited API.
6717
0
      if (CFAudited)
6718
0
        Entity.setParameterCFAudited();
6719
6720
0
      ExprResult ArgE = PerformCopyInitialization(
6721
0
          Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6722
0
      if (ArgE.isInvalid())
6723
0
        return true;
6724
6725
0
      Arg = ArgE.getAs<Expr>();
6726
0
    } else {
6727
0
      assert(Param && "can't use default arguments without a known callee");
6728
6729
0
      ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6730
0
      if (ArgExpr.isInvalid())
6731
0
        return true;
6732
6733
0
      Arg = ArgExpr.getAs<Expr>();
6734
0
    }
6735
6736
    // Check for array bounds violations for each argument to the call. This
6737
    // check only triggers warnings when the argument isn't a more complex Expr
6738
    // with its own checking, such as a BinaryOperator.
6739
0
    CheckArrayAccess(Arg);
6740
6741
    // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6742
0
    CheckStaticArrayArgument(CallLoc, Param, Arg);
6743
6744
0
    AllArgs.push_back(Arg);
6745
0
  }
6746
6747
  // If this is a variadic call, handle args passed through "...".
6748
0
  if (CallType != VariadicDoesNotApply) {
6749
    // Assume that extern "C" functions with variadic arguments that
6750
    // return __unknown_anytype aren't *really* variadic.
6751
0
    if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6752
0
        FDecl->isExternC()) {
6753
0
      for (Expr *A : Args.slice(ArgIx)) {
6754
0
        QualType paramType; // ignored
6755
0
        ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6756
0
        Invalid |= arg.isInvalid();
6757
0
        AllArgs.push_back(arg.get());
6758
0
      }
6759
6760
    // Otherwise do argument promotion, (C99 6.5.2.2p7).
6761
0
    } else {
6762
0
      for (Expr *A : Args.slice(ArgIx)) {
6763
0
        ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6764
0
        Invalid |= Arg.isInvalid();
6765
0
        AllArgs.push_back(Arg.get());
6766
0
      }
6767
0
    }
6768
6769
    // Check for array bounds violations.
6770
0
    for (Expr *A : Args.slice(ArgIx))
6771
0
      CheckArrayAccess(A);
6772
0
  }
6773
0
  return Invalid;
6774
0
}
6775
6776
0
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6777
0
  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6778
0
  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6779
0
    TL = DTL.getOriginalLoc();
6780
0
  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6781
0
    S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6782
0
      << ATL.getLocalSourceRange();
6783
0
}
6784
6785
/// CheckStaticArrayArgument - If the given argument corresponds to a static
6786
/// array parameter, check that it is non-null, and that if it is formed by
6787
/// array-to-pointer decay, the underlying array is sufficiently large.
6788
///
6789
/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6790
/// array type derivation, then for each call to the function, the value of the
6791
/// corresponding actual argument shall provide access to the first element of
6792
/// an array with at least as many elements as specified by the size expression.
6793
void
6794
Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6795
                               ParmVarDecl *Param,
6796
0
                               const Expr *ArgExpr) {
6797
  // Static array parameters are not supported in C++.
6798
0
  if (!Param || getLangOpts().CPlusPlus)
6799
0
    return;
6800
6801
0
  QualType OrigTy = Param->getOriginalType();
6802
6803
0
  const ArrayType *AT = Context.getAsArrayType(OrigTy);
6804
0
  if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6805
0
    return;
6806
6807
0
  if (ArgExpr->isNullPointerConstant(Context,
6808
0
                                     Expr::NPC_NeverValueDependent)) {
6809
0
    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6810
0
    DiagnoseCalleeStaticArrayParam(*this, Param);
6811
0
    return;
6812
0
  }
6813
6814
0
  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6815
0
  if (!CAT)
6816
0
    return;
6817
6818
0
  const ConstantArrayType *ArgCAT =
6819
0
    Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6820
0
  if (!ArgCAT)
6821
0
    return;
6822
6823
0
  if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6824
0
                                             ArgCAT->getElementType())) {
6825
0
    if (ArgCAT->getSize().ult(CAT->getSize())) {
6826
0
      Diag(CallLoc, diag::warn_static_array_too_small)
6827
0
          << ArgExpr->getSourceRange()
6828
0
          << (unsigned)ArgCAT->getSize().getZExtValue()
6829
0
          << (unsigned)CAT->getSize().getZExtValue() << 0;
6830
0
      DiagnoseCalleeStaticArrayParam(*this, Param);
6831
0
    }
6832
0
    return;
6833
0
  }
6834
6835
0
  std::optional<CharUnits> ArgSize =
6836
0
      getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6837
0
  std::optional<CharUnits> ParmSize =
6838
0
      getASTContext().getTypeSizeInCharsIfKnown(CAT);
6839
0
  if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6840
0
    Diag(CallLoc, diag::warn_static_array_too_small)
6841
0
        << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6842
0
        << (unsigned)ParmSize->getQuantity() << 1;
6843
0
    DiagnoseCalleeStaticArrayParam(*this, Param);
6844
0
  }
6845
0
}
6846
6847
/// Given a function expression of unknown-any type, try to rebuild it
6848
/// to have a function type.
6849
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6850
6851
/// Is the given type a placeholder that we need to lower out
6852
/// immediately during argument processing?
6853
0
static bool isPlaceholderToRemoveAsArg(QualType type) {
6854
  // Placeholders are never sugared.
6855
0
  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6856
0
  if (!placeholder) return false;
6857
6858
0
  switch (placeholder->getKind()) {
6859
  // Ignore all the non-placeholder types.
6860
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6861
0
  case BuiltinType::Id:
6862
0
#include "clang/Basic/OpenCLImageTypes.def"
6863
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6864
0
  case BuiltinType::Id:
6865
0
#include "clang/Basic/OpenCLExtensionTypes.def"
6866
  // In practice we'll never use this, since all SVE types are sugared
6867
  // via TypedefTypes rather than exposed directly as BuiltinTypes.
6868
0
#define SVE_TYPE(Name, Id, SingletonId) \
6869
0
  case BuiltinType::Id:
6870
0
#include "clang/Basic/AArch64SVEACLETypes.def"
6871
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
6872
0
  case BuiltinType::Id:
6873
0
#include "clang/Basic/PPCTypes.def"
6874
0
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6875
0
#include "clang/Basic/RISCVVTypes.def"
6876
0
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6877
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
6878
0
#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6879
0
#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6880
0
#include "clang/AST/BuiltinTypes.def"
6881
0
    return false;
6882
6883
  // We cannot lower out overload sets; they might validly be resolved
6884
  // by the call machinery.
6885
0
  case BuiltinType::Overload:
6886
0
    return false;
6887
6888
  // Unbridged casts in ARC can be handled in some call positions and
6889
  // should be left in place.
6890
0
  case BuiltinType::ARCUnbridgedCast:
6891
0
    return false;
6892
6893
  // Pseudo-objects should be converted as soon as possible.
6894
0
  case BuiltinType::PseudoObject:
6895
0
    return true;
6896
6897
  // The debugger mode could theoretically but currently does not try
6898
  // to resolve unknown-typed arguments based on known parameter types.
6899
0
  case BuiltinType::UnknownAny:
6900
0
    return true;
6901
6902
  // These are always invalid as call arguments and should be reported.
6903
0
  case BuiltinType::BoundMember:
6904
0
  case BuiltinType::BuiltinFn:
6905
0
  case BuiltinType::IncompleteMatrixIdx:
6906
0
  case BuiltinType::OMPArraySection:
6907
0
  case BuiltinType::OMPArrayShaping:
6908
0
  case BuiltinType::OMPIterator:
6909
0
    return true;
6910
6911
0
  }
6912
0
  llvm_unreachable("bad builtin type kind");
6913
0
}
6914
6915
/// Check an argument list for placeholders that we won't try to
6916
/// handle later.
6917
0
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6918
  // Apply this processing to all the arguments at once instead of
6919
  // dying at the first failure.
6920
0
  bool hasInvalid = false;
6921
0
  for (size_t i = 0, e = args.size(); i != e; i++) {
6922
0
    if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6923
0
      ExprResult result = S.CheckPlaceholderExpr(args[i]);
6924
0
      if (result.isInvalid()) hasInvalid = true;
6925
0
      else args[i] = result.get();
6926
0
    }
6927
0
  }
6928
0
  return hasInvalid;
6929
0
}
6930
6931
/// If a builtin function has a pointer argument with no explicit address
6932
/// space, then it should be able to accept a pointer to any address
6933
/// space as input.  In order to do this, we need to replace the
6934
/// standard builtin declaration with one that uses the same address space
6935
/// as the call.
6936
///
6937
/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6938
///                  it does not contain any pointer arguments without
6939
///                  an address space qualifer.  Otherwise the rewritten
6940
///                  FunctionDecl is returned.
6941
/// TODO: Handle pointer return types.
6942
static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6943
                                                FunctionDecl *FDecl,
6944
0
                                                MultiExprArg ArgExprs) {
6945
6946
0
  QualType DeclType = FDecl->getType();
6947
0
  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6948
6949
0
  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6950
0
      ArgExprs.size() < FT->getNumParams())
6951
0
    return nullptr;
6952
6953
0
  bool NeedsNewDecl = false;
6954
0
  unsigned i = 0;
6955
0
  SmallVector<QualType, 8> OverloadParams;
6956
6957
0
  for (QualType ParamType : FT->param_types()) {
6958
6959
    // Convert array arguments to pointer to simplify type lookup.
6960
0
    ExprResult ArgRes =
6961
0
        Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6962
0
    if (ArgRes.isInvalid())
6963
0
      return nullptr;
6964
0
    Expr *Arg = ArgRes.get();
6965
0
    QualType ArgType = Arg->getType();
6966
0
    if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6967
0
        !ArgType->isPointerType() ||
6968
0
        !ArgType->getPointeeType().hasAddressSpace() ||
6969
0
        isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6970
0
      OverloadParams.push_back(ParamType);
6971
0
      continue;
6972
0
    }
6973
6974
0
    QualType PointeeType = ParamType->getPointeeType();
6975
0
    if (PointeeType.hasAddressSpace())
6976
0
      continue;
6977
6978
0
    NeedsNewDecl = true;
6979
0
    LangAS AS = ArgType->getPointeeType().getAddressSpace();
6980
6981
0
    PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6982
0
    OverloadParams.push_back(Context.getPointerType(PointeeType));
6983
0
  }
6984
6985
0
  if (!NeedsNewDecl)
6986
0
    return nullptr;
6987
6988
0
  FunctionProtoType::ExtProtoInfo EPI;
6989
0
  EPI.Variadic = FT->isVariadic();
6990
0
  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6991
0
                                                OverloadParams, EPI);
6992
0
  DeclContext *Parent = FDecl->getParent();
6993
0
  FunctionDecl *OverloadDecl = FunctionDecl::Create(
6994
0
      Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6995
0
      FDecl->getIdentifier(), OverloadTy,
6996
0
      /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6997
0
      false,
6998
0
      /*hasPrototype=*/true);
6999
0
  SmallVector<ParmVarDecl*, 16> Params;
7000
0
  FT = cast<FunctionProtoType>(OverloadTy);
7001
0
  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
7002
0
    QualType ParamType = FT->getParamType(i);
7003
0
    ParmVarDecl *Parm =
7004
0
        ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
7005
0
                                SourceLocation(), nullptr, ParamType,
7006
0
                                /*TInfo=*/nullptr, SC_None, nullptr);
7007
0
    Parm->setScopeInfo(0, i);
7008
0
    Params.push_back(Parm);
7009
0
  }
7010
0
  OverloadDecl->setParams(Params);
7011
0
  Sema->mergeDeclAttributes(OverloadDecl, FDecl);
7012
0
  return OverloadDecl;
7013
0
}
7014
7015
static void checkDirectCallValidity(Sema &S, const Expr *Fn,
7016
                                    FunctionDecl *Callee,
7017
0
                                    MultiExprArg ArgExprs) {
7018
  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
7019
  // similar attributes) really don't like it when functions are called with an
7020
  // invalid number of args.
7021
0
  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
7022
0
                         /*PartialOverloading=*/false) &&
7023
0
      !Callee->isVariadic())
7024
0
    return;
7025
0
  if (Callee->getMinRequiredArguments() > ArgExprs.size())
7026
0
    return;
7027
7028
0
  if (const EnableIfAttr *Attr =
7029
0
          S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
7030
0
    S.Diag(Fn->getBeginLoc(),
7031
0
           isa<CXXMethodDecl>(Callee)
7032
0
               ? diag::err_ovl_no_viable_member_function_in_call
7033
0
               : diag::err_ovl_no_viable_function_in_call)
7034
0
        << Callee << Callee->getSourceRange();
7035
0
    S.Diag(Callee->getLocation(),
7036
0
           diag::note_ovl_candidate_disabled_by_function_cond_attr)
7037
0
        << Attr->getCond()->getSourceRange() << Attr->getMessage();
7038
0
    return;
7039
0
  }
7040
0
}
7041
7042
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
7043
0
    const UnresolvedMemberExpr *const UME, Sema &S) {
7044
7045
0
  const auto GetFunctionLevelDCIfCXXClass =
7046
0
      [](Sema &S) -> const CXXRecordDecl * {
7047
0
    const DeclContext *const DC = S.getFunctionLevelDeclContext();
7048
0
    if (!DC || !DC->getParent())
7049
0
      return nullptr;
7050
7051
    // If the call to some member function was made from within a member
7052
    // function body 'M' return return 'M's parent.
7053
0
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
7054
0
      return MD->getParent()->getCanonicalDecl();
7055
    // else the call was made from within a default member initializer of a
7056
    // class, so return the class.
7057
0
    if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
7058
0
      return RD->getCanonicalDecl();
7059
0
    return nullptr;
7060
0
  };
7061
  // If our DeclContext is neither a member function nor a class (in the
7062
  // case of a lambda in a default member initializer), we can't have an
7063
  // enclosing 'this'.
7064
7065
0
  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
7066
0
  if (!CurParentClass)
7067
0
    return false;
7068
7069
  // The naming class for implicit member functions call is the class in which
7070
  // name lookup starts.
7071
0
  const CXXRecordDecl *const NamingClass =
7072
0
      UME->getNamingClass()->getCanonicalDecl();
7073
0
  assert(NamingClass && "Must have naming class even for implicit access");
7074
7075
  // If the unresolved member functions were found in a 'naming class' that is
7076
  // related (either the same or derived from) to the class that contains the
7077
  // member function that itself contained the implicit member access.
7078
7079
0
  return CurParentClass == NamingClass ||
7080
0
         CurParentClass->isDerivedFrom(NamingClass);
7081
0
}
7082
7083
static void
7084
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7085
0
    Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
7086
7087
0
  if (!UME)
7088
0
    return;
7089
7090
0
  LambdaScopeInfo *const CurLSI = S.getCurLambda();
7091
  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
7092
  // already been captured, or if this is an implicit member function call (if
7093
  // it isn't, an attempt to capture 'this' should already have been made).
7094
0
  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
7095
0
      !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
7096
0
    return;
7097
7098
  // Check if the naming class in which the unresolved members were found is
7099
  // related (same as or is a base of) to the enclosing class.
7100
7101
0
  if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
7102
0
    return;
7103
7104
7105
0
  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
7106
  // If the enclosing function is not dependent, then this lambda is
7107
  // capture ready, so if we can capture this, do so.
7108
0
  if (!EnclosingFunctionCtx->isDependentContext()) {
7109
    // If the current lambda and all enclosing lambdas can capture 'this' -
7110
    // then go ahead and capture 'this' (since our unresolved overload set
7111
    // contains at least one non-static member function).
7112
0
    if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
7113
0
      S.CheckCXXThisCapture(CallLoc);
7114
0
  } else if (S.CurContext->isDependentContext()) {
7115
    // ... since this is an implicit member reference, that might potentially
7116
    // involve a 'this' capture, mark 'this' for potential capture in
7117
    // enclosing lambdas.
7118
0
    if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
7119
0
      CurLSI->addPotentialThisCapture(CallLoc);
7120
0
  }
7121
0
}
7122
7123
// Once a call is fully resolved, warn for unqualified calls to specific
7124
// C++ standard functions, like move and forward.
7125
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
7126
0
                                                    const CallExpr *Call) {
7127
  // We are only checking unary move and forward so exit early here.
7128
0
  if (Call->getNumArgs() != 1)
7129
0
    return;
7130
7131
0
  const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
7132
0
  if (!E || isa<UnresolvedLookupExpr>(E))
7133
0
    return;
7134
0
  const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
7135
0
  if (!DRE || !DRE->getLocation().isValid())
7136
0
    return;
7137
7138
0
  if (DRE->getQualifier())
7139
0
    return;
7140
7141
0
  const FunctionDecl *FD = Call->getDirectCallee();
7142
0
  if (!FD)
7143
0
    return;
7144
7145
  // Only warn for some functions deemed more frequent or problematic.
7146
0
  unsigned BuiltinID = FD->getBuiltinID();
7147
0
  if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
7148
0
    return;
7149
7150
0
  S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
7151
0
      << FD->getQualifiedNameAsString()
7152
0
      << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
7153
0
}
7154
7155
ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7156
                               MultiExprArg ArgExprs, SourceLocation RParenLoc,
7157
0
                               Expr *ExecConfig) {
7158
0
  ExprResult Call =
7159
0
      BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7160
0
                    /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7161
0
  if (Call.isInvalid())
7162
0
    return Call;
7163
7164
  // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7165
  // language modes.
7166
0
  if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
7167
0
      ULE && ULE->hasExplicitTemplateArgs() &&
7168
0
      ULE->decls_begin() == ULE->decls_end()) {
7169
0
    Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
7170
0
                               ? diag::warn_cxx17_compat_adl_only_template_id
7171
0
                               : diag::ext_adl_only_template_id)
7172
0
        << ULE->getName();
7173
0
  }
7174
7175
0
  if (LangOpts.OpenMP)
7176
0
    Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
7177
0
                           ExecConfig);
7178
0
  if (LangOpts.CPlusPlus) {
7179
0
    if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
7180
0
      DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
7181
0
  }
7182
0
  return Call;
7183
0
}
7184
7185
/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7186
/// This provides the location of the left/right parens and a list of comma
7187
/// locations.
7188
ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7189
                               MultiExprArg ArgExprs, SourceLocation RParenLoc,
7190
                               Expr *ExecConfig, bool IsExecConfig,
7191
0
                               bool AllowRecovery) {
7192
  // Since this might be a postfix expression, get rid of ParenListExprs.
7193
0
  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
7194
0
  if (Result.isInvalid()) return ExprError();
7195
0
  Fn = Result.get();
7196
7197
0
  if (checkArgsForPlaceholders(*this, ArgExprs))
7198
0
    return ExprError();
7199
7200
0
  if (getLangOpts().CPlusPlus) {
7201
    // If this is a pseudo-destructor expression, build the call immediately.
7202
0
    if (isa<CXXPseudoDestructorExpr>(Fn)) {
7203
0
      if (!ArgExprs.empty()) {
7204
        // Pseudo-destructor calls should not have any arguments.
7205
0
        Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
7206
0
            << FixItHint::CreateRemoval(
7207
0
                   SourceRange(ArgExprs.front()->getBeginLoc(),
7208
0
                               ArgExprs.back()->getEndLoc()));
7209
0
      }
7210
7211
0
      return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
7212
0
                              VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7213
0
    }
7214
0
    if (Fn->getType() == Context.PseudoObjectTy) {
7215
0
      ExprResult result = CheckPlaceholderExpr(Fn);
7216
0
      if (result.isInvalid()) return ExprError();
7217
0
      Fn = result.get();
7218
0
    }
7219
7220
    // Determine whether this is a dependent call inside a C++ template,
7221
    // in which case we won't do any semantic analysis now.
7222
0
    if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
7223
0
      if (ExecConfig) {
7224
0
        return CUDAKernelCallExpr::Create(Context, Fn,
7225
0
                                          cast<CallExpr>(ExecConfig), ArgExprs,
7226
0
                                          Context.DependentTy, VK_PRValue,
7227
0
                                          RParenLoc, CurFPFeatureOverrides());
7228
0
      } else {
7229
7230
0
        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7231
0
            *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
7232
0
            Fn->getBeginLoc());
7233
7234
0
        return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7235
0
                                VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7236
0
      }
7237
0
    }
7238
7239
    // Determine whether this is a call to an object (C++ [over.call.object]).
7240
0
    if (Fn->getType()->isRecordType())
7241
0
      return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7242
0
                                          RParenLoc);
7243
7244
0
    if (Fn->getType() == Context.UnknownAnyTy) {
7245
0
      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7246
0
      if (result.isInvalid()) return ExprError();
7247
0
      Fn = result.get();
7248
0
    }
7249
7250
0
    if (Fn->getType() == Context.BoundMemberTy) {
7251
0
      return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7252
0
                                       RParenLoc, ExecConfig, IsExecConfig,
7253
0
                                       AllowRecovery);
7254
0
    }
7255
0
  }
7256
7257
  // Check for overloaded calls.  This can happen even in C due to extensions.
7258
0
  if (Fn->getType() == Context.OverloadTy) {
7259
0
    OverloadExpr::FindResult find = OverloadExpr::find(Fn);
7260
7261
    // We aren't supposed to apply this logic if there's an '&' involved.
7262
0
    if (!find.HasFormOfMemberPointer) {
7263
0
      if (Expr::hasAnyTypeDependentArguments(ArgExprs))
7264
0
        return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7265
0
                                VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7266
0
      OverloadExpr *ovl = find.Expression;
7267
0
      if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7268
0
        return BuildOverloadedCallExpr(
7269
0
            Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7270
0
            /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7271
0
      return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7272
0
                                       RParenLoc, ExecConfig, IsExecConfig,
7273
0
                                       AllowRecovery);
7274
0
    }
7275
0
  }
7276
7277
  // If we're directly calling a function, get the appropriate declaration.
7278
0
  if (Fn->getType() == Context.UnknownAnyTy) {
7279
0
    ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7280
0
    if (result.isInvalid()) return ExprError();
7281
0
    Fn = result.get();
7282
0
  }
7283
7284
0
  Expr *NakedFn = Fn->IgnoreParens();
7285
7286
0
  bool CallingNDeclIndirectly = false;
7287
0
  NamedDecl *NDecl = nullptr;
7288
0
  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7289
0
    if (UnOp->getOpcode() == UO_AddrOf) {
7290
0
      CallingNDeclIndirectly = true;
7291
0
      NakedFn = UnOp->getSubExpr()->IgnoreParens();
7292
0
    }
7293
0
  }
7294
7295
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7296
0
    NDecl = DRE->getDecl();
7297
7298
0
    FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7299
0
    if (FDecl && FDecl->getBuiltinID()) {
7300
      // Rewrite the function decl for this builtin by replacing parameters
7301
      // with no explicit address space with the address space of the arguments
7302
      // in ArgExprs.
7303
0
      if ((FDecl =
7304
0
               rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7305
0
        NDecl = FDecl;
7306
0
        Fn = DeclRefExpr::Create(
7307
0
            Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7308
0
            SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7309
0
            nullptr, DRE->isNonOdrUse());
7310
0
      }
7311
0
    }
7312
0
  } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7313
0
    NDecl = ME->getMemberDecl();
7314
7315
0
  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7316
0
    if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7317
0
                                      FD, /*Complain=*/true, Fn->getBeginLoc()))
7318
0
      return ExprError();
7319
7320
0
    checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7321
7322
    // If this expression is a call to a builtin function in HIP device
7323
    // compilation, allow a pointer-type argument to default address space to be
7324
    // passed as a pointer-type parameter to a non-default address space.
7325
    // If Arg is declared in the default address space and Param is declared
7326
    // in a non-default address space, perform an implicit address space cast to
7327
    // the parameter type.
7328
0
    if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7329
0
        FD->getBuiltinID()) {
7330
0
      for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7331
0
        ParmVarDecl *Param = FD->getParamDecl(Idx);
7332
0
        if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7333
0
            !ArgExprs[Idx]->getType()->isPointerType())
7334
0
          continue;
7335
7336
0
        auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7337
0
        auto ArgTy = ArgExprs[Idx]->getType();
7338
0
        auto ArgPtTy = ArgTy->getPointeeType();
7339
0
        auto ArgAS = ArgPtTy.getAddressSpace();
7340
7341
        // Add address space cast if target address spaces are different
7342
0
        bool NeedImplicitASC =
7343
0
          ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
7344
0
          ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
7345
                                              // or from specific AS which has target AS matching that of Param.
7346
0
          getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7347
0
        if (!NeedImplicitASC)
7348
0
          continue;
7349
7350
        // First, ensure that the Arg is an RValue.
7351
0
        if (ArgExprs[Idx]->isGLValue()) {
7352
0
          ArgExprs[Idx] = ImplicitCastExpr::Create(
7353
0
              Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7354
0
              nullptr, VK_PRValue, FPOptionsOverride());
7355
0
        }
7356
7357
        // Construct a new arg type with address space of Param
7358
0
        Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7359
0
        ArgPtQuals.setAddressSpace(ParamAS);
7360
0
        auto NewArgPtTy =
7361
0
            Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7362
0
        auto NewArgTy =
7363
0
            Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7364
0
                                     ArgTy.getQualifiers());
7365
7366
        // Finally perform an implicit address space cast
7367
0
        ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7368
0
                                          CK_AddressSpaceConversion)
7369
0
                            .get();
7370
0
      }
7371
0
    }
7372
0
  }
7373
7374
0
  if (Context.isDependenceAllowed() &&
7375
0
      (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7376
0
    assert(!getLangOpts().CPlusPlus);
7377
0
    assert((Fn->containsErrors() ||
7378
0
            llvm::any_of(ArgExprs,
7379
0
                         [](clang::Expr *E) { return E->containsErrors(); })) &&
7380
0
           "should only occur in error-recovery path.");
7381
0
    return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7382
0
                            VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7383
0
  }
7384
0
  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7385
0
                               ExecConfig, IsExecConfig);
7386
0
}
7387
7388
/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7389
//  with the specified CallArgs
7390
Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7391
0
                                 MultiExprArg CallArgs) {
7392
0
  StringRef Name = Context.BuiltinInfo.getName(Id);
7393
0
  LookupResult R(*this, &Context.Idents.get(Name), Loc,
7394
0
                 Sema::LookupOrdinaryName);
7395
0
  LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7396
7397
0
  auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7398
0
  assert(BuiltInDecl && "failed to find builtin declaration");
7399
7400
0
  ExprResult DeclRef =
7401
0
      BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7402
0
  assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7403
7404
0
  ExprResult Call =
7405
0
      BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7406
7407
0
  assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7408
0
  return Call.get();
7409
0
}
7410
7411
/// Parse a __builtin_astype expression.
7412
///
7413
/// __builtin_astype( value, dst type )
7414
///
7415
ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7416
                                 SourceLocation BuiltinLoc,
7417
0
                                 SourceLocation RParenLoc) {
7418
0
  QualType DstTy = GetTypeFromParser(ParsedDestTy);
7419
0
  return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7420
0
}
7421
7422
/// Create a new AsTypeExpr node (bitcast) from the arguments.
7423
ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7424
                                 SourceLocation BuiltinLoc,
7425
0
                                 SourceLocation RParenLoc) {
7426
0
  ExprValueKind VK = VK_PRValue;
7427
0
  ExprObjectKind OK = OK_Ordinary;
7428
0
  QualType SrcTy = E->getType();
7429
0
  if (!SrcTy->isDependentType() &&
7430
0
      Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7431
0
    return ExprError(
7432
0
        Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7433
0
        << DestTy << SrcTy << E->getSourceRange());
7434
0
  return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7435
0
}
7436
7437
/// ActOnConvertVectorExpr - create a new convert-vector expression from the
7438
/// provided arguments.
7439
///
7440
/// __builtin_convertvector( value, dst type )
7441
///
7442
ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7443
                                        SourceLocation BuiltinLoc,
7444
0
                                        SourceLocation RParenLoc) {
7445
0
  TypeSourceInfo *TInfo;
7446
0
  GetTypeFromParser(ParsedDestTy, &TInfo);
7447
0
  return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7448
0
}
7449
7450
/// BuildResolvedCallExpr - Build a call to a resolved expression,
7451
/// i.e. an expression not of \p OverloadTy.  The expression should
7452
/// unary-convert to an expression of function-pointer or
7453
/// block-pointer type.
7454
///
7455
/// \param NDecl the declaration being called, if available
7456
ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7457
                                       SourceLocation LParenLoc,
7458
                                       ArrayRef<Expr *> Args,
7459
                                       SourceLocation RParenLoc, Expr *Config,
7460
0
                                       bool IsExecConfig, ADLCallKind UsesADL) {
7461
0
  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7462
0
  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7463
7464
  // Functions with 'interrupt' attribute cannot be called directly.
7465
0
  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7466
0
    Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7467
0
    return ExprError();
7468
0
  }
7469
7470
  // Interrupt handlers don't save off the VFP regs automatically on ARM,
7471
  // so there's some risk when calling out to non-interrupt handler functions
7472
  // that the callee might not preserve them. This is easy to diagnose here,
7473
  // but can be very challenging to debug.
7474
  // Likewise, X86 interrupt handlers may only call routines with attribute
7475
  // no_caller_saved_registers since there is no efficient way to
7476
  // save and restore the non-GPR state.
7477
0
  if (auto *Caller = getCurFunctionDecl()) {
7478
0
    if (Caller->hasAttr<ARMInterruptAttr>()) {
7479
0
      bool VFP = Context.getTargetInfo().hasFeature("vfp");
7480
0
      if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7481
0
        Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7482
0
        if (FDecl)
7483
0
          Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7484
0
      }
7485
0
    }
7486
0
    if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7487
0
        Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7488
0
      const TargetInfo &TI = Context.getTargetInfo();
7489
0
      bool HasNonGPRRegisters =
7490
0
          TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7491
0
      if (HasNonGPRRegisters &&
7492
0
          (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7493
0
        Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7494
0
            << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7495
0
        if (FDecl)
7496
0
          Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7497
0
      }
7498
0
    }
7499
0
  }
7500
7501
  // Promote the function operand.
7502
  // We special-case function promotion here because we only allow promoting
7503
  // builtin functions to function pointers in the callee of a call.
7504
0
  ExprResult Result;
7505
0
  QualType ResultTy;
7506
0
  if (BuiltinID &&
7507
0
      Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7508
    // Extract the return type from the (builtin) function pointer type.
7509
    // FIXME Several builtins still have setType in
7510
    // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7511
    // Builtins.def to ensure they are correct before removing setType calls.
7512
0
    QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7513
0
    Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7514
0
    ResultTy = FDecl->getCallResultType();
7515
0
  } else {
7516
0
    Result = CallExprUnaryConversions(Fn);
7517
0
    ResultTy = Context.BoolTy;
7518
0
  }
7519
0
  if (Result.isInvalid())
7520
0
    return ExprError();
7521
0
  Fn = Result.get();
7522
7523
  // Check for a valid function type, but only if it is not a builtin which
7524
  // requires custom type checking. These will be handled by
7525
  // CheckBuiltinFunctionCall below just after creation of the call expression.
7526
0
  const FunctionType *FuncT = nullptr;
7527
0
  if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7528
0
  retry:
7529
0
    if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7530
      // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7531
      // have type pointer to function".
7532
0
      FuncT = PT->getPointeeType()->getAs<FunctionType>();
7533
0
      if (!FuncT)
7534
0
        return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7535
0
                         << Fn->getType() << Fn->getSourceRange());
7536
0
    } else if (const BlockPointerType *BPT =
7537
0
                   Fn->getType()->getAs<BlockPointerType>()) {
7538
0
      FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7539
0
    } else {
7540
      // Handle calls to expressions of unknown-any type.
7541
0
      if (Fn->getType() == Context.UnknownAnyTy) {
7542
0
        ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7543
0
        if (rewrite.isInvalid())
7544
0
          return ExprError();
7545
0
        Fn = rewrite.get();
7546
0
        goto retry;
7547
0
      }
7548
7549
0
      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7550
0
                       << Fn->getType() << Fn->getSourceRange());
7551
0
    }
7552
0
  }
7553
7554
  // Get the number of parameters in the function prototype, if any.
7555
  // We will allocate space for max(Args.size(), NumParams) arguments
7556
  // in the call expression.
7557
0
  const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7558
0
  unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7559
7560
0
  CallExpr *TheCall;
7561
0
  if (Config) {
7562
0
    assert(UsesADL == ADLCallKind::NotADL &&
7563
0
           "CUDAKernelCallExpr should not use ADL");
7564
0
    TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7565
0
                                         Args, ResultTy, VK_PRValue, RParenLoc,
7566
0
                                         CurFPFeatureOverrides(), NumParams);
7567
0
  } else {
7568
0
    TheCall =
7569
0
        CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7570
0
                         CurFPFeatureOverrides(), NumParams, UsesADL);
7571
0
  }
7572
7573
0
  if (!Context.isDependenceAllowed()) {
7574
    // Forget about the nulled arguments since typo correction
7575
    // do not handle them well.
7576
0
    TheCall->shrinkNumArgs(Args.size());
7577
    // C cannot always handle TypoExpr nodes in builtin calls and direct
7578
    // function calls as their argument checking don't necessarily handle
7579
    // dependent types properly, so make sure any TypoExprs have been
7580
    // dealt with.
7581
0
    ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7582
0
    if (!Result.isUsable()) return ExprError();
7583
0
    CallExpr *TheOldCall = TheCall;
7584
0
    TheCall = dyn_cast<CallExpr>(Result.get());
7585
0
    bool CorrectedTypos = TheCall != TheOldCall;
7586
0
    if (!TheCall) return Result;
7587
0
    Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7588
7589
    // A new call expression node was created if some typos were corrected.
7590
    // However it may not have been constructed with enough storage. In this
7591
    // case, rebuild the node with enough storage. The waste of space is
7592
    // immaterial since this only happens when some typos were corrected.
7593
0
    if (CorrectedTypos && Args.size() < NumParams) {
7594
0
      if (Config)
7595
0
        TheCall = CUDAKernelCallExpr::Create(
7596
0
            Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7597
0
            RParenLoc, CurFPFeatureOverrides(), NumParams);
7598
0
      else
7599
0
        TheCall =
7600
0
            CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7601
0
                             CurFPFeatureOverrides(), NumParams, UsesADL);
7602
0
    }
7603
    // We can now handle the nulled arguments for the default arguments.
7604
0
    TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7605
0
  }
7606
7607
  // Bail out early if calling a builtin with custom type checking.
7608
0
  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7609
0
    return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7610
7611
0
  if (getLangOpts().CUDA) {
7612
0
    if (Config) {
7613
      // CUDA: Kernel calls must be to global functions
7614
0
      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7615
0
        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7616
0
            << FDecl << Fn->getSourceRange());
7617
7618
      // CUDA: Kernel function must have 'void' return type
7619
0
      if (!FuncT->getReturnType()->isVoidType() &&
7620
0
          !FuncT->getReturnType()->getAs<AutoType>() &&
7621
0
          !FuncT->getReturnType()->isInstantiationDependentType())
7622
0
        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7623
0
            << Fn->getType() << Fn->getSourceRange());
7624
0
    } else {
7625
      // CUDA: Calls to global functions must be configured
7626
0
      if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7627
0
        return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7628
0
            << FDecl << Fn->getSourceRange());
7629
0
    }
7630
0
  }
7631
7632
  // Check for a valid return type
7633
0
  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7634
0
                          FDecl))
7635
0
    return ExprError();
7636
7637
  // We know the result type of the call, set it.
7638
0
  TheCall->setType(FuncT->getCallResultType(Context));
7639
0
  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7640
7641
  // WebAssembly tables can't be used as arguments.
7642
0
  if (Context.getTargetInfo().getTriple().isWasm()) {
7643
0
    for (const Expr *Arg : Args) {
7644
0
      if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7645
0
        return ExprError(Diag(Arg->getExprLoc(),
7646
0
                              diag::err_wasm_table_as_function_parameter));
7647
0
      }
7648
0
    }
7649
0
  }
7650
7651
0
  if (Proto) {
7652
0
    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7653
0
                                IsExecConfig))
7654
0
      return ExprError();
7655
0
  } else {
7656
0
    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7657
7658
0
    if (FDecl) {
7659
      // Check if we have too few/too many template arguments, based
7660
      // on our knowledge of the function definition.
7661
0
      const FunctionDecl *Def = nullptr;
7662
0
      if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7663
0
        Proto = Def->getType()->getAs<FunctionProtoType>();
7664
0
       if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7665
0
          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7666
0
          << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7667
0
      }
7668
7669
      // If the function we're calling isn't a function prototype, but we have
7670
      // a function prototype from a prior declaratiom, use that prototype.
7671
0
      if (!FDecl->hasPrototype())
7672
0
        Proto = FDecl->getType()->getAs<FunctionProtoType>();
7673
0
    }
7674
7675
    // If we still haven't found a prototype to use but there are arguments to
7676
    // the call, diagnose this as calling a function without a prototype.
7677
    // However, if we found a function declaration, check to see if
7678
    // -Wdeprecated-non-prototype was disabled where the function was declared.
7679
    // If so, we will silence the diagnostic here on the assumption that this
7680
    // interface is intentional and the user knows what they're doing. We will
7681
    // also silence the diagnostic if there is a function declaration but it
7682
    // was implicitly defined (the user already gets diagnostics about the
7683
    // creation of the implicit function declaration, so the additional warning
7684
    // is not helpful).
7685
0
    if (!Proto && !Args.empty() &&
7686
0
        (!FDecl || (!FDecl->isImplicit() &&
7687
0
                    !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7688
0
                                     FDecl->getLocation()))))
7689
0
      Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7690
0
          << (FDecl != nullptr) << FDecl;
7691
7692
    // Promote the arguments (C99 6.5.2.2p6).
7693
0
    for (unsigned i = 0, e = Args.size(); i != e; i++) {
7694
0
      Expr *Arg = Args[i];
7695
7696
0
      if (Proto && i < Proto->getNumParams()) {
7697
0
        InitializedEntity Entity = InitializedEntity::InitializeParameter(
7698
0
            Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7699
0
        ExprResult ArgE =
7700
0
            PerformCopyInitialization(Entity, SourceLocation(), Arg);
7701
0
        if (ArgE.isInvalid())
7702
0
          return true;
7703
7704
0
        Arg = ArgE.getAs<Expr>();
7705
7706
0
      } else {
7707
0
        ExprResult ArgE = DefaultArgumentPromotion(Arg);
7708
7709
0
        if (ArgE.isInvalid())
7710
0
          return true;
7711
7712
0
        Arg = ArgE.getAs<Expr>();
7713
0
      }
7714
7715
0
      if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7716
0
                              diag::err_call_incomplete_argument, Arg))
7717
0
        return ExprError();
7718
7719
0
      TheCall->setArg(i, Arg);
7720
0
    }
7721
0
    TheCall->computeDependence();
7722
0
  }
7723
7724
0
  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7725
0
    if (Method->isImplicitObjectMemberFunction())
7726
0
      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7727
0
                       << Fn->getSourceRange() << 0);
7728
7729
  // Check for sentinels
7730
0
  if (NDecl)
7731
0
    DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7732
7733
  // Warn for unions passing across security boundary (CMSE).
7734
0
  if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7735
0
    for (unsigned i = 0, e = Args.size(); i != e; i++) {
7736
0
      if (const auto *RT =
7737
0
              dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7738
0
        if (RT->getDecl()->isOrContainsUnion())
7739
0
          Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7740
0
              << 0 << i;
7741
0
      }
7742
0
    }
7743
0
  }
7744
7745
  // Do special checking on direct calls to functions.
7746
0
  if (FDecl) {
7747
0
    if (CheckFunctionCall(FDecl, TheCall, Proto))
7748
0
      return ExprError();
7749
7750
0
    checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7751
7752
0
    if (BuiltinID)
7753
0
      return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7754
0
  } else if (NDecl) {
7755
0
    if (CheckPointerCall(NDecl, TheCall, Proto))
7756
0
      return ExprError();
7757
0
  } else {
7758
0
    if (CheckOtherCall(TheCall, Proto))
7759
0
      return ExprError();
7760
0
  }
7761
7762
0
  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7763
0
}
7764
7765
ExprResult
7766
Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7767
0
                           SourceLocation RParenLoc, Expr *InitExpr) {
7768
0
  assert(Ty && "ActOnCompoundLiteral(): missing type");
7769
0
  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7770
7771
0
  TypeSourceInfo *TInfo;
7772
0
  QualType literalType = GetTypeFromParser(Ty, &TInfo);
7773
0
  if (!TInfo)
7774
0
    TInfo = Context.getTrivialTypeSourceInfo(literalType);
7775
7776
0
  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7777
0
}
7778
7779
ExprResult
7780
Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7781
0
                               SourceLocation RParenLoc, Expr *LiteralExpr) {
7782
0
  QualType literalType = TInfo->getType();
7783
7784
0
  if (literalType->isArrayType()) {
7785
0
    if (RequireCompleteSizedType(
7786
0
            LParenLoc, Context.getBaseElementType(literalType),
7787
0
            diag::err_array_incomplete_or_sizeless_type,
7788
0
            SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7789
0
      return ExprError();
7790
0
    if (literalType->isVariableArrayType()) {
7791
      // C23 6.7.10p4: An entity of variable length array type shall not be
7792
      // initialized except by an empty initializer.
7793
      //
7794
      // The C extension warnings are issued from ParseBraceInitializer() and
7795
      // do not need to be issued here. However, we continue to issue an error
7796
      // in the case there are initializers or we are compiling C++. We allow
7797
      // use of VLAs in C++, but it's not clear we want to allow {} to zero
7798
      // init a VLA in C++ in all cases (such as with non-trivial constructors).
7799
      // FIXME: should we allow this construct in C++ when it makes sense to do
7800
      // so?
7801
0
      std::optional<unsigned> NumInits;
7802
0
      if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7803
0
        NumInits = ILE->getNumInits();
7804
0
      if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7805
0
          !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7806
0
                                           diag::err_variable_object_no_init))
7807
0
        return ExprError();
7808
0
    }
7809
0
  } else if (!literalType->isDependentType() &&
7810
0
             RequireCompleteType(LParenLoc, literalType,
7811
0
               diag::err_typecheck_decl_incomplete_type,
7812
0
               SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7813
0
    return ExprError();
7814
7815
0
  InitializedEntity Entity
7816
0
    = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7817
0
  InitializationKind Kind
7818
0
    = InitializationKind::CreateCStyleCast(LParenLoc,
7819
0
                                           SourceRange(LParenLoc, RParenLoc),
7820
0
                                           /*InitList=*/true);
7821
0
  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7822
0
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7823
0
                                      &literalType);
7824
0
  if (Result.isInvalid())
7825
0
    return ExprError();
7826
0
  LiteralExpr = Result.get();
7827
7828
0
  bool isFileScope = !CurContext->isFunctionOrMethod();
7829
7830
  // In C, compound literals are l-values for some reason.
7831
  // For GCC compatibility, in C++, file-scope array compound literals with
7832
  // constant initializers are also l-values, and compound literals are
7833
  // otherwise prvalues.
7834
  //
7835
  // (GCC also treats C++ list-initialized file-scope array prvalues with
7836
  // constant initializers as l-values, but that's non-conforming, so we don't
7837
  // follow it there.)
7838
  //
7839
  // FIXME: It would be better to handle the lvalue cases as materializing and
7840
  // lifetime-extending a temporary object, but our materialized temporaries
7841
  // representation only supports lifetime extension from a variable, not "out
7842
  // of thin air".
7843
  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7844
  // is bound to the result of applying array-to-pointer decay to the compound
7845
  // literal.
7846
  // FIXME: GCC supports compound literals of reference type, which should
7847
  // obviously have a value kind derived from the kind of reference involved.
7848
0
  ExprValueKind VK =
7849
0
      (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7850
0
          ? VK_PRValue
7851
0
          : VK_LValue;
7852
7853
0
  if (isFileScope)
7854
0
    if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7855
0
      for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7856
0
        Expr *Init = ILE->getInit(i);
7857
0
        ILE->setInit(i, ConstantExpr::Create(Context, Init));
7858
0
      }
7859
7860
0
  auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7861
0
                                              VK, LiteralExpr, isFileScope);
7862
0
  if (isFileScope) {
7863
0
    if (!LiteralExpr->isTypeDependent() &&
7864
0
        !LiteralExpr->isValueDependent() &&
7865
0
        !literalType->isDependentType()) // C99 6.5.2.5p3
7866
0
      if (CheckForConstantInitializer(LiteralExpr, literalType))
7867
0
        return ExprError();
7868
0
  } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7869
0
             literalType.getAddressSpace() != LangAS::Default) {
7870
    // Embedded-C extensions to C99 6.5.2.5:
7871
    //   "If the compound literal occurs inside the body of a function, the
7872
    //   type name shall not be qualified by an address-space qualifier."
7873
0
    Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7874
0
      << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7875
0
    return ExprError();
7876
0
  }
7877
7878
0
  if (!isFileScope && !getLangOpts().CPlusPlus) {
7879
    // Compound literals that have automatic storage duration are destroyed at
7880
    // the end of the scope in C; in C++, they're just temporaries.
7881
7882
    // Emit diagnostics if it is or contains a C union type that is non-trivial
7883
    // to destruct.
7884
0
    if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7885
0
      checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7886
0
                            NTCUC_CompoundLiteral, NTCUK_Destruct);
7887
7888
    // Diagnose jumps that enter or exit the lifetime of the compound literal.
7889
0
    if (literalType.isDestructedType()) {
7890
0
      Cleanup.setExprNeedsCleanups(true);
7891
0
      ExprCleanupObjects.push_back(E);
7892
0
      getCurFunction()->setHasBranchProtectedScope();
7893
0
    }
7894
0
  }
7895
7896
0
  if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7897
0
      E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7898
0
    checkNonTrivialCUnionInInitializer(E->getInitializer(),
7899
0
                                       E->getInitializer()->getExprLoc());
7900
7901
0
  return MaybeBindToTemporary(E);
7902
0
}
7903
7904
ExprResult
7905
Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7906
3
                    SourceLocation RBraceLoc) {
7907
  // Only produce each kind of designated initialization diagnostic once.
7908
3
  SourceLocation FirstDesignator;
7909
3
  bool DiagnosedArrayDesignator = false;
7910
3
  bool DiagnosedNestedDesignator = false;
7911
3
  bool DiagnosedMixedDesignator = false;
7912
7913
  // Check that any designated initializers are syntactically valid in the
7914
  // current language mode.
7915
5
  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7916
2
    if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7917
0
      if (FirstDesignator.isInvalid())
7918
0
        FirstDesignator = DIE->getBeginLoc();
7919
7920
0
      if (!getLangOpts().CPlusPlus)
7921
0
        break;
7922
7923
0
      if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7924
0
        DiagnosedNestedDesignator = true;
7925
0
        Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7926
0
          << DIE->getDesignatorsSourceRange();
7927
0
      }
7928
7929
0
      for (auto &Desig : DIE->designators()) {
7930
0
        if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7931
0
          DiagnosedArrayDesignator = true;
7932
0
          Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7933
0
            << Desig.getSourceRange();
7934
0
        }
7935
0
      }
7936
7937
0
      if (!DiagnosedMixedDesignator &&
7938
0
          !isa<DesignatedInitExpr>(InitArgList[0])) {
7939
0
        DiagnosedMixedDesignator = true;
7940
0
        Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7941
0
          << DIE->getSourceRange();
7942
0
        Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7943
0
          << InitArgList[0]->getSourceRange();
7944
0
      }
7945
2
    } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7946
2
               isa<DesignatedInitExpr>(InitArgList[0])) {
7947
0
      DiagnosedMixedDesignator = true;
7948
0
      auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7949
0
      Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7950
0
        << DIE->getSourceRange();
7951
0
      Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7952
0
        << InitArgList[I]->getSourceRange();
7953
0
    }
7954
2
  }
7955
7956
3
  if (FirstDesignator.isValid()) {
7957
    // Only diagnose designated initiaization as a C++20 extension if we didn't
7958
    // already diagnose use of (non-C++20) C99 designator syntax.
7959
0
    if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7960
0
        !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7961
0
      Diag(FirstDesignator, getLangOpts().CPlusPlus20
7962
0
                                ? diag::warn_cxx17_compat_designated_init
7963
0
                                : diag::ext_cxx_designated_init);
7964
0
    } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7965
0
      Diag(FirstDesignator, diag::ext_designated_init);
7966
0
    }
7967
0
  }
7968
7969
3
  return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7970
3
}
7971
7972
ExprResult
7973
Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7974
3
                    SourceLocation RBraceLoc) {
7975
  // Semantic analysis for initializers is done by ActOnDeclarator() and
7976
  // CheckInitializer() - it requires knowledge of the object being initialized.
7977
7978
  // Immediately handle non-overload placeholders.  Overloads can be
7979
  // resolved contextually, but everything else here can't.
7980
5
  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7981
2
    if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7982
0
      ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7983
7984
      // Ignore failures; dropping the entire initializer list because
7985
      // of one failure would be terrible for indexing/etc.
7986
0
      if (result.isInvalid()) continue;
7987
7988
0
      InitArgList[I] = result.get();
7989
0
    }
7990
2
  }
7991
7992
3
  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7993
3
                                               RBraceLoc);
7994
3
  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7995
3
  return E;
7996
3
}
7997
7998
/// Do an explicit extend of the given block pointer if we're in ARC.
7999
0
void Sema::maybeExtendBlockObject(ExprResult &E) {
8000
0
  assert(E.get()->getType()->isBlockPointerType());
8001
0
  assert(E.get()->isPRValue());
8002
8003
  // Only do this in an r-value context.
8004
0
  if (!getLangOpts().ObjCAutoRefCount) return;
8005
8006
0
  E = ImplicitCastExpr::Create(
8007
0
      Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
8008
0
      /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
8009
0
  Cleanup.setExprNeedsCleanups(true);
8010
0
}
8011
8012
/// Prepare a conversion of the given expression to an ObjC object
8013
/// pointer type.
8014
0
CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
8015
0
  QualType type = E.get()->getType();
8016
0
  if (type->isObjCObjectPointerType()) {
8017
0
    return CK_BitCast;
8018
0
  } else if (type->isBlockPointerType()) {
8019
0
    maybeExtendBlockObject(E);
8020
0
    return CK_BlockPointerToObjCPointerCast;
8021
0
  } else {
8022
0
    assert(type->isPointerType());
8023
0
    return CK_CPointerToObjCPointerCast;
8024
0
  }
8025
0
}
8026
8027
/// Prepares for a scalar cast, performing all the necessary stages
8028
/// except the final cast and returning the kind required.
8029
0
CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
8030
  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
8031
  // Also, callers should have filtered out the invalid cases with
8032
  // pointers.  Everything else should be possible.
8033
8034
0
  QualType SrcTy = Src.get()->getType();
8035
0
  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
8036
0
    return CK_NoOp;
8037
8038
0
  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
8039
0
  case Type::STK_MemberPointer:
8040
0
    llvm_unreachable("member pointer type in C");
8041
8042
0
  case Type::STK_CPointer:
8043
0
  case Type::STK_BlockPointer:
8044
0
  case Type::STK_ObjCObjectPointer:
8045
0
    switch (DestTy->getScalarTypeKind()) {
8046
0
    case Type::STK_CPointer: {
8047
0
      LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
8048
0
      LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
8049
0
      if (SrcAS != DestAS)
8050
0
        return CK_AddressSpaceConversion;
8051
0
      if (Context.hasCvrSimilarType(SrcTy, DestTy))
8052
0
        return CK_NoOp;
8053
0
      return CK_BitCast;
8054
0
    }
8055
0
    case Type::STK_BlockPointer:
8056
0
      return (SrcKind == Type::STK_BlockPointer
8057
0
                ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
8058
0
    case Type::STK_ObjCObjectPointer:
8059
0
      if (SrcKind == Type::STK_ObjCObjectPointer)
8060
0
        return CK_BitCast;
8061
0
      if (SrcKind == Type::STK_CPointer)
8062
0
        return CK_CPointerToObjCPointerCast;
8063
0
      maybeExtendBlockObject(Src);
8064
0
      return CK_BlockPointerToObjCPointerCast;
8065
0
    case Type::STK_Bool:
8066
0
      return CK_PointerToBoolean;
8067
0
    case Type::STK_Integral:
8068
0
      return CK_PointerToIntegral;
8069
0
    case Type::STK_Floating:
8070
0
    case Type::STK_FloatingComplex:
8071
0
    case Type::STK_IntegralComplex:
8072
0
    case Type::STK_MemberPointer:
8073
0
    case Type::STK_FixedPoint:
8074
0
      llvm_unreachable("illegal cast from pointer");
8075
0
    }
8076
0
    llvm_unreachable("Should have returned before this");
8077
8078
0
  case Type::STK_FixedPoint:
8079
0
    switch (DestTy->getScalarTypeKind()) {
8080
0
    case Type::STK_FixedPoint:
8081
0
      return CK_FixedPointCast;
8082
0
    case Type::STK_Bool:
8083
0
      return CK_FixedPointToBoolean;
8084
0
    case Type::STK_Integral:
8085
0
      return CK_FixedPointToIntegral;
8086
0
    case Type::STK_Floating:
8087
0
      return CK_FixedPointToFloating;
8088
0
    case Type::STK_IntegralComplex:
8089
0
    case Type::STK_FloatingComplex:
8090
0
      Diag(Src.get()->getExprLoc(),
8091
0
           diag::err_unimplemented_conversion_with_fixed_point_type)
8092
0
          << DestTy;
8093
0
      return CK_IntegralCast;
8094
0
    case Type::STK_CPointer:
8095
0
    case Type::STK_ObjCObjectPointer:
8096
0
    case Type::STK_BlockPointer:
8097
0
    case Type::STK_MemberPointer:
8098
0
      llvm_unreachable("illegal cast to pointer type");
8099
0
    }
8100
0
    llvm_unreachable("Should have returned before this");
8101
8102
0
  case Type::STK_Bool: // casting from bool is like casting from an integer
8103
0
  case Type::STK_Integral:
8104
0
    switch (DestTy->getScalarTypeKind()) {
8105
0
    case Type::STK_CPointer:
8106
0
    case Type::STK_ObjCObjectPointer:
8107
0
    case Type::STK_BlockPointer:
8108
0
      if (Src.get()->isNullPointerConstant(Context,
8109
0
                                           Expr::NPC_ValueDependentIsNull))
8110
0
        return CK_NullToPointer;
8111
0
      return CK_IntegralToPointer;
8112
0
    case Type::STK_Bool:
8113
0
      return CK_IntegralToBoolean;
8114
0
    case Type::STK_Integral:
8115
0
      return CK_IntegralCast;
8116
0
    case Type::STK_Floating:
8117
0
      return CK_IntegralToFloating;
8118
0
    case Type::STK_IntegralComplex:
8119
0
      Src = ImpCastExprToType(Src.get(),
8120
0
                      DestTy->castAs<ComplexType>()->getElementType(),
8121
0
                      CK_IntegralCast);
8122
0
      return CK_IntegralRealToComplex;
8123
0
    case Type::STK_FloatingComplex:
8124
0
      Src = ImpCastExprToType(Src.get(),
8125
0
                      DestTy->castAs<ComplexType>()->getElementType(),
8126
0
                      CK_IntegralToFloating);
8127
0
      return CK_FloatingRealToComplex;
8128
0
    case Type::STK_MemberPointer:
8129
0
      llvm_unreachable("member pointer type in C");
8130
0
    case Type::STK_FixedPoint:
8131
0
      return CK_IntegralToFixedPoint;
8132
0
    }
8133
0
    llvm_unreachable("Should have returned before this");
8134
8135
0
  case Type::STK_Floating:
8136
0
    switch (DestTy->getScalarTypeKind()) {
8137
0
    case Type::STK_Floating:
8138
0
      return CK_FloatingCast;
8139
0
    case Type::STK_Bool:
8140
0
      return CK_FloatingToBoolean;
8141
0
    case Type::STK_Integral:
8142
0
      return CK_FloatingToIntegral;
8143
0
    case Type::STK_FloatingComplex:
8144
0
      Src = ImpCastExprToType(Src.get(),
8145
0
                              DestTy->castAs<ComplexType>()->getElementType(),
8146
0
                              CK_FloatingCast);
8147
0
      return CK_FloatingRealToComplex;
8148
0
    case Type::STK_IntegralComplex:
8149
0
      Src = ImpCastExprToType(Src.get(),
8150
0
                              DestTy->castAs<ComplexType>()->getElementType(),
8151
0
                              CK_FloatingToIntegral);
8152
0
      return CK_IntegralRealToComplex;
8153
0
    case Type::STK_CPointer:
8154
0
    case Type::STK_ObjCObjectPointer:
8155
0
    case Type::STK_BlockPointer:
8156
0
      llvm_unreachable("valid float->pointer cast?");
8157
0
    case Type::STK_MemberPointer:
8158
0
      llvm_unreachable("member pointer type in C");
8159
0
    case Type::STK_FixedPoint:
8160
0
      return CK_FloatingToFixedPoint;
8161
0
    }
8162
0
    llvm_unreachable("Should have returned before this");
8163
8164
0
  case Type::STK_FloatingComplex:
8165
0
    switch (DestTy->getScalarTypeKind()) {
8166
0
    case Type::STK_FloatingComplex:
8167
0
      return CK_FloatingComplexCast;
8168
0
    case Type::STK_IntegralComplex:
8169
0
      return CK_FloatingComplexToIntegralComplex;
8170
0
    case Type::STK_Floating: {
8171
0
      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8172
0
      if (Context.hasSameType(ET, DestTy))
8173
0
        return CK_FloatingComplexToReal;
8174
0
      Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
8175
0
      return CK_FloatingCast;
8176
0
    }
8177
0
    case Type::STK_Bool:
8178
0
      return CK_FloatingComplexToBoolean;
8179
0
    case Type::STK_Integral:
8180
0
      Src = ImpCastExprToType(Src.get(),
8181
0
                              SrcTy->castAs<ComplexType>()->getElementType(),
8182
0
                              CK_FloatingComplexToReal);
8183
0
      return CK_FloatingToIntegral;
8184
0
    case Type::STK_CPointer:
8185
0
    case Type::STK_ObjCObjectPointer:
8186
0
    case Type::STK_BlockPointer:
8187
0
      llvm_unreachable("valid complex float->pointer cast?");
8188
0
    case Type::STK_MemberPointer:
8189
0
      llvm_unreachable("member pointer type in C");
8190
0
    case Type::STK_FixedPoint:
8191
0
      Diag(Src.get()->getExprLoc(),
8192
0
           diag::err_unimplemented_conversion_with_fixed_point_type)
8193
0
          << SrcTy;
8194
0
      return CK_IntegralCast;
8195
0
    }
8196
0
    llvm_unreachable("Should have returned before this");
8197
8198
0
  case Type::STK_IntegralComplex:
8199
0
    switch (DestTy->getScalarTypeKind()) {
8200
0
    case Type::STK_FloatingComplex:
8201
0
      return CK_IntegralComplexToFloatingComplex;
8202
0
    case Type::STK_IntegralComplex:
8203
0
      return CK_IntegralComplexCast;
8204
0
    case Type::STK_Integral: {
8205
0
      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8206
0
      if (Context.hasSameType(ET, DestTy))
8207
0
        return CK_IntegralComplexToReal;
8208
0
      Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
8209
0
      return CK_IntegralCast;
8210
0
    }
8211
0
    case Type::STK_Bool:
8212
0
      return CK_IntegralComplexToBoolean;
8213
0
    case Type::STK_Floating:
8214
0
      Src = ImpCastExprToType(Src.get(),
8215
0
                              SrcTy->castAs<ComplexType>()->getElementType(),
8216
0
                              CK_IntegralComplexToReal);
8217
0
      return CK_IntegralToFloating;
8218
0
    case Type::STK_CPointer:
8219
0
    case Type::STK_ObjCObjectPointer:
8220
0
    case Type::STK_BlockPointer:
8221
0
      llvm_unreachable("valid complex int->pointer cast?");
8222
0
    case Type::STK_MemberPointer:
8223
0
      llvm_unreachable("member pointer type in C");
8224
0
    case Type::STK_FixedPoint:
8225
0
      Diag(Src.get()->getExprLoc(),
8226
0
           diag::err_unimplemented_conversion_with_fixed_point_type)
8227
0
          << SrcTy;
8228
0
      return CK_IntegralCast;
8229
0
    }
8230
0
    llvm_unreachable("Should have returned before this");
8231
0
  }
8232
8233
0
  llvm_unreachable("Unhandled scalar cast");
8234
0
}
8235
8236
static bool breakDownVectorType(QualType type, uint64_t &len,
8237
0
                                QualType &eltType) {
8238
  // Vectors are simple.
8239
0
  if (const VectorType *vecType = type->getAs<VectorType>()) {
8240
0
    len = vecType->getNumElements();
8241
0
    eltType = vecType->getElementType();
8242
0
    assert(eltType->isScalarType());
8243
0
    return true;
8244
0
  }
8245
8246
  // We allow lax conversion to and from non-vector types, but only if
8247
  // they're real types (i.e. non-complex, non-pointer scalar types).
8248
0
  if (!type->isRealType()) return false;
8249
8250
0
  len = 1;
8251
0
  eltType = type;
8252
0
  return true;
8253
0
}
8254
8255
/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
8256
/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
8257
/// allowed?
8258
///
8259
/// This will also return false if the two given types do not make sense from
8260
/// the perspective of SVE bitcasts.
8261
0
bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8262
0
  assert(srcTy->isVectorType() || destTy->isVectorType());
8263
8264
0
  auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8265
0
    if (!FirstType->isSVESizelessBuiltinType())
8266
0
      return false;
8267
8268
0
    const auto *VecTy = SecondType->getAs<VectorType>();
8269
0
    return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8270
0
  };
8271
8272
0
  return ValidScalableConversion(srcTy, destTy) ||
8273
0
         ValidScalableConversion(destTy, srcTy);
8274
0
}
8275
8276
/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
8277
/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
8278
/// VLS type) allowed?
8279
///
8280
/// This will also return false if the two given types do not make sense from
8281
/// the perspective of RVV bitcasts.
8282
0
bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
8283
0
  assert(srcTy->isVectorType() || destTy->isVectorType());
8284
8285
0
  auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8286
0
    if (!FirstType->isRVVSizelessBuiltinType())
8287
0
      return false;
8288
8289
0
    const auto *VecTy = SecondType->getAs<VectorType>();
8290
0
    return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData;
8291
0
  };
8292
8293
0
  return ValidScalableConversion(srcTy, destTy) ||
8294
0
         ValidScalableConversion(destTy, srcTy);
8295
0
}
8296
8297
/// Are the two types matrix types and do they have the same dimensions i.e.
8298
/// do they have the same number of rows and the same number of columns?
8299
0
bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8300
0
  if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8301
0
    return false;
8302
8303
0
  const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8304
0
  const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8305
8306
0
  return matSrcType->getNumRows() == matDestType->getNumRows() &&
8307
0
         matSrcType->getNumColumns() == matDestType->getNumColumns();
8308
0
}
8309
8310
0
bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8311
0
  assert(DestTy->isVectorType() || SrcTy->isVectorType());
8312
8313
0
  uint64_t SrcLen, DestLen;
8314
0
  QualType SrcEltTy, DestEltTy;
8315
0
  if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8316
0
    return false;
8317
0
  if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8318
0
    return false;
8319
8320
  // ASTContext::getTypeSize will return the size rounded up to a
8321
  // power of 2, so instead of using that, we need to use the raw
8322
  // element size multiplied by the element count.
8323
0
  uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8324
0
  uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8325
8326
0
  return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8327
0
}
8328
8329
// This returns true if at least one of the types is an altivec vector.
8330
0
bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8331
0
  assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8332
0
         "expected at least one type to be a vector here");
8333
8334
0
  bool IsSrcTyAltivec =
8335
0
      SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8336
0
                                 VectorKind::AltiVecVector) ||
8337
0
                                (SrcTy->castAs<VectorType>()->getVectorKind() ==
8338
0
                                 VectorKind::AltiVecBool) ||
8339
0
                                (SrcTy->castAs<VectorType>()->getVectorKind() ==
8340
0
                                 VectorKind::AltiVecPixel));
8341
8342
0
  bool IsDestTyAltivec = DestTy->isVectorType() &&
8343
0
                         ((DestTy->castAs<VectorType>()->getVectorKind() ==
8344
0
                           VectorKind::AltiVecVector) ||
8345
0
                          (DestTy->castAs<VectorType>()->getVectorKind() ==
8346
0
                           VectorKind::AltiVecBool) ||
8347
0
                          (DestTy->castAs<VectorType>()->getVectorKind() ==
8348
0
                           VectorKind::AltiVecPixel));
8349
8350
0
  return (IsSrcTyAltivec || IsDestTyAltivec);
8351
0
}
8352
8353
/// Are the two types lax-compatible vector types?  That is, given
8354
/// that one of them is a vector, do they have equal storage sizes,
8355
/// where the storage size is the number of elements times the element
8356
/// size?
8357
///
8358
/// This will also return false if either of the types is neither a
8359
/// vector nor a real type.
8360
0
bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8361
0
  assert(destTy->isVectorType() || srcTy->isVectorType());
8362
8363
  // Disallow lax conversions between scalars and ExtVectors (these
8364
  // conversions are allowed for other vector types because common headers
8365
  // depend on them).  Most scalar OP ExtVector cases are handled by the
8366
  // splat path anyway, which does what we want (convert, not bitcast).
8367
  // What this rules out for ExtVectors is crazy things like char4*float.
8368
0
  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8369
0
  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8370
8371
0
  return areVectorTypesSameSize(srcTy, destTy);
8372
0
}
8373
8374
/// Is this a legal conversion between two types, one of which is
8375
/// known to be a vector type?
8376
0
bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8377
0
  assert(destTy->isVectorType() || srcTy->isVectorType());
8378
8379
0
  switch (Context.getLangOpts().getLaxVectorConversions()) {
8380
0
  case LangOptions::LaxVectorConversionKind::None:
8381
0
    return false;
8382
8383
0
  case LangOptions::LaxVectorConversionKind::Integer:
8384
0
    if (!srcTy->isIntegralOrEnumerationType()) {
8385
0
      auto *Vec = srcTy->getAs<VectorType>();
8386
0
      if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8387
0
        return false;
8388
0
    }
8389
0
    if (!destTy->isIntegralOrEnumerationType()) {
8390
0
      auto *Vec = destTy->getAs<VectorType>();
8391
0
      if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8392
0
        return false;
8393
0
    }
8394
    // OK, integer (vector) -> integer (vector) bitcast.
8395
0
    break;
8396
8397
0
    case LangOptions::LaxVectorConversionKind::All:
8398
0
    break;
8399
0
  }
8400
8401
0
  return areLaxCompatibleVectorTypes(srcTy, destTy);
8402
0
}
8403
8404
bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8405
0
                           CastKind &Kind) {
8406
0
  if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8407
0
    if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8408
0
      return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8409
0
             << DestTy << SrcTy << R;
8410
0
    }
8411
0
  } else if (SrcTy->isMatrixType()) {
8412
0
    return Diag(R.getBegin(),
8413
0
                diag::err_invalid_conversion_between_matrix_and_type)
8414
0
           << SrcTy << DestTy << R;
8415
0
  } else if (DestTy->isMatrixType()) {
8416
0
    return Diag(R.getBegin(),
8417
0
                diag::err_invalid_conversion_between_matrix_and_type)
8418
0
           << DestTy << SrcTy << R;
8419
0
  }
8420
8421
0
  Kind = CK_MatrixCast;
8422
0
  return false;
8423
0
}
8424
8425
bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8426
0
                           CastKind &Kind) {
8427
0
  assert(VectorTy->isVectorType() && "Not a vector type!");
8428
8429
0
  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8430
0
    if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8431
0
      return Diag(R.getBegin(),
8432
0
                  Ty->isVectorType() ?
8433
0
                  diag::err_invalid_conversion_between_vectors :
8434
0
                  diag::err_invalid_conversion_between_vector_and_integer)
8435
0
        << VectorTy << Ty << R;
8436
0
  } else
8437
0
    return Diag(R.getBegin(),
8438
0
                diag::err_invalid_conversion_between_vector_and_scalar)
8439
0
      << VectorTy << Ty << R;
8440
8441
0
  Kind = CK_BitCast;
8442
0
  return false;
8443
0
}
8444
8445
0
ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8446
0
  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8447
8448
0
  if (DestElemTy == SplattedExpr->getType())
8449
0
    return SplattedExpr;
8450
8451
0
  assert(DestElemTy->isFloatingType() ||
8452
0
         DestElemTy->isIntegralOrEnumerationType());
8453
8454
0
  CastKind CK;
8455
0
  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8456
    // OpenCL requires that we convert `true` boolean expressions to -1, but
8457
    // only when splatting vectors.
8458
0
    if (DestElemTy->isFloatingType()) {
8459
      // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8460
      // in two steps: boolean to signed integral, then to floating.
8461
0
      ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8462
0
                                                 CK_BooleanToSignedIntegral);
8463
0
      SplattedExpr = CastExprRes.get();
8464
0
      CK = CK_IntegralToFloating;
8465
0
    } else {
8466
0
      CK = CK_BooleanToSignedIntegral;
8467
0
    }
8468
0
  } else {
8469
0
    ExprResult CastExprRes = SplattedExpr;
8470
0
    CK = PrepareScalarCast(CastExprRes, DestElemTy);
8471
0
    if (CastExprRes.isInvalid())
8472
0
      return ExprError();
8473
0
    SplattedExpr = CastExprRes.get();
8474
0
  }
8475
0
  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8476
0
}
8477
8478
ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8479
0
                                    Expr *CastExpr, CastKind &Kind) {
8480
0
  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8481
8482
0
  QualType SrcTy = CastExpr->getType();
8483
8484
  // If SrcTy is a VectorType, the total size must match to explicitly cast to
8485
  // an ExtVectorType.
8486
  // In OpenCL, casts between vectors of different types are not allowed.
8487
  // (See OpenCL 6.2).
8488
0
  if (SrcTy->isVectorType()) {
8489
0
    if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8490
0
        (getLangOpts().OpenCL &&
8491
0
         !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8492
0
      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8493
0
        << DestTy << SrcTy << R;
8494
0
      return ExprError();
8495
0
    }
8496
0
    Kind = CK_BitCast;
8497
0
    return CastExpr;
8498
0
  }
8499
8500
  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
8501
  // conversion will take place first from scalar to elt type, and then
8502
  // splat from elt type to vector.
8503
0
  if (SrcTy->isPointerType())
8504
0
    return Diag(R.getBegin(),
8505
0
                diag::err_invalid_conversion_between_vector_and_scalar)
8506
0
      << DestTy << SrcTy << R;
8507
8508
0
  Kind = CK_VectorSplat;
8509
0
  return prepareVectorSplat(DestTy, CastExpr);
8510
0
}
8511
8512
ExprResult
8513
Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8514
                    Declarator &D, ParsedType &Ty,
8515
0
                    SourceLocation RParenLoc, Expr *CastExpr) {
8516
0
  assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8517
0
         "ActOnCastExpr(): missing type or expr");
8518
8519
0
  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8520
0
  if (D.isInvalidType())
8521
0
    return ExprError();
8522
8523
0
  if (getLangOpts().CPlusPlus) {
8524
    // Check that there are no default arguments (C++ only).
8525
0
    CheckExtraCXXDefaultArguments(D);
8526
0
  } else {
8527
    // Make sure any TypoExprs have been dealt with.
8528
0
    ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8529
0
    if (!Res.isUsable())
8530
0
      return ExprError();
8531
0
    CastExpr = Res.get();
8532
0
  }
8533
8534
0
  checkUnusedDeclAttributes(D);
8535
8536
0
  QualType castType = castTInfo->getType();
8537
0
  Ty = CreateParsedType(castType, castTInfo);
8538
8539
0
  bool isVectorLiteral = false;
8540
8541
  // Check for an altivec or OpenCL literal,
8542
  // i.e. all the elements are integer constants.
8543
0
  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8544
0
  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8545
0
  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8546
0
       && castType->isVectorType() && (PE || PLE)) {
8547
0
    if (PLE && PLE->getNumExprs() == 0) {
8548
0
      Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8549
0
      return ExprError();
8550
0
    }
8551
0
    if (PE || PLE->getNumExprs() == 1) {
8552
0
      Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8553
0
      if (!E->isTypeDependent() && !E->getType()->isVectorType())
8554
0
        isVectorLiteral = true;
8555
0
    }
8556
0
    else
8557
0
      isVectorLiteral = true;
8558
0
  }
8559
8560
  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8561
  // then handle it as such.
8562
0
  if (isVectorLiteral)
8563
0
    return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8564
8565
  // If the Expr being casted is a ParenListExpr, handle it specially.
8566
  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8567
  // sequence of BinOp comma operators.
8568
0
  if (isa<ParenListExpr>(CastExpr)) {
8569
0
    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8570
0
    if (Result.isInvalid()) return ExprError();
8571
0
    CastExpr = Result.get();
8572
0
  }
8573
8574
0
  if (getLangOpts().CPlusPlus && !castType->isVoidType())
8575
0
    Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8576
8577
0
  CheckTollFreeBridgeCast(castType, CastExpr);
8578
8579
0
  CheckObjCBridgeRelatedCast(castType, CastExpr);
8580
8581
0
  DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8582
8583
0
  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8584
0
}
8585
8586
ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8587
                                    SourceLocation RParenLoc, Expr *E,
8588
0
                                    TypeSourceInfo *TInfo) {
8589
0
  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8590
0
         "Expected paren or paren list expression");
8591
8592
0
  Expr **exprs;
8593
0
  unsigned numExprs;
8594
0
  Expr *subExpr;
8595
0
  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8596
0
  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8597
0
    LiteralLParenLoc = PE->getLParenLoc();
8598
0
    LiteralRParenLoc = PE->getRParenLoc();
8599
0
    exprs = PE->getExprs();
8600
0
    numExprs = PE->getNumExprs();
8601
0
  } else { // isa<ParenExpr> by assertion at function entrance
8602
0
    LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8603
0
    LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8604
0
    subExpr = cast<ParenExpr>(E)->getSubExpr();
8605
0
    exprs = &subExpr;
8606
0
    numExprs = 1;
8607
0
  }
8608
8609
0
  QualType Ty = TInfo->getType();
8610
0
  assert(Ty->isVectorType() && "Expected vector type");
8611
8612
0
  SmallVector<Expr *, 8> initExprs;
8613
0
  const VectorType *VTy = Ty->castAs<VectorType>();
8614
0
  unsigned numElems = VTy->getNumElements();
8615
8616
  // '(...)' form of vector initialization in AltiVec: the number of
8617
  // initializers must be one or must match the size of the vector.
8618
  // If a single value is specified in the initializer then it will be
8619
  // replicated to all the components of the vector
8620
0
  if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8621
0
                                 VTy->getElementType()))
8622
0
    return ExprError();
8623
0
  if (ShouldSplatAltivecScalarInCast(VTy)) {
8624
    // The number of initializers must be one or must match the size of the
8625
    // vector. If a single value is specified in the initializer then it will
8626
    // be replicated to all the components of the vector
8627
0
    if (numExprs == 1) {
8628
0
      QualType ElemTy = VTy->getElementType();
8629
0
      ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8630
0
      if (Literal.isInvalid())
8631
0
        return ExprError();
8632
0
      Literal = ImpCastExprToType(Literal.get(), ElemTy,
8633
0
                                  PrepareScalarCast(Literal, ElemTy));
8634
0
      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8635
0
    }
8636
0
    else if (numExprs < numElems) {
8637
0
      Diag(E->getExprLoc(),
8638
0
           diag::err_incorrect_number_of_vector_initializers);
8639
0
      return ExprError();
8640
0
    }
8641
0
    else
8642
0
      initExprs.append(exprs, exprs + numExprs);
8643
0
  }
8644
0
  else {
8645
    // For OpenCL, when the number of initializers is a single value,
8646
    // it will be replicated to all components of the vector.
8647
0
    if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8648
0
        numExprs == 1) {
8649
0
      QualType ElemTy = VTy->getElementType();
8650
0
      ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8651
0
      if (Literal.isInvalid())
8652
0
        return ExprError();
8653
0
      Literal = ImpCastExprToType(Literal.get(), ElemTy,
8654
0
                                  PrepareScalarCast(Literal, ElemTy));
8655
0
      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8656
0
    }
8657
8658
0
    initExprs.append(exprs, exprs + numExprs);
8659
0
  }
8660
  // FIXME: This means that pretty-printing the final AST will produce curly
8661
  // braces instead of the original commas.
8662
0
  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8663
0
                                                   initExprs, LiteralRParenLoc);
8664
0
  initE->setType(Ty);
8665
0
  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8666
0
}
8667
8668
/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8669
/// the ParenListExpr into a sequence of comma binary operators.
8670
ExprResult
8671
4
Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8672
4
  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8673
4
  if (!E)
8674
4
    return OrigExpr;
8675
8676
0
  ExprResult Result(E->getExpr(0));
8677
8678
0
  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8679
0
    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8680
0
                        E->getExpr(i));
8681
8682
0
  if (Result.isInvalid()) return ExprError();
8683
8684
0
  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8685
0
}
8686
8687
ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8688
                                    SourceLocation R,
8689
11
                                    MultiExprArg Val) {
8690
11
  return ParenListExpr::Create(Context, L, Val, R);
8691
11
}
8692
8693
/// Emit a specialized diagnostic when one expression is a null pointer
8694
/// constant and the other is not a pointer.  Returns true if a diagnostic is
8695
/// emitted.
8696
bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8697
0
                                      SourceLocation QuestionLoc) {
8698
0
  const Expr *NullExpr = LHSExpr;
8699
0
  const Expr *NonPointerExpr = RHSExpr;
8700
0
  Expr::NullPointerConstantKind NullKind =
8701
0
      NullExpr->isNullPointerConstant(Context,
8702
0
                                      Expr::NPC_ValueDependentIsNotNull);
8703
8704
0
  if (NullKind == Expr::NPCK_NotNull) {
8705
0
    NullExpr = RHSExpr;
8706
0
    NonPointerExpr = LHSExpr;
8707
0
    NullKind =
8708
0
        NullExpr->isNullPointerConstant(Context,
8709
0
                                        Expr::NPC_ValueDependentIsNotNull);
8710
0
  }
8711
8712
0
  if (NullKind == Expr::NPCK_NotNull)
8713
0
    return false;
8714
8715
0
  if (NullKind == Expr::NPCK_ZeroExpression)
8716
0
    return false;
8717
8718
0
  if (NullKind == Expr::NPCK_ZeroLiteral) {
8719
    // In this case, check to make sure that we got here from a "NULL"
8720
    // string in the source code.
8721
0
    NullExpr = NullExpr->IgnoreParenImpCasts();
8722
0
    SourceLocation loc = NullExpr->getExprLoc();
8723
0
    if (!findMacroSpelling(loc, "NULL"))
8724
0
      return false;
8725
0
  }
8726
8727
0
  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8728
0
  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8729
0
      << NonPointerExpr->getType() << DiagType
8730
0
      << NonPointerExpr->getSourceRange();
8731
0
  return true;
8732
0
}
8733
8734
/// Return false if the condition expression is valid, true otherwise.
8735
static bool checkCondition(Sema &S, const Expr *Cond,
8736
0
                           SourceLocation QuestionLoc) {
8737
0
  QualType CondTy = Cond->getType();
8738
8739
  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8740
0
  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8741
0
    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8742
0
      << CondTy << Cond->getSourceRange();
8743
0
    return true;
8744
0
  }
8745
8746
  // C99 6.5.15p2
8747
0
  if (CondTy->isScalarType()) return false;
8748
8749
0
  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8750
0
    << CondTy << Cond->getSourceRange();
8751
0
  return true;
8752
0
}
8753
8754
/// Return false if the NullExpr can be promoted to PointerTy,
8755
/// true otherwise.
8756
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8757
0
                                        QualType PointerTy) {
8758
0
  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8759
0
      !NullExpr.get()->isNullPointerConstant(S.Context,
8760
0
                                            Expr::NPC_ValueDependentIsNull))
8761
0
    return true;
8762
8763
0
  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8764
0
  return false;
8765
0
}
8766
8767
/// Checks compatibility between two pointers and return the resulting
8768
/// type.
8769
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8770
                                                     ExprResult &RHS,
8771
0
                                                     SourceLocation Loc) {
8772
0
  QualType LHSTy = LHS.get()->getType();
8773
0
  QualType RHSTy = RHS.get()->getType();
8774
8775
0
  if (S.Context.hasSameType(LHSTy, RHSTy)) {
8776
    // Two identical pointers types are always compatible.
8777
0
    return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8778
0
  }
8779
8780
0
  QualType lhptee, rhptee;
8781
8782
  // Get the pointee types.
8783
0
  bool IsBlockPointer = false;
8784
0
  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8785
0
    lhptee = LHSBTy->getPointeeType();
8786
0
    rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8787
0
    IsBlockPointer = true;
8788
0
  } else {
8789
0
    lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8790
0
    rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8791
0
  }
8792
8793
  // C99 6.5.15p6: If both operands are pointers to compatible types or to
8794
  // differently qualified versions of compatible types, the result type is
8795
  // a pointer to an appropriately qualified version of the composite
8796
  // type.
8797
8798
  // Only CVR-qualifiers exist in the standard, and the differently-qualified
8799
  // clause doesn't make sense for our extensions. E.g. address space 2 should
8800
  // be incompatible with address space 3: they may live on different devices or
8801
  // anything.
8802
0
  Qualifiers lhQual = lhptee.getQualifiers();
8803
0
  Qualifiers rhQual = rhptee.getQualifiers();
8804
8805
0
  LangAS ResultAddrSpace = LangAS::Default;
8806
0
  LangAS LAddrSpace = lhQual.getAddressSpace();
8807
0
  LangAS RAddrSpace = rhQual.getAddressSpace();
8808
8809
  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8810
  // spaces is disallowed.
8811
0
  if (lhQual.isAddressSpaceSupersetOf(rhQual))
8812
0
    ResultAddrSpace = LAddrSpace;
8813
0
  else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8814
0
    ResultAddrSpace = RAddrSpace;
8815
0
  else {
8816
0
    S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8817
0
        << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8818
0
        << RHS.get()->getSourceRange();
8819
0
    return QualType();
8820
0
  }
8821
8822
0
  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8823
0
  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8824
0
  lhQual.removeCVRQualifiers();
8825
0
  rhQual.removeCVRQualifiers();
8826
8827
  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8828
  // (C99 6.7.3) for address spaces. We assume that the check should behave in
8829
  // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8830
  // qual types are compatible iff
8831
  //  * corresponded types are compatible
8832
  //  * CVR qualifiers are equal
8833
  //  * address spaces are equal
8834
  // Thus for conditional operator we merge CVR and address space unqualified
8835
  // pointees and if there is a composite type we return a pointer to it with
8836
  // merged qualifiers.
8837
0
  LHSCastKind =
8838
0
      LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8839
0
  RHSCastKind =
8840
0
      RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8841
0
  lhQual.removeAddressSpace();
8842
0
  rhQual.removeAddressSpace();
8843
8844
0
  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8845
0
  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8846
8847
0
  QualType CompositeTy = S.Context.mergeTypes(
8848
0
      lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8849
0
      /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8850
8851
0
  if (CompositeTy.isNull()) {
8852
    // In this situation, we assume void* type. No especially good
8853
    // reason, but this is what gcc does, and we do have to pick
8854
    // to get a consistent AST.
8855
0
    QualType incompatTy;
8856
0
    incompatTy = S.Context.getPointerType(
8857
0
        S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8858
0
    LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8859
0
    RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8860
8861
    // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8862
    // for casts between types with incompatible address space qualifiers.
8863
    // For the following code the compiler produces casts between global and
8864
    // local address spaces of the corresponded innermost pointees:
8865
    // local int *global *a;
8866
    // global int *global *b;
8867
    // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8868
0
    S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8869
0
        << LHSTy << RHSTy << LHS.get()->getSourceRange()
8870
0
        << RHS.get()->getSourceRange();
8871
8872
0
    return incompatTy;
8873
0
  }
8874
8875
  // The pointer types are compatible.
8876
  // In case of OpenCL ResultTy should have the address space qualifier
8877
  // which is a superset of address spaces of both the 2nd and the 3rd
8878
  // operands of the conditional operator.
8879
0
  QualType ResultTy = [&, ResultAddrSpace]() {
8880
0
    if (S.getLangOpts().OpenCL) {
8881
0
      Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8882
0
      CompositeQuals.setAddressSpace(ResultAddrSpace);
8883
0
      return S.Context
8884
0
          .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8885
0
          .withCVRQualifiers(MergedCVRQual);
8886
0
    }
8887
0
    return CompositeTy.withCVRQualifiers(MergedCVRQual);
8888
0
  }();
8889
0
  if (IsBlockPointer)
8890
0
    ResultTy = S.Context.getBlockPointerType(ResultTy);
8891
0
  else
8892
0
    ResultTy = S.Context.getPointerType(ResultTy);
8893
8894
0
  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8895
0
  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8896
0
  return ResultTy;
8897
0
}
8898
8899
/// Return the resulting type when the operands are both block pointers.
8900
static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8901
                                                          ExprResult &LHS,
8902
                                                          ExprResult &RHS,
8903
0
                                                          SourceLocation Loc) {
8904
0
  QualType LHSTy = LHS.get()->getType();
8905
0
  QualType RHSTy = RHS.get()->getType();
8906
8907
0
  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8908
0
    if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8909
0
      QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8910
0
      LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8911
0
      RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8912
0
      return destType;
8913
0
    }
8914
0
    S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8915
0
      << LHSTy << RHSTy << LHS.get()->getSourceRange()
8916
0
      << RHS.get()->getSourceRange();
8917
0
    return QualType();
8918
0
  }
8919
8920
  // We have 2 block pointer types.
8921
0
  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8922
0
}
8923
8924
/// Return the resulting type when the operands are both pointers.
8925
static QualType
8926
checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8927
                                            ExprResult &RHS,
8928
0
                                            SourceLocation Loc) {
8929
  // get the pointer types
8930
0
  QualType LHSTy = LHS.get()->getType();
8931
0
  QualType RHSTy = RHS.get()->getType();
8932
8933
  // get the "pointed to" types
8934
0
  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8935
0
  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8936
8937
  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8938
0
  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8939
    // Figure out necessary qualifiers (C99 6.5.15p6)
8940
0
    QualType destPointee
8941
0
      = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8942
0
    QualType destType = S.Context.getPointerType(destPointee);
8943
    // Add qualifiers if necessary.
8944
0
    LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8945
    // Promote to void*.
8946
0
    RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8947
0
    return destType;
8948
0
  }
8949
0
  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8950
0
    QualType destPointee
8951
0
      = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8952
0
    QualType destType = S.Context.getPointerType(destPointee);
8953
    // Add qualifiers if necessary.
8954
0
    RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8955
    // Promote to void*.
8956
0
    LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8957
0
    return destType;
8958
0
  }
8959
8960
0
  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8961
0
}
8962
8963
/// Return false if the first expression is not an integer and the second
8964
/// expression is not a pointer, true otherwise.
8965
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8966
                                        Expr* PointerExpr, SourceLocation Loc,
8967
0
                                        bool IsIntFirstExpr) {
8968
0
  if (!PointerExpr->getType()->isPointerType() ||
8969
0
      !Int.get()->getType()->isIntegerType())
8970
0
    return false;
8971
8972
0
  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8973
0
  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8974
8975
0
  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8976
0
    << Expr1->getType() << Expr2->getType()
8977
0
    << Expr1->getSourceRange() << Expr2->getSourceRange();
8978
0
  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8979
0
                            CK_IntegralToPointer);
8980
0
  return true;
8981
0
}
8982
8983
/// Simple conversion between integer and floating point types.
8984
///
8985
/// Used when handling the OpenCL conditional operator where the
8986
/// condition is a vector while the other operands are scalar.
8987
///
8988
/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8989
/// types are either integer or floating type. Between the two
8990
/// operands, the type with the higher rank is defined as the "result
8991
/// type". The other operand needs to be promoted to the same type. No
8992
/// other type promotion is allowed. We cannot use
8993
/// UsualArithmeticConversions() for this purpose, since it always
8994
/// promotes promotable types.
8995
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8996
                                            ExprResult &RHS,
8997
0
                                            SourceLocation QuestionLoc) {
8998
0
  LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8999
0
  if (LHS.isInvalid())
9000
0
    return QualType();
9001
0
  RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9002
0
  if (RHS.isInvalid())
9003
0
    return QualType();
9004
9005
  // For conversion purposes, we ignore any qualifiers.
9006
  // For example, "const float" and "float" are equivalent.
9007
0
  QualType LHSType =
9008
0
    S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
9009
0
  QualType RHSType =
9010
0
    S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
9011
9012
0
  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
9013
0
    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
9014
0
      << LHSType << LHS.get()->getSourceRange();
9015
0
    return QualType();
9016
0
  }
9017
9018
0
  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
9019
0
    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
9020
0
      << RHSType << RHS.get()->getSourceRange();
9021
0
    return QualType();
9022
0
  }
9023
9024
  // If both types are identical, no conversion is needed.
9025
0
  if (LHSType == RHSType)
9026
0
    return LHSType;
9027
9028
  // Now handle "real" floating types (i.e. float, double, long double).
9029
0
  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
9030
0
    return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
9031
0
                                 /*IsCompAssign = */ false);
9032
9033
  // Finally, we have two differing integer types.
9034
0
  return handleIntegerConversion<doIntegralCast, doIntegralCast>
9035
0
  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
9036
0
}
9037
9038
/// Convert scalar operands to a vector that matches the
9039
///        condition in length.
9040
///
9041
/// Used when handling the OpenCL conditional operator where the
9042
/// condition is a vector while the other operands are scalar.
9043
///
9044
/// We first compute the "result type" for the scalar operands
9045
/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
9046
/// into a vector of that type where the length matches the condition
9047
/// vector type. s6.11.6 requires that the element types of the result
9048
/// and the condition must have the same number of bits.
9049
static QualType
9050
OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
9051
0
                              QualType CondTy, SourceLocation QuestionLoc) {
9052
0
  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
9053
0
  if (ResTy.isNull()) return QualType();
9054
9055
0
  const VectorType *CV = CondTy->getAs<VectorType>();
9056
0
  assert(CV);
9057
9058
  // Determine the vector result type
9059
0
  unsigned NumElements = CV->getNumElements();
9060
0
  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
9061
9062
  // Ensure that all types have the same number of bits
9063
0
  if (S.Context.getTypeSize(CV->getElementType())
9064
0
      != S.Context.getTypeSize(ResTy)) {
9065
    // Since VectorTy is created internally, it does not pretty print
9066
    // with an OpenCL name. Instead, we just print a description.
9067
0
    std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
9068
0
    SmallString<64> Str;
9069
0
    llvm::raw_svector_ostream OS(Str);
9070
0
    OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
9071
0
    S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9072
0
      << CondTy << OS.str();
9073
0
    return QualType();
9074
0
  }
9075
9076
  // Convert operands to the vector result type
9077
0
  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
9078
0
  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
9079
9080
0
  return VectorTy;
9081
0
}
9082
9083
/// Return false if this is a valid OpenCL condition vector
9084
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
9085
0
                                       SourceLocation QuestionLoc) {
9086
  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9087
  // integral type.
9088
0
  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
9089
0
  assert(CondTy);
9090
0
  QualType EleTy = CondTy->getElementType();
9091
0
  if (EleTy->isIntegerType()) return false;
9092
9093
0
  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
9094
0
    << Cond->getType() << Cond->getSourceRange();
9095
0
  return true;
9096
0
}
9097
9098
/// Return false if the vector condition type and the vector
9099
///        result type are compatible.
9100
///
9101
/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9102
/// number of elements, and their element types have the same number
9103
/// of bits.
9104
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
9105
0
                              SourceLocation QuestionLoc) {
9106
0
  const VectorType *CV = CondTy->getAs<VectorType>();
9107
0
  const VectorType *RV = VecResTy->getAs<VectorType>();
9108
0
  assert(CV && RV);
9109
9110
0
  if (CV->getNumElements() != RV->getNumElements()) {
9111
0
    S.Diag(QuestionLoc, diag::err_conditional_vector_size)
9112
0
      << CondTy << VecResTy;
9113
0
    return true;
9114
0
  }
9115
9116
0
  QualType CVE = CV->getElementType();
9117
0
  QualType RVE = RV->getElementType();
9118
9119
0
  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
9120
0
    S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9121
0
      << CondTy << VecResTy;
9122
0
    return true;
9123
0
  }
9124
9125
0
  return false;
9126
0
}
9127
9128
/// Return the resulting type for the conditional operator in
9129
///        OpenCL (aka "ternary selection operator", OpenCL v1.1
9130
///        s6.3.i) when the condition is a vector type.
9131
static QualType
9132
OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9133
                             ExprResult &LHS, ExprResult &RHS,
9134
0
                             SourceLocation QuestionLoc) {
9135
0
  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
9136
0
  if (Cond.isInvalid())
9137
0
    return QualType();
9138
0
  QualType CondTy = Cond.get()->getType();
9139
9140
0
  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
9141
0
    return QualType();
9142
9143
  // If either operand is a vector then find the vector type of the
9144
  // result as specified in OpenCL v1.1 s6.3.i.
9145
0
  if (LHS.get()->getType()->isVectorType() ||
9146
0
      RHS.get()->getType()->isVectorType()) {
9147
0
    bool IsBoolVecLang =
9148
0
        !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9149
0
    QualType VecResTy =
9150
0
        S.CheckVectorOperands(LHS, RHS, QuestionLoc,
9151
0
                              /*isCompAssign*/ false,
9152
0
                              /*AllowBothBool*/ true,
9153
0
                              /*AllowBoolConversions*/ false,
9154
0
                              /*AllowBooleanOperation*/ IsBoolVecLang,
9155
0
                              /*ReportInvalid*/ true);
9156
0
    if (VecResTy.isNull())
9157
0
      return QualType();
9158
    // The result type must match the condition type as specified in
9159
    // OpenCL v1.1 s6.11.6.
9160
0
    if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9161
0
      return QualType();
9162
0
    return VecResTy;
9163
0
  }
9164
9165
  // Both operands are scalar.
9166
0
  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9167
0
}
9168
9169
/// Return true if the Expr is block type
9170
0
static bool checkBlockType(Sema &S, const Expr *E) {
9171
0
  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9172
0
    QualType Ty = CE->getCallee()->getType();
9173
0
    if (Ty->isBlockPointerType()) {
9174
0
      S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9175
0
      return true;
9176
0
    }
9177
0
  }
9178
0
  return false;
9179
0
}
9180
9181
/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9182
/// In that case, LHS = cond.
9183
/// C99 6.5.15
9184
QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9185
                                        ExprResult &RHS, ExprValueKind &VK,
9186
                                        ExprObjectKind &OK,
9187
2
                                        SourceLocation QuestionLoc) {
9188
9189
2
  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9190
2
  if (!LHSResult.isUsable()) return QualType();
9191
2
  LHS = LHSResult;
9192
9193
2
  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9194
2
  if (!RHSResult.isUsable()) return QualType();
9195
2
  RHS = RHSResult;
9196
9197
  // C++ is sufficiently different to merit its own checker.
9198
2
  if (getLangOpts().CPlusPlus)
9199
2
    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9200
9201
0
  VK = VK_PRValue;
9202
0
  OK = OK_Ordinary;
9203
9204
0
  if (Context.isDependenceAllowed() &&
9205
0
      (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9206
0
       RHS.get()->isTypeDependent())) {
9207
0
    assert(!getLangOpts().CPlusPlus);
9208
0
    assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9209
0
            RHS.get()->containsErrors()) &&
9210
0
           "should only occur in error-recovery path.");
9211
0
    return Context.DependentTy;
9212
0
  }
9213
9214
  // The OpenCL operator with a vector condition is sufficiently
9215
  // different to merit its own checker.
9216
0
  if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9217
0
      Cond.get()->getType()->isExtVectorType())
9218
0
    return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9219
9220
  // First, check the condition.
9221
0
  Cond = UsualUnaryConversions(Cond.get());
9222
0
  if (Cond.isInvalid())
9223
0
    return QualType();
9224
0
  if (checkCondition(*this, Cond.get(), QuestionLoc))
9225
0
    return QualType();
9226
9227
  // Handle vectors.
9228
0
  if (LHS.get()->getType()->isVectorType() ||
9229
0
      RHS.get()->getType()->isVectorType())
9230
0
    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9231
0
                               /*AllowBothBool*/ true,
9232
0
                               /*AllowBoolConversions*/ false,
9233
0
                               /*AllowBooleanOperation*/ false,
9234
0
                               /*ReportInvalid*/ true);
9235
9236
0
  QualType ResTy =
9237
0
      UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
9238
0
  if (LHS.isInvalid() || RHS.isInvalid())
9239
0
    return QualType();
9240
9241
  // WebAssembly tables are not allowed as conditional LHS or RHS.
9242
0
  QualType LHSTy = LHS.get()->getType();
9243
0
  QualType RHSTy = RHS.get()->getType();
9244
0
  if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9245
0
    Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9246
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9247
0
    return QualType();
9248
0
  }
9249
9250
  // Diagnose attempts to convert between __ibm128, __float128 and long double
9251
  // where such conversions currently can't be handled.
9252
0
  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9253
0
    Diag(QuestionLoc,
9254
0
         diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9255
0
      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9256
0
    return QualType();
9257
0
  }
9258
9259
  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9260
  // selection operator (?:).
9261
0
  if (getLangOpts().OpenCL &&
9262
0
      ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9263
0
    return QualType();
9264
0
  }
9265
9266
  // If both operands have arithmetic type, do the usual arithmetic conversions
9267
  // to find a common type: C99 6.5.15p3,5.
9268
0
  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9269
    // Disallow invalid arithmetic conversions, such as those between bit-
9270
    // precise integers types of different sizes, or between a bit-precise
9271
    // integer and another type.
9272
0
    if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9273
0
      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9274
0
          << LHSTy << RHSTy << LHS.get()->getSourceRange()
9275
0
          << RHS.get()->getSourceRange();
9276
0
      return QualType();
9277
0
    }
9278
9279
0
    LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9280
0
    RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9281
9282
0
    return ResTy;
9283
0
  }
9284
9285
  // If both operands are the same structure or union type, the result is that
9286
  // type.
9287
0
  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
9288
0
    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9289
0
      if (LHSRT->getDecl() == RHSRT->getDecl())
9290
        // "If both the operands have structure or union type, the result has
9291
        // that type."  This implies that CV qualifiers are dropped.
9292
0
        return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9293
0
                                            RHSTy.getUnqualifiedType());
9294
    // FIXME: Type of conditional expression must be complete in C mode.
9295
0
  }
9296
9297
  // C99 6.5.15p5: "If both operands have void type, the result has void type."
9298
  // The following || allows only one side to be void (a GCC-ism).
9299
0
  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9300
0
    QualType ResTy;
9301
0
    if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9302
0
      ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
9303
0
    } else if (RHSTy->isVoidType()) {
9304
0
      ResTy = RHSTy;
9305
0
      Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9306
0
          << RHS.get()->getSourceRange();
9307
0
    } else {
9308
0
      ResTy = LHSTy;
9309
0
      Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9310
0
          << LHS.get()->getSourceRange();
9311
0
    }
9312
0
    LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9313
0
    RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9314
0
    return ResTy;
9315
0
  }
9316
9317
  // C23 6.5.15p7:
9318
  //   ... if both the second and third operands have nullptr_t type, the
9319
  //   result also has that type.
9320
0
  if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9321
0
    return ResTy;
9322
9323
  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9324
  // the type of the other operand."
9325
0
  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9326
0
  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9327
9328
  // All objective-c pointer type analysis is done here.
9329
0
  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9330
0
                                                        QuestionLoc);
9331
0
  if (LHS.isInvalid() || RHS.isInvalid())
9332
0
    return QualType();
9333
0
  if (!compositeType.isNull())
9334
0
    return compositeType;
9335
9336
9337
  // Handle block pointer types.
9338
0
  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9339
0
    return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9340
0
                                                     QuestionLoc);
9341
9342
  // Check constraints for C object pointers types (C99 6.5.15p3,6).
9343
0
  if (LHSTy->isPointerType() && RHSTy->isPointerType())
9344
0
    return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9345
0
                                                       QuestionLoc);
9346
9347
  // GCC compatibility: soften pointer/integer mismatch.  Note that
9348
  // null pointers have been filtered out by this point.
9349
0
  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9350
0
      /*IsIntFirstExpr=*/true))
9351
0
    return RHSTy;
9352
0
  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9353
0
      /*IsIntFirstExpr=*/false))
9354
0
    return LHSTy;
9355
9356
  // Emit a better diagnostic if one of the expressions is a null pointer
9357
  // constant and the other is not a pointer type. In this case, the user most
9358
  // likely forgot to take the address of the other expression.
9359
0
  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9360
0
    return QualType();
9361
9362
  // Finally, if the LHS and RHS types are canonically the same type, we can
9363
  // use the common sugared type.
9364
0
  if (Context.hasSameType(LHSTy, RHSTy))
9365
0
    return Context.getCommonSugaredType(LHSTy, RHSTy);
9366
9367
  // Otherwise, the operands are not compatible.
9368
0
  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9369
0
    << LHSTy << RHSTy << LHS.get()->getSourceRange()
9370
0
    << RHS.get()->getSourceRange();
9371
0
  return QualType();
9372
0
}
9373
9374
/// FindCompositeObjCPointerType - Helper method to find composite type of
9375
/// two objective-c pointer types of the two input expressions.
9376
QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9377
0
                                            SourceLocation QuestionLoc) {
9378
0
  QualType LHSTy = LHS.get()->getType();
9379
0
  QualType RHSTy = RHS.get()->getType();
9380
9381
  // Handle things like Class and struct objc_class*.  Here we case the result
9382
  // to the pseudo-builtin, because that will be implicitly cast back to the
9383
  // redefinition type if an attempt is made to access its fields.
9384
0
  if (LHSTy->isObjCClassType() &&
9385
0
      (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9386
0
    RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9387
0
    return LHSTy;
9388
0
  }
9389
0
  if (RHSTy->isObjCClassType() &&
9390
0
      (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9391
0
    LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9392
0
    return RHSTy;
9393
0
  }
9394
  // And the same for struct objc_object* / id
9395
0
  if (LHSTy->isObjCIdType() &&
9396
0
      (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9397
0
    RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9398
0
    return LHSTy;
9399
0
  }
9400
0
  if (RHSTy->isObjCIdType() &&
9401
0
      (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9402
0
    LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9403
0
    return RHSTy;
9404
0
  }
9405
  // And the same for struct objc_selector* / SEL
9406
0
  if (Context.isObjCSelType(LHSTy) &&
9407
0
      (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9408
0
    RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9409
0
    return LHSTy;
9410
0
  }
9411
0
  if (Context.isObjCSelType(RHSTy) &&
9412
0
      (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9413
0
    LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9414
0
    return RHSTy;
9415
0
  }
9416
  // Check constraints for Objective-C object pointers types.
9417
0
  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9418
9419
0
    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9420
      // Two identical object pointer types are always compatible.
9421
0
      return LHSTy;
9422
0
    }
9423
0
    const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9424
0
    const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9425
0
    QualType compositeType = LHSTy;
9426
9427
    // If both operands are interfaces and either operand can be
9428
    // assigned to the other, use that type as the composite
9429
    // type. This allows
9430
    //   xxx ? (A*) a : (B*) b
9431
    // where B is a subclass of A.
9432
    //
9433
    // Additionally, as for assignment, if either type is 'id'
9434
    // allow silent coercion. Finally, if the types are
9435
    // incompatible then make sure to use 'id' as the composite
9436
    // type so the result is acceptable for sending messages to.
9437
9438
    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9439
    // It could return the composite type.
9440
0
    if (!(compositeType =
9441
0
          Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9442
      // Nothing more to do.
9443
0
    } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9444
0
      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9445
0
    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9446
0
      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9447
0
    } else if ((LHSOPT->isObjCQualifiedIdType() ||
9448
0
                RHSOPT->isObjCQualifiedIdType()) &&
9449
0
               Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9450
0
                                                         true)) {
9451
      // Need to handle "id<xx>" explicitly.
9452
      // GCC allows qualified id and any Objective-C type to devolve to
9453
      // id. Currently localizing to here until clear this should be
9454
      // part of ObjCQualifiedIdTypesAreCompatible.
9455
0
      compositeType = Context.getObjCIdType();
9456
0
    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9457
0
      compositeType = Context.getObjCIdType();
9458
0
    } else {
9459
0
      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9460
0
      << LHSTy << RHSTy
9461
0
      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9462
0
      QualType incompatTy = Context.getObjCIdType();
9463
0
      LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9464
0
      RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9465
0
      return incompatTy;
9466
0
    }
9467
    // The object pointer types are compatible.
9468
0
    LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9469
0
    RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9470
0
    return compositeType;
9471
0
  }
9472
  // Check Objective-C object pointer types and 'void *'
9473
0
  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9474
0
    if (getLangOpts().ObjCAutoRefCount) {
9475
      // ARC forbids the implicit conversion of object pointers to 'void *',
9476
      // so these types are not compatible.
9477
0
      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9478
0
          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9479
0
      LHS = RHS = true;
9480
0
      return QualType();
9481
0
    }
9482
0
    QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9483
0
    QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9484
0
    QualType destPointee
9485
0
    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9486
0
    QualType destType = Context.getPointerType(destPointee);
9487
    // Add qualifiers if necessary.
9488
0
    LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9489
    // Promote to void*.
9490
0
    RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9491
0
    return destType;
9492
0
  }
9493
0
  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9494
0
    if (getLangOpts().ObjCAutoRefCount) {
9495
      // ARC forbids the implicit conversion of object pointers to 'void *',
9496
      // so these types are not compatible.
9497
0
      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9498
0
          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9499
0
      LHS = RHS = true;
9500
0
      return QualType();
9501
0
    }
9502
0
    QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9503
0
    QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9504
0
    QualType destPointee
9505
0
    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9506
0
    QualType destType = Context.getPointerType(destPointee);
9507
    // Add qualifiers if necessary.
9508
0
    RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9509
    // Promote to void*.
9510
0
    LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9511
0
    return destType;
9512
0
  }
9513
0
  return QualType();
9514
0
}
9515
9516
/// SuggestParentheses - Emit a note with a fixit hint that wraps
9517
/// ParenRange in parentheses.
9518
static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9519
                               const PartialDiagnostic &Note,
9520
0
                               SourceRange ParenRange) {
9521
0
  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9522
0
  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9523
0
      EndLoc.isValid()) {
9524
0
    Self.Diag(Loc, Note)
9525
0
      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9526
0
      << FixItHint::CreateInsertion(EndLoc, ")");
9527
0
  } else {
9528
    // We can't display the parentheses, so just show the bare note.
9529
0
    Self.Diag(Loc, Note) << ParenRange;
9530
0
  }
9531
0
}
9532
9533
0
static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9534
0
  return BinaryOperator::isAdditiveOp(Opc) ||
9535
0
         BinaryOperator::isMultiplicativeOp(Opc) ||
9536
0
         BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9537
  // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9538
  // not any of the logical operators.  Bitwise-xor is commonly used as a
9539
  // logical-xor because there is no logical-xor operator.  The logical
9540
  // operators, including uses of xor, have a high false positive rate for
9541
  // precedence warnings.
9542
0
}
9543
9544
/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9545
/// expression, either using a built-in or overloaded operator,
9546
/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9547
/// expression.
9548
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9549
2
                                   const Expr **RHSExprs) {
9550
  // Don't strip parenthesis: we should not warn if E is in parenthesis.
9551
2
  E = E->IgnoreImpCasts();
9552
2
  E = E->IgnoreConversionOperatorSingleStep();
9553
2
  E = E->IgnoreImpCasts();
9554
2
  if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9555
0
    E = MTE->getSubExpr();
9556
0
    E = E->IgnoreImpCasts();
9557
0
  }
9558
9559
  // Built-in binary operator.
9560
2
  if (const auto *OP = dyn_cast<BinaryOperator>(E);
9561
2
      OP && IsArithmeticOp(OP->getOpcode())) {
9562
0
    *Opcode = OP->getOpcode();
9563
0
    *RHSExprs = OP->getRHS();
9564
0
    return true;
9565
0
  }
9566
9567
  // Overloaded operator.
9568
2
  if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9569
0
    if (Call->getNumArgs() != 2)
9570
0
      return false;
9571
9572
    // Make sure this is really a binary operator that is safe to pass into
9573
    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9574
0
    OverloadedOperatorKind OO = Call->getOperator();
9575
0
    if (OO < OO_Plus || OO > OO_Arrow ||
9576
0
        OO == OO_PlusPlus || OO == OO_MinusMinus)
9577
0
      return false;
9578
9579
0
    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9580
0
    if (IsArithmeticOp(OpKind)) {
9581
0
      *Opcode = OpKind;
9582
0
      *RHSExprs = Call->getArg(1);
9583
0
      return true;
9584
0
    }
9585
0
  }
9586
9587
2
  return false;
9588
2
}
9589
9590
/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9591
/// or is a logical expression such as (x==y) which has int type, but is
9592
/// commonly interpreted as boolean.
9593
0
static bool ExprLooksBoolean(const Expr *E) {
9594
0
  E = E->IgnoreParenImpCasts();
9595
9596
0
  if (E->getType()->isBooleanType())
9597
0
    return true;
9598
0
  if (const auto *OP = dyn_cast<BinaryOperator>(E))
9599
0
    return OP->isComparisonOp() || OP->isLogicalOp();
9600
0
  if (const auto *OP = dyn_cast<UnaryOperator>(E))
9601
0
    return OP->getOpcode() == UO_LNot;
9602
0
  if (E->getType()->isPointerType())
9603
0
    return true;
9604
  // FIXME: What about overloaded operator calls returning "unspecified boolean
9605
  // type"s (commonly pointer-to-members)?
9606
9607
0
  return false;
9608
0
}
9609
9610
/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9611
/// and binary operator are mixed in a way that suggests the programmer assumed
9612
/// the conditional operator has higher precedence, for example:
9613
/// "int x = a + someBinaryCondition ? 1 : 2".
9614
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9615
                                          Expr *Condition, const Expr *LHSExpr,
9616
2
                                          const Expr *RHSExpr) {
9617
2
  BinaryOperatorKind CondOpcode;
9618
2
  const Expr *CondRHS;
9619
9620
2
  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9621
2
    return;
9622
0
  if (!ExprLooksBoolean(CondRHS))
9623
0
    return;
9624
9625
  // The condition is an arithmetic binary expression, with a right-
9626
  // hand side that looks boolean, so warn.
9627
9628
0
  unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9629
0
                        ? diag::warn_precedence_bitwise_conditional
9630
0
                        : diag::warn_precedence_conditional;
9631
9632
0
  Self.Diag(OpLoc, DiagID)
9633
0
      << Condition->getSourceRange()
9634
0
      << BinaryOperator::getOpcodeStr(CondOpcode);
9635
9636
0
  SuggestParentheses(
9637
0
      Self, OpLoc,
9638
0
      Self.PDiag(diag::note_precedence_silence)
9639
0
          << BinaryOperator::getOpcodeStr(CondOpcode),
9640
0
      SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9641
9642
0
  SuggestParentheses(Self, OpLoc,
9643
0
                     Self.PDiag(diag::note_precedence_conditional_first),
9644
0
                     SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9645
0
}
9646
9647
/// Compute the nullability of a conditional expression.
9648
static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9649
                                              QualType LHSTy, QualType RHSTy,
9650
2
                                              ASTContext &Ctx) {
9651
2
  if (!ResTy->isAnyPointerType())
9652
2
    return ResTy;
9653
9654
0
  auto GetNullability = [](QualType Ty) {
9655
0
    std::optional<NullabilityKind> Kind = Ty->getNullability();
9656
0
    if (Kind) {
9657
      // For our purposes, treat _Nullable_result as _Nullable.
9658
0
      if (*Kind == NullabilityKind::NullableResult)
9659
0
        return NullabilityKind::Nullable;
9660
0
      return *Kind;
9661
0
    }
9662
0
    return NullabilityKind::Unspecified;
9663
0
  };
9664
9665
0
  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9666
0
  NullabilityKind MergedKind;
9667
9668
  // Compute nullability of a binary conditional expression.
9669
0
  if (IsBin) {
9670
0
    if (LHSKind == NullabilityKind::NonNull)
9671
0
      MergedKind = NullabilityKind::NonNull;
9672
0
    else
9673
0
      MergedKind = RHSKind;
9674
  // Compute nullability of a normal conditional expression.
9675
0
  } else {
9676
0
    if (LHSKind == NullabilityKind::Nullable ||
9677
0
        RHSKind == NullabilityKind::Nullable)
9678
0
      MergedKind = NullabilityKind::Nullable;
9679
0
    else if (LHSKind == NullabilityKind::NonNull)
9680
0
      MergedKind = RHSKind;
9681
0
    else if (RHSKind == NullabilityKind::NonNull)
9682
0
      MergedKind = LHSKind;
9683
0
    else
9684
0
      MergedKind = NullabilityKind::Unspecified;
9685
0
  }
9686
9687
  // Return if ResTy already has the correct nullability.
9688
0
  if (GetNullability(ResTy) == MergedKind)
9689
0
    return ResTy;
9690
9691
  // Strip all nullability from ResTy.
9692
0
  while (ResTy->getNullability())
9693
0
    ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9694
9695
  // Create a new AttributedType with the new nullability kind.
9696
0
  auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9697
0
  return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9698
0
}
9699
9700
/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
9701
/// in the case of a the GNU conditional expr extension.
9702
ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9703
                                    SourceLocation ColonLoc,
9704
                                    Expr *CondExpr, Expr *LHSExpr,
9705
2
                                    Expr *RHSExpr) {
9706
2
  if (!Context.isDependenceAllowed()) {
9707
    // C cannot handle TypoExpr nodes in the condition because it
9708
    // doesn't handle dependent types properly, so make sure any TypoExprs have
9709
    // been dealt with before checking the operands.
9710
0
    ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9711
0
    ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9712
0
    ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9713
9714
0
    if (!CondResult.isUsable())
9715
0
      return ExprError();
9716
9717
0
    if (LHSExpr) {
9718
0
      if (!LHSResult.isUsable())
9719
0
        return ExprError();
9720
0
    }
9721
9722
0
    if (!RHSResult.isUsable())
9723
0
      return ExprError();
9724
9725
0
    CondExpr = CondResult.get();
9726
0
    LHSExpr = LHSResult.get();
9727
0
    RHSExpr = RHSResult.get();
9728
0
  }
9729
9730
  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9731
  // was the condition.
9732
2
  OpaqueValueExpr *opaqueValue = nullptr;
9733
2
  Expr *commonExpr = nullptr;
9734
2
  if (!LHSExpr) {
9735
0
    commonExpr = CondExpr;
9736
    // Lower out placeholder types first.  This is important so that we don't
9737
    // try to capture a placeholder. This happens in few cases in C++; such
9738
    // as Objective-C++'s dictionary subscripting syntax.
9739
0
    if (commonExpr->hasPlaceholderType()) {
9740
0
      ExprResult result = CheckPlaceholderExpr(commonExpr);
9741
0
      if (!result.isUsable()) return ExprError();
9742
0
      commonExpr = result.get();
9743
0
    }
9744
    // We usually want to apply unary conversions *before* saving, except
9745
    // in the special case of a C++ l-value conditional.
9746
0
    if (!(getLangOpts().CPlusPlus
9747
0
          && !commonExpr->isTypeDependent()
9748
0
          && commonExpr->getValueKind() == RHSExpr->getValueKind()
9749
0
          && commonExpr->isGLValue()
9750
0
          && commonExpr->isOrdinaryOrBitFieldObject()
9751
0
          && RHSExpr->isOrdinaryOrBitFieldObject()
9752
0
          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9753
0
      ExprResult commonRes = UsualUnaryConversions(commonExpr);
9754
0
      if (commonRes.isInvalid())
9755
0
        return ExprError();
9756
0
      commonExpr = commonRes.get();
9757
0
    }
9758
9759
    // If the common expression is a class or array prvalue, materialize it
9760
    // so that we can safely refer to it multiple times.
9761
0
    if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9762
0
                                    commonExpr->getType()->isArrayType())) {
9763
0
      ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9764
0
      if (MatExpr.isInvalid())
9765
0
        return ExprError();
9766
0
      commonExpr = MatExpr.get();
9767
0
    }
9768
9769
0
    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9770
0
                                                commonExpr->getType(),
9771
0
                                                commonExpr->getValueKind(),
9772
0
                                                commonExpr->getObjectKind(),
9773
0
                                                commonExpr);
9774
0
    LHSExpr = CondExpr = opaqueValue;
9775
0
  }
9776
9777
2
  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9778
2
  ExprValueKind VK = VK_PRValue;
9779
2
  ExprObjectKind OK = OK_Ordinary;
9780
2
  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9781
2
  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9782
2
                                             VK, OK, QuestionLoc);
9783
2
  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9784
2
      RHS.isInvalid())
9785
0
    return ExprError();
9786
9787
2
  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9788
2
                                RHS.get());
9789
9790
2
  CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9791
9792
2
  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9793
2
                                         Context);
9794
9795
2
  if (!commonExpr)
9796
2
    return new (Context)
9797
2
        ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9798
2
                            RHS.get(), result, VK, OK);
9799
9800
0
  return new (Context) BinaryConditionalOperator(
9801
0
      commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9802
0
      ColonLoc, result, VK, OK);
9803
2
}
9804
9805
// Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9806
0
bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9807
0
  unsigned FromAttributes = 0, ToAttributes = 0;
9808
0
  if (const auto *FromFn =
9809
0
          dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9810
0
    FromAttributes =
9811
0
        FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9812
0
  if (const auto *ToFn =
9813
0
          dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9814
0
    ToAttributes =
9815
0
        ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9816
9817
0
  return FromAttributes != ToAttributes;
9818
0
}
9819
9820
// Check if we have a conversion between incompatible cmse function pointer
9821
// types, that is, a conversion between a function pointer with the
9822
// cmse_nonsecure_call attribute and one without.
9823
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9824
0
                                          QualType ToType) {
9825
0
  if (const auto *ToFn =
9826
0
          dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9827
0
    if (const auto *FromFn =
9828
0
            dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9829
0
      FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9830
0
      FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9831
9832
0
      return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9833
0
    }
9834
0
  }
9835
0
  return false;
9836
0
}
9837
9838
// checkPointerTypesForAssignment - This is a very tricky routine (despite
9839
// being closely modeled after the C99 spec:-). The odd characteristic of this
9840
// routine is it effectively iqnores the qualifiers on the top level pointee.
9841
// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9842
// FIXME: add a couple examples in this comment.
9843
static Sema::AssignConvertType
9844
checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9845
0
                               SourceLocation Loc) {
9846
0
  assert(LHSType.isCanonical() && "LHS not canonicalized!");
9847
0
  assert(RHSType.isCanonical() && "RHS not canonicalized!");
9848
9849
  // get the "pointed to" type (ignoring qualifiers at the top level)
9850
0
  const Type *lhptee, *rhptee;
9851
0
  Qualifiers lhq, rhq;
9852
0
  std::tie(lhptee, lhq) =
9853
0
      cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9854
0
  std::tie(rhptee, rhq) =
9855
0
      cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9856
9857
0
  Sema::AssignConvertType ConvTy = Sema::Compatible;
9858
9859
  // C99 6.5.16.1p1: This following citation is common to constraints
9860
  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9861
  // qualifiers of the type *pointed to* by the right;
9862
9863
  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9864
0
  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9865
0
      lhq.compatiblyIncludesObjCLifetime(rhq)) {
9866
    // Ignore lifetime for further calculation.
9867
0
    lhq.removeObjCLifetime();
9868
0
    rhq.removeObjCLifetime();
9869
0
  }
9870
9871
0
  if (!lhq.compatiblyIncludes(rhq)) {
9872
    // Treat address-space mismatches as fatal.
9873
0
    if (!lhq.isAddressSpaceSupersetOf(rhq))
9874
0
      return Sema::IncompatiblePointerDiscardsQualifiers;
9875
9876
    // It's okay to add or remove GC or lifetime qualifiers when converting to
9877
    // and from void*.
9878
0
    else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9879
0
                        .compatiblyIncludes(
9880
0
                                rhq.withoutObjCGCAttr().withoutObjCLifetime())
9881
0
             && (lhptee->isVoidType() || rhptee->isVoidType()))
9882
0
      ; // keep old
9883
9884
    // Treat lifetime mismatches as fatal.
9885
0
    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9886
0
      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9887
9888
    // For GCC/MS compatibility, other qualifier mismatches are treated
9889
    // as still compatible in C.
9890
0
    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9891
0
  }
9892
9893
  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9894
  // incomplete type and the other is a pointer to a qualified or unqualified
9895
  // version of void...
9896
0
  if (lhptee->isVoidType()) {
9897
0
    if (rhptee->isIncompleteOrObjectType())
9898
0
      return ConvTy;
9899
9900
    // As an extension, we allow cast to/from void* to function pointer.
9901
0
    assert(rhptee->isFunctionType());
9902
0
    return Sema::FunctionVoidPointer;
9903
0
  }
9904
9905
0
  if (rhptee->isVoidType()) {
9906
0
    if (lhptee->isIncompleteOrObjectType())
9907
0
      return ConvTy;
9908
9909
    // As an extension, we allow cast to/from void* to function pointer.
9910
0
    assert(lhptee->isFunctionType());
9911
0
    return Sema::FunctionVoidPointer;
9912
0
  }
9913
9914
0
  if (!S.Diags.isIgnored(
9915
0
          diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9916
0
          Loc) &&
9917
0
      RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9918
0
      !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9919
0
    return Sema::IncompatibleFunctionPointerStrict;
9920
9921
  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9922
  // unqualified versions of compatible types, ...
9923
0
  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9924
0
  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9925
    // Check if the pointee types are compatible ignoring the sign.
9926
    // We explicitly check for char so that we catch "char" vs
9927
    // "unsigned char" on systems where "char" is unsigned.
9928
0
    if (lhptee->isCharType())
9929
0
      ltrans = S.Context.UnsignedCharTy;
9930
0
    else if (lhptee->hasSignedIntegerRepresentation())
9931
0
      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9932
9933
0
    if (rhptee->isCharType())
9934
0
      rtrans = S.Context.UnsignedCharTy;
9935
0
    else if (rhptee->hasSignedIntegerRepresentation())
9936
0
      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9937
9938
0
    if (ltrans == rtrans) {
9939
      // Types are compatible ignoring the sign. Qualifier incompatibility
9940
      // takes priority over sign incompatibility because the sign
9941
      // warning can be disabled.
9942
0
      if (ConvTy != Sema::Compatible)
9943
0
        return ConvTy;
9944
9945
0
      return Sema::IncompatiblePointerSign;
9946
0
    }
9947
9948
    // If we are a multi-level pointer, it's possible that our issue is simply
9949
    // one of qualification - e.g. char ** -> const char ** is not allowed. If
9950
    // the eventual target type is the same and the pointers have the same
9951
    // level of indirection, this must be the issue.
9952
0
    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9953
0
      do {
9954
0
        std::tie(lhptee, lhq) =
9955
0
          cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9956
0
        std::tie(rhptee, rhq) =
9957
0
          cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9958
9959
        // Inconsistent address spaces at this point is invalid, even if the
9960
        // address spaces would be compatible.
9961
        // FIXME: This doesn't catch address space mismatches for pointers of
9962
        // different nesting levels, like:
9963
        //   __local int *** a;
9964
        //   int ** b = a;
9965
        // It's not clear how to actually determine when such pointers are
9966
        // invalidly incompatible.
9967
0
        if (lhq.getAddressSpace() != rhq.getAddressSpace())
9968
0
          return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9969
9970
0
      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9971
9972
0
      if (lhptee == rhptee)
9973
0
        return Sema::IncompatibleNestedPointerQualifiers;
9974
0
    }
9975
9976
    // General pointer incompatibility takes priority over qualifiers.
9977
0
    if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9978
0
      return Sema::IncompatibleFunctionPointer;
9979
0
    return Sema::IncompatiblePointer;
9980
0
  }
9981
0
  if (!S.getLangOpts().CPlusPlus &&
9982
0
      S.IsFunctionConversion(ltrans, rtrans, ltrans))
9983
0
    return Sema::IncompatibleFunctionPointer;
9984
0
  if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9985
0
    return Sema::IncompatibleFunctionPointer;
9986
0
  if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9987
0
    return Sema::IncompatibleFunctionPointer;
9988
0
  return ConvTy;
9989
0
}
9990
9991
/// checkBlockPointerTypesForAssignment - This routine determines whether two
9992
/// block pointer types are compatible or whether a block and normal pointer
9993
/// are compatible. It is more restrict than comparing two function pointer
9994
// types.
9995
static Sema::AssignConvertType
9996
checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9997
0
                                    QualType RHSType) {
9998
0
  assert(LHSType.isCanonical() && "LHS not canonicalized!");
9999
0
  assert(RHSType.isCanonical() && "RHS not canonicalized!");
10000
10001
0
  QualType lhptee, rhptee;
10002
10003
  // get the "pointed to" type (ignoring qualifiers at the top level)
10004
0
  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
10005
0
  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
10006
10007
  // In C++, the types have to match exactly.
10008
0
  if (S.getLangOpts().CPlusPlus)
10009
0
    return Sema::IncompatibleBlockPointer;
10010
10011
0
  Sema::AssignConvertType ConvTy = Sema::Compatible;
10012
10013
  // For blocks we enforce that qualifiers are identical.
10014
0
  Qualifiers LQuals = lhptee.getLocalQualifiers();
10015
0
  Qualifiers RQuals = rhptee.getLocalQualifiers();
10016
0
  if (S.getLangOpts().OpenCL) {
10017
0
    LQuals.removeAddressSpace();
10018
0
    RQuals.removeAddressSpace();
10019
0
  }
10020
0
  if (LQuals != RQuals)
10021
0
    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
10022
10023
  // FIXME: OpenCL doesn't define the exact compile time semantics for a block
10024
  // assignment.
10025
  // The current behavior is similar to C++ lambdas. A block might be
10026
  // assigned to a variable iff its return type and parameters are compatible
10027
  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
10028
  // an assignment. Presumably it should behave in way that a function pointer
10029
  // assignment does in C, so for each parameter and return type:
10030
  //  * CVR and address space of LHS should be a superset of CVR and address
10031
  //  space of RHS.
10032
  //  * unqualified types should be compatible.
10033
0
  if (S.getLangOpts().OpenCL) {
10034
0
    if (!S.Context.typesAreBlockPointerCompatible(
10035
0
            S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
10036
0
            S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
10037
0
      return Sema::IncompatibleBlockPointer;
10038
0
  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
10039
0
    return Sema::IncompatibleBlockPointer;
10040
10041
0
  return ConvTy;
10042
0
}
10043
10044
/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
10045
/// for assignment compatibility.
10046
static Sema::AssignConvertType
10047
checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
10048
0
                                   QualType RHSType) {
10049
0
  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
10050
0
  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
10051
10052
0
  if (LHSType->isObjCBuiltinType()) {
10053
    // Class is not compatible with ObjC object pointers.
10054
0
    if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
10055
0
        !RHSType->isObjCQualifiedClassType())
10056
0
      return Sema::IncompatiblePointer;
10057
0
    return Sema::Compatible;
10058
0
  }
10059
0
  if (RHSType->isObjCBuiltinType()) {
10060
0
    if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
10061
0
        !LHSType->isObjCQualifiedClassType())
10062
0
      return Sema::IncompatiblePointer;
10063
0
    return Sema::Compatible;
10064
0
  }
10065
0
  QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10066
0
  QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10067
10068
0
  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
10069
      // make an exception for id<P>
10070
0
      !LHSType->isObjCQualifiedIdType())
10071
0
    return Sema::CompatiblePointerDiscardsQualifiers;
10072
10073
0
  if (S.Context.typesAreCompatible(LHSType, RHSType))
10074
0
    return Sema::Compatible;
10075
0
  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
10076
0
    return Sema::IncompatibleObjCQualifiedId;
10077
0
  return Sema::IncompatiblePointer;
10078
0
}
10079
10080
Sema::AssignConvertType
10081
Sema::CheckAssignmentConstraints(SourceLocation Loc,
10082
0
                                 QualType LHSType, QualType RHSType) {
10083
  // Fake up an opaque expression.  We don't actually care about what
10084
  // cast operations are required, so if CheckAssignmentConstraints
10085
  // adds casts to this they'll be wasted, but fortunately that doesn't
10086
  // usually happen on valid code.
10087
0
  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
10088
0
  ExprResult RHSPtr = &RHSExpr;
10089
0
  CastKind K;
10090
10091
0
  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
10092
0
}
10093
10094
/// This helper function returns true if QT is a vector type that has element
10095
/// type ElementType.
10096
0
static bool isVector(QualType QT, QualType ElementType) {
10097
0
  if (const VectorType *VT = QT->getAs<VectorType>())
10098
0
    return VT->getElementType().getCanonicalType() == ElementType;
10099
0
  return false;
10100
0
}
10101
10102
/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
10103
/// has code to accommodate several GCC extensions when type checking
10104
/// pointers. Here are some objectionable examples that GCC considers warnings:
10105
///
10106
///  int a, *pint;
10107
///  short *pshort;
10108
///  struct foo *pfoo;
10109
///
10110
///  pint = pshort; // warning: assignment from incompatible pointer type
10111
///  a = pint; // warning: assignment makes integer from pointer without a cast
10112
///  pint = a; // warning: assignment makes pointer from integer without a cast
10113
///  pint = pfoo; // warning: assignment from incompatible pointer type
10114
///
10115
/// As a result, the code for dealing with pointers is more complex than the
10116
/// C99 spec dictates.
10117
///
10118
/// Sets 'Kind' for any result kind except Incompatible.
10119
Sema::AssignConvertType
10120
Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
10121
7
                                 CastKind &Kind, bool ConvertRHS) {
10122
7
  QualType RHSType = RHS.get()->getType();
10123
7
  QualType OrigLHSType = LHSType;
10124
10125
  // Get canonical types.  We're not formatting these types, just comparing
10126
  // them.
10127
7
  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
10128
7
  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
10129
10130
  // Common case: no conversion required.
10131
7
  if (LHSType == RHSType) {
10132
6
    Kind = CK_NoOp;
10133
6
    return Compatible;
10134
6
  }
10135
10136
  // If the LHS has an __auto_type, there are no additional type constraints
10137
  // to be worried about.
10138
1
  if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
10139
0
    if (AT->isGNUAutoType()) {
10140
0
      Kind = CK_NoOp;
10141
0
      return Compatible;
10142
0
    }
10143
0
  }
10144
10145
  // If we have an atomic type, try a non-atomic assignment, then just add an
10146
  // atomic qualification step.
10147
1
  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
10148
0
    Sema::AssignConvertType result =
10149
0
      CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
10150
0
    if (result != Compatible)
10151
0
      return result;
10152
0
    if (Kind != CK_NoOp && ConvertRHS)
10153
0
      RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
10154
0
    Kind = CK_NonAtomicToAtomic;
10155
0
    return Compatible;
10156
0
  }
10157
10158
  // If the left-hand side is a reference type, then we are in a
10159
  // (rare!) case where we've allowed the use of references in C,
10160
  // e.g., as a parameter type in a built-in function. In this case,
10161
  // just make sure that the type referenced is compatible with the
10162
  // right-hand side type. The caller is responsible for adjusting
10163
  // LHSType so that the resulting expression does not have reference
10164
  // type.
10165
1
  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
10166
0
    if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
10167
0
      Kind = CK_LValueBitCast;
10168
0
      return Compatible;
10169
0
    }
10170
0
    return Incompatible;
10171
0
  }
10172
10173
  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
10174
  // to the same ExtVector type.
10175
1
  if (LHSType->isExtVectorType()) {
10176
0
    if (RHSType->isExtVectorType())
10177
0
      return Incompatible;
10178
0
    if (RHSType->isArithmeticType()) {
10179
      // CK_VectorSplat does T -> vector T, so first cast to the element type.
10180
0
      if (ConvertRHS)
10181
0
        RHS = prepareVectorSplat(LHSType, RHS.get());
10182
0
      Kind = CK_VectorSplat;
10183
0
      return Compatible;
10184
0
    }
10185
0
  }
10186
10187
  // Conversions to or from vector type.
10188
1
  if (LHSType->isVectorType() || RHSType->isVectorType()) {
10189
0
    if (LHSType->isVectorType() && RHSType->isVectorType()) {
10190
      // Allow assignments of an AltiVec vector type to an equivalent GCC
10191
      // vector type and vice versa
10192
0
      if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10193
0
        Kind = CK_BitCast;
10194
0
        return Compatible;
10195
0
      }
10196
10197
      // If we are allowing lax vector conversions, and LHS and RHS are both
10198
      // vectors, the total size only needs to be the same. This is a bitcast;
10199
      // no bits are changed but the result type is different.
10200
0
      if (isLaxVectorConversion(RHSType, LHSType)) {
10201
        // The default for lax vector conversions with Altivec vectors will
10202
        // change, so if we are converting between vector types where
10203
        // at least one is an Altivec vector, emit a warning.
10204
0
        if (Context.getTargetInfo().getTriple().isPPC() &&
10205
0
            anyAltivecTypes(RHSType, LHSType) &&
10206
0
            !Context.areCompatibleVectorTypes(RHSType, LHSType))
10207
0
          Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10208
0
              << RHSType << LHSType;
10209
0
        Kind = CK_BitCast;
10210
0
        return IncompatibleVectors;
10211
0
      }
10212
0
    }
10213
10214
    // When the RHS comes from another lax conversion (e.g. binops between
10215
    // scalars and vectors) the result is canonicalized as a vector. When the
10216
    // LHS is also a vector, the lax is allowed by the condition above. Handle
10217
    // the case where LHS is a scalar.
10218
0
    if (LHSType->isScalarType()) {
10219
0
      const VectorType *VecType = RHSType->getAs<VectorType>();
10220
0
      if (VecType && VecType->getNumElements() == 1 &&
10221
0
          isLaxVectorConversion(RHSType, LHSType)) {
10222
0
        if (Context.getTargetInfo().getTriple().isPPC() &&
10223
0
            (VecType->getVectorKind() == VectorKind::AltiVecVector ||
10224
0
             VecType->getVectorKind() == VectorKind::AltiVecBool ||
10225
0
             VecType->getVectorKind() == VectorKind::AltiVecPixel))
10226
0
          Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10227
0
              << RHSType << LHSType;
10228
0
        ExprResult *VecExpr = &RHS;
10229
0
        *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
10230
0
        Kind = CK_BitCast;
10231
0
        return Compatible;
10232
0
      }
10233
0
    }
10234
10235
    // Allow assignments between fixed-length and sizeless SVE vectors.
10236
0
    if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10237
0
        (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10238
0
      if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
10239
0
          Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
10240
0
        Kind = CK_BitCast;
10241
0
        return Compatible;
10242
0
      }
10243
10244
    // Allow assignments between fixed-length and sizeless RVV vectors.
10245
0
    if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10246
0
        (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10247
0
      if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
10248
0
          Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
10249
0
        Kind = CK_BitCast;
10250
0
        return Compatible;
10251
0
      }
10252
0
    }
10253
10254
0
    return Incompatible;
10255
0
  }
10256
10257
  // Diagnose attempts to convert between __ibm128, __float128 and long double
10258
  // where such conversions currently can't be handled.
10259
1
  if (unsupportedTypeConversion(*this, LHSType, RHSType))
10260
0
    return Incompatible;
10261
10262
  // Disallow assigning a _Complex to a real type in C++ mode since it simply
10263
  // discards the imaginary part.
10264
1
  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10265
1
      !LHSType->getAs<ComplexType>())
10266
0
    return Incompatible;
10267
10268
  // Arithmetic conversions.
10269
1
  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10270
1
      !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10271
0
    if (ConvertRHS)
10272
0
      Kind = PrepareScalarCast(RHS, LHSType);
10273
0
    return Compatible;
10274
0
  }
10275
10276
  // Conversions to normal pointers.
10277
1
  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10278
    // U* -> T*
10279
0
    if (isa<PointerType>(RHSType)) {
10280
0
      LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10281
0
      LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10282
0
      if (AddrSpaceL != AddrSpaceR)
10283
0
        Kind = CK_AddressSpaceConversion;
10284
0
      else if (Context.hasCvrSimilarType(RHSType, LHSType))
10285
0
        Kind = CK_NoOp;
10286
0
      else
10287
0
        Kind = CK_BitCast;
10288
0
      return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10289
0
                                            RHS.get()->getBeginLoc());
10290
0
    }
10291
10292
    // int -> T*
10293
0
    if (RHSType->isIntegerType()) {
10294
0
      Kind = CK_IntegralToPointer; // FIXME: null?
10295
0
      return IntToPointer;
10296
0
    }
10297
10298
    // C pointers are not compatible with ObjC object pointers,
10299
    // with two exceptions:
10300
0
    if (isa<ObjCObjectPointerType>(RHSType)) {
10301
      //  - conversions to void*
10302
0
      if (LHSPointer->getPointeeType()->isVoidType()) {
10303
0
        Kind = CK_BitCast;
10304
0
        return Compatible;
10305
0
      }
10306
10307
      //  - conversions from 'Class' to the redefinition type
10308
0
      if (RHSType->isObjCClassType() &&
10309
0
          Context.hasSameType(LHSType,
10310
0
                              Context.getObjCClassRedefinitionType())) {
10311
0
        Kind = CK_BitCast;
10312
0
        return Compatible;
10313
0
      }
10314
10315
0
      Kind = CK_BitCast;
10316
0
      return IncompatiblePointer;
10317
0
    }
10318
10319
    // U^ -> void*
10320
0
    if (RHSType->getAs<BlockPointerType>()) {
10321
0
      if (LHSPointer->getPointeeType()->isVoidType()) {
10322
0
        LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10323
0
        LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10324
0
                                ->getPointeeType()
10325
0
                                .getAddressSpace();
10326
0
        Kind =
10327
0
            AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10328
0
        return Compatible;
10329
0
      }
10330
0
    }
10331
10332
0
    return Incompatible;
10333
0
  }
10334
10335
  // Conversions to block pointers.
10336
1
  if (isa<BlockPointerType>(LHSType)) {
10337
    // U^ -> T^
10338
0
    if (RHSType->isBlockPointerType()) {
10339
0
      LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10340
0
                              ->getPointeeType()
10341
0
                              .getAddressSpace();
10342
0
      LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10343
0
                              ->getPointeeType()
10344
0
                              .getAddressSpace();
10345
0
      Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10346
0
      return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10347
0
    }
10348
10349
    // int or null -> T^
10350
0
    if (RHSType->isIntegerType()) {
10351
0
      Kind = CK_IntegralToPointer; // FIXME: null
10352
0
      return IntToBlockPointer;
10353
0
    }
10354
10355
    // id -> T^
10356
0
    if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10357
0
      Kind = CK_AnyPointerToBlockPointerCast;
10358
0
      return Compatible;
10359
0
    }
10360
10361
    // void* -> T^
10362
0
    if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10363
0
      if (RHSPT->getPointeeType()->isVoidType()) {
10364
0
        Kind = CK_AnyPointerToBlockPointerCast;
10365
0
        return Compatible;
10366
0
      }
10367
10368
0
    return Incompatible;
10369
0
  }
10370
10371
  // Conversions to Objective-C pointers.
10372
1
  if (isa<ObjCObjectPointerType>(LHSType)) {
10373
    // A* -> B*
10374
1
    if (RHSType->isObjCObjectPointerType()) {
10375
0
      Kind = CK_BitCast;
10376
0
      Sema::AssignConvertType result =
10377
0
        checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10378
0
      if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10379
0
          result == Compatible &&
10380
0
          !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10381
0
        result = IncompatibleObjCWeakRef;
10382
0
      return result;
10383
0
    }
10384
10385
    // int or null -> A*
10386
1
    if (RHSType->isIntegerType()) {
10387
1
      Kind = CK_IntegralToPointer; // FIXME: null
10388
1
      return IntToPointer;
10389
1
    }
10390
10391
    // In general, C pointers are not compatible with ObjC object pointers,
10392
    // with two exceptions:
10393
0
    if (isa<PointerType>(RHSType)) {
10394
0
      Kind = CK_CPointerToObjCPointerCast;
10395
10396
      //  - conversions from 'void*'
10397
0
      if (RHSType->isVoidPointerType()) {
10398
0
        return Compatible;
10399
0
      }
10400
10401
      //  - conversions to 'Class' from its redefinition type
10402
0
      if (LHSType->isObjCClassType() &&
10403
0
          Context.hasSameType(RHSType,
10404
0
                              Context.getObjCClassRedefinitionType())) {
10405
0
        return Compatible;
10406
0
      }
10407
10408
0
      return IncompatiblePointer;
10409
0
    }
10410
10411
    // Only under strict condition T^ is compatible with an Objective-C pointer.
10412
0
    if (RHSType->isBlockPointerType() &&
10413
0
        LHSType->isBlockCompatibleObjCPointerType(Context)) {
10414
0
      if (ConvertRHS)
10415
0
        maybeExtendBlockObject(RHS);
10416
0
      Kind = CK_BlockPointerToObjCPointerCast;
10417
0
      return Compatible;
10418
0
    }
10419
10420
0
    return Incompatible;
10421
0
  }
10422
10423
  // Conversion to nullptr_t (C23 only)
10424
0
  if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10425
0
      RHS.get()->isNullPointerConstant(Context,
10426
0
                                       Expr::NPC_ValueDependentIsNull)) {
10427
    // null -> nullptr_t
10428
0
    Kind = CK_NullToPointer;
10429
0
    return Compatible;
10430
0
  }
10431
10432
  // Conversions from pointers that are not covered by the above.
10433
0
  if (isa<PointerType>(RHSType)) {
10434
    // T* -> _Bool
10435
0
    if (LHSType == Context.BoolTy) {
10436
0
      Kind = CK_PointerToBoolean;
10437
0
      return Compatible;
10438
0
    }
10439
10440
    // T* -> int
10441
0
    if (LHSType->isIntegerType()) {
10442
0
      Kind = CK_PointerToIntegral;
10443
0
      return PointerToInt;
10444
0
    }
10445
10446
0
    return Incompatible;
10447
0
  }
10448
10449
  // Conversions from Objective-C pointers that are not covered by the above.
10450
0
  if (isa<ObjCObjectPointerType>(RHSType)) {
10451
    // T* -> _Bool
10452
0
    if (LHSType == Context.BoolTy) {
10453
0
      Kind = CK_PointerToBoolean;
10454
0
      return Compatible;
10455
0
    }
10456
10457
    // T* -> int
10458
0
    if (LHSType->isIntegerType()) {
10459
0
      Kind = CK_PointerToIntegral;
10460
0
      return PointerToInt;
10461
0
    }
10462
10463
0
    return Incompatible;
10464
0
  }
10465
10466
  // struct A -> struct B
10467
0
  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10468
0
    if (Context.typesAreCompatible(LHSType, RHSType)) {
10469
0
      Kind = CK_NoOp;
10470
0
      return Compatible;
10471
0
    }
10472
0
  }
10473
10474
0
  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10475
0
    Kind = CK_IntToOCLSampler;
10476
0
    return Compatible;
10477
0
  }
10478
10479
0
  return Incompatible;
10480
0
}
10481
10482
/// Constructs a transparent union from an expression that is
10483
/// used to initialize the transparent union.
10484
static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10485
                                      ExprResult &EResult, QualType UnionType,
10486
0
                                      FieldDecl *Field) {
10487
  // Build an initializer list that designates the appropriate member
10488
  // of the transparent union.
10489
0
  Expr *E = EResult.get();
10490
0
  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10491
0
                                                   E, SourceLocation());
10492
0
  Initializer->setType(UnionType);
10493
0
  Initializer->setInitializedFieldInUnion(Field);
10494
10495
  // Build a compound literal constructing a value of the transparent
10496
  // union type from this initializer list.
10497
0
  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10498
0
  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10499
0
                                        VK_PRValue, Initializer, false);
10500
0
}
10501
10502
Sema::AssignConvertType
10503
Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10504
0
                                               ExprResult &RHS) {
10505
0
  QualType RHSType = RHS.get()->getType();
10506
10507
  // If the ArgType is a Union type, we want to handle a potential
10508
  // transparent_union GCC extension.
10509
0
  const RecordType *UT = ArgType->getAsUnionType();
10510
0
  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10511
0
    return Incompatible;
10512
10513
  // The field to initialize within the transparent union.
10514
0
  RecordDecl *UD = UT->getDecl();
10515
0
  FieldDecl *InitField = nullptr;
10516
  // It's compatible if the expression matches any of the fields.
10517
0
  for (auto *it : UD->fields()) {
10518
0
    if (it->getType()->isPointerType()) {
10519
      // If the transparent union contains a pointer type, we allow:
10520
      // 1) void pointer
10521
      // 2) null pointer constant
10522
0
      if (RHSType->isPointerType())
10523
0
        if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10524
0
          RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10525
0
          InitField = it;
10526
0
          break;
10527
0
        }
10528
10529
0
      if (RHS.get()->isNullPointerConstant(Context,
10530
0
                                           Expr::NPC_ValueDependentIsNull)) {
10531
0
        RHS = ImpCastExprToType(RHS.get(), it->getType(),
10532
0
                                CK_NullToPointer);
10533
0
        InitField = it;
10534
0
        break;
10535
0
      }
10536
0
    }
10537
10538
0
    CastKind Kind;
10539
0
    if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10540
0
          == Compatible) {
10541
0
      RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10542
0
      InitField = it;
10543
0
      break;
10544
0
    }
10545
0
  }
10546
10547
0
  if (!InitField)
10548
0
    return Incompatible;
10549
10550
0
  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10551
0
  return Compatible;
10552
0
}
10553
10554
Sema::AssignConvertType
10555
Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10556
                                       bool Diagnose,
10557
                                       bool DiagnoseCFAudited,
10558
7
                                       bool ConvertRHS) {
10559
  // We need to be able to tell the caller whether we diagnosed a problem, if
10560
  // they ask us to issue diagnostics.
10561
7
  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10562
10563
  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10564
  // we can't avoid *all* modifications at the moment, so we need some somewhere
10565
  // to put the updated value.
10566
0
  ExprResult LocalRHS = CallerRHS;
10567
7
  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10568
10569
7
  if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10570
0
    if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10571
0
      if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10572
0
          !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10573
0
        Diag(RHS.get()->getExprLoc(),
10574
0
             diag::warn_noderef_to_dereferenceable_pointer)
10575
0
            << RHS.get()->getSourceRange();
10576
0
      }
10577
0
    }
10578
0
  }
10579
10580
7
  if (getLangOpts().CPlusPlus) {
10581
0
    if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10582
      // C++ 5.17p3: If the left operand is not of class type, the
10583
      // expression is implicitly converted (C++ 4) to the
10584
      // cv-unqualified type of the left operand.
10585
0
      QualType RHSType = RHS.get()->getType();
10586
0
      if (Diagnose) {
10587
0
        RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10588
0
                                        AA_Assigning);
10589
0
      } else {
10590
0
        ImplicitConversionSequence ICS =
10591
0
            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10592
0
                                  /*SuppressUserConversions=*/false,
10593
0
                                  AllowedExplicit::None,
10594
0
                                  /*InOverloadResolution=*/false,
10595
0
                                  /*CStyle=*/false,
10596
0
                                  /*AllowObjCWritebackConversion=*/false);
10597
0
        if (ICS.isFailure())
10598
0
          return Incompatible;
10599
0
        RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10600
0
                                        ICS, AA_Assigning);
10601
0
      }
10602
0
      if (RHS.isInvalid())
10603
0
        return Incompatible;
10604
0
      Sema::AssignConvertType result = Compatible;
10605
0
      if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10606
0
          !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10607
0
        result = IncompatibleObjCWeakRef;
10608
0
      return result;
10609
0
    }
10610
10611
    // FIXME: Currently, we fall through and treat C++ classes like C
10612
    // structures.
10613
    // FIXME: We also fall through for atomics; not sure what should
10614
    // happen there, though.
10615
7
  } else if (RHS.get()->getType() == Context.OverloadTy) {
10616
    // As a set of extensions to C, we support overloading on functions. These
10617
    // functions need to be resolved here.
10618
0
    DeclAccessPair DAP;
10619
0
    if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10620
0
            RHS.get(), LHSType, /*Complain=*/false, DAP))
10621
0
      RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10622
0
    else
10623
0
      return Incompatible;
10624
0
  }
10625
10626
  // This check seems unnatural, however it is necessary to ensure the proper
10627
  // conversion of functions/arrays. If the conversion were done for all
10628
  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10629
  // expressions that suppress this implicit conversion (&, sizeof). This needs
10630
  // to happen before we check for null pointer conversions because C does not
10631
  // undergo the same implicit conversions as C++ does above (by the calls to
10632
  // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10633
  // lvalue to rvalue cast before checking for null pointer constraints. This
10634
  // addresses code like: nullptr_t val; int *ptr; ptr = val;
10635
  //
10636
  // Suppress this for references: C++ 8.5.3p5.
10637
7
  if (!LHSType->isReferenceType()) {
10638
    // FIXME: We potentially allocate here even if ConvertRHS is false.
10639
7
    RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10640
7
    if (RHS.isInvalid())
10641
0
      return Incompatible;
10642
7
  }
10643
10644
  // The constraints are expressed in terms of the atomic, qualified, or
10645
  // unqualified type of the LHS.
10646
7
  QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10647
10648
  // C99 6.5.16.1p1: the left operand is a pointer and the right is
10649
  // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10650
7
  if ((LHSTypeAfterConversion->isPointerType() ||
10651
7
       LHSTypeAfterConversion->isObjCObjectPointerType() ||
10652
7
       LHSTypeAfterConversion->isBlockPointerType()) &&
10653
7
      ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10654
1
       RHS.get()->isNullPointerConstant(Context,
10655
1
                                        Expr::NPC_ValueDependentIsNull))) {
10656
0
    if (Diagnose || ConvertRHS) {
10657
0
      CastKind Kind;
10658
0
      CXXCastPath Path;
10659
0
      CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10660
0
                             /*IgnoreBaseAccess=*/false, Diagnose);
10661
0
      if (ConvertRHS)
10662
0
        RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10663
0
    }
10664
0
    return Compatible;
10665
0
  }
10666
  // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10667
  // unqualified bool, and the right operand is a pointer or its type is
10668
  // nullptr_t.
10669
7
  if (getLangOpts().C23 && LHSType->isBooleanType() &&
10670
7
      RHS.get()->getType()->isNullPtrType()) {
10671
    // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10672
    // only handles nullptr -> _Bool due to needing an extra conversion
10673
    // step.
10674
    // We model this by converting from nullptr -> void * and then let the
10675
    // conversion from void * -> _Bool happen naturally.
10676
0
    if (Diagnose || ConvertRHS) {
10677
0
      CastKind Kind;
10678
0
      CXXCastPath Path;
10679
0
      CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10680
0
                             /*IgnoreBaseAccess=*/false, Diagnose);
10681
0
      if (ConvertRHS)
10682
0
        RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10683
0
                                &Path);
10684
0
    }
10685
0
  }
10686
10687
  // OpenCL queue_t type assignment.
10688
7
  if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10689
0
                                 Context, Expr::NPC_ValueDependentIsNull)) {
10690
0
    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10691
0
    return Compatible;
10692
0
  }
10693
10694
7
  CastKind Kind;
10695
7
  Sema::AssignConvertType result =
10696
7
    CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10697
10698
  // C99 6.5.16.1p2: The value of the right operand is converted to the
10699
  // type of the assignment expression.
10700
  // CheckAssignmentConstraints allows the left-hand side to be a reference,
10701
  // so that we can use references in built-in functions even in C.
10702
  // The getNonReferenceType() call makes sure that the resulting expression
10703
  // does not have reference type.
10704
7
  if (result != Incompatible && RHS.get()->getType() != LHSType) {
10705
1
    QualType Ty = LHSType.getNonLValueExprType(Context);
10706
1
    Expr *E = RHS.get();
10707
10708
    // Check for various Objective-C errors. If we are not reporting
10709
    // diagnostics and just checking for errors, e.g., during overload
10710
    // resolution, return Incompatible to indicate the failure.
10711
1
    if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10712
1
        CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10713
0
                            Diagnose, DiagnoseCFAudited) != ACR_okay) {
10714
0
      if (!Diagnose)
10715
0
        return Incompatible;
10716
0
    }
10717
1
    if (getLangOpts().ObjC &&
10718
1
        (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10719
1
                                           E->getType(), E, Diagnose) ||
10720
1
         CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10721
0
      if (!Diagnose)
10722
0
        return Incompatible;
10723
      // Replace the expression with a corrected version and continue so we
10724
      // can find further errors.
10725
0
      RHS = E;
10726
0
      return Compatible;
10727
0
    }
10728
10729
1
    if (ConvertRHS)
10730
1
      RHS = ImpCastExprToType(E, Ty, Kind);
10731
1
  }
10732
10733
7
  return result;
10734
7
}
10735
10736
namespace {
10737
/// The original operand to an operator, prior to the application of the usual
10738
/// arithmetic conversions and converting the arguments of a builtin operator
10739
/// candidate.
10740
struct OriginalOperand {
10741
0
  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10742
0
    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10743
0
      Op = MTE->getSubExpr();
10744
0
    if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10745
0
      Op = BTE->getSubExpr();
10746
0
    if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10747
0
      Orig = ICE->getSubExprAsWritten();
10748
0
      Conversion = ICE->getConversionFunction();
10749
0
    }
10750
0
  }
10751
10752
0
  QualType getType() const { return Orig->getType(); }
10753
10754
  Expr *Orig;
10755
  NamedDecl *Conversion;
10756
};
10757
}
10758
10759
QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10760
0
                               ExprResult &RHS) {
10761
0
  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10762
10763
0
  Diag(Loc, diag::err_typecheck_invalid_operands)
10764
0
    << OrigLHS.getType() << OrigRHS.getType()
10765
0
    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10766
10767
  // If a user-defined conversion was applied to either of the operands prior
10768
  // to applying the built-in operator rules, tell the user about it.
10769
0
  if (OrigLHS.Conversion) {
10770
0
    Diag(OrigLHS.Conversion->getLocation(),
10771
0
         diag::note_typecheck_invalid_operands_converted)
10772
0
      << 0 << LHS.get()->getType();
10773
0
  }
10774
0
  if (OrigRHS.Conversion) {
10775
0
    Diag(OrigRHS.Conversion->getLocation(),
10776
0
         diag::note_typecheck_invalid_operands_converted)
10777
0
      << 1 << RHS.get()->getType();
10778
0
  }
10779
10780
0
  return QualType();
10781
0
}
10782
10783
// Diagnose cases where a scalar was implicitly converted to a vector and
10784
// diagnose the underlying types. Otherwise, diagnose the error
10785
// as invalid vector logical operands for non-C++ cases.
10786
QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10787
0
                                            ExprResult &RHS) {
10788
0
  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10789
0
  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10790
10791
0
  bool LHSNatVec = LHSType->isVectorType();
10792
0
  bool RHSNatVec = RHSType->isVectorType();
10793
10794
0
  if (!(LHSNatVec && RHSNatVec)) {
10795
0
    Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10796
0
    Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10797
0
    Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10798
0
        << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10799
0
        << Vector->getSourceRange();
10800
0
    return QualType();
10801
0
  }
10802
10803
0
  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10804
0
      << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10805
0
      << RHS.get()->getSourceRange();
10806
10807
0
  return QualType();
10808
0
}
10809
10810
/// Try to convert a value of non-vector type to a vector type by converting
10811
/// the type to the element type of the vector and then performing a splat.
10812
/// If the language is OpenCL, we only use conversions that promote scalar
10813
/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10814
/// for float->int.
10815
///
10816
/// OpenCL V2.0 6.2.6.p2:
10817
/// An error shall occur if any scalar operand type has greater rank
10818
/// than the type of the vector element.
10819
///
10820
/// \param scalar - if non-null, actually perform the conversions
10821
/// \return true if the operation fails (but without diagnosing the failure)
10822
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10823
                                     QualType scalarTy,
10824
                                     QualType vectorEltTy,
10825
                                     QualType vectorTy,
10826
0
                                     unsigned &DiagID) {
10827
  // The conversion to apply to the scalar before splatting it,
10828
  // if necessary.
10829
0
  CastKind scalarCast = CK_NoOp;
10830
10831
0
  if (vectorEltTy->isIntegralType(S.Context)) {
10832
0
    if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10833
0
        (scalarTy->isIntegerType() &&
10834
0
         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10835
0
      DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10836
0
      return true;
10837
0
    }
10838
0
    if (!scalarTy->isIntegralType(S.Context))
10839
0
      return true;
10840
0
    scalarCast = CK_IntegralCast;
10841
0
  } else if (vectorEltTy->isRealFloatingType()) {
10842
0
    if (scalarTy->isRealFloatingType()) {
10843
0
      if (S.getLangOpts().OpenCL &&
10844
0
          S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10845
0
        DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10846
0
        return true;
10847
0
      }
10848
0
      scalarCast = CK_FloatingCast;
10849
0
    }
10850
0
    else if (scalarTy->isIntegralType(S.Context))
10851
0
      scalarCast = CK_IntegralToFloating;
10852
0
    else
10853
0
      return true;
10854
0
  } else {
10855
0
    return true;
10856
0
  }
10857
10858
  // Adjust scalar if desired.
10859
0
  if (scalar) {
10860
0
    if (scalarCast != CK_NoOp)
10861
0
      *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10862
0
    *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10863
0
  }
10864
0
  return false;
10865
0
}
10866
10867
/// Convert vector E to a vector with the same number of elements but different
10868
/// element type.
10869
0
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10870
0
  const auto *VecTy = E->getType()->getAs<VectorType>();
10871
0
  assert(VecTy && "Expression E must be a vector");
10872
0
  QualType NewVecTy =
10873
0
      VecTy->isExtVectorType()
10874
0
          ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10875
0
          : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10876
0
                                    VecTy->getVectorKind());
10877
10878
  // Look through the implicit cast. Return the subexpression if its type is
10879
  // NewVecTy.
10880
0
  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10881
0
    if (ICE->getSubExpr()->getType() == NewVecTy)
10882
0
      return ICE->getSubExpr();
10883
10884
0
  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10885
0
  return S.ImpCastExprToType(E, NewVecTy, Cast);
10886
0
}
10887
10888
/// Test if a (constant) integer Int can be casted to another integer type
10889
/// IntTy without losing precision.
10890
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10891
0
                                      QualType OtherIntTy) {
10892
0
  QualType IntTy = Int->get()->getType().getUnqualifiedType();
10893
10894
  // Reject cases where the value of the Int is unknown as that would
10895
  // possibly cause truncation, but accept cases where the scalar can be
10896
  // demoted without loss of precision.
10897
0
  Expr::EvalResult EVResult;
10898
0
  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10899
0
  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10900
0
  bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10901
0
  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10902
10903
0
  if (CstInt) {
10904
    // If the scalar is constant and is of a higher order and has more active
10905
    // bits that the vector element type, reject it.
10906
0
    llvm::APSInt Result = EVResult.Val.getInt();
10907
0
    unsigned NumBits = IntSigned
10908
0
                           ? (Result.isNegative() ? Result.getSignificantBits()
10909
0
                                                  : Result.getActiveBits())
10910
0
                           : Result.getActiveBits();
10911
0
    if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10912
0
      return true;
10913
10914
    // If the signedness of the scalar type and the vector element type
10915
    // differs and the number of bits is greater than that of the vector
10916
    // element reject it.
10917
0
    return (IntSigned != OtherIntSigned &&
10918
0
            NumBits > S.Context.getIntWidth(OtherIntTy));
10919
0
  }
10920
10921
  // Reject cases where the value of the scalar is not constant and it's
10922
  // order is greater than that of the vector element type.
10923
0
  return (Order < 0);
10924
0
}
10925
10926
/// Test if a (constant) integer Int can be casted to floating point type
10927
/// FloatTy without losing precision.
10928
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10929
0
                                     QualType FloatTy) {
10930
0
  QualType IntTy = Int->get()->getType().getUnqualifiedType();
10931
10932
  // Determine if the integer constant can be expressed as a floating point
10933
  // number of the appropriate type.
10934
0
  Expr::EvalResult EVResult;
10935
0
  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10936
10937
0
  uint64_t Bits = 0;
10938
0
  if (CstInt) {
10939
    // Reject constants that would be truncated if they were converted to
10940
    // the floating point type. Test by simple to/from conversion.
10941
    // FIXME: Ideally the conversion to an APFloat and from an APFloat
10942
    //        could be avoided if there was a convertFromAPInt method
10943
    //        which could signal back if implicit truncation occurred.
10944
0
    llvm::APSInt Result = EVResult.Val.getInt();
10945
0
    llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10946
0
    Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10947
0
                           llvm::APFloat::rmTowardZero);
10948
0
    llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10949
0
                             !IntTy->hasSignedIntegerRepresentation());
10950
0
    bool Ignored = false;
10951
0
    Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10952
0
                           &Ignored);
10953
0
    if (Result != ConvertBack)
10954
0
      return true;
10955
0
  } else {
10956
    // Reject types that cannot be fully encoded into the mantissa of
10957
    // the float.
10958
0
    Bits = S.Context.getTypeSize(IntTy);
10959
0
    unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10960
0
        S.Context.getFloatTypeSemantics(FloatTy));
10961
0
    if (Bits > FloatPrec)
10962
0
      return true;
10963
0
  }
10964
10965
0
  return false;
10966
0
}
10967
10968
/// Attempt to convert and splat Scalar into a vector whose types matches
10969
/// Vector following GCC conversion rules. The rule is that implicit
10970
/// conversion can occur when Scalar can be casted to match Vector's element
10971
/// type without causing truncation of Scalar.
10972
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10973
0
                                        ExprResult *Vector) {
10974
0
  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10975
0
  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10976
0
  QualType VectorEltTy;
10977
10978
0
  if (const auto *VT = VectorTy->getAs<VectorType>()) {
10979
0
    assert(!isa<ExtVectorType>(VT) &&
10980
0
           "ExtVectorTypes should not be handled here!");
10981
0
    VectorEltTy = VT->getElementType();
10982
0
  } else if (VectorTy->isSveVLSBuiltinType()) {
10983
0
    VectorEltTy =
10984
0
        VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10985
0
  } else {
10986
0
    llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10987
0
  }
10988
10989
  // Reject cases where the vector element type or the scalar element type are
10990
  // not integral or floating point types.
10991
0
  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10992
0
    return true;
10993
10994
  // The conversion to apply to the scalar before splatting it,
10995
  // if necessary.
10996
0
  CastKind ScalarCast = CK_NoOp;
10997
10998
  // Accept cases where the vector elements are integers and the scalar is
10999
  // an integer.
11000
  // FIXME: Notionally if the scalar was a floating point value with a precise
11001
  //        integral representation, we could cast it to an appropriate integer
11002
  //        type and then perform the rest of the checks here. GCC will perform
11003
  //        this conversion in some cases as determined by the input language.
11004
  //        We should accept it on a language independent basis.
11005
0
  if (VectorEltTy->isIntegralType(S.Context) &&
11006
0
      ScalarTy->isIntegralType(S.Context) &&
11007
0
      S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
11008
11009
0
    if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
11010
0
      return true;
11011
11012
0
    ScalarCast = CK_IntegralCast;
11013
0
  } else if (VectorEltTy->isIntegralType(S.Context) &&
11014
0
             ScalarTy->isRealFloatingType()) {
11015
0
    if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
11016
0
      ScalarCast = CK_FloatingToIntegral;
11017
0
    else
11018
0
      return true;
11019
0
  } else if (VectorEltTy->isRealFloatingType()) {
11020
0
    if (ScalarTy->isRealFloatingType()) {
11021
11022
      // Reject cases where the scalar type is not a constant and has a higher
11023
      // Order than the vector element type.
11024
0
      llvm::APFloat Result(0.0);
11025
11026
      // Determine whether this is a constant scalar. In the event that the
11027
      // value is dependent (and thus cannot be evaluated by the constant
11028
      // evaluator), skip the evaluation. This will then diagnose once the
11029
      // expression is instantiated.
11030
0
      bool CstScalar = Scalar->get()->isValueDependent() ||
11031
0
                       Scalar->get()->EvaluateAsFloat(Result, S.Context);
11032
0
      int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
11033
0
      if (!CstScalar && Order < 0)
11034
0
        return true;
11035
11036
      // If the scalar cannot be safely casted to the vector element type,
11037
      // reject it.
11038
0
      if (CstScalar) {
11039
0
        bool Truncated = false;
11040
0
        Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
11041
0
                       llvm::APFloat::rmNearestTiesToEven, &Truncated);
11042
0
        if (Truncated)
11043
0
          return true;
11044
0
      }
11045
11046
0
      ScalarCast = CK_FloatingCast;
11047
0
    } else if (ScalarTy->isIntegralType(S.Context)) {
11048
0
      if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
11049
0
        return true;
11050
11051
0
      ScalarCast = CK_IntegralToFloating;
11052
0
    } else
11053
0
      return true;
11054
0
  } else if (ScalarTy->isEnumeralType())
11055
0
    return true;
11056
11057
  // Adjust scalar if desired.
11058
0
  if (ScalarCast != CK_NoOp)
11059
0
    *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
11060
0
  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
11061
0
  return false;
11062
0
}
11063
11064
QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11065
                                   SourceLocation Loc, bool IsCompAssign,
11066
                                   bool AllowBothBool,
11067
                                   bool AllowBoolConversions,
11068
                                   bool AllowBoolOperation,
11069
0
                                   bool ReportInvalid) {
11070
0
  if (!IsCompAssign) {
11071
0
    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11072
0
    if (LHS.isInvalid())
11073
0
      return QualType();
11074
0
  }
11075
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11076
0
  if (RHS.isInvalid())
11077
0
    return QualType();
11078
11079
  // For conversion purposes, we ignore any qualifiers.
11080
  // For example, "const float" and "float" are equivalent.
11081
0
  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11082
0
  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11083
11084
0
  const VectorType *LHSVecType = LHSType->getAs<VectorType>();
11085
0
  const VectorType *RHSVecType = RHSType->getAs<VectorType>();
11086
0
  assert(LHSVecType || RHSVecType);
11087
11088
  // AltiVec-style "vector bool op vector bool" combinations are allowed
11089
  // for some operators but not others.
11090
0
  if (!AllowBothBool && LHSVecType &&
11091
0
      LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
11092
0
      RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11093
0
    return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11094
11095
  // This operation may not be performed on boolean vectors.
11096
0
  if (!AllowBoolOperation &&
11097
0
      (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
11098
0
    return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11099
11100
  // If the vector types are identical, return.
11101
0
  if (Context.hasSameType(LHSType, RHSType))
11102
0
    return Context.getCommonSugaredType(LHSType, RHSType);
11103
11104
  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11105
0
  if (LHSVecType && RHSVecType &&
11106
0
      Context.areCompatibleVectorTypes(LHSType, RHSType)) {
11107
0
    if (isa<ExtVectorType>(LHSVecType)) {
11108
0
      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11109
0
      return LHSType;
11110
0
    }
11111
11112
0
    if (!IsCompAssign)
11113
0
      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11114
0
    return RHSType;
11115
0
  }
11116
11117
  // AllowBoolConversions says that bool and non-bool AltiVec vectors
11118
  // can be mixed, with the result being the non-bool type.  The non-bool
11119
  // operand must have integer element type.
11120
0
  if (AllowBoolConversions && LHSVecType && RHSVecType &&
11121
0
      LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
11122
0
      (Context.getTypeSize(LHSVecType->getElementType()) ==
11123
0
       Context.getTypeSize(RHSVecType->getElementType()))) {
11124
0
    if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11125
0
        LHSVecType->getElementType()->isIntegerType() &&
11126
0
        RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
11127
0
      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11128
0
      return LHSType;
11129
0
    }
11130
0
    if (!IsCompAssign &&
11131
0
        LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
11132
0
        RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11133
0
        RHSVecType->getElementType()->isIntegerType()) {
11134
0
      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11135
0
      return RHSType;
11136
0
    }
11137
0
  }
11138
11139
  // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11140
  // invalid since the ambiguity can affect the ABI.
11141
0
  auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11142
0
                               unsigned &SVEorRVV) {
11143
0
    const VectorType *VecType = SecondType->getAs<VectorType>();
11144
0
    SVEorRVV = 0;
11145
0
    if (FirstType->isSizelessBuiltinType() && VecType) {
11146
0
      if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11147
0
          VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
11148
0
        return true;
11149
0
      if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData) {
11150
0
        SVEorRVV = 1;
11151
0
        return true;
11152
0
      }
11153
0
    }
11154
11155
0
    return false;
11156
0
  };
11157
11158
0
  unsigned SVEorRVV;
11159
0
  if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11160
0
      IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11161
0
    Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
11162
0
        << SVEorRVV << LHSType << RHSType;
11163
0
    return QualType();
11164
0
  }
11165
11166
  // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11167
  // invalid since the ambiguity can affect the ABI.
11168
0
  auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11169
0
                                  unsigned &SVEorRVV) {
11170
0
    const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11171
0
    const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11172
11173
0
    SVEorRVV = 0;
11174
0
    if (FirstVecType && SecondVecType) {
11175
0
      if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11176
0
        if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11177
0
            SecondVecType->getVectorKind() ==
11178
0
                VectorKind::SveFixedLengthPredicate)
11179
0
          return true;
11180
0
        if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData) {
11181
0
          SVEorRVV = 1;
11182
0
          return true;
11183
0
        }
11184
0
      }
11185
0
      return false;
11186
0
    }
11187
11188
0
    if (SecondVecType &&
11189
0
        SecondVecType->getVectorKind() == VectorKind::Generic) {
11190
0
      if (FirstType->isSVESizelessBuiltinType())
11191
0
        return true;
11192
0
      if (FirstType->isRVVSizelessBuiltinType()) {
11193
0
        SVEorRVV = 1;
11194
0
        return true;
11195
0
      }
11196
0
    }
11197
11198
0
    return false;
11199
0
  };
11200
11201
0
  if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11202
0
      IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11203
0
    Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11204
0
        << SVEorRVV << LHSType << RHSType;
11205
0
    return QualType();
11206
0
  }
11207
11208
  // If there's a vector type and a scalar, try to convert the scalar to
11209
  // the vector element type and splat.
11210
0
  unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11211
0
  if (!RHSVecType) {
11212
0
    if (isa<ExtVectorType>(LHSVecType)) {
11213
0
      if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11214
0
                                    LHSVecType->getElementType(), LHSType,
11215
0
                                    DiagID))
11216
0
        return LHSType;
11217
0
    } else {
11218
0
      if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11219
0
        return LHSType;
11220
0
    }
11221
0
  }
11222
0
  if (!LHSVecType) {
11223
0
    if (isa<ExtVectorType>(RHSVecType)) {
11224
0
      if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11225
0
                                    LHSType, RHSVecType->getElementType(),
11226
0
                                    RHSType, DiagID))
11227
0
        return RHSType;
11228
0
    } else {
11229
0
      if (LHS.get()->isLValue() ||
11230
0
          !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11231
0
        return RHSType;
11232
0
    }
11233
0
  }
11234
11235
  // FIXME: The code below also handles conversion between vectors and
11236
  // non-scalars, we should break this down into fine grained specific checks
11237
  // and emit proper diagnostics.
11238
0
  QualType VecType = LHSVecType ? LHSType : RHSType;
11239
0
  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11240
0
  QualType OtherType = LHSVecType ? RHSType : LHSType;
11241
0
  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11242
0
  if (isLaxVectorConversion(OtherType, VecType)) {
11243
0
    if (Context.getTargetInfo().getTriple().isPPC() &&
11244
0
        anyAltivecTypes(RHSType, LHSType) &&
11245
0
        !Context.areCompatibleVectorTypes(RHSType, LHSType))
11246
0
      Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11247
    // If we're allowing lax vector conversions, only the total (data) size
11248
    // needs to be the same. For non compound assignment, if one of the types is
11249
    // scalar, the result is always the vector type.
11250
0
    if (!IsCompAssign) {
11251
0
      *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11252
0
      return VecType;
11253
    // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11254
    // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11255
    // type. Note that this is already done by non-compound assignments in
11256
    // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11257
    // <1 x T> -> T. The result is also a vector type.
11258
0
    } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11259
0
               (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11260
0
      ExprResult *RHSExpr = &RHS;
11261
0
      *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11262
0
      return VecType;
11263
0
    }
11264
0
  }
11265
11266
  // Okay, the expression is invalid.
11267
11268
  // If there's a non-vector, non-real operand, diagnose that.
11269
0
  if ((!RHSVecType && !RHSType->isRealType()) ||
11270
0
      (!LHSVecType && !LHSType->isRealType())) {
11271
0
    Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11272
0
      << LHSType << RHSType
11273
0
      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11274
0
    return QualType();
11275
0
  }
11276
11277
  // OpenCL V1.1 6.2.6.p1:
11278
  // If the operands are of more than one vector type, then an error shall
11279
  // occur. Implicit conversions between vector types are not permitted, per
11280
  // section 6.2.1.
11281
0
  if (getLangOpts().OpenCL &&
11282
0
      RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11283
0
      LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11284
0
    Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11285
0
                                                           << RHSType;
11286
0
    return QualType();
11287
0
  }
11288
11289
11290
  // If there is a vector type that is not a ExtVector and a scalar, we reach
11291
  // this point if scalar could not be converted to the vector's element type
11292
  // without truncation.
11293
0
  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11294
0
      (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11295
0
    QualType Scalar = LHSVecType ? RHSType : LHSType;
11296
0
    QualType Vector = LHSVecType ? LHSType : RHSType;
11297
0
    unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11298
0
    Diag(Loc,
11299
0
         diag::err_typecheck_vector_not_convertable_implict_truncation)
11300
0
        << ScalarOrVector << Scalar << Vector;
11301
11302
0
    return QualType();
11303
0
  }
11304
11305
  // Otherwise, use the generic diagnostic.
11306
0
  Diag(Loc, DiagID)
11307
0
    << LHSType << RHSType
11308
0
    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11309
0
  return QualType();
11310
0
}
11311
11312
QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11313
                                           SourceLocation Loc,
11314
                                           bool IsCompAssign,
11315
0
                                           ArithConvKind OperationKind) {
11316
0
  if (!IsCompAssign) {
11317
0
    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11318
0
    if (LHS.isInvalid())
11319
0
      return QualType();
11320
0
  }
11321
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11322
0
  if (RHS.isInvalid())
11323
0
    return QualType();
11324
11325
0
  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11326
0
  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11327
11328
0
  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11329
0
  const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11330
11331
0
  unsigned DiagID = diag::err_typecheck_invalid_operands;
11332
0
  if ((OperationKind == ACK_Arithmetic) &&
11333
0
      ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11334
0
       (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11335
0
    Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11336
0
                      << RHS.get()->getSourceRange();
11337
0
    return QualType();
11338
0
  }
11339
11340
0
  if (Context.hasSameType(LHSType, RHSType))
11341
0
    return LHSType;
11342
11343
0
  if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11344
0
    if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11345
0
      return LHSType;
11346
0
  }
11347
0
  if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11348
0
    if (LHS.get()->isLValue() ||
11349
0
        !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11350
0
      return RHSType;
11351
0
  }
11352
11353
0
  if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11354
0
      (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11355
0
    Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11356
0
        << LHSType << RHSType << LHS.get()->getSourceRange()
11357
0
        << RHS.get()->getSourceRange();
11358
0
    return QualType();
11359
0
  }
11360
11361
0
  if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11362
0
      Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11363
0
          Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11364
0
    Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11365
0
        << LHSType << RHSType << LHS.get()->getSourceRange()
11366
0
        << RHS.get()->getSourceRange();
11367
0
    return QualType();
11368
0
  }
11369
11370
0
  if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11371
0
    QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11372
0
    QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11373
0
    bool ScalarOrVector =
11374
0
        LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11375
11376
0
    Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11377
0
        << ScalarOrVector << Scalar << Vector;
11378
11379
0
    return QualType();
11380
0
  }
11381
11382
0
  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11383
0
                    << RHS.get()->getSourceRange();
11384
0
  return QualType();
11385
0
}
11386
11387
// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11388
// expression.  These are mainly cases where the null pointer is used as an
11389
// integer instead of a pointer.
11390
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11391
0
                                SourceLocation Loc, bool IsCompare) {
11392
  // The canonical way to check for a GNU null is with isNullPointerConstant,
11393
  // but we use a bit of a hack here for speed; this is a relatively
11394
  // hot path, and isNullPointerConstant is slow.
11395
0
  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11396
0
  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11397
11398
0
  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11399
11400
  // Avoid analyzing cases where the result will either be invalid (and
11401
  // diagnosed as such) or entirely valid and not something to warn about.
11402
0
  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11403
0
      NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11404
0
    return;
11405
11406
  // Comparison operations would not make sense with a null pointer no matter
11407
  // what the other expression is.
11408
0
  if (!IsCompare) {
11409
0
    S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11410
0
        << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11411
0
        << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11412
0
    return;
11413
0
  }
11414
11415
  // The rest of the operations only make sense with a null pointer
11416
  // if the other expression is a pointer.
11417
0
  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11418
0
      NonNullType->canDecayToPointerType())
11419
0
    return;
11420
11421
0
  S.Diag(Loc, diag::warn_null_in_comparison_operation)
11422
0
      << LHSNull /* LHS is NULL */ << NonNullType
11423
0
      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11424
0
}
11425
11426
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11427
0
                                          SourceLocation Loc) {
11428
0
  const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11429
0
  const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11430
0
  if (!LUE || !RUE)
11431
0
    return;
11432
0
  if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11433
0
      RUE->getKind() != UETT_SizeOf)
11434
0
    return;
11435
11436
0
  const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11437
0
  QualType LHSTy = LHSArg->getType();
11438
0
  QualType RHSTy;
11439
11440
0
  if (RUE->isArgumentType())
11441
0
    RHSTy = RUE->getArgumentType().getNonReferenceType();
11442
0
  else
11443
0
    RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11444
11445
0
  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11446
0
    if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11447
0
      return;
11448
11449
0
    S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11450
0
    if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11451
0
      if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11452
0
        S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11453
0
            << LHSArgDecl;
11454
0
    }
11455
0
  } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11456
0
    QualType ArrayElemTy = ArrayTy->getElementType();
11457
0
    if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11458
0
        ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11459
0
        RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11460
0
        S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11461
0
      return;
11462
0
    S.Diag(Loc, diag::warn_division_sizeof_array)
11463
0
        << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11464
0
    if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11465
0
      if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11466
0
        S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11467
0
            << LHSArgDecl;
11468
0
    }
11469
11470
0
    S.Diag(Loc, diag::note_precedence_silence) << RHS;
11471
0
  }
11472
0
}
11473
11474
static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11475
                                               ExprResult &RHS,
11476
0
                                               SourceLocation Loc, bool IsDiv) {
11477
  // Check for division/remainder by zero.
11478
0
  Expr::EvalResult RHSValue;
11479
0
  if (!RHS.get()->isValueDependent() &&
11480
0
      RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11481
0
      RHSValue.Val.getInt() == 0)
11482
0
    S.DiagRuntimeBehavior(Loc, RHS.get(),
11483
0
                          S.PDiag(diag::warn_remainder_division_by_zero)
11484
0
                            << IsDiv << RHS.get()->getSourceRange());
11485
0
}
11486
11487
QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11488
                                           SourceLocation Loc,
11489
0
                                           bool IsCompAssign, bool IsDiv) {
11490
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11491
11492
0
  QualType LHSTy = LHS.get()->getType();
11493
0
  QualType RHSTy = RHS.get()->getType();
11494
0
  if (LHSTy->isVectorType() || RHSTy->isVectorType())
11495
0
    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11496
0
                               /*AllowBothBool*/ getLangOpts().AltiVec,
11497
0
                               /*AllowBoolConversions*/ false,
11498
0
                               /*AllowBooleanOperation*/ false,
11499
0
                               /*ReportInvalid*/ true);
11500
0
  if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11501
0
    return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11502
0
                                       ACK_Arithmetic);
11503
0
  if (!IsDiv &&
11504
0
      (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11505
0
    return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11506
  // For division, only matrix-by-scalar is supported. Other combinations with
11507
  // matrix types are invalid.
11508
0
  if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11509
0
    return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11510
11511
0
  QualType compType = UsualArithmeticConversions(
11512
0
      LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11513
0
  if (LHS.isInvalid() || RHS.isInvalid())
11514
0
    return QualType();
11515
11516
11517
0
  if (compType.isNull() || !compType->isArithmeticType())
11518
0
    return InvalidOperands(Loc, LHS, RHS);
11519
0
  if (IsDiv) {
11520
0
    DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11521
0
    DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11522
0
  }
11523
0
  return compType;
11524
0
}
11525
11526
QualType Sema::CheckRemainderOperands(
11527
0
  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11528
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11529
11530
0
  if (LHS.get()->getType()->isVectorType() ||
11531
0
      RHS.get()->getType()->isVectorType()) {
11532
0
    if (LHS.get()->getType()->hasIntegerRepresentation() &&
11533
0
        RHS.get()->getType()->hasIntegerRepresentation())
11534
0
      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11535
0
                                 /*AllowBothBool*/ getLangOpts().AltiVec,
11536
0
                                 /*AllowBoolConversions*/ false,
11537
0
                                 /*AllowBooleanOperation*/ false,
11538
0
                                 /*ReportInvalid*/ true);
11539
0
    return InvalidOperands(Loc, LHS, RHS);
11540
0
  }
11541
11542
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11543
0
      RHS.get()->getType()->isSveVLSBuiltinType()) {
11544
0
    if (LHS.get()->getType()->hasIntegerRepresentation() &&
11545
0
        RHS.get()->getType()->hasIntegerRepresentation())
11546
0
      return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11547
0
                                         ACK_Arithmetic);
11548
11549
0
    return InvalidOperands(Loc, LHS, RHS);
11550
0
  }
11551
11552
0
  QualType compType = UsualArithmeticConversions(
11553
0
      LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11554
0
  if (LHS.isInvalid() || RHS.isInvalid())
11555
0
    return QualType();
11556
11557
0
  if (compType.isNull() || !compType->isIntegerType())
11558
0
    return InvalidOperands(Loc, LHS, RHS);
11559
0
  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11560
0
  return compType;
11561
0
}
11562
11563
/// Diagnose invalid arithmetic on two void pointers.
11564
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11565
0
                                                Expr *LHSExpr, Expr *RHSExpr) {
11566
0
  S.Diag(Loc, S.getLangOpts().CPlusPlus
11567
0
                ? diag::err_typecheck_pointer_arith_void_type
11568
0
                : diag::ext_gnu_void_ptr)
11569
0
    << 1 /* two pointers */ << LHSExpr->getSourceRange()
11570
0
                            << RHSExpr->getSourceRange();
11571
0
}
11572
11573
/// Diagnose invalid arithmetic on a void pointer.
11574
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11575
0
                                            Expr *Pointer) {
11576
0
  S.Diag(Loc, S.getLangOpts().CPlusPlus
11577
0
                ? diag::err_typecheck_pointer_arith_void_type
11578
0
                : diag::ext_gnu_void_ptr)
11579
0
    << 0 /* one pointer */ << Pointer->getSourceRange();
11580
0
}
11581
11582
/// Diagnose invalid arithmetic on a null pointer.
11583
///
11584
/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11585
/// idiom, which we recognize as a GNU extension.
11586
///
11587
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11588
0
                                            Expr *Pointer, bool IsGNUIdiom) {
11589
0
  if (IsGNUIdiom)
11590
0
    S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11591
0
      << Pointer->getSourceRange();
11592
0
  else
11593
0
    S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11594
0
      << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11595
0
}
11596
11597
/// Diagnose invalid subraction on a null pointer.
11598
///
11599
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11600
0
                                             Expr *Pointer, bool BothNull) {
11601
  // Null - null is valid in C++ [expr.add]p7
11602
0
  if (BothNull && S.getLangOpts().CPlusPlus)
11603
0
    return;
11604
11605
  // Is this s a macro from a system header?
11606
0
  if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11607
0
    return;
11608
11609
0
  S.DiagRuntimeBehavior(Loc, Pointer,
11610
0
                        S.PDiag(diag::warn_pointer_sub_null_ptr)
11611
0
                            << S.getLangOpts().CPlusPlus
11612
0
                            << Pointer->getSourceRange());
11613
0
}
11614
11615
/// Diagnose invalid arithmetic on two function pointers.
11616
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11617
0
                                                    Expr *LHS, Expr *RHS) {
11618
0
  assert(LHS->getType()->isAnyPointerType());
11619
0
  assert(RHS->getType()->isAnyPointerType());
11620
0
  S.Diag(Loc, S.getLangOpts().CPlusPlus
11621
0
                ? diag::err_typecheck_pointer_arith_function_type
11622
0
                : diag::ext_gnu_ptr_func_arith)
11623
0
    << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11624
    // We only show the second type if it differs from the first.
11625
0
    << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11626
0
                                                   RHS->getType())
11627
0
    << RHS->getType()->getPointeeType()
11628
0
    << LHS->getSourceRange() << RHS->getSourceRange();
11629
0
}
11630
11631
/// Diagnose invalid arithmetic on a function pointer.
11632
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11633
0
                                                Expr *Pointer) {
11634
0
  assert(Pointer->getType()->isAnyPointerType());
11635
0
  S.Diag(Loc, S.getLangOpts().CPlusPlus
11636
0
                ? diag::err_typecheck_pointer_arith_function_type
11637
0
                : diag::ext_gnu_ptr_func_arith)
11638
0
    << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11639
0
    << 0 /* one pointer, so only one type */
11640
0
    << Pointer->getSourceRange();
11641
0
}
11642
11643
/// Emit error if Operand is incomplete pointer type
11644
///
11645
/// \returns True if pointer has incomplete type
11646
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11647
0
                                                 Expr *Operand) {
11648
0
  QualType ResType = Operand->getType();
11649
0
  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11650
0
    ResType = ResAtomicType->getValueType();
11651
11652
0
  assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11653
0
  QualType PointeeTy = ResType->getPointeeType();
11654
0
  return S.RequireCompleteSizedType(
11655
0
      Loc, PointeeTy,
11656
0
      diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11657
0
      Operand->getSourceRange());
11658
0
}
11659
11660
/// Check the validity of an arithmetic pointer operand.
11661
///
11662
/// If the operand has pointer type, this code will check for pointer types
11663
/// which are invalid in arithmetic operations. These will be diagnosed
11664
/// appropriately, including whether or not the use is supported as an
11665
/// extension.
11666
///
11667
/// \returns True when the operand is valid to use (even if as an extension).
11668
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11669
0
                                            Expr *Operand) {
11670
0
  QualType ResType = Operand->getType();
11671
0
  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11672
0
    ResType = ResAtomicType->getValueType();
11673
11674
0
  if (!ResType->isAnyPointerType()) return true;
11675
11676
0
  QualType PointeeTy = ResType->getPointeeType();
11677
0
  if (PointeeTy->isVoidType()) {
11678
0
    diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11679
0
    return !S.getLangOpts().CPlusPlus;
11680
0
  }
11681
0
  if (PointeeTy->isFunctionType()) {
11682
0
    diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11683
0
    return !S.getLangOpts().CPlusPlus;
11684
0
  }
11685
11686
0
  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11687
11688
0
  return true;
11689
0
}
11690
11691
/// Check the validity of a binary arithmetic operation w.r.t. pointer
11692
/// operands.
11693
///
11694
/// This routine will diagnose any invalid arithmetic on pointer operands much
11695
/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11696
/// for emitting a single diagnostic even for operations where both LHS and RHS
11697
/// are (potentially problematic) pointers.
11698
///
11699
/// \returns True when the operand is valid to use (even if as an extension).
11700
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11701
0
                                                Expr *LHSExpr, Expr *RHSExpr) {
11702
0
  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11703
0
  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11704
0
  if (!isLHSPointer && !isRHSPointer) return true;
11705
11706
0
  QualType LHSPointeeTy, RHSPointeeTy;
11707
0
  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11708
0
  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11709
11710
  // if both are pointers check if operation is valid wrt address spaces
11711
0
  if (isLHSPointer && isRHSPointer) {
11712
0
    if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11713
0
      S.Diag(Loc,
11714
0
             diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11715
0
          << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11716
0
          << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11717
0
      return false;
11718
0
    }
11719
0
  }
11720
11721
  // Check for arithmetic on pointers to incomplete types.
11722
0
  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11723
0
  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11724
0
  if (isLHSVoidPtr || isRHSVoidPtr) {
11725
0
    if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11726
0
    else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11727
0
    else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11728
11729
0
    return !S.getLangOpts().CPlusPlus;
11730
0
  }
11731
11732
0
  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11733
0
  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11734
0
  if (isLHSFuncPtr || isRHSFuncPtr) {
11735
0
    if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11736
0
    else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11737
0
                                                                RHSExpr);
11738
0
    else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11739
11740
0
    return !S.getLangOpts().CPlusPlus;
11741
0
  }
11742
11743
0
  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11744
0
    return false;
11745
0
  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11746
0
    return false;
11747
11748
0
  return true;
11749
0
}
11750
11751
/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11752
/// literal.
11753
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11754
0
                                  Expr *LHSExpr, Expr *RHSExpr) {
11755
0
  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11756
0
  Expr* IndexExpr = RHSExpr;
11757
0
  if (!StrExpr) {
11758
0
    StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11759
0
    IndexExpr = LHSExpr;
11760
0
  }
11761
11762
0
  bool IsStringPlusInt = StrExpr &&
11763
0
      IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11764
0
  if (!IsStringPlusInt || IndexExpr->isValueDependent())
11765
0
    return;
11766
11767
0
  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11768
0
  Self.Diag(OpLoc, diag::warn_string_plus_int)
11769
0
      << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11770
11771
  // Only print a fixit for "str" + int, not for int + "str".
11772
0
  if (IndexExpr == RHSExpr) {
11773
0
    SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11774
0
    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11775
0
        << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11776
0
        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11777
0
        << FixItHint::CreateInsertion(EndLoc, "]");
11778
0
  } else
11779
0
    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11780
0
}
11781
11782
/// Emit a warning when adding a char literal to a string.
11783
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11784
0
                                   Expr *LHSExpr, Expr *RHSExpr) {
11785
0
  const Expr *StringRefExpr = LHSExpr;
11786
0
  const CharacterLiteral *CharExpr =
11787
0
      dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11788
11789
0
  if (!CharExpr) {
11790
0
    CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11791
0
    StringRefExpr = RHSExpr;
11792
0
  }
11793
11794
0
  if (!CharExpr || !StringRefExpr)
11795
0
    return;
11796
11797
0
  const QualType StringType = StringRefExpr->getType();
11798
11799
  // Return if not a PointerType.
11800
0
  if (!StringType->isAnyPointerType())
11801
0
    return;
11802
11803
  // Return if not a CharacterType.
11804
0
  if (!StringType->getPointeeType()->isAnyCharacterType())
11805
0
    return;
11806
11807
0
  ASTContext &Ctx = Self.getASTContext();
11808
0
  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11809
11810
0
  const QualType CharType = CharExpr->getType();
11811
0
  if (!CharType->isAnyCharacterType() &&
11812
0
      CharType->isIntegerType() &&
11813
0
      llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11814
0
    Self.Diag(OpLoc, diag::warn_string_plus_char)
11815
0
        << DiagRange << Ctx.CharTy;
11816
0
  } else {
11817
0
    Self.Diag(OpLoc, diag::warn_string_plus_char)
11818
0
        << DiagRange << CharExpr->getType();
11819
0
  }
11820
11821
  // Only print a fixit for str + char, not for char + str.
11822
0
  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11823
0
    SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11824
0
    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11825
0
        << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11826
0
        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11827
0
        << FixItHint::CreateInsertion(EndLoc, "]");
11828
0
  } else {
11829
0
    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11830
0
  }
11831
0
}
11832
11833
/// Emit error when two pointers are incompatible.
11834
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11835
0
                                           Expr *LHSExpr, Expr *RHSExpr) {
11836
0
  assert(LHSExpr->getType()->isAnyPointerType());
11837
0
  assert(RHSExpr->getType()->isAnyPointerType());
11838
0
  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11839
0
    << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11840
0
    << RHSExpr->getSourceRange();
11841
0
}
11842
11843
// C99 6.5.6
11844
QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11845
                                     SourceLocation Loc, BinaryOperatorKind Opc,
11846
0
                                     QualType* CompLHSTy) {
11847
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11848
11849
0
  if (LHS.get()->getType()->isVectorType() ||
11850
0
      RHS.get()->getType()->isVectorType()) {
11851
0
    QualType compType =
11852
0
        CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11853
0
                            /*AllowBothBool*/ getLangOpts().AltiVec,
11854
0
                            /*AllowBoolConversions*/ getLangOpts().ZVector,
11855
0
                            /*AllowBooleanOperation*/ false,
11856
0
                            /*ReportInvalid*/ true);
11857
0
    if (CompLHSTy) *CompLHSTy = compType;
11858
0
    return compType;
11859
0
  }
11860
11861
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11862
0
      RHS.get()->getType()->isSveVLSBuiltinType()) {
11863
0
    QualType compType =
11864
0
        CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11865
0
    if (CompLHSTy)
11866
0
      *CompLHSTy = compType;
11867
0
    return compType;
11868
0
  }
11869
11870
0
  if (LHS.get()->getType()->isConstantMatrixType() ||
11871
0
      RHS.get()->getType()->isConstantMatrixType()) {
11872
0
    QualType compType =
11873
0
        CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11874
0
    if (CompLHSTy)
11875
0
      *CompLHSTy = compType;
11876
0
    return compType;
11877
0
  }
11878
11879
0
  QualType compType = UsualArithmeticConversions(
11880
0
      LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11881
0
  if (LHS.isInvalid() || RHS.isInvalid())
11882
0
    return QualType();
11883
11884
  // Diagnose "string literal" '+' int and string '+' "char literal".
11885
0
  if (Opc == BO_Add) {
11886
0
    diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11887
0
    diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11888
0
  }
11889
11890
  // handle the common case first (both operands are arithmetic).
11891
0
  if (!compType.isNull() && compType->isArithmeticType()) {
11892
0
    if (CompLHSTy) *CompLHSTy = compType;
11893
0
    return compType;
11894
0
  }
11895
11896
  // Type-checking.  Ultimately the pointer's going to be in PExp;
11897
  // note that we bias towards the LHS being the pointer.
11898
0
  Expr *PExp = LHS.get(), *IExp = RHS.get();
11899
11900
0
  bool isObjCPointer;
11901
0
  if (PExp->getType()->isPointerType()) {
11902
0
    isObjCPointer = false;
11903
0
  } else if (PExp->getType()->isObjCObjectPointerType()) {
11904
0
    isObjCPointer = true;
11905
0
  } else {
11906
0
    std::swap(PExp, IExp);
11907
0
    if (PExp->getType()->isPointerType()) {
11908
0
      isObjCPointer = false;
11909
0
    } else if (PExp->getType()->isObjCObjectPointerType()) {
11910
0
      isObjCPointer = true;
11911
0
    } else {
11912
0
      return InvalidOperands(Loc, LHS, RHS);
11913
0
    }
11914
0
  }
11915
0
  assert(PExp->getType()->isAnyPointerType());
11916
11917
0
  if (!IExp->getType()->isIntegerType())
11918
0
    return InvalidOperands(Loc, LHS, RHS);
11919
11920
  // Adding to a null pointer results in undefined behavior.
11921
0
  if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11922
0
          Context, Expr::NPC_ValueDependentIsNotNull)) {
11923
    // In C++ adding zero to a null pointer is defined.
11924
0
    Expr::EvalResult KnownVal;
11925
0
    if (!getLangOpts().CPlusPlus ||
11926
0
        (!IExp->isValueDependent() &&
11927
0
         (!IExp->EvaluateAsInt(KnownVal, Context) ||
11928
0
          KnownVal.Val.getInt() != 0))) {
11929
      // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11930
0
      bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11931
0
          Context, BO_Add, PExp, IExp);
11932
0
      diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11933
0
    }
11934
0
  }
11935
11936
0
  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11937
0
    return QualType();
11938
11939
0
  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11940
0
    return QualType();
11941
11942
  // Check array bounds for pointer arithemtic
11943
0
  CheckArrayAccess(PExp, IExp);
11944
11945
0
  if (CompLHSTy) {
11946
0
    QualType LHSTy = Context.isPromotableBitField(LHS.get());
11947
0
    if (LHSTy.isNull()) {
11948
0
      LHSTy = LHS.get()->getType();
11949
0
      if (Context.isPromotableIntegerType(LHSTy))
11950
0
        LHSTy = Context.getPromotedIntegerType(LHSTy);
11951
0
    }
11952
0
    *CompLHSTy = LHSTy;
11953
0
  }
11954
11955
0
  return PExp->getType();
11956
0
}
11957
11958
// C99 6.5.6
11959
QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11960
                                        SourceLocation Loc,
11961
0
                                        QualType* CompLHSTy) {
11962
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11963
11964
0
  if (LHS.get()->getType()->isVectorType() ||
11965
0
      RHS.get()->getType()->isVectorType()) {
11966
0
    QualType compType =
11967
0
        CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11968
0
                            /*AllowBothBool*/ getLangOpts().AltiVec,
11969
0
                            /*AllowBoolConversions*/ getLangOpts().ZVector,
11970
0
                            /*AllowBooleanOperation*/ false,
11971
0
                            /*ReportInvalid*/ true);
11972
0
    if (CompLHSTy) *CompLHSTy = compType;
11973
0
    return compType;
11974
0
  }
11975
11976
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11977
0
      RHS.get()->getType()->isSveVLSBuiltinType()) {
11978
0
    QualType compType =
11979
0
        CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11980
0
    if (CompLHSTy)
11981
0
      *CompLHSTy = compType;
11982
0
    return compType;
11983
0
  }
11984
11985
0
  if (LHS.get()->getType()->isConstantMatrixType() ||
11986
0
      RHS.get()->getType()->isConstantMatrixType()) {
11987
0
    QualType compType =
11988
0
        CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11989
0
    if (CompLHSTy)
11990
0
      *CompLHSTy = compType;
11991
0
    return compType;
11992
0
  }
11993
11994
0
  QualType compType = UsualArithmeticConversions(
11995
0
      LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11996
0
  if (LHS.isInvalid() || RHS.isInvalid())
11997
0
    return QualType();
11998
11999
  // Enforce type constraints: C99 6.5.6p3.
12000
12001
  // Handle the common case first (both operands are arithmetic).
12002
0
  if (!compType.isNull() && compType->isArithmeticType()) {
12003
0
    if (CompLHSTy) *CompLHSTy = compType;
12004
0
    return compType;
12005
0
  }
12006
12007
  // Either ptr - int   or   ptr - ptr.
12008
0
  if (LHS.get()->getType()->isAnyPointerType()) {
12009
0
    QualType lpointee = LHS.get()->getType()->getPointeeType();
12010
12011
    // Diagnose bad cases where we step over interface counts.
12012
0
    if (LHS.get()->getType()->isObjCObjectPointerType() &&
12013
0
        checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
12014
0
      return QualType();
12015
12016
    // The result type of a pointer-int computation is the pointer type.
12017
0
    if (RHS.get()->getType()->isIntegerType()) {
12018
      // Subtracting from a null pointer should produce a warning.
12019
      // The last argument to the diagnose call says this doesn't match the
12020
      // GNU int-to-pointer idiom.
12021
0
      if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
12022
0
                                           Expr::NPC_ValueDependentIsNotNull)) {
12023
        // In C++ adding zero to a null pointer is defined.
12024
0
        Expr::EvalResult KnownVal;
12025
0
        if (!getLangOpts().CPlusPlus ||
12026
0
            (!RHS.get()->isValueDependent() &&
12027
0
             (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
12028
0
              KnownVal.Val.getInt() != 0))) {
12029
0
          diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
12030
0
        }
12031
0
      }
12032
12033
0
      if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
12034
0
        return QualType();
12035
12036
      // Check array bounds for pointer arithemtic
12037
0
      CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
12038
0
                       /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12039
12040
0
      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12041
0
      return LHS.get()->getType();
12042
0
    }
12043
12044
    // Handle pointer-pointer subtractions.
12045
0
    if (const PointerType *RHSPTy
12046
0
          = RHS.get()->getType()->getAs<PointerType>()) {
12047
0
      QualType rpointee = RHSPTy->getPointeeType();
12048
12049
0
      if (getLangOpts().CPlusPlus) {
12050
        // Pointee types must be the same: C++ [expr.add]
12051
0
        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
12052
0
          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12053
0
        }
12054
0
      } else {
12055
        // Pointee types must be compatible C99 6.5.6p3
12056
0
        if (!Context.typesAreCompatible(
12057
0
                Context.getCanonicalType(lpointee).getUnqualifiedType(),
12058
0
                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
12059
0
          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12060
0
          return QualType();
12061
0
        }
12062
0
      }
12063
12064
0
      if (!checkArithmeticBinOpPointerOperands(*this, Loc,
12065
0
                                               LHS.get(), RHS.get()))
12066
0
        return QualType();
12067
12068
0
      bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12069
0
          Context, Expr::NPC_ValueDependentIsNotNull);
12070
0
      bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12071
0
          Context, Expr::NPC_ValueDependentIsNotNull);
12072
12073
      // Subtracting nullptr or from nullptr is suspect
12074
0
      if (LHSIsNullPtr)
12075
0
        diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
12076
0
      if (RHSIsNullPtr)
12077
0
        diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
12078
12079
      // The pointee type may have zero size.  As an extension, a structure or
12080
      // union may have zero size or an array may have zero length.  In this
12081
      // case subtraction does not make sense.
12082
0
      if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
12083
0
        CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
12084
0
        if (ElementSize.isZero()) {
12085
0
          Diag(Loc,diag::warn_sub_ptr_zero_size_types)
12086
0
            << rpointee.getUnqualifiedType()
12087
0
            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12088
0
        }
12089
0
      }
12090
12091
0
      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12092
0
      return Context.getPointerDiffType();
12093
0
    }
12094
0
  }
12095
12096
0
  return InvalidOperands(Loc, LHS, RHS);
12097
0
}
12098
12099
0
static bool isScopedEnumerationType(QualType T) {
12100
0
  if (const EnumType *ET = T->getAs<EnumType>())
12101
0
    return ET->getDecl()->isScoped();
12102
0
  return false;
12103
0
}
12104
12105
static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12106
                                   SourceLocation Loc, BinaryOperatorKind Opc,
12107
0
                                   QualType LHSType) {
12108
  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12109
  // so skip remaining warnings as we don't want to modify values within Sema.
12110
0
  if (S.getLangOpts().OpenCL)
12111
0
    return;
12112
12113
  // Check right/shifter operand
12114
0
  Expr::EvalResult RHSResult;
12115
0
  if (RHS.get()->isValueDependent() ||
12116
0
      !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
12117
0
    return;
12118
0
  llvm::APSInt Right = RHSResult.Val.getInt();
12119
12120
0
  if (Right.isNegative()) {
12121
0
    S.DiagRuntimeBehavior(Loc, RHS.get(),
12122
0
                          S.PDiag(diag::warn_shift_negative)
12123
0
                            << RHS.get()->getSourceRange());
12124
0
    return;
12125
0
  }
12126
12127
0
  QualType LHSExprType = LHS.get()->getType();
12128
0
  uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
12129
0
  if (LHSExprType->isBitIntType())
12130
0
    LeftSize = S.Context.getIntWidth(LHSExprType);
12131
0
  else if (LHSExprType->isFixedPointType()) {
12132
0
    auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
12133
0
    LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12134
0
  }
12135
0
  if (Right.uge(LeftSize)) {
12136
0
    S.DiagRuntimeBehavior(Loc, RHS.get(),
12137
0
                          S.PDiag(diag::warn_shift_gt_typewidth)
12138
0
                            << RHS.get()->getSourceRange());
12139
0
    return;
12140
0
  }
12141
12142
  // FIXME: We probably need to handle fixed point types specially here.
12143
0
  if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12144
0
    return;
12145
12146
  // When left shifting an ICE which is signed, we can check for overflow which
12147
  // according to C++ standards prior to C++2a has undefined behavior
12148
  // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12149
  // more than the maximum value representable in the result type, so never
12150
  // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12151
  // expression is still probably a bug.)
12152
0
  Expr::EvalResult LHSResult;
12153
0
  if (LHS.get()->isValueDependent() ||
12154
0
      LHSType->hasUnsignedIntegerRepresentation() ||
12155
0
      !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12156
0
    return;
12157
0
  llvm::APSInt Left = LHSResult.Val.getInt();
12158
12159
  // Don't warn if signed overflow is defined, then all the rest of the
12160
  // diagnostics will not be triggered because the behavior is defined.
12161
  // Also don't warn in C++20 mode (and newer), as signed left shifts
12162
  // always wrap and never overflow.
12163
0
  if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12164
0
    return;
12165
12166
  // If LHS does not have a non-negative value then, the
12167
  // behavior is undefined before C++2a. Warn about it.
12168
0
  if (Left.isNegative()) {
12169
0
    S.DiagRuntimeBehavior(Loc, LHS.get(),
12170
0
                          S.PDiag(diag::warn_shift_lhs_negative)
12171
0
                            << LHS.get()->getSourceRange());
12172
0
    return;
12173
0
  }
12174
12175
0
  llvm::APInt ResultBits =
12176
0
      static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12177
0
  if (ResultBits.ule(LeftSize))
12178
0
    return;
12179
0
  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12180
0
  Result = Result.shl(Right);
12181
12182
  // Print the bit representation of the signed integer as an unsigned
12183
  // hexadecimal number.
12184
0
  SmallString<40> HexResult;
12185
0
  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12186
12187
  // If we are only missing a sign bit, this is less likely to result in actual
12188
  // bugs -- if the result is cast back to an unsigned type, it will have the
12189
  // expected value. Thus we place this behind a different warning that can be
12190
  // turned off separately if needed.
12191
0
  if (ResultBits - 1 == LeftSize) {
12192
0
    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12193
0
        << HexResult << LHSType
12194
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12195
0
    return;
12196
0
  }
12197
12198
0
  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12199
0
      << HexResult.str() << Result.getSignificantBits() << LHSType
12200
0
      << Left.getBitWidth() << LHS.get()->getSourceRange()
12201
0
      << RHS.get()->getSourceRange();
12202
0
}
12203
12204
/// Return the resulting type when a vector is shifted
12205
///        by a scalar or vector shift amount.
12206
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12207
0
                                 SourceLocation Loc, bool IsCompAssign) {
12208
  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12209
0
  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12210
0
      !LHS.get()->getType()->isVectorType()) {
12211
0
    S.Diag(Loc, diag::err_shift_rhs_only_vector)
12212
0
      << RHS.get()->getType() << LHS.get()->getType()
12213
0
      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12214
0
    return QualType();
12215
0
  }
12216
12217
0
  if (!IsCompAssign) {
12218
0
    LHS = S.UsualUnaryConversions(LHS.get());
12219
0
    if (LHS.isInvalid()) return QualType();
12220
0
  }
12221
12222
0
  RHS = S.UsualUnaryConversions(RHS.get());
12223
0
  if (RHS.isInvalid()) return QualType();
12224
12225
0
  QualType LHSType = LHS.get()->getType();
12226
  // Note that LHS might be a scalar because the routine calls not only in
12227
  // OpenCL case.
12228
0
  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12229
0
  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12230
12231
  // Note that RHS might not be a vector.
12232
0
  QualType RHSType = RHS.get()->getType();
12233
0
  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12234
0
  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12235
12236
  // Do not allow shifts for boolean vectors.
12237
0
  if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12238
0
      (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12239
0
    S.Diag(Loc, diag::err_typecheck_invalid_operands)
12240
0
        << LHS.get()->getType() << RHS.get()->getType()
12241
0
        << LHS.get()->getSourceRange();
12242
0
    return QualType();
12243
0
  }
12244
12245
  // The operands need to be integers.
12246
0
  if (!LHSEleType->isIntegerType()) {
12247
0
    S.Diag(Loc, diag::err_typecheck_expect_int)
12248
0
      << LHS.get()->getType() << LHS.get()->getSourceRange();
12249
0
    return QualType();
12250
0
  }
12251
12252
0
  if (!RHSEleType->isIntegerType()) {
12253
0
    S.Diag(Loc, diag::err_typecheck_expect_int)
12254
0
      << RHS.get()->getType() << RHS.get()->getSourceRange();
12255
0
    return QualType();
12256
0
  }
12257
12258
0
  if (!LHSVecTy) {
12259
0
    assert(RHSVecTy);
12260
0
    if (IsCompAssign)
12261
0
      return RHSType;
12262
0
    if (LHSEleType != RHSEleType) {
12263
0
      LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12264
0
      LHSEleType = RHSEleType;
12265
0
    }
12266
0
    QualType VecTy =
12267
0
        S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12268
0
    LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12269
0
    LHSType = VecTy;
12270
0
  } else if (RHSVecTy) {
12271
    // OpenCL v1.1 s6.3.j says that for vector types, the operators
12272
    // are applied component-wise. So if RHS is a vector, then ensure
12273
    // that the number of elements is the same as LHS...
12274
0
    if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12275
0
      S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12276
0
        << LHS.get()->getType() << RHS.get()->getType()
12277
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12278
0
      return QualType();
12279
0
    }
12280
0
    if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12281
0
      const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12282
0
      const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12283
0
      if (LHSBT != RHSBT &&
12284
0
          S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12285
0
        S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12286
0
            << LHS.get()->getType() << RHS.get()->getType()
12287
0
            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12288
0
      }
12289
0
    }
12290
0
  } else {
12291
    // ...else expand RHS to match the number of elements in LHS.
12292
0
    QualType VecTy =
12293
0
      S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12294
0
    RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12295
0
  }
12296
12297
0
  return LHSType;
12298
0
}
12299
12300
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12301
                                         ExprResult &RHS, SourceLocation Loc,
12302
0
                                         bool IsCompAssign) {
12303
0
  if (!IsCompAssign) {
12304
0
    LHS = S.UsualUnaryConversions(LHS.get());
12305
0
    if (LHS.isInvalid())
12306
0
      return QualType();
12307
0
  }
12308
12309
0
  RHS = S.UsualUnaryConversions(RHS.get());
12310
0
  if (RHS.isInvalid())
12311
0
    return QualType();
12312
12313
0
  QualType LHSType = LHS.get()->getType();
12314
0
  const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12315
0
  QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12316
0
                            ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12317
0
                            : LHSType;
12318
12319
  // Note that RHS might not be a vector
12320
0
  QualType RHSType = RHS.get()->getType();
12321
0
  const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12322
0
  QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12323
0
                            ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12324
0
                            : RHSType;
12325
12326
0
  if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12327
0
      (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12328
0
    S.Diag(Loc, diag::err_typecheck_invalid_operands)
12329
0
        << LHSType << RHSType << LHS.get()->getSourceRange();
12330
0
    return QualType();
12331
0
  }
12332
12333
0
  if (!LHSEleType->isIntegerType()) {
12334
0
    S.Diag(Loc, diag::err_typecheck_expect_int)
12335
0
        << LHS.get()->getType() << LHS.get()->getSourceRange();
12336
0
    return QualType();
12337
0
  }
12338
12339
0
  if (!RHSEleType->isIntegerType()) {
12340
0
    S.Diag(Loc, diag::err_typecheck_expect_int)
12341
0
        << RHS.get()->getType() << RHS.get()->getSourceRange();
12342
0
    return QualType();
12343
0
  }
12344
12345
0
  if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12346
0
      (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12347
0
       S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12348
0
    S.Diag(Loc, diag::err_typecheck_invalid_operands)
12349
0
        << LHSType << RHSType << LHS.get()->getSourceRange()
12350
0
        << RHS.get()->getSourceRange();
12351
0
    return QualType();
12352
0
  }
12353
12354
0
  if (!LHSType->isSveVLSBuiltinType()) {
12355
0
    assert(RHSType->isSveVLSBuiltinType());
12356
0
    if (IsCompAssign)
12357
0
      return RHSType;
12358
0
    if (LHSEleType != RHSEleType) {
12359
0
      LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12360
0
      LHSEleType = RHSEleType;
12361
0
    }
12362
0
    const llvm::ElementCount VecSize =
12363
0
        S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12364
0
    QualType VecTy =
12365
0
        S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12366
0
    LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12367
0
    LHSType = VecTy;
12368
0
  } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12369
0
    if (S.Context.getTypeSize(RHSBuiltinTy) !=
12370
0
        S.Context.getTypeSize(LHSBuiltinTy)) {
12371
0
      S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12372
0
          << LHSType << RHSType << LHS.get()->getSourceRange()
12373
0
          << RHS.get()->getSourceRange();
12374
0
      return QualType();
12375
0
    }
12376
0
  } else {
12377
0
    const llvm::ElementCount VecSize =
12378
0
        S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12379
0
    if (LHSEleType != RHSEleType) {
12380
0
      RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12381
0
      RHSEleType = LHSEleType;
12382
0
    }
12383
0
    QualType VecTy =
12384
0
        S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12385
0
    RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12386
0
  }
12387
12388
0
  return LHSType;
12389
0
}
12390
12391
// C99 6.5.7
12392
QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12393
                                  SourceLocation Loc, BinaryOperatorKind Opc,
12394
0
                                  bool IsCompAssign) {
12395
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12396
12397
  // Vector shifts promote their scalar inputs to vector type.
12398
0
  if (LHS.get()->getType()->isVectorType() ||
12399
0
      RHS.get()->getType()->isVectorType()) {
12400
0
    if (LangOpts.ZVector) {
12401
      // The shift operators for the z vector extensions work basically
12402
      // like general shifts, except that neither the LHS nor the RHS is
12403
      // allowed to be a "vector bool".
12404
0
      if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12405
0
        if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12406
0
          return InvalidOperands(Loc, LHS, RHS);
12407
0
      if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12408
0
        if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12409
0
          return InvalidOperands(Loc, LHS, RHS);
12410
0
    }
12411
0
    return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12412
0
  }
12413
12414
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12415
0
      RHS.get()->getType()->isSveVLSBuiltinType())
12416
0
    return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12417
12418
  // Shifts don't perform usual arithmetic conversions, they just do integer
12419
  // promotions on each operand. C99 6.5.7p3
12420
12421
  // For the LHS, do usual unary conversions, but then reset them away
12422
  // if this is a compound assignment.
12423
0
  ExprResult OldLHS = LHS;
12424
0
  LHS = UsualUnaryConversions(LHS.get());
12425
0
  if (LHS.isInvalid())
12426
0
    return QualType();
12427
0
  QualType LHSType = LHS.get()->getType();
12428
0
  if (IsCompAssign) LHS = OldLHS;
12429
12430
  // The RHS is simpler.
12431
0
  RHS = UsualUnaryConversions(RHS.get());
12432
0
  if (RHS.isInvalid())
12433
0
    return QualType();
12434
0
  QualType RHSType = RHS.get()->getType();
12435
12436
  // C99 6.5.7p2: Each of the operands shall have integer type.
12437
  // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12438
0
  if ((!LHSType->isFixedPointOrIntegerType() &&
12439
0
       !LHSType->hasIntegerRepresentation()) ||
12440
0
      !RHSType->hasIntegerRepresentation())
12441
0
    return InvalidOperands(Loc, LHS, RHS);
12442
12443
  // C++0x: Don't allow scoped enums. FIXME: Use something better than
12444
  // hasIntegerRepresentation() above instead of this.
12445
0
  if (isScopedEnumerationType(LHSType) ||
12446
0
      isScopedEnumerationType(RHSType)) {
12447
0
    return InvalidOperands(Loc, LHS, RHS);
12448
0
  }
12449
0
  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12450
12451
  // "The type of the result is that of the promoted left operand."
12452
0
  return LHSType;
12453
0
}
12454
12455
/// Diagnose bad pointer comparisons.
12456
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12457
                                              ExprResult &LHS, ExprResult &RHS,
12458
0
                                              bool IsError) {
12459
0
  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12460
0
                      : diag::ext_typecheck_comparison_of_distinct_pointers)
12461
0
    << LHS.get()->getType() << RHS.get()->getType()
12462
0
    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12463
0
}
12464
12465
/// Returns false if the pointers are converted to a composite type,
12466
/// true otherwise.
12467
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12468
0
                                           ExprResult &LHS, ExprResult &RHS) {
12469
  // C++ [expr.rel]p2:
12470
  //   [...] Pointer conversions (4.10) and qualification
12471
  //   conversions (4.4) are performed on pointer operands (or on
12472
  //   a pointer operand and a null pointer constant) to bring
12473
  //   them to their composite pointer type. [...]
12474
  //
12475
  // C++ [expr.eq]p1 uses the same notion for (in)equality
12476
  // comparisons of pointers.
12477
12478
0
  QualType LHSType = LHS.get()->getType();
12479
0
  QualType RHSType = RHS.get()->getType();
12480
0
  assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12481
0
         LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12482
12483
0
  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12484
0
  if (T.isNull()) {
12485
0
    if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12486
0
        (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12487
0
      diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12488
0
    else
12489
0
      S.InvalidOperands(Loc, LHS, RHS);
12490
0
    return true;
12491
0
  }
12492
12493
0
  return false;
12494
0
}
12495
12496
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12497
                                                    ExprResult &LHS,
12498
                                                    ExprResult &RHS,
12499
0
                                                    bool IsError) {
12500
0
  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12501
0
                      : diag::ext_typecheck_comparison_of_fptr_to_void)
12502
0
    << LHS.get()->getType() << RHS.get()->getType()
12503
0
    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12504
0
}
12505
12506
0
static bool isObjCObjectLiteral(ExprResult &E) {
12507
0
  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12508
0
  case Stmt::ObjCArrayLiteralClass:
12509
0
  case Stmt::ObjCDictionaryLiteralClass:
12510
0
  case Stmt::ObjCStringLiteralClass:
12511
0
  case Stmt::ObjCBoxedExprClass:
12512
0
    return true;
12513
0
  default:
12514
    // Note that ObjCBoolLiteral is NOT an object literal!
12515
0
    return false;
12516
0
  }
12517
0
}
12518
12519
0
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12520
0
  const ObjCObjectPointerType *Type =
12521
0
    LHS->getType()->getAs<ObjCObjectPointerType>();
12522
12523
  // If this is not actually an Objective-C object, bail out.
12524
0
  if (!Type)
12525
0
    return false;
12526
12527
  // Get the LHS object's interface type.
12528
0
  QualType InterfaceType = Type->getPointeeType();
12529
12530
  // If the RHS isn't an Objective-C object, bail out.
12531
0
  if (!RHS->getType()->isObjCObjectPointerType())
12532
0
    return false;
12533
12534
  // Try to find the -isEqual: method.
12535
0
  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12536
0
  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12537
0
                                                      InterfaceType,
12538
0
                                                      /*IsInstance=*/true);
12539
0
  if (!Method) {
12540
0
    if (Type->isObjCIdType()) {
12541
      // For 'id', just check the global pool.
12542
0
      Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12543
0
                                                  /*receiverId=*/true);
12544
0
    } else {
12545
      // Check protocols.
12546
0
      Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12547
0
                                             /*IsInstance=*/true);
12548
0
    }
12549
0
  }
12550
12551
0
  if (!Method)
12552
0
    return false;
12553
12554
0
  QualType T = Method->parameters()[0]->getType();
12555
0
  if (!T->isObjCObjectPointerType())
12556
0
    return false;
12557
12558
0
  QualType R = Method->getReturnType();
12559
0
  if (!R->isScalarType())
12560
0
    return false;
12561
12562
0
  return true;
12563
0
}
12564
12565
0
Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12566
0
  FromE = FromE->IgnoreParenImpCasts();
12567
0
  switch (FromE->getStmtClass()) {
12568
0
    default:
12569
0
      break;
12570
0
    case Stmt::ObjCStringLiteralClass:
12571
      // "string literal"
12572
0
      return LK_String;
12573
0
    case Stmt::ObjCArrayLiteralClass:
12574
      // "array literal"
12575
0
      return LK_Array;
12576
0
    case Stmt::ObjCDictionaryLiteralClass:
12577
      // "dictionary literal"
12578
0
      return LK_Dictionary;
12579
0
    case Stmt::BlockExprClass:
12580
0
      return LK_Block;
12581
0
    case Stmt::ObjCBoxedExprClass: {
12582
0
      Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12583
0
      switch (Inner->getStmtClass()) {
12584
0
        case Stmt::IntegerLiteralClass:
12585
0
        case Stmt::FloatingLiteralClass:
12586
0
        case Stmt::CharacterLiteralClass:
12587
0
        case Stmt::ObjCBoolLiteralExprClass:
12588
0
        case Stmt::CXXBoolLiteralExprClass:
12589
          // "numeric literal"
12590
0
          return LK_Numeric;
12591
0
        case Stmt::ImplicitCastExprClass: {
12592
0
          CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12593
          // Boolean literals can be represented by implicit casts.
12594
0
          if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12595
0
            return LK_Numeric;
12596
0
          break;
12597
0
        }
12598
0
        default:
12599
0
          break;
12600
0
      }
12601
0
      return LK_Boxed;
12602
0
    }
12603
0
  }
12604
0
  return LK_None;
12605
0
}
12606
12607
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12608
                                          ExprResult &LHS, ExprResult &RHS,
12609
0
                                          BinaryOperator::Opcode Opc){
12610
0
  Expr *Literal;
12611
0
  Expr *Other;
12612
0
  if (isObjCObjectLiteral(LHS)) {
12613
0
    Literal = LHS.get();
12614
0
    Other = RHS.get();
12615
0
  } else {
12616
0
    Literal = RHS.get();
12617
0
    Other = LHS.get();
12618
0
  }
12619
12620
  // Don't warn on comparisons against nil.
12621
0
  Other = Other->IgnoreParenCasts();
12622
0
  if (Other->isNullPointerConstant(S.getASTContext(),
12623
0
                                   Expr::NPC_ValueDependentIsNotNull))
12624
0
    return;
12625
12626
  // This should be kept in sync with warn_objc_literal_comparison.
12627
  // LK_String should always be after the other literals, since it has its own
12628
  // warning flag.
12629
0
  Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12630
0
  assert(LiteralKind != Sema::LK_Block);
12631
0
  if (LiteralKind == Sema::LK_None) {
12632
0
    llvm_unreachable("Unknown Objective-C object literal kind");
12633
0
  }
12634
12635
0
  if (LiteralKind == Sema::LK_String)
12636
0
    S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12637
0
      << Literal->getSourceRange();
12638
0
  else
12639
0
    S.Diag(Loc, diag::warn_objc_literal_comparison)
12640
0
      << LiteralKind << Literal->getSourceRange();
12641
12642
0
  if (BinaryOperator::isEqualityOp(Opc) &&
12643
0
      hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12644
0
    SourceLocation Start = LHS.get()->getBeginLoc();
12645
0
    SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12646
0
    CharSourceRange OpRange =
12647
0
      CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12648
12649
0
    S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12650
0
      << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12651
0
      << FixItHint::CreateReplacement(OpRange, " isEqual:")
12652
0
      << FixItHint::CreateInsertion(End, "]");
12653
0
  }
12654
0
}
12655
12656
/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12657
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12658
                                           ExprResult &RHS, SourceLocation Loc,
12659
0
                                           BinaryOperatorKind Opc) {
12660
  // Check that left hand side is !something.
12661
0
  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12662
0
  if (!UO || UO->getOpcode() != UO_LNot) return;
12663
12664
  // Only check if the right hand side is non-bool arithmetic type.
12665
0
  if (RHS.get()->isKnownToHaveBooleanValue()) return;
12666
12667
  // Make sure that the something in !something is not bool.
12668
0
  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12669
0
  if (SubExpr->isKnownToHaveBooleanValue()) return;
12670
12671
  // Emit warning.
12672
0
  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12673
0
  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12674
0
      << Loc << IsBitwiseOp;
12675
12676
  // First note suggest !(x < y)
12677
0
  SourceLocation FirstOpen = SubExpr->getBeginLoc();
12678
0
  SourceLocation FirstClose = RHS.get()->getEndLoc();
12679
0
  FirstClose = S.getLocForEndOfToken(FirstClose);
12680
0
  if (FirstClose.isInvalid())
12681
0
    FirstOpen = SourceLocation();
12682
0
  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12683
0
      << IsBitwiseOp
12684
0
      << FixItHint::CreateInsertion(FirstOpen, "(")
12685
0
      << FixItHint::CreateInsertion(FirstClose, ")");
12686
12687
  // Second note suggests (!x) < y
12688
0
  SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12689
0
  SourceLocation SecondClose = LHS.get()->getEndLoc();
12690
0
  SecondClose = S.getLocForEndOfToken(SecondClose);
12691
0
  if (SecondClose.isInvalid())
12692
0
    SecondOpen = SourceLocation();
12693
0
  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12694
0
      << FixItHint::CreateInsertion(SecondOpen, "(")
12695
0
      << FixItHint::CreateInsertion(SecondClose, ")");
12696
0
}
12697
12698
// Returns true if E refers to a non-weak array.
12699
0
static bool checkForArray(const Expr *E) {
12700
0
  const ValueDecl *D = nullptr;
12701
0
  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12702
0
    D = DR->getDecl();
12703
0
  } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12704
0
    if (Mem->isImplicitAccess())
12705
0
      D = Mem->getMemberDecl();
12706
0
  }
12707
0
  if (!D)
12708
0
    return false;
12709
0
  return D->getType()->isArrayType() && !D->isWeak();
12710
0
}
12711
12712
/// Diagnose some forms of syntactically-obvious tautological comparison.
12713
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12714
                                           Expr *LHS, Expr *RHS,
12715
0
                                           BinaryOperatorKind Opc) {
12716
0
  Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12717
0
  Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12718
12719
0
  QualType LHSType = LHS->getType();
12720
0
  QualType RHSType = RHS->getType();
12721
0
  if (LHSType->hasFloatingRepresentation() ||
12722
0
      (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12723
0
      S.inTemplateInstantiation())
12724
0
    return;
12725
12726
  // WebAssembly Tables cannot be compared, therefore shouldn't emit
12727
  // Tautological diagnostics.
12728
0
  if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12729
0
    return;
12730
12731
  // Comparisons between two array types are ill-formed for operator<=>, so
12732
  // we shouldn't emit any additional warnings about it.
12733
0
  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12734
0
    return;
12735
12736
  // For non-floating point types, check for self-comparisons of the form
12737
  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12738
  // often indicate logic errors in the program.
12739
  //
12740
  // NOTE: Don't warn about comparison expressions resulting from macro
12741
  // expansion. Also don't warn about comparisons which are only self
12742
  // comparisons within a template instantiation. The warnings should catch
12743
  // obvious cases in the definition of the template anyways. The idea is to
12744
  // warn when the typed comparison operator will always evaluate to the same
12745
  // result.
12746
12747
  // Used for indexing into %select in warn_comparison_always
12748
0
  enum {
12749
0
    AlwaysConstant,
12750
0
    AlwaysTrue,
12751
0
    AlwaysFalse,
12752
0
    AlwaysEqual, // std::strong_ordering::equal from operator<=>
12753
0
  };
12754
12755
  // C++2a [depr.array.comp]:
12756
  //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12757
  //   operands of array type are deprecated.
12758
0
  if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12759
0
      RHSStripped->getType()->isArrayType()) {
12760
0
    S.Diag(Loc, diag::warn_depr_array_comparison)
12761
0
        << LHS->getSourceRange() << RHS->getSourceRange()
12762
0
        << LHSStripped->getType() << RHSStripped->getType();
12763
    // Carry on to produce the tautological comparison warning, if this
12764
    // expression is potentially-evaluated, we can resolve the array to a
12765
    // non-weak declaration, and so on.
12766
0
  }
12767
12768
0
  if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12769
0
    if (Expr::isSameComparisonOperand(LHS, RHS)) {
12770
0
      unsigned Result;
12771
0
      switch (Opc) {
12772
0
      case BO_EQ:
12773
0
      case BO_LE:
12774
0
      case BO_GE:
12775
0
        Result = AlwaysTrue;
12776
0
        break;
12777
0
      case BO_NE:
12778
0
      case BO_LT:
12779
0
      case BO_GT:
12780
0
        Result = AlwaysFalse;
12781
0
        break;
12782
0
      case BO_Cmp:
12783
0
        Result = AlwaysEqual;
12784
0
        break;
12785
0
      default:
12786
0
        Result = AlwaysConstant;
12787
0
        break;
12788
0
      }
12789
0
      S.DiagRuntimeBehavior(Loc, nullptr,
12790
0
                            S.PDiag(diag::warn_comparison_always)
12791
0
                                << 0 /*self-comparison*/
12792
0
                                << Result);
12793
0
    } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12794
      // What is it always going to evaluate to?
12795
0
      unsigned Result;
12796
0
      switch (Opc) {
12797
0
      case BO_EQ: // e.g. array1 == array2
12798
0
        Result = AlwaysFalse;
12799
0
        break;
12800
0
      case BO_NE: // e.g. array1 != array2
12801
0
        Result = AlwaysTrue;
12802
0
        break;
12803
0
      default: // e.g. array1 <= array2
12804
        // The best we can say is 'a constant'
12805
0
        Result = AlwaysConstant;
12806
0
        break;
12807
0
      }
12808
0
      S.DiagRuntimeBehavior(Loc, nullptr,
12809
0
                            S.PDiag(diag::warn_comparison_always)
12810
0
                                << 1 /*array comparison*/
12811
0
                                << Result);
12812
0
    }
12813
0
  }
12814
12815
0
  if (isa<CastExpr>(LHSStripped))
12816
0
    LHSStripped = LHSStripped->IgnoreParenCasts();
12817
0
  if (isa<CastExpr>(RHSStripped))
12818
0
    RHSStripped = RHSStripped->IgnoreParenCasts();
12819
12820
  // Warn about comparisons against a string constant (unless the other
12821
  // operand is null); the user probably wants string comparison function.
12822
0
  Expr *LiteralString = nullptr;
12823
0
  Expr *LiteralStringStripped = nullptr;
12824
0
  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12825
0
      !RHSStripped->isNullPointerConstant(S.Context,
12826
0
                                          Expr::NPC_ValueDependentIsNull)) {
12827
0
    LiteralString = LHS;
12828
0
    LiteralStringStripped = LHSStripped;
12829
0
  } else if ((isa<StringLiteral>(RHSStripped) ||
12830
0
              isa<ObjCEncodeExpr>(RHSStripped)) &&
12831
0
             !LHSStripped->isNullPointerConstant(S.Context,
12832
0
                                          Expr::NPC_ValueDependentIsNull)) {
12833
0
    LiteralString = RHS;
12834
0
    LiteralStringStripped = RHSStripped;
12835
0
  }
12836
12837
0
  if (LiteralString) {
12838
0
    S.DiagRuntimeBehavior(Loc, nullptr,
12839
0
                          S.PDiag(diag::warn_stringcompare)
12840
0
                              << isa<ObjCEncodeExpr>(LiteralStringStripped)
12841
0
                              << LiteralString->getSourceRange());
12842
0
  }
12843
0
}
12844
12845
0
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12846
0
  switch (CK) {
12847
0
  default: {
12848
0
#ifndef NDEBUG
12849
0
    llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12850
0
                 << "\n";
12851
0
#endif
12852
0
    llvm_unreachable("unhandled cast kind");
12853
0
  }
12854
0
  case CK_UserDefinedConversion:
12855
0
    return ICK_Identity;
12856
0
  case CK_LValueToRValue:
12857
0
    return ICK_Lvalue_To_Rvalue;
12858
0
  case CK_ArrayToPointerDecay:
12859
0
    return ICK_Array_To_Pointer;
12860
0
  case CK_FunctionToPointerDecay:
12861
0
    return ICK_Function_To_Pointer;
12862
0
  case CK_IntegralCast:
12863
0
    return ICK_Integral_Conversion;
12864
0
  case CK_FloatingCast:
12865
0
    return ICK_Floating_Conversion;
12866
0
  case CK_IntegralToFloating:
12867
0
  case CK_FloatingToIntegral:
12868
0
    return ICK_Floating_Integral;
12869
0
  case CK_IntegralComplexCast:
12870
0
  case CK_FloatingComplexCast:
12871
0
  case CK_FloatingComplexToIntegralComplex:
12872
0
  case CK_IntegralComplexToFloatingComplex:
12873
0
    return ICK_Complex_Conversion;
12874
0
  case CK_FloatingComplexToReal:
12875
0
  case CK_FloatingRealToComplex:
12876
0
  case CK_IntegralComplexToReal:
12877
0
  case CK_IntegralRealToComplex:
12878
0
    return ICK_Complex_Real;
12879
0
  }
12880
0
}
12881
12882
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12883
                                             QualType FromType,
12884
0
                                             SourceLocation Loc) {
12885
  // Check for a narrowing implicit conversion.
12886
0
  StandardConversionSequence SCS;
12887
0
  SCS.setAsIdentityConversion();
12888
0
  SCS.setToType(0, FromType);
12889
0
  SCS.setToType(1, ToType);
12890
0
  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12891
0
    SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12892
12893
0
  APValue PreNarrowingValue;
12894
0
  QualType PreNarrowingType;
12895
0
  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12896
0
                               PreNarrowingType,
12897
0
                               /*IgnoreFloatToIntegralConversion*/ true)) {
12898
0
  case NK_Dependent_Narrowing:
12899
    // Implicit conversion to a narrower type, but the expression is
12900
    // value-dependent so we can't tell whether it's actually narrowing.
12901
0
  case NK_Not_Narrowing:
12902
0
    return false;
12903
12904
0
  case NK_Constant_Narrowing:
12905
    // Implicit conversion to a narrower type, and the value is not a constant
12906
    // expression.
12907
0
    S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12908
0
        << /*Constant*/ 1
12909
0
        << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12910
0
    return true;
12911
12912
0
  case NK_Variable_Narrowing:
12913
    // Implicit conversion to a narrower type, and the value is not a constant
12914
    // expression.
12915
0
  case NK_Type_Narrowing:
12916
0
    S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12917
0
        << /*Constant*/ 0 << FromType << ToType;
12918
    // TODO: It's not a constant expression, but what if the user intended it
12919
    // to be? Can we produce notes to help them figure out why it isn't?
12920
0
    return true;
12921
0
  }
12922
0
  llvm_unreachable("unhandled case in switch");
12923
0
}
12924
12925
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12926
                                                         ExprResult &LHS,
12927
                                                         ExprResult &RHS,
12928
0
                                                         SourceLocation Loc) {
12929
0
  QualType LHSType = LHS.get()->getType();
12930
0
  QualType RHSType = RHS.get()->getType();
12931
  // Dig out the original argument type and expression before implicit casts
12932
  // were applied. These are the types/expressions we need to check the
12933
  // [expr.spaceship] requirements against.
12934
0
  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12935
0
  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12936
0
  QualType LHSStrippedType = LHSStripped.get()->getType();
12937
0
  QualType RHSStrippedType = RHSStripped.get()->getType();
12938
12939
  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12940
  // other is not, the program is ill-formed.
12941
0
  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12942
0
    S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12943
0
    return QualType();
12944
0
  }
12945
12946
  // FIXME: Consider combining this with checkEnumArithmeticConversions.
12947
0
  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12948
0
                    RHSStrippedType->isEnumeralType();
12949
0
  if (NumEnumArgs == 1) {
12950
0
    bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12951
0
    QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12952
0
    if (OtherTy->hasFloatingRepresentation()) {
12953
0
      S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12954
0
      return QualType();
12955
0
    }
12956
0
  }
12957
0
  if (NumEnumArgs == 2) {
12958
    // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12959
    // type E, the operator yields the result of converting the operands
12960
    // to the underlying type of E and applying <=> to the converted operands.
12961
0
    if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12962
0
      S.InvalidOperands(Loc, LHS, RHS);
12963
0
      return QualType();
12964
0
    }
12965
0
    QualType IntType =
12966
0
        LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12967
0
    assert(IntType->isArithmeticType());
12968
12969
    // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12970
    // promote the boolean type, and all other promotable integer types, to
12971
    // avoid this.
12972
0
    if (S.Context.isPromotableIntegerType(IntType))
12973
0
      IntType = S.Context.getPromotedIntegerType(IntType);
12974
12975
0
    LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12976
0
    RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12977
0
    LHSType = RHSType = IntType;
12978
0
  }
12979
12980
  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12981
  // usual arithmetic conversions are applied to the operands.
12982
0
  QualType Type =
12983
0
      S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12984
0
  if (LHS.isInvalid() || RHS.isInvalid())
12985
0
    return QualType();
12986
0
  if (Type.isNull())
12987
0
    return S.InvalidOperands(Loc, LHS, RHS);
12988
12989
0
  std::optional<ComparisonCategoryType> CCT =
12990
0
      getComparisonCategoryForBuiltinCmp(Type);
12991
0
  if (!CCT)
12992
0
    return S.InvalidOperands(Loc, LHS, RHS);
12993
12994
0
  bool HasNarrowing = checkThreeWayNarrowingConversion(
12995
0
      S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12996
0
  HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12997
0
                                                   RHS.get()->getBeginLoc());
12998
0
  if (HasNarrowing)
12999
0
    return QualType();
13000
13001
0
  assert(!Type.isNull() && "composite type for <=> has not been set");
13002
13003
0
  return S.CheckComparisonCategoryType(
13004
0
      *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
13005
0
}
13006
13007
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13008
                                                 ExprResult &RHS,
13009
                                                 SourceLocation Loc,
13010
0
                                                 BinaryOperatorKind Opc) {
13011
0
  if (Opc == BO_Cmp)
13012
0
    return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13013
13014
  // C99 6.5.8p3 / C99 6.5.9p4
13015
0
  QualType Type =
13016
0
      S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
13017
0
  if (LHS.isInvalid() || RHS.isInvalid())
13018
0
    return QualType();
13019
0
  if (Type.isNull())
13020
0
    return S.InvalidOperands(Loc, LHS, RHS);
13021
0
  assert(Type->isArithmeticType() || Type->isEnumeralType());
13022
13023
0
  if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13024
0
    return S.InvalidOperands(Loc, LHS, RHS);
13025
13026
  // Check for comparisons of floating point operands using != and ==.
13027
0
  if (Type->hasFloatingRepresentation())
13028
0
    S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13029
13030
  // The result of comparisons is 'bool' in C++, 'int' in C.
13031
0
  return S.Context.getLogicalOperationType();
13032
0
}
13033
13034
0
void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13035
0
  if (!NullE.get()->getType()->isAnyPointerType())
13036
0
    return;
13037
0
  int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
13038
0
  if (!E.get()->getType()->isAnyPointerType() &&
13039
0
      E.get()->isNullPointerConstant(Context,
13040
0
                                     Expr::NPC_ValueDependentIsNotNull) ==
13041
0
        Expr::NPCK_ZeroExpression) {
13042
0
    if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
13043
0
      if (CL->getValue() == 0)
13044
0
        Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13045
0
            << NullValue
13046
0
            << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13047
0
                                            NullValue ? "NULL" : "(void *)0");
13048
0
    } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
13049
0
        TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13050
0
        QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
13051
0
        if (T == Context.CharTy)
13052
0
          Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13053
0
              << NullValue
13054
0
              << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13055
0
                                              NullValue ? "NULL" : "(void *)0");
13056
0
      }
13057
0
  }
13058
0
}
13059
13060
// C99 6.5.8, C++ [expr.rel]
13061
QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13062
                                    SourceLocation Loc,
13063
0
                                    BinaryOperatorKind Opc) {
13064
0
  bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13065
0
  bool IsThreeWay = Opc == BO_Cmp;
13066
0
  bool IsOrdered = IsRelational || IsThreeWay;
13067
0
  auto IsAnyPointerType = [](ExprResult E) {
13068
0
    QualType Ty = E.get()->getType();
13069
0
    return Ty->isPointerType() || Ty->isMemberPointerType();
13070
0
  };
13071
13072
  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13073
  // type, array-to-pointer, ..., conversions are performed on both operands to
13074
  // bring them to their composite type.
13075
  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13076
  // any type-related checks.
13077
0
  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13078
0
    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13079
0
    if (LHS.isInvalid())
13080
0
      return QualType();
13081
0
    RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13082
0
    if (RHS.isInvalid())
13083
0
      return QualType();
13084
0
  } else {
13085
0
    LHS = DefaultLvalueConversion(LHS.get());
13086
0
    if (LHS.isInvalid())
13087
0
      return QualType();
13088
0
    RHS = DefaultLvalueConversion(RHS.get());
13089
0
    if (RHS.isInvalid())
13090
0
      return QualType();
13091
0
  }
13092
13093
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
13094
0
  if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13095
0
    CheckPtrComparisonWithNullChar(LHS, RHS);
13096
0
    CheckPtrComparisonWithNullChar(RHS, LHS);
13097
0
  }
13098
13099
  // Handle vector comparisons separately.
13100
0
  if (LHS.get()->getType()->isVectorType() ||
13101
0
      RHS.get()->getType()->isVectorType())
13102
0
    return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13103
13104
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13105
0
      RHS.get()->getType()->isSveVLSBuiltinType())
13106
0
    return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13107
13108
0
  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13109
0
  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13110
13111
0
  QualType LHSType = LHS.get()->getType();
13112
0
  QualType RHSType = RHS.get()->getType();
13113
0
  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13114
0
      (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13115
0
    return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13116
13117
0
  if ((LHSType->isPointerType() &&
13118
0
       LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13119
0
      (RHSType->isPointerType() &&
13120
0
       RHSType->getPointeeType().isWebAssemblyReferenceType()))
13121
0
    return InvalidOperands(Loc, LHS, RHS);
13122
13123
0
  const Expr::NullPointerConstantKind LHSNullKind =
13124
0
      LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
13125
0
  const Expr::NullPointerConstantKind RHSNullKind =
13126
0
      RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
13127
0
  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13128
0
  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13129
13130
0
  auto computeResultTy = [&]() {
13131
0
    if (Opc != BO_Cmp)
13132
0
      return Context.getLogicalOperationType();
13133
0
    assert(getLangOpts().CPlusPlus);
13134
0
    assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13135
13136
0
    QualType CompositeTy = LHS.get()->getType();
13137
0
    assert(!CompositeTy->isReferenceType());
13138
13139
0
    std::optional<ComparisonCategoryType> CCT =
13140
0
        getComparisonCategoryForBuiltinCmp(CompositeTy);
13141
0
    if (!CCT)
13142
0
      return InvalidOperands(Loc, LHS, RHS);
13143
13144
0
    if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13145
      // P0946R0: Comparisons between a null pointer constant and an object
13146
      // pointer result in std::strong_equality, which is ill-formed under
13147
      // P1959R0.
13148
0
      Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13149
0
          << (LHSIsNull ? LHS.get()->getSourceRange()
13150
0
                        : RHS.get()->getSourceRange());
13151
0
      return QualType();
13152
0
    }
13153
13154
0
    return CheckComparisonCategoryType(
13155
0
        *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
13156
0
  };
13157
13158
0
  if (!IsOrdered && LHSIsNull != RHSIsNull) {
13159
0
    bool IsEquality = Opc == BO_EQ;
13160
0
    if (RHSIsNull)
13161
0
      DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13162
0
                                   RHS.get()->getSourceRange());
13163
0
    else
13164
0
      DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13165
0
                                   LHS.get()->getSourceRange());
13166
0
  }
13167
13168
0
  if (IsOrdered && LHSType->isFunctionPointerType() &&
13169
0
      RHSType->isFunctionPointerType()) {
13170
    // Valid unless a relational comparison of function pointers
13171
0
    bool IsError = Opc == BO_Cmp;
13172
0
    auto DiagID =
13173
0
        IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13174
0
        : getLangOpts().CPlusPlus
13175
0
            ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13176
0
            : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13177
0
    Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13178
0
                      << RHS.get()->getSourceRange();
13179
0
    if (IsError)
13180
0
      return QualType();
13181
0
  }
13182
13183
0
  if ((LHSType->isIntegerType() && !LHSIsNull) ||
13184
0
      (RHSType->isIntegerType() && !RHSIsNull)) {
13185
    // Skip normal pointer conversion checks in this case; we have better
13186
    // diagnostics for this below.
13187
0
  } else if (getLangOpts().CPlusPlus) {
13188
    // Equality comparison of a function pointer to a void pointer is invalid,
13189
    // but we allow it as an extension.
13190
    // FIXME: If we really want to allow this, should it be part of composite
13191
    // pointer type computation so it works in conditionals too?
13192
0
    if (!IsOrdered &&
13193
0
        ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13194
0
         (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13195
      // This is a gcc extension compatibility comparison.
13196
      // In a SFINAE context, we treat this as a hard error to maintain
13197
      // conformance with the C++ standard.
13198
0
      diagnoseFunctionPointerToVoidComparison(
13199
0
          *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
13200
13201
0
      if (isSFINAEContext())
13202
0
        return QualType();
13203
13204
0
      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13205
0
      return computeResultTy();
13206
0
    }
13207
13208
    // C++ [expr.eq]p2:
13209
    //   If at least one operand is a pointer [...] bring them to their
13210
    //   composite pointer type.
13211
    // C++ [expr.spaceship]p6
13212
    //  If at least one of the operands is of pointer type, [...] bring them
13213
    //  to their composite pointer type.
13214
    // C++ [expr.rel]p2:
13215
    //   If both operands are pointers, [...] bring them to their composite
13216
    //   pointer type.
13217
    // For <=>, the only valid non-pointer types are arrays and functions, and
13218
    // we already decayed those, so this is really the same as the relational
13219
    // comparison rule.
13220
0
    if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13221
0
            (IsOrdered ? 2 : 1) &&
13222
0
        (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13223
0
                                         RHSType->isObjCObjectPointerType()))) {
13224
0
      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13225
0
        return QualType();
13226
0
      return computeResultTy();
13227
0
    }
13228
0
  } else if (LHSType->isPointerType() &&
13229
0
             RHSType->isPointerType()) { // C99 6.5.8p2
13230
    // All of the following pointer-related warnings are GCC extensions, except
13231
    // when handling null pointer constants.
13232
0
    QualType LCanPointeeTy =
13233
0
      LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13234
0
    QualType RCanPointeeTy =
13235
0
      RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13236
13237
    // C99 6.5.9p2 and C99 6.5.8p2
13238
0
    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13239
0
                                   RCanPointeeTy.getUnqualifiedType())) {
13240
0
      if (IsRelational) {
13241
        // Pointers both need to point to complete or incomplete types
13242
0
        if ((LCanPointeeTy->isIncompleteType() !=
13243
0
             RCanPointeeTy->isIncompleteType()) &&
13244
0
            !getLangOpts().C11) {
13245
0
          Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13246
0
              << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13247
0
              << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13248
0
              << RCanPointeeTy->isIncompleteType();
13249
0
        }
13250
0
      }
13251
0
    } else if (!IsRelational &&
13252
0
               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13253
      // Valid unless comparison between non-null pointer and function pointer
13254
0
      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13255
0
          && !LHSIsNull && !RHSIsNull)
13256
0
        diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13257
0
                                                /*isError*/false);
13258
0
    } else {
13259
      // Invalid
13260
0
      diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13261
0
    }
13262
0
    if (LCanPointeeTy != RCanPointeeTy) {
13263
      // Treat NULL constant as a special case in OpenCL.
13264
0
      if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13265
0
        if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
13266
0
          Diag(Loc,
13267
0
               diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13268
0
              << LHSType << RHSType << 0 /* comparison */
13269
0
              << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13270
0
        }
13271
0
      }
13272
0
      LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13273
0
      LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13274
0
      CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13275
0
                                               : CK_BitCast;
13276
0
      if (LHSIsNull && !RHSIsNull)
13277
0
        LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13278
0
      else
13279
0
        RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13280
0
    }
13281
0
    return computeResultTy();
13282
0
  }
13283
13284
13285
  // C++ [expr.eq]p4:
13286
  //   Two operands of type std::nullptr_t or one operand of type
13287
  //   std::nullptr_t and the other a null pointer constant compare
13288
  //   equal.
13289
  // C23 6.5.9p5:
13290
  //   If both operands have type nullptr_t or one operand has type nullptr_t
13291
  //   and the other is a null pointer constant, they compare equal if the
13292
  //   former is a null pointer.
13293
0
  if (!IsOrdered && LHSIsNull && RHSIsNull) {
13294
0
    if (LHSType->isNullPtrType()) {
13295
0
      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13296
0
      return computeResultTy();
13297
0
    }
13298
0
    if (RHSType->isNullPtrType()) {
13299
0
      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13300
0
      return computeResultTy();
13301
0
    }
13302
0
  }
13303
13304
0
  if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13305
    // C23 6.5.9p6:
13306
    //   Otherwise, at least one operand is a pointer. If one is a pointer and
13307
    //   the other is a null pointer constant or has type nullptr_t, they
13308
    //   compare equal
13309
0
    if (LHSIsNull && RHSType->isPointerType()) {
13310
0
      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13311
0
      return computeResultTy();
13312
0
    }
13313
0
    if (RHSIsNull && LHSType->isPointerType()) {
13314
0
      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13315
0
      return computeResultTy();
13316
0
    }
13317
0
  }
13318
13319
  // Comparison of Objective-C pointers and block pointers against nullptr_t.
13320
  // These aren't covered by the composite pointer type rules.
13321
0
  if (!IsOrdered && RHSType->isNullPtrType() &&
13322
0
      (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13323
0
    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13324
0
    return computeResultTy();
13325
0
  }
13326
0
  if (!IsOrdered && LHSType->isNullPtrType() &&
13327
0
      (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13328
0
    LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13329
0
    return computeResultTy();
13330
0
  }
13331
13332
0
  if (getLangOpts().CPlusPlus) {
13333
0
    if (IsRelational &&
13334
0
        ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13335
0
         (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13336
      // HACK: Relational comparison of nullptr_t against a pointer type is
13337
      // invalid per DR583, but we allow it within std::less<> and friends,
13338
      // since otherwise common uses of it break.
13339
      // FIXME: Consider removing this hack once LWG fixes std::less<> and
13340
      // friends to have std::nullptr_t overload candidates.
13341
0
      DeclContext *DC = CurContext;
13342
0
      if (isa<FunctionDecl>(DC))
13343
0
        DC = DC->getParent();
13344
0
      if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13345
0
        if (CTSD->isInStdNamespace() &&
13346
0
            llvm::StringSwitch<bool>(CTSD->getName())
13347
0
                .Cases("less", "less_equal", "greater", "greater_equal", true)
13348
0
                .Default(false)) {
13349
0
          if (RHSType->isNullPtrType())
13350
0
            RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13351
0
          else
13352
0
            LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13353
0
          return computeResultTy();
13354
0
        }
13355
0
      }
13356
0
    }
13357
13358
    // C++ [expr.eq]p2:
13359
    //   If at least one operand is a pointer to member, [...] bring them to
13360
    //   their composite pointer type.
13361
0
    if (!IsOrdered &&
13362
0
        (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13363
0
      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13364
0
        return QualType();
13365
0
      else
13366
0
        return computeResultTy();
13367
0
    }
13368
0
  }
13369
13370
  // Handle block pointer types.
13371
0
  if (!IsOrdered && LHSType->isBlockPointerType() &&
13372
0
      RHSType->isBlockPointerType()) {
13373
0
    QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13374
0
    QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13375
13376
0
    if (!LHSIsNull && !RHSIsNull &&
13377
0
        !Context.typesAreCompatible(lpointee, rpointee)) {
13378
0
      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13379
0
        << LHSType << RHSType << LHS.get()->getSourceRange()
13380
0
        << RHS.get()->getSourceRange();
13381
0
    }
13382
0
    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13383
0
    return computeResultTy();
13384
0
  }
13385
13386
  // Allow block pointers to be compared with null pointer constants.
13387
0
  if (!IsOrdered
13388
0
      && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13389
0
          || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13390
0
    if (!LHSIsNull && !RHSIsNull) {
13391
0
      if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13392
0
             ->getPointeeType()->isVoidType())
13393
0
            || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13394
0
                ->getPointeeType()->isVoidType())))
13395
0
        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13396
0
          << LHSType << RHSType << LHS.get()->getSourceRange()
13397
0
          << RHS.get()->getSourceRange();
13398
0
    }
13399
0
    if (LHSIsNull && !RHSIsNull)
13400
0
      LHS = ImpCastExprToType(LHS.get(), RHSType,
13401
0
                              RHSType->isPointerType() ? CK_BitCast
13402
0
                                : CK_AnyPointerToBlockPointerCast);
13403
0
    else
13404
0
      RHS = ImpCastExprToType(RHS.get(), LHSType,
13405
0
                              LHSType->isPointerType() ? CK_BitCast
13406
0
                                : CK_AnyPointerToBlockPointerCast);
13407
0
    return computeResultTy();
13408
0
  }
13409
13410
0
  if (LHSType->isObjCObjectPointerType() ||
13411
0
      RHSType->isObjCObjectPointerType()) {
13412
0
    const PointerType *LPT = LHSType->getAs<PointerType>();
13413
0
    const PointerType *RPT = RHSType->getAs<PointerType>();
13414
0
    if (LPT || RPT) {
13415
0
      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13416
0
      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13417
13418
0
      if (!LPtrToVoid && !RPtrToVoid &&
13419
0
          !Context.typesAreCompatible(LHSType, RHSType)) {
13420
0
        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13421
0
                                          /*isError*/false);
13422
0
      }
13423
      // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13424
      // the RHS, but we have test coverage for this behavior.
13425
      // FIXME: Consider using convertPointersToCompositeType in C++.
13426
0
      if (LHSIsNull && !RHSIsNull) {
13427
0
        Expr *E = LHS.get();
13428
0
        if (getLangOpts().ObjCAutoRefCount)
13429
0
          CheckObjCConversion(SourceRange(), RHSType, E,
13430
0
                              CCK_ImplicitConversion);
13431
0
        LHS = ImpCastExprToType(E, RHSType,
13432
0
                                RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13433
0
      }
13434
0
      else {
13435
0
        Expr *E = RHS.get();
13436
0
        if (getLangOpts().ObjCAutoRefCount)
13437
0
          CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13438
0
                              /*Diagnose=*/true,
13439
0
                              /*DiagnoseCFAudited=*/false, Opc);
13440
0
        RHS = ImpCastExprToType(E, LHSType,
13441
0
                                LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13442
0
      }
13443
0
      return computeResultTy();
13444
0
    }
13445
0
    if (LHSType->isObjCObjectPointerType() &&
13446
0
        RHSType->isObjCObjectPointerType()) {
13447
0
      if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13448
0
        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13449
0
                                          /*isError*/false);
13450
0
      if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13451
0
        diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13452
13453
0
      if (LHSIsNull && !RHSIsNull)
13454
0
        LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13455
0
      else
13456
0
        RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13457
0
      return computeResultTy();
13458
0
    }
13459
13460
0
    if (!IsOrdered && LHSType->isBlockPointerType() &&
13461
0
        RHSType->isBlockCompatibleObjCPointerType(Context)) {
13462
0
      LHS = ImpCastExprToType(LHS.get(), RHSType,
13463
0
                              CK_BlockPointerToObjCPointerCast);
13464
0
      return computeResultTy();
13465
0
    } else if (!IsOrdered &&
13466
0
               LHSType->isBlockCompatibleObjCPointerType(Context) &&
13467
0
               RHSType->isBlockPointerType()) {
13468
0
      RHS = ImpCastExprToType(RHS.get(), LHSType,
13469
0
                              CK_BlockPointerToObjCPointerCast);
13470
0
      return computeResultTy();
13471
0
    }
13472
0
  }
13473
0
  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13474
0
      (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13475
0
    unsigned DiagID = 0;
13476
0
    bool isError = false;
13477
0
    if (LangOpts.DebuggerSupport) {
13478
      // Under a debugger, allow the comparison of pointers to integers,
13479
      // since users tend to want to compare addresses.
13480
0
    } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13481
0
               (RHSIsNull && RHSType->isIntegerType())) {
13482
0
      if (IsOrdered) {
13483
0
        isError = getLangOpts().CPlusPlus;
13484
0
        DiagID =
13485
0
          isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13486
0
                  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13487
0
      }
13488
0
    } else if (getLangOpts().CPlusPlus) {
13489
0
      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13490
0
      isError = true;
13491
0
    } else if (IsOrdered)
13492
0
      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13493
0
    else
13494
0
      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13495
13496
0
    if (DiagID) {
13497
0
      Diag(Loc, DiagID)
13498
0
        << LHSType << RHSType << LHS.get()->getSourceRange()
13499
0
        << RHS.get()->getSourceRange();
13500
0
      if (isError)
13501
0
        return QualType();
13502
0
    }
13503
13504
0
    if (LHSType->isIntegerType())
13505
0
      LHS = ImpCastExprToType(LHS.get(), RHSType,
13506
0
                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13507
0
    else
13508
0
      RHS = ImpCastExprToType(RHS.get(), LHSType,
13509
0
                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13510
0
    return computeResultTy();
13511
0
  }
13512
13513
  // Handle block pointers.
13514
0
  if (!IsOrdered && RHSIsNull
13515
0
      && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13516
0
    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13517
0
    return computeResultTy();
13518
0
  }
13519
0
  if (!IsOrdered && LHSIsNull
13520
0
      && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13521
0
    LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13522
0
    return computeResultTy();
13523
0
  }
13524
13525
0
  if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13526
0
    if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13527
0
      return computeResultTy();
13528
0
    }
13529
13530
0
    if (LHSType->isQueueT() && RHSType->isQueueT()) {
13531
0
      return computeResultTy();
13532
0
    }
13533
13534
0
    if (LHSIsNull && RHSType->isQueueT()) {
13535
0
      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13536
0
      return computeResultTy();
13537
0
    }
13538
13539
0
    if (LHSType->isQueueT() && RHSIsNull) {
13540
0
      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13541
0
      return computeResultTy();
13542
0
    }
13543
0
  }
13544
13545
0
  return InvalidOperands(Loc, LHS, RHS);
13546
0
}
13547
13548
// Return a signed ext_vector_type that is of identical size and number of
13549
// elements. For floating point vectors, return an integer type of identical
13550
// size and number of elements. In the non ext_vector_type case, search from
13551
// the largest type to the smallest type to avoid cases where long long == long,
13552
// where long gets picked over long long.
13553
0
QualType Sema::GetSignedVectorType(QualType V) {
13554
0
  const VectorType *VTy = V->castAs<VectorType>();
13555
0
  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13556
13557
0
  if (isa<ExtVectorType>(VTy)) {
13558
0
    if (VTy->isExtVectorBoolType())
13559
0
      return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13560
0
    if (TypeSize == Context.getTypeSize(Context.CharTy))
13561
0
      return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13562
0
    if (TypeSize == Context.getTypeSize(Context.ShortTy))
13563
0
      return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13564
0
    if (TypeSize == Context.getTypeSize(Context.IntTy))
13565
0
      return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13566
0
    if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13567
0
      return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13568
0
    if (TypeSize == Context.getTypeSize(Context.LongTy))
13569
0
      return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13570
0
    assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13571
0
           "Unhandled vector element size in vector compare");
13572
0
    return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13573
0
  }
13574
13575
0
  if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13576
0
    return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13577
0
                                 VectorKind::Generic);
13578
0
  if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13579
0
    return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13580
0
                                 VectorKind::Generic);
13581
0
  if (TypeSize == Context.getTypeSize(Context.LongTy))
13582
0
    return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13583
0
                                 VectorKind::Generic);
13584
0
  if (TypeSize == Context.getTypeSize(Context.IntTy))
13585
0
    return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13586
0
                                 VectorKind::Generic);
13587
0
  if (TypeSize == Context.getTypeSize(Context.ShortTy))
13588
0
    return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13589
0
                                 VectorKind::Generic);
13590
0
  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13591
0
         "Unhandled vector element size in vector compare");
13592
0
  return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13593
0
                               VectorKind::Generic);
13594
0
}
13595
13596
0
QualType Sema::GetSignedSizelessVectorType(QualType V) {
13597
0
  const BuiltinType *VTy = V->castAs<BuiltinType>();
13598
0
  assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13599
13600
0
  const QualType ETy = V->getSveEltType(Context);
13601
0
  const auto TypeSize = Context.getTypeSize(ETy);
13602
13603
0
  const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13604
0
  const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13605
0
  return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13606
0
}
13607
13608
/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13609
/// operates on extended vector types.  Instead of producing an IntTy result,
13610
/// like a scalar comparison, a vector comparison produces a vector of integer
13611
/// types.
13612
QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13613
                                          SourceLocation Loc,
13614
0
                                          BinaryOperatorKind Opc) {
13615
0
  if (Opc == BO_Cmp) {
13616
0
    Diag(Loc, diag::err_three_way_vector_comparison);
13617
0
    return QualType();
13618
0
  }
13619
13620
  // Check to make sure we're operating on vectors of the same type and width,
13621
  // Allowing one side to be a scalar of element type.
13622
0
  QualType vType =
13623
0
      CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13624
0
                          /*AllowBothBool*/ true,
13625
0
                          /*AllowBoolConversions*/ getLangOpts().ZVector,
13626
0
                          /*AllowBooleanOperation*/ true,
13627
0
                          /*ReportInvalid*/ true);
13628
0
  if (vType.isNull())
13629
0
    return vType;
13630
13631
0
  QualType LHSType = LHS.get()->getType();
13632
13633
  // Determine the return type of a vector compare. By default clang will return
13634
  // a scalar for all vector compares except vector bool and vector pixel.
13635
  // With the gcc compiler we will always return a vector type and with the xl
13636
  // compiler we will always return a scalar type. This switch allows choosing
13637
  // which behavior is prefered.
13638
0
  if (getLangOpts().AltiVec) {
13639
0
    switch (getLangOpts().getAltivecSrcCompat()) {
13640
0
    case LangOptions::AltivecSrcCompatKind::Mixed:
13641
      // If AltiVec, the comparison results in a numeric type, i.e.
13642
      // bool for C++, int for C
13643
0
      if (vType->castAs<VectorType>()->getVectorKind() ==
13644
0
          VectorKind::AltiVecVector)
13645
0
        return Context.getLogicalOperationType();
13646
0
      else
13647
0
        Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13648
0
      break;
13649
0
    case LangOptions::AltivecSrcCompatKind::GCC:
13650
      // For GCC we always return the vector type.
13651
0
      break;
13652
0
    case LangOptions::AltivecSrcCompatKind::XL:
13653
0
      return Context.getLogicalOperationType();
13654
0
      break;
13655
0
    }
13656
0
  }
13657
13658
  // For non-floating point types, check for self-comparisons of the form
13659
  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
13660
  // often indicate logic errors in the program.
13661
0
  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13662
13663
  // Check for comparisons of floating point operands using != and ==.
13664
0
  if (LHSType->hasFloatingRepresentation()) {
13665
0
    assert(RHS.get()->getType()->hasFloatingRepresentation());
13666
0
    CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13667
0
  }
13668
13669
  // Return a signed type for the vector.
13670
0
  return GetSignedVectorType(vType);
13671
0
}
13672
13673
QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13674
                                                  ExprResult &RHS,
13675
                                                  SourceLocation Loc,
13676
0
                                                  BinaryOperatorKind Opc) {
13677
0
  if (Opc == BO_Cmp) {
13678
0
    Diag(Loc, diag::err_three_way_vector_comparison);
13679
0
    return QualType();
13680
0
  }
13681
13682
  // Check to make sure we're operating on vectors of the same type and width,
13683
  // Allowing one side to be a scalar of element type.
13684
0
  QualType vType = CheckSizelessVectorOperands(
13685
0
      LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13686
13687
0
  if (vType.isNull())
13688
0
    return vType;
13689
13690
0
  QualType LHSType = LHS.get()->getType();
13691
13692
  // For non-floating point types, check for self-comparisons of the form
13693
  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
13694
  // often indicate logic errors in the program.
13695
0
  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13696
13697
  // Check for comparisons of floating point operands using != and ==.
13698
0
  if (LHSType->hasFloatingRepresentation()) {
13699
0
    assert(RHS.get()->getType()->hasFloatingRepresentation());
13700
0
    CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13701
0
  }
13702
13703
0
  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13704
0
  const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13705
13706
0
  if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13707
0
      RHSBuiltinTy->isSVEBool())
13708
0
    return LHSType;
13709
13710
  // Return a signed type for the vector.
13711
0
  return GetSignedSizelessVectorType(vType);
13712
0
}
13713
13714
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13715
                                    const ExprResult &XorRHS,
13716
0
                                    const SourceLocation Loc) {
13717
  // Do not diagnose macros.
13718
0
  if (Loc.isMacroID())
13719
0
    return;
13720
13721
  // Do not diagnose if both LHS and RHS are macros.
13722
0
  if (XorLHS.get()->getExprLoc().isMacroID() &&
13723
0
      XorRHS.get()->getExprLoc().isMacroID())
13724
0
    return;
13725
13726
0
  bool Negative = false;
13727
0
  bool ExplicitPlus = false;
13728
0
  const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13729
0
  const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13730
13731
0
  if (!LHSInt)
13732
0
    return;
13733
0
  if (!RHSInt) {
13734
    // Check negative literals.
13735
0
    if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13736
0
      UnaryOperatorKind Opc = UO->getOpcode();
13737
0
      if (Opc != UO_Minus && Opc != UO_Plus)
13738
0
        return;
13739
0
      RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13740
0
      if (!RHSInt)
13741
0
        return;
13742
0
      Negative = (Opc == UO_Minus);
13743
0
      ExplicitPlus = !Negative;
13744
0
    } else {
13745
0
      return;
13746
0
    }
13747
0
  }
13748
13749
0
  const llvm::APInt &LeftSideValue = LHSInt->getValue();
13750
0
  llvm::APInt RightSideValue = RHSInt->getValue();
13751
0
  if (LeftSideValue != 2 && LeftSideValue != 10)
13752
0
    return;
13753
13754
0
  if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13755
0
    return;
13756
13757
0
  CharSourceRange ExprRange = CharSourceRange::getCharRange(
13758
0
      LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13759
0
  llvm::StringRef ExprStr =
13760
0
      Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13761
13762
0
  CharSourceRange XorRange =
13763
0
      CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13764
0
  llvm::StringRef XorStr =
13765
0
      Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13766
  // Do not diagnose if xor keyword/macro is used.
13767
0
  if (XorStr == "xor")
13768
0
    return;
13769
13770
0
  std::string LHSStr = std::string(Lexer::getSourceText(
13771
0
      CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13772
0
      S.getSourceManager(), S.getLangOpts()));
13773
0
  std::string RHSStr = std::string(Lexer::getSourceText(
13774
0
      CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13775
0
      S.getSourceManager(), S.getLangOpts()));
13776
13777
0
  if (Negative) {
13778
0
    RightSideValue = -RightSideValue;
13779
0
    RHSStr = "-" + RHSStr;
13780
0
  } else if (ExplicitPlus) {
13781
0
    RHSStr = "+" + RHSStr;
13782
0
  }
13783
13784
0
  StringRef LHSStrRef = LHSStr;
13785
0
  StringRef RHSStrRef = RHSStr;
13786
  // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13787
  // literals.
13788
0
  if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13789
0
      RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13790
0
      LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13791
0
      RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13792
0
      (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13793
0
      (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13794
0
      LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13795
0
    return;
13796
13797
0
  bool SuggestXor =
13798
0
      S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13799
0
  const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13800
0
  int64_t RightSideIntValue = RightSideValue.getSExtValue();
13801
0
  if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13802
0
    std::string SuggestedExpr = "1 << " + RHSStr;
13803
0
    bool Overflow = false;
13804
0
    llvm::APInt One = (LeftSideValue - 1);
13805
0
    llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13806
0
    if (Overflow) {
13807
0
      if (RightSideIntValue < 64)
13808
0
        S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13809
0
            << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13810
0
            << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13811
0
      else if (RightSideIntValue == 64)
13812
0
        S.Diag(Loc, diag::warn_xor_used_as_pow)
13813
0
            << ExprStr << toString(XorValue, 10, true);
13814
0
      else
13815
0
        return;
13816
0
    } else {
13817
0
      S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13818
0
          << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13819
0
          << toString(PowValue, 10, true)
13820
0
          << FixItHint::CreateReplacement(
13821
0
                 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13822
0
    }
13823
13824
0
    S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13825
0
        << ("0x2 ^ " + RHSStr) << SuggestXor;
13826
0
  } else if (LeftSideValue == 10) {
13827
0
    std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13828
0
    S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13829
0
        << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13830
0
        << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13831
0
    S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13832
0
        << ("0xA ^ " + RHSStr) << SuggestXor;
13833
0
  }
13834
0
}
13835
13836
QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13837
0
                                          SourceLocation Loc) {
13838
  // Ensure that either both operands are of the same vector type, or
13839
  // one operand is of a vector type and the other is of its element type.
13840
0
  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13841
0
                                       /*AllowBothBool*/ true,
13842
0
                                       /*AllowBoolConversions*/ false,
13843
0
                                       /*AllowBooleanOperation*/ false,
13844
0
                                       /*ReportInvalid*/ false);
13845
0
  if (vType.isNull())
13846
0
    return InvalidOperands(Loc, LHS, RHS);
13847
0
  if (getLangOpts().OpenCL &&
13848
0
      getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13849
0
      vType->hasFloatingRepresentation())
13850
0
    return InvalidOperands(Loc, LHS, RHS);
13851
  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13852
  //        usage of the logical operators && and || with vectors in C. This
13853
  //        check could be notionally dropped.
13854
0
  if (!getLangOpts().CPlusPlus &&
13855
0
      !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13856
0
    return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13857
13858
0
  return GetSignedVectorType(LHS.get()->getType());
13859
0
}
13860
13861
QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13862
                                              SourceLocation Loc,
13863
0
                                              bool IsCompAssign) {
13864
0
  if (!IsCompAssign) {
13865
0
    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13866
0
    if (LHS.isInvalid())
13867
0
      return QualType();
13868
0
  }
13869
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13870
0
  if (RHS.isInvalid())
13871
0
    return QualType();
13872
13873
  // For conversion purposes, we ignore any qualifiers.
13874
  // For example, "const float" and "float" are equivalent.
13875
0
  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13876
0
  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13877
13878
0
  const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13879
0
  const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13880
0
  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13881
13882
0
  if (Context.hasSameType(LHSType, RHSType))
13883
0
    return Context.getCommonSugaredType(LHSType, RHSType);
13884
13885
  // Type conversion may change LHS/RHS. Keep copies to the original results, in
13886
  // case we have to return InvalidOperands.
13887
0
  ExprResult OriginalLHS = LHS;
13888
0
  ExprResult OriginalRHS = RHS;
13889
0
  if (LHSMatType && !RHSMatType) {
13890
0
    RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13891
0
    if (!RHS.isInvalid())
13892
0
      return LHSType;
13893
13894
0
    return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13895
0
  }
13896
13897
0
  if (!LHSMatType && RHSMatType) {
13898
0
    LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13899
0
    if (!LHS.isInvalid())
13900
0
      return RHSType;
13901
0
    return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13902
0
  }
13903
13904
0
  return InvalidOperands(Loc, LHS, RHS);
13905
0
}
13906
13907
QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13908
                                           SourceLocation Loc,
13909
0
                                           bool IsCompAssign) {
13910
0
  if (!IsCompAssign) {
13911
0
    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13912
0
    if (LHS.isInvalid())
13913
0
      return QualType();
13914
0
  }
13915
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13916
0
  if (RHS.isInvalid())
13917
0
    return QualType();
13918
13919
0
  auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13920
0
  auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13921
0
  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13922
13923
0
  if (LHSMatType && RHSMatType) {
13924
0
    if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13925
0
      return InvalidOperands(Loc, LHS, RHS);
13926
13927
0
    if (Context.hasSameType(LHSMatType, RHSMatType))
13928
0
      return Context.getCommonSugaredType(
13929
0
          LHS.get()->getType().getUnqualifiedType(),
13930
0
          RHS.get()->getType().getUnqualifiedType());
13931
13932
0
    QualType LHSELTy = LHSMatType->getElementType(),
13933
0
             RHSELTy = RHSMatType->getElementType();
13934
0
    if (!Context.hasSameType(LHSELTy, RHSELTy))
13935
0
      return InvalidOperands(Loc, LHS, RHS);
13936
13937
0
    return Context.getConstantMatrixType(
13938
0
        Context.getCommonSugaredType(LHSELTy, RHSELTy),
13939
0
        LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13940
0
  }
13941
0
  return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13942
0
}
13943
13944
0
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13945
0
  switch (Opc) {
13946
0
  default:
13947
0
    return false;
13948
0
  case BO_And:
13949
0
  case BO_AndAssign:
13950
0
  case BO_Or:
13951
0
  case BO_OrAssign:
13952
0
  case BO_Xor:
13953
0
  case BO_XorAssign:
13954
0
    return true;
13955
0
  }
13956
0
}
13957
13958
inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13959
                                           SourceLocation Loc,
13960
0
                                           BinaryOperatorKind Opc) {
13961
0
  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13962
13963
0
  bool IsCompAssign =
13964
0
      Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13965
13966
0
  bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13967
13968
0
  if (LHS.get()->getType()->isVectorType() ||
13969
0
      RHS.get()->getType()->isVectorType()) {
13970
0
    if (LHS.get()->getType()->hasIntegerRepresentation() &&
13971
0
        RHS.get()->getType()->hasIntegerRepresentation())
13972
0
      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13973
0
                                 /*AllowBothBool*/ true,
13974
0
                                 /*AllowBoolConversions*/ getLangOpts().ZVector,
13975
0
                                 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13976
0
                                 /*ReportInvalid*/ true);
13977
0
    return InvalidOperands(Loc, LHS, RHS);
13978
0
  }
13979
13980
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13981
0
      RHS.get()->getType()->isSveVLSBuiltinType()) {
13982
0
    if (LHS.get()->getType()->hasIntegerRepresentation() &&
13983
0
        RHS.get()->getType()->hasIntegerRepresentation())
13984
0
      return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13985
0
                                         ACK_BitwiseOp);
13986
0
    return InvalidOperands(Loc, LHS, RHS);
13987
0
  }
13988
13989
0
  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13990
0
      RHS.get()->getType()->isSveVLSBuiltinType()) {
13991
0
    if (LHS.get()->getType()->hasIntegerRepresentation() &&
13992
0
        RHS.get()->getType()->hasIntegerRepresentation())
13993
0
      return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13994
0
                                         ACK_BitwiseOp);
13995
0
    return InvalidOperands(Loc, LHS, RHS);
13996
0
  }
13997
13998
0
  if (Opc == BO_And)
13999
0
    diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
14000
14001
0
  if (LHS.get()->getType()->hasFloatingRepresentation() ||
14002
0
      RHS.get()->getType()->hasFloatingRepresentation())
14003
0
    return InvalidOperands(Loc, LHS, RHS);
14004
14005
0
  ExprResult LHSResult = LHS, RHSResult = RHS;
14006
0
  QualType compType = UsualArithmeticConversions(
14007
0
      LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
14008
0
  if (LHSResult.isInvalid() || RHSResult.isInvalid())
14009
0
    return QualType();
14010
0
  LHS = LHSResult.get();
14011
0
  RHS = RHSResult.get();
14012
14013
0
  if (Opc == BO_Xor)
14014
0
    diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
14015
14016
0
  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14017
0
    return compType;
14018
0
  return InvalidOperands(Loc, LHS, RHS);
14019
0
}
14020
14021
// C99 6.5.[13,14]
14022
inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14023
                                           SourceLocation Loc,
14024
0
                                           BinaryOperatorKind Opc) {
14025
  // Check vector operands differently.
14026
0
  if (LHS.get()->getType()->isVectorType() ||
14027
0
      RHS.get()->getType()->isVectorType())
14028
0
    return CheckVectorLogicalOperands(LHS, RHS, Loc);
14029
14030
0
  bool EnumConstantInBoolContext = false;
14031
0
  for (const ExprResult &HS : {LHS, RHS}) {
14032
0
    if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
14033
0
      const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
14034
0
      if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14035
0
        EnumConstantInBoolContext = true;
14036
0
    }
14037
0
  }
14038
14039
0
  if (EnumConstantInBoolContext)
14040
0
    Diag(Loc, diag::warn_enum_constant_in_bool_context);
14041
14042
  // WebAssembly tables can't be used with logical operators.
14043
0
  QualType LHSTy = LHS.get()->getType();
14044
0
  QualType RHSTy = RHS.get()->getType();
14045
0
  const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
14046
0
  const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
14047
0
  if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14048
0
      (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14049
0
    return InvalidOperands(Loc, LHS, RHS);
14050
0
  }
14051
14052
  // Diagnose cases where the user write a logical and/or but probably meant a
14053
  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
14054
  // is a constant.
14055
0
  if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14056
0
      !LHS.get()->getType()->isBooleanType() &&
14057
0
      RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14058
      // Don't warn in macros or template instantiations.
14059
0
      !Loc.isMacroID() && !inTemplateInstantiation()) {
14060
    // If the RHS can be constant folded, and if it constant folds to something
14061
    // that isn't 0 or 1 (which indicate a potential logical operation that
14062
    // happened to fold to true/false) then warn.
14063
    // Parens on the RHS are ignored.
14064
0
    Expr::EvalResult EVResult;
14065
0
    if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
14066
0
      llvm::APSInt Result = EVResult.Val.getInt();
14067
0
      if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
14068
0
           !RHS.get()->getExprLoc().isMacroID()) ||
14069
0
          (Result != 0 && Result != 1)) {
14070
0
        Diag(Loc, diag::warn_logical_instead_of_bitwise)
14071
0
            << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14072
        // Suggest replacing the logical operator with the bitwise version
14073
0
        Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14074
0
            << (Opc == BO_LAnd ? "&" : "|")
14075
0
            << FixItHint::CreateReplacement(
14076
0
                   SourceRange(Loc, getLocForEndOfToken(Loc)),
14077
0
                   Opc == BO_LAnd ? "&" : "|");
14078
0
        if (Opc == BO_LAnd)
14079
          // Suggest replacing "Foo() && kNonZero" with "Foo()"
14080
0
          Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14081
0
              << FixItHint::CreateRemoval(
14082
0
                     SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
14083
0
                                 RHS.get()->getEndLoc()));
14084
0
      }
14085
0
    }
14086
0
  }
14087
14088
0
  if (!Context.getLangOpts().CPlusPlus) {
14089
    // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14090
    // not operate on the built-in scalar and vector float types.
14091
0
    if (Context.getLangOpts().OpenCL &&
14092
0
        Context.getLangOpts().OpenCLVersion < 120) {
14093
0
      if (LHS.get()->getType()->isFloatingType() ||
14094
0
          RHS.get()->getType()->isFloatingType())
14095
0
        return InvalidOperands(Loc, LHS, RHS);
14096
0
    }
14097
14098
0
    LHS = UsualUnaryConversions(LHS.get());
14099
0
    if (LHS.isInvalid())
14100
0
      return QualType();
14101
14102
0
    RHS = UsualUnaryConversions(RHS.get());
14103
0
    if (RHS.isInvalid())
14104
0
      return QualType();
14105
14106
0
    if (!LHS.get()->getType()->isScalarType() ||
14107
0
        !RHS.get()->getType()->isScalarType())
14108
0
      return InvalidOperands(Loc, LHS, RHS);
14109
14110
0
    return Context.IntTy;
14111
0
  }
14112
14113
  // The following is safe because we only use this method for
14114
  // non-overloadable operands.
14115
14116
  // C++ [expr.log.and]p1
14117
  // C++ [expr.log.or]p1
14118
  // The operands are both contextually converted to type bool.
14119
0
  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
14120
0
  if (LHSRes.isInvalid())
14121
0
    return InvalidOperands(Loc, LHS, RHS);
14122
0
  LHS = LHSRes;
14123
14124
0
  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
14125
0
  if (RHSRes.isInvalid())
14126
0
    return InvalidOperands(Loc, LHS, RHS);
14127
0
  RHS = RHSRes;
14128
14129
  // C++ [expr.log.and]p2
14130
  // C++ [expr.log.or]p2
14131
  // The result is a bool.
14132
0
  return Context.BoolTy;
14133
0
}
14134
14135
0
static bool IsReadonlyMessage(Expr *E, Sema &S) {
14136
0
  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14137
0
  if (!ME) return false;
14138
0
  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14139
0
  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14140
0
      ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14141
0
  if (!Base) return false;
14142
0
  return Base->getMethodDecl() != nullptr;
14143
0
}
14144
14145
/// Is the given expression (which must be 'const') a reference to a
14146
/// variable which was originally non-const, but which has become
14147
/// 'const' due to being captured within a block?
14148
enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14149
0
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14150
0
  assert(E->isLValue() && E->getType().isConstQualified());
14151
0
  E = E->IgnoreParens();
14152
14153
  // Must be a reference to a declaration from an enclosing scope.
14154
0
  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14155
0
  if (!DRE) return NCCK_None;
14156
0
  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14157
14158
  // The declaration must be a variable which is not declared 'const'.
14159
0
  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
14160
0
  if (!var) return NCCK_None;
14161
0
  if (var->getType().isConstQualified()) return NCCK_None;
14162
0
  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
14163
14164
  // Decide whether the first capture was for a block or a lambda.
14165
0
  DeclContext *DC = S.CurContext, *Prev = nullptr;
14166
  // Decide whether the first capture was for a block or a lambda.
14167
0
  while (DC) {
14168
    // For init-capture, it is possible that the variable belongs to the
14169
    // template pattern of the current context.
14170
0
    if (auto *FD = dyn_cast<FunctionDecl>(DC))
14171
0
      if (var->isInitCapture() &&
14172
0
          FD->getTemplateInstantiationPattern() == var->getDeclContext())
14173
0
        break;
14174
0
    if (DC == var->getDeclContext())
14175
0
      break;
14176
0
    Prev = DC;
14177
0
    DC = DC->getParent();
14178
0
  }
14179
  // Unless we have an init-capture, we've gone one step too far.
14180
0
  if (!var->isInitCapture())
14181
0
    DC = Prev;
14182
0
  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14183
0
}
14184
14185
0
static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14186
0
  Ty = Ty.getNonReferenceType();
14187
0
  if (IsDereference && Ty->isPointerType())
14188
0
    Ty = Ty->getPointeeType();
14189
0
  return !Ty.isConstQualified();
14190
0
}
14191
14192
// Update err_typecheck_assign_const and note_typecheck_assign_const
14193
// when this enum is changed.
14194
enum {
14195
  ConstFunction,
14196
  ConstVariable,
14197
  ConstMember,
14198
  ConstMethod,
14199
  NestedConstMember,
14200
  ConstUnknown,  // Keep as last element
14201
};
14202
14203
/// Emit the "read-only variable not assignable" error and print notes to give
14204
/// more information about why the variable is not assignable, such as pointing
14205
/// to the declaration of a const variable, showing that a method is const, or
14206
/// that the function is returning a const reference.
14207
static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14208
0
                                    SourceLocation Loc) {
14209
0
  SourceRange ExprRange = E->getSourceRange();
14210
14211
  // Only emit one error on the first const found.  All other consts will emit
14212
  // a note to the error.
14213
0
  bool DiagnosticEmitted = false;
14214
14215
  // Track if the current expression is the result of a dereference, and if the
14216
  // next checked expression is the result of a dereference.
14217
0
  bool IsDereference = false;
14218
0
  bool NextIsDereference = false;
14219
14220
  // Loop to process MemberExpr chains.
14221
0
  while (true) {
14222
0
    IsDereference = NextIsDereference;
14223
14224
0
    E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14225
0
    if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14226
0
      NextIsDereference = ME->isArrow();
14227
0
      const ValueDecl *VD = ME->getMemberDecl();
14228
0
      if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14229
        // Mutable fields can be modified even if the class is const.
14230
0
        if (Field->isMutable()) {
14231
0
          assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14232
0
          break;
14233
0
        }
14234
14235
0
        if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14236
0
          if (!DiagnosticEmitted) {
14237
0
            S.Diag(Loc, diag::err_typecheck_assign_const)
14238
0
                << ExprRange << ConstMember << false /*static*/ << Field
14239
0
                << Field->getType();
14240
0
            DiagnosticEmitted = true;
14241
0
          }
14242
0
          S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14243
0
              << ConstMember << false /*static*/ << Field << Field->getType()
14244
0
              << Field->getSourceRange();
14245
0
        }
14246
0
        E = ME->getBase();
14247
0
        continue;
14248
0
      } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14249
0
        if (VDecl->getType().isConstQualified()) {
14250
0
          if (!DiagnosticEmitted) {
14251
0
            S.Diag(Loc, diag::err_typecheck_assign_const)
14252
0
                << ExprRange << ConstMember << true /*static*/ << VDecl
14253
0
                << VDecl->getType();
14254
0
            DiagnosticEmitted = true;
14255
0
          }
14256
0
          S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14257
0
              << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14258
0
              << VDecl->getSourceRange();
14259
0
        }
14260
        // Static fields do not inherit constness from parents.
14261
0
        break;
14262
0
      }
14263
0
      break; // End MemberExpr
14264
0
    } else if (const ArraySubscriptExpr *ASE =
14265
0
                   dyn_cast<ArraySubscriptExpr>(E)) {
14266
0
      E = ASE->getBase()->IgnoreParenImpCasts();
14267
0
      continue;
14268
0
    } else if (const ExtVectorElementExpr *EVE =
14269
0
                   dyn_cast<ExtVectorElementExpr>(E)) {
14270
0
      E = EVE->getBase()->IgnoreParenImpCasts();
14271
0
      continue;
14272
0
    }
14273
0
    break;
14274
0
  }
14275
14276
0
  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14277
    // Function calls
14278
0
    const FunctionDecl *FD = CE->getDirectCallee();
14279
0
    if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14280
0
      if (!DiagnosticEmitted) {
14281
0
        S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14282
0
                                                      << ConstFunction << FD;
14283
0
        DiagnosticEmitted = true;
14284
0
      }
14285
0
      S.Diag(FD->getReturnTypeSourceRange().getBegin(),
14286
0
             diag::note_typecheck_assign_const)
14287
0
          << ConstFunction << FD << FD->getReturnType()
14288
0
          << FD->getReturnTypeSourceRange();
14289
0
    }
14290
0
  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14291
    // Point to variable declaration.
14292
0
    if (const ValueDecl *VD = DRE->getDecl()) {
14293
0
      if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14294
0
        if (!DiagnosticEmitted) {
14295
0
          S.Diag(Loc, diag::err_typecheck_assign_const)
14296
0
              << ExprRange << ConstVariable << VD << VD->getType();
14297
0
          DiagnosticEmitted = true;
14298
0
        }
14299
0
        S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14300
0
            << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14301
0
      }
14302
0
    }
14303
0
  } else if (isa<CXXThisExpr>(E)) {
14304
0
    if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14305
0
      if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14306
0
        if (MD->isConst()) {
14307
0
          if (!DiagnosticEmitted) {
14308
0
            S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14309
0
                                                          << ConstMethod << MD;
14310
0
            DiagnosticEmitted = true;
14311
0
          }
14312
0
          S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
14313
0
              << ConstMethod << MD << MD->getSourceRange();
14314
0
        }
14315
0
      }
14316
0
    }
14317
0
  }
14318
14319
0
  if (DiagnosticEmitted)
14320
0
    return;
14321
14322
  // Can't determine a more specific message, so display the generic error.
14323
0
  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14324
0
}
14325
14326
enum OriginalExprKind {
14327
  OEK_Variable,
14328
  OEK_Member,
14329
  OEK_LValue
14330
};
14331
14332
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14333
                                         const RecordType *Ty,
14334
                                         SourceLocation Loc, SourceRange Range,
14335
                                         OriginalExprKind OEK,
14336
0
                                         bool &DiagnosticEmitted) {
14337
0
  std::vector<const RecordType *> RecordTypeList;
14338
0
  RecordTypeList.push_back(Ty);
14339
0
  unsigned NextToCheckIndex = 0;
14340
  // We walk the record hierarchy breadth-first to ensure that we print
14341
  // diagnostics in field nesting order.
14342
0
  while (RecordTypeList.size() > NextToCheckIndex) {
14343
0
    bool IsNested = NextToCheckIndex > 0;
14344
0
    for (const FieldDecl *Field :
14345
0
         RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14346
      // First, check every field for constness.
14347
0
      QualType FieldTy = Field->getType();
14348
0
      if (FieldTy.isConstQualified()) {
14349
0
        if (!DiagnosticEmitted) {
14350
0
          S.Diag(Loc, diag::err_typecheck_assign_const)
14351
0
              << Range << NestedConstMember << OEK << VD
14352
0
              << IsNested << Field;
14353
0
          DiagnosticEmitted = true;
14354
0
        }
14355
0
        S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14356
0
            << NestedConstMember << IsNested << Field
14357
0
            << FieldTy << Field->getSourceRange();
14358
0
      }
14359
14360
      // Then we append it to the list to check next in order.
14361
0
      FieldTy = FieldTy.getCanonicalType();
14362
0
      if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14363
0
        if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14364
0
          RecordTypeList.push_back(FieldRecTy);
14365
0
      }
14366
0
    }
14367
0
    ++NextToCheckIndex;
14368
0
  }
14369
0
}
14370
14371
/// Emit an error for the case where a record we are trying to assign to has a
14372
/// const-qualified field somewhere in its hierarchy.
14373
static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14374
0
                                         SourceLocation Loc) {
14375
0
  QualType Ty = E->getType();
14376
0
  assert(Ty->isRecordType() && "lvalue was not record?");
14377
0
  SourceRange Range = E->getSourceRange();
14378
0
  const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14379
0
  bool DiagEmitted = false;
14380
14381
0
  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14382
0
    DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14383
0
            Range, OEK_Member, DiagEmitted);
14384
0
  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14385
0
    DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14386
0
            Range, OEK_Variable, DiagEmitted);
14387
0
  else
14388
0
    DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14389
0
            Range, OEK_LValue, DiagEmitted);
14390
0
  if (!DiagEmitted)
14391
0
    DiagnoseConstAssignment(S, E, Loc);
14392
0
}
14393
14394
/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
14395
/// emit an error and return true.  If so, return false.
14396
0
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14397
0
  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14398
14399
0
  S.CheckShadowingDeclModification(E, Loc);
14400
14401
0
  SourceLocation OrigLoc = Loc;
14402
0
  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14403
0
                                                              &Loc);
14404
0
  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14405
0
    IsLV = Expr::MLV_InvalidMessageExpression;
14406
0
  if (IsLV == Expr::MLV_Valid)
14407
0
    return false;
14408
14409
0
  unsigned DiagID = 0;
14410
0
  bool NeedType = false;
14411
0
  switch (IsLV) { // C99 6.5.16p2
14412
0
  case Expr::MLV_ConstQualified:
14413
    // Use a specialized diagnostic when we're assigning to an object
14414
    // from an enclosing function or block.
14415
0
    if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14416
0
      if (NCCK == NCCK_Block)
14417
0
        DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14418
0
      else
14419
0
        DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14420
0
      break;
14421
0
    }
14422
14423
    // In ARC, use some specialized diagnostics for occasions where we
14424
    // infer 'const'.  These are always pseudo-strong variables.
14425
0
    if (S.getLangOpts().ObjCAutoRefCount) {
14426
0
      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14427
0
      if (declRef && isa<VarDecl>(declRef->getDecl())) {
14428
0
        VarDecl *var = cast<VarDecl>(declRef->getDecl());
14429
14430
        // Use the normal diagnostic if it's pseudo-__strong but the
14431
        // user actually wrote 'const'.
14432
0
        if (var->isARCPseudoStrong() &&
14433
0
            (!var->getTypeSourceInfo() ||
14434
0
             !var->getTypeSourceInfo()->getType().isConstQualified())) {
14435
          // There are three pseudo-strong cases:
14436
          //  - self
14437
0
          ObjCMethodDecl *method = S.getCurMethodDecl();
14438
0
          if (method && var == method->getSelfDecl()) {
14439
0
            DiagID = method->isClassMethod()
14440
0
              ? diag::err_typecheck_arc_assign_self_class_method
14441
0
              : diag::err_typecheck_arc_assign_self;
14442
14443
          //  - Objective-C externally_retained attribute.
14444
0
          } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14445
0
                     isa<ParmVarDecl>(var)) {
14446
0
            DiagID = diag::err_typecheck_arc_assign_externally_retained;
14447
14448
          //  - fast enumeration variables
14449
0
          } else {
14450
0
            DiagID = diag::err_typecheck_arr_assign_enumeration;
14451
0
          }
14452
14453
0
          SourceRange Assign;
14454
0
          if (Loc != OrigLoc)
14455
0
            Assign = SourceRange(OrigLoc, OrigLoc);
14456
0
          S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14457
          // We need to preserve the AST regardless, so migration tool
14458
          // can do its job.
14459
0
          return false;
14460
0
        }
14461
0
      }
14462
0
    }
14463
14464
    // If none of the special cases above are triggered, then this is a
14465
    // simple const assignment.
14466
0
    if (DiagID == 0) {
14467
0
      DiagnoseConstAssignment(S, E, Loc);
14468
0
      return true;
14469
0
    }
14470
14471
0
    break;
14472
0
  case Expr::MLV_ConstAddrSpace:
14473
0
    DiagnoseConstAssignment(S, E, Loc);
14474
0
    return true;
14475
0
  case Expr::MLV_ConstQualifiedField:
14476
0
    DiagnoseRecursiveConstFields(S, E, Loc);
14477
0
    return true;
14478
0
  case Expr::MLV_ArrayType:
14479
0
  case Expr::MLV_ArrayTemporary:
14480
0
    DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14481
0
    NeedType = true;
14482
0
    break;
14483
0
  case Expr::MLV_NotObjectType:
14484
0
    DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14485
0
    NeedType = true;
14486
0
    break;
14487
0
  case Expr::MLV_LValueCast:
14488
0
    DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14489
0
    break;
14490
0
  case Expr::MLV_Valid:
14491
0
    llvm_unreachable("did not take early return for MLV_Valid");
14492
0
  case Expr::MLV_InvalidExpression:
14493
0
  case Expr::MLV_MemberFunction:
14494
0
  case Expr::MLV_ClassTemporary:
14495
0
    DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14496
0
    break;
14497
0
  case Expr::MLV_IncompleteType:
14498
0
  case Expr::MLV_IncompleteVoidType:
14499
0
    return S.RequireCompleteType(Loc, E->getType(),
14500
0
             diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14501
0
  case Expr::MLV_DuplicateVectorComponents:
14502
0
    DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14503
0
    break;
14504
0
  case Expr::MLV_NoSetterProperty:
14505
0
    llvm_unreachable("readonly properties should be processed differently");
14506
0
  case Expr::MLV_InvalidMessageExpression:
14507
0
    DiagID = diag::err_readonly_message_assignment;
14508
0
    break;
14509
0
  case Expr::MLV_SubObjCPropertySetting:
14510
0
    DiagID = diag::err_no_subobject_property_setting;
14511
0
    break;
14512
0
  }
14513
14514
0
  SourceRange Assign;
14515
0
  if (Loc != OrigLoc)
14516
0
    Assign = SourceRange(OrigLoc, OrigLoc);
14517
0
  if (NeedType)
14518
0
    S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14519
0
  else
14520
0
    S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14521
0
  return true;
14522
0
}
14523
14524
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14525
                                         SourceLocation Loc,
14526
6
                                         Sema &Sema) {
14527
6
  if (Sema.inTemplateInstantiation())
14528
0
    return;
14529
6
  if (Sema.isUnevaluatedContext())
14530
0
    return;
14531
6
  if (Loc.isInvalid() || Loc.isMacroID())
14532
0
    return;
14533
6
  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14534
0
    return;
14535
14536
  // C / C++ fields
14537
6
  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14538
6
  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14539
6
  if (ML && MR) {
14540
0
    if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14541
0
      return;
14542
0
    const ValueDecl *LHSDecl =
14543
0
        cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14544
0
    const ValueDecl *RHSDecl =
14545
0
        cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14546
0
    if (LHSDecl != RHSDecl)
14547
0
      return;
14548
0
    if (LHSDecl->getType().isVolatileQualified())
14549
0
      return;
14550
0
    if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14551
0
      if (RefTy->getPointeeType().isVolatileQualified())
14552
0
        return;
14553
14554
0
    Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14555
0
  }
14556
14557
  // Objective-C instance variables
14558
6
  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14559
6
  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14560
6
  if (OL && OR && OL->getDecl() == OR->getDecl()) {
14561
0
    DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14562
0
    DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14563
0
    if (RL && RR && RL->getDecl() == RR->getDecl())
14564
0
      Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14565
0
  }
14566
6
}
14567
14568
// C99 6.5.16.1
14569
QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14570
                                       SourceLocation Loc,
14571
                                       QualType CompoundType,
14572
0
                                       BinaryOperatorKind Opc) {
14573
0
  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14574
14575
  // Verify that LHS is a modifiable lvalue, and emit error if not.
14576
0
  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14577
0
    return QualType();
14578
14579
0
  QualType LHSType = LHSExpr->getType();
14580
0
  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14581
0
                                             CompoundType;
14582
  // OpenCL v1.2 s6.1.1.1 p2:
14583
  // The half data type can only be used to declare a pointer to a buffer that
14584
  // contains half values
14585
0
  if (getLangOpts().OpenCL &&
14586
0
      !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14587
0
      LHSType->isHalfType()) {
14588
0
    Diag(Loc, diag::err_opencl_half_load_store) << 1
14589
0
        << LHSType.getUnqualifiedType();
14590
0
    return QualType();
14591
0
  }
14592
14593
  // WebAssembly tables can't be used on RHS of an assignment expression.
14594
0
  if (RHSType->isWebAssemblyTableType()) {
14595
0
    Diag(Loc, diag::err_wasm_table_art) << 0;
14596
0
    return QualType();
14597
0
  }
14598
14599
0
  AssignConvertType ConvTy;
14600
0
  if (CompoundType.isNull()) {
14601
0
    Expr *RHSCheck = RHS.get();
14602
14603
0
    CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14604
14605
0
    QualType LHSTy(LHSType);
14606
0
    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14607
0
    if (RHS.isInvalid())
14608
0
      return QualType();
14609
    // Special case of NSObject attributes on c-style pointer types.
14610
0
    if (ConvTy == IncompatiblePointer &&
14611
0
        ((Context.isObjCNSObjectType(LHSType) &&
14612
0
          RHSType->isObjCObjectPointerType()) ||
14613
0
         (Context.isObjCNSObjectType(RHSType) &&
14614
0
          LHSType->isObjCObjectPointerType())))
14615
0
      ConvTy = Compatible;
14616
14617
0
    if (ConvTy == Compatible &&
14618
0
        LHSType->isObjCObjectType())
14619
0
        Diag(Loc, diag::err_objc_object_assignment)
14620
0
          << LHSType;
14621
14622
    // If the RHS is a unary plus or minus, check to see if they = and + are
14623
    // right next to each other.  If so, the user may have typo'd "x =+ 4"
14624
    // instead of "x += 4".
14625
0
    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14626
0
      RHSCheck = ICE->getSubExpr();
14627
0
    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14628
0
      if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14629
0
          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14630
          // Only if the two operators are exactly adjacent.
14631
0
          Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14632
          // And there is a space or other character before the subexpr of the
14633
          // unary +/-.  We don't want to warn on "x=-1".
14634
0
          Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14635
0
          UO->getSubExpr()->getBeginLoc().isFileID()) {
14636
0
        Diag(Loc, diag::warn_not_compound_assign)
14637
0
          << (UO->getOpcode() == UO_Plus ? "+" : "-")
14638
0
          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14639
0
      }
14640
0
    }
14641
14642
0
    if (ConvTy == Compatible) {
14643
0
      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14644
        // Warn about retain cycles where a block captures the LHS, but
14645
        // not if the LHS is a simple variable into which the block is
14646
        // being stored...unless that variable can be captured by reference!
14647
0
        const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14648
0
        const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14649
0
        if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14650
0
          checkRetainCycles(LHSExpr, RHS.get());
14651
0
      }
14652
14653
0
      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14654
0
          LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14655
        // It is safe to assign a weak reference into a strong variable.
14656
        // Although this code can still have problems:
14657
        //   id x = self.weakProp;
14658
        //   id y = self.weakProp;
14659
        // we do not warn to warn spuriously when 'x' and 'y' are on separate
14660
        // paths through the function. This should be revisited if
14661
        // -Wrepeated-use-of-weak is made flow-sensitive.
14662
        // For ObjCWeak only, we do not warn if the assign is to a non-weak
14663
        // variable, which will be valid for the current autorelease scope.
14664
0
        if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14665
0
                             RHS.get()->getBeginLoc()))
14666
0
          getCurFunction()->markSafeWeakUse(RHS.get());
14667
14668
0
      } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14669
0
        checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14670
0
      }
14671
0
    }
14672
0
  } else {
14673
    // Compound assignment "x += y"
14674
0
    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14675
0
  }
14676
14677
0
  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14678
0
                               RHS.get(), AA_Assigning))
14679
0
    return QualType();
14680
14681
0
  CheckForNullPointerDereference(*this, LHSExpr);
14682
14683
0
  if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14684
0
    if (CompoundType.isNull()) {
14685
      // C++2a [expr.ass]p5:
14686
      //   A simple-assignment whose left operand is of a volatile-qualified
14687
      //   type is deprecated unless the assignment is either a discarded-value
14688
      //   expression or an unevaluated operand
14689
0
      ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14690
0
    }
14691
0
  }
14692
14693
  // C11 6.5.16p3: The type of an assignment expression is the type of the
14694
  // left operand would have after lvalue conversion.
14695
  // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14696
  // qualified type, the value has the unqualified version of the type of the
14697
  // lvalue; additionally, if the lvalue has atomic type, the value has the
14698
  // non-atomic version of the type of the lvalue.
14699
  // C++ 5.17p1: the type of the assignment expression is that of its left
14700
  // operand.
14701
0
  return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14702
0
}
14703
14704
// Scenarios to ignore if expression E is:
14705
// 1. an explicit cast expression into void
14706
// 2. a function call expression that returns void
14707
0
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14708
0
  E = E->IgnoreParens();
14709
14710
0
  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14711
0
    if (CE->getCastKind() == CK_ToVoid) {
14712
0
      return true;
14713
0
    }
14714
14715
    // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14716
0
    if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14717
0
        CE->getSubExpr()->getType()->isDependentType()) {
14718
0
      return true;
14719
0
    }
14720
0
  }
14721
14722
0
  if (const auto *CE = dyn_cast<CallExpr>(E))
14723
0
    return CE->getCallReturnType(Context)->isVoidType();
14724
0
  return false;
14725
0
}
14726
14727
// Look for instances where it is likely the comma operator is confused with
14728
// another operator.  There is an explicit list of acceptable expressions for
14729
// the left hand side of the comma operator, otherwise emit a warning.
14730
0
void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14731
  // No warnings in macros
14732
0
  if (Loc.isMacroID())
14733
0
    return;
14734
14735
  // Don't warn in template instantiations.
14736
0
  if (inTemplateInstantiation())
14737
0
    return;
14738
14739
  // Scope isn't fine-grained enough to explicitly list the specific cases, so
14740
  // instead, skip more than needed, then call back into here with the
14741
  // CommaVisitor in SemaStmt.cpp.
14742
  // The listed locations are the initialization and increment portions
14743
  // of a for loop.  The additional checks are on the condition of
14744
  // if statements, do/while loops, and for loops.
14745
  // Differences in scope flags for C89 mode requires the extra logic.
14746
0
  const unsigned ForIncrementFlags =
14747
0
      getLangOpts().C99 || getLangOpts().CPlusPlus
14748
0
          ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14749
0
          : Scope::ContinueScope | Scope::BreakScope;
14750
0
  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14751
0
  const unsigned ScopeFlags = getCurScope()->getFlags();
14752
0
  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14753
0
      (ScopeFlags & ForInitFlags) == ForInitFlags)
14754
0
    return;
14755
14756
  // If there are multiple comma operators used together, get the RHS of the
14757
  // of the comma operator as the LHS.
14758
0
  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14759
0
    if (BO->getOpcode() != BO_Comma)
14760
0
      break;
14761
0
    LHS = BO->getRHS();
14762
0
  }
14763
14764
  // Only allow some expressions on LHS to not warn.
14765
0
  if (IgnoreCommaOperand(LHS, Context))
14766
0
    return;
14767
14768
0
  Diag(Loc, diag::warn_comma_operator);
14769
0
  Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14770
0
      << LHS->getSourceRange()
14771
0
      << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14772
0
                                    LangOpts.CPlusPlus ? "static_cast<void>("
14773
0
                                                       : "(void)(")
14774
0
      << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14775
0
                                    ")");
14776
0
}
14777
14778
// C99 6.5.17
14779
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14780
0
                                   SourceLocation Loc) {
14781
0
  LHS = S.CheckPlaceholderExpr(LHS.get());
14782
0
  RHS = S.CheckPlaceholderExpr(RHS.get());
14783
0
  if (LHS.isInvalid() || RHS.isInvalid())
14784
0
    return QualType();
14785
14786
  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14787
  // operands, but not unary promotions.
14788
  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14789
14790
  // So we treat the LHS as a ignored value, and in C++ we allow the
14791
  // containing site to determine what should be done with the RHS.
14792
0
  LHS = S.IgnoredValueConversions(LHS.get());
14793
0
  if (LHS.isInvalid())
14794
0
    return QualType();
14795
14796
0
  S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14797
14798
0
  if (!S.getLangOpts().CPlusPlus) {
14799
0
    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14800
0
    if (RHS.isInvalid())
14801
0
      return QualType();
14802
0
    if (!RHS.get()->getType()->isVoidType())
14803
0
      S.RequireCompleteType(Loc, RHS.get()->getType(),
14804
0
                            diag::err_incomplete_type);
14805
0
  }
14806
14807
0
  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14808
0
    S.DiagnoseCommaOperator(LHS.get(), Loc);
14809
14810
0
  return RHS.get()->getType();
14811
0
}
14812
14813
/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14814
/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14815
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14816
                                               ExprValueKind &VK,
14817
                                               ExprObjectKind &OK,
14818
                                               SourceLocation OpLoc,
14819
0
                                               bool IsInc, bool IsPrefix) {
14820
0
  if (Op->isTypeDependent())
14821
0
    return S.Context.DependentTy;
14822
14823
0
  QualType ResType = Op->getType();
14824
  // Atomic types can be used for increment / decrement where the non-atomic
14825
  // versions can, so ignore the _Atomic() specifier for the purpose of
14826
  // checking.
14827
0
  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14828
0
    ResType = ResAtomicType->getValueType();
14829
14830
0
  assert(!ResType.isNull() && "no type for increment/decrement expression");
14831
14832
0
  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14833
    // Decrement of bool is not allowed.
14834
0
    if (!IsInc) {
14835
0
      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14836
0
      return QualType();
14837
0
    }
14838
    // Increment of bool sets it to true, but is deprecated.
14839
0
    S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14840
0
                                              : diag::warn_increment_bool)
14841
0
      << Op->getSourceRange();
14842
0
  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14843
    // Error on enum increments and decrements in C++ mode
14844
0
    S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14845
0
    return QualType();
14846
0
  } else if (ResType->isRealType()) {
14847
    // OK!
14848
0
  } else if (ResType->isPointerType()) {
14849
    // C99 6.5.2.4p2, 6.5.6p2
14850
0
    if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14851
0
      return QualType();
14852
0
  } else if (ResType->isObjCObjectPointerType()) {
14853
    // On modern runtimes, ObjC pointer arithmetic is forbidden.
14854
    // Otherwise, we just need a complete type.
14855
0
    if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14856
0
        checkArithmeticOnObjCPointer(S, OpLoc, Op))
14857
0
      return QualType();
14858
0
  } else if (ResType->isAnyComplexType()) {
14859
    // C99 does not support ++/-- on complex types, we allow as an extension.
14860
0
    S.Diag(OpLoc, diag::ext_integer_increment_complex)
14861
0
      << ResType << Op->getSourceRange();
14862
0
  } else if (ResType->isPlaceholderType()) {
14863
0
    ExprResult PR = S.CheckPlaceholderExpr(Op);
14864
0
    if (PR.isInvalid()) return QualType();
14865
0
    return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14866
0
                                          IsInc, IsPrefix);
14867
0
  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14868
    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14869
0
  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14870
0
             (ResType->castAs<VectorType>()->getVectorKind() !=
14871
0
              VectorKind::AltiVecBool)) {
14872
    // The z vector extensions allow ++ and -- for non-bool vectors.
14873
0
  } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14874
0
             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14875
    // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14876
0
  } else {
14877
0
    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14878
0
      << ResType << int(IsInc) << Op->getSourceRange();
14879
0
    return QualType();
14880
0
  }
14881
  // At this point, we know we have a real, complex or pointer type.
14882
  // Now make sure the operand is a modifiable lvalue.
14883
0
  if (CheckForModifiableLvalue(Op, OpLoc, S))
14884
0
    return QualType();
14885
0
  if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14886
    // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14887
    //   An operand with volatile-qualified type is deprecated
14888
0
    S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14889
0
        << IsInc << ResType;
14890
0
  }
14891
  // In C++, a prefix increment is the same type as the operand. Otherwise
14892
  // (in C or with postfix), the increment is the unqualified type of the
14893
  // operand.
14894
0
  if (IsPrefix && S.getLangOpts().CPlusPlus) {
14895
0
    VK = VK_LValue;
14896
0
    OK = Op->getObjectKind();
14897
0
    return ResType;
14898
0
  } else {
14899
0
    VK = VK_PRValue;
14900
0
    return ResType.getUnqualifiedType();
14901
0
  }
14902
0
}
14903
14904
14905
/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14906
/// This routine allows us to typecheck complex/recursive expressions
14907
/// where the declaration is needed for type checking. We only need to
14908
/// handle cases when the expression references a function designator
14909
/// or is an lvalue. Here are some examples:
14910
///  - &(x) => x
14911
///  - &*****f => f for f a function designator.
14912
///  - &s.xx => s
14913
///  - &s.zz[1].yy -> s, if zz is an array
14914
///  - *(x + 1) -> x, if x is an array
14915
///  - &"123"[2] -> 0
14916
///  - & __real__ x -> x
14917
///
14918
/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14919
/// members.
14920
0
static ValueDecl *getPrimaryDecl(Expr *E) {
14921
0
  switch (E->getStmtClass()) {
14922
0
  case Stmt::DeclRefExprClass:
14923
0
    return cast<DeclRefExpr>(E)->getDecl();
14924
0
  case Stmt::MemberExprClass:
14925
    // If this is an arrow operator, the address is an offset from
14926
    // the base's value, so the object the base refers to is
14927
    // irrelevant.
14928
0
    if (cast<MemberExpr>(E)->isArrow())
14929
0
      return nullptr;
14930
    // Otherwise, the expression refers to a part of the base
14931
0
    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14932
0
  case Stmt::ArraySubscriptExprClass: {
14933
    // FIXME: This code shouldn't be necessary!  We should catch the implicit
14934
    // promotion of register arrays earlier.
14935
0
    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14936
0
    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14937
0
      if (ICE->getSubExpr()->getType()->isArrayType())
14938
0
        return getPrimaryDecl(ICE->getSubExpr());
14939
0
    }
14940
0
    return nullptr;
14941
0
  }
14942
0
  case Stmt::UnaryOperatorClass: {
14943
0
    UnaryOperator *UO = cast<UnaryOperator>(E);
14944
14945
0
    switch(UO->getOpcode()) {
14946
0
    case UO_Real:
14947
0
    case UO_Imag:
14948
0
    case UO_Extension:
14949
0
      return getPrimaryDecl(UO->getSubExpr());
14950
0
    default:
14951
0
      return nullptr;
14952
0
    }
14953
0
  }
14954
0
  case Stmt::ParenExprClass:
14955
0
    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14956
0
  case Stmt::ImplicitCastExprClass:
14957
    // If the result of an implicit cast is an l-value, we care about
14958
    // the sub-expression; otherwise, the result here doesn't matter.
14959
0
    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14960
0
  case Stmt::CXXUuidofExprClass:
14961
0
    return cast<CXXUuidofExpr>(E)->getGuidDecl();
14962
0
  default:
14963
0
    return nullptr;
14964
0
  }
14965
0
}
14966
14967
namespace {
14968
enum {
14969
  AO_Bit_Field = 0,
14970
  AO_Vector_Element = 1,
14971
  AO_Property_Expansion = 2,
14972
  AO_Register_Variable = 3,
14973
  AO_Matrix_Element = 4,
14974
  AO_No_Error = 5
14975
};
14976
}
14977
/// Diagnose invalid operand for address of operations.
14978
///
14979
/// \param Type The type of operand which cannot have its address taken.
14980
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14981
0
                                         Expr *E, unsigned Type) {
14982
0
  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14983
0
}
14984
14985
bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14986
                                                 const Expr *Op,
14987
0
                                                 const CXXMethodDecl *MD) {
14988
0
  const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14989
14990
0
  if (Op != DRE)
14991
0
    return Diag(OpLoc, diag::err_parens_pointer_member_function)
14992
0
           << Op->getSourceRange();
14993
14994
  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14995
0
  if (isa<CXXDestructorDecl>(MD))
14996
0
    return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14997
0
           << DRE->getSourceRange();
14998
14999
0
  if (DRE->getQualifier())
15000
0
    return false;
15001
15002
0
  if (MD->getParent()->getName().empty())
15003
0
    return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15004
0
           << DRE->getSourceRange();
15005
15006
0
  SmallString<32> Str;
15007
0
  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15008
0
  return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15009
0
         << DRE->getSourceRange()
15010
0
         << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
15011
0
}
15012
15013
/// CheckAddressOfOperand - The operand of & must be either a function
15014
/// designator or an lvalue designating an object. If it is an lvalue, the
15015
/// object cannot be declared with storage class register or be a bit field.
15016
/// Note: The usual conversions are *not* applied to the operand of the &
15017
/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
15018
/// In C++, the operand might be an overloaded function name, in which case
15019
/// we allow the '&' but retain the overloaded-function type.
15020
0
QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15021
0
  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15022
0
    if (PTy->getKind() == BuiltinType::Overload) {
15023
0
      Expr *E = OrigOp.get()->IgnoreParens();
15024
0
      if (!isa<OverloadExpr>(E)) {
15025
0
        assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15026
0
        Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15027
0
          << OrigOp.get()->getSourceRange();
15028
0
        return QualType();
15029
0
      }
15030
15031
0
      OverloadExpr *Ovl = cast<OverloadExpr>(E);
15032
0
      if (isa<UnresolvedMemberExpr>(Ovl))
15033
0
        if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
15034
0
          Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15035
0
            << OrigOp.get()->getSourceRange();
15036
0
          return QualType();
15037
0
        }
15038
15039
0
      return Context.OverloadTy;
15040
0
    }
15041
15042
0
    if (PTy->getKind() == BuiltinType::UnknownAny)
15043
0
      return Context.UnknownAnyTy;
15044
15045
0
    if (PTy->getKind() == BuiltinType::BoundMember) {
15046
0
      Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15047
0
        << OrigOp.get()->getSourceRange();
15048
0
      return QualType();
15049
0
    }
15050
15051
0
    OrigOp = CheckPlaceholderExpr(OrigOp.get());
15052
0
    if (OrigOp.isInvalid()) return QualType();
15053
0
  }
15054
15055
0
  if (OrigOp.get()->isTypeDependent())
15056
0
    return Context.DependentTy;
15057
15058
0
  assert(!OrigOp.get()->hasPlaceholderType());
15059
15060
  // Make sure to ignore parentheses in subsequent checks
15061
0
  Expr *op = OrigOp.get()->IgnoreParens();
15062
15063
  // In OpenCL captures for blocks called as lambda functions
15064
  // are located in the private address space. Blocks used in
15065
  // enqueue_kernel can be located in a different address space
15066
  // depending on a vendor implementation. Thus preventing
15067
  // taking an address of the capture to avoid invalid AS casts.
15068
0
  if (LangOpts.OpenCL) {
15069
0
    auto* VarRef = dyn_cast<DeclRefExpr>(op);
15070
0
    if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15071
0
      Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15072
0
      return QualType();
15073
0
    }
15074
0
  }
15075
15076
0
  if (getLangOpts().C99) {
15077
    // Implement C99-only parts of addressof rules.
15078
0
    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15079
0
      if (uOp->getOpcode() == UO_Deref)
15080
        // Per C99 6.5.3.2, the address of a deref always returns a valid result
15081
        // (assuming the deref expression is valid).
15082
0
        return uOp->getSubExpr()->getType();
15083
0
    }
15084
    // Technically, there should be a check for array subscript
15085
    // expressions here, but the result of one is always an lvalue anyway.
15086
0
  }
15087
0
  ValueDecl *dcl = getPrimaryDecl(op);
15088
15089
0
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15090
0
    if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15091
0
                                           op->getBeginLoc()))
15092
0
      return QualType();
15093
15094
0
  Expr::LValueClassification lval = op->ClassifyLValue(Context);
15095
0
  unsigned AddressOfError = AO_No_Error;
15096
15097
0
  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15098
0
    bool sfinae = (bool)isSFINAEContext();
15099
0
    Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
15100
0
                                  : diag::ext_typecheck_addrof_temporary)
15101
0
      << op->getType() << op->getSourceRange();
15102
0
    if (sfinae)
15103
0
      return QualType();
15104
    // Materialize the temporary as an lvalue so that we can take its address.
15105
0
    OrigOp = op =
15106
0
        CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15107
0
  } else if (isa<ObjCSelectorExpr>(op)) {
15108
0
    return Context.getPointerType(op->getType());
15109
0
  } else if (lval == Expr::LV_MemberFunction) {
15110
    // If it's an instance method, make a member pointer.
15111
    // The expression must have exactly the form &A::foo.
15112
15113
    // If the underlying expression isn't a decl ref, give up.
15114
0
    if (!isa<DeclRefExpr>(op)) {
15115
0
      Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15116
0
        << OrigOp.get()->getSourceRange();
15117
0
      return QualType();
15118
0
    }
15119
0
    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15120
0
    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
15121
15122
0
    CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15123
15124
0
    QualType MPTy = Context.getMemberPointerType(
15125
0
        op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
15126
    // Under the MS ABI, lock down the inheritance model now.
15127
0
    if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15128
0
      (void)isCompleteType(OpLoc, MPTy);
15129
0
    return MPTy;
15130
0
  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15131
    // C99 6.5.3.2p1
15132
    // The operand must be either an l-value or a function designator
15133
0
    if (!op->getType()->isFunctionType()) {
15134
      // Use a special diagnostic for loads from property references.
15135
0
      if (isa<PseudoObjectExpr>(op)) {
15136
0
        AddressOfError = AO_Property_Expansion;
15137
0
      } else {
15138
0
        Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15139
0
          << op->getType() << op->getSourceRange();
15140
0
        return QualType();
15141
0
      }
15142
0
    } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15143
0
      if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15144
0
        CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15145
0
    }
15146
15147
0
  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15148
    // The operand cannot be a bit-field
15149
0
    AddressOfError = AO_Bit_Field;
15150
0
  } else if (op->getObjectKind() == OK_VectorComponent) {
15151
    // The operand cannot be an element of a vector
15152
0
    AddressOfError = AO_Vector_Element;
15153
0
  } else if (op->getObjectKind() == OK_MatrixComponent) {
15154
    // The operand cannot be an element of a matrix.
15155
0
    AddressOfError = AO_Matrix_Element;
15156
0
  } else if (dcl) { // C99 6.5.3.2p1
15157
    // We have an lvalue with a decl. Make sure the decl is not declared
15158
    // with the register storage-class specifier.
15159
0
    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15160
      // in C++ it is not error to take address of a register
15161
      // variable (c++03 7.1.1P3)
15162
0
      if (vd->getStorageClass() == SC_Register &&
15163
0
          !getLangOpts().CPlusPlus) {
15164
0
        AddressOfError = AO_Register_Variable;
15165
0
      }
15166
0
    } else if (isa<MSPropertyDecl>(dcl)) {
15167
0
      AddressOfError = AO_Property_Expansion;
15168
0
    } else if (isa<FunctionTemplateDecl>(dcl)) {
15169
0
      return Context.OverloadTy;
15170
0
    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15171
      // Okay: we can take the address of a field.
15172
      // Could be a pointer to member, though, if there is an explicit
15173
      // scope qualifier for the class.
15174
0
      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
15175
0
        DeclContext *Ctx = dcl->getDeclContext();
15176
0
        if (Ctx && Ctx->isRecord()) {
15177
0
          if (dcl->getType()->isReferenceType()) {
15178
0
            Diag(OpLoc,
15179
0
                 diag::err_cannot_form_pointer_to_member_of_reference_type)
15180
0
              << dcl->getDeclName() << dcl->getType();
15181
0
            return QualType();
15182
0
          }
15183
15184
0
          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15185
0
            Ctx = Ctx->getParent();
15186
15187
0
          QualType MPTy = Context.getMemberPointerType(
15188
0
              op->getType(),
15189
0
              Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
15190
          // Under the MS ABI, lock down the inheritance model now.
15191
0
          if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15192
0
            (void)isCompleteType(OpLoc, MPTy);
15193
0
          return MPTy;
15194
0
        }
15195
0
      }
15196
0
    } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
15197
0
                    MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
15198
0
      llvm_unreachable("Unknown/unexpected decl type");
15199
0
  }
15200
15201
0
  if (AddressOfError != AO_No_Error) {
15202
0
    diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15203
0
    return QualType();
15204
0
  }
15205
15206
0
  if (lval == Expr::LV_IncompleteVoidType) {
15207
    // Taking the address of a void variable is technically illegal, but we
15208
    // allow it in cases which are otherwise valid.
15209
    // Example: "extern void x; void* y = &x;".
15210
0
    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15211
0
  }
15212
15213
  // If the operand has type "type", the result has type "pointer to type".
15214
0
  if (op->getType()->isObjCObjectType())
15215
0
    return Context.getObjCObjectPointerType(op->getType());
15216
15217
  // Cannot take the address of WebAssembly references or tables.
15218
0
  if (Context.getTargetInfo().getTriple().isWasm()) {
15219
0
    QualType OpTy = op->getType();
15220
0
    if (OpTy.isWebAssemblyReferenceType()) {
15221
0
      Diag(OpLoc, diag::err_wasm_ca_reference)
15222
0
          << 1 << OrigOp.get()->getSourceRange();
15223
0
      return QualType();
15224
0
    }
15225
0
    if (OpTy->isWebAssemblyTableType()) {
15226
0
      Diag(OpLoc, diag::err_wasm_table_pr)
15227
0
          << 1 << OrigOp.get()->getSourceRange();
15228
0
      return QualType();
15229
0
    }
15230
0
  }
15231
15232
0
  CheckAddressOfPackedMember(op);
15233
15234
0
  return Context.getPointerType(op->getType());
15235
0
}
15236
15237
0
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15238
0
  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15239
0
  if (!DRE)
15240
0
    return;
15241
0
  const Decl *D = DRE->getDecl();
15242
0
  if (!D)
15243
0
    return;
15244
0
  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15245
0
  if (!Param)
15246
0
    return;
15247
0
  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15248
0
    if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15249
0
      return;
15250
0
  if (FunctionScopeInfo *FD = S.getCurFunction())
15251
0
    FD->ModifiedNonNullParams.insert(Param);
15252
0
}
15253
15254
/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15255
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15256
                                        SourceLocation OpLoc,
15257
1
                                        bool IsAfterAmp = false) {
15258
1
  if (Op->isTypeDependent())
15259
1
    return S.Context.DependentTy;
15260
15261
0
  ExprResult ConvResult = S.UsualUnaryConversions(Op);
15262
0
  if (ConvResult.isInvalid())
15263
0
    return QualType();
15264
0
  Op = ConvResult.get();
15265
0
  QualType OpTy = Op->getType();
15266
0
  QualType Result;
15267
15268
0
  if (isa<CXXReinterpretCastExpr>(Op)) {
15269
0
    QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15270
0
    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15271
0
                                     Op->getSourceRange());
15272
0
  }
15273
15274
0
  if (const PointerType *PT = OpTy->getAs<PointerType>())
15275
0
  {
15276
0
    Result = PT->getPointeeType();
15277
0
  }
15278
0
  else if (const ObjCObjectPointerType *OPT =
15279
0
             OpTy->getAs<ObjCObjectPointerType>())
15280
0
    Result = OPT->getPointeeType();
15281
0
  else {
15282
0
    ExprResult PR = S.CheckPlaceholderExpr(Op);
15283
0
    if (PR.isInvalid()) return QualType();
15284
0
    if (PR.get() != Op)
15285
0
      return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15286
0
  }
15287
15288
0
  if (Result.isNull()) {
15289
0
    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15290
0
      << OpTy << Op->getSourceRange();
15291
0
    return QualType();
15292
0
  }
15293
15294
0
  if (Result->isVoidType()) {
15295
    // C++ [expr.unary.op]p1:
15296
    //   [...] the expression to which [the unary * operator] is applied shall
15297
    //   be a pointer to an object type, or a pointer to a function type
15298
0
    LangOptions LO = S.getLangOpts();
15299
0
    if (LO.CPlusPlus)
15300
0
      S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15301
0
          << OpTy << Op->getSourceRange();
15302
0
    else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15303
0
      S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15304
0
          << OpTy << Op->getSourceRange();
15305
0
  }
15306
15307
  // Dereferences are usually l-values...
15308
0
  VK = VK_LValue;
15309
15310
  // ...except that certain expressions are never l-values in C.
15311
0
  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15312
0
    VK = VK_PRValue;
15313
15314
0
  return Result;
15315
0
}
15316
15317
26
BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15318
26
  BinaryOperatorKind Opc;
15319
26
  switch (Kind) {
15320
0
  default: llvm_unreachable("Unknown binop!");
15321
0
  case tok::periodstar:           Opc = BO_PtrMemD; break;
15322
0
  case tok::arrowstar:            Opc = BO_PtrMemI; break;
15323
0
  case tok::star:                 Opc = BO_Mul; break;
15324
1
  case tok::slash:                Opc = BO_Div; break;
15325
0
  case tok::percent:              Opc = BO_Rem; break;
15326
3
  case tok::plus:                 Opc = BO_Add; break;
15327
0
  case tok::minus:                Opc = BO_Sub; break;
15328
0
  case tok::lessless:             Opc = BO_Shl; break;
15329
0
  case tok::greatergreater:       Opc = BO_Shr; break;
15330
0
  case tok::lessequal:            Opc = BO_LE; break;
15331
7
  case tok::less:                 Opc = BO_LT; break;
15332
0
  case tok::greaterequal:         Opc = BO_GE; break;
15333
2
  case tok::greater:              Opc = BO_GT; break;
15334
0
  case tok::exclaimequal:         Opc = BO_NE; break;
15335
0
  case tok::equalequal:           Opc = BO_EQ; break;
15336
0
  case tok::spaceship:            Opc = BO_Cmp; break;
15337
2
  case tok::amp:                  Opc = BO_And; break;
15338
1
  case tok::caret:                Opc = BO_Xor; break;
15339
4
  case tok::pipe:                 Opc = BO_Or; break;
15340
0
  case tok::ampamp:               Opc = BO_LAnd; break;
15341
0
  case tok::pipepipe:             Opc = BO_LOr; break;
15342
6
  case tok::equal:                Opc = BO_Assign; break;
15343
0
  case tok::starequal:            Opc = BO_MulAssign; break;
15344
0
  case tok::slashequal:           Opc = BO_DivAssign; break;
15345
0
  case tok::percentequal:         Opc = BO_RemAssign; break;
15346
0
  case tok::plusequal:            Opc = BO_AddAssign; break;
15347
0
  case tok::minusequal:           Opc = BO_SubAssign; break;
15348
0
  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
15349
0
  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
15350
0
  case tok::ampequal:             Opc = BO_AndAssign; break;
15351
0
  case tok::caretequal:           Opc = BO_XorAssign; break;
15352
0
  case tok::pipeequal:            Opc = BO_OrAssign; break;
15353
0
  case tok::comma:                Opc = BO_Comma; break;
15354
26
  }
15355
26
  return Opc;
15356
26
}
15357
15358
static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15359
11
  tok::TokenKind Kind) {
15360
11
  UnaryOperatorKind Opc;
15361
11
  switch (Kind) {
15362
0
  default: llvm_unreachable("Unknown unary op!");
15363
0
  case tok::plusplus:     Opc = UO_PreInc; break;
15364
0
  case tok::minusminus:   Opc = UO_PreDec; break;
15365
1
  case tok::amp:          Opc = UO_AddrOf; break;
15366
3
  case tok::star:         Opc = UO_Deref; break;
15367
0
  case tok::plus:         Opc = UO_Plus; break;
15368
4
  case tok::minus:        Opc = UO_Minus; break;
15369
0
  case tok::tilde:        Opc = UO_Not; break;
15370
3
  case tok::exclaim:      Opc = UO_LNot; break;
15371
0
  case tok::kw___real:    Opc = UO_Real; break;
15372
0
  case tok::kw___imag:    Opc = UO_Imag; break;
15373
0
  case tok::kw___extension__: Opc = UO_Extension; break;
15374
11
  }
15375
11
  return Opc;
15376
11
}
15377
15378
const FieldDecl *
15379
0
Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15380
  // Explore the case for adding 'this->' to the LHS of a self assignment, very
15381
  // common for setters.
15382
  // struct A {
15383
  // int X;
15384
  // -void setX(int X) { X = X; }
15385
  // +void setX(int X) { this->X = X; }
15386
  // };
15387
15388
  // Only consider parameters for self assignment fixes.
15389
0
  if (!isa<ParmVarDecl>(SelfAssigned))
15390
0
    return nullptr;
15391
0
  const auto *Method =
15392
0
      dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15393
0
  if (!Method)
15394
0
    return nullptr;
15395
15396
0
  const CXXRecordDecl *Parent = Method->getParent();
15397
  // In theory this is fixable if the lambda explicitly captures this, but
15398
  // that's added complexity that's rarely going to be used.
15399
0
  if (Parent->isLambda())
15400
0
    return nullptr;
15401
15402
  // FIXME: Use an actual Lookup operation instead of just traversing fields
15403
  // in order to get base class fields.
15404
0
  auto Field =
15405
0
      llvm::find_if(Parent->fields(),
15406
0
                    [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15407
0
                      return F->getDeclName() == Name;
15408
0
                    });
15409
0
  return (Field != Parent->field_end()) ? *Field : nullptr;
15410
0
}
15411
15412
/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15413
/// This warning suppressed in the event of macro expansions.
15414
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15415
6
                                   SourceLocation OpLoc, bool IsBuiltin) {
15416
6
  if (S.inTemplateInstantiation())
15417
0
    return;
15418
6
  if (S.isUnevaluatedContext())
15419
0
    return;
15420
6
  if (OpLoc.isInvalid() || OpLoc.isMacroID())
15421
0
    return;
15422
6
  LHSExpr = LHSExpr->IgnoreParenImpCasts();
15423
6
  RHSExpr = RHSExpr->IgnoreParenImpCasts();
15424
6
  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15425
6
  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15426
6
  if (!LHSDeclRef || !RHSDeclRef ||
15427
6
      LHSDeclRef->getLocation().isMacroID() ||
15428
6
      RHSDeclRef->getLocation().isMacroID())
15429
6
    return;
15430
0
  const ValueDecl *LHSDecl =
15431
0
    cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15432
0
  const ValueDecl *RHSDecl =
15433
0
    cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15434
0
  if (LHSDecl != RHSDecl)
15435
0
    return;
15436
0
  if (LHSDecl->getType().isVolatileQualified())
15437
0
    return;
15438
0
  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15439
0
    if (RefTy->getPointeeType().isVolatileQualified())
15440
0
      return;
15441
15442
0
  auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15443
0
                                      : diag::warn_self_assignment_overloaded)
15444
0
              << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15445
0
              << RHSExpr->getSourceRange();
15446
0
  if (const FieldDecl *SelfAssignField =
15447
0
          S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15448
0
    Diag << 1 << SelfAssignField
15449
0
         << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15450
0
  else
15451
0
    Diag << 0;
15452
0
}
15453
15454
/// Check if a bitwise-& is performed on an Objective-C pointer.  This
15455
/// is usually indicative of introspection within the Objective-C pointer.
15456
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15457
0
                                          SourceLocation OpLoc) {
15458
0
  if (!S.getLangOpts().ObjC)
15459
0
    return;
15460
15461
0
  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15462
0
  const Expr *LHS = L.get();
15463
0
  const Expr *RHS = R.get();
15464
15465
0
  if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15466
0
    ObjCPointerExpr = LHS;
15467
0
    OtherExpr = RHS;
15468
0
  }
15469
0
  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15470
0
    ObjCPointerExpr = RHS;
15471
0
    OtherExpr = LHS;
15472
0
  }
15473
15474
  // This warning is deliberately made very specific to reduce false
15475
  // positives with logic that uses '&' for hashing.  This logic mainly
15476
  // looks for code trying to introspect into tagged pointers, which
15477
  // code should generally never do.
15478
0
  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15479
0
    unsigned Diag = diag::warn_objc_pointer_masking;
15480
    // Determine if we are introspecting the result of performSelectorXXX.
15481
0
    const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15482
    // Special case messages to -performSelector and friends, which
15483
    // can return non-pointer values boxed in a pointer value.
15484
    // Some clients may wish to silence warnings in this subcase.
15485
0
    if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15486
0
      Selector S = ME->getSelector();
15487
0
      StringRef SelArg0 = S.getNameForSlot(0);
15488
0
      if (SelArg0.starts_with("performSelector"))
15489
0
        Diag = diag::warn_objc_pointer_masking_performSelector;
15490
0
    }
15491
15492
0
    S.Diag(OpLoc, Diag)
15493
0
      << ObjCPointerExpr->getSourceRange();
15494
0
  }
15495
0
}
15496
15497
0
static NamedDecl *getDeclFromExpr(Expr *E) {
15498
0
  if (!E)
15499
0
    return nullptr;
15500
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15501
0
    return DRE->getDecl();
15502
0
  if (auto *ME = dyn_cast<MemberExpr>(E))
15503
0
    return ME->getMemberDecl();
15504
0
  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15505
0
    return IRE->getDecl();
15506
0
  return nullptr;
15507
0
}
15508
15509
// This helper function promotes a binary operator's operands (which are of a
15510
// half vector type) to a vector of floats and then truncates the result to
15511
// a vector of either half or short.
15512
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15513
                                      BinaryOperatorKind Opc, QualType ResultTy,
15514
                                      ExprValueKind VK, ExprObjectKind OK,
15515
                                      bool IsCompAssign, SourceLocation OpLoc,
15516
0
                                      FPOptionsOverride FPFeatures) {
15517
0
  auto &Context = S.getASTContext();
15518
0
  assert((isVector(ResultTy, Context.HalfTy) ||
15519
0
          isVector(ResultTy, Context.ShortTy)) &&
15520
0
         "Result must be a vector of half or short");
15521
0
  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15522
0
         isVector(RHS.get()->getType(), Context.HalfTy) &&
15523
0
         "both operands expected to be a half vector");
15524
15525
0
  RHS = convertVector(RHS.get(), Context.FloatTy, S);
15526
0
  QualType BinOpResTy = RHS.get()->getType();
15527
15528
  // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15529
  // change BinOpResTy to a vector of ints.
15530
0
  if (isVector(ResultTy, Context.ShortTy))
15531
0
    BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15532
15533
0
  if (IsCompAssign)
15534
0
    return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15535
0
                                          ResultTy, VK, OK, OpLoc, FPFeatures,
15536
0
                                          BinOpResTy, BinOpResTy);
15537
15538
0
  LHS = convertVector(LHS.get(), Context.FloatTy, S);
15539
0
  auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15540
0
                                    BinOpResTy, VK, OK, OpLoc, FPFeatures);
15541
0
  return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15542
0
}
15543
15544
static std::pair<ExprResult, ExprResult>
15545
CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15546
26
                           Expr *RHSExpr) {
15547
26
  ExprResult LHS = LHSExpr, RHS = RHSExpr;
15548
26
  if (!S.Context.isDependenceAllowed()) {
15549
    // C cannot handle TypoExpr nodes on either side of a binop because it
15550
    // doesn't handle dependent types properly, so make sure any TypoExprs have
15551
    // been dealt with before checking the operands.
15552
0
    LHS = S.CorrectDelayedTyposInExpr(LHS);
15553
0
    RHS = S.CorrectDelayedTyposInExpr(
15554
0
        RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15555
0
        [Opc, LHS](Expr *E) {
15556
0
          if (Opc != BO_Assign)
15557
0
            return ExprResult(E);
15558
          // Avoid correcting the RHS to the same Expr as the LHS.
15559
0
          Decl *D = getDeclFromExpr(E);
15560
0
          return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15561
0
        });
15562
0
  }
15563
26
  return std::make_pair(LHS, RHS);
15564
26
}
15565
15566
/// Returns true if conversion between vectors of halfs and vectors of floats
15567
/// is needed.
15568
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15569
2
                                     Expr *E0, Expr *E1 = nullptr) {
15570
2
  if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15571
2
      Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15572
0
    return false;
15573
15574
2
  auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15575
2
    QualType Ty = E->IgnoreImplicit()->getType();
15576
15577
    // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15578
    // to vectors of floats. Although the element type of the vectors is __fp16,
15579
    // the vectors shouldn't be treated as storage-only types. See the
15580
    // discussion here: https://reviews.llvm.org/rG825235c140e7
15581
2
    if (const VectorType *VT = Ty->getAs<VectorType>()) {
15582
0
      if (VT->getVectorKind() == VectorKind::Neon)
15583
0
        return false;
15584
0
      return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15585
0
    }
15586
2
    return false;
15587
2
  };
15588
15589
2
  return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15590
2
}
15591
15592
/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15593
/// operator @p Opc at location @c TokLoc. This routine only supports
15594
/// built-in operations; ActOnBinOp handles overloaded operators.
15595
ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15596
                                    BinaryOperatorKind Opc,
15597
0
                                    Expr *LHSExpr, Expr *RHSExpr) {
15598
0
  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15599
    // The syntax only allows initializer lists on the RHS of assignment,
15600
    // so we don't need to worry about accepting invalid code for
15601
    // non-assignment operators.
15602
    // C++11 5.17p9:
15603
    //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15604
    //   of x = {} is x = T().
15605
0
    InitializationKind Kind = InitializationKind::CreateDirectList(
15606
0
        RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15607
0
    InitializedEntity Entity =
15608
0
        InitializedEntity::InitializeTemporary(LHSExpr->getType());
15609
0
    InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15610
0
    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15611
0
    if (Init.isInvalid())
15612
0
      return Init;
15613
0
    RHSExpr = Init.get();
15614
0
  }
15615
15616
0
  ExprResult LHS = LHSExpr, RHS = RHSExpr;
15617
0
  QualType ResultTy;     // Result type of the binary operator.
15618
  // The following two variables are used for compound assignment operators
15619
0
  QualType CompLHSTy;    // Type of LHS after promotions for computation
15620
0
  QualType CompResultTy; // Type of computation result
15621
0
  ExprValueKind VK = VK_PRValue;
15622
0
  ExprObjectKind OK = OK_Ordinary;
15623
0
  bool ConvertHalfVec = false;
15624
15625
0
  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15626
0
  if (!LHS.isUsable() || !RHS.isUsable())
15627
0
    return ExprError();
15628
15629
0
  if (getLangOpts().OpenCL) {
15630
0
    QualType LHSTy = LHSExpr->getType();
15631
0
    QualType RHSTy = RHSExpr->getType();
15632
    // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15633
    // the ATOMIC_VAR_INIT macro.
15634
0
    if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15635
0
      SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15636
0
      if (BO_Assign == Opc)
15637
0
        Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15638
0
      else
15639
0
        ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15640
0
      return ExprError();
15641
0
    }
15642
15643
    // OpenCL special types - image, sampler, pipe, and blocks are to be used
15644
    // only with a builtin functions and therefore should be disallowed here.
15645
0
    if (LHSTy->isImageType() || RHSTy->isImageType() ||
15646
0
        LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15647
0
        LHSTy->isPipeType() || RHSTy->isPipeType() ||
15648
0
        LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15649
0
      ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15650
0
      return ExprError();
15651
0
    }
15652
0
  }
15653
15654
0
  checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15655
0
  checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15656
15657
0
  switch (Opc) {
15658
0
  case BO_Assign:
15659
0
    ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15660
0
    if (getLangOpts().CPlusPlus &&
15661
0
        LHS.get()->getObjectKind() != OK_ObjCProperty) {
15662
0
      VK = LHS.get()->getValueKind();
15663
0
      OK = LHS.get()->getObjectKind();
15664
0
    }
15665
0
    if (!ResultTy.isNull()) {
15666
0
      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15667
0
      DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15668
15669
      // Avoid copying a block to the heap if the block is assigned to a local
15670
      // auto variable that is declared in the same scope as the block. This
15671
      // optimization is unsafe if the local variable is declared in an outer
15672
      // scope. For example:
15673
      //
15674
      // BlockTy b;
15675
      // {
15676
      //   b = ^{...};
15677
      // }
15678
      // // It is unsafe to invoke the block here if it wasn't copied to the
15679
      // // heap.
15680
      // b();
15681
15682
0
      if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15683
0
        if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15684
0
          if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15685
0
            if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15686
0
              BE->getBlockDecl()->setCanAvoidCopyToHeap();
15687
15688
0
      if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15689
0
        checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15690
0
                              NTCUC_Assignment, NTCUK_Copy);
15691
0
    }
15692
0
    RecordModifiableNonNullParam(*this, LHS.get());
15693
0
    break;
15694
0
  case BO_PtrMemD:
15695
0
  case BO_PtrMemI:
15696
0
    ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15697
0
                                            Opc == BO_PtrMemI);
15698
0
    break;
15699
0
  case BO_Mul:
15700
0
  case BO_Div:
15701
0
    ConvertHalfVec = true;
15702
0
    ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15703
0
                                           Opc == BO_Div);
15704
0
    break;
15705
0
  case BO_Rem:
15706
0
    ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15707
0
    break;
15708
0
  case BO_Add:
15709
0
    ConvertHalfVec = true;
15710
0
    ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15711
0
    break;
15712
0
  case BO_Sub:
15713
0
    ConvertHalfVec = true;
15714
0
    ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15715
0
    break;
15716
0
  case BO_Shl:
15717
0
  case BO_Shr:
15718
0
    ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15719
0
    break;
15720
0
  case BO_LE:
15721
0
  case BO_LT:
15722
0
  case BO_GE:
15723
0
  case BO_GT:
15724
0
    ConvertHalfVec = true;
15725
0
    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15726
0
    break;
15727
0
  case BO_EQ:
15728
0
  case BO_NE:
15729
0
    ConvertHalfVec = true;
15730
0
    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15731
0
    break;
15732
0
  case BO_Cmp:
15733
0
    ConvertHalfVec = true;
15734
0
    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15735
0
    assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15736
0
    break;
15737
0
  case BO_And:
15738
0
    checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15739
0
    [[fallthrough]];
15740
0
  case BO_Xor:
15741
0
  case BO_Or:
15742
0
    ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15743
0
    break;
15744
0
  case BO_LAnd:
15745
0
  case BO_LOr:
15746
0
    ConvertHalfVec = true;
15747
0
    ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15748
0
    break;
15749
0
  case BO_MulAssign:
15750
0
  case BO_DivAssign:
15751
0
    ConvertHalfVec = true;
15752
0
    CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15753
0
                                               Opc == BO_DivAssign);
15754
0
    CompLHSTy = CompResultTy;
15755
0
    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15756
0
      ResultTy =
15757
0
          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15758
0
    break;
15759
0
  case BO_RemAssign:
15760
0
    CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15761
0
    CompLHSTy = CompResultTy;
15762
0
    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15763
0
      ResultTy =
15764
0
          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15765
0
    break;
15766
0
  case BO_AddAssign:
15767
0
    ConvertHalfVec = true;
15768
0
    CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15769
0
    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15770
0
      ResultTy =
15771
0
          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15772
0
    break;
15773
0
  case BO_SubAssign:
15774
0
    ConvertHalfVec = true;
15775
0
    CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15776
0
    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15777
0
      ResultTy =
15778
0
          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15779
0
    break;
15780
0
  case BO_ShlAssign:
15781
0
  case BO_ShrAssign:
15782
0
    CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15783
0
    CompLHSTy = CompResultTy;
15784
0
    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15785
0
      ResultTy =
15786
0
          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15787
0
    break;
15788
0
  case BO_AndAssign:
15789
0
  case BO_OrAssign: // fallthrough
15790
0
    DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15791
0
    [[fallthrough]];
15792
0
  case BO_XorAssign:
15793
0
    CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15794
0
    CompLHSTy = CompResultTy;
15795
0
    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15796
0
      ResultTy =
15797
0
          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15798
0
    break;
15799
0
  case BO_Comma:
15800
0
    ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15801
0
    if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15802
0
      VK = RHS.get()->getValueKind();
15803
0
      OK = RHS.get()->getObjectKind();
15804
0
    }
15805
0
    break;
15806
0
  }
15807
0
  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15808
0
    return ExprError();
15809
15810
  // Some of the binary operations require promoting operands of half vector to
15811
  // float vectors and truncating the result back to half vector. For now, we do
15812
  // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15813
  // arm64).
15814
0
  assert(
15815
0
      (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15816
0
                              isVector(LHS.get()->getType(), Context.HalfTy)) &&
15817
0
      "both sides are half vectors or neither sides are");
15818
0
  ConvertHalfVec =
15819
0
      needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15820
15821
  // Check for array bounds violations for both sides of the BinaryOperator
15822
0
  CheckArrayAccess(LHS.get());
15823
0
  CheckArrayAccess(RHS.get());
15824
15825
0
  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15826
0
    NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15827
0
                                                 &Context.Idents.get("object_setClass"),
15828
0
                                                 SourceLocation(), LookupOrdinaryName);
15829
0
    if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15830
0
      SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15831
0
      Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15832
0
          << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15833
0
                                        "object_setClass(")
15834
0
          << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15835
0
                                          ",")
15836
0
          << FixItHint::CreateInsertion(RHSLocEnd, ")");
15837
0
    }
15838
0
    else
15839
0
      Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15840
0
  }
15841
0
  else if (const ObjCIvarRefExpr *OIRE =
15842
0
           dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15843
0
    DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15844
15845
  // Opc is not a compound assignment if CompResultTy is null.
15846
0
  if (CompResultTy.isNull()) {
15847
0
    if (ConvertHalfVec)
15848
0
      return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15849
0
                                 OpLoc, CurFPFeatureOverrides());
15850
0
    return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15851
0
                                  VK, OK, OpLoc, CurFPFeatureOverrides());
15852
0
  }
15853
15854
  // Handle compound assignments.
15855
0
  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15856
0
      OK_ObjCProperty) {
15857
0
    VK = VK_LValue;
15858
0
    OK = LHS.get()->getObjectKind();
15859
0
  }
15860
15861
  // The LHS is not converted to the result type for fixed-point compound
15862
  // assignment as the common type is computed on demand. Reset the CompLHSTy
15863
  // to the LHS type we would have gotten after unary conversions.
15864
0
  if (CompResultTy->isFixedPointType())
15865
0
    CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15866
15867
0
  if (ConvertHalfVec)
15868
0
    return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15869
0
                               OpLoc, CurFPFeatureOverrides());
15870
15871
0
  return CompoundAssignOperator::Create(
15872
0
      Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15873
0
      CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15874
0
}
15875
15876
/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15877
/// operators are mixed in a way that suggests that the programmer forgot that
15878
/// comparison operators have higher precedence. The most typical example of
15879
/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15880
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15881
                                      SourceLocation OpLoc, Expr *LHSExpr,
15882
7
                                      Expr *RHSExpr) {
15883
7
  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15884
7
  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15885
15886
  // Check that one of the sides is a comparison operator and the other isn't.
15887
7
  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15888
7
  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15889
7
  if (isLeftComp == isRightComp)
15890
7
    return;
15891
15892
  // Bitwise operations are sometimes used as eager logical ops.
15893
  // Don't diagnose this.
15894
0
  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15895
0
  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15896
0
  if (isLeftBitwise || isRightBitwise)
15897
0
    return;
15898
15899
0
  SourceRange DiagRange = isLeftComp
15900
0
                              ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15901
0
                              : SourceRange(OpLoc, RHSExpr->getEndLoc());
15902
0
  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15903
0
  SourceRange ParensRange =
15904
0
      isLeftComp
15905
0
          ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15906
0
          : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15907
15908
0
  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15909
0
    << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15910
0
  SuggestParentheses(Self, OpLoc,
15911
0
    Self.PDiag(diag::note_precedence_silence) << OpStr,
15912
0
    (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15913
0
  SuggestParentheses(Self, OpLoc,
15914
0
    Self.PDiag(diag::note_precedence_bitwise_first)
15915
0
      << BinaryOperator::getOpcodeStr(Opc),
15916
0
    ParensRange);
15917
0
}
15918
15919
/// It accepts a '&&' expr that is inside a '||' one.
15920
/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15921
/// in parentheses.
15922
static void
15923
EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15924
0
                                       BinaryOperator *Bop) {
15925
0
  assert(Bop->getOpcode() == BO_LAnd);
15926
0
  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15927
0
      << Bop->getSourceRange() << OpLoc;
15928
0
  SuggestParentheses(Self, Bop->getOperatorLoc(),
15929
0
    Self.PDiag(diag::note_precedence_silence)
15930
0
      << Bop->getOpcodeStr(),
15931
0
    Bop->getSourceRange());
15932
0
}
15933
15934
/// Look for '&&' in the left hand of a '||' expr.
15935
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15936
0
                                             Expr *LHSExpr, Expr *RHSExpr) {
15937
0
  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15938
0
    if (Bop->getOpcode() == BO_LAnd) {
15939
      // If it's "string_literal && a || b" don't warn since the precedence
15940
      // doesn't matter.
15941
0
      if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15942
0
        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15943
0
    } else if (Bop->getOpcode() == BO_LOr) {
15944
0
      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15945
        // If it's "a || b && string_literal || c" we didn't warn earlier for
15946
        // "a || b && string_literal", but warn now.
15947
0
        if (RBop->getOpcode() == BO_LAnd &&
15948
0
            isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15949
0
          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15950
0
      }
15951
0
    }
15952
0
  }
15953
0
}
15954
15955
/// Look for '&&' in the right hand of a '||' expr.
15956
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15957
0
                                             Expr *LHSExpr, Expr *RHSExpr) {
15958
0
  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15959
0
    if (Bop->getOpcode() == BO_LAnd) {
15960
      // If it's "a || b && string_literal" don't warn since the precedence
15961
      // doesn't matter.
15962
0
      if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15963
0
        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15964
0
    }
15965
0
  }
15966
0
}
15967
15968
/// Look for bitwise op in the left or right hand of a bitwise op with
15969
/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15970
/// the '&' expression in parentheses.
15971
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15972
10
                                         SourceLocation OpLoc, Expr *SubExpr) {
15973
10
  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15974
1
    if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15975
0
      S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15976
0
        << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15977
0
        << Bop->getSourceRange() << OpLoc;
15978
0
      SuggestParentheses(S, Bop->getOperatorLoc(),
15979
0
        S.PDiag(diag::note_precedence_silence)
15980
0
          << Bop->getOpcodeStr(),
15981
0
        Bop->getSourceRange());
15982
0
    }
15983
1
  }
15984
10
}
15985
15986
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15987
0
                                    Expr *SubExpr, StringRef Shift) {
15988
0
  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15989
0
    if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15990
0
      StringRef Op = Bop->getOpcodeStr();
15991
0
      S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15992
0
          << Bop->getSourceRange() << OpLoc << Shift << Op;
15993
0
      SuggestParentheses(S, Bop->getOperatorLoc(),
15994
0
          S.PDiag(diag::note_precedence_silence) << Op,
15995
0
          Bop->getSourceRange());
15996
0
    }
15997
0
  }
15998
0
}
15999
16000
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16001
9
                                 Expr *LHSExpr, Expr *RHSExpr) {
16002
9
  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
16003
9
  if (!OCE)
16004
9
    return;
16005
16006
0
  FunctionDecl *FD = OCE->getDirectCallee();
16007
0
  if (!FD || !FD->isOverloadedOperator())
16008
0
    return;
16009
16010
0
  OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16011
0
  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16012
0
    return;
16013
16014
0
  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
16015
0
      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16016
0
      << (Kind == OO_LessLess);
16017
0
  SuggestParentheses(S, OCE->getOperatorLoc(),
16018
0
                     S.PDiag(diag::note_precedence_silence)
16019
0
                         << (Kind == OO_LessLess ? "<<" : ">>"),
16020
0
                     OCE->getSourceRange());
16021
0
  SuggestParentheses(
16022
0
      S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
16023
0
      SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
16024
0
}
16025
16026
/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16027
/// precedence.
16028
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16029
                                    SourceLocation OpLoc, Expr *LHSExpr,
16030
26
                                    Expr *RHSExpr){
16031
  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16032
26
  if (BinaryOperator::isBitwiseOp(Opc))
16033
7
    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16034
16035
  // Diagnose "arg1 & arg2 | arg3"
16036
26
  if ((Opc == BO_Or || Opc == BO_Xor) &&
16037
26
      !OpLoc.isMacroID()/* Don't warn in macros. */) {
16038
5
    DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
16039
5
    DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
16040
5
  }
16041
16042
  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16043
  // We don't warn for 'assert(a || b && "bad")' since this is safe.
16044
26
  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16045
0
    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
16046
0
    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
16047
0
  }
16048
16049
26
  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
16050
26
      || Opc == BO_Shr) {
16051
0
    StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
16052
0
    DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
16053
0
    DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16054
0
  }
16055
16056
  // Warn on overloaded shift operators and comparisons, such as:
16057
  // cout << 5 == 4;
16058
26
  if (BinaryOperator::isComparisonOp(Opc))
16059
9
    DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16060
26
}
16061
16062
// Binary Operators.  'Tok' is the token for the operator.
16063
ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16064
                            tok::TokenKind Kind,
16065
26
                            Expr *LHSExpr, Expr *RHSExpr) {
16066
26
  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16067
26
  assert(LHSExpr && "ActOnBinOp(): missing left expression");
16068
0
  assert(RHSExpr && "ActOnBinOp(): missing right expression");
16069
16070
  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16071
0
  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16072
16073
26
  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16074
26
}
16075
16076
void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16077
23
                       UnresolvedSetImpl &Functions) {
16078
23
  OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16079
23
  if (OverOp != OO_None && OverOp != OO_Equal)
16080
17
    LookupOverloadedOperatorName(OverOp, S, Functions);
16081
16082
  // In C++20 onwards, we may have a second operator to look up.
16083
23
  if (getLangOpts().CPlusPlus20) {
16084
0
    if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
16085
0
      LookupOverloadedOperatorName(ExtraOp, S, Functions);
16086
0
  }
16087
23
}
16088
16089
/// Build an overloaded binary operator expression in the given scope.
16090
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16091
                                       BinaryOperatorKind Opc,
16092
23
                                       Expr *LHS, Expr *RHS) {
16093
23
  switch (Opc) {
16094
6
  case BO_Assign:
16095
    // In the non-overloaded case, we warn about self-assignment (x = x) for
16096
    // both simple assignment and certain compound assignments where algebra
16097
    // tells us the operation yields a constant result.  When the operator is
16098
    // overloaded, we can't do the latter because we don't want to assume that
16099
    // those algebraic identities still apply; for example, a path-building
16100
    // library might use operator/= to append paths.  But it's still reasonable
16101
    // to assume that simple assignment is just moving/copying values around
16102
    // and so self-assignment is likely a bug.
16103
6
    DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16104
6
    [[fallthrough]];
16105
6
  case BO_DivAssign:
16106
6
  case BO_RemAssign:
16107
6
  case BO_SubAssign:
16108
6
  case BO_AndAssign:
16109
6
  case BO_OrAssign:
16110
6
  case BO_XorAssign:
16111
6
    CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16112
6
    break;
16113
17
  default:
16114
17
    break;
16115
23
  }
16116
16117
  // Find all of the overloaded operators visible from this point.
16118
23
  UnresolvedSet<16> Functions;
16119
23
  S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16120
16121
  // Build the (potentially-overloaded, potentially-dependent)
16122
  // binary operation.
16123
23
  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16124
23
}
16125
16126
ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16127
                            BinaryOperatorKind Opc,
16128
26
                            Expr *LHSExpr, Expr *RHSExpr) {
16129
26
  ExprResult LHS, RHS;
16130
26
  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
16131
26
  if (!LHS.isUsable() || !RHS.isUsable())
16132
0
    return ExprError();
16133
26
  LHSExpr = LHS.get();
16134
26
  RHSExpr = RHS.get();
16135
16136
  // We want to end up calling one of checkPseudoObjectAssignment
16137
  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16138
  // both expressions are overloadable or either is type-dependent),
16139
  // or CreateBuiltinBinOp (in any other case).  We also want to get
16140
  // any placeholder types out of the way.
16141
16142
  // Handle pseudo-objects in the LHS.
16143
26
  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16144
    // Assignments with a pseudo-object l-value need special analysis.
16145
0
    if (pty->getKind() == BuiltinType::PseudoObject &&
16146
0
        BinaryOperator::isAssignmentOp(Opc))
16147
0
      return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16148
16149
    // Don't resolve overloads if the other type is overloadable.
16150
0
    if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16151
      // We can't actually test that if we still have a placeholder,
16152
      // though.  Fortunately, none of the exceptions we see in that
16153
      // code below are valid when the LHS is an overload set.  Note
16154
      // that an overload set can be dependently-typed, but it never
16155
      // instantiates to having an overloadable type.
16156
0
      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16157
0
      if (resolvedRHS.isInvalid()) return ExprError();
16158
0
      RHSExpr = resolvedRHS.get();
16159
16160
0
      if (RHSExpr->isTypeDependent() ||
16161
0
          RHSExpr->getType()->isOverloadableType())
16162
0
        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16163
0
    }
16164
16165
    // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16166
    // template, diagnose the missing 'template' keyword instead of diagnosing
16167
    // an invalid use of a bound member function.
16168
    //
16169
    // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16170
    // to C++1z [over.over]/1.4, but we already checked for that case above.
16171
0
    if (Opc == BO_LT && inTemplateInstantiation() &&
16172
0
        (pty->getKind() == BuiltinType::BoundMember ||
16173
0
         pty->getKind() == BuiltinType::Overload)) {
16174
0
      auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16175
0
      if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16176
0
          llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16177
0
            return isa<FunctionTemplateDecl>(ND);
16178
0
          })) {
16179
0
        Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16180
0
                                : OE->getNameLoc(),
16181
0
             diag::err_template_kw_missing)
16182
0
          << OE->getName().getAsString() << "";
16183
0
        return ExprError();
16184
0
      }
16185
0
    }
16186
16187
0
    ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16188
0
    if (LHS.isInvalid()) return ExprError();
16189
0
    LHSExpr = LHS.get();
16190
0
  }
16191
16192
  // Handle pseudo-objects in the RHS.
16193
26
  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16194
    // An overload in the RHS can potentially be resolved by the type
16195
    // being assigned to.
16196
0
    if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16197
0
      if (getLangOpts().CPlusPlus &&
16198
0
          (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16199
0
           LHSExpr->getType()->isOverloadableType()))
16200
0
        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16201
16202
0
      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16203
0
    }
16204
16205
    // Don't resolve overloads if the other type is overloadable.
16206
0
    if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16207
0
        LHSExpr->getType()->isOverloadableType())
16208
0
      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16209
16210
0
    ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16211
0
    if (!resolvedRHS.isUsable()) return ExprError();
16212
0
    RHSExpr = resolvedRHS.get();
16213
0
  }
16214
16215
26
  if (getLangOpts().CPlusPlus) {
16216
    // If either expression is type-dependent, always build an
16217
    // overloaded op.
16218
23
    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
16219
23
      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16220
16221
    // Otherwise, build an overloaded op if either expression has an
16222
    // overloadable type.
16223
0
    if (LHSExpr->getType()->isOverloadableType() ||
16224
0
        RHSExpr->getType()->isOverloadableType())
16225
0
      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16226
0
  }
16227
16228
3
  if (getLangOpts().RecoveryAST &&
16229
3
      (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16230
3
    assert(!getLangOpts().CPlusPlus);
16231
0
    assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16232
3
           "Should only occur in error-recovery path.");
16233
3
    if (BinaryOperator::isCompoundAssignmentOp(Opc))
16234
      // C [6.15.16] p3:
16235
      // An assignment expression has the value of the left operand after the
16236
      // assignment, but is not an lvalue.
16237
0
      return CompoundAssignOperator::Create(
16238
0
          Context, LHSExpr, RHSExpr, Opc,
16239
0
          LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
16240
0
          OpLoc, CurFPFeatureOverrides());
16241
3
    QualType ResultType;
16242
3
    switch (Opc) {
16243
0
    case BO_Assign:
16244
0
      ResultType = LHSExpr->getType().getUnqualifiedType();
16245
0
      break;
16246
0
    case BO_LT:
16247
0
    case BO_GT:
16248
0
    case BO_LE:
16249
0
    case BO_GE:
16250
0
    case BO_EQ:
16251
0
    case BO_NE:
16252
0
    case BO_LAnd:
16253
0
    case BO_LOr:
16254
      // These operators have a fixed result type regardless of operands.
16255
0
      ResultType = Context.IntTy;
16256
0
      break;
16257
0
    case BO_Comma:
16258
0
      ResultType = RHSExpr->getType();
16259
0
      break;
16260
3
    default:
16261
3
      ResultType = Context.DependentTy;
16262
3
      break;
16263
3
    }
16264
3
    return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16265
3
                                  VK_PRValue, OK_Ordinary, OpLoc,
16266
3
                                  CurFPFeatureOverrides());
16267
3
  }
16268
16269
  // Build a built-in binary operation.
16270
0
  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16271
3
}
16272
16273
2
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16274
2
  if (T.isNull() || T->isDependentType())
16275
0
    return false;
16276
16277
2
  if (!Ctx.isPromotableIntegerType(T))
16278
2
    return true;
16279
16280
0
  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16281
2
}
16282
16283
ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16284
                                      UnaryOperatorKind Opc, Expr *InputExpr,
16285
5
                                      bool IsAfterAmp) {
16286
5
  ExprResult Input = InputExpr;
16287
5
  ExprValueKind VK = VK_PRValue;
16288
5
  ExprObjectKind OK = OK_Ordinary;
16289
5
  QualType resultType;
16290
5
  bool CanOverflow = false;
16291
16292
5
  bool ConvertHalfVec = false;
16293
5
  if (getLangOpts().OpenCL) {
16294
0
    QualType Ty = InputExpr->getType();
16295
    // The only legal unary operation for atomics is '&'.
16296
0
    if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16297
    // OpenCL special types - image, sampler, pipe, and blocks are to be used
16298
    // only with a builtin functions and therefore should be disallowed here.
16299
0
        (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16300
0
        || Ty->isBlockPointerType())) {
16301
0
      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16302
0
                       << InputExpr->getType()
16303
0
                       << Input.get()->getSourceRange());
16304
0
    }
16305
0
  }
16306
16307
5
  if (getLangOpts().HLSL && OpLoc.isValid()) {
16308
0
    if (Opc == UO_AddrOf)
16309
0
      return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16310
0
    if (Opc == UO_Deref)
16311
0
      return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16312
0
  }
16313
16314
5
  switch (Opc) {
16315
0
  case UO_PreInc:
16316
0
  case UO_PreDec:
16317
0
  case UO_PostInc:
16318
0
  case UO_PostDec:
16319
0
    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
16320
0
                                                OpLoc,
16321
0
                                                Opc == UO_PreInc ||
16322
0
                                                Opc == UO_PostInc,
16323
0
                                                Opc == UO_PreInc ||
16324
0
                                                Opc == UO_PreDec);
16325
0
    CanOverflow = isOverflowingIntegerType(Context, resultType);
16326
0
    break;
16327
0
  case UO_AddrOf:
16328
0
    resultType = CheckAddressOfOperand(Input, OpLoc);
16329
0
    CheckAddressOfNoDeref(InputExpr);
16330
0
    RecordModifiableNonNullParam(*this, InputExpr);
16331
0
    break;
16332
1
  case UO_Deref: {
16333
1
    Input = DefaultFunctionArrayLvalueConversion(Input.get());
16334
1
    if (Input.isInvalid()) return ExprError();
16335
1
    resultType =
16336
1
        CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16337
1
    break;
16338
1
  }
16339
0
  case UO_Plus:
16340
2
  case UO_Minus:
16341
2
    CanOverflow = Opc == UO_Minus &&
16342
2
                  isOverflowingIntegerType(Context, Input.get()->getType());
16343
2
    Input = UsualUnaryConversions(Input.get());
16344
2
    if (Input.isInvalid()) return ExprError();
16345
    // Unary plus and minus require promoting an operand of half vector to a
16346
    // float vector and truncating the result back to a half vector. For now, we
16347
    // do this only when HalfArgsAndReturns is set (that is, when the target is
16348
    // arm or arm64).
16349
2
    ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16350
16351
    // If the operand is a half vector, promote it to a float vector.
16352
2
    if (ConvertHalfVec)
16353
0
      Input = convertVector(Input.get(), Context.FloatTy, *this);
16354
2
    resultType = Input.get()->getType();
16355
2
    if (resultType->isDependentType())
16356
0
      break;
16357
2
    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16358
2
      break;
16359
0
    else if (resultType->isVectorType() &&
16360
             // The z vector extensions don't allow + or - with bool vectors.
16361
0
             (!Context.getLangOpts().ZVector ||
16362
0
              resultType->castAs<VectorType>()->getVectorKind() !=
16363
0
                  VectorKind::AltiVecBool))
16364
0
      break;
16365
0
    else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16366
0
      break;
16367
0
    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16368
0
             Opc == UO_Plus &&
16369
0
             resultType->isPointerType())
16370
0
      break;
16371
16372
0
    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16373
0
      << resultType << Input.get()->getSourceRange());
16374
16375
0
  case UO_Not: // bitwise complement
16376
0
    Input = UsualUnaryConversions(Input.get());
16377
0
    if (Input.isInvalid())
16378
0
      return ExprError();
16379
0
    resultType = Input.get()->getType();
16380
0
    if (resultType->isDependentType())
16381
0
      break;
16382
    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16383
0
    if (resultType->isComplexType() || resultType->isComplexIntegerType())
16384
      // C99 does not support '~' for complex conjugation.
16385
0
      Diag(OpLoc, diag::ext_integer_complement_complex)
16386
0
          << resultType << Input.get()->getSourceRange();
16387
0
    else if (resultType->hasIntegerRepresentation())
16388
0
      break;
16389
0
    else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16390
      // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16391
      // on vector float types.
16392
0
      QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16393
0
      if (!T->isIntegerType())
16394
0
        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16395
0
                          << resultType << Input.get()->getSourceRange());
16396
0
    } else {
16397
0
      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16398
0
                       << resultType << Input.get()->getSourceRange());
16399
0
    }
16400
0
    break;
16401
16402
2
  case UO_LNot: // logical negation
16403
    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16404
2
    Input = DefaultFunctionArrayLvalueConversion(Input.get());
16405
2
    if (Input.isInvalid()) return ExprError();
16406
2
    resultType = Input.get()->getType();
16407
16408
    // Though we still have to promote half FP to float...
16409
2
    if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16410
0
      Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
16411
0
      resultType = Context.FloatTy;
16412
0
    }
16413
16414
    // WebAsembly tables can't be used in unary expressions.
16415
2
    if (resultType->isPointerType() &&
16416
2
        resultType->getPointeeType().isWebAssemblyReferenceType()) {
16417
0
      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16418
0
                       << resultType << Input.get()->getSourceRange());
16419
0
    }
16420
16421
2
    if (resultType->isDependentType())
16422
2
      break;
16423
0
    if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16424
      // C99 6.5.3.3p1: ok, fallthrough;
16425
0
      if (Context.getLangOpts().CPlusPlus) {
16426
        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16427
        // operand contextually converted to bool.
16428
0
        Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16429
0
                                  ScalarTypeToBooleanCastKind(resultType));
16430
0
      } else if (Context.getLangOpts().OpenCL &&
16431
0
                 Context.getLangOpts().OpenCLVersion < 120) {
16432
        // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16433
        // operate on scalar float types.
16434
0
        if (!resultType->isIntegerType() && !resultType->isPointerType())
16435
0
          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16436
0
                           << resultType << Input.get()->getSourceRange());
16437
0
      }
16438
0
    } else if (resultType->isExtVectorType()) {
16439
0
      if (Context.getLangOpts().OpenCL &&
16440
0
          Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16441
        // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16442
        // operate on vector float types.
16443
0
        QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16444
0
        if (!T->isIntegerType())
16445
0
          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16446
0
                           << resultType << Input.get()->getSourceRange());
16447
0
      }
16448
      // Vector logical not returns the signed variant of the operand type.
16449
0
      resultType = GetSignedVectorType(resultType);
16450
0
      break;
16451
0
    } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16452
0
      const VectorType *VTy = resultType->castAs<VectorType>();
16453
0
      if (VTy->getVectorKind() != VectorKind::Generic)
16454
0
        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16455
0
                         << resultType << Input.get()->getSourceRange());
16456
16457
      // Vector logical not returns the signed variant of the operand type.
16458
0
      resultType = GetSignedVectorType(resultType);
16459
0
      break;
16460
0
    } else {
16461
0
      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16462
0
        << resultType << Input.get()->getSourceRange());
16463
0
    }
16464
16465
    // LNot always has type int. C99 6.5.3.3p5.
16466
    // In C++, it's bool. C++ 5.3.1p8
16467
0
    resultType = Context.getLogicalOperationType();
16468
0
    break;
16469
0
  case UO_Real:
16470
0
  case UO_Imag:
16471
0
    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16472
    // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16473
    // complex l-values to ordinary l-values and all other values to r-values.
16474
0
    if (Input.isInvalid()) return ExprError();
16475
0
    if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16476
0
      if (Input.get()->isGLValue() &&
16477
0
          Input.get()->getObjectKind() == OK_Ordinary)
16478
0
        VK = Input.get()->getValueKind();
16479
0
    } else if (!getLangOpts().CPlusPlus) {
16480
      // In C, a volatile scalar is read by __imag. In C++, it is not.
16481
0
      Input = DefaultLvalueConversion(Input.get());
16482
0
    }
16483
0
    break;
16484
0
  case UO_Extension:
16485
0
    resultType = Input.get()->getType();
16486
0
    VK = Input.get()->getValueKind();
16487
0
    OK = Input.get()->getObjectKind();
16488
0
    break;
16489
0
  case UO_Coawait:
16490
    // It's unnecessary to represent the pass-through operator co_await in the
16491
    // AST; just return the input expression instead.
16492
0
    assert(!Input.get()->getType()->isDependentType() &&
16493
0
                   "the co_await expression must be non-dependant before "
16494
0
                   "building operator co_await");
16495
0
    return Input;
16496
5
  }
16497
5
  if (resultType.isNull() || Input.isInvalid())
16498
0
    return ExprError();
16499
16500
  // Check for array bounds violations in the operand of the UnaryOperator,
16501
  // except for the '*' and '&' operators that have to be handled specially
16502
  // by CheckArrayAccess (as there are special cases like &array[arraysize]
16503
  // that are explicitly defined as valid by the standard).
16504
5
  if (Opc != UO_AddrOf && Opc != UO_Deref)
16505
4
    CheckArrayAccess(Input.get());
16506
16507
5
  auto *UO =
16508
5
      UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16509
5
                            OpLoc, CanOverflow, CurFPFeatureOverrides());
16510
16511
5
  if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16512
5
      !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16513
5
      !isUnevaluatedContext())
16514
0
    ExprEvalContexts.back().PossibleDerefs.insert(UO);
16515
16516
  // Convert the result back to a half vector.
16517
5
  if (ConvertHalfVec)
16518
0
    return convertVector(UO, Context.HalfTy, *this);
16519
5
  return UO;
16520
5
}
16521
16522
/// Determine whether the given expression is a qualified member
16523
/// access expression, of a form that could be turned into a pointer to member
16524
/// with the address-of operator.
16525
1
bool Sema::isQualifiedMemberAccess(Expr *E) {
16526
1
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16527
0
    if (!DRE->getQualifier())
16528
0
      return false;
16529
16530
0
    ValueDecl *VD = DRE->getDecl();
16531
0
    if (!VD->isCXXClassMember())
16532
0
      return false;
16533
16534
0
    if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16535
0
      return true;
16536
0
    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16537
0
      return Method->isImplicitObjectMemberFunction();
16538
16539
0
    return false;
16540
0
  }
16541
16542
1
  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16543
0
    if (!ULE->getQualifier())
16544
0
      return false;
16545
16546
0
    for (NamedDecl *D : ULE->decls()) {
16547
0
      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16548
0
        if (Method->isImplicitObjectMemberFunction())
16549
0
          return true;
16550
0
      } else {
16551
        // Overload set does not contain methods.
16552
0
        break;
16553
0
      }
16554
0
    }
16555
16556
0
    return false;
16557
0
  }
16558
16559
1
  return false;
16560
1
}
16561
16562
ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16563
                              UnaryOperatorKind Opc, Expr *Input,
16564
11
                              bool IsAfterAmp) {
16565
  // First things first: handle placeholders so that the
16566
  // overloaded-operator check considers the right type.
16567
11
  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16568
    // Increment and decrement of pseudo-object references.
16569
0
    if (pty->getKind() == BuiltinType::PseudoObject &&
16570
0
        UnaryOperator::isIncrementDecrementOp(Opc))
16571
0
      return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16572
16573
    // extension is always a builtin operator.
16574
0
    if (Opc == UO_Extension)
16575
0
      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16576
16577
    // & gets special logic for several kinds of placeholder.
16578
    // The builtin code knows what to do.
16579
0
    if (Opc == UO_AddrOf &&
16580
0
        (pty->getKind() == BuiltinType::Overload ||
16581
0
         pty->getKind() == BuiltinType::UnknownAny ||
16582
0
         pty->getKind() == BuiltinType::BoundMember))
16583
0
      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16584
16585
    // Anything else needs to be handled now.
16586
0
    ExprResult Result = CheckPlaceholderExpr(Input);
16587
0
    if (Result.isInvalid()) return ExprError();
16588
0
    Input = Result.get();
16589
0
  }
16590
16591
11
  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16592
11
      UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16593
11
      !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16594
    // Find all of the overloaded operators visible from this point.
16595
6
    UnresolvedSet<16> Functions;
16596
6
    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16597
6
    if (S && OverOp != OO_None)
16598
6
      LookupOverloadedOperatorName(OverOp, S, Functions);
16599
16600
6
    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16601
6
  }
16602
16603
5
  return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16604
11
}
16605
16606
// Unary Operators.  'Tok' is the token for the operator.
16607
ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16608
11
                              Expr *Input, bool IsAfterAmp) {
16609
11
  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16610
11
                      IsAfterAmp);
16611
11
}
16612
16613
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16614
ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16615
0
                                LabelDecl *TheDecl) {
16616
0
  TheDecl->markUsed(Context);
16617
  // Create the AST node.  The address of a label always has type 'void*'.
16618
0
  auto *Res = new (Context) AddrLabelExpr(
16619
0
      OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16620
16621
0
  if (getCurFunction())
16622
0
    getCurFunction()->AddrLabels.push_back(Res);
16623
16624
0
  return Res;
16625
0
}
16626
16627
0
void Sema::ActOnStartStmtExpr() {
16628
0
  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16629
  // Make sure we diagnose jumping into a statement expression.
16630
0
  setFunctionHasBranchProtectedScope();
16631
0
}
16632
16633
0
void Sema::ActOnStmtExprError() {
16634
  // Note that function is also called by TreeTransform when leaving a
16635
  // StmtExpr scope without rebuilding anything.
16636
16637
0
  DiscardCleanupsInEvaluationContext();
16638
0
  PopExpressionEvaluationContext();
16639
0
}
16640
16641
ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16642
0
                               SourceLocation RPLoc) {
16643
0
  return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16644
0
}
16645
16646
ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16647
0
                               SourceLocation RPLoc, unsigned TemplateDepth) {
16648
0
  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16649
0
  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16650
16651
0
  if (hasAnyUnrecoverableErrorsInThisFunction())
16652
0
    DiscardCleanupsInEvaluationContext();
16653
0
  assert(!Cleanup.exprNeedsCleanups() &&
16654
0
         "cleanups within StmtExpr not correctly bound!");
16655
0
  PopExpressionEvaluationContext();
16656
16657
  // FIXME: there are a variety of strange constraints to enforce here, for
16658
  // example, it is not possible to goto into a stmt expression apparently.
16659
  // More semantic analysis is needed.
16660
16661
  // If there are sub-stmts in the compound stmt, take the type of the last one
16662
  // as the type of the stmtexpr.
16663
0
  QualType Ty = Context.VoidTy;
16664
0
  bool StmtExprMayBindToTemp = false;
16665
0
  if (!Compound->body_empty()) {
16666
    // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16667
0
    if (const auto *LastStmt =
16668
0
            dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16669
0
      if (const Expr *Value = LastStmt->getExprStmt()) {
16670
0
        StmtExprMayBindToTemp = true;
16671
0
        Ty = Value->getType();
16672
0
      }
16673
0
    }
16674
0
  }
16675
16676
  // FIXME: Check that expression type is complete/non-abstract; statement
16677
  // expressions are not lvalues.
16678
0
  Expr *ResStmtExpr =
16679
0
      new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16680
0
  if (StmtExprMayBindToTemp)
16681
0
    return MaybeBindToTemporary(ResStmtExpr);
16682
0
  return ResStmtExpr;
16683
0
}
16684
16685
0
ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16686
0
  if (ER.isInvalid())
16687
0
    return ExprError();
16688
16689
  // Do function/array conversion on the last expression, but not
16690
  // lvalue-to-rvalue.  However, initialize an unqualified type.
16691
0
  ER = DefaultFunctionArrayConversion(ER.get());
16692
0
  if (ER.isInvalid())
16693
0
    return ExprError();
16694
0
  Expr *E = ER.get();
16695
16696
0
  if (E->isTypeDependent())
16697
0
    return E;
16698
16699
  // In ARC, if the final expression ends in a consume, splice
16700
  // the consume out and bind it later.  In the alternate case
16701
  // (when dealing with a retainable type), the result
16702
  // initialization will create a produce.  In both cases the
16703
  // result will be +1, and we'll need to balance that out with
16704
  // a bind.
16705
0
  auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16706
0
  if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16707
0
    return Cast->getSubExpr();
16708
16709
  // FIXME: Provide a better location for the initialization.
16710
0
  return PerformCopyInitialization(
16711
0
      InitializedEntity::InitializeStmtExprResult(
16712
0
          E->getBeginLoc(), E->getType().getUnqualifiedType()),
16713
0
      SourceLocation(), E);
16714
0
}
16715
16716
ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16717
                                      TypeSourceInfo *TInfo,
16718
                                      ArrayRef<OffsetOfComponent> Components,
16719
0
                                      SourceLocation RParenLoc) {
16720
0
  QualType ArgTy = TInfo->getType();
16721
0
  bool Dependent = ArgTy->isDependentType();
16722
0
  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16723
16724
  // We must have at least one component that refers to the type, and the first
16725
  // one is known to be a field designator.  Verify that the ArgTy represents
16726
  // a struct/union/class.
16727
0
  if (!Dependent && !ArgTy->isRecordType())
16728
0
    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16729
0
                       << ArgTy << TypeRange);
16730
16731
  // Type must be complete per C99 7.17p3 because a declaring a variable
16732
  // with an incomplete type would be ill-formed.
16733
0
  if (!Dependent
16734
0
      && RequireCompleteType(BuiltinLoc, ArgTy,
16735
0
                             diag::err_offsetof_incomplete_type, TypeRange))
16736
0
    return ExprError();
16737
16738
0
  bool DidWarnAboutNonPOD = false;
16739
0
  QualType CurrentType = ArgTy;
16740
0
  SmallVector<OffsetOfNode, 4> Comps;
16741
0
  SmallVector<Expr*, 4> Exprs;
16742
0
  for (const OffsetOfComponent &OC : Components) {
16743
0
    if (OC.isBrackets) {
16744
      // Offset of an array sub-field.  TODO: Should we allow vector elements?
16745
0
      if (!CurrentType->isDependentType()) {
16746
0
        const ArrayType *AT = Context.getAsArrayType(CurrentType);
16747
0
        if(!AT)
16748
0
          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16749
0
                           << CurrentType);
16750
0
        CurrentType = AT->getElementType();
16751
0
      } else
16752
0
        CurrentType = Context.DependentTy;
16753
16754
0
      ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16755
0
      if (IdxRval.isInvalid())
16756
0
        return ExprError();
16757
0
      Expr *Idx = IdxRval.get();
16758
16759
      // The expression must be an integral expression.
16760
      // FIXME: An integral constant expression?
16761
0
      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16762
0
          !Idx->getType()->isIntegerType())
16763
0
        return ExprError(
16764
0
            Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16765
0
            << Idx->getSourceRange());
16766
16767
      // Record this array index.
16768
0
      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16769
0
      Exprs.push_back(Idx);
16770
0
      continue;
16771
0
    }
16772
16773
    // Offset of a field.
16774
0
    if (CurrentType->isDependentType()) {
16775
      // We have the offset of a field, but we can't look into the dependent
16776
      // type. Just record the identifier of the field.
16777
0
      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16778
0
      CurrentType = Context.DependentTy;
16779
0
      continue;
16780
0
    }
16781
16782
    // We need to have a complete type to look into.
16783
0
    if (RequireCompleteType(OC.LocStart, CurrentType,
16784
0
                            diag::err_offsetof_incomplete_type))
16785
0
      return ExprError();
16786
16787
    // Look for the designated field.
16788
0
    const RecordType *RC = CurrentType->getAs<RecordType>();
16789
0
    if (!RC)
16790
0
      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16791
0
                       << CurrentType);
16792
0
    RecordDecl *RD = RC->getDecl();
16793
16794
    // C++ [lib.support.types]p5:
16795
    //   The macro offsetof accepts a restricted set of type arguments in this
16796
    //   International Standard. type shall be a POD structure or a POD union
16797
    //   (clause 9).
16798
    // C++11 [support.types]p4:
16799
    //   If type is not a standard-layout class (Clause 9), the results are
16800
    //   undefined.
16801
0
    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16802
0
      bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16803
0
      unsigned DiagID =
16804
0
        LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16805
0
                            : diag::ext_offsetof_non_pod_type;
16806
16807
0
      if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16808
0
        Diag(BuiltinLoc, DiagID)
16809
0
            << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16810
0
        DidWarnAboutNonPOD = true;
16811
0
      }
16812
0
    }
16813
16814
    // Look for the field.
16815
0
    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16816
0
    LookupQualifiedName(R, RD);
16817
0
    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16818
0
    IndirectFieldDecl *IndirectMemberDecl = nullptr;
16819
0
    if (!MemberDecl) {
16820
0
      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16821
0
        MemberDecl = IndirectMemberDecl->getAnonField();
16822
0
    }
16823
16824
0
    if (!MemberDecl) {
16825
      // Lookup could be ambiguous when looking up a placeholder variable
16826
      // __builtin_offsetof(S, _).
16827
      // In that case we would already have emitted a diagnostic
16828
0
      if (!R.isAmbiguous())
16829
0
        Diag(BuiltinLoc, diag::err_no_member)
16830
0
            << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16831
0
      return ExprError();
16832
0
    }
16833
16834
    // C99 7.17p3:
16835
    //   (If the specified member is a bit-field, the behavior is undefined.)
16836
    //
16837
    // We diagnose this as an error.
16838
0
    if (MemberDecl->isBitField()) {
16839
0
      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16840
0
        << MemberDecl->getDeclName()
16841
0
        << SourceRange(BuiltinLoc, RParenLoc);
16842
0
      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16843
0
      return ExprError();
16844
0
    }
16845
16846
0
    RecordDecl *Parent = MemberDecl->getParent();
16847
0
    if (IndirectMemberDecl)
16848
0
      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16849
16850
    // If the member was found in a base class, introduce OffsetOfNodes for
16851
    // the base class indirections.
16852
0
    CXXBasePaths Paths;
16853
0
    if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16854
0
                      Paths)) {
16855
0
      if (Paths.getDetectedVirtual()) {
16856
0
        Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16857
0
          << MemberDecl->getDeclName()
16858
0
          << SourceRange(BuiltinLoc, RParenLoc);
16859
0
        return ExprError();
16860
0
      }
16861
16862
0
      CXXBasePath &Path = Paths.front();
16863
0
      for (const CXXBasePathElement &B : Path)
16864
0
        Comps.push_back(OffsetOfNode(B.Base));
16865
0
    }
16866
16867
0
    if (IndirectMemberDecl) {
16868
0
      for (auto *FI : IndirectMemberDecl->chain()) {
16869
0
        assert(isa<FieldDecl>(FI));
16870
0
        Comps.push_back(OffsetOfNode(OC.LocStart,
16871
0
                                     cast<FieldDecl>(FI), OC.LocEnd));
16872
0
      }
16873
0
    } else
16874
0
      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16875
16876
0
    CurrentType = MemberDecl->getType().getNonReferenceType();
16877
0
  }
16878
16879
0
  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16880
0
                              Comps, Exprs, RParenLoc);
16881
0
}
16882
16883
ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16884
                                      SourceLocation BuiltinLoc,
16885
                                      SourceLocation TypeLoc,
16886
                                      ParsedType ParsedArgTy,
16887
                                      ArrayRef<OffsetOfComponent> Components,
16888
0
                                      SourceLocation RParenLoc) {
16889
16890
0
  TypeSourceInfo *ArgTInfo;
16891
0
  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16892
0
  if (ArgTy.isNull())
16893
0
    return ExprError();
16894
16895
0
  if (!ArgTInfo)
16896
0
    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16897
16898
0
  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16899
0
}
16900
16901
16902
ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16903
                                 Expr *CondExpr,
16904
                                 Expr *LHSExpr, Expr *RHSExpr,
16905
0
                                 SourceLocation RPLoc) {
16906
0
  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16907
16908
0
  ExprValueKind VK = VK_PRValue;
16909
0
  ExprObjectKind OK = OK_Ordinary;
16910
0
  QualType resType;
16911
0
  bool CondIsTrue = false;
16912
0
  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16913
0
    resType = Context.DependentTy;
16914
0
  } else {
16915
    // The conditional expression is required to be a constant expression.
16916
0
    llvm::APSInt condEval(32);
16917
0
    ExprResult CondICE = VerifyIntegerConstantExpression(
16918
0
        CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16919
0
    if (CondICE.isInvalid())
16920
0
      return ExprError();
16921
0
    CondExpr = CondICE.get();
16922
0
    CondIsTrue = condEval.getZExtValue();
16923
16924
    // If the condition is > zero, then the AST type is the same as the LHSExpr.
16925
0
    Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16926
16927
0
    resType = ActiveExpr->getType();
16928
0
    VK = ActiveExpr->getValueKind();
16929
0
    OK = ActiveExpr->getObjectKind();
16930
0
  }
16931
16932
0
  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16933
0
                                  resType, VK, OK, RPLoc, CondIsTrue);
16934
0
}
16935
16936
//===----------------------------------------------------------------------===//
16937
// Clang Extensions.
16938
//===----------------------------------------------------------------------===//
16939
16940
/// ActOnBlockStart - This callback is invoked when a block literal is started.
16941
5
void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16942
5
  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16943
16944
5
  if (LangOpts.CPlusPlus) {
16945
4
    MangleNumberingContext *MCtx;
16946
4
    Decl *ManglingContextDecl;
16947
4
    std::tie(MCtx, ManglingContextDecl) =
16948
4
        getCurrentMangleNumberContext(Block->getDeclContext());
16949
4
    if (MCtx) {
16950
0
      unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16951
0
      Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16952
0
    }
16953
4
  }
16954
16955
5
  PushBlockScope(CurScope, Block);
16956
5
  CurContext->addDecl(Block);
16957
5
  if (CurScope)
16958
5
    PushDeclContext(CurScope, Block);
16959
0
  else
16960
0
    CurContext = Block;
16961
16962
5
  getCurBlock()->HasImplicitReturnType = true;
16963
16964
  // Enter a new evaluation context to insulate the block from any
16965
  // cleanups from the enclosing full-expression.
16966
5
  PushExpressionEvaluationContext(
16967
5
      ExpressionEvaluationContext::PotentiallyEvaluated);
16968
5
}
16969
16970
void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16971
5
                               Scope *CurScope) {
16972
5
  assert(ParamInfo.getIdentifier() == nullptr &&
16973
5
         "block-id should have no identifier!");
16974
0
  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16975
0
  BlockScopeInfo *CurBlock = getCurBlock();
16976
16977
5
  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16978
5
  QualType T = Sig->getType();
16979
16980
  // FIXME: We should allow unexpanded parameter packs here, but that would,
16981
  // in turn, make the block expression contain unexpanded parameter packs.
16982
5
  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16983
    // Drop the parameters.
16984
0
    FunctionProtoType::ExtProtoInfo EPI;
16985
0
    EPI.HasTrailingReturn = false;
16986
0
    EPI.TypeQuals.addConst();
16987
0
    T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16988
0
    Sig = Context.getTrivialTypeSourceInfo(T);
16989
0
  }
16990
16991
  // GetTypeForDeclarator always produces a function type for a block
16992
  // literal signature.  Furthermore, it is always a FunctionProtoType
16993
  // unless the function was written with a typedef.
16994
5
  assert(T->isFunctionType() &&
16995
5
         "GetTypeForDeclarator made a non-function block signature");
16996
16997
  // Look for an explicit signature in that function type.
16998
0
  FunctionProtoTypeLoc ExplicitSignature;
16999
17000
5
  if ((ExplicitSignature = Sig->getTypeLoc()
17001
5
                               .getAsAdjusted<FunctionProtoTypeLoc>())) {
17002
17003
    // Check whether that explicit signature was synthesized by
17004
    // GetTypeForDeclarator.  If so, don't save that as part of the
17005
    // written signature.
17006
4
    if (ExplicitSignature.getLocalRangeBegin() ==
17007
4
        ExplicitSignature.getLocalRangeEnd()) {
17008
      // This would be much cheaper if we stored TypeLocs instead of
17009
      // TypeSourceInfos.
17010
4
      TypeLoc Result = ExplicitSignature.getReturnLoc();
17011
4
      unsigned Size = Result.getFullDataSize();
17012
4
      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
17013
4
      Sig->getTypeLoc().initializeFullCopy(Result, Size);
17014
17015
4
      ExplicitSignature = FunctionProtoTypeLoc();
17016
4
    }
17017
4
  }
17018
17019
5
  CurBlock->TheDecl->setSignatureAsWritten(Sig);
17020
5
  CurBlock->FunctionType = T;
17021
17022
5
  const auto *Fn = T->castAs<FunctionType>();
17023
5
  QualType RetTy = Fn->getReturnType();
17024
5
  bool isVariadic =
17025
5
      (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
17026
17027
5
  CurBlock->TheDecl->setIsVariadic(isVariadic);
17028
17029
  // Context.DependentTy is used as a placeholder for a missing block
17030
  // return type.  TODO:  what should we do with declarators like:
17031
  //   ^ * { ... }
17032
  // If the answer is "apply template argument deduction"....
17033
5
  if (RetTy != Context.DependentTy) {
17034
4
    CurBlock->ReturnType = RetTy;
17035
4
    CurBlock->TheDecl->setBlockMissingReturnType(false);
17036
4
    CurBlock->HasImplicitReturnType = false;
17037
4
  }
17038
17039
  // Push block parameters from the declarator if we had them.
17040
5
  SmallVector<ParmVarDecl*, 8> Params;
17041
5
  if (ExplicitSignature) {
17042
0
    for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17043
0
      ParmVarDecl *Param = ExplicitSignature.getParam(I);
17044
0
      if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17045
0
          !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17046
        // Diagnose this as an extension in C17 and earlier.
17047
0
        if (!getLangOpts().C23)
17048
0
          Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17049
0
      }
17050
0
      Params.push_back(Param);
17051
0
    }
17052
17053
  // Fake up parameter variables if we have a typedef, like
17054
  //   ^ fntype { ... }
17055
5
  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17056
4
    for (const auto &I : Fn->param_types()) {
17057
0
      ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17058
0
          CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17059
0
      Params.push_back(Param);
17060
0
    }
17061
4
  }
17062
17063
  // Set the parameters on the block decl.
17064
5
  if (!Params.empty()) {
17065
0
    CurBlock->TheDecl->setParams(Params);
17066
0
    CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
17067
0
                             /*CheckParameterNames=*/false);
17068
0
  }
17069
17070
  // Finally we can process decl attributes.
17071
5
  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17072
17073
  // Put the parameter variables in scope.
17074
5
  for (auto *AI : CurBlock->TheDecl->parameters()) {
17075
0
    AI->setOwningFunction(CurBlock->TheDecl);
17076
17077
    // If this has an identifier, add it to the scope stack.
17078
0
    if (AI->getIdentifier()) {
17079
0
      CheckShadow(CurBlock->TheScope, AI);
17080
17081
0
      PushOnScopeChains(AI, CurBlock->TheScope);
17082
0
    }
17083
17084
0
    if (AI->isInvalidDecl())
17085
0
      CurBlock->TheDecl->setInvalidDecl();
17086
0
  }
17087
5
}
17088
17089
/// ActOnBlockError - If there is an error parsing a block, this callback
17090
/// is invoked to pop the information about the block from the action impl.
17091
4
void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17092
  // Leave the expression-evaluation context.
17093
4
  DiscardCleanupsInEvaluationContext();
17094
4
  PopExpressionEvaluationContext();
17095
17096
  // Pop off CurBlock, handle nested blocks.
17097
4
  PopDeclContext();
17098
4
  PopFunctionScopeInfo();
17099
4
}
17100
17101
/// ActOnBlockStmtExpr - This is called when the body of a block statement
17102
/// literal was successfully completed.  ^(int x){...}
17103
ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17104
1
                                    Stmt *Body, Scope *CurScope) {
17105
  // If blocks are disabled, emit an error.
17106
1
  if (!LangOpts.Blocks)
17107
1
    Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17108
17109
  // Leave the expression-evaluation context.
17110
1
  if (hasAnyUnrecoverableErrorsInThisFunction())
17111
1
    DiscardCleanupsInEvaluationContext();
17112
1
  assert(!Cleanup.exprNeedsCleanups() &&
17113
1
         "cleanups within block not correctly bound!");
17114
0
  PopExpressionEvaluationContext();
17115
17116
1
  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
17117
1
  BlockDecl *BD = BSI->TheDecl;
17118
17119
1
  if (BSI->HasImplicitReturnType)
17120
1
    deduceClosureReturnType(*BSI);
17121
17122
1
  QualType RetTy = Context.VoidTy;
17123
1
  if (!BSI->ReturnType.isNull())
17124
1
    RetTy = BSI->ReturnType;
17125
17126
1
  bool NoReturn = BD->hasAttr<NoReturnAttr>();
17127
1
  QualType BlockTy;
17128
17129
  // If the user wrote a function type in some form, try to use that.
17130
1
  if (!BSI->FunctionType.isNull()) {
17131
1
    const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17132
17133
1
    FunctionType::ExtInfo Ext = FTy->getExtInfo();
17134
1
    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17135
17136
    // Turn protoless block types into nullary block types.
17137
1
    if (isa<FunctionNoProtoType>(FTy)) {
17138
0
      FunctionProtoType::ExtProtoInfo EPI;
17139
0
      EPI.ExtInfo = Ext;
17140
0
      BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17141
17142
      // Otherwise, if we don't need to change anything about the function type,
17143
      // preserve its sugar structure.
17144
1
    } else if (FTy->getReturnType() == RetTy &&
17145
1
               (!NoReturn || FTy->getNoReturnAttr())) {
17146
0
      BlockTy = BSI->FunctionType;
17147
17148
    // Otherwise, make the minimal modifications to the function type.
17149
1
    } else {
17150
1
      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
17151
1
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17152
1
      EPI.TypeQuals = Qualifiers();
17153
1
      EPI.ExtInfo = Ext;
17154
1
      BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17155
1
    }
17156
17157
  // If we don't have a function type, just build one from nothing.
17158
1
  } else {
17159
0
    FunctionProtoType::ExtProtoInfo EPI;
17160
0
    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17161
0
    BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17162
0
  }
17163
17164
1
  DiagnoseUnusedParameters(BD->parameters());
17165
1
  BlockTy = Context.getBlockPointerType(BlockTy);
17166
17167
  // If needed, diagnose invalid gotos and switches in the block.
17168
1
  if (getCurFunction()->NeedsScopeChecking() &&
17169
1
      !PP.isCodeCompletionEnabled())
17170
0
    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
17171
17172
1
  BD->setBody(cast<CompoundStmt>(Body));
17173
17174
1
  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17175
0
    DiagnoseUnguardedAvailabilityViolations(BD);
17176
17177
  // Try to apply the named return value optimization. We have to check again
17178
  // if we can do this, though, because blocks keep return statements around
17179
  // to deduce an implicit return type.
17180
1
  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17181
1
      !BD->isDependentContext())
17182
0
    computeNRVO(Body, BSI);
17183
17184
1
  if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17185
1
      RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17186
0
    checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
17187
0
                          NTCUK_Destruct|NTCUK_Copy);
17188
17189
1
  PopDeclContext();
17190
17191
  // Set the captured variables on the block.
17192
1
  SmallVector<BlockDecl::Capture, 4> Captures;
17193
1
  for (Capture &Cap : BSI->Captures) {
17194
0
    if (Cap.isInvalid() || Cap.isThisCapture())
17195
0
      continue;
17196
    // Cap.getVariable() is always a VarDecl because
17197
    // blocks cannot capture structured bindings or other ValueDecl kinds.
17198
0
    auto *Var = cast<VarDecl>(Cap.getVariable());
17199
0
    Expr *CopyExpr = nullptr;
17200
0
    if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17201
0
      if (const RecordType *Record =
17202
0
              Cap.getCaptureType()->getAs<RecordType>()) {
17203
        // The capture logic needs the destructor, so make sure we mark it.
17204
        // Usually this is unnecessary because most local variables have
17205
        // their destructors marked at declaration time, but parameters are
17206
        // an exception because it's technically only the call site that
17207
        // actually requires the destructor.
17208
0
        if (isa<ParmVarDecl>(Var))
17209
0
          FinalizeVarWithDestructor(Var, Record);
17210
17211
        // Enter a separate potentially-evaluated context while building block
17212
        // initializers to isolate their cleanups from those of the block
17213
        // itself.
17214
        // FIXME: Is this appropriate even when the block itself occurs in an
17215
        // unevaluated operand?
17216
0
        EnterExpressionEvaluationContext EvalContext(
17217
0
            *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17218
17219
0
        SourceLocation Loc = Cap.getLocation();
17220
17221
0
        ExprResult Result = BuildDeclarationNameExpr(
17222
0
            CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17223
17224
        // According to the blocks spec, the capture of a variable from
17225
        // the stack requires a const copy constructor.  This is not true
17226
        // of the copy/move done to move a __block variable to the heap.
17227
0
        if (!Result.isInvalid() &&
17228
0
            !Result.get()->getType().isConstQualified()) {
17229
0
          Result = ImpCastExprToType(Result.get(),
17230
0
                                     Result.get()->getType().withConst(),
17231
0
                                     CK_NoOp, VK_LValue);
17232
0
        }
17233
17234
0
        if (!Result.isInvalid()) {
17235
0
          Result = PerformCopyInitialization(
17236
0
              InitializedEntity::InitializeBlock(Var->getLocation(),
17237
0
                                                 Cap.getCaptureType()),
17238
0
              Loc, Result.get());
17239
0
        }
17240
17241
        // Build a full-expression copy expression if initialization
17242
        // succeeded and used a non-trivial constructor.  Recover from
17243
        // errors by pretending that the copy isn't necessary.
17244
0
        if (!Result.isInvalid() &&
17245
0
            !cast<CXXConstructExpr>(Result.get())->getConstructor()
17246
0
                ->isTrivial()) {
17247
0
          Result = MaybeCreateExprWithCleanups(Result);
17248
0
          CopyExpr = Result.get();
17249
0
        }
17250
0
      }
17251
0
    }
17252
17253
0
    BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17254
0
                              CopyExpr);
17255
0
    Captures.push_back(NewCap);
17256
0
  }
17257
1
  BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17258
17259
  // Pop the block scope now but keep it alive to the end of this function.
17260
1
  AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
17261
1
  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17262
17263
1
  BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
17264
17265
  // If the block isn't obviously global, i.e. it captures anything at
17266
  // all, then we need to do a few things in the surrounding context:
17267
1
  if (Result->getBlockDecl()->hasCaptures()) {
17268
    // First, this expression has a new cleanup object.
17269
0
    ExprCleanupObjects.push_back(Result->getBlockDecl());
17270
0
    Cleanup.setExprNeedsCleanups(true);
17271
17272
    // It also gets a branch-protected scope if any of the captured
17273
    // variables needs destruction.
17274
0
    for (const auto &CI : Result->getBlockDecl()->captures()) {
17275
0
      const VarDecl *var = CI.getVariable();
17276
0
      if (var->getType().isDestructedType() != QualType::DK_none) {
17277
0
        setFunctionHasBranchProtectedScope();
17278
0
        break;
17279
0
      }
17280
0
    }
17281
0
  }
17282
17283
1
  if (getCurFunction())
17284
0
    getCurFunction()->addBlock(BD);
17285
17286
1
  if (BD->isInvalidDecl())
17287
0
    return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17288
0
                              {Result}, Result->getType());
17289
1
  return Result;
17290
1
}
17291
17292
ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17293
0
                            SourceLocation RPLoc) {
17294
0
  TypeSourceInfo *TInfo;
17295
0
  GetTypeFromParser(Ty, &TInfo);
17296
0
  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17297
0
}
17298
17299
ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17300
                                Expr *E, TypeSourceInfo *TInfo,
17301
0
                                SourceLocation RPLoc) {
17302
0
  Expr *OrigExpr = E;
17303
0
  bool IsMS = false;
17304
17305
  // CUDA device code does not support varargs.
17306
0
  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17307
0
    if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17308
0
      CUDAFunctionTarget T = IdentifyCUDATarget(F);
17309
0
      if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
17310
0
        return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17311
0
    }
17312
0
  }
17313
17314
  // NVPTX does not support va_arg expression.
17315
0
  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17316
0
      Context.getTargetInfo().getTriple().isNVPTX())
17317
0
    targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17318
17319
  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17320
  // as Microsoft ABI on an actual Microsoft platform, where
17321
  // __builtin_ms_va_list and __builtin_va_list are the same.)
17322
0
  if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17323
0
      Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17324
0
    QualType MSVaListType = Context.getBuiltinMSVaListType();
17325
0
    if (Context.hasSameType(MSVaListType, E->getType())) {
17326
0
      if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17327
0
        return ExprError();
17328
0
      IsMS = true;
17329
0
    }
17330
0
  }
17331
17332
  // Get the va_list type
17333
0
  QualType VaListType = Context.getBuiltinVaListType();
17334
0
  if (!IsMS) {
17335
0
    if (VaListType->isArrayType()) {
17336
      // Deal with implicit array decay; for example, on x86-64,
17337
      // va_list is an array, but it's supposed to decay to
17338
      // a pointer for va_arg.
17339
0
      VaListType = Context.getArrayDecayedType(VaListType);
17340
      // Make sure the input expression also decays appropriately.
17341
0
      ExprResult Result = UsualUnaryConversions(E);
17342
0
      if (Result.isInvalid())
17343
0
        return ExprError();
17344
0
      E = Result.get();
17345
0
    } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17346
      // If va_list is a record type and we are compiling in C++ mode,
17347
      // check the argument using reference binding.
17348
0
      InitializedEntity Entity = InitializedEntity::InitializeParameter(
17349
0
          Context, Context.getLValueReferenceType(VaListType), false);
17350
0
      ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
17351
0
      if (Init.isInvalid())
17352
0
        return ExprError();
17353
0
      E = Init.getAs<Expr>();
17354
0
    } else {
17355
      // Otherwise, the va_list argument must be an l-value because
17356
      // it is modified by va_arg.
17357
0
      if (!E->isTypeDependent() &&
17358
0
          CheckForModifiableLvalue(E, BuiltinLoc, *this))
17359
0
        return ExprError();
17360
0
    }
17361
0
  }
17362
17363
0
  if (!IsMS && !E->isTypeDependent() &&
17364
0
      !Context.hasSameType(VaListType, E->getType()))
17365
0
    return ExprError(
17366
0
        Diag(E->getBeginLoc(),
17367
0
             diag::err_first_argument_to_va_arg_not_of_type_va_list)
17368
0
        << OrigExpr->getType() << E->getSourceRange());
17369
17370
0
  if (!TInfo->getType()->isDependentType()) {
17371
0
    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17372
0
                            diag::err_second_parameter_to_va_arg_incomplete,
17373
0
                            TInfo->getTypeLoc()))
17374
0
      return ExprError();
17375
17376
0
    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17377
0
                               TInfo->getType(),
17378
0
                               diag::err_second_parameter_to_va_arg_abstract,
17379
0
                               TInfo->getTypeLoc()))
17380
0
      return ExprError();
17381
17382
0
    if (!TInfo->getType().isPODType(Context)) {
17383
0
      Diag(TInfo->getTypeLoc().getBeginLoc(),
17384
0
           TInfo->getType()->isObjCLifetimeType()
17385
0
             ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17386
0
             : diag::warn_second_parameter_to_va_arg_not_pod)
17387
0
        << TInfo->getType()
17388
0
        << TInfo->getTypeLoc().getSourceRange();
17389
0
    }
17390
17391
    // Check for va_arg where arguments of the given type will be promoted
17392
    // (i.e. this va_arg is guaranteed to have undefined behavior).
17393
0
    QualType PromoteType;
17394
0
    if (Context.isPromotableIntegerType(TInfo->getType())) {
17395
0
      PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17396
      // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17397
      // and C23 7.16.1.1p2 says, in part:
17398
      //   If type is not compatible with the type of the actual next argument
17399
      //   (as promoted according to the default argument promotions), the
17400
      //   behavior is undefined, except for the following cases:
17401
      //     - both types are pointers to qualified or unqualified versions of
17402
      //       compatible types;
17403
      //     - one type is compatible with a signed integer type, the other
17404
      //       type is compatible with the corresponding unsigned integer type,
17405
      //       and the value is representable in both types;
17406
      //     - one type is pointer to qualified or unqualified void and the
17407
      //       other is a pointer to a qualified or unqualified character type;
17408
      //     - or, the type of the next argument is nullptr_t and type is a
17409
      //       pointer type that has the same representation and alignment
17410
      //       requirements as a pointer to a character type.
17411
      // Given that type compatibility is the primary requirement (ignoring
17412
      // qualifications), you would think we could call typesAreCompatible()
17413
      // directly to test this. However, in C++, that checks for *same type*,
17414
      // which causes false positives when passing an enumeration type to
17415
      // va_arg. Instead, get the underlying type of the enumeration and pass
17416
      // that.
17417
0
      QualType UnderlyingType = TInfo->getType();
17418
0
      if (const auto *ET = UnderlyingType->getAs<EnumType>())
17419
0
        UnderlyingType = ET->getDecl()->getIntegerType();
17420
0
      if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17421
0
                                     /*CompareUnqualified*/ true))
17422
0
        PromoteType = QualType();
17423
17424
      // If the types are still not compatible, we need to test whether the
17425
      // promoted type and the underlying type are the same except for
17426
      // signedness. Ask the AST for the correctly corresponding type and see
17427
      // if that's compatible.
17428
0
      if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17429
0
          PromoteType->isUnsignedIntegerType() !=
17430
0
              UnderlyingType->isUnsignedIntegerType()) {
17431
0
        UnderlyingType =
17432
0
            UnderlyingType->isUnsignedIntegerType()
17433
0
                ? Context.getCorrespondingSignedType(UnderlyingType)
17434
0
                : Context.getCorrespondingUnsignedType(UnderlyingType);
17435
0
        if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17436
0
                                       /*CompareUnqualified*/ true))
17437
0
          PromoteType = QualType();
17438
0
      }
17439
0
    }
17440
0
    if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17441
0
      PromoteType = Context.DoubleTy;
17442
0
    if (!PromoteType.isNull())
17443
0
      DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17444
0
                  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17445
0
                          << TInfo->getType()
17446
0
                          << PromoteType
17447
0
                          << TInfo->getTypeLoc().getSourceRange());
17448
0
  }
17449
17450
0
  QualType T = TInfo->getType().getNonLValueExprType(Context);
17451
0
  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17452
0
}
17453
17454
0
ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17455
  // The type of __null will be int or long, depending on the size of
17456
  // pointers on the target.
17457
0
  QualType Ty;
17458
0
  unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17459
0
  if (pw == Context.getTargetInfo().getIntWidth())
17460
0
    Ty = Context.IntTy;
17461
0
  else if (pw == Context.getTargetInfo().getLongWidth())
17462
0
    Ty = Context.LongTy;
17463
0
  else if (pw == Context.getTargetInfo().getLongLongWidth())
17464
0
    Ty = Context.LongLongTy;
17465
0
  else {
17466
0
    llvm_unreachable("I don't know size of pointer!");
17467
0
  }
17468
17469
0
  return new (Context) GNUNullExpr(Ty, TokenLoc);
17470
0
}
17471
17472
0
static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17473
0
  CXXRecordDecl *ImplDecl = nullptr;
17474
17475
  // Fetch the std::source_location::__impl decl.
17476
0
  if (NamespaceDecl *Std = S.getStdNamespace()) {
17477
0
    LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17478
0
                          Loc, Sema::LookupOrdinaryName);
17479
0
    if (S.LookupQualifiedName(ResultSL, Std)) {
17480
0
      if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17481
0
        LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17482
0
                                Loc, Sema::LookupOrdinaryName);
17483
0
        if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17484
0
            S.LookupQualifiedName(ResultImpl, SLDecl)) {
17485
0
          ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17486
0
        }
17487
0
      }
17488
0
    }
17489
0
  }
17490
17491
0
  if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17492
0
    S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17493
0
    return nullptr;
17494
0
  }
17495
17496
  // Verify that __impl is a trivial struct type, with no base classes, and with
17497
  // only the four expected fields.
17498
0
  if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17499
0
      ImplDecl->getNumBases() != 0) {
17500
0
    S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17501
0
    return nullptr;
17502
0
  }
17503
17504
0
  unsigned Count = 0;
17505
0
  for (FieldDecl *F : ImplDecl->fields()) {
17506
0
    StringRef Name = F->getName();
17507
17508
0
    if (Name == "_M_file_name") {
17509
0
      if (F->getType() !=
17510
0
          S.Context.getPointerType(S.Context.CharTy.withConst()))
17511
0
        break;
17512
0
      Count++;
17513
0
    } else if (Name == "_M_function_name") {
17514
0
      if (F->getType() !=
17515
0
          S.Context.getPointerType(S.Context.CharTy.withConst()))
17516
0
        break;
17517
0
      Count++;
17518
0
    } else if (Name == "_M_line") {
17519
0
      if (!F->getType()->isIntegerType())
17520
0
        break;
17521
0
      Count++;
17522
0
    } else if (Name == "_M_column") {
17523
0
      if (!F->getType()->isIntegerType())
17524
0
        break;
17525
0
      Count++;
17526
0
    } else {
17527
0
      Count = 100; // invalid
17528
0
      break;
17529
0
    }
17530
0
  }
17531
0
  if (Count != 4) {
17532
0
    S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17533
0
    return nullptr;
17534
0
  }
17535
17536
0
  return ImplDecl;
17537
0
}
17538
17539
ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17540
                                    SourceLocation BuiltinLoc,
17541
0
                                    SourceLocation RPLoc) {
17542
0
  QualType ResultTy;
17543
0
  switch (Kind) {
17544
0
  case SourceLocIdentKind::File:
17545
0
  case SourceLocIdentKind::FileName:
17546
0
  case SourceLocIdentKind::Function:
17547
0
  case SourceLocIdentKind::FuncSig: {
17548
0
    QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17549
0
    ResultTy =
17550
0
        Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17551
0
    break;
17552
0
  }
17553
0
  case SourceLocIdentKind::Line:
17554
0
  case SourceLocIdentKind::Column:
17555
0
    ResultTy = Context.UnsignedIntTy;
17556
0
    break;
17557
0
  case SourceLocIdentKind::SourceLocStruct:
17558
0
    if (!StdSourceLocationImplDecl) {
17559
0
      StdSourceLocationImplDecl =
17560
0
          LookupStdSourceLocationImpl(*this, BuiltinLoc);
17561
0
      if (!StdSourceLocationImplDecl)
17562
0
        return ExprError();
17563
0
    }
17564
0
    ResultTy = Context.getPointerType(
17565
0
        Context.getRecordType(StdSourceLocationImplDecl).withConst());
17566
0
    break;
17567
0
  }
17568
17569
0
  return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17570
0
}
17571
17572
ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17573
                                    SourceLocation BuiltinLoc,
17574
                                    SourceLocation RPLoc,
17575
0
                                    DeclContext *ParentContext) {
17576
0
  return new (Context)
17577
0
      SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17578
0
}
17579
17580
bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17581
8
                                        bool Diagnose) {
17582
8
  if (!getLangOpts().ObjC)
17583
0
    return false;
17584
17585
8
  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17586
8
  if (!PT)
17587
6
    return false;
17588
2
  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17589
17590
  // Ignore any parens, implicit casts (should only be
17591
  // array-to-pointer decays), and not-so-opaque values.  The last is
17592
  // important for making this trigger for property assignments.
17593
2
  Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17594
2
  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17595
0
    if (OV->getSourceExpr())
17596
0
      SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17597
17598
2
  if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17599
0
    if (!PT->isObjCIdType() &&
17600
0
        !(ID && ID->getIdentifier()->isStr("NSString")))
17601
0
      return false;
17602
0
    if (!SL->isOrdinary())
17603
0
      return false;
17604
17605
0
    if (Diagnose) {
17606
0
      Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17607
0
          << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17608
0
      Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17609
0
    }
17610
0
    return true;
17611
0
  }
17612
17613
2
  if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17614
2
      isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17615
2
      isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17616
2
      !SrcExpr->isNullPointerConstant(
17617
0
          getASTContext(), Expr::NPC_NeverValueDependent)) {
17618
0
    if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17619
0
      return false;
17620
0
    if (Diagnose) {
17621
0
      Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17622
0
          << /*number*/1
17623
0
          << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17624
0
      Expr *NumLit =
17625
0
          BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17626
0
      if (NumLit)
17627
0
        Exp = NumLit;
17628
0
    }
17629
0
    return true;
17630
0
  }
17631
17632
2
  return false;
17633
2
}
17634
17635
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17636
0
                                              const Expr *SrcExpr) {
17637
0
  if (!DstType->isFunctionPointerType() ||
17638
0
      !SrcExpr->getType()->isFunctionType())
17639
0
    return false;
17640
17641
0
  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17642
0
  if (!DRE)
17643
0
    return false;
17644
17645
0
  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17646
0
  if (!FD)
17647
0
    return false;
17648
17649
0
  return !S.checkAddressOfFunctionIsAvailable(FD,
17650
0
                                              /*Complain=*/true,
17651
0
                                              SrcExpr->getBeginLoc());
17652
0
}
17653
17654
bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17655
                                    SourceLocation Loc,
17656
                                    QualType DstType, QualType SrcType,
17657
                                    Expr *SrcExpr, AssignmentAction Action,
17658
7
                                    bool *Complained) {
17659
7
  if (Complained)
17660
7
    *Complained = false;
17661
17662
  // Decode the result (notice that AST's are still created for extensions).
17663
7
  bool CheckInferredResultType = false;
17664
7
  bool isInvalid = false;
17665
7
  unsigned DiagKind = 0;
17666
7
  ConversionFixItGenerator ConvHints;
17667
7
  bool MayHaveConvFixit = false;
17668
7
  bool MayHaveFunctionDiff = false;
17669
7
  const ObjCInterfaceDecl *IFace = nullptr;
17670
7
  const ObjCProtocolDecl *PDecl = nullptr;
17671
17672
7
  switch (ConvTy) {
17673
6
  case Compatible:
17674
6
      DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17675
6
      return false;
17676
17677
0
  case PointerToInt:
17678
0
    if (getLangOpts().CPlusPlus) {
17679
0
      DiagKind = diag::err_typecheck_convert_pointer_int;
17680
0
      isInvalid = true;
17681
0
    } else {
17682
0
      DiagKind = diag::ext_typecheck_convert_pointer_int;
17683
0
    }
17684
0
    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17685
0
    MayHaveConvFixit = true;
17686
0
    break;
17687
1
  case IntToPointer:
17688
1
    if (getLangOpts().CPlusPlus) {
17689
0
      DiagKind = diag::err_typecheck_convert_int_pointer;
17690
0
      isInvalid = true;
17691
1
    } else {
17692
1
      DiagKind = diag::ext_typecheck_convert_int_pointer;
17693
1
    }
17694
1
    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17695
1
    MayHaveConvFixit = true;
17696
1
    break;
17697
0
  case IncompatibleFunctionPointerStrict:
17698
0
    DiagKind =
17699
0
        diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17700
0
    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17701
0
    MayHaveConvFixit = true;
17702
0
    break;
17703
0
  case IncompatibleFunctionPointer:
17704
0
    if (getLangOpts().CPlusPlus) {
17705
0
      DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17706
0
      isInvalid = true;
17707
0
    } else {
17708
0
      DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17709
0
    }
17710
0
    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17711
0
    MayHaveConvFixit = true;
17712
0
    break;
17713
0
  case IncompatiblePointer:
17714
0
    if (Action == AA_Passing_CFAudited) {
17715
0
      DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17716
0
    } else if (getLangOpts().CPlusPlus) {
17717
0
      DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17718
0
      isInvalid = true;
17719
0
    } else {
17720
0
      DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17721
0
    }
17722
0
    CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17723
0
      SrcType->isObjCObjectPointerType();
17724
0
    if (!CheckInferredResultType) {
17725
0
      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17726
0
    } else if (CheckInferredResultType) {
17727
0
      SrcType = SrcType.getUnqualifiedType();
17728
0
      DstType = DstType.getUnqualifiedType();
17729
0
    }
17730
0
    MayHaveConvFixit = true;
17731
0
    break;
17732
0
  case IncompatiblePointerSign:
17733
0
    if (getLangOpts().CPlusPlus) {
17734
0
      DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17735
0
      isInvalid = true;
17736
0
    } else {
17737
0
      DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17738
0
    }
17739
0
    break;
17740
0
  case FunctionVoidPointer:
17741
0
    if (getLangOpts().CPlusPlus) {
17742
0
      DiagKind = diag::err_typecheck_convert_pointer_void_func;
17743
0
      isInvalid = true;
17744
0
    } else {
17745
0
      DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17746
0
    }
17747
0
    break;
17748
0
  case IncompatiblePointerDiscardsQualifiers: {
17749
    // Perform array-to-pointer decay if necessary.
17750
0
    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17751
17752
0
    isInvalid = true;
17753
17754
0
    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17755
0
    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17756
0
    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17757
0
      DiagKind = diag::err_typecheck_incompatible_address_space;
17758
0
      break;
17759
17760
0
    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17761
0
      DiagKind = diag::err_typecheck_incompatible_ownership;
17762
0
      break;
17763
0
    }
17764
17765
0
    llvm_unreachable("unknown error case for discarding qualifiers!");
17766
    // fallthrough
17767
0
  }
17768
0
  case CompatiblePointerDiscardsQualifiers:
17769
    // If the qualifiers lost were because we were applying the
17770
    // (deprecated) C++ conversion from a string literal to a char*
17771
    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
17772
    // Ideally, this check would be performed in
17773
    // checkPointerTypesForAssignment. However, that would require a
17774
    // bit of refactoring (so that the second argument is an
17775
    // expression, rather than a type), which should be done as part
17776
    // of a larger effort to fix checkPointerTypesForAssignment for
17777
    // C++ semantics.
17778
0
    if (getLangOpts().CPlusPlus &&
17779
0
        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17780
0
      return false;
17781
0
    if (getLangOpts().CPlusPlus) {
17782
0
      DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
17783
0
      isInvalid = true;
17784
0
    } else {
17785
0
      DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
17786
0
    }
17787
17788
0
    break;
17789
0
  case IncompatibleNestedPointerQualifiers:
17790
0
    if (getLangOpts().CPlusPlus) {
17791
0
      isInvalid = true;
17792
0
      DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17793
0
    } else {
17794
0
      DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17795
0
    }
17796
0
    break;
17797
0
  case IncompatibleNestedPointerAddressSpaceMismatch:
17798
0
    DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17799
0
    isInvalid = true;
17800
0
    break;
17801
0
  case IntToBlockPointer:
17802
0
    DiagKind = diag::err_int_to_block_pointer;
17803
0
    isInvalid = true;
17804
0
    break;
17805
0
  case IncompatibleBlockPointer:
17806
0
    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17807
0
    isInvalid = true;
17808
0
    break;
17809
0
  case IncompatibleObjCQualifiedId: {
17810
0
    if (SrcType->isObjCQualifiedIdType()) {
17811
0
      const ObjCObjectPointerType *srcOPT =
17812
0
                SrcType->castAs<ObjCObjectPointerType>();
17813
0
      for (auto *srcProto : srcOPT->quals()) {
17814
0
        PDecl = srcProto;
17815
0
        break;
17816
0
      }
17817
0
      if (const ObjCInterfaceType *IFaceT =
17818
0
            DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17819
0
        IFace = IFaceT->getDecl();
17820
0
    }
17821
0
    else if (DstType->isObjCQualifiedIdType()) {
17822
0
      const ObjCObjectPointerType *dstOPT =
17823
0
        DstType->castAs<ObjCObjectPointerType>();
17824
0
      for (auto *dstProto : dstOPT->quals()) {
17825
0
        PDecl = dstProto;
17826
0
        break;
17827
0
      }
17828
0
      if (const ObjCInterfaceType *IFaceT =
17829
0
            SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17830
0
        IFace = IFaceT->getDecl();
17831
0
    }
17832
0
    if (getLangOpts().CPlusPlus) {
17833
0
      DiagKind = diag::err_incompatible_qualified_id;
17834
0
      isInvalid = true;
17835
0
    } else {
17836
0
      DiagKind = diag::warn_incompatible_qualified_id;
17837
0
    }
17838
0
    break;
17839
0
  }
17840
0
  case IncompatibleVectors:
17841
0
    if (getLangOpts().CPlusPlus) {
17842
0
      DiagKind = diag::err_incompatible_vectors;
17843
0
      isInvalid = true;
17844
0
    } else {
17845
0
      DiagKind = diag::warn_incompatible_vectors;
17846
0
    }
17847
0
    break;
17848
0
  case IncompatibleObjCWeakRef:
17849
0
    DiagKind = diag::err_arc_weak_unavailable_assign;
17850
0
    isInvalid = true;
17851
0
    break;
17852
0
  case Incompatible:
17853
0
    if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17854
0
      if (Complained)
17855
0
        *Complained = true;
17856
0
      return true;
17857
0
    }
17858
17859
0
    DiagKind = diag::err_typecheck_convert_incompatible;
17860
0
    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17861
0
    MayHaveConvFixit = true;
17862
0
    isInvalid = true;
17863
0
    MayHaveFunctionDiff = true;
17864
0
    break;
17865
7
  }
17866
17867
1
  QualType FirstType, SecondType;
17868
1
  switch (Action) {
17869
0
  case AA_Assigning:
17870
1
  case AA_Initializing:
17871
    // The destination type comes first.
17872
1
    FirstType = DstType;
17873
1
    SecondType = SrcType;
17874
1
    break;
17875
17876
0
  case AA_Returning:
17877
0
  case AA_Passing:
17878
0
  case AA_Passing_CFAudited:
17879
0
  case AA_Converting:
17880
0
  case AA_Sending:
17881
0
  case AA_Casting:
17882
    // The source type comes first.
17883
0
    FirstType = SrcType;
17884
0
    SecondType = DstType;
17885
0
    break;
17886
1
  }
17887
17888
1
  PartialDiagnostic FDiag = PDiag(DiagKind);
17889
1
  AssignmentAction ActionForDiag = Action;
17890
1
  if (Action == AA_Passing_CFAudited)
17891
0
    ActionForDiag = AA_Passing;
17892
17893
1
  FDiag << FirstType << SecondType << ActionForDiag
17894
1
        << SrcExpr->getSourceRange();
17895
17896
1
  if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17897
1
      DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17898
0
    auto isPlainChar = [](const clang::Type *Type) {
17899
0
      return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17900
0
             Type->isSpecificBuiltinType(BuiltinType::Char_U);
17901
0
    };
17902
0
    FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17903
0
              isPlainChar(SecondType->getPointeeOrArrayElementType()));
17904
0
  }
17905
17906
  // If we can fix the conversion, suggest the FixIts.
17907
1
  if (!ConvHints.isNull()) {
17908
0
    for (FixItHint &H : ConvHints.Hints)
17909
0
      FDiag << H;
17910
0
  }
17911
17912
1
  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17913
17914
1
  if (MayHaveFunctionDiff)
17915
0
    HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17916
17917
1
  Diag(Loc, FDiag);
17918
1
  if ((DiagKind == diag::warn_incompatible_qualified_id ||
17919
1
       DiagKind == diag::err_incompatible_qualified_id) &&
17920
1
      PDecl && IFace && !IFace->hasDefinition())
17921
0
    Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17922
0
        << IFace << PDecl;
17923
17924
1
  if (SecondType == Context.OverloadTy)
17925
0
    NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17926
0
                              FirstType, /*TakingAddress=*/true);
17927
17928
1
  if (CheckInferredResultType)
17929
0
    EmitRelatedResultTypeNote(SrcExpr);
17930
17931
1
  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17932
0
    EmitRelatedResultTypeNoteForReturn(DstType);
17933
17934
1
  if (Complained)
17935
1
    *Complained = true;
17936
1
  return isInvalid;
17937
1
}
17938
17939
ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17940
                                                 llvm::APSInt *Result,
17941
0
                                                 AllowFoldKind CanFold) {
17942
0
  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17943
0
  public:
17944
0
    SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17945
0
                                             QualType T) override {
17946
0
      return S.Diag(Loc, diag::err_ice_not_integral)
17947
0
             << T << S.LangOpts.CPlusPlus;
17948
0
    }
17949
0
    SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17950
0
      return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17951
0
    }
17952
0
  } Diagnoser;
17953
17954
0
  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17955
0
}
17956
17957
ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17958
                                                 llvm::APSInt *Result,
17959
                                                 unsigned DiagID,
17960
0
                                                 AllowFoldKind CanFold) {
17961
0
  class IDDiagnoser : public VerifyICEDiagnoser {
17962
0
    unsigned DiagID;
17963
17964
0
  public:
17965
0
    IDDiagnoser(unsigned DiagID)
17966
0
      : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17967
17968
0
    SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17969
0
      return S.Diag(Loc, DiagID);
17970
0
    }
17971
0
  } Diagnoser(DiagID);
17972
17973
0
  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17974
0
}
17975
17976
Sema::SemaDiagnosticBuilder
17977
Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17978
0
                                             QualType T) {
17979
0
  return diagnoseNotICE(S, Loc);
17980
0
}
17981
17982
Sema::SemaDiagnosticBuilder
17983
0
Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17984
0
  return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17985
0
}
17986
17987
ExprResult
17988
Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17989
                                      VerifyICEDiagnoser &Diagnoser,
17990
8
                                      AllowFoldKind CanFold) {
17991
8
  SourceLocation DiagLoc = E->getBeginLoc();
17992
17993
8
  if (getLangOpts().CPlusPlus11) {
17994
    // C++11 [expr.const]p5:
17995
    //   If an expression of literal class type is used in a context where an
17996
    //   integral constant expression is required, then that class type shall
17997
    //   have a single non-explicit conversion function to an integral or
17998
    //   unscoped enumeration type
17999
2
    ExprResult Converted;
18000
2
    class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18001
2
      VerifyICEDiagnoser &BaseDiagnoser;
18002
2
    public:
18003
2
      CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18004
2
          : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18005
2
                                BaseDiagnoser.Suppress, true),
18006
2
            BaseDiagnoser(BaseDiagnoser) {}
18007
18008
2
      SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18009
2
                                           QualType T) override {
18010
0
        return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18011
0
      }
18012
18013
2
      SemaDiagnosticBuilder diagnoseIncomplete(
18014
2
          Sema &S, SourceLocation Loc, QualType T) override {
18015
0
        return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18016
0
      }
18017
18018
2
      SemaDiagnosticBuilder diagnoseExplicitConv(
18019
2
          Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18020
0
        return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18021
0
      }
18022
18023
2
      SemaDiagnosticBuilder noteExplicitConv(
18024
2
          Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18025
0
        return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18026
0
                 << ConvTy->isEnumeralType() << ConvTy;
18027
0
      }
18028
18029
2
      SemaDiagnosticBuilder diagnoseAmbiguous(
18030
2
          Sema &S, SourceLocation Loc, QualType T) override {
18031
0
        return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18032
0
      }
18033
18034
2
      SemaDiagnosticBuilder noteAmbiguous(
18035
2
          Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18036
0
        return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18037
0
                 << ConvTy->isEnumeralType() << ConvTy;
18038
0
      }
18039
18040
2
      SemaDiagnosticBuilder diagnoseConversion(
18041
2
          Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18042
0
        llvm_unreachable("conversion functions are permitted");
18043
0
      }
18044
2
    } ConvertDiagnoser(Diagnoser);
18045
18046
2
    Converted = PerformContextualImplicitConversion(DiagLoc, E,
18047
2
                                                    ConvertDiagnoser);
18048
2
    if (Converted.isInvalid())
18049
0
      return Converted;
18050
2
    E = Converted.get();
18051
2
    if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18052
0
      return ExprError();
18053
6
  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18054
    // An ICE must be of integral or unscoped enumeration type.
18055
0
    if (!Diagnoser.Suppress)
18056
0
      Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18057
0
          << E->getSourceRange();
18058
0
    return ExprError();
18059
0
  }
18060
18061
8
  ExprResult RValueExpr = DefaultLvalueConversion(E);
18062
8
  if (RValueExpr.isInvalid())
18063
0
    return ExprError();
18064
18065
8
  E = RValueExpr.get();
18066
18067
  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18068
  // in the non-ICE case.
18069
8
  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
18070
4
    if (Result)
18071
4
      *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
18072
4
    if (!isa<ConstantExpr>(E))
18073
4
      E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
18074
4
                 : ConstantExpr::Create(Context, E);
18075
4
    return E;
18076
4
  }
18077
18078
4
  Expr::EvalResult EvalResult;
18079
4
  SmallVector<PartialDiagnosticAt, 8> Notes;
18080
4
  EvalResult.Diag = &Notes;
18081
18082
  // Try to evaluate the expression, and produce diagnostics explaining why it's
18083
  // not a constant expression as a side-effect.
18084
4
  bool Folded =
18085
4
      E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18086
4
      EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
18087
18088
4
  if (!isa<ConstantExpr>(E))
18089
4
    E = ConstantExpr::Create(Context, E, EvalResult.Val);
18090
18091
  // In C++11, we can rely on diagnostics being produced for any expression
18092
  // which is not a constant expression. If no diagnostics were produced, then
18093
  // this is a constant expression.
18094
4
  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18095
2
    if (Result)
18096
2
      *Result = EvalResult.Val.getInt();
18097
2
    return E;
18098
2
  }
18099
18100
  // If our only note is the usual "invalid subexpression" note, just point
18101
  // the caret at its location rather than producing an essentially
18102
  // redundant note.
18103
2
  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18104
2
        diag::note_invalid_subexpr_in_const_expr) {
18105
2
    DiagLoc = Notes[0].first;
18106
2
    Notes.clear();
18107
2
  }
18108
18109
2
  if (!Folded || !CanFold) {
18110
2
    if (!Diagnoser.Suppress) {
18111
2
      Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18112
2
      for (const PartialDiagnosticAt &Note : Notes)
18113
0
        Diag(Note.first, Note.second);
18114
2
    }
18115
18116
2
    return ExprError();
18117
2
  }
18118
18119
0
  Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18120
0
  for (const PartialDiagnosticAt &Note : Notes)
18121
0
    Diag(Note.first, Note.second);
18122
18123
0
  if (Result)
18124
0
    *Result = EvalResult.Val.getInt();
18125
0
  return E;
18126
2
}
18127
18128
namespace {
18129
  // Handle the case where we conclude a expression which we speculatively
18130
  // considered to be unevaluated is actually evaluated.
18131
  class TransformToPE : public TreeTransform<TransformToPE> {
18132
    typedef TreeTransform<TransformToPE> BaseTransform;
18133
18134
  public:
18135
0
    TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18136
18137
    // Make sure we redo semantic analysis
18138
0
    bool AlwaysRebuild() { return true; }
18139
0
    bool ReplacingOriginal() { return true; }
18140
18141
    // We need to special-case DeclRefExprs referring to FieldDecls which
18142
    // are not part of a member pointer formation; normal TreeTransforming
18143
    // doesn't catch this case because of the way we represent them in the AST.
18144
    // FIXME: This is a bit ugly; is it really the best way to handle this
18145
    // case?
18146
    //
18147
    // Error on DeclRefExprs referring to FieldDecls.
18148
0
    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18149
0
      if (isa<FieldDecl>(E->getDecl()) &&
18150
0
          !SemaRef.isUnevaluatedContext())
18151
0
        return SemaRef.Diag(E->getLocation(),
18152
0
                            diag::err_invalid_non_static_member_use)
18153
0
            << E->getDecl() << E->getSourceRange();
18154
18155
0
      return BaseTransform::TransformDeclRefExpr(E);
18156
0
    }
18157
18158
    // Exception: filter out member pointer formation
18159
0
    ExprResult TransformUnaryOperator(UnaryOperator *E) {
18160
0
      if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18161
0
        return E;
18162
18163
0
      return BaseTransform::TransformUnaryOperator(E);
18164
0
    }
18165
18166
    // The body of a lambda-expression is in a separate expression evaluation
18167
    // context so never needs to be transformed.
18168
    // FIXME: Ideally we wouldn't transform the closure type either, and would
18169
    // just recreate the capture expressions and lambda expression.
18170
0
    StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18171
0
      return SkipLambdaBody(E, Body);
18172
0
    }
18173
  };
18174
}
18175
18176
0
ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18177
0
  assert(isUnevaluatedContext() &&
18178
0
         "Should only transform unevaluated expressions");
18179
0
  ExprEvalContexts.back().Context =
18180
0
      ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18181
0
  if (isUnevaluatedContext())
18182
0
    return E;
18183
0
  return TransformToPE(*this).TransformExpr(E);
18184
0
}
18185
18186
0
TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18187
0
  assert(isUnevaluatedContext() &&
18188
0
         "Should only transform unevaluated expressions");
18189
0
  ExprEvalContexts.back().Context =
18190
0
      ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
18191
0
  if (isUnevaluatedContext())
18192
0
    return TInfo;
18193
0
  return TransformToPE(*this).TransformType(TInfo);
18194
0
}
18195
18196
void
18197
Sema::PushExpressionEvaluationContext(
18198
    ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18199
502
    ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18200
502
  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18201
502
                                LambdaContextDecl, ExprContext);
18202
18203
  // Discarded statements and immediate contexts nested in other
18204
  // discarded statements or immediate context are themselves
18205
  // a discarded statement or an immediate context, respectively.
18206
502
  ExprEvalContexts.back().InDiscardedStatement =
18207
502
      ExprEvalContexts[ExprEvalContexts.size() - 2]
18208
502
          .isDiscardedStatementContext();
18209
18210
  // C++23 [expr.const]/p15
18211
  // An expression or conversion is in an immediate function context if [...]
18212
  // it is a subexpression of a manifestly constant-evaluated expression or
18213
  // conversion.
18214
502
  const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
18215
502
  ExprEvalContexts.back().InImmediateFunctionContext =
18216
502
      Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18217
18218
502
  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18219
502
      Prev.InImmediateEscalatingFunctionContext;
18220
18221
502
  Cleanup.reset();
18222
502
  if (!MaybeODRUseExprs.empty())
18223
0
    std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18224
502
}
18225
18226
void
18227
Sema::PushExpressionEvaluationContext(
18228
    ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18229
0
    ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18230
0
  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18231
0
  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18232
0
}
18233
18234
namespace {
18235
18236
0
const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18237
0
  PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18238
0
  if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18239
0
    if (E->getOpcode() == UO_Deref)
18240
0
      return CheckPossibleDeref(S, E->getSubExpr());
18241
0
  } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18242
0
    return CheckPossibleDeref(S, E->getBase());
18243
0
  } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18244
0
    return CheckPossibleDeref(S, E->getBase());
18245
0
  } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18246
0
    QualType Inner;
18247
0
    QualType Ty = E->getType();
18248
0
    if (const auto *Ptr = Ty->getAs<PointerType>())
18249
0
      Inner = Ptr->getPointeeType();
18250
0
    else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18251
0
      Inner = Arr->getElementType();
18252
0
    else
18253
0
      return nullptr;
18254
18255
0
    if (Inner->hasAttr(attr::NoDeref))
18256
0
      return E;
18257
0
  }
18258
0
  return nullptr;
18259
0
}
18260
18261
} // namespace
18262
18263
502
void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18264
502
  for (const Expr *E : Rec.PossibleDerefs) {
18265
0
    const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18266
0
    if (DeclRef) {
18267
0
      const ValueDecl *Decl = DeclRef->getDecl();
18268
0
      Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18269
0
          << Decl->getName() << E->getSourceRange();
18270
0
      Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18271
0
    } else {
18272
0
      Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18273
0
          << E->getSourceRange();
18274
0
    }
18275
0
  }
18276
502
  Rec.PossibleDerefs.clear();
18277
502
}
18278
18279
/// Check whether E, which is either a discarded-value expression or an
18280
/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
18281
/// and if so, remove it from the list of volatile-qualified assignments that
18282
/// we are going to warn are deprecated.
18283
0
void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18284
0
  if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18285
0
    return;
18286
18287
  // Note: ignoring parens here is not justified by the standard rules, but
18288
  // ignoring parentheses seems like a more reasonable approach, and this only
18289
  // drives a deprecation warning so doesn't affect conformance.
18290
0
  if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18291
0
    if (BO->getOpcode() == BO_Assign) {
18292
0
      auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18293
0
      llvm::erase(LHSs, BO->getLHS());
18294
0
    }
18295
0
  }
18296
0
}
18297
18298
0
void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18299
0
  assert(!FunctionScopes.empty() && "Expected a function scope");
18300
0
  assert(getLangOpts().CPlusPlus20 &&
18301
0
         ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18302
0
         "Cannot mark an immediate escalating expression outside of an "
18303
0
         "immediate escalating context");
18304
0
  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18305
0
      Call && Call->getCallee()) {
18306
0
    if (auto *DeclRef =
18307
0
            dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18308
0
      DeclRef->setIsImmediateEscalating(true);
18309
0
  } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18310
0
    Ctr->setIsImmediateEscalating(true);
18311
0
  } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18312
0
    DeclRef->setIsImmediateEscalating(true);
18313
0
  } else {
18314
0
    assert(false && "expected an immediately escalating expression");
18315
0
  }
18316
0
  getCurFunction()->FoundImmediateEscalatingExpression = true;
18317
0
}
18318
18319
0
ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18320
0
  if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18321
0
      !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18322
0
      isCheckingDefaultArgumentOrInitializer() ||
18323
0
      RebuildingImmediateInvocation || isImmediateFunctionContext())
18324
0
    return E;
18325
18326
  /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18327
  /// It's OK if this fails; we'll also remove this in
18328
  /// HandleImmediateInvocations, but catching it here allows us to avoid
18329
  /// walking the AST looking for it in simple cases.
18330
0
  if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18331
0
    if (auto *DeclRef =
18332
0
            dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18333
0
      ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18334
18335
  // C++23 [expr.const]/p16
18336
  // An expression or conversion is immediate-escalating if it is not initially
18337
  // in an immediate function context and it is [...] an immediate invocation
18338
  // that is not a constant expression and is not a subexpression of an
18339
  // immediate invocation.
18340
0
  APValue Cached;
18341
0
  auto CheckConstantExpressionAndKeepResult = [&]() {
18342
0
    llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18343
0
    Expr::EvalResult Eval;
18344
0
    Eval.Diag = &Notes;
18345
0
    bool Res = E.get()->EvaluateAsConstantExpr(
18346
0
        Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18347
0
    if (Res && Notes.empty()) {
18348
0
      Cached = std::move(Eval.Val);
18349
0
      return true;
18350
0
    }
18351
0
    return false;
18352
0
  };
18353
18354
0
  if (!E.get()->isValueDependent() &&
18355
0
      ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18356
0
      !CheckConstantExpressionAndKeepResult()) {
18357
0
    MarkExpressionAsImmediateEscalating(E.get());
18358
0
    return E;
18359
0
  }
18360
18361
0
  if (Cleanup.exprNeedsCleanups()) {
18362
    // Since an immediate invocation is a full expression itself - it requires
18363
    // an additional ExprWithCleanups node, but it can participate to a bigger
18364
    // full expression which actually requires cleanups to be run after so
18365
    // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18366
    // may discard cleanups for outer expression too early.
18367
18368
    // Note that ExprWithCleanups created here must always have empty cleanup
18369
    // objects:
18370
    // - compound literals do not create cleanup objects in C++ and immediate
18371
    // invocations are C++-only.
18372
    // - blocks are not allowed inside constant expressions and compiler will
18373
    // issue an error if they appear there.
18374
    //
18375
    // Hence, in correct code any cleanup objects created inside current
18376
    // evaluation context must be outside the immediate invocation.
18377
0
    E = ExprWithCleanups::Create(getASTContext(), E.get(),
18378
0
                                 Cleanup.cleanupsHaveSideEffects(), {});
18379
0
  }
18380
18381
0
  ConstantExpr *Res = ConstantExpr::Create(
18382
0
      getASTContext(), E.get(),
18383
0
      ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18384
0
                                   getASTContext()),
18385
0
      /*IsImmediateInvocation*/ true);
18386
0
  if (Cached.hasValue())
18387
0
    Res->MoveIntoResult(Cached, getASTContext());
18388
  /// Value-dependent constant expressions should not be immediately
18389
  /// evaluated until they are instantiated.
18390
0
  if (!Res->isValueDependent())
18391
0
    ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18392
0
  return Res;
18393
0
}
18394
18395
static void EvaluateAndDiagnoseImmediateInvocation(
18396
0
    Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18397
0
  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18398
0
  Expr::EvalResult Eval;
18399
0
  Eval.Diag = &Notes;
18400
0
  ConstantExpr *CE = Candidate.getPointer();
18401
0
  bool Result = CE->EvaluateAsConstantExpr(
18402
0
      Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18403
0
  if (!Result || !Notes.empty()) {
18404
0
    SemaRef.FailedImmediateInvocations.insert(CE);
18405
0
    Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18406
0
    if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18407
0
      InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18408
0
    FunctionDecl *FD = nullptr;
18409
0
    if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18410
0
      FD = cast<FunctionDecl>(Call->getCalleeDecl());
18411
0
    else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18412
0
      FD = Call->getConstructor();
18413
0
    else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18414
0
      FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18415
18416
0
    assert(FD && FD->isImmediateFunction() &&
18417
0
           "could not find an immediate function in this expression");
18418
0
    if (FD->isInvalidDecl())
18419
0
      return;
18420
0
    SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18421
0
        << FD << FD->isConsteval();
18422
0
    if (auto Context =
18423
0
            SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18424
0
      SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18425
0
          << Context->Decl;
18426
0
      SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18427
0
    }
18428
0
    if (!FD->isConsteval())
18429
0
      SemaRef.DiagnoseImmediateEscalatingReason(FD);
18430
0
    for (auto &Note : Notes)
18431
0
      SemaRef.Diag(Note.first, Note.second);
18432
0
    return;
18433
0
  }
18434
0
  CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
18435
0
}
18436
18437
static void RemoveNestedImmediateInvocation(
18438
    Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18439
0
    SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18440
0
  struct ComplexRemove : TreeTransform<ComplexRemove> {
18441
0
    using Base = TreeTransform<ComplexRemove>;
18442
0
    llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18443
0
    SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18444
0
    SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18445
0
        CurrentII;
18446
0
    ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18447
0
                  SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18448
0
                  SmallVector<Sema::ImmediateInvocationCandidate,
18449
0
                              4>::reverse_iterator Current)
18450
0
        : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18451
0
    void RemoveImmediateInvocation(ConstantExpr* E) {
18452
0
      auto It = std::find_if(CurrentII, IISet.rend(),
18453
0
                             [E](Sema::ImmediateInvocationCandidate Elem) {
18454
0
                               return Elem.getPointer() == E;
18455
0
                             });
18456
      // It is possible that some subexpression of the current immediate
18457
      // invocation was handled from another expression evaluation context. Do
18458
      // not handle the current immediate invocation if some of its
18459
      // subexpressions failed before.
18460
0
      if (It == IISet.rend()) {
18461
0
        if (SemaRef.FailedImmediateInvocations.contains(E))
18462
0
          CurrentII->setInt(1);
18463
0
      } else {
18464
0
        It->setInt(1); // Mark as deleted
18465
0
      }
18466
0
    }
18467
0
    ExprResult TransformConstantExpr(ConstantExpr *E) {
18468
0
      if (!E->isImmediateInvocation())
18469
0
        return Base::TransformConstantExpr(E);
18470
0
      RemoveImmediateInvocation(E);
18471
0
      return Base::TransformExpr(E->getSubExpr());
18472
0
    }
18473
    /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18474
    /// we need to remove its DeclRefExpr from the DRSet.
18475
0
    ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18476
0
      DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18477
0
      return Base::TransformCXXOperatorCallExpr(E);
18478
0
    }
18479
    /// Base::TransformUserDefinedLiteral doesn't preserve the
18480
    /// UserDefinedLiteral node.
18481
0
    ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18482
    /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18483
    /// here.
18484
0
    ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18485
0
      if (!Init)
18486
0
        return Init;
18487
      /// ConstantExpr are the first layer of implicit node to be removed so if
18488
      /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18489
0
      if (auto *CE = dyn_cast<ConstantExpr>(Init))
18490
0
        if (CE->isImmediateInvocation())
18491
0
          RemoveImmediateInvocation(CE);
18492
0
      return Base::TransformInitializer(Init, NotCopyInit);
18493
0
    }
18494
0
    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18495
0
      DRSet.erase(E);
18496
0
      return E;
18497
0
    }
18498
0
    ExprResult TransformLambdaExpr(LambdaExpr *E) {
18499
      // Do not rebuild lambdas to avoid creating a new type.
18500
      // Lambdas have already been processed inside their eval context.
18501
0
      return E;
18502
0
    }
18503
0
    bool AlwaysRebuild() { return false; }
18504
0
    bool ReplacingOriginal() { return true; }
18505
0
    bool AllowSkippingCXXConstructExpr() {
18506
0
      bool Res = AllowSkippingFirstCXXConstructExpr;
18507
0
      AllowSkippingFirstCXXConstructExpr = true;
18508
0
      return Res;
18509
0
    }
18510
0
    bool AllowSkippingFirstCXXConstructExpr = true;
18511
0
  } Transformer(SemaRef, Rec.ReferenceToConsteval,
18512
0
                Rec.ImmediateInvocationCandidates, It);
18513
18514
  /// CXXConstructExpr with a single argument are getting skipped by
18515
  /// TreeTransform in some situtation because they could be implicit. This
18516
  /// can only occur for the top-level CXXConstructExpr because it is used
18517
  /// nowhere in the expression being transformed therefore will not be rebuilt.
18518
  /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18519
  /// skipping the first CXXConstructExpr.
18520
0
  if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18521
0
    Transformer.AllowSkippingFirstCXXConstructExpr = false;
18522
18523
0
  ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18524
  // The result may not be usable in case of previous compilation errors.
18525
  // In this case evaluation of the expression may result in crash so just
18526
  // don't do anything further with the result.
18527
0
  if (Res.isUsable()) {
18528
0
    Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18529
0
    It->getPointer()->setSubExpr(Res.get());
18530
0
  }
18531
0
}
18532
18533
static void
18534
HandleImmediateInvocations(Sema &SemaRef,
18535
502
                           Sema::ExpressionEvaluationContextRecord &Rec) {
18536
502
  if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18537
502
       Rec.ReferenceToConsteval.size() == 0) ||
18538
502
      SemaRef.RebuildingImmediateInvocation)
18539
502
    return;
18540
18541
  /// When we have more than 1 ImmediateInvocationCandidates or previously
18542
  /// failed immediate invocations, we need to check for nested
18543
  /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18544
  /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18545
  /// invocation.
18546
0
  if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18547
0
      !SemaRef.FailedImmediateInvocations.empty()) {
18548
18549
    /// Prevent sema calls during the tree transform from adding pointers that
18550
    /// are already in the sets.
18551
0
    llvm::SaveAndRestore DisableIITracking(
18552
0
        SemaRef.RebuildingImmediateInvocation, true);
18553
18554
    /// Prevent diagnostic during tree transfrom as they are duplicates
18555
0
    Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18556
18557
0
    for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18558
0
         It != Rec.ImmediateInvocationCandidates.rend(); It++)
18559
0
      if (!It->getInt())
18560
0
        RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18561
0
  } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18562
0
             Rec.ReferenceToConsteval.size()) {
18563
0
    struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18564
0
      llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18565
0
      SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18566
0
      bool VisitDeclRefExpr(DeclRefExpr *E) {
18567
0
        DRSet.erase(E);
18568
0
        return DRSet.size();
18569
0
      }
18570
0
    } Visitor(Rec.ReferenceToConsteval);
18571
0
    Visitor.TraverseStmt(
18572
0
        Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18573
0
  }
18574
0
  for (auto CE : Rec.ImmediateInvocationCandidates)
18575
0
    if (!CE.getInt())
18576
0
      EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18577
0
  for (auto *DR : Rec.ReferenceToConsteval) {
18578
    // If the expression is immediate escalating, it is not an error;
18579
    // The outer context itself becomes immediate and further errors,
18580
    // if any, will be handled by DiagnoseImmediateEscalatingReason.
18581
0
    if (DR->isImmediateEscalating())
18582
0
      continue;
18583
0
    auto *FD = cast<FunctionDecl>(DR->getDecl());
18584
0
    const NamedDecl *ND = FD;
18585
0
    if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18586
0
        MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18587
0
      ND = MD->getParent();
18588
18589
    // C++23 [expr.const]/p16
18590
    // An expression or conversion is immediate-escalating if it is not
18591
    // initially in an immediate function context and it is [...] a
18592
    // potentially-evaluated id-expression that denotes an immediate function
18593
    // that is not a subexpression of an immediate invocation.
18594
0
    bool ImmediateEscalating = false;
18595
0
    bool IsPotentiallyEvaluated =
18596
0
        Rec.Context ==
18597
0
            Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18598
0
        Rec.Context ==
18599
0
            Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18600
0
    if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18601
0
      ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18602
18603
0
    if (!Rec.InImmediateEscalatingFunctionContext ||
18604
0
        (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18605
0
      SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18606
0
          << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18607
0
      SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18608
0
      if (auto Context =
18609
0
              SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18610
0
        SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18611
0
            << Context->Decl;
18612
0
        SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18613
0
      }
18614
0
      if (FD->isImmediateEscalating() && !FD->isConsteval())
18615
0
        SemaRef.DiagnoseImmediateEscalatingReason(FD);
18616
18617
0
    } else {
18618
0
      SemaRef.MarkExpressionAsImmediateEscalating(DR);
18619
0
    }
18620
0
  }
18621
0
}
18622
18623
502
void Sema::PopExpressionEvaluationContext() {
18624
502
  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18625
502
  unsigned NumTypos = Rec.NumTypos;
18626
18627
502
  if (!Rec.Lambdas.empty()) {
18628
0
    using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18629
0
    if (!getLangOpts().CPlusPlus20 &&
18630
0
        (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18631
0
         Rec.isUnevaluated() ||
18632
0
         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18633
0
      unsigned D;
18634
0
      if (Rec.isUnevaluated()) {
18635
        // C++11 [expr.prim.lambda]p2:
18636
        //   A lambda-expression shall not appear in an unevaluated operand
18637
        //   (Clause 5).
18638
0
        D = diag::err_lambda_unevaluated_operand;
18639
0
      } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18640
        // C++1y [expr.const]p2:
18641
        //   A conditional-expression e is a core constant expression unless the
18642
        //   evaluation of e, following the rules of the abstract machine, would
18643
        //   evaluate [...] a lambda-expression.
18644
0
        D = diag::err_lambda_in_constant_expression;
18645
0
      } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18646
        // C++17 [expr.prim.lamda]p2:
18647
        // A lambda-expression shall not appear [...] in a template-argument.
18648
0
        D = diag::err_lambda_in_invalid_context;
18649
0
      } else
18650
0
        llvm_unreachable("Couldn't infer lambda error message.");
18651
18652
0
      for (const auto *L : Rec.Lambdas)
18653
0
        Diag(L->getBeginLoc(), D);
18654
0
    }
18655
0
  }
18656
18657
502
  WarnOnPendingNoDerefs(Rec);
18658
502
  HandleImmediateInvocations(*this, Rec);
18659
18660
  // Warn on any volatile-qualified simple-assignments that are not discarded-
18661
  // value expressions nor unevaluated operands (those cases get removed from
18662
  // this list by CheckUnusedVolatileAssignment).
18663
502
  for (auto *BO : Rec.VolatileAssignmentLHSs)
18664
0
    Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18665
0
        << BO->getType();
18666
18667
  // When are coming out of an unevaluated context, clear out any
18668
  // temporaries that we may have created as part of the evaluation of
18669
  // the expression in that context: they aren't relevant because they
18670
  // will never be constructed.
18671
502
  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18672
450
    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18673
450
                             ExprCleanupObjects.end());
18674
450
    Cleanup = Rec.ParentCleanup;
18675
450
    CleanupVarDeclMarking();
18676
450
    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18677
  // Otherwise, merge the contexts together.
18678
450
  } else {
18679
52
    Cleanup.mergeFrom(Rec.ParentCleanup);
18680
52
    MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18681
52
                            Rec.SavedMaybeODRUseExprs.end());
18682
52
  }
18683
18684
  // Pop the current expression evaluation context off the stack.
18685
502
  ExprEvalContexts.pop_back();
18686
18687
  // The global expression evaluation context record is never popped.
18688
502
  ExprEvalContexts.back().NumTypos += NumTypos;
18689
502
}
18690
18691
6
void Sema::DiscardCleanupsInEvaluationContext() {
18692
6
  ExprCleanupObjects.erase(
18693
6
         ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18694
6
         ExprCleanupObjects.end());
18695
6
  Cleanup.reset();
18696
6
  MaybeODRUseExprs.clear();
18697
6
}
18698
18699
0
ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18700
0
  ExprResult Result = CheckPlaceholderExpr(E);
18701
0
  if (Result.isInvalid())
18702
0
    return ExprError();
18703
0
  E = Result.get();
18704
0
  if (!E->getType()->isVariablyModifiedType())
18705
0
    return E;
18706
0
  return TransformToPotentiallyEvaluated(E);
18707
0
}
18708
18709
/// Are we in a context that is potentially constant evaluated per C++20
18710
/// [expr.const]p12?
18711
17
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18712
  /// C++2a [expr.const]p12:
18713
  //   An expression or conversion is potentially constant evaluated if it is
18714
17
  switch (SemaRef.ExprEvalContexts.back().Context) {
18715
10
    case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18716
10
    case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18717
18718
      // -- a manifestly constant-evaluated expression,
18719
17
    case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18720
17
    case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18721
17
    case Sema::ExpressionEvaluationContext::DiscardedStatement:
18722
      // -- a potentially-evaluated expression,
18723
17
    case Sema::ExpressionEvaluationContext::UnevaluatedList:
18724
      // -- an immediate subexpression of a braced-init-list,
18725
18726
      // -- [FIXME] an expression of the form & cast-expression that occurs
18727
      //    within a templated entity
18728
      // -- a subexpression of one of the above that is not a subexpression of
18729
      // a nested unevaluated operand.
18730
17
      return true;
18731
18732
0
    case Sema::ExpressionEvaluationContext::Unevaluated:
18733
0
    case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18734
      // Expressions in this context are never evaluated.
18735
0
      return false;
18736
17
  }
18737
0
  llvm_unreachable("Invalid context");
18738
0
}
18739
18740
/// Return true if this function has a calling convention that requires mangling
18741
/// in the size of the parameter pack.
18742
0
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18743
  // These manglings don't do anything on non-Windows or non-x86 platforms, so
18744
  // we don't need parameter type sizes.
18745
0
  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18746
0
  if (!TT.isOSWindows() || !TT.isX86())
18747
0
    return false;
18748
18749
  // If this is C++ and this isn't an extern "C" function, parameters do not
18750
  // need to be complete. In this case, C++ mangling will apply, which doesn't
18751
  // use the size of the parameters.
18752
0
  if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18753
0
    return false;
18754
18755
  // Stdcall, fastcall, and vectorcall need this special treatment.
18756
0
  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18757
0
  switch (CC) {
18758
0
  case CC_X86StdCall:
18759
0
  case CC_X86FastCall:
18760
0
  case CC_X86VectorCall:
18761
0
    return true;
18762
0
  default:
18763
0
    break;
18764
0
  }
18765
0
  return false;
18766
0
}
18767
18768
/// Require that all of the parameter types of function be complete. Normally,
18769
/// parameter types are only required to be complete when a function is called
18770
/// or defined, but to mangle functions with certain calling conventions, the
18771
/// mangler needs to know the size of the parameter list. In this situation,
18772
/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18773
/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18774
/// result in a linker error. Clang doesn't implement this behavior, and instead
18775
/// attempts to error at compile time.
18776
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18777
0
                                                  SourceLocation Loc) {
18778
0
  class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18779
0
    FunctionDecl *FD;
18780
0
    ParmVarDecl *Param;
18781
18782
0
  public:
18783
0
    ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18784
0
        : FD(FD), Param(Param) {}
18785
18786
0
    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18787
0
      CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18788
0
      StringRef CCName;
18789
0
      switch (CC) {
18790
0
      case CC_X86StdCall:
18791
0
        CCName = "stdcall";
18792
0
        break;
18793
0
      case CC_X86FastCall:
18794
0
        CCName = "fastcall";
18795
0
        break;
18796
0
      case CC_X86VectorCall:
18797
0
        CCName = "vectorcall";
18798
0
        break;
18799
0
      default:
18800
0
        llvm_unreachable("CC does not need mangling");
18801
0
      }
18802
18803
0
      S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18804
0
          << Param->getDeclName() << FD->getDeclName() << CCName;
18805
0
    }
18806
0
  };
18807
18808
0
  for (ParmVarDecl *Param : FD->parameters()) {
18809
0
    ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18810
0
    S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18811
0
  }
18812
0
}
18813
18814
namespace {
18815
enum class OdrUseContext {
18816
  /// Declarations in this context are not odr-used.
18817
  None,
18818
  /// Declarations in this context are formally odr-used, but this is a
18819
  /// dependent context.
18820
  Dependent,
18821
  /// Declarations in this context are odr-used but not actually used (yet).
18822
  FormallyOdrUsed,
18823
  /// Declarations in this context are used.
18824
  Used
18825
};
18826
}
18827
18828
/// Are we within a context in which references to resolved functions or to
18829
/// variables result in odr-use?
18830
17
static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18831
17
  OdrUseContext Result;
18832
18833
17
  switch (SemaRef.ExprEvalContexts.back().Context) {
18834
0
    case Sema::ExpressionEvaluationContext::Unevaluated:
18835
0
    case Sema::ExpressionEvaluationContext::UnevaluatedList:
18836
0
    case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18837
0
      return OdrUseContext::None;
18838
18839
10
    case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18840
10
    case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18841
17
    case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18842
17
      Result = OdrUseContext::Used;
18843
17
      break;
18844
18845
0
    case Sema::ExpressionEvaluationContext::DiscardedStatement:
18846
0
      Result = OdrUseContext::FormallyOdrUsed;
18847
0
      break;
18848
18849
0
    case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18850
      // A default argument formally results in odr-use, but doesn't actually
18851
      // result in a use in any real sense until it itself is used.
18852
0
      Result = OdrUseContext::FormallyOdrUsed;
18853
0
      break;
18854
17
  }
18855
18856
17
  if (SemaRef.CurContext->isDependentContext())
18857
0
    return OdrUseContext::Dependent;
18858
18859
17
  return Result;
18860
17
}
18861
18862
0
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18863
0
  if (!Func->isConstexpr())
18864
0
    return false;
18865
18866
0
  if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18867
0
    return true;
18868
0
  auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18869
0
  return CCD && CCD->getInheritedConstructor();
18870
0
}
18871
18872
/// Mark a function referenced, and check whether it is odr-used
18873
/// (C++ [basic.def.odr]p2, C99 6.9p3)
18874
void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18875
0
                                  bool MightBeOdrUse) {
18876
0
  assert(Func && "No function?");
18877
18878
0
  Func->setReferenced();
18879
18880
  // Recursive functions aren't really used until they're used from some other
18881
  // context.
18882
0
  bool IsRecursiveCall = CurContext == Func;
18883
18884
  // C++11 [basic.def.odr]p3:
18885
  //   A function whose name appears as a potentially-evaluated expression is
18886
  //   odr-used if it is the unique lookup result or the selected member of a
18887
  //   set of overloaded functions [...].
18888
  //
18889
  // We (incorrectly) mark overload resolution as an unevaluated context, so we
18890
  // can just check that here.
18891
0
  OdrUseContext OdrUse =
18892
0
      MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18893
0
  if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18894
0
    OdrUse = OdrUseContext::FormallyOdrUsed;
18895
18896
  // Trivial default constructors and destructors are never actually used.
18897
  // FIXME: What about other special members?
18898
0
  if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18899
0
      OdrUse == OdrUseContext::Used) {
18900
0
    if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18901
0
      if (Constructor->isDefaultConstructor())
18902
0
        OdrUse = OdrUseContext::FormallyOdrUsed;
18903
0
    if (isa<CXXDestructorDecl>(Func))
18904
0
      OdrUse = OdrUseContext::FormallyOdrUsed;
18905
0
  }
18906
18907
  // C++20 [expr.const]p12:
18908
  //   A function [...] is needed for constant evaluation if it is [...] a
18909
  //   constexpr function that is named by an expression that is potentially
18910
  //   constant evaluated
18911
0
  bool NeededForConstantEvaluation =
18912
0
      isPotentiallyConstantEvaluatedContext(*this) &&
18913
0
      isImplicitlyDefinableConstexprFunction(Func);
18914
18915
  // Determine whether we require a function definition to exist, per
18916
  // C++11 [temp.inst]p3:
18917
  //   Unless a function template specialization has been explicitly
18918
  //   instantiated or explicitly specialized, the function template
18919
  //   specialization is implicitly instantiated when the specialization is
18920
  //   referenced in a context that requires a function definition to exist.
18921
  // C++20 [temp.inst]p7:
18922
  //   The existence of a definition of a [...] function is considered to
18923
  //   affect the semantics of the program if the [...] function is needed for
18924
  //   constant evaluation by an expression
18925
  // C++20 [basic.def.odr]p10:
18926
  //   Every program shall contain exactly one definition of every non-inline
18927
  //   function or variable that is odr-used in that program outside of a
18928
  //   discarded statement
18929
  // C++20 [special]p1:
18930
  //   The implementation will implicitly define [defaulted special members]
18931
  //   if they are odr-used or needed for constant evaluation.
18932
  //
18933
  // Note that we skip the implicit instantiation of templates that are only
18934
  // used in unused default arguments or by recursive calls to themselves.
18935
  // This is formally non-conforming, but seems reasonable in practice.
18936
0
  bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18937
0
                                             NeededForConstantEvaluation);
18938
18939
  // C++14 [temp.expl.spec]p6:
18940
  //   If a template [...] is explicitly specialized then that specialization
18941
  //   shall be declared before the first use of that specialization that would
18942
  //   cause an implicit instantiation to take place, in every translation unit
18943
  //   in which such a use occurs
18944
0
  if (NeedDefinition &&
18945
0
      (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18946
0
       Func->getMemberSpecializationInfo()))
18947
0
    checkSpecializationReachability(Loc, Func);
18948
18949
0
  if (getLangOpts().CUDA)
18950
0
    CheckCUDACall(Loc, Func);
18951
18952
  // If we need a definition, try to create one.
18953
0
  if (NeedDefinition && !Func->getBody()) {
18954
0
    runWithSufficientStackSpace(Loc, [&] {
18955
0
      if (CXXConstructorDecl *Constructor =
18956
0
              dyn_cast<CXXConstructorDecl>(Func)) {
18957
0
        Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18958
0
        if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18959
0
          if (Constructor->isDefaultConstructor()) {
18960
0
            if (Constructor->isTrivial() &&
18961
0
                !Constructor->hasAttr<DLLExportAttr>())
18962
0
              return;
18963
0
            DefineImplicitDefaultConstructor(Loc, Constructor);
18964
0
          } else if (Constructor->isCopyConstructor()) {
18965
0
            DefineImplicitCopyConstructor(Loc, Constructor);
18966
0
          } else if (Constructor->isMoveConstructor()) {
18967
0
            DefineImplicitMoveConstructor(Loc, Constructor);
18968
0
          }
18969
0
        } else if (Constructor->getInheritedConstructor()) {
18970
0
          DefineInheritingConstructor(Loc, Constructor);
18971
0
        }
18972
0
      } else if (CXXDestructorDecl *Destructor =
18973
0
                     dyn_cast<CXXDestructorDecl>(Func)) {
18974
0
        Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18975
0
        if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18976
0
          if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18977
0
            return;
18978
0
          DefineImplicitDestructor(Loc, Destructor);
18979
0
        }
18980
0
        if (Destructor->isVirtual() && getLangOpts().AppleKext)
18981
0
          MarkVTableUsed(Loc, Destructor->getParent());
18982
0
      } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18983
0
        if (MethodDecl->isOverloadedOperator() &&
18984
0
            MethodDecl->getOverloadedOperator() == OO_Equal) {
18985
0
          MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18986
0
          if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18987
0
            if (MethodDecl->isCopyAssignmentOperator())
18988
0
              DefineImplicitCopyAssignment(Loc, MethodDecl);
18989
0
            else if (MethodDecl->isMoveAssignmentOperator())
18990
0
              DefineImplicitMoveAssignment(Loc, MethodDecl);
18991
0
          }
18992
0
        } else if (isa<CXXConversionDecl>(MethodDecl) &&
18993
0
                   MethodDecl->getParent()->isLambda()) {
18994
0
          CXXConversionDecl *Conversion =
18995
0
              cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18996
0
          if (Conversion->isLambdaToBlockPointerConversion())
18997
0
            DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18998
0
          else
18999
0
            DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
19000
0
        } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19001
0
          MarkVTableUsed(Loc, MethodDecl->getParent());
19002
0
      }
19003
19004
0
      if (Func->isDefaulted() && !Func->isDeleted()) {
19005
0
        DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
19006
0
        if (DCK != DefaultedComparisonKind::None)
19007
0
          DefineDefaultedComparison(Loc, Func, DCK);
19008
0
      }
19009
19010
      // Implicit instantiation of function templates and member functions of
19011
      // class templates.
19012
0
      if (Func->isImplicitlyInstantiable()) {
19013
0
        TemplateSpecializationKind TSK =
19014
0
            Func->getTemplateSpecializationKindForInstantiation();
19015
0
        SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19016
0
        bool FirstInstantiation = PointOfInstantiation.isInvalid();
19017
0
        if (FirstInstantiation) {
19018
0
          PointOfInstantiation = Loc;
19019
0
          if (auto *MSI = Func->getMemberSpecializationInfo())
19020
0
            MSI->setPointOfInstantiation(Loc);
19021
            // FIXME: Notify listener.
19022
0
          else
19023
0
            Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19024
0
        } else if (TSK != TSK_ImplicitInstantiation) {
19025
          // Use the point of use as the point of instantiation, instead of the
19026
          // point of explicit instantiation (which we track as the actual point
19027
          // of instantiation). This gives better backtraces in diagnostics.
19028
0
          PointOfInstantiation = Loc;
19029
0
        }
19030
19031
0
        if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19032
0
            Func->isConstexpr()) {
19033
0
          if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19034
0
              cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19035
0
              CodeSynthesisContexts.size())
19036
0
            PendingLocalImplicitInstantiations.push_back(
19037
0
                std::make_pair(Func, PointOfInstantiation));
19038
0
          else if (Func->isConstexpr())
19039
            // Do not defer instantiations of constexpr functions, to avoid the
19040
            // expression evaluator needing to call back into Sema if it sees a
19041
            // call to such a function.
19042
0
            InstantiateFunctionDefinition(PointOfInstantiation, Func);
19043
0
          else {
19044
0
            Func->setInstantiationIsPending(true);
19045
0
            PendingInstantiations.push_back(
19046
0
                std::make_pair(Func, PointOfInstantiation));
19047
            // Notify the consumer that a function was implicitly instantiated.
19048
0
            Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19049
0
          }
19050
0
        }
19051
0
      } else {
19052
        // Walk redefinitions, as some of them may be instantiable.
19053
0
        for (auto *i : Func->redecls()) {
19054
0
          if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19055
0
            MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19056
0
        }
19057
0
      }
19058
0
    });
19059
0
  }
19060
19061
  // If a constructor was defined in the context of a default parameter
19062
  // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19063
  // context), its initializers may not be referenced yet.
19064
0
  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19065
0
    EnterExpressionEvaluationContext EvalContext(
19066
0
        *this,
19067
0
        Constructor->isImmediateFunction()
19068
0
            ? ExpressionEvaluationContext::ImmediateFunctionContext
19069
0
            : ExpressionEvaluationContext::PotentiallyEvaluated,
19070
0
        Constructor);
19071
0
    for (CXXCtorInitializer *Init : Constructor->inits()) {
19072
0
      if (Init->isInClassMemberInitializer())
19073
0
        runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19074
0
          MarkDeclarationsReferencedInExpr(Init->getInit());
19075
0
        });
19076
0
    }
19077
0
  }
19078
19079
  // C++14 [except.spec]p17:
19080
  //   An exception-specification is considered to be needed when:
19081
  //   - the function is odr-used or, if it appears in an unevaluated operand,
19082
  //     would be odr-used if the expression were potentially-evaluated;
19083
  //
19084
  // Note, we do this even if MightBeOdrUse is false. That indicates that the
19085
  // function is a pure virtual function we're calling, and in that case the
19086
  // function was selected by overload resolution and we need to resolve its
19087
  // exception specification for a different reason.
19088
0
  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19089
0
  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
19090
0
    ResolveExceptionSpec(Loc, FPT);
19091
19092
  // A callee could be called by a host function then by a device function.
19093
  // If we only try recording once, we will miss recording the use on device
19094
  // side. Therefore keep trying until it is recorded.
19095
0
  if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19096
0
      !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19097
0
    CUDARecordImplicitHostDeviceFuncUsedByDevice(Func);
19098
19099
  // If this is the first "real" use, act on that.
19100
0
  if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19101
    // Keep track of used but undefined functions.
19102
0
    if (!Func->isDefined()) {
19103
0
      if (mightHaveNonExternalLinkage(Func))
19104
0
        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19105
0
      else if (Func->getMostRecentDecl()->isInlined() &&
19106
0
               !LangOpts.GNUInline &&
19107
0
               !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19108
0
        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19109
0
      else if (isExternalWithNoLinkageType(Func))
19110
0
        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19111
0
    }
19112
19113
    // Some x86 Windows calling conventions mangle the size of the parameter
19114
    // pack into the name. Computing the size of the parameters requires the
19115
    // parameter types to be complete. Check that now.
19116
0
    if (funcHasParameterSizeMangling(*this, Func))
19117
0
      CheckCompleteParameterTypesForMangler(*this, Func, Loc);
19118
19119
    // In the MS C++ ABI, the compiler emits destructor variants where they are
19120
    // used. If the destructor is used here but defined elsewhere, mark the
19121
    // virtual base destructors referenced. If those virtual base destructors
19122
    // are inline, this will ensure they are defined when emitting the complete
19123
    // destructor variant. This checking may be redundant if the destructor is
19124
    // provided later in this TU.
19125
0
    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19126
0
      if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19127
0
        CXXRecordDecl *Parent = Dtor->getParent();
19128
0
        if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19129
0
          CheckCompleteDestructorVariant(Loc, Dtor);
19130
0
      }
19131
0
    }
19132
19133
0
    Func->markUsed(Context);
19134
0
  }
19135
0
}
19136
19137
/// Directly mark a variable odr-used. Given a choice, prefer to use
19138
/// MarkVariableReferenced since it does additional checks and then
19139
/// calls MarkVarDeclODRUsed.
19140
/// If the variable must be captured:
19141
///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19142
///  - else capture it in the DeclContext that maps to the
19143
///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19144
static void
19145
MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19146
17
                   const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19147
  // Keep track of used but undefined variables.
19148
  // FIXME: We shouldn't suppress this warning for static data members.
19149
17
  VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19150
17
  assert(Var && "expected a capturable variable");
19151
19152
17
  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19153
17
      (!Var->isExternallyVisible() || Var->isInline() ||
19154
0
       SemaRef.isExternalWithNoLinkageType(Var)) &&
19155
17
      !(Var->isStaticDataMember() && Var->hasInit())) {
19156
0
    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19157
0
    if (old.isInvalid())
19158
0
      old = Loc;
19159
0
  }
19160
17
  QualType CaptureType, DeclRefType;
19161
17
  if (SemaRef.LangOpts.OpenMP)
19162
0
    SemaRef.tryCaptureOpenMPLambdas(V);
19163
17
  SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
19164
17
                             /*EllipsisLoc*/ SourceLocation(),
19165
17
                             /*BuildAndDiagnose*/ true, CaptureType,
19166
17
                             DeclRefType, FunctionScopeIndexToStopAt);
19167
19168
17
  if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19169
0
    auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19170
0
    auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
19171
0
    auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
19172
0
    if (VarTarget == Sema::CVT_Host &&
19173
0
        (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
19174
0
         UserTarget == Sema::CFT_Global)) {
19175
      // Diagnose ODR-use of host global variables in device functions.
19176
      // Reference of device global variables in host functions is allowed
19177
      // through shadow variables therefore it is not diagnosed.
19178
0
      if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19179
0
        SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19180
0
            << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19181
0
        SemaRef.targetDiag(Var->getLocation(),
19182
0
                           Var->getType().isConstQualified()
19183
0
                               ? diag::note_cuda_const_var_unpromoted
19184
0
                               : diag::note_cuda_host_var);
19185
0
      }
19186
0
    } else if (VarTarget == Sema::CVT_Device &&
19187
0
               !Var->hasAttr<CUDASharedAttr>() &&
19188
0
               (UserTarget == Sema::CFT_Host ||
19189
0
                UserTarget == Sema::CFT_HostDevice)) {
19190
      // Record a CUDA/HIP device side variable if it is ODR-used
19191
      // by host code. This is done conservatively, when the variable is
19192
      // referenced in any of the following contexts:
19193
      //   - a non-function context
19194
      //   - a host function
19195
      //   - a host device function
19196
      // This makes the ODR-use of the device side variable by host code to
19197
      // be visible in the device compilation for the compiler to be able to
19198
      // emit template variables instantiated by host code only and to
19199
      // externalize the static device side variable ODR-used by host code.
19200
0
      if (!Var->hasExternalStorage())
19201
0
        SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
19202
0
      else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
19203
0
        SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
19204
0
    }
19205
0
  }
19206
19207
17
  V->markUsed(SemaRef.Context);
19208
17
}
19209
19210
void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19211
                                             SourceLocation Loc,
19212
0
                                             unsigned CapturingScopeIndex) {
19213
0
  MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19214
0
}
19215
19216
void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
19217
0
                                                 ValueDecl *var) {
19218
0
  DeclContext *VarDC = var->getDeclContext();
19219
19220
  //  If the parameter still belongs to the translation unit, then
19221
  //  we're actually just using one parameter in the declaration of
19222
  //  the next.
19223
0
  if (isa<ParmVarDecl>(var) &&
19224
0
      isa<TranslationUnitDecl>(VarDC))
19225
0
    return;
19226
19227
  // For C code, don't diagnose about capture if we're not actually in code
19228
  // right now; it's impossible to write a non-constant expression outside of
19229
  // function context, so we'll get other (more useful) diagnostics later.
19230
  //
19231
  // For C++, things get a bit more nasty... it would be nice to suppress this
19232
  // diagnostic for certain cases like using a local variable in an array bound
19233
  // for a member of a local class, but the correct predicate is not obvious.
19234
0
  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19235
0
    return;
19236
19237
0
  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19238
0
  unsigned ContextKind = 3; // unknown
19239
0
  if (isa<CXXMethodDecl>(VarDC) &&
19240
0
      cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19241
0
    ContextKind = 2;
19242
0
  } else if (isa<FunctionDecl>(VarDC)) {
19243
0
    ContextKind = 0;
19244
0
  } else if (isa<BlockDecl>(VarDC)) {
19245
0
    ContextKind = 1;
19246
0
  }
19247
19248
0
  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19249
0
    << var << ValueKind << ContextKind << VarDC;
19250
0
  S.Diag(var->getLocation(), diag::note_entity_declared_at)
19251
0
      << var;
19252
19253
  // FIXME: Add additional diagnostic info about class etc. which prevents
19254
  // capture.
19255
0
}
19256
19257
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19258
                                                 ValueDecl *Var,
19259
                                                 bool &SubCapturesAreNested,
19260
                                                 QualType &CaptureType,
19261
0
                                                 QualType &DeclRefType) {
19262
  // Check whether we've already captured it.
19263
0
  if (CSI->CaptureMap.count(Var)) {
19264
    // If we found a capture, any subcaptures are nested.
19265
0
    SubCapturesAreNested = true;
19266
19267
    // Retrieve the capture type for this variable.
19268
0
    CaptureType = CSI->getCapture(Var).getCaptureType();
19269
19270
    // Compute the type of an expression that refers to this variable.
19271
0
    DeclRefType = CaptureType.getNonReferenceType();
19272
19273
    // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19274
    // are mutable in the sense that user can change their value - they are
19275
    // private instances of the captured declarations.
19276
0
    const Capture &Cap = CSI->getCapture(Var);
19277
0
    if (Cap.isCopyCapture() &&
19278
0
        !(isa<LambdaScopeInfo>(CSI) &&
19279
0
          !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19280
0
        !(isa<CapturedRegionScopeInfo>(CSI) &&
19281
0
          cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19282
0
      DeclRefType.addConst();
19283
0
    return true;
19284
0
  }
19285
0
  return false;
19286
0
}
19287
19288
// Only block literals, captured statements, and lambda expressions can
19289
// capture; other scopes don't work.
19290
static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19291
                                                      ValueDecl *Var,
19292
                                                      SourceLocation Loc,
19293
                                                      const bool Diagnose,
19294
0
                                                      Sema &S) {
19295
0
  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
19296
0
    return getLambdaAwareParentOfDeclContext(DC);
19297
19298
0
  VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19299
0
  if (Underlying) {
19300
0
    if (Underlying->hasLocalStorage() && Diagnose)
19301
0
      diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19302
0
  }
19303
0
  return nullptr;
19304
0
}
19305
19306
// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19307
// certain types of variables (unnamed, variably modified types etc.)
19308
// so check for eligibility.
19309
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19310
                                 SourceLocation Loc, const bool Diagnose,
19311
0
                                 Sema &S) {
19312
19313
0
  assert((isa<VarDecl, BindingDecl>(Var)) &&
19314
0
         "Only variables and structured bindings can be captured");
19315
19316
0
  bool IsBlock = isa<BlockScopeInfo>(CSI);
19317
0
  bool IsLambda = isa<LambdaScopeInfo>(CSI);
19318
19319
  // Lambdas are not allowed to capture unnamed variables
19320
  // (e.g. anonymous unions).
19321
  // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19322
  // assuming that's the intent.
19323
0
  if (IsLambda && !Var->getDeclName()) {
19324
0
    if (Diagnose) {
19325
0
      S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19326
0
      S.Diag(Var->getLocation(), diag::note_declared_at);
19327
0
    }
19328
0
    return false;
19329
0
  }
19330
19331
  // Prohibit variably-modified types in blocks; they're difficult to deal with.
19332
0
  if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19333
0
    if (Diagnose) {
19334
0
      S.Diag(Loc, diag::err_ref_vm_type);
19335
0
      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19336
0
    }
19337
0
    return false;
19338
0
  }
19339
  // Prohibit structs with flexible array members too.
19340
  // We cannot capture what is in the tail end of the struct.
19341
0
  if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
19342
0
    if (VTTy->getDecl()->hasFlexibleArrayMember()) {
19343
0
      if (Diagnose) {
19344
0
        if (IsBlock)
19345
0
          S.Diag(Loc, diag::err_ref_flexarray_type);
19346
0
        else
19347
0
          S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19348
0
        S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19349
0
      }
19350
0
      return false;
19351
0
    }
19352
0
  }
19353
0
  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19354
  // Lambdas and captured statements are not allowed to capture __block
19355
  // variables; they don't support the expected semantics.
19356
0
  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19357
0
    if (Diagnose) {
19358
0
      S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19359
0
      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19360
0
    }
19361
0
    return false;
19362
0
  }
19363
  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19364
0
  if (S.getLangOpts().OpenCL && IsBlock &&
19365
0
      Var->getType()->isBlockPointerType()) {
19366
0
    if (Diagnose)
19367
0
      S.Diag(Loc, diag::err_opencl_block_ref_block);
19368
0
    return false;
19369
0
  }
19370
19371
0
  if (isa<BindingDecl>(Var)) {
19372
0
    if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19373
0
      if (Diagnose)
19374
0
        diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19375
0
      return false;
19376
0
    } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19377
0
      S.Diag(Loc, S.LangOpts.CPlusPlus20
19378
0
                      ? diag::warn_cxx17_compat_capture_binding
19379
0
                      : diag::ext_capture_binding)
19380
0
          << Var;
19381
0
      S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19382
0
    }
19383
0
  }
19384
19385
0
  return true;
19386
0
}
19387
19388
// Returns true if the capture by block was successful.
19389
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19390
                           SourceLocation Loc, const bool BuildAndDiagnose,
19391
                           QualType &CaptureType, QualType &DeclRefType,
19392
0
                           const bool Nested, Sema &S, bool Invalid) {
19393
0
  bool ByRef = false;
19394
19395
  // Blocks are not allowed to capture arrays, excepting OpenCL.
19396
  // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19397
  // (decayed to pointers).
19398
0
  if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19399
0
    if (BuildAndDiagnose) {
19400
0
      S.Diag(Loc, diag::err_ref_array_type);
19401
0
      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19402
0
      Invalid = true;
19403
0
    } else {
19404
0
      return false;
19405
0
    }
19406
0
  }
19407
19408
  // Forbid the block-capture of autoreleasing variables.
19409
0
  if (!Invalid &&
19410
0
      CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19411
0
    if (BuildAndDiagnose) {
19412
0
      S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19413
0
        << /*block*/ 0;
19414
0
      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19415
0
      Invalid = true;
19416
0
    } else {
19417
0
      return false;
19418
0
    }
19419
0
  }
19420
19421
  // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19422
0
  if (const auto *PT = CaptureType->getAs<PointerType>()) {
19423
0
    QualType PointeeTy = PT->getPointeeType();
19424
19425
0
    if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19426
0
        PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19427
0
        !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19428
0
      if (BuildAndDiagnose) {
19429
0
        SourceLocation VarLoc = Var->getLocation();
19430
0
        S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19431
0
        S.Diag(VarLoc, diag::note_declare_parameter_strong);
19432
0
      }
19433
0
    }
19434
0
  }
19435
19436
0
  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19437
0
  if (HasBlocksAttr || CaptureType->isReferenceType() ||
19438
0
      (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
19439
    // Block capture by reference does not change the capture or
19440
    // declaration reference types.
19441
0
    ByRef = true;
19442
0
  } else {
19443
    // Block capture by copy introduces 'const'.
19444
0
    CaptureType = CaptureType.getNonReferenceType().withConst();
19445
0
    DeclRefType = CaptureType;
19446
0
  }
19447
19448
  // Actually capture the variable.
19449
0
  if (BuildAndDiagnose)
19450
0
    BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19451
0
                    CaptureType, Invalid);
19452
19453
0
  return !Invalid;
19454
0
}
19455
19456
/// Capture the given variable in the captured region.
19457
static bool captureInCapturedRegion(
19458
    CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19459
    const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19460
    const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
19461
0
    bool IsTopScope, Sema &S, bool Invalid) {
19462
  // By default, capture variables by reference.
19463
0
  bool ByRef = true;
19464
0
  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19465
0
    ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19466
0
  } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19467
    // Using an LValue reference type is consistent with Lambdas (see below).
19468
0
    if (S.isOpenMPCapturedDecl(Var)) {
19469
0
      bool HasConst = DeclRefType.isConstQualified();
19470
0
      DeclRefType = DeclRefType.getUnqualifiedType();
19471
      // Don't lose diagnostics about assignments to const.
19472
0
      if (HasConst)
19473
0
        DeclRefType.addConst();
19474
0
    }
19475
    // Do not capture firstprivates in tasks.
19476
0
    if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
19477
0
        OMPC_unknown)
19478
0
      return true;
19479
0
    ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19480
0
                                    RSI->OpenMPCaptureLevel);
19481
0
  }
19482
19483
0
  if (ByRef)
19484
0
    CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19485
0
  else
19486
0
    CaptureType = DeclRefType;
19487
19488
  // Actually capture the variable.
19489
0
  if (BuildAndDiagnose)
19490
0
    RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19491
0
                    Loc, SourceLocation(), CaptureType, Invalid);
19492
19493
0
  return !Invalid;
19494
0
}
19495
19496
/// Capture the given variable in the lambda.
19497
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19498
                            SourceLocation Loc, const bool BuildAndDiagnose,
19499
                            QualType &CaptureType, QualType &DeclRefType,
19500
                            const bool RefersToCapturedVariable,
19501
                            const Sema::TryCaptureKind Kind,
19502
                            SourceLocation EllipsisLoc, const bool IsTopScope,
19503
0
                            Sema &S, bool Invalid) {
19504
  // Determine whether we are capturing by reference or by value.
19505
0
  bool ByRef = false;
19506
0
  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19507
0
    ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19508
0
  } else {
19509
0
    ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19510
0
  }
19511
19512
0
  BindingDecl *BD = dyn_cast<BindingDecl>(Var);
19513
  // FIXME: We should support capturing structured bindings in OpenMP.
19514
0
  if (!Invalid && BD && S.LangOpts.OpenMP) {
19515
0
    if (BuildAndDiagnose) {
19516
0
      S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
19517
0
      S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19518
0
    }
19519
0
    Invalid = true;
19520
0
  }
19521
19522
0
  if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19523
0
      CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19524
0
    S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19525
0
    Invalid = true;
19526
0
  }
19527
19528
  // Compute the type of the field that will capture this variable.
19529
0
  if (ByRef) {
19530
    // C++11 [expr.prim.lambda]p15:
19531
    //   An entity is captured by reference if it is implicitly or
19532
    //   explicitly captured but not captured by copy. It is
19533
    //   unspecified whether additional unnamed non-static data
19534
    //   members are declared in the closure type for entities
19535
    //   captured by reference.
19536
    //
19537
    // FIXME: It is not clear whether we want to build an lvalue reference
19538
    // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19539
    // to do the former, while EDG does the latter. Core issue 1249 will
19540
    // clarify, but for now we follow GCC because it's a more permissive and
19541
    // easily defensible position.
19542
0
    CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19543
0
  } else {
19544
    // C++11 [expr.prim.lambda]p14:
19545
    //   For each entity captured by copy, an unnamed non-static
19546
    //   data member is declared in the closure type. The
19547
    //   declaration order of these members is unspecified. The type
19548
    //   of such a data member is the type of the corresponding
19549
    //   captured entity if the entity is not a reference to an
19550
    //   object, or the referenced type otherwise. [Note: If the
19551
    //   captured entity is a reference to a function, the
19552
    //   corresponding data member is also a reference to a
19553
    //   function. - end note ]
19554
0
    if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19555
0
      if (!RefType->getPointeeType()->isFunctionType())
19556
0
        CaptureType = RefType->getPointeeType();
19557
0
    }
19558
19559
    // Forbid the lambda copy-capture of autoreleasing variables.
19560
0
    if (!Invalid &&
19561
0
        CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19562
0
      if (BuildAndDiagnose) {
19563
0
        S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19564
0
        S.Diag(Var->getLocation(), diag::note_previous_decl)
19565
0
          << Var->getDeclName();
19566
0
        Invalid = true;
19567
0
      } else {
19568
0
        return false;
19569
0
      }
19570
0
    }
19571
19572
    // Make sure that by-copy captures are of a complete and non-abstract type.
19573
0
    if (!Invalid && BuildAndDiagnose) {
19574
0
      if (!CaptureType->isDependentType() &&
19575
0
          S.RequireCompleteSizedType(
19576
0
              Loc, CaptureType,
19577
0
              diag::err_capture_of_incomplete_or_sizeless_type,
19578
0
              Var->getDeclName()))
19579
0
        Invalid = true;
19580
0
      else if (S.RequireNonAbstractType(Loc, CaptureType,
19581
0
                                        diag::err_capture_of_abstract_type))
19582
0
        Invalid = true;
19583
0
    }
19584
0
  }
19585
19586
  // Compute the type of a reference to this captured variable.
19587
0
  if (ByRef)
19588
0
    DeclRefType = CaptureType.getNonReferenceType();
19589
0
  else {
19590
    // C++ [expr.prim.lambda]p5:
19591
    //   The closure type for a lambda-expression has a public inline
19592
    //   function call operator [...]. This function call operator is
19593
    //   declared const (9.3.1) if and only if the lambda-expression's
19594
    //   parameter-declaration-clause is not followed by mutable.
19595
0
    DeclRefType = CaptureType.getNonReferenceType();
19596
0
    bool Const = LSI->lambdaCaptureShouldBeConst();
19597
0
    if (Const && !CaptureType->isReferenceType())
19598
0
      DeclRefType.addConst();
19599
0
  }
19600
19601
  // Add the capture.
19602
0
  if (BuildAndDiagnose)
19603
0
    LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19604
0
                    Loc, EllipsisLoc, CaptureType, Invalid);
19605
19606
0
  return !Invalid;
19607
0
}
19608
19609
static bool canCaptureVariableByCopy(ValueDecl *Var,
19610
0
                                     const ASTContext &Context) {
19611
  // Offer a Copy fix even if the type is dependent.
19612
0
  if (Var->getType()->isDependentType())
19613
0
    return true;
19614
0
  QualType T = Var->getType().getNonReferenceType();
19615
0
  if (T.isTriviallyCopyableType(Context))
19616
0
    return true;
19617
0
  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19618
19619
0
    if (!(RD = RD->getDefinition()))
19620
0
      return false;
19621
0
    if (RD->hasSimpleCopyConstructor())
19622
0
      return true;
19623
0
    if (RD->hasUserDeclaredCopyConstructor())
19624
0
      for (CXXConstructorDecl *Ctor : RD->ctors())
19625
0
        if (Ctor->isCopyConstructor())
19626
0
          return !Ctor->isDeleted();
19627
0
  }
19628
0
  return false;
19629
0
}
19630
19631
/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19632
/// default capture. Fixes may be omitted if they aren't allowed by the
19633
/// standard, for example we can't emit a default copy capture fix-it if we
19634
/// already explicitly copy capture capture another variable.
19635
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19636
0
                                    ValueDecl *Var) {
19637
0
  assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19638
  // Don't offer Capture by copy of default capture by copy fixes if Var is
19639
  // known not to be copy constructible.
19640
0
  bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19641
19642
0
  SmallString<32> FixBuffer;
19643
0
  StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19644
0
  if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19645
0
    SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19646
0
    if (ShouldOfferCopyFix) {
19647
      // Offer fixes to insert an explicit capture for the variable.
19648
      // [] -> [VarName]
19649
      // [OtherCapture] -> [OtherCapture, VarName]
19650
0
      FixBuffer.assign({Separator, Var->getName()});
19651
0
      Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19652
0
          << Var << /*value*/ 0
19653
0
          << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19654
0
    }
19655
    // As above but capture by reference.
19656
0
    FixBuffer.assign({Separator, "&", Var->getName()});
19657
0
    Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19658
0
        << Var << /*reference*/ 1
19659
0
        << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19660
0
  }
19661
19662
  // Only try to offer default capture if there are no captures excluding this
19663
  // and init captures.
19664
  // [this]: OK.
19665
  // [X = Y]: OK.
19666
  // [&A, &B]: Don't offer.
19667
  // [A, B]: Don't offer.
19668
0
  if (llvm::any_of(LSI->Captures, [](Capture &C) {
19669
0
        return !C.isThisCapture() && !C.isInitCapture();
19670
0
      }))
19671
0
    return;
19672
19673
  // The default capture specifiers, '=' or '&', must appear first in the
19674
  // capture body.
19675
0
  SourceLocation DefaultInsertLoc =
19676
0
      LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19677
19678
0
  if (ShouldOfferCopyFix) {
19679
0
    bool CanDefaultCopyCapture = true;
19680
    // [=, *this] OK since c++17
19681
    // [=, this] OK since c++20
19682
0
    if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19683
0
      CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19684
0
                                  ? LSI->getCXXThisCapture().isCopyCapture()
19685
0
                                  : false;
19686
    // We can't use default capture by copy if any captures already specified
19687
    // capture by copy.
19688
0
    if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19689
0
          return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19690
0
        })) {
19691
0
      FixBuffer.assign({"=", Separator});
19692
0
      Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19693
0
          << /*value*/ 0
19694
0
          << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19695
0
    }
19696
0
  }
19697
19698
  // We can't use default capture by reference if any captures already specified
19699
  // capture by reference.
19700
0
  if (llvm::none_of(LSI->Captures, [](Capture &C) {
19701
0
        return !C.isInitCapture() && C.isReferenceCapture() &&
19702
0
               !C.isThisCapture();
19703
0
      })) {
19704
0
    FixBuffer.assign({"&", Separator});
19705
0
    Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19706
0
        << /*reference*/ 1
19707
0
        << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19708
0
  }
19709
0
}
19710
19711
bool Sema::tryCaptureVariable(
19712
    ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19713
    SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19714
135
    QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19715
  // An init-capture is notionally from the context surrounding its
19716
  // declaration, but its parent DC is the lambda class.
19717
135
  DeclContext *VarDC = Var->getDeclContext();
19718
135
  DeclContext *DC = CurContext;
19719
19720
  // tryCaptureVariable is called every time a DeclRef is formed,
19721
  // it can therefore have non-negigible impact on performances.
19722
  // For local variables and when there is no capturing scope,
19723
  // we can bailout early.
19724
135
  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19725
133
    return true;
19726
19727
2
  const auto *VD = dyn_cast<VarDecl>(Var);
19728
2
  if (VD) {
19729
2
    if (VD->isInitCapture())
19730
0
      VarDC = VarDC->getParent();
19731
2
  } else {
19732
0
    VD = Var->getPotentiallyDecomposedVarDecl();
19733
0
  }
19734
2
  assert(VD && "Cannot capture a null variable");
19735
19736
2
  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19737
2
      ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19738
  // We need to sync up the Declaration Context with the
19739
  // FunctionScopeIndexToStopAt
19740
2
  if (FunctionScopeIndexToStopAt) {
19741
0
    unsigned FSIndex = FunctionScopes.size() - 1;
19742
0
    while (FSIndex != MaxFunctionScopesIndex) {
19743
0
      DC = getLambdaAwareParentOfDeclContext(DC);
19744
0
      --FSIndex;
19745
0
    }
19746
0
  }
19747
19748
  // Capture global variables if it is required to use private copy of this
19749
  // variable.
19750
2
  bool IsGlobal = !VD->hasLocalStorage();
19751
2
  if (IsGlobal &&
19752
2
      !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19753
0
                                                MaxFunctionScopesIndex)))
19754
2
    return true;
19755
19756
0
  if (isa<VarDecl>(Var))
19757
0
    Var = cast<VarDecl>(Var->getCanonicalDecl());
19758
19759
  // Walk up the stack to determine whether we can capture the variable,
19760
  // performing the "simple" checks that don't depend on type. We stop when
19761
  // we've either hit the declared scope of the variable or find an existing
19762
  // capture of that variable.  We start from the innermost capturing-entity
19763
  // (the DC) and ensure that all intervening capturing-entities
19764
  // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19765
  // declcontext can either capture the variable or have already captured
19766
  // the variable.
19767
0
  CaptureType = Var->getType();
19768
0
  DeclRefType = CaptureType.getNonReferenceType();
19769
0
  bool Nested = false;
19770
0
  bool Explicit = (Kind != TryCapture_Implicit);
19771
0
  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19772
0
  do {
19773
19774
0
    LambdaScopeInfo *LSI = nullptr;
19775
0
    if (!FunctionScopes.empty())
19776
0
      LSI = dyn_cast_or_null<LambdaScopeInfo>(
19777
0
          FunctionScopes[FunctionScopesIndex]);
19778
19779
0
    bool IsInScopeDeclarationContext =
19780
0
        !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19781
19782
0
    if (LSI && !LSI->AfterParameterList) {
19783
      // This allows capturing parameters from a default value which does not
19784
      // seems correct
19785
0
      if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19786
0
        return true;
19787
0
    }
19788
    // If the variable is declared in the current context, there is no need to
19789
    // capture it.
19790
0
    if (IsInScopeDeclarationContext &&
19791
0
        FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19792
0
      return true;
19793
19794
    // Only block literals, captured statements, and lambda expressions can
19795
    // capture; other scopes don't work.
19796
0
    DeclContext *ParentDC =
19797
0
        !IsInScopeDeclarationContext
19798
0
            ? DC->getParent()
19799
0
            : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19800
0
                                                BuildAndDiagnose, *this);
19801
    // We need to check for the parent *first* because, if we *have*
19802
    // private-captured a global variable, we need to recursively capture it in
19803
    // intermediate blocks, lambdas, etc.
19804
0
    if (!ParentDC) {
19805
0
      if (IsGlobal) {
19806
0
        FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19807
0
        break;
19808
0
      }
19809
0
      return true;
19810
0
    }
19811
19812
0
    FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
19813
0
    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19814
19815
    // Check whether we've already captured it.
19816
0
    if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19817
0
                                             DeclRefType)) {
19818
0
      CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19819
0
      break;
19820
0
    }
19821
19822
    // When evaluating some attributes (like enable_if) we might refer to a
19823
    // function parameter appertaining to the same declaration as that
19824
    // attribute.
19825
0
    if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19826
0
        Parm && Parm->getDeclContext() == DC)
19827
0
      return true;
19828
19829
    // If we are instantiating a generic lambda call operator body,
19830
    // we do not want to capture new variables.  What was captured
19831
    // during either a lambdas transformation or initial parsing
19832
    // should be used.
19833
0
    if (isGenericLambdaCallOperatorSpecialization(DC)) {
19834
0
      if (BuildAndDiagnose) {
19835
0
        LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19836
0
        if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19837
0
          Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19838
0
          Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19839
0
          Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19840
0
          buildLambdaCaptureFixit(*this, LSI, Var);
19841
0
        } else
19842
0
          diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19843
0
      }
19844
0
      return true;
19845
0
    }
19846
19847
    // Try to capture variable-length arrays types.
19848
0
    if (Var->getType()->isVariablyModifiedType()) {
19849
      // We're going to walk down into the type and look for VLA
19850
      // expressions.
19851
0
      QualType QTy = Var->getType();
19852
0
      if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19853
0
        QTy = PVD->getOriginalType();
19854
0
      captureVariablyModifiedType(Context, QTy, CSI);
19855
0
    }
19856
19857
0
    if (getLangOpts().OpenMP) {
19858
0
      if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19859
        // OpenMP private variables should not be captured in outer scope, so
19860
        // just break here. Similarly, global variables that are captured in a
19861
        // target region should not be captured outside the scope of the region.
19862
0
        if (RSI->CapRegionKind == CR_OpenMP) {
19863
0
          OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19864
0
              Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19865
          // If the variable is private (i.e. not captured) and has variably
19866
          // modified type, we still need to capture the type for correct
19867
          // codegen in all regions, associated with the construct. Currently,
19868
          // it is captured in the innermost captured region only.
19869
0
          if (IsOpenMPPrivateDecl != OMPC_unknown &&
19870
0
              Var->getType()->isVariablyModifiedType()) {
19871
0
            QualType QTy = Var->getType();
19872
0
            if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19873
0
              QTy = PVD->getOriginalType();
19874
0
            for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19875
0
                 I < E; ++I) {
19876
0
              auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19877
0
                  FunctionScopes[FunctionScopesIndex - I]);
19878
0
              assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19879
0
                     "Wrong number of captured regions associated with the "
19880
0
                     "OpenMP construct.");
19881
0
              captureVariablyModifiedType(Context, QTy, OuterRSI);
19882
0
            }
19883
0
          }
19884
0
          bool IsTargetCap =
19885
0
              IsOpenMPPrivateDecl != OMPC_private &&
19886
0
              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19887
0
                                         RSI->OpenMPCaptureLevel);
19888
          // Do not capture global if it is not privatized in outer regions.
19889
0
          bool IsGlobalCap =
19890
0
              IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19891
0
                                                     RSI->OpenMPCaptureLevel);
19892
19893
          // When we detect target captures we are looking from inside the
19894
          // target region, therefore we need to propagate the capture from the
19895
          // enclosing region. Therefore, the capture is not initially nested.
19896
0
          if (IsTargetCap)
19897
0
            adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19898
19899
0
          if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19900
0
              (IsGlobal && !IsGlobalCap)) {
19901
0
            Nested = !IsTargetCap;
19902
0
            bool HasConst = DeclRefType.isConstQualified();
19903
0
            DeclRefType = DeclRefType.getUnqualifiedType();
19904
            // Don't lose diagnostics about assignments to const.
19905
0
            if (HasConst)
19906
0
              DeclRefType.addConst();
19907
0
            CaptureType = Context.getLValueReferenceType(DeclRefType);
19908
0
            break;
19909
0
          }
19910
0
        }
19911
0
      }
19912
0
    }
19913
0
    if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19914
      // No capture-default, and this is not an explicit capture
19915
      // so cannot capture this variable.
19916
0
      if (BuildAndDiagnose) {
19917
0
        Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19918
0
        Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19919
0
        auto *LSI = cast<LambdaScopeInfo>(CSI);
19920
0
        if (LSI->Lambda) {
19921
0
          Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19922
0
          buildLambdaCaptureFixit(*this, LSI, Var);
19923
0
        }
19924
        // FIXME: If we error out because an outer lambda can not implicitly
19925
        // capture a variable that an inner lambda explicitly captures, we
19926
        // should have the inner lambda do the explicit capture - because
19927
        // it makes for cleaner diagnostics later.  This would purely be done
19928
        // so that the diagnostic does not misleadingly claim that a variable
19929
        // can not be captured by a lambda implicitly even though it is captured
19930
        // explicitly.  Suggestion:
19931
        //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19932
        //    at the function head
19933
        //  - cache the StartingDeclContext - this must be a lambda
19934
        //  - captureInLambda in the innermost lambda the variable.
19935
0
      }
19936
0
      return true;
19937
0
    }
19938
0
    Explicit = false;
19939
0
    FunctionScopesIndex--;
19940
0
    if (IsInScopeDeclarationContext)
19941
0
      DC = ParentDC;
19942
0
  } while (!VarDC->Equals(DC));
19943
19944
  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19945
  // computing the type of the capture at each step, checking type-specific
19946
  // requirements, and adding captures if requested.
19947
  // If the variable had already been captured previously, we start capturing
19948
  // at the lambda nested within that one.
19949
0
  bool Invalid = false;
19950
0
  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19951
0
       ++I) {
19952
0
    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19953
19954
    // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19955
    // certain types of variables (unnamed, variably modified types etc.)
19956
    // so check for eligibility.
19957
0
    if (!Invalid)
19958
0
      Invalid =
19959
0
          !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19960
19961
    // After encountering an error, if we're actually supposed to capture, keep
19962
    // capturing in nested contexts to suppress any follow-on diagnostics.
19963
0
    if (Invalid && !BuildAndDiagnose)
19964
0
      return true;
19965
19966
0
    if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19967
0
      Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19968
0
                               DeclRefType, Nested, *this, Invalid);
19969
0
      Nested = true;
19970
0
    } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19971
0
      Invalid = !captureInCapturedRegion(
19972
0
          RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19973
0
          Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19974
0
      Nested = true;
19975
0
    } else {
19976
0
      LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19977
0
      Invalid =
19978
0
          !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19979
0
                           DeclRefType, Nested, Kind, EllipsisLoc,
19980
0
                           /*IsTopScope*/ I == N - 1, *this, Invalid);
19981
0
      Nested = true;
19982
0
    }
19983
19984
0
    if (Invalid && !BuildAndDiagnose)
19985
0
      return true;
19986
0
  }
19987
0
  return Invalid;
19988
0
}
19989
19990
bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19991
0
                              TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19992
0
  QualType CaptureType;
19993
0
  QualType DeclRefType;
19994
0
  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19995
0
                            /*BuildAndDiagnose=*/true, CaptureType,
19996
0
                            DeclRefType, nullptr);
19997
0
}
19998
19999
59
bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20000
59
  QualType CaptureType;
20001
59
  QualType DeclRefType;
20002
59
  return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
20003
59
                             /*BuildAndDiagnose=*/false, CaptureType,
20004
59
                             DeclRefType, nullptr);
20005
59
}
20006
20007
59
QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20008
59
  QualType CaptureType;
20009
59
  QualType DeclRefType;
20010
20011
  // Determine whether we can capture this variable.
20012
59
  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
20013
59
                         /*BuildAndDiagnose=*/false, CaptureType,
20014
59
                         DeclRefType, nullptr))
20015
59
    return QualType();
20016
20017
0
  return DeclRefType;
20018
59
}
20019
20020
namespace {
20021
// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20022
// The produced TemplateArgumentListInfo* points to data stored within this
20023
// object, so should only be used in contexts where the pointer will not be
20024
// used after the CopiedTemplateArgs object is destroyed.
20025
class CopiedTemplateArgs {
20026
  bool HasArgs;
20027
  TemplateArgumentListInfo TemplateArgStorage;
20028
public:
20029
  template<typename RefExpr>
20030
0
  CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20031
0
    if (HasArgs)
20032
0
      E->copyTemplateArgumentsInto(TemplateArgStorage);
20033
0
  }
Unexecuted instantiation: SemaExpr.cpp:(anonymous namespace)::CopiedTemplateArgs::CopiedTemplateArgs<clang::DeclRefExpr>(clang::DeclRefExpr*)
Unexecuted instantiation: SemaExpr.cpp:(anonymous namespace)::CopiedTemplateArgs::CopiedTemplateArgs<clang::MemberExpr>(clang::MemberExpr*)
20034
  operator TemplateArgumentListInfo*()
20035
#ifdef __has_cpp_attribute
20036
#if __has_cpp_attribute(clang::lifetimebound)
20037
  [[clang::lifetimebound]]
20038
#endif
20039
#endif
20040
0
  {
20041
0
    return HasArgs ? &TemplateArgStorage : nullptr;
20042
0
  }
20043
};
20044
}
20045
20046
/// Walk the set of potential results of an expression and mark them all as
20047
/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20048
///
20049
/// \return A new expression if we found any potential results, ExprEmpty() if
20050
///         not, and ExprError() if we diagnosed an error.
20051
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20052
100
                                                      NonOdrUseReason NOUR) {
20053
  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20054
  // an object that satisfies the requirements for appearing in a
20055
  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20056
  // is immediately applied."  This function handles the lvalue-to-rvalue
20057
  // conversion part.
20058
  //
20059
  // If we encounter a node that claims to be an odr-use but shouldn't be, we
20060
  // transform it into the relevant kind of non-odr-use node and rebuild the
20061
  // tree of nodes leading to it.
20062
  //
20063
  // This is a mini-TreeTransform that only transforms a restricted subset of
20064
  // nodes (and only certain operands of them).
20065
20066
  // Rebuild a subexpression.
20067
100
  auto Rebuild = [&](Expr *Sub) {
20068
2
    return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20069
2
  };
20070
20071
  // Check whether a potential result satisfies the requirements of NOUR.
20072
100
  auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20073
    // Any entity other than a VarDecl is always odr-used whenever it's named
20074
    // in a potentially-evaluated expression.
20075
8
    auto *VD = dyn_cast<VarDecl>(D);
20076
8
    if (!VD)
20077
0
      return true;
20078
20079
    // C++2a [basic.def.odr]p4:
20080
    //   A variable x whose name appears as a potentially-evalauted expression
20081
    //   e is odr-used by e unless
20082
    //   -- x is a reference that is usable in constant expressions, or
20083
    //   -- x is a variable of non-reference type that is usable in constant
20084
    //      expressions and has no mutable subobjects, and e is an element of
20085
    //      the set of potential results of an expression of
20086
    //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
20087
    //      conversion is applied, or
20088
    //   -- x is a variable of non-reference type, and e is an element of the
20089
    //      set of potential results of a discarded-value expression to which
20090
    //      the lvalue-to-rvalue conversion is not applied
20091
    //
20092
    // We check the first bullet and the "potentially-evaluated" condition in
20093
    // BuildDeclRefExpr. We check the type requirements in the second bullet
20094
    // in CheckLValueToRValueConversionOperand below.
20095
8
    switch (NOUR) {
20096
0
    case NOUR_None:
20097
0
    case NOUR_Unevaluated:
20098
0
      llvm_unreachable("unexpected non-odr-use-reason");
20099
20100
8
    case NOUR_Constant:
20101
      // Constant references were handled when they were built.
20102
8
      if (VD->getType()->isReferenceType())
20103
0
        return true;
20104
8
      if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20105
0
        if (RD->hasMutableFields())
20106
0
          return true;
20107
8
      if (!VD->isUsableInConstantExpressions(S.Context))
20108
8
        return true;
20109
0
      break;
20110
20111
0
    case NOUR_Discarded:
20112
0
      if (VD->getType()->isReferenceType())
20113
0
        return true;
20114
0
      break;
20115
8
    }
20116
0
    return false;
20117
8
  };
20118
20119
  // Mark that this expression does not constitute an odr-use.
20120
100
  auto MarkNotOdrUsed = [&] {
20121
0
    S.MaybeODRUseExprs.remove(E);
20122
0
    if (LambdaScopeInfo *LSI = S.getCurLambda())
20123
0
      LSI->markVariableExprAsNonODRUsed(E);
20124
0
  };
20125
20126
  // C++2a [basic.def.odr]p2:
20127
  //   The set of potential results of an expression e is defined as follows:
20128
100
  switch (E->getStmtClass()) {
20129
  //   -- If e is an id-expression, ...
20130
8
  case Expr::DeclRefExprClass: {
20131
8
    auto *DRE = cast<DeclRefExpr>(E);
20132
8
    if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20133
8
      break;
20134
20135
    // Rebuild as a non-odr-use DeclRefExpr.
20136
0
    MarkNotOdrUsed();
20137
0
    return DeclRefExpr::Create(
20138
0
        S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20139
0
        DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20140
0
        DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20141
0
        DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20142
8
  }
20143
20144
0
  case Expr::FunctionParmPackExprClass: {
20145
0
    auto *FPPE = cast<FunctionParmPackExpr>(E);
20146
    // If any of the declarations in the pack is odr-used, then the expression
20147
    // as a whole constitutes an odr-use.
20148
0
    for (VarDecl *D : *FPPE)
20149
0
      if (IsPotentialResultOdrUsed(D))
20150
0
        return ExprEmpty();
20151
20152
    // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20153
    // nothing cares about whether we marked this as an odr-use, but it might
20154
    // be useful for non-compiler tools.
20155
0
    MarkNotOdrUsed();
20156
0
    break;
20157
0
  }
20158
20159
  //   -- If e is a subscripting operation with an array operand...
20160
0
  case Expr::ArraySubscriptExprClass: {
20161
0
    auto *ASE = cast<ArraySubscriptExpr>(E);
20162
0
    Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20163
0
    if (!OldBase->getType()->isArrayType())
20164
0
      break;
20165
0
    ExprResult Base = Rebuild(OldBase);
20166
0
    if (!Base.isUsable())
20167
0
      return Base;
20168
0
    Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20169
0
    Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20170
0
    SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20171
0
    return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20172
0
                                     ASE->getRBracketLoc());
20173
0
  }
20174
20175
0
  case Expr::MemberExprClass: {
20176
0
    auto *ME = cast<MemberExpr>(E);
20177
    // -- If e is a class member access expression [...] naming a non-static
20178
    //    data member...
20179
0
    if (isa<FieldDecl>(ME->getMemberDecl())) {
20180
0
      ExprResult Base = Rebuild(ME->getBase());
20181
0
      if (!Base.isUsable())
20182
0
        return Base;
20183
0
      return MemberExpr::Create(
20184
0
          S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20185
0
          ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20186
0
          ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20187
0
          CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20188
0
          ME->getObjectKind(), ME->isNonOdrUse());
20189
0
    }
20190
20191
0
    if (ME->getMemberDecl()->isCXXInstanceMember())
20192
0
      break;
20193
20194
    // -- If e is a class member access expression naming a static data member,
20195
    //    ...
20196
0
    if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20197
0
      break;
20198
20199
    // Rebuild as a non-odr-use MemberExpr.
20200
0
    MarkNotOdrUsed();
20201
0
    return MemberExpr::Create(
20202
0
        S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20203
0
        ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20204
0
        ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20205
0
        ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20206
0
  }
20207
20208
4
  case Expr::BinaryOperatorClass: {
20209
4
    auto *BO = cast<BinaryOperator>(E);
20210
4
    Expr *LHS = BO->getLHS();
20211
4
    Expr *RHS = BO->getRHS();
20212
    // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20213
4
    if (BO->getOpcode() == BO_PtrMemD) {
20214
0
      ExprResult Sub = Rebuild(LHS);
20215
0
      if (!Sub.isUsable())
20216
0
        return Sub;
20217
0
      LHS = Sub.get();
20218
    //   -- If e is a comma expression, ...
20219
4
    } else if (BO->getOpcode() == BO_Comma) {
20220
0
      ExprResult Sub = Rebuild(RHS);
20221
0
      if (!Sub.isUsable())
20222
0
        return Sub;
20223
0
      RHS = Sub.get();
20224
4
    } else {
20225
4
      break;
20226
4
    }
20227
0
    return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
20228
0
                        LHS, RHS);
20229
4
  }
20230
20231
  //   -- If e has the form (e1)...
20232
0
  case Expr::ParenExprClass: {
20233
0
    auto *PE = cast<ParenExpr>(E);
20234
0
    ExprResult Sub = Rebuild(PE->getSubExpr());
20235
0
    if (!Sub.isUsable())
20236
0
      return Sub;
20237
0
    return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20238
0
  }
20239
20240
  //   -- If e is a glvalue conditional expression, ...
20241
  // We don't apply this to a binary conditional operator. FIXME: Should we?
20242
1
  case Expr::ConditionalOperatorClass: {
20243
1
    auto *CO = cast<ConditionalOperator>(E);
20244
1
    ExprResult LHS = Rebuild(CO->getLHS());
20245
1
    if (LHS.isInvalid())
20246
0
      return ExprError();
20247
1
    ExprResult RHS = Rebuild(CO->getRHS());
20248
1
    if (RHS.isInvalid())
20249
0
      return ExprError();
20250
1
    if (!LHS.isUsable() && !RHS.isUsable())
20251
1
      return ExprEmpty();
20252
0
    if (!LHS.isUsable())
20253
0
      LHS = CO->getLHS();
20254
0
    if (!RHS.isUsable())
20255
0
      RHS = CO->getRHS();
20256
0
    return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20257
0
                                CO->getCond(), LHS.get(), RHS.get());
20258
1
  }
20259
20260
  // [Clang extension]
20261
  //   -- If e has the form __extension__ e1...
20262
3
  case Expr::UnaryOperatorClass: {
20263
3
    auto *UO = cast<UnaryOperator>(E);
20264
3
    if (UO->getOpcode() != UO_Extension)
20265
3
      break;
20266
0
    ExprResult Sub = Rebuild(UO->getSubExpr());
20267
0
    if (!Sub.isUsable())
20268
0
      return Sub;
20269
0
    return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20270
0
                          Sub.get());
20271
0
  }
20272
20273
  // [Clang extension]
20274
  //   -- If e has the form _Generic(...), the set of potential results is the
20275
  //      union of the sets of potential results of the associated expressions.
20276
0
  case Expr::GenericSelectionExprClass: {
20277
0
    auto *GSE = cast<GenericSelectionExpr>(E);
20278
20279
0
    SmallVector<Expr *, 4> AssocExprs;
20280
0
    bool AnyChanged = false;
20281
0
    for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20282
0
      ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20283
0
      if (AssocExpr.isInvalid())
20284
0
        return ExprError();
20285
0
      if (AssocExpr.isUsable()) {
20286
0
        AssocExprs.push_back(AssocExpr.get());
20287
0
        AnyChanged = true;
20288
0
      } else {
20289
0
        AssocExprs.push_back(OrigAssocExpr);
20290
0
      }
20291
0
    }
20292
20293
0
    void *ExOrTy = nullptr;
20294
0
    bool IsExpr = GSE->isExprPredicate();
20295
0
    if (IsExpr)
20296
0
      ExOrTy = GSE->getControllingExpr();
20297
0
    else
20298
0
      ExOrTy = GSE->getControllingType();
20299
0
    return AnyChanged ? S.CreateGenericSelectionExpr(
20300
0
                            GSE->getGenericLoc(), GSE->getDefaultLoc(),
20301
0
                            GSE->getRParenLoc(), IsExpr, ExOrTy,
20302
0
                            GSE->getAssocTypeSourceInfos(), AssocExprs)
20303
0
                      : ExprEmpty();
20304
0
  }
20305
20306
  // [Clang extension]
20307
  //   -- If e has the form __builtin_choose_expr(...), the set of potential
20308
  //      results is the union of the sets of potential results of the
20309
  //      second and third subexpressions.
20310
0
  case Expr::ChooseExprClass: {
20311
0
    auto *CE = cast<ChooseExpr>(E);
20312
20313
0
    ExprResult LHS = Rebuild(CE->getLHS());
20314
0
    if (LHS.isInvalid())
20315
0
      return ExprError();
20316
20317
0
    ExprResult RHS = Rebuild(CE->getLHS());
20318
0
    if (RHS.isInvalid())
20319
0
      return ExprError();
20320
20321
0
    if (!LHS.get() && !RHS.get())
20322
0
      return ExprEmpty();
20323
0
    if (!LHS.isUsable())
20324
0
      LHS = CE->getLHS();
20325
0
    if (!RHS.isUsable())
20326
0
      RHS = CE->getRHS();
20327
20328
0
    return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20329
0
                             RHS.get(), CE->getRParenLoc());
20330
0
  }
20331
20332
  // Step through non-syntactic nodes.
20333
0
  case Expr::ConstantExprClass: {
20334
0
    auto *CE = cast<ConstantExpr>(E);
20335
0
    ExprResult Sub = Rebuild(CE->getSubExpr());
20336
0
    if (!Sub.isUsable())
20337
0
      return Sub;
20338
0
    return ConstantExpr::Create(S.Context, Sub.get());
20339
0
  }
20340
20341
  // We could mostly rely on the recursive rebuilding to rebuild implicit
20342
  // casts, but not at the top level, so rebuild them here.
20343
0
  case Expr::ImplicitCastExprClass: {
20344
0
    auto *ICE = cast<ImplicitCastExpr>(E);
20345
    // Only step through the narrow set of cast kinds we expect to encounter.
20346
    // Anything else suggests we've left the region in which potential results
20347
    // can be found.
20348
0
    switch (ICE->getCastKind()) {
20349
0
    case CK_NoOp:
20350
0
    case CK_DerivedToBase:
20351
0
    case CK_UncheckedDerivedToBase: {
20352
0
      ExprResult Sub = Rebuild(ICE->getSubExpr());
20353
0
      if (!Sub.isUsable())
20354
0
        return Sub;
20355
0
      CXXCastPath Path(ICE->path());
20356
0
      return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20357
0
                                 ICE->getValueKind(), &Path);
20358
0
    }
20359
20360
0
    default:
20361
0
      break;
20362
0
    }
20363
0
    break;
20364
0
  }
20365
20366
84
  default:
20367
84
    break;
20368
100
  }
20369
20370
  // Can't traverse through this node. Nothing to do.
20371
99
  return ExprEmpty();
20372
100
}
20373
20374
98
ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20375
  // Check whether the operand is or contains an object of non-trivial C union
20376
  // type.
20377
98
  if (E->getType().isVolatileQualified() &&
20378
98
      (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20379
0
       E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20380
0
    checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
20381
0
                          Sema::NTCUC_LValueToRValueVolatile,
20382
0
                          NTCUK_Destruct|NTCUK_Copy);
20383
20384
  // C++2a [basic.def.odr]p4:
20385
  //   [...] an expression of non-volatile-qualified non-class type to which
20386
  //   the lvalue-to-rvalue conversion is applied [...]
20387
98
  if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
20388
0
    return E;
20389
20390
98
  ExprResult Result =
20391
98
      rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
20392
98
  if (Result.isInvalid())
20393
0
    return ExprError();
20394
98
  return Result.get() ? Result : E;
20395
98
}
20396
20397
268
ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20398
268
  Res = CorrectDelayedTyposInExpr(Res);
20399
20400
268
  if (!Res.isUsable())
20401
197
    return Res;
20402
20403
  // If a constant-expression is a reference to a variable where we delay
20404
  // deciding whether it is an odr-use, just assume we will apply the
20405
  // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
20406
  // (a non-type template argument), we have special handling anyway.
20407
71
  return CheckLValueToRValueConversionOperand(Res.get());
20408
268
}
20409
20410
470
void Sema::CleanupVarDeclMarking() {
20411
  // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20412
  // call.
20413
470
  MaybeODRUseExprSet LocalMaybeODRUseExprs;
20414
470
  std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20415
20416
470
  for (Expr *E : LocalMaybeODRUseExprs) {
20417
0
    if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20418
0
      MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20419
0
                         DRE->getLocation(), *this);
20420
0
    } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20421
0
      MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20422
0
                         *this);
20423
0
    } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20424
0
      for (VarDecl *VD : *FP)
20425
0
        MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20426
0
    } else {
20427
0
      llvm_unreachable("Unexpected expression");
20428
0
    }
20429
0
  }
20430
20431
470
  assert(MaybeODRUseExprs.empty() &&
20432
470
         "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20433
470
}
20434
20435
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20436
0
                                   ValueDecl *Var, Expr *E) {
20437
0
  VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20438
0
  if (!VD)
20439
0
    return;
20440
20441
0
  const bool RefersToEnclosingScope =
20442
0
      (SemaRef.CurContext != VD->getDeclContext() &&
20443
0
       VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20444
0
  if (RefersToEnclosingScope) {
20445
0
    LambdaScopeInfo *const LSI =
20446
0
        SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20447
0
    if (LSI && (!LSI->CallOperator ||
20448
0
                !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20449
      // If a variable could potentially be odr-used, defer marking it so
20450
      // until we finish analyzing the full expression for any
20451
      // lvalue-to-rvalue
20452
      // or discarded value conversions that would obviate odr-use.
20453
      // Add it to the list of potential captures that will be analyzed
20454
      // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20455
      // unless the variable is a reference that was initialized by a constant
20456
      // expression (this will never need to be captured or odr-used).
20457
      //
20458
      // FIXME: We can simplify this a lot after implementing P0588R1.
20459
0
      assert(E && "Capture variable should be used in an expression.");
20460
0
      if (!Var->getType()->isReferenceType() ||
20461
0
          !VD->isUsableInConstantExpressions(SemaRef.Context))
20462
0
        LSI->addPotentialCapture(E->IgnoreParens());
20463
0
    }
20464
0
  }
20465
0
}
20466
20467
static void DoMarkVarDeclReferenced(
20468
    Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20469
60
    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20470
60
  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20471
60
          isa<FunctionParmPackExpr>(E)) &&
20472
60
         "Invalid Expr argument to DoMarkVarDeclReferenced");
20473
0
  Var->setReferenced();
20474
20475
60
  if (Var->isInvalidDecl())
20476
43
    return;
20477
20478
17
  auto *MSI = Var->getMemberSpecializationInfo();
20479
17
  TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20480
17
                                       : Var->getTemplateSpecializationKind();
20481
20482
17
  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20483
17
  bool UsableInConstantExpr =
20484
17
      Var->mightBeUsableInConstantExpressions(SemaRef.Context);
20485
20486
17
  if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20487
0
    RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20488
0
  }
20489
20490
  // C++20 [expr.const]p12:
20491
  //   A variable [...] is needed for constant evaluation if it is [...] a
20492
  //   variable whose name appears as a potentially constant evaluated
20493
  //   expression that is either a contexpr variable or is of non-volatile
20494
  //   const-qualified integral type or of reference type
20495
17
  bool NeededForConstantEvaluation =
20496
17
      isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20497
20498
17
  bool NeedDefinition =
20499
17
      OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20500
20501
17
  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20502
17
         "Can't instantiate a partial template specialization.");
20503
20504
  // If this might be a member specialization of a static data member, check
20505
  // the specialization is visible. We already did the checks for variable
20506
  // template specializations when we created them.
20507
17
  if (NeedDefinition && TSK != TSK_Undeclared &&
20508
17
      !isa<VarTemplateSpecializationDecl>(Var))
20509
0
    SemaRef.checkSpecializationVisibility(Loc, Var);
20510
20511
  // Perform implicit instantiation of static data members, static data member
20512
  // templates of class templates, and variable template specializations. Delay
20513
  // instantiations of variable templates, except for those that could be used
20514
  // in a constant expression.
20515
17
  if (NeedDefinition && isTemplateInstantiation(TSK)) {
20516
    // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20517
    // instantiation declaration if a variable is usable in a constant
20518
    // expression (among other cases).
20519
0
    bool TryInstantiating =
20520
0
        TSK == TSK_ImplicitInstantiation ||
20521
0
        (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20522
20523
0
    if (TryInstantiating) {
20524
0
      SourceLocation PointOfInstantiation =
20525
0
          MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20526
0
      bool FirstInstantiation = PointOfInstantiation.isInvalid();
20527
0
      if (FirstInstantiation) {
20528
0
        PointOfInstantiation = Loc;
20529
0
        if (MSI)
20530
0
          MSI->setPointOfInstantiation(PointOfInstantiation);
20531
          // FIXME: Notify listener.
20532
0
        else
20533
0
          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20534
0
      }
20535
20536
0
      if (UsableInConstantExpr) {
20537
        // Do not defer instantiations of variables that could be used in a
20538
        // constant expression.
20539
0
        SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20540
0
          SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20541
0
        });
20542
20543
        // Re-set the member to trigger a recomputation of the dependence bits
20544
        // for the expression.
20545
0
        if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20546
0
          DRE->setDecl(DRE->getDecl());
20547
0
        else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20548
0
          ME->setMemberDecl(ME->getMemberDecl());
20549
0
      } else if (FirstInstantiation) {
20550
0
        SemaRef.PendingInstantiations
20551
0
            .push_back(std::make_pair(Var, PointOfInstantiation));
20552
0
      } else {
20553
0
        bool Inserted = false;
20554
0
        for (auto &I : SemaRef.SavedPendingInstantiations) {
20555
0
          auto Iter = llvm::find_if(
20556
0
              I, [Var](const Sema::PendingImplicitInstantiation &P) {
20557
0
                return P.first == Var;
20558
0
              });
20559
0
          if (Iter != I.end()) {
20560
0
            SemaRef.PendingInstantiations.push_back(*Iter);
20561
0
            I.erase(Iter);
20562
0
            Inserted = true;
20563
0
            break;
20564
0
          }
20565
0
        }
20566
20567
        // FIXME: For a specialization of a variable template, we don't
20568
        // distinguish between "declaration and type implicitly instantiated"
20569
        // and "implicit instantiation of definition requested", so we have
20570
        // no direct way to avoid enqueueing the pending instantiation
20571
        // multiple times.
20572
0
        if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20573
0
          SemaRef.PendingInstantiations
20574
0
            .push_back(std::make_pair(Var, PointOfInstantiation));
20575
0
      }
20576
0
    }
20577
0
  }
20578
20579
  // C++2a [basic.def.odr]p4:
20580
  //   A variable x whose name appears as a potentially-evaluated expression e
20581
  //   is odr-used by e unless
20582
  //   -- x is a reference that is usable in constant expressions
20583
  //   -- x is a variable of non-reference type that is usable in constant
20584
  //      expressions and has no mutable subobjects [FIXME], and e is an
20585
  //      element of the set of potential results of an expression of
20586
  //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
20587
  //      conversion is applied
20588
  //   -- x is a variable of non-reference type, and e is an element of the set
20589
  //      of potential results of a discarded-value expression to which the
20590
  //      lvalue-to-rvalue conversion is not applied [FIXME]
20591
  //
20592
  // We check the first part of the second bullet here, and
20593
  // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20594
  // FIXME: To get the third bullet right, we need to delay this even for
20595
  // variables that are not usable in constant expressions.
20596
20597
  // If we already know this isn't an odr-use, there's nothing more to do.
20598
17
  if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20599
17
    if (DRE->isNonOdrUse())
20600
0
      return;
20601
17
  if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20602
0
    if (ME->isNonOdrUse())
20603
0
      return;
20604
20605
17
  switch (OdrUse) {
20606
0
  case OdrUseContext::None:
20607
    // In some cases, a variable may not have been marked unevaluated, if it
20608
    // appears in a defaukt initializer.
20609
0
    assert((!E || isa<FunctionParmPackExpr>(E) ||
20610
0
            SemaRef.isUnevaluatedContext()) &&
20611
0
           "missing non-odr-use marking for unevaluated decl ref");
20612
0
    break;
20613
20614
0
  case OdrUseContext::FormallyOdrUsed:
20615
    // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20616
    // behavior.
20617
0
    break;
20618
20619
17
  case OdrUseContext::Used:
20620
    // If we might later find that this expression isn't actually an odr-use,
20621
    // delay the marking.
20622
17
    if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20623
0
      SemaRef.MaybeODRUseExprs.insert(E);
20624
17
    else
20625
17
      MarkVarDeclODRUsed(Var, Loc, SemaRef);
20626
17
    break;
20627
20628
0
  case OdrUseContext::Dependent:
20629
    // If this is a dependent context, we don't need to mark variables as
20630
    // odr-used, but we may still need to track them for lambda capture.
20631
    // FIXME: Do we also need to do this inside dependent typeid expressions
20632
    // (which are modeled as unevaluated at this point)?
20633
0
    DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20634
0
    break;
20635
17
  }
20636
17
}
20637
20638
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20639
0
                                        BindingDecl *BD, Expr *E) {
20640
0
  BD->setReferenced();
20641
20642
0
  if (BD->isInvalidDecl())
20643
0
    return;
20644
20645
0
  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20646
0
  if (OdrUse == OdrUseContext::Used) {
20647
0
    QualType CaptureType, DeclRefType;
20648
0
    SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20649
0
                               /*EllipsisLoc*/ SourceLocation(),
20650
0
                               /*BuildAndDiagnose*/ true, CaptureType,
20651
0
                               DeclRefType,
20652
0
                               /*FunctionScopeIndexToStopAt*/ nullptr);
20653
0
  } else if (OdrUse == OdrUseContext::Dependent) {
20654
0
    DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20655
0
  }
20656
0
}
20657
20658
/// Mark a variable referenced, and check whether it is odr-used
20659
/// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
20660
/// used directly for normal expressions referring to VarDecl.
20661
0
void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20662
0
  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20663
0
}
20664
20665
// C++ [temp.dep.expr]p3:
20666
//   An id-expression is type-dependent if it contains:
20667
//     - an identifier associated by name lookup with an entity captured by copy
20668
//       in a lambda-expression that has an explicit object parameter whose type
20669
//       is dependent ([dcl.fct]),
20670
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20671
43
    Sema &SemaRef, ValueDecl *D, Expr *E) {
20672
43
  auto *ID = dyn_cast<DeclRefExpr>(E);
20673
43
  if (!ID || ID->isTypeDependent())
20674
0
    return;
20675
20676
43
  auto IsDependent = [&]() {
20677
43
    const LambdaScopeInfo *LSI = SemaRef.getCurLambda();
20678
43
    if (!LSI)
20679
43
      return false;
20680
0
    if (!LSI->ExplicitObjectParameter ||
20681
0
        !LSI->ExplicitObjectParameter->getType()->isDependentType())
20682
0
      return false;
20683
0
    if (!LSI->CaptureMap.count(D))
20684
0
      return false;
20685
0
    const Capture &Cap = LSI->getCapture(D);
20686
0
    return !Cap.isCopyCapture();
20687
0
  }();
20688
20689
43
  ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20690
43
      IsDependent, SemaRef.getASTContext());
20691
43
}
20692
20693
static void
20694
MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20695
                   bool MightBeOdrUse,
20696
60
                   llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20697
60
  if (SemaRef.isInOpenMPDeclareTargetContext())
20698
0
    SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20699
20700
60
  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20701
60
    DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20702
60
    if (SemaRef.getLangOpts().CPlusPlus)
20703
43
      FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20704
43
                                                                       Var, E);
20705
60
    return;
20706
60
  }
20707
20708
0
  if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20709
0
    DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20710
0
    if (SemaRef.getLangOpts().CPlusPlus)
20711
0
      FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20712
0
                                                                       Decl, E);
20713
0
    return;
20714
0
  }
20715
0
  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20716
20717
  // If this is a call to a method via a cast, also mark the method in the
20718
  // derived class used in case codegen can devirtualize the call.
20719
0
  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20720
0
  if (!ME)
20721
0
    return;
20722
0
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20723
0
  if (!MD)
20724
0
    return;
20725
  // Only attempt to devirtualize if this is truly a virtual call.
20726
0
  bool IsVirtualCall = MD->isVirtual() &&
20727
0
                          ME->performsVirtualDispatch(SemaRef.getLangOpts());
20728
0
  if (!IsVirtualCall)
20729
0
    return;
20730
20731
  // If it's possible to devirtualize the call, mark the called function
20732
  // referenced.
20733
0
  CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20734
0
      ME->getBase(), SemaRef.getLangOpts().AppleKext);
20735
0
  if (DM)
20736
0
    SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20737
0
}
20738
20739
/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20740
///
20741
/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20742
/// handled with care if the DeclRefExpr is not newly-created.
20743
60
void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20744
  // TODO: update this with DR# once a defect report is filed.
20745
  // C++11 defect. The address of a pure member should not be an ODR use, even
20746
  // if it's a qualified reference.
20747
60
  bool OdrUse = true;
20748
60
  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20749
0
    if (Method->isVirtual() &&
20750
0
        !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20751
0
      OdrUse = false;
20752
20753
60
  if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20754
0
    if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20755
0
        !isImmediateFunctionContext() &&
20756
0
        !isCheckingDefaultArgumentOrInitializer() &&
20757
0
        FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20758
0
        !FD->isDependentContext())
20759
0
      ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20760
0
  }
20761
60
  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20762
60
                     RefsMinusAssignments);
20763
60
}
20764
20765
/// Perform reference-marking and odr-use handling for a MemberExpr.
20766
0
void Sema::MarkMemberReferenced(MemberExpr *E) {
20767
  // C++11 [basic.def.odr]p2:
20768
  //   A non-overloaded function whose name appears as a potentially-evaluated
20769
  //   expression or a member of a set of candidate functions, if selected by
20770
  //   overload resolution when referred to from a potentially-evaluated
20771
  //   expression, is odr-used, unless it is a pure virtual function and its
20772
  //   name is not explicitly qualified.
20773
0
  bool MightBeOdrUse = true;
20774
0
  if (E->performsVirtualDispatch(getLangOpts())) {
20775
0
    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20776
0
      if (Method->isPure())
20777
0
        MightBeOdrUse = false;
20778
0
  }
20779
0
  SourceLocation Loc =
20780
0
      E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20781
0
  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20782
0
                     RefsMinusAssignments);
20783
0
}
20784
20785
/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20786
0
void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20787
0
  for (VarDecl *VD : *E)
20788
0
    MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20789
0
                       RefsMinusAssignments);
20790
0
}
20791
20792
/// Perform marking for a reference to an arbitrary declaration.  It
20793
/// marks the declaration referenced, and performs odr-use checking for
20794
/// functions and variables. This method should not be used when building a
20795
/// normal expression which refers to a variable.
20796
void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20797
0
                                 bool MightBeOdrUse) {
20798
0
  if (MightBeOdrUse) {
20799
0
    if (auto *VD = dyn_cast<VarDecl>(D)) {
20800
0
      MarkVariableReferenced(Loc, VD);
20801
0
      return;
20802
0
    }
20803
0
  }
20804
0
  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20805
0
    MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20806
0
    return;
20807
0
  }
20808
0
  D->setReferenced();
20809
0
}
20810
20811
namespace {
20812
  // Mark all of the declarations used by a type as referenced.
20813
  // FIXME: Not fully implemented yet! We need to have a better understanding
20814
  // of when we're entering a context we should not recurse into.
20815
  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20816
  // TreeTransforms rebuilding the type in a new context. Rather than
20817
  // duplicating the TreeTransform logic, we should consider reusing it here.
20818
  // Currently that causes problems when rebuilding LambdaExprs.
20819
  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20820
    Sema &S;
20821
    SourceLocation Loc;
20822
20823
  public:
20824
    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20825
20826
0
    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20827
20828
    bool TraverseTemplateArgument(const TemplateArgument &Arg);
20829
  };
20830
}
20831
20832
bool MarkReferencedDecls::TraverseTemplateArgument(
20833
0
    const TemplateArgument &Arg) {
20834
0
  {
20835
    // A non-type template argument is a constant-evaluated context.
20836
0
    EnterExpressionEvaluationContext Evaluated(
20837
0
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20838
0
    if (Arg.getKind() == TemplateArgument::Declaration) {
20839
0
      if (Decl *D = Arg.getAsDecl())
20840
0
        S.MarkAnyDeclReferenced(Loc, D, true);
20841
0
    } else if (Arg.getKind() == TemplateArgument::Expression) {
20842
0
      S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20843
0
    }
20844
0
  }
20845
20846
0
  return Inherited::TraverseTemplateArgument(Arg);
20847
0
}
20848
20849
0
void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20850
0
  MarkReferencedDecls Marker(*this, Loc);
20851
0
  Marker.TraverseType(T);
20852
0
}
20853
20854
namespace {
20855
/// Helper class that marks all of the declarations referenced by
20856
/// potentially-evaluated subexpressions as "referenced".
20857
class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20858
public:
20859
  typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20860
  bool SkipLocalVariables;
20861
  ArrayRef<const Expr *> StopAt;
20862
20863
  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20864
                      ArrayRef<const Expr *> StopAt)
20865
0
      : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20866
20867
0
  void visitUsedDecl(SourceLocation Loc, Decl *D) {
20868
0
    S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20869
0
  }
20870
20871
0
  void Visit(Expr *E) {
20872
0
    if (llvm::is_contained(StopAt, E))
20873
0
      return;
20874
0
    Inherited::Visit(E);
20875
0
  }
20876
20877
0
  void VisitConstantExpr(ConstantExpr *E) {
20878
    // Don't mark declarations within a ConstantExpression, as this expression
20879
    // will be evaluated and folded to a value.
20880
0
  }
20881
20882
0
  void VisitDeclRefExpr(DeclRefExpr *E) {
20883
    // If we were asked not to visit local variables, don't.
20884
0
    if (SkipLocalVariables) {
20885
0
      if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20886
0
        if (VD->hasLocalStorage())
20887
0
          return;
20888
0
    }
20889
20890
    // FIXME: This can trigger the instantiation of the initializer of a
20891
    // variable, which can cause the expression to become value-dependent
20892
    // or error-dependent. Do we need to propagate the new dependence bits?
20893
0
    S.MarkDeclRefReferenced(E);
20894
0
  }
20895
20896
0
  void VisitMemberExpr(MemberExpr *E) {
20897
0
    S.MarkMemberReferenced(E);
20898
0
    Visit(E->getBase());
20899
0
  }
20900
};
20901
} // namespace
20902
20903
/// Mark any declarations that appear within this expression or any
20904
/// potentially-evaluated subexpressions as "referenced".
20905
///
20906
/// \param SkipLocalVariables If true, don't mark local variables as
20907
/// 'referenced'.
20908
/// \param StopAt Subexpressions that we shouldn't recurse into.
20909
void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20910
                                            bool SkipLocalVariables,
20911
0
                                            ArrayRef<const Expr*> StopAt) {
20912
0
  EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20913
0
}
20914
20915
/// Emit a diagnostic when statements are reachable.
20916
/// FIXME: check for reachability even in expressions for which we don't build a
20917
///        CFG (eg, in the initializer of a global or in a constant expression).
20918
///        For example,
20919
///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20920
bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20921
0
                           const PartialDiagnostic &PD) {
20922
0
  if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20923
0
    if (!FunctionScopes.empty())
20924
0
      FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20925
0
          sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20926
0
    return true;
20927
0
  }
20928
20929
  // The initializer of a constexpr variable or of the first declaration of a
20930
  // static data member is not syntactically a constant evaluated constant,
20931
  // but nonetheless is always required to be a constant expression, so we
20932
  // can skip diagnosing.
20933
  // FIXME: Using the mangling context here is a hack.
20934
0
  if (auto *VD = dyn_cast_or_null<VarDecl>(
20935
0
          ExprEvalContexts.back().ManglingContextDecl)) {
20936
0
    if (VD->isConstexpr() ||
20937
0
        (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20938
0
      return false;
20939
    // FIXME: For any other kind of variable, we should build a CFG for its
20940
    // initializer and check whether the context in question is reachable.
20941
0
  }
20942
20943
0
  Diag(Loc, PD);
20944
0
  return true;
20945
0
}
20946
20947
/// Emit a diagnostic that describes an effect on the run-time behavior
20948
/// of the program being compiled.
20949
///
20950
/// This routine emits the given diagnostic when the code currently being
20951
/// type-checked is "potentially evaluated", meaning that there is a
20952
/// possibility that the code will actually be executable. Code in sizeof()
20953
/// expressions, code used only during overload resolution, etc., are not
20954
/// potentially evaluated. This routine will suppress such diagnostics or,
20955
/// in the absolutely nutty case of potentially potentially evaluated
20956
/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20957
/// later.
20958
///
20959
/// This routine should be used for all diagnostics that describe the run-time
20960
/// behavior of a program, such as passing a non-POD value through an ellipsis.
20961
/// Failure to do so will likely result in spurious diagnostics or failures
20962
/// during overload resolution or within sizeof/alignof/typeof/typeid.
20963
bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20964
0
                               const PartialDiagnostic &PD) {
20965
20966
0
  if (ExprEvalContexts.back().isDiscardedStatementContext())
20967
0
    return false;
20968
20969
0
  switch (ExprEvalContexts.back().Context) {
20970
0
  case ExpressionEvaluationContext::Unevaluated:
20971
0
  case ExpressionEvaluationContext::UnevaluatedList:
20972
0
  case ExpressionEvaluationContext::UnevaluatedAbstract:
20973
0
  case ExpressionEvaluationContext::DiscardedStatement:
20974
    // The argument will never be evaluated, so don't complain.
20975
0
    break;
20976
20977
0
  case ExpressionEvaluationContext::ConstantEvaluated:
20978
0
  case ExpressionEvaluationContext::ImmediateFunctionContext:
20979
    // Relevant diagnostics should be produced by constant evaluation.
20980
0
    break;
20981
20982
0
  case ExpressionEvaluationContext::PotentiallyEvaluated:
20983
0
  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20984
0
    return DiagIfReachable(Loc, Stmts, PD);
20985
0
  }
20986
20987
0
  return false;
20988
0
}
20989
20990
bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20991
0
                               const PartialDiagnostic &PD) {
20992
0
  return DiagRuntimeBehavior(
20993
0
      Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20994
0
}
20995
20996
bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20997
0
                               CallExpr *CE, FunctionDecl *FD) {
20998
0
  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20999
0
    return false;
21000
21001
  // If we're inside a decltype's expression, don't check for a valid return
21002
  // type or construct temporaries until we know whether this is the last call.
21003
0
  if (ExprEvalContexts.back().ExprContext ==
21004
0
      ExpressionEvaluationContextRecord::EK_Decltype) {
21005
0
    ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21006
0
    return false;
21007
0
  }
21008
21009
0
  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21010
0
    FunctionDecl *FD;
21011
0
    CallExpr *CE;
21012
21013
0
  public:
21014
0
    CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21015
0
      : FD(FD), CE(CE) { }
21016
21017
0
    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21018
0
      if (!FD) {
21019
0
        S.Diag(Loc, diag::err_call_incomplete_return)
21020
0
          << T << CE->getSourceRange();
21021
0
        return;
21022
0
      }
21023
21024
0
      S.Diag(Loc, diag::err_call_function_incomplete_return)
21025
0
          << CE->getSourceRange() << FD << T;
21026
0
      S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21027
0
          << FD->getDeclName();
21028
0
    }
21029
0
  } Diagnoser(FD, CE);
21030
21031
0
  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21032
0
    return true;
21033
21034
0
  return false;
21035
0
}
21036
21037
// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21038
// will prevent this condition from triggering, which is what we want.
21039
0
void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21040
0
  SourceLocation Loc;
21041
21042
0
  unsigned diagnostic = diag::warn_condition_is_assignment;
21043
0
  bool IsOrAssign = false;
21044
21045
0
  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21046
0
    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21047
0
      return;
21048
21049
0
    IsOrAssign = Op->getOpcode() == BO_OrAssign;
21050
21051
    // Greylist some idioms by putting them into a warning subcategory.
21052
0
    if (ObjCMessageExpr *ME
21053
0
          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21054
0
      Selector Sel = ME->getSelector();
21055
21056
      // self = [<foo> init...]
21057
0
      if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21058
0
        diagnostic = diag::warn_condition_is_idiomatic_assignment;
21059
21060
      // <foo> = [<bar> nextObject]
21061
0
      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21062
0
        diagnostic = diag::warn_condition_is_idiomatic_assignment;
21063
0
    }
21064
21065
0
    Loc = Op->getOperatorLoc();
21066
0
  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21067
0
    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21068
0
      return;
21069
21070
0
    IsOrAssign = Op->getOperator() == OO_PipeEqual;
21071
0
    Loc = Op->getOperatorLoc();
21072
0
  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21073
0
    return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21074
0
  else {
21075
    // Not an assignment.
21076
0
    return;
21077
0
  }
21078
21079
0
  Diag(Loc, diagnostic) << E->getSourceRange();
21080
21081
0
  SourceLocation Open = E->getBeginLoc();
21082
0
  SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
21083
0
  Diag(Loc, diag::note_condition_assign_silence)
21084
0
        << FixItHint::CreateInsertion(Open, "(")
21085
0
        << FixItHint::CreateInsertion(Close, ")");
21086
21087
0
  if (IsOrAssign)
21088
0
    Diag(Loc, diag::note_condition_or_assign_to_comparison)
21089
0
      << FixItHint::CreateReplacement(Loc, "!=");
21090
0
  else
21091
0
    Diag(Loc, diag::note_condition_assign_to_comparison)
21092
0
      << FixItHint::CreateReplacement(Loc, "==");
21093
0
}
21094
21095
/// Redundant parentheses over an equality comparison can indicate
21096
/// that the user intended an assignment used as condition.
21097
0
void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21098
  // Don't warn if the parens came from a macro.
21099
0
  SourceLocation parenLoc = ParenE->getBeginLoc();
21100
0
  if (parenLoc.isInvalid() || parenLoc.isMacroID())
21101
0
    return;
21102
  // Don't warn for dependent expressions.
21103
0
  if (ParenE->isTypeDependent())
21104
0
    return;
21105
21106
0
  Expr *E = ParenE->IgnoreParens();
21107
21108
0
  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21109
0
    if (opE->getOpcode() == BO_EQ &&
21110
0
        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21111
0
                                                           == Expr::MLV_Valid) {
21112
0
      SourceLocation Loc = opE->getOperatorLoc();
21113
21114
0
      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21115
0
      SourceRange ParenERange = ParenE->getSourceRange();
21116
0
      Diag(Loc, diag::note_equality_comparison_silence)
21117
0
        << FixItHint::CreateRemoval(ParenERange.getBegin())
21118
0
        << FixItHint::CreateRemoval(ParenERange.getEnd());
21119
0
      Diag(Loc, diag::note_equality_comparison_to_assign)
21120
0
        << FixItHint::CreateReplacement(Loc, "=");
21121
0
    }
21122
0
}
21123
21124
ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21125
0
                                       bool IsConstexpr) {
21126
0
  DiagnoseAssignmentAsCondition(E);
21127
0
  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21128
0
    DiagnoseEqualityWithExtraParens(parenE);
21129
21130
0
  ExprResult result = CheckPlaceholderExpr(E);
21131
0
  if (result.isInvalid()) return ExprError();
21132
0
  E = result.get();
21133
21134
0
  if (!E->isTypeDependent()) {
21135
0
    if (getLangOpts().CPlusPlus)
21136
0
      return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21137
21138
0
    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21139
0
    if (ERes.isInvalid())
21140
0
      return ExprError();
21141
0
    E = ERes.get();
21142
21143
0
    QualType T = E->getType();
21144
0
    if (!T->isScalarType()) { // C99 6.8.4.1p1
21145
0
      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21146
0
        << T << E->getSourceRange();
21147
0
      return ExprError();
21148
0
    }
21149
0
    CheckBoolLikeConversion(E, Loc);
21150
0
  }
21151
21152
0
  return E;
21153
0
}
21154
21155
Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21156
                                           Expr *SubExpr, ConditionKind CK,
21157
0
                                           bool MissingOK) {
21158
  // MissingOK indicates whether having no condition expression is valid
21159
  // (for loop) or invalid (e.g. while loop).
21160
0
  if (!SubExpr)
21161
0
    return MissingOK ? ConditionResult() : ConditionError();
21162
21163
0
  ExprResult Cond;
21164
0
  switch (CK) {
21165
0
  case ConditionKind::Boolean:
21166
0
    Cond = CheckBooleanCondition(Loc, SubExpr);
21167
0
    break;
21168
21169
0
  case ConditionKind::ConstexprIf:
21170
0
    Cond = CheckBooleanCondition(Loc, SubExpr, true);
21171
0
    break;
21172
21173
0
  case ConditionKind::Switch:
21174
0
    Cond = CheckSwitchCondition(Loc, SubExpr);
21175
0
    break;
21176
0
  }
21177
0
  if (Cond.isInvalid()) {
21178
0
    Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21179
0
                              {SubExpr}, PreferredConditionType(CK));
21180
0
    if (!Cond.get())
21181
0
      return ConditionError();
21182
0
  }
21183
  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
21184
0
  FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
21185
0
  if (!FullExpr.get())
21186
0
    return ConditionError();
21187
21188
0
  return ConditionResult(*this, nullptr, FullExpr,
21189
0
                         CK == ConditionKind::ConstexprIf);
21190
0
}
21191
21192
namespace {
21193
  /// A visitor for rebuilding a call to an __unknown_any expression
21194
  /// to have an appropriate type.
21195
  struct RebuildUnknownAnyFunction
21196
    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21197
21198
    Sema &S;
21199
21200
0
    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21201
21202
0
    ExprResult VisitStmt(Stmt *S) {
21203
0
      llvm_unreachable("unexpected statement!");
21204
0
    }
21205
21206
0
    ExprResult VisitExpr(Expr *E) {
21207
0
      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21208
0
        << E->getSourceRange();
21209
0
      return ExprError();
21210
0
    }
21211
21212
    /// Rebuild an expression which simply semantically wraps another
21213
    /// expression which it shares the type and value kind of.
21214
0
    template <class T> ExprResult rebuildSugarExpr(T *E) {
21215
0
      ExprResult SubResult = Visit(E->getSubExpr());
21216
0
      if (SubResult.isInvalid()) return ExprError();
21217
21218
0
      Expr *SubExpr = SubResult.get();
21219
0
      E->setSubExpr(SubExpr);
21220
0
      E->setType(SubExpr->getType());
21221
0
      E->setValueKind(SubExpr->getValueKind());
21222
0
      assert(E->getObjectKind() == OK_Ordinary);
21223
0
      return E;
21224
0
    }
Unexecuted instantiation: SemaExpr.cpp:clang::ActionResult<clang::Expr*, true> (anonymous namespace)::RebuildUnknownAnyFunction::rebuildSugarExpr<clang::UnaryOperator>(clang::UnaryOperator*)
Unexecuted instantiation: SemaExpr.cpp:clang::ActionResult<clang::Expr*, true> (anonymous namespace)::RebuildUnknownAnyFunction::rebuildSugarExpr<clang::ParenExpr>(clang::ParenExpr*)
21225
21226
0
    ExprResult VisitParenExpr(ParenExpr *E) {
21227
0
      return rebuildSugarExpr(E);
21228
0
    }
21229
21230
0
    ExprResult VisitUnaryExtension(UnaryOperator *E) {
21231
0
      return rebuildSugarExpr(E);
21232
0
    }
21233
21234
0
    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21235
0
      ExprResult SubResult = Visit(E->getSubExpr());
21236
0
      if (SubResult.isInvalid()) return ExprError();
21237
21238
0
      Expr *SubExpr = SubResult.get();
21239
0
      E->setSubExpr(SubExpr);
21240
0
      E->setType(S.Context.getPointerType(SubExpr->getType()));
21241
0
      assert(E->isPRValue());
21242
0
      assert(E->getObjectKind() == OK_Ordinary);
21243
0
      return E;
21244
0
    }
21245
21246
0
    ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21247
0
      if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21248
21249
0
      E->setType(VD->getType());
21250
21251
0
      assert(E->isPRValue());
21252
0
      if (S.getLangOpts().CPlusPlus &&
21253
0
          !(isa<CXXMethodDecl>(VD) &&
21254
0
            cast<CXXMethodDecl>(VD)->isInstance()))
21255
0
        E->setValueKind(VK_LValue);
21256
21257
0
      return E;
21258
0
    }
21259
21260
0
    ExprResult VisitMemberExpr(MemberExpr *E) {
21261
0
      return resolveDecl(E, E->getMemberDecl());
21262
0
    }
21263
21264
0
    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21265
0
      return resolveDecl(E, E->getDecl());
21266
0
    }
21267
  };
21268
}
21269
21270
/// Given a function expression of unknown-any type, try to rebuild it
21271
/// to have a function type.
21272
0
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21273
0
  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21274
0
  if (Result.isInvalid()) return ExprError();
21275
0
  return S.DefaultFunctionArrayConversion(Result.get());
21276
0
}
21277
21278
namespace {
21279
  /// A visitor for rebuilding an expression of type __unknown_anytype
21280
  /// into one which resolves the type directly on the referring
21281
  /// expression.  Strict preservation of the original source
21282
  /// structure is not a goal.
21283
  struct RebuildUnknownAnyExpr
21284
    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21285
21286
    Sema &S;
21287
21288
    /// The current destination type.
21289
    QualType DestType;
21290
21291
    RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21292
0
      : S(S), DestType(CastType) {}
21293
21294
0
    ExprResult VisitStmt(Stmt *S) {
21295
0
      llvm_unreachable("unexpected statement!");
21296
0
    }
21297
21298
0
    ExprResult VisitExpr(Expr *E) {
21299
0
      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21300
0
        << E->getSourceRange();
21301
0
      return ExprError();
21302
0
    }
21303
21304
    ExprResult VisitCallExpr(CallExpr *E);
21305
    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21306
21307
    /// Rebuild an expression which simply semantically wraps another
21308
    /// expression which it shares the type and value kind of.
21309
0
    template <class T> ExprResult rebuildSugarExpr(T *E) {
21310
0
      ExprResult SubResult = Visit(E->getSubExpr());
21311
0
      if (SubResult.isInvalid()) return ExprError();
21312
0
      Expr *SubExpr = SubResult.get();
21313
0
      E->setSubExpr(SubExpr);
21314
0
      E->setType(SubExpr->getType());
21315
0
      E->setValueKind(SubExpr->getValueKind());
21316
0
      assert(E->getObjectKind() == OK_Ordinary);
21317
0
      return E;
21318
0
    }
Unexecuted instantiation: SemaExpr.cpp:clang::ActionResult<clang::Expr*, true> (anonymous namespace)::RebuildUnknownAnyExpr::rebuildSugarExpr<clang::UnaryOperator>(clang::UnaryOperator*)
Unexecuted instantiation: SemaExpr.cpp:clang::ActionResult<clang::Expr*, true> (anonymous namespace)::RebuildUnknownAnyExpr::rebuildSugarExpr<clang::ParenExpr>(clang::ParenExpr*)
21319
21320
0
    ExprResult VisitParenExpr(ParenExpr *E) {
21321
0
      return rebuildSugarExpr(E);
21322
0
    }
21323
21324
0
    ExprResult VisitUnaryExtension(UnaryOperator *E) {
21325
0
      return rebuildSugarExpr(E);
21326
0
    }
21327
21328
0
    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21329
0
      const PointerType *Ptr = DestType->getAs<PointerType>();
21330
0
      if (!Ptr) {
21331
0
        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21332
0
          << E->getSourceRange();
21333
0
        return ExprError();
21334
0
      }
21335
21336
0
      if (isa<CallExpr>(E->getSubExpr())) {
21337
0
        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21338
0
          << E->getSourceRange();
21339
0
        return ExprError();
21340
0
      }
21341
21342
0
      assert(E->isPRValue());
21343
0
      assert(E->getObjectKind() == OK_Ordinary);
21344
0
      E->setType(DestType);
21345
21346
      // Build the sub-expression as if it were an object of the pointee type.
21347
0
      DestType = Ptr->getPointeeType();
21348
0
      ExprResult SubResult = Visit(E->getSubExpr());
21349
0
      if (SubResult.isInvalid()) return ExprError();
21350
0
      E->setSubExpr(SubResult.get());
21351
0
      return E;
21352
0
    }
21353
21354
    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21355
21356
    ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21357
21358
0
    ExprResult VisitMemberExpr(MemberExpr *E) {
21359
0
      return resolveDecl(E, E->getMemberDecl());
21360
0
    }
21361
21362
0
    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21363
0
      return resolveDecl(E, E->getDecl());
21364
0
    }
21365
  };
21366
}
21367
21368
/// Rebuilds a call expression which yielded __unknown_anytype.
21369
0
ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21370
0
  Expr *CalleeExpr = E->getCallee();
21371
21372
0
  enum FnKind {
21373
0
    FK_MemberFunction,
21374
0
    FK_FunctionPointer,
21375
0
    FK_BlockPointer
21376
0
  };
21377
21378
0
  FnKind Kind;
21379
0
  QualType CalleeType = CalleeExpr->getType();
21380
0
  if (CalleeType == S.Context.BoundMemberTy) {
21381
0
    assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21382
0
    Kind = FK_MemberFunction;
21383
0
    CalleeType = Expr::findBoundMemberType(CalleeExpr);
21384
0
  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21385
0
    CalleeType = Ptr->getPointeeType();
21386
0
    Kind = FK_FunctionPointer;
21387
0
  } else {
21388
0
    CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21389
0
    Kind = FK_BlockPointer;
21390
0
  }
21391
0
  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21392
21393
  // Verify that this is a legal result type of a function.
21394
0
  if (DestType->isArrayType() || DestType->isFunctionType()) {
21395
0
    unsigned diagID = diag::err_func_returning_array_function;
21396
0
    if (Kind == FK_BlockPointer)
21397
0
      diagID = diag::err_block_returning_array_function;
21398
21399
0
    S.Diag(E->getExprLoc(), diagID)
21400
0
      << DestType->isFunctionType() << DestType;
21401
0
    return ExprError();
21402
0
  }
21403
21404
  // Otherwise, go ahead and set DestType as the call's result.
21405
0
  E->setType(DestType.getNonLValueExprType(S.Context));
21406
0
  E->setValueKind(Expr::getValueKindForType(DestType));
21407
0
  assert(E->getObjectKind() == OK_Ordinary);
21408
21409
  // Rebuild the function type, replacing the result type with DestType.
21410
0
  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21411
0
  if (Proto) {
21412
    // __unknown_anytype(...) is a special case used by the debugger when
21413
    // it has no idea what a function's signature is.
21414
    //
21415
    // We want to build this call essentially under the K&R
21416
    // unprototyped rules, but making a FunctionNoProtoType in C++
21417
    // would foul up all sorts of assumptions.  However, we cannot
21418
    // simply pass all arguments as variadic arguments, nor can we
21419
    // portably just call the function under a non-variadic type; see
21420
    // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21421
    // However, it turns out that in practice it is generally safe to
21422
    // call a function declared as "A foo(B,C,D);" under the prototype
21423
    // "A foo(B,C,D,...);".  The only known exception is with the
21424
    // Windows ABI, where any variadic function is implicitly cdecl
21425
    // regardless of its normal CC.  Therefore we change the parameter
21426
    // types to match the types of the arguments.
21427
    //
21428
    // This is a hack, but it is far superior to moving the
21429
    // corresponding target-specific code from IR-gen to Sema/AST.
21430
21431
0
    ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21432
0
    SmallVector<QualType, 8> ArgTypes;
21433
0
    if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21434
0
      ArgTypes.reserve(E->getNumArgs());
21435
0
      for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21436
0
        ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21437
0
      }
21438
0
      ParamTypes = ArgTypes;
21439
0
    }
21440
0
    DestType = S.Context.getFunctionType(DestType, ParamTypes,
21441
0
                                         Proto->getExtProtoInfo());
21442
0
  } else {
21443
0
    DestType = S.Context.getFunctionNoProtoType(DestType,
21444
0
                                                FnType->getExtInfo());
21445
0
  }
21446
21447
  // Rebuild the appropriate pointer-to-function type.
21448
0
  switch (Kind) {
21449
0
  case FK_MemberFunction:
21450
    // Nothing to do.
21451
0
    break;
21452
21453
0
  case FK_FunctionPointer:
21454
0
    DestType = S.Context.getPointerType(DestType);
21455
0
    break;
21456
21457
0
  case FK_BlockPointer:
21458
0
    DestType = S.Context.getBlockPointerType(DestType);
21459
0
    break;
21460
0
  }
21461
21462
  // Finally, we can recurse.
21463
0
  ExprResult CalleeResult = Visit(CalleeExpr);
21464
0
  if (!CalleeResult.isUsable()) return ExprError();
21465
0
  E->setCallee(CalleeResult.get());
21466
21467
  // Bind a temporary if necessary.
21468
0
  return S.MaybeBindToTemporary(E);
21469
0
}
21470
21471
0
ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21472
  // Verify that this is a legal result type of a call.
21473
0
  if (DestType->isArrayType() || DestType->isFunctionType()) {
21474
0
    S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21475
0
      << DestType->isFunctionType() << DestType;
21476
0
    return ExprError();
21477
0
  }
21478
21479
  // Rewrite the method result type if available.
21480
0
  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21481
0
    assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21482
0
    Method->setReturnType(DestType);
21483
0
  }
21484
21485
  // Change the type of the message.
21486
0
  E->setType(DestType.getNonReferenceType());
21487
0
  E->setValueKind(Expr::getValueKindForType(DestType));
21488
21489
0
  return S.MaybeBindToTemporary(E);
21490
0
}
21491
21492
0
ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21493
  // The only case we should ever see here is a function-to-pointer decay.
21494
0
  if (E->getCastKind() == CK_FunctionToPointerDecay) {
21495
0
    assert(E->isPRValue());
21496
0
    assert(E->getObjectKind() == OK_Ordinary);
21497
21498
0
    E->setType(DestType);
21499
21500
    // Rebuild the sub-expression as the pointee (function) type.
21501
0
    DestType = DestType->castAs<PointerType>()->getPointeeType();
21502
21503
0
    ExprResult Result = Visit(E->getSubExpr());
21504
0
    if (!Result.isUsable()) return ExprError();
21505
21506
0
    E->setSubExpr(Result.get());
21507
0
    return E;
21508
0
  } else if (E->getCastKind() == CK_LValueToRValue) {
21509
0
    assert(E->isPRValue());
21510
0
    assert(E->getObjectKind() == OK_Ordinary);
21511
21512
0
    assert(isa<BlockPointerType>(E->getType()));
21513
21514
0
    E->setType(DestType);
21515
21516
    // The sub-expression has to be a lvalue reference, so rebuild it as such.
21517
0
    DestType = S.Context.getLValueReferenceType(DestType);
21518
21519
0
    ExprResult Result = Visit(E->getSubExpr());
21520
0
    if (!Result.isUsable()) return ExprError();
21521
21522
0
    E->setSubExpr(Result.get());
21523
0
    return E;
21524
0
  } else {
21525
0
    llvm_unreachable("Unhandled cast type!");
21526
0
  }
21527
0
}
21528
21529
0
ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21530
0
  ExprValueKind ValueKind = VK_LValue;
21531
0
  QualType Type = DestType;
21532
21533
  // We know how to make this work for certain kinds of decls:
21534
21535
  //  - functions
21536
0
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21537
0
    if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21538
0
      DestType = Ptr->getPointeeType();
21539
0
      ExprResult Result = resolveDecl(E, VD);
21540
0
      if (Result.isInvalid()) return ExprError();
21541
0
      return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21542
0
                                 VK_PRValue);
21543
0
    }
21544
21545
0
    if (!Type->isFunctionType()) {
21546
0
      S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21547
0
        << VD << E->getSourceRange();
21548
0
      return ExprError();
21549
0
    }
21550
0
    if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21551
      // We must match the FunctionDecl's type to the hack introduced in
21552
      // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21553
      // type. See the lengthy commentary in that routine.
21554
0
      QualType FDT = FD->getType();
21555
0
      const FunctionType *FnType = FDT->castAs<FunctionType>();
21556
0
      const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21557
0
      DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21558
0
      if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21559
0
        SourceLocation Loc = FD->getLocation();
21560
0
        FunctionDecl *NewFD = FunctionDecl::Create(
21561
0
            S.Context, FD->getDeclContext(), Loc, Loc,
21562
0
            FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21563
0
            SC_None, S.getCurFPFeatures().isFPConstrained(),
21564
0
            false /*isInlineSpecified*/, FD->hasPrototype(),
21565
0
            /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21566
21567
0
        if (FD->getQualifier())
21568
0
          NewFD->setQualifierInfo(FD->getQualifierLoc());
21569
21570
0
        SmallVector<ParmVarDecl*, 16> Params;
21571
0
        for (const auto &AI : FT->param_types()) {
21572
0
          ParmVarDecl *Param =
21573
0
            S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21574
0
          Param->setScopeInfo(0, Params.size());
21575
0
          Params.push_back(Param);
21576
0
        }
21577
0
        NewFD->setParams(Params);
21578
0
        DRE->setDecl(NewFD);
21579
0
        VD = DRE->getDecl();
21580
0
      }
21581
0
    }
21582
21583
0
    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21584
0
      if (MD->isInstance()) {
21585
0
        ValueKind = VK_PRValue;
21586
0
        Type = S.Context.BoundMemberTy;
21587
0
      }
21588
21589
    // Function references aren't l-values in C.
21590
0
    if (!S.getLangOpts().CPlusPlus)
21591
0
      ValueKind = VK_PRValue;
21592
21593
  //  - variables
21594
0
  } else if (isa<VarDecl>(VD)) {
21595
0
    if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21596
0
      Type = RefTy->getPointeeType();
21597
0
    } else if (Type->isFunctionType()) {
21598
0
      S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21599
0
        << VD << E->getSourceRange();
21600
0
      return ExprError();
21601
0
    }
21602
21603
  //  - nothing else
21604
0
  } else {
21605
0
    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21606
0
      << VD << E->getSourceRange();
21607
0
    return ExprError();
21608
0
  }
21609
21610
  // Modifying the declaration like this is friendly to IR-gen but
21611
  // also really dangerous.
21612
0
  VD->setType(DestType);
21613
0
  E->setType(Type);
21614
0
  E->setValueKind(ValueKind);
21615
0
  return E;
21616
0
}
21617
21618
/// Check a cast of an unknown-any type.  We intentionally only
21619
/// trigger this for C-style casts.
21620
ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21621
                                     Expr *CastExpr, CastKind &CastKind,
21622
0
                                     ExprValueKind &VK, CXXCastPath &Path) {
21623
  // The type we're casting to must be either void or complete.
21624
0
  if (!CastType->isVoidType() &&
21625
0
      RequireCompleteType(TypeRange.getBegin(), CastType,
21626
0
                          diag::err_typecheck_cast_to_incomplete))
21627
0
    return ExprError();
21628
21629
  // Rewrite the casted expression from scratch.
21630
0
  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21631
0
  if (!result.isUsable()) return ExprError();
21632
21633
0
  CastExpr = result.get();
21634
0
  VK = CastExpr->getValueKind();
21635
0
  CastKind = CK_NoOp;
21636
21637
0
  return CastExpr;
21638
0
}
21639
21640
0
ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21641
0
  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21642
0
}
21643
21644
ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21645
0
                                    Expr *arg, QualType &paramType) {
21646
  // If the syntactic form of the argument is not an explicit cast of
21647
  // any sort, just do default argument promotion.
21648
0
  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21649
0
  if (!castArg) {
21650
0
    ExprResult result = DefaultArgumentPromotion(arg);
21651
0
    if (result.isInvalid()) return ExprError();
21652
0
    paramType = result.get()->getType();
21653
0
    return result;
21654
0
  }
21655
21656
  // Otherwise, use the type that was written in the explicit cast.
21657
0
  assert(!arg->hasPlaceholderType());
21658
0
  paramType = castArg->getTypeAsWritten();
21659
21660
  // Copy-initialize a parameter of that type.
21661
0
  InitializedEntity entity =
21662
0
    InitializedEntity::InitializeParameter(Context, paramType,
21663
0
                                           /*consumed*/ false);
21664
0
  return PerformCopyInitialization(entity, callLoc, arg);
21665
0
}
21666
21667
0
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21668
0
  Expr *orig = E;
21669
0
  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21670
0
  while (true) {
21671
0
    E = E->IgnoreParenImpCasts();
21672
0
    if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21673
0
      E = call->getCallee();
21674
0
      diagID = diag::err_uncasted_call_of_unknown_any;
21675
0
    } else {
21676
0
      break;
21677
0
    }
21678
0
  }
21679
21680
0
  SourceLocation loc;
21681
0
  NamedDecl *d;
21682
0
  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21683
0
    loc = ref->getLocation();
21684
0
    d = ref->getDecl();
21685
0
  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21686
0
    loc = mem->getMemberLoc();
21687
0
    d = mem->getMemberDecl();
21688
0
  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21689
0
    diagID = diag::err_uncasted_call_of_unknown_any;
21690
0
    loc = msg->getSelectorStartLoc();
21691
0
    d = msg->getMethodDecl();
21692
0
    if (!d) {
21693
0
      S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21694
0
        << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21695
0
        << orig->getSourceRange();
21696
0
      return ExprError();
21697
0
    }
21698
0
  } else {
21699
0
    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21700
0
      << E->getSourceRange();
21701
0
    return ExprError();
21702
0
  }
21703
21704
0
  S.Diag(loc, diagID) << d << orig->getSourceRange();
21705
21706
  // Never recoverable.
21707
0
  return ExprError();
21708
0
}
21709
21710
/// Check for operands with placeholder types and complain if found.
21711
/// Returns ExprError() if there was an error and no recovery was possible.
21712
6
ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21713
6
  if (!Context.isDependenceAllowed()) {
21714
    // C cannot handle TypoExpr nodes on either side of a binop because it
21715
    // doesn't handle dependent types properly, so make sure any TypoExprs have
21716
    // been dealt with before checking the operands.
21717
0
    ExprResult Result = CorrectDelayedTyposInExpr(E);
21718
0
    if (!Result.isUsable()) return ExprError();
21719
0
    E = Result.get();
21720
0
  }
21721
21722
6
  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21723
6
  if (!placeholderType) return E;
21724
21725
0
  switch (placeholderType->getKind()) {
21726
21727
  // Overloaded expressions.
21728
0
  case BuiltinType::Overload: {
21729
    // Try to resolve a single function template specialization.
21730
    // This is obligatory.
21731
0
    ExprResult Result = E;
21732
0
    if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21733
0
      return Result;
21734
21735
    // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21736
    // leaves Result unchanged on failure.
21737
0
    Result = E;
21738
0
    if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21739
0
      return Result;
21740
21741
    // If that failed, try to recover with a call.
21742
0
    tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21743
0
                         /*complain*/ true);
21744
0
    return Result;
21745
0
  }
21746
21747
  // Bound member functions.
21748
0
  case BuiltinType::BoundMember: {
21749
0
    ExprResult result = E;
21750
0
    const Expr *BME = E->IgnoreParens();
21751
0
    PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21752
    // Try to give a nicer diagnostic if it is a bound member that we recognize.
21753
0
    if (isa<CXXPseudoDestructorExpr>(BME)) {
21754
0
      PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21755
0
    } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21756
0
      if (ME->getMemberNameInfo().getName().getNameKind() ==
21757
0
          DeclarationName::CXXDestructorName)
21758
0
        PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21759
0
    }
21760
0
    tryToRecoverWithCall(result, PD,
21761
0
                         /*complain*/ true);
21762
0
    return result;
21763
0
  }
21764
21765
  // ARC unbridged casts.
21766
0
  case BuiltinType::ARCUnbridgedCast: {
21767
0
    Expr *realCast = stripARCUnbridgedCast(E);
21768
0
    diagnoseARCUnbridgedCast(realCast);
21769
0
    return realCast;
21770
0
  }
21771
21772
  // Expressions of unknown type.
21773
0
  case BuiltinType::UnknownAny:
21774
0
    return diagnoseUnknownAnyExpr(*this, E);
21775
21776
  // Pseudo-objects.
21777
0
  case BuiltinType::PseudoObject:
21778
0
    return checkPseudoObjectRValue(E);
21779
21780
0
  case BuiltinType::BuiltinFn: {
21781
    // Accept __noop without parens by implicitly converting it to a call expr.
21782
0
    auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21783
0
    if (DRE) {
21784
0
      auto *FD = cast<FunctionDecl>(DRE->getDecl());
21785
0
      unsigned BuiltinID = FD->getBuiltinID();
21786
0
      if (BuiltinID == Builtin::BI__noop) {
21787
0
        E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21788
0
                              CK_BuiltinFnToFnPtr)
21789
0
                .get();
21790
0
        return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21791
0
                                VK_PRValue, SourceLocation(),
21792
0
                                FPOptionsOverride());
21793
0
      }
21794
21795
0
      if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21796
        // Any use of these other than a direct call is ill-formed as of C++20,
21797
        // because they are not addressable functions. In earlier language
21798
        // modes, warn and force an instantiation of the real body.
21799
0
        Diag(E->getBeginLoc(),
21800
0
             getLangOpts().CPlusPlus20
21801
0
                 ? diag::err_use_of_unaddressable_function
21802
0
                 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21803
0
        if (FD->isImplicitlyInstantiable()) {
21804
          // Require a definition here because a normal attempt at
21805
          // instantiation for a builtin will be ignored, and we won't try
21806
          // again later. We assume that the definition of the template
21807
          // precedes this use.
21808
0
          InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21809
0
                                        /*Recursive=*/false,
21810
0
                                        /*DefinitionRequired=*/true,
21811
0
                                        /*AtEndOfTU=*/false);
21812
0
        }
21813
        // Produce a properly-typed reference to the function.
21814
0
        CXXScopeSpec SS;
21815
0
        SS.Adopt(DRE->getQualifierLoc());
21816
0
        TemplateArgumentListInfo TemplateArgs;
21817
0
        DRE->copyTemplateArgumentsInto(TemplateArgs);
21818
0
        return BuildDeclRefExpr(
21819
0
            FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21820
0
            DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21821
0
            DRE->getTemplateKeywordLoc(),
21822
0
            DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21823
0
      }
21824
0
    }
21825
21826
0
    Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21827
0
    return ExprError();
21828
0
  }
21829
21830
0
  case BuiltinType::IncompleteMatrixIdx:
21831
0
    Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21832
0
             ->getRowIdx()
21833
0
             ->getBeginLoc(),
21834
0
         diag::err_matrix_incomplete_index);
21835
0
    return ExprError();
21836
21837
  // Expressions of unknown type.
21838
0
  case BuiltinType::OMPArraySection:
21839
0
    Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21840
0
    return ExprError();
21841
21842
  // Expressions of unknown type.
21843
0
  case BuiltinType::OMPArrayShaping:
21844
0
    return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21845
21846
0
  case BuiltinType::OMPIterator:
21847
0
    return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21848
21849
  // Everything else should be impossible.
21850
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21851
0
  case BuiltinType::Id:
21852
0
#include "clang/Basic/OpenCLImageTypes.def"
21853
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21854
0
  case BuiltinType::Id:
21855
0
#include "clang/Basic/OpenCLExtensionTypes.def"
21856
0
#define SVE_TYPE(Name, Id, SingletonId) \
21857
0
  case BuiltinType::Id:
21858
0
#include "clang/Basic/AArch64SVEACLETypes.def"
21859
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
21860
0
  case BuiltinType::Id:
21861
0
#include "clang/Basic/PPCTypes.def"
21862
0
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21863
0
#include "clang/Basic/RISCVVTypes.def"
21864
0
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21865
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
21866
0
#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21867
0
#define PLACEHOLDER_TYPE(Id, SingletonId)
21868
0
#include "clang/AST/BuiltinTypes.def"
21869
0
    break;
21870
0
  }
21871
21872
0
  llvm_unreachable("invalid placeholder type!");
21873
0
}
21874
21875
0
bool Sema::CheckCaseExpression(Expr *E) {
21876
0
  if (E->isTypeDependent())
21877
0
    return true;
21878
0
  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21879
0
    return E->getType()->isIntegralOrEnumerationType();
21880
0
  return false;
21881
0
}
21882
21883
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21884
ExprResult
21885
0
Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21886
0
  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21887
0
         "Unknown Objective-C Boolean value!");
21888
0
  QualType BoolT = Context.ObjCBuiltinBoolTy;
21889
0
  if (!Context.getBOOLDecl()) {
21890
0
    LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21891
0
                        Sema::LookupOrdinaryName);
21892
0
    if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21893
0
      NamedDecl *ND = Result.getFoundDecl();
21894
0
      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21895
0
        Context.setBOOLDecl(TD);
21896
0
    }
21897
0
  }
21898
0
  if (Context.getBOOLDecl())
21899
0
    BoolT = Context.getBOOLType();
21900
0
  return new (Context)
21901
0
      ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21902
0
}
21903
21904
ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21905
    llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21906
0
    SourceLocation RParen) {
21907
0
  auto FindSpecVersion =
21908
0
      [&](StringRef Platform) -> std::optional<VersionTuple> {
21909
0
    auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21910
0
      return Spec.getPlatform() == Platform;
21911
0
    });
21912
    // Transcribe the "ios" availability check to "maccatalyst" when compiling
21913
    // for "maccatalyst" if "maccatalyst" is not specified.
21914
0
    if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21915
0
      Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21916
0
        return Spec.getPlatform() == "ios";
21917
0
      });
21918
0
    }
21919
0
    if (Spec == AvailSpecs.end())
21920
0
      return std::nullopt;
21921
0
    return Spec->getVersion();
21922
0
  };
21923
21924
0
  VersionTuple Version;
21925
0
  if (auto MaybeVersion =
21926
0
          FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21927
0
    Version = *MaybeVersion;
21928
21929
  // The use of `@available` in the enclosing context should be analyzed to
21930
  // warn when it's used inappropriately (i.e. not if(@available)).
21931
0
  if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21932
0
    Context->HasPotentialAvailabilityViolations = true;
21933
21934
0
  return new (Context)
21935
0
      ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21936
0
}
21937
21938
ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21939
258
                                    ArrayRef<Expr *> SubExprs, QualType T) {
21940
258
  if (!Context.getLangOpts().RecoveryAST)
21941
0
    return ExprError();
21942
21943
258
  if (isSFINAEContext())
21944
0
    return ExprError();
21945
21946
258
  if (T.isNull() || T->isUndeducedType() ||
21947
258
      !Context.getLangOpts().RecoveryASTType)
21948
    // We don't know the concrete type, fallback to dependent type.
21949
257
    T = Context.DependentTy;
21950
21951
258
  return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21952
258
}