Coverage Report

Created: 2021-01-19 06:58

/Users/buildslave/jenkins/workspace/coverage/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/RecursiveASTVisitor.h"
29
#include "clang/AST/TypeLoc.h"
30
#include "clang/Basic/Builtins.h"
31
#include "clang/Basic/PartialDiagnostic.h"
32
#include "clang/Basic/SourceManager.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/Lex/LiteralSupport.h"
35
#include "clang/Lex/Preprocessor.h"
36
#include "clang/Sema/AnalysisBasedWarnings.h"
37
#include "clang/Sema/DeclSpec.h"
38
#include "clang/Sema/DelayedDiagnostic.h"
39
#include "clang/Sema/Designator.h"
40
#include "clang/Sema/Initialization.h"
41
#include "clang/Sema/Lookup.h"
42
#include "clang/Sema/Overload.h"
43
#include "clang/Sema/ParsedTemplate.h"
44
#include "clang/Sema/Scope.h"
45
#include "clang/Sema/ScopeInfo.h"
46
#include "clang/Sema/SemaFixItUtils.h"
47
#include "clang/Sema/SemaInternal.h"
48
#include "clang/Sema/Template.h"
49
#include "llvm/Support/ConvertUTF.h"
50
#include "llvm/Support/SaveAndRestore.h"
51
using namespace clang;
52
using namespace sema;
53
using llvm::RoundingMode;
54
55
/// Determine whether the use of this declaration is valid, without
56
/// emitting diagnostics.
57
37.6k
bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58
  // See if this is an auto-typed variable whose initializer we are parsing.
59
37.6k
  if (ParsingInitForAutoVars.count(D))
60
0
    return false;
61
62
  // See if this is a deleted function.
63
37.6k
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64
8
    if (FD->isDeleted())
65
1
      return false;
66
67
    // If the function has a deduced return type, and we can't deduce it,
68
    // then we can't use it either.
69
7
    if (getLangOpts().CPlusPlus14 && 
FD->getReturnType()->isUndeducedType()0
&&
70
0
        DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71
0
      return false;
72
73
    // See if this is an aligned allocation/deallocation function that is
74
    // unavailable.
75
7
    if (TreatUnavailableAsInvalid &&
76
0
        isUnavailableAlignedAllocationFunction(*FD))
77
0
      return false;
78
37.6k
  }
79
80
  // See if this function is unavailable.
81
37.6k
  if (TreatUnavailableAsInvalid && 
D->getAvailability() == AR_Unavailable17.2k
&&
82
0
      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83
0
    return false;
84
85
37.6k
  return true;
86
37.6k
}
87
88
81.5M
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89
  // Warn if this is used but marked unused.
90
81.5M
  if (const auto *A = D->getAttr<UnusedAttr>()) {
91
    // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92
    // should diagnose them.
93
141k
    if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94
141k
        A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95
141k
      const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96
141k
      if (DC && !DC->hasAttr<UnusedAttr>())
97
141k
        S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98
141k
    }
99
141k
  }
100
81.5M
}
101
102
/// Emit a note explaining that this function is deleted.
103
1.05k
void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104
1.05k
  assert(Decl && Decl->isDeleted());
105
106
1.05k
  if (Decl->isDefaulted()) {
107
    // If the method was explicitly defaulted, point at that declaration.
108
610
    if (!Decl->isImplicit())
109
50
      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110
111
    // Try to diagnose why this special member function was implicitly
112
    // deleted. This might fail, if that reason no longer applies.
113
610
    DiagnoseDeletedDefaultedFunction(Decl);
114
610
    return;
115
610
  }
116
117
445
  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118
445
  if (Ctor && 
Ctor->isInheritingConstructor()246
)
119
8
    return NoteDeletedInheritingConstructor(Ctor);
120
121
437
  Diag(Decl->getLocation(), diag::note_availability_specified_here)
122
437
    << Decl << 1;
123
437
}
124
125
/// Determine whether a FunctionDecl was ever declared with an
126
/// explicit storage class.
127
6.77k
static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128
6.77k
  for (auto I : D->redecls()) {
129
6.77k
    if (I->getStorageClass() != SC_None)
130
6.74k
      return true;
131
6.77k
  }
132
26
  return false;
133
6.77k
}
134
135
/// Check whether we're in an extern inline function and referring to a
136
/// variable or function with internal linkage (C11 6.7.4p3).
137
///
138
/// This is only a warning because we used to silently accept this code, but
139
/// in many cases it will not behave correctly. This is not enabled in C++ mode
140
/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141
/// and so while there may still be user mistakes, most of the time we can't
142
/// prove that there are errors.
143
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144
                                                      const NamedDecl *D,
145
81.5M
                                                      SourceLocation Loc) {
146
  // This is disabled under C++; there are too many ways for this to fire in
147
  // contexts where the warning is a false positive, or where it is technically
148
  // correct but benign.
149
81.5M
  if (S.getLangOpts().CPlusPlus)
150
24.6M
    return;
151
152
  // Check if this is an inlined function or method.
153
56.8M
  FunctionDecl *Current = S.getCurFunctionDecl();
154
56.8M
  if (!Current)
155
45.4M
    return;
156
11.3M
  if (!Current->isInlined())
157
621k
    return;
158
10.7M
  if (!Current->isExternallyVisible())
159
10.6M
    return;
160
161
  // Check if the decl has internal linkage.
162
122k
  if (D->getFormalLinkage() != InternalLinkage)
163
115k
    return;
164
165
  // Downgrade from ExtWarn to Extension if
166
  //  (1) the supposedly external inline function is in the main file,
167
  //      and probably won't be included anywhere else.
168
  //  (2) the thing we're referencing is a pure function.
169
  //  (3) the thing we're referencing is another inline function.
170
  // This last can give us false negatives, but it's better than warning on
171
  // wrappers for simple C library functions.
172
6.76k
  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173
6.76k
  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174
6.76k
  if (!DowngradeWarning && 
UsedFn6.75k
)
175
6.75k
    DowngradeWarning = UsedFn->isInlined() || 
UsedFn->hasAttr<ConstAttr>()19
;
176
177
6.73k
  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178
22
                               : diag::ext_internal_in_extern_inline)
179
6.76k
    << /*IsVar=*/!UsedFn << D;
180
181
6.76k
  S.MaybeSuggestAddingStaticToDecl(Current);
182
183
6.76k
  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184
6.76k
      << D;
185
6.76k
}
186
187
6.77k
void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188
6.77k
  const FunctionDecl *First = Cur->getFirstDecl();
189
190
  // Suggest "static" on the function, if possible.
191
6.77k
  if (!hasAnyExplicitStorageClass(First)) {
192
26
    SourceLocation DeclBegin = First->getSourceRange().getBegin();
193
26
    Diag(DeclBegin, diag::note_convert_inline_to_static)
194
26
      << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195
26
  }
196
6.77k
}
197
198
/// Determine whether the use of this declaration is valid, and
199
/// emit any corresponding diagnostics.
200
///
201
/// This routine diagnoses various problems with referencing
202
/// declarations that can occur when using a declaration. For example,
203
/// it might warn if a deprecated or unavailable declaration is being
204
/// used, or produce an error (and return true) if a C++0x deleted
205
/// function is being used.
206
///
207
/// \returns true if there was an error (this declaration cannot be
208
/// referenced), false otherwise.
209
///
210
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211
                             const ObjCInterfaceDecl *UnknownObjCClass,
212
                             bool ObjCPropertyAccess,
213
                             bool AvoidPartialAvailabilityChecks,
214
81.5M
                             ObjCInterfaceDecl *ClassReceiver) {
215
81.5M
  SourceLocation Loc = Locs.front();
216
81.5M
  if (getLangOpts().CPlusPlus && 
isa<FunctionDecl>(D)24.6M
) {
217
    // If there were any diagnostics suppressed by template argument deduction,
218
    // emit them now.
219
1.91M
    auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220
1.91M
    if (Pos != SuppressedDiagnostics.end()) {
221
3.76k
      for (const PartialDiagnosticAt &Suppressed : Pos->second)
222
4.37k
        Diag(Suppressed.first, Suppressed.second);
223
224
      // Clear out the list of suppressed diagnostics, so that we don't emit
225
      // them again for this specialization. However, we don't obsolete this
226
      // entry from the table, because we want to avoid ever emitting these
227
      // diagnostics again.
228
3.76k
      Pos->second.clear();
229
3.76k
    }
230
231
    // C++ [basic.start.main]p3:
232
    //   The function 'main' shall not be used within a program.
233
1.91M
    if (cast<FunctionDecl>(D)->isMain())
234
75
      Diag(Loc, diag::ext_main_used);
235
236
1.91M
    diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237
1.91M
  }
238
239
  // See if this is an auto-typed variable whose initializer we are parsing.
240
81.5M
  if (ParsingInitForAutoVars.count(D)) {
241
23
    if (isa<BindingDecl>(D)) {
242
1
      Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243
1
        << D->getDeclName();
244
22
    } else {
245
22
      Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246
22
        << D->getDeclName() << cast<VarDecl>(D)->getType();
247
22
    }
248
23
    return true;
249
23
  }
250
251
81.5M
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252
    // See if this is a deleted function.
253
4.12M
    if (FD->isDeleted()) {
254
167
      auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255
167
      if (Ctor && 
Ctor->isInheritingConstructor()10
)
256
8
        Diag(Loc, diag::err_deleted_inherited_ctor_use)
257
8
            << Ctor->getParent()
258
8
            << Ctor->getInheritedConstructor().getConstructor()->getParent();
259
159
      else
260
159
        Diag(Loc, diag::err_deleted_function_use);
261
167
      NoteDeletedFunction(FD);
262
167
      return true;
263
167
    }
264
265
    // [expr.prim.id]p4
266
    //   A program that refers explicitly or implicitly to a function with a
267
    //   trailing requires-clause whose constraint-expression is not satisfied,
268
    //   other than to declare it, is ill-formed. [...]
269
    //
270
    // See if this is a function with constraints that need to be satisfied.
271
    // Check this before deducing the return type, as it might instantiate the
272
    // definition.
273
4.12M
    if (FD->getTrailingRequiresClause()) {
274
67
      ConstraintSatisfaction Satisfaction;
275
67
      if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276
        // A diagnostic will have already been generated (non-constant
277
        // constraint expression, for example)
278
1
        return true;
279
66
      if (!Satisfaction.IsSatisfied) {
280
15
        Diag(Loc,
281
15
             diag::err_reference_to_function_with_unsatisfied_constraints)
282
15
            << D;
283
15
        DiagnoseUnsatisfiedConstraint(Satisfaction);
284
15
        return true;
285
15
      }
286
4.12M
    }
287
288
    // If the function has a deduced return type, and we can't deduce it,
289
    // then we can't use it either.
290
4.12M
    if (getLangOpts().CPlusPlus14 && 
FD->getReturnType()->isUndeducedType()397k
&&
291
2.05k
        DeduceReturnType(FD, Loc))
292
30
      return true;
293
294
4.12M
    if (getLangOpts().CUDA && 
!CheckCUDACall(Loc, FD)6.03k
)
295
87
      return true;
296
297
4.12M
    if (getLangOpts().SYCLIsDevice && 
!checkSYCLDeviceFunction(Loc, FD)94
)
298
0
      return true;
299
81.5M
  }
300
301
81.5M
  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302
    // Lambdas are only default-constructible or assignable in C++2a onwards.
303
1.17M
    if (MD->getParent()->isLambda() &&
304
18.8k
        ((isa<CXXConstructorDecl>(MD) &&
305
4.13k
          cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306
18.7k
         MD->isCopyAssignmentOperator() || 
MD->isMoveAssignmentOperator()18.7k
)) {
307
136
      Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308
136
        << !isa<CXXConstructorDecl>(MD);
309
136
    }
310
1.17M
  }
311
312
81.5M
  auto getReferencedObjCProp = [](const NamedDecl *D) ->
313
81.5M
                                      const ObjCPropertyDecl * {
314
81.5M
    if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315
23.5k
      return MD->findPropertyDecl();
316
81.5M
    return nullptr;
317
81.5M
  };
318
81.5M
  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319
1.98k
    if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320
0
      return true;
321
81.5M
  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322
21
      return true;
323
21
  }
324
325
  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326
  // Only the variables omp_in and omp_out are allowed in the combiner.
327
  // Only the variables omp_priv and omp_orig are allowed in the
328
  // initializer-clause.
329
81.5M
  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330
81.5M
  if (LangOpts.OpenMP && 
DRD1.73M
&&
!CurContext->containsDecl(D)1.89k
&&
331
341
      isa<VarDecl>(D)) {
332
54
    Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333
54
        << getCurFunction()->HasOMPDeclareReductionCombiner;
334
54
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335
54
    return true;
336
54
  }
337
338
  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339
  //  List-items in map clauses on this construct may only refer to the declared
340
  //  variable var and entities that could be referenced by a procedure defined
341
  //  at the same location
342
81.5M
  if (LangOpts.OpenMP && 
isa<VarDecl>(D)1.73M
&&
343
1.32M
      !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
344
8
    Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
345
8
        << getOpenMPDeclareMapperVarName();
346
8
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
347
8
    return true;
348
8
  }
349
350
81.5M
  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
351
81.5M
                             AvoidPartialAvailabilityChecks, ClassReceiver);
352
353
81.5M
  DiagnoseUnusedOfDecl(*this, D, Loc);
354
355
81.5M
  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
356
357
  // CUDA/HIP: Diagnose invalid references of host global variables in device
358
  // functions. Reference of device global variables in host functions is
359
  // allowed through shadow variables therefore it is not diagnosed.
360
81.5M
  if (LangOpts.CUDAIsDevice) {
361
14.6k
    auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext);
362
14.6k
    auto Target = IdentifyCUDATarget(FD);
363
14.6k
    if (FD && 
Target != CFT_Host11.3k
) {
364
10.3k
      const auto *VD = dyn_cast<VarDecl>(D);
365
10.3k
      if (VD && 
VD->hasGlobalStorage()6.57k
&&
!VD->hasAttr<CUDADeviceAttr>()488
&&
366
283
          !VD->hasAttr<CUDAConstantAttr>() && 
!VD->hasAttr<CUDASharedAttr>()243
&&
367
42
          !VD->getType()->isCUDADeviceBuiltinSurfaceType() &&
368
41
          !VD->getType()->isCUDADeviceBuiltinTextureType() &&
369
38
          !VD->isConstexpr() && 
!VD->getType().isConstQualified()30
)
370
12
        targetDiag(*Locs.begin(), diag::err_ref_bad_target)
371
12
            << /*host*/ 2 << /*variable*/ 1 << VD << Target;
372
10.3k
    }
373
14.6k
  }
374
375
81.5M
  if (LangOpts.SYCLIsDevice || 
(81.5M
LangOpts.OpenMP81.5M
&&
LangOpts.OpenMPIsDevice1.73M
)) {
376
99.7k
    if (const auto *VD = dyn_cast<ValueDecl>(D))
377
93.8k
      checkDeviceDecl(VD, Loc);
378
379
99.7k
    if (!Context.getTargetInfo().isTLSSupported())
380
64.9k
      if (const auto *VD = dyn_cast<VarDecl>(D))
381
43.7k
        if (VD->getTLSKind() != VarDecl::TLS_None)
382
8
          targetDiag(*Locs.begin(), diag::err_thread_unsupported);
383
99.7k
  }
384
385
81.5M
  if (isa<ParmVarDecl>(D) && 
isa<RequiresExprBodyDecl>(D->getDeclContext())7.96M
&&
386
174
      !isUnevaluatedContext()) {
387
    // C++ [expr.prim.req.nested] p3
388
    //   A local parameter shall only appear as an unevaluated operand
389
    //   (Clause 8) within the constraint-expression.
390
2
    Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
391
2
        << D;
392
2
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
393
2
    return true;
394
2
  }
395
396
81.5M
  return false;
397
81.5M
}
398
399
/// DiagnoseSentinelCalls - This routine checks whether a call or
400
/// message-send is to a declaration with the sentinel attribute, and
401
/// if so, it checks that the requirements of the sentinel are
402
/// satisfied.
403
void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
404
3.45M
                                 ArrayRef<Expr *> Args) {
405
3.45M
  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
406
3.45M
  if (!attr)
407
3.45M
    return;
408
409
  // The number of formal parameters of the declaration.
410
280
  unsigned numFormalParams;
411
412
  // The kind of declaration.  This is also an index into a %select in
413
  // the diagnostic.
414
280
  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
415
416
280
  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
417
241
    numFormalParams = MD->param_size();
418
241
    calleeType = CT_Method;
419
39
  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
420
27
    numFormalParams = FD->param_size();
421
27
    calleeType = CT_Function;
422
12
  } else if (isa<VarDecl>(D)) {
423
12
    QualType type = cast<ValueDecl>(D)->getType();
424
12
    const FunctionType *fn = nullptr;
425
12
    if (const PointerType *ptr = type->getAs<PointerType>()) {
426
6
      fn = ptr->getPointeeType()->getAs<FunctionType>();
427
6
      if (!fn) 
return0
;
428
6
      calleeType = CT_Function;
429
6
    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
430
6
      fn = ptr->getPointeeType()->castAs<FunctionType>();
431
6
      calleeType = CT_Block;
432
0
    } else {
433
0
      return;
434
0
    }
435
436
12
    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
437
12
      numFormalParams = proto->getNumParams();
438
0
    } else {
439
0
      numFormalParams = 0;
440
0
    }
441
0
  } else {
442
0
    return;
443
0
  }
444
445
  // "nullPos" is the number of formal parameters at the end which
446
  // effectively count as part of the variadic arguments.  This is
447
  // useful if you would prefer to not have *any* formal parameters,
448
  // but the language forces you to have at least one.
449
280
  unsigned nullPos = attr->getNullPos();
450
280
  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
451
280
  numFormalParams = (nullPos > numFormalParams ? 
00
: numFormalParams - nullPos);
452
453
  // The number of arguments which should follow the sentinel.
454
280
  unsigned numArgsAfterSentinel = attr->getSentinel();
455
456
  // If there aren't enough arguments for all the formal parameters,
457
  // the sentinel, and the args after the sentinel, complain.
458
280
  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
459
4
    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
460
4
    Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
461
4
    return;
462
4
  }
463
464
  // Otherwise, find the sentinel expression.
465
276
  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
466
276
  if (!sentinelExpr) 
return0
;
467
276
  if (sentinelExpr->isValueDependent()) 
return0
;
468
276
  if (Context.isSentinelNullExpr(sentinelExpr)) 
return251
;
469
470
  // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
471
  // or 'NULL' if those are actually defined in the context.  Only use
472
  // 'nil' for ObjC methods, where it's much more likely that the
473
  // variadic arguments form a list of object pointers.
474
25
  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
475
25
  std::string NullValue;
476
25
  if (calleeType == CT_Method && 
PP.isMacroDefined("nil")5
)
477
2
    NullValue = "nil";
478
23
  else if (getLangOpts().CPlusPlus11)
479
5
    NullValue = "nullptr";
480
18
  else if (PP.isMacroDefined("NULL"))
481
13
    NullValue = "NULL";
482
5
  else
483
5
    NullValue = "(void*) 0";
484
485
25
  if (MissingNilLoc.isInvalid())
486
1
    Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
487
24
  else
488
24
    Diag(MissingNilLoc, diag::warn_missing_sentinel)
489
24
      << int(calleeType)
490
24
      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
491
25
  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
492
25
}
493
494
84
SourceRange Sema::getExprRange(Expr *E) const {
495
84
  return E ? E->getSourceRange() : 
SourceRange()0
;
496
84
}
497
498
//===----------------------------------------------------------------------===//
499
//  Standard Promotions and Conversions
500
//===----------------------------------------------------------------------===//
501
502
/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
503
25.7M
ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
504
  // Handle any placeholder expressions which made it here.
505
25.7M
  if (E->getType()->isPlaceholderType()) {
506
25
    ExprResult result = CheckPlaceholderExpr(E);
507
25
    if (result.isInvalid()) 
return ExprError()2
;
508
23
    E = result.get();
509
23
  }
510
511
25.7M
  QualType Ty = E->getType();
512
25.7M
  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
513
514
25.7M
  if (Ty->isFunctionType()) {
515
2.38k
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
516
2.36k
      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
517
2.36k
        if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
518
11
          return ExprError();
519
520
2.37k
    E = ImpCastExprToType(E, Context.getPointerType(Ty),
521
2.37k
                          CK_FunctionToPointerDecay).get();
522
25.7M
  } else if (Ty->isArrayType()) {
523
    // In C90 mode, arrays only promote to pointers if the array expression is
524
    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
525
    // type 'array of type' is converted to an expression that has type 'pointer
526
    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
527
    // that has type 'array of type' ...".  The relevant change is "an lvalue"
528
    // (C90) to "an expression" (C99).
529
    //
530
    // C++ 4.2p1:
531
    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
532
    // T" can be converted to an rvalue of type "pointer to T".
533
    //
534
128k
    if (getLangOpts().C99 || 
getLangOpts().CPlusPlus73.2k
||
E->isLValue()1.24k
)
535
128k
      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
536
128k
                            CK_ArrayToPointerDecay).get();
537
128k
  }
538
25.7M
  return E;
539
25.7M
}
540
541
12.0M
static void CheckForNullPointerDereference(Sema &S, Expr *E) {
542
  // Check to see if we are dereferencing a null pointer.  If so,
543
  // and if not volatile-qualified, this is undefined behavior that the
544
  // optimizer will delete, so warn about it.  People sometimes try to use this
545
  // to get a deterministic trap and are surprised by clang's behavior.  This
546
  // only handles the pattern "*null", which is a very syntactic check.
547
12.0M
  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
548
12.0M
  if (UO && 
UO->getOpcode() == UO_Deref88.5k
&&
549
80.0k
      UO->getSubExpr()->getType()->isPointerType()) {
550
80.0k
    const LangAS AS =
551
80.0k
        UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
552
80.0k
    if ((!isTargetAddressSpace(AS) ||
553
15
         (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
554
80.0k
        UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
555
80.0k
            S.Context, Expr::NPC_ValueDependentIsNotNull) &&
556
1.09k
        !UO->getType().isVolatileQualified()) {
557
36
      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
558
36
                            S.PDiag(diag::warn_indirection_through_null)
559
36
                                << UO->getSubExpr()->getSourceRange());
560
36
      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561
36
                            S.PDiag(diag::note_indirection_through_null));
562
36
    }
563
80.0k
  }
564
12.0M
}
565
566
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
567
                                    SourceLocation AssignLoc,
568
3.06k
                                    const Expr* RHS) {
569
3.06k
  const ObjCIvarDecl *IV = OIRE->getDecl();
570
3.06k
  if (!IV)
571
0
    return;
572
573
3.06k
  DeclarationName MemberName = IV->getDeclName();
574
3.06k
  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
575
3.06k
  if (!Member || !Member->isStr("isa"))
576
3.04k
    return;
577
578
19
  const Expr *Base = OIRE->getBase();
579
19
  QualType BaseType = Base->getType();
580
19
  if (OIRE->isArrow())
581
18
    BaseType = BaseType->getPointeeType();
582
19
  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
583
19
    if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
584
19
      ObjCInterfaceDecl *ClassDeclared = nullptr;
585
19
      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
586
19
      if (!ClassDeclared->getSuperClass()
587
16
          && (*ClassDeclared->ivar_begin()) == IV) {
588
11
        if (RHS) {
589
4
          NamedDecl *ObjectSetClass =
590
4
            S.LookupSingleName(S.TUScope,
591
4
                               &S.Context.Idents.get("object_setClass"),
592
4
                               SourceLocation(), S.LookupOrdinaryName);
593
4
          if (ObjectSetClass) {
594
3
            SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
595
3
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
596
3
                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
597
3
                                              "object_setClass(")
598
3
                << FixItHint::CreateReplacement(
599
3
                       SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
600
3
                << FixItHint::CreateInsertion(RHSLocEnd, ")");
601
3
          }
602
1
          else
603
1
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
604
7
        } else {
605
7
          NamedDecl *ObjectGetClass =
606
7
            S.LookupSingleName(S.TUScope,
607
7
                               &S.Context.Idents.get("object_getClass"),
608
7
                               SourceLocation(), S.LookupOrdinaryName);
609
7
          if (ObjectGetClass)
610
4
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
611
4
                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
612
4
                                              "object_getClass(")
613
4
                << FixItHint::CreateReplacement(
614
4
                       SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
615
3
          else
616
3
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
617
7
        }
618
11
        S.Diag(IV->getLocation(), diag::note_ivar_decl);
619
11
      }
620
19
    }
621
19
}
622
623
39.6M
ExprResult Sema::DefaultLvalueConversion(Expr *E) {
624
  // Handle any placeholder expressions which made it here.
625
39.6M
  if (E->getType()->isPlaceholderType()) {
626
63
    ExprResult result = CheckPlaceholderExpr(E);
627
63
    if (result.isInvalid()) 
return ExprError()20
;
628
43
    E = result.get();
629
43
  }
630
631
  // C++ [conv.lval]p1:
632
  //   A glvalue of a non-function, non-array type T can be
633
  //   converted to a prvalue.
634
39.6M
  if (!E->isGLValue()) 
return E29.2M
;
635
636
10.3M
  QualType T = E->getType();
637
10.3M
  assert(!T.isNull() && "r-value conversion on typeless expression?");
638
639
  // lvalue-to-rvalue conversion cannot be applied to function or array types.
640
10.3M
  if (T->isFunctionType() || 
T->isArrayType()10.3M
)
641
35
    return E;
642
643
  // We don't want to throw lvalue-to-rvalue casts on top of
644
  // expressions of certain types in C++.
645
10.3M
  if (getLangOpts().CPlusPlus &&
646
5.05M
      (E->getType() == Context.OverloadTy ||
647
5.05M
       T->isDependentType() ||
648
5.05M
       T->isRecordType()))
649
34.2k
    return E;
650
651
  // The C standard is actually really unclear on this point, and
652
  // DR106 tells us what the result should be but not why.  It's
653
  // generally best to say that void types just doesn't undergo
654
  // lvalue-to-rvalue at all.  Note that expressions of unqualified
655
  // 'void' type are never l-values, but qualified void can be.
656
10.3M
  if (T->isVoidType())
657
11
    return E;
658
659
  // OpenCL usually rejects direct accesses to values of 'half' type.
660
10.3M
  if (getLangOpts().OpenCL && 
!getOpenCLOptions().isEnabled("cl_khr_fp16")10.5k
&&
661
5.53k
      T->isHalfType()) {
662
4
    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663
4
      << 0 << T;
664
4
    return ExprError();
665
4
  }
666
667
10.3M
  CheckForNullPointerDereference(*this, E);
668
10.3M
  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669
45
    NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670
45
                                     &Context.Idents.get("object_getClass"),
671
45
                                     SourceLocation(), LookupOrdinaryName);
672
45
    if (ObjectGetClass)
673
6
      Diag(E->getExprLoc(), diag::warn_objc_isa_use)
674
6
          << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
675
6
          << FixItHint::CreateReplacement(
676
6
                 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677
39
    else
678
39
      Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679
45
  }
680
10.3M
  else if (const ObjCIvarRefExpr *OIRE =
681
1.61k
            dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682
1.61k
    DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683
684
  // C++ [conv.lval]p1:
685
  //   [...] If T is a non-class type, the type of the prvalue is the
686
  //   cv-unqualified version of T. Otherwise, the type of the
687
  //   rvalue is T.
688
  //
689
  // C99 6.3.2.1p2:
690
  //   If the lvalue has qualified type, the value has the unqualified
691
  //   version of the type of the lvalue; otherwise, the value has the
692
  //   type of the lvalue.
693
10.3M
  if (T.hasQualifiers())
694
1.31M
    T = T.getUnqualifiedType();
695
696
  // Under the MS ABI, lock down the inheritance model now.
697
10.3M
  if (T->isMemberPointerType() &&
698
1.02k
      Context.getTargetInfo().getCXXABI().isMicrosoft())
699
114
    (void)isCompleteType(E->getExprLoc(), T);
700
701
10.3M
  ExprResult Res = CheckLValueToRValueConversionOperand(E);
702
10.3M
  if (Res.isInvalid())
703
0
    return Res;
704
10.3M
  E = Res.get();
705
706
  // Loading a __weak object implicitly retains the value, so we need a cleanup to
707
  // balance that.
708
10.3M
  if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709
291
    Cleanup.setExprNeedsCleanups(true);
710
711
10.3M
  if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
712
112
    Cleanup.setExprNeedsCleanups(true);
713
714
  // C++ [conv.lval]p3:
715
  //   If T is cv std::nullptr_t, the result is a null pointer constant.
716
10.3M
  CastKind CK = T->isNullPtrType() ? 
CK_NullToPointer1.11k
: CK_LValueToRValue;
717
10.3M
  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
718
10.3M
                                 CurFPFeatureOverrides());
719
720
  // C11 6.3.2.1p2:
721
  //   ... if the lvalue has atomic type, the value has the non-atomic version
722
  //   of the type of the lvalue ...
723
10.3M
  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724
148
    T = Atomic->getValueType().getUnqualifiedType();
725
148
    Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726
148
                                   nullptr, VK_RValue, FPOptionsOverride());
727
148
  }
728
729
10.3M
  return Res;
730
10.3M
}
731
732
25.7M
ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733
25.7M
  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734
25.7M
  if (Res.isInvalid())
735
13
    return ExprError();
736
25.7M
  Res = DefaultLvalueConversion(Res.get());
737
25.7M
  if (Res.isInvalid())
738
4
    return ExprError();
739
25.7M
  return Res;
740
25.7M
}
741
742
/// CallExprUnaryConversions - a special case of an unary conversion
743
/// performed on a function designator of a call expression.
744
1.49M
ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745
1.49M
  QualType Ty = E->getType();
746
1.49M
  ExprResult Res = E;
747
  // Only do implicit cast for a function type, but not for a pointer
748
  // to function type.
749
1.49M
  if (Ty->isFunctionType()) {
750
1.48M
    Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751
1.48M
                            CK_FunctionToPointerDecay);
752
1.48M
    if (Res.isInvalid())
753
0
      return ExprError();
754
1.49M
  }
755
1.49M
  Res = DefaultLvalueConversion(Res.get());
756
1.49M
  if (Res.isInvalid())
757
16
    return ExprError();
758
1.49M
  return Res.get();
759
1.49M
}
760
761
/// UsualUnaryConversions - Performs various conversions that are common to most
762
/// operators (C99 6.3). The conversions of array and function types are
763
/// sometimes suppressed. For example, the array->pointer conversion doesn't
764
/// apply if the array is an argument to the sizeof or address (&) operators.
765
/// In these instances, this routine should *not* be called.
766
9.85M
ExprResult Sema::UsualUnaryConversions(Expr *E) {
767
  // First, convert to an r-value.
768
9.85M
  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769
9.85M
  if (Res.isInvalid())
770
0
    return ExprError();
771
9.85M
  E = Res.get();
772
773
9.85M
  QualType Ty = E->getType();
774
9.85M
  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775
776
  // Half FP have to be promoted to float unless it is natively supported
777
9.85M
  if (Ty->isHalfType() && 
!getLangOpts().NativeHalfType1.47k
)
778
1.00k
    return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
779
780
  // Try to perform integral promotions if the object has a theoretically
781
  // promotable type.
782
9.85M
  if (Ty->isIntegralOrUnscopedEnumerationType()) {
783
    // C99 6.3.1.1p2:
784
    //
785
    //   The following may be used in an expression wherever an int or
786
    //   unsigned int may be used:
787
    //     - an object or expression with an integer type whose integer
788
    //       conversion rank is less than or equal to the rank of int
789
    //       and unsigned int.
790
    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
791
    //
792
    //   If an int can represent all values of the original type, the
793
    //   value is converted to an int; otherwise, it is converted to an
794
    //   unsigned int. These are called the integer promotions. All
795
    //   other types are unchanged by the integer promotions.
796
797
9.46M
    QualType PTy = Context.isPromotableBitField(E);
798
9.46M
    if (!PTy.isNull()) {
799
1.52k
      E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800
1.52k
      return E;
801
1.52k
    }
802
9.46M
    if (Ty->isPromotableIntegerType()) {
803
190k
      QualType PT = Context.getPromotedIntegerType(Ty);
804
190k
      E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
805
190k
      return E;
806
190k
    }
807
9.66M
  }
808
9.66M
  return E;
809
9.66M
}
810
811
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
812
/// do not have a prototype. Arguments that have type float or __fp16
813
/// are promoted to double. All other argument types are converted by
814
/// UsualUnaryConversions().
815
85.9k
ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816
85.9k
  QualType Ty = E->getType();
817
85.9k
  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
818
819
85.9k
  ExprResult Res = UsualUnaryConversions(E);
820
85.9k
  if (Res.isInvalid())
821
0
    return ExprError();
822
85.9k
  E = Res.get();
823
824
  // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
825
  // promote to double.
826
  // Note that default argument promotion applies only to float (and
827
  // half/fp16); it does not apply to _Float16.
828
85.9k
  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
829
85.9k
  if (BTy && 
(60.6k
BTy->getKind() == BuiltinType::Half60.6k
||
830
60.6k
              BTy->getKind() == BuiltinType::Float)) {
831
814
    if (getLangOpts().OpenCL &&
832
6
        !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
833
2
        if (BTy->getKind() == BuiltinType::Half) {
834
0
            E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
835
0
        }
836
812
    } else {
837
812
      E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
838
812
    }
839
814
  }
840
841
  // C++ performs lvalue-to-rvalue conversion as a default argument
842
  // promotion, even on class types, but note:
843
  //   C++11 [conv.lval]p2:
844
  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
845
  //     operand or a subexpression thereof the value contained in the
846
  //     referenced object is not accessed. Otherwise, if the glvalue
847
  //     has a class type, the conversion copy-initializes a temporary
848
  //     of type T from the glvalue and the result of the conversion
849
  //     is a prvalue for the temporary.
850
  // FIXME: add some way to gate this entire thing for correctness in
851
  // potentially potentially evaluated contexts.
852
85.9k
  if (getLangOpts().CPlusPlus && 
E->isGLValue()63.4k
&&
!isUnevaluatedContext()244
) {
853
230
    ExprResult Temp = PerformCopyInitialization(
854
230
                       InitializedEntity::InitializeTemporary(E->getType()),
855
230
                                                E->getExprLoc(), E);
856
230
    if (Temp.isInvalid())
857
8
      return ExprError();
858
222
    E = Temp.get();
859
222
  }
860
861
85.9k
  return E;
862
85.9k
}
863
864
/// Determine the degree of POD-ness for an expression.
865
/// Incomplete types are considered POD, since this check can be performed
866
/// when we're in an unevaluated context.
867
135k
Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
868
135k
  if (Ty->isIncompleteType()) {
869
    // C++11 [expr.call]p7:
870
    //   After these conversions, if the argument does not have arithmetic,
871
    //   enumeration, pointer, pointer to member, or class type, the program
872
    //   is ill-formed.
873
    //
874
    // Since we've already performed array-to-pointer and function-to-pointer
875
    // decay, the only such type in C++ is cv void. This also handles
876
    // initializer lists as variadic arguments.
877
14
    if (Ty->isVoidType())
878
11
      return VAK_Invalid;
879
880
3
    if (Ty->isObjCObjectType())
881
0
      return VAK_Invalid;
882
3
    return VAK_Valid;
883
3
  }
884
885
135k
  if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
886
2
    return VAK_Invalid;
887
888
135k
  if (Ty.isCXX98PODType(Context))
889
134k
    return VAK_Valid;
890
891
  // C++11 [expr.call]p7:
892
  //   Passing a potentially-evaluated argument of class type (Clause 9)
893
  //   having a non-trivial copy constructor, a non-trivial move constructor,
894
  //   or a non-trivial destructor, with no corresponding parameter,
895
  //   is conditionally-supported with implementation-defined semantics.
896
468
  if (getLangOpts().CPlusPlus11 && 
!Ty->isDependentType()329
)
897
329
    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
898
329
      if (!Record->hasNonTrivialCopyConstructor() &&
899
271
          !Record->hasNonTrivialMoveConstructor() &&
900
271
          !Record->hasNonTrivialDestructor())
901
254
        return VAK_ValidInCXX11;
902
903
214
  if (getLangOpts().ObjCAutoRefCount && 
Ty->isObjCLifetimeType()0
)
904
0
    return VAK_Valid;
905
906
214
  if (Ty->isObjCObjectType())
907
10
    return VAK_Invalid;
908
909
204
  if (getLangOpts().MSVCCompat)
910
60
    return VAK_MSVCUndefined;
911
912
  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
913
  // permitted to reject them. We should consider doing so.
914
144
  return VAK_Undefined;
915
144
}
916
917
59.8k
void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
918
  // Don't allow one to pass an Objective-C interface to a vararg.
919
59.8k
  const QualType &Ty = E->getType();
920
59.8k
  VarArgKind VAK = isValidVarArgType(Ty);
921
922
  // Complain about passing non-POD types through varargs.
923
59.8k
  switch (VAK) {
924
115
  case VAK_ValidInCXX11:
925
115
    DiagRuntimeBehavior(
926
115
        E->getBeginLoc(), nullptr,
927
115
        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
928
115
    LLVM_FALLTHROUGH;
929
59.7k
  case VAK_Valid:
930
59.7k
    if (Ty->isRecordType()) {
931
      // This is unlikely to be what the user intended. If the class has a
932
      // 'c_str' member function, the user probably meant to call that.
933
1.28k
      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
934
1.28k
                          PDiag(diag::warn_pass_class_arg_to_vararg)
935
1.28k
                              << Ty << CT << hasCStrMethod(E) << ".c_str()");
936
1.28k
    }
937
59.7k
    break;
938
939
60
  case VAK_Undefined:
940
90
  case VAK_MSVCUndefined:
941
90
    DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
942
90
                        PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
943
90
                            << getLangOpts().CPlusPlus11 << Ty << CT);
944
90
    break;
945
946
7
  case VAK_Invalid:
947
7
    if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
948
1
      Diag(E->getBeginLoc(),
949
1
           diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
950
1
          << Ty << CT;
951
6
    else if (Ty->isObjCObjectType())
952
3
      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
953
3
                          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
954
3
                              << Ty << CT);
955
3
    else
956
3
      Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
957
3
          << isa<InitListExpr>(E) << Ty << CT;
958
7
    break;
959
59.8k
  }
960
59.8k
}
961
962
/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
963
/// will create a trap if the resulting type is not a POD type.
964
ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
965
71.6k
                                                  FunctionDecl *FDecl) {
966
71.6k
  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
967
    // Strip the unbridged-cast placeholder expression off, if applicable.
968
15
    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
969
9
        (CT == VariadicMethod ||
970
7
         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
971
5
      E = stripARCUnbridgedCast(E);
972
973
    // Otherwise, do normal placeholder checking.
974
10
    } else {
975
10
      ExprResult ExprRes = CheckPlaceholderExpr(E);
976
10
      if (ExprRes.isInvalid())
977
3
        return ExprError();
978
7
      E = ExprRes.get();
979
7
    }
980
15
  }
981
982
71.6k
  ExprResult ExprRes = DefaultArgumentPromotion(E);
983
71.6k
  if (ExprRes.isInvalid())
984
8
    return ExprError();
985
986
  // Copy blocks to the heap.
987
71.6k
  if (ExprRes.get()->getType()->isBlockPointerType())
988
19
    maybeExtendBlockObject(ExprRes);
989
990
71.6k
  E = ExprRes.get();
991
992
  // Diagnostics regarding non-POD argument types are
993
  // emitted along with format string checking in Sema::CheckFunctionCall().
994
71.6k
  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
995
    // Turn this into a trap.
996
75
    CXXScopeSpec SS;
997
75
    SourceLocation TemplateKWLoc;
998
75
    UnqualifiedId Name;
999
75
    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1000
75
                       E->getBeginLoc());
1001
75
    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1002
75
                                          /*HasTrailingLParen=*/true,
1003
75
                                          /*IsAddressOfOperand=*/false);
1004
75
    if (TrapFn.isInvalid())
1005
0
      return ExprError();
1006
1007
75
    ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1008
75
                                    None, E->getEndLoc());
1009
75
    if (Call.isInvalid())
1010
0
      return ExprError();
1011
1012
75
    ExprResult Comma =
1013
75
        ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1014
75
    if (Comma.isInvalid())
1015
0
      return ExprError();
1016
75
    return Comma.get();
1017
75
  }
1018
1019
71.5k
  if (!getLangOpts().CPlusPlus &&
1020
8.29k
      RequireCompleteType(E->getExprLoc(), E->getType(),
1021
8.29k
                          diag::err_call_incomplete_argument))
1022
2
    return ExprError();
1023
1024
71.5k
  return E;
1025
71.5k
}
1026
1027
/// Converts an integer to complex float type.  Helper function of
1028
/// UsualArithmeticConversions()
1029
///
1030
/// \return false if the integer expression is an integer type and is
1031
/// successfully converted to the complex type.
1032
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1033
                                                  ExprResult &ComplexExpr,
1034
                                                  QualType IntTy,
1035
                                                  QualType ComplexTy,
1036
1.30k
                                                  bool SkipCast) {
1037
1.30k
  if (IntTy->isComplexType() || 
IntTy->isRealFloatingType()650
)
return true1.23k
;
1038
70
  if (SkipCast) 
return false0
;
1039
70
  if (IntTy->isIntegerType()) {
1040
43
    QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1041
43
    IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1042
43
    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1043
43
                                  CK_FloatingRealToComplex);
1044
27
  } else {
1045
27
    assert(IntTy->isComplexIntegerType());
1046
27
    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1047
27
                                  CK_IntegralComplexToFloatingComplex);
1048
27
  }
1049
70
  return false;
1050
70
}
1051
1052
/// Handle arithmetic conversion with complex types.  Helper function of
1053
/// UsualArithmeticConversions()
1054
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1055
                                             ExprResult &RHS, QualType LHSType,
1056
                                             QualType RHSType,
1057
662
                                             bool IsCompAssign) {
1058
  // if we have an integer operand, the result is the complex type.
1059
662
  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1060
662
                                             /*skipCast*/false))
1061
24
    return LHSType;
1062
638
  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1063
638
                                             /*skipCast*/IsCompAssign))
1064
46
    return RHSType;
1065
1066
  // This handles complex/complex, complex/float, or float/complex.
1067
  // When both operands are complex, the shorter operand is converted to the
1068
  // type of the longer, and that is the type of the result. This corresponds
1069
  // to what is done when combining two real floating-point operands.
1070
  // The fun begins when size promotion occur across type domains.
1071
  // From H&S 6.3.4: When one operand is complex and the other is a real
1072
  // floating-point type, the less precise type is converted, within it's
1073
  // real or complex domain, to the precision of the other type. For example,
1074
  // when combining a "long double" with a "double _Complex", the
1075
  // "double _Complex" is promoted to "long double _Complex".
1076
1077
  // Compute the rank of the two types, regardless of whether they are complex.
1078
592
  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1079
1080
592
  auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1081
592
  auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1082
592
  QualType LHSElementType =
1083
415
      LHSComplexType ? 
LHSComplexType->getElementType()177
: LHSType;
1084
592
  QualType RHSElementType =
1085
427
      RHSComplexType ? RHSComplexType->getElementType() : 
RHSType165
;
1086
1087
592
  QualType ResultType = S.Context.getComplexType(LHSElementType);
1088
592
  if (Order < 0) {
1089
    // Promote the precision of the LHS if not an assignment.
1090
20
    ResultType = S.Context.getComplexType(RHSElementType);
1091
20
    if (!IsCompAssign) {
1092
16
      if (LHSComplexType)
1093
10
        LHS =
1094
10
            S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1095
6
      else
1096
6
        LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1097
16
    }
1098
572
  } else if (Order > 0) {
1099
    // Promote the precision of the RHS.
1100
35
    if (RHSComplexType)
1101
29
      RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1102
6
    else
1103
6
      RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1104
35
  }
1105
592
  return ResultType;
1106
592
}
1107
1108
/// Handle arithmetic conversion from integer to float.  Helper function
1109
/// of UsualArithmeticConversions()
1110
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1111
                                           ExprResult &IntExpr,
1112
                                           QualType FloatTy, QualType IntTy,
1113
9.22k
                                           bool ConvertFloat, bool ConvertInt) {
1114
9.22k
  if (IntTy->isIntegerType()) {
1115
9.20k
    if (ConvertInt)
1116
      // Convert intExpr to the lhs floating point type.
1117
8.94k
      IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1118
8.94k
                                    CK_IntegralToFloating);
1119
9.20k
    return FloatTy;
1120
9.20k
  }
1121
1122
  // Convert both sides to the appropriate complex float.
1123
23
  assert(IntTy->isComplexIntegerType());
1124
23
  QualType result = S.Context.getComplexType(FloatTy);
1125
1126
  // _Complex int -> _Complex float
1127
23
  if (ConvertInt)
1128
23
    IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1129
23
                                  CK_IntegralComplexToFloatingComplex);
1130
1131
  // float -> _Complex float
1132
23
  if (ConvertFloat)
1133
23
    FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1134
23
                                    CK_FloatingRealToComplex);
1135
1136
23
  return result;
1137
23
}
1138
1139
/// Handle arithmethic conversion with floating point types.  Helper
1140
/// function of UsualArithmeticConversions()
1141
static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1142
                                      ExprResult &RHS, QualType LHSType,
1143
10.8k
                                      QualType RHSType, bool IsCompAssign) {
1144
10.8k
  bool LHSFloat = LHSType->isRealFloatingType();
1145
10.8k
  bool RHSFloat = RHSType->isRealFloatingType();
1146
1147
  // N1169 4.1.4: If one of the operands has a floating type and the other
1148
  //              operand has a fixed-point type, the fixed-point operand
1149
  //              is converted to the floating type [...]
1150
10.8k
  if (LHSType->isFixedPointType() || 
RHSType->isFixedPointType()10.8k
) {
1151
14
    if (LHSFloat)
1152
4
      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1153
10
    else if (!IsCompAssign)
1154
0
      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1155
10
    return LHSFloat ? 
LHSType4
: RHSType;
1156
14
  }
1157
1158
  // If we have two real floating types, convert the smaller operand
1159
  // to the bigger result.
1160
10.8k
  if (LHSFloat && 
RHSFloat6.68k
) {
1161
1.66k
    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1162
1.66k
    if (order > 0) {
1163
134
      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1164
134
      return LHSType;
1165
134
    }
1166
1167
1.52k
    assert(order < 0 && "illegal float comparison");
1168
1.52k
    if (!IsCompAssign)
1169
584
      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1170
1.52k
    return RHSType;
1171
1.52k
  }
1172
1173
9.22k
  if (LHSFloat) {
1174
    // Half FP has to be promoted to float unless it is natively supported
1175
5.02k
    if (LHSType->isHalfType() && 
!S.getLangOpts().NativeHalfType110
)
1176
40
      LHSType = S.Context.FloatTy;
1177
1178
5.02k
    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1179
5.02k
                                      /*ConvertFloat=*/!IsCompAssign,
1180
5.02k
                                      /*ConvertInt=*/ true);
1181
5.02k
  }
1182
4.19k
  assert(RHSFloat);
1183
4.19k
  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1184
4.19k
                                    /*ConvertFloat=*/ true,
1185
4.19k
                                    /*ConvertInt=*/!IsCompAssign);
1186
4.19k
}
1187
1188
/// Diagnose attempts to convert between __float128 and long double if
1189
/// there is no support for such conversion. Helper function of
1190
/// UsualArithmeticConversions().
1191
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1192
1.19M
                                      QualType RHSType) {
1193
  /*  No issue converting if at least one of the types is not a floating point
1194
      type or the two types have the same rank.
1195
  */
1196
1.19M
  if (!LHSType->isFloatingType() || 
!RHSType->isFloatingType()33.9k
||
1197
11.7k
      S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1198
1.18M
    return false;
1199
1200
10.8k
  assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1201
10.8k
         "The remaining types must be floating point types.");
1202
1203
10.8k
  auto *LHSComplex = LHSType->getAs<ComplexType>();
1204
10.8k
  auto *RHSComplex = RHSType->getAs<ComplexType>();
1205
1206
10.8k
  QualType LHSElemType = LHSComplex ?
1207
10.5k
    
LHSComplex->getElementType()314
: LHSType;
1208
10.8k
  QualType RHSElemType = RHSComplex ?
1209
10.7k
    
RHSComplex->getElementType()142
: RHSType;
1210
1211
  // No issue if the two types have the same representation
1212
10.8k
  if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1213
10.8k
      &S.Context.getFloatTypeSemantics(RHSElemType))
1214
22
    return false;
1215
1216
10.8k
  bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1217
395
                                RHSElemType == S.Context.LongDoubleTy);
1218
10.8k
  Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1219
869
                            RHSElemType == S.Context.Float128Ty);
1220
1221
  // We've handled the situation where __float128 and long double have the same
1222
  // representation. We allow all conversions for all possible long double types
1223
  // except PPC's double double.
1224
10.8k
  return Float128AndLongDouble &&
1225
24
    (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1226
24
     &llvm::APFloat::PPCDoubleDouble());
1227
10.8k
}
1228
1229
typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1230
1231
namespace {
1232
/// These helper callbacks are placed in an anonymous namespace to
1233
/// permit their use as function template parameters.
1234
493k
ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1235
493k
  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1236
493k
}
1237
1238
115
ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1239
115
  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1240
115
                             CK_IntegralComplexCast);
1241
115
}
1242
}
1243
1244
/// Handle integer arithmetic conversions.  Helper function of
1245
/// UsualArithmeticConversions()
1246
template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1247
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1248
                                        ExprResult &RHS, QualType LHSType,
1249
493k
                                        QualType RHSType, bool IsCompAssign) {
1250
  // The rules for this case are in C99 6.3.1.8
1251
493k
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252
493k
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253
493k
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254
493k
  if (LHSSigned == RHSSigned) {
1255
    // Same signedness; use the higher-ranked type
1256
93.7k
    if (order >= 0) {
1257
77.9k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258
77.9k
      return LHSType;
1259
15.8k
    } else if (!IsCompAssign)
1260
15.6k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261
15.8k
    return RHSType;
1262
399k
  } else if (order != (LHSSigned ? 
1106k
:
-1293k
)) {
1263
    // The unsigned type has greater than or equal rank to the
1264
    // signed type, so use the unsigned type
1265
395k
    if (RHSSigned) {
1266
290k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267
290k
      return LHSType;
1268
104k
    } else if (!IsCompAssign)
1269
104k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270
104k
    return RHSType;
1271
4.60k
  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272
    // The two types are different widths; if we are here, that
1273
    // means the signed type is larger than the unsigned type, so
1274
    // use the signed type.
1275
4.23k
    if (LHSSigned) {
1276
1.62k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277
1.62k
      return LHSType;
1278
2.60k
    } else if (!IsCompAssign)
1279
2.60k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280
2.60k
    return RHSType;
1281
371
  } else {
1282
    // The signed type is higher-ranked than the unsigned type,
1283
    // but isn't actually any bigger (like unsigned int and long
1284
    // on most 32-bit systems).  Use the unsigned type corresponding
1285
    // to the signed type.
1286
371
    QualType result =
1287
249
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : 
RHSType122
);
1288
371
    RHS = (*doRHSCast)(S, RHS.get(), result);
1289
371
    if (!IsCompAssign)
1290
371
      LHS = (*doLHSCast)(S, LHS.get(), result);
1291
371
    return result;
1292
371
  }
1293
493k
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1249
17
                                        QualType RHSType, bool IsCompAssign) {
1250
  // The rules for this case are in C99 6.3.1.8
1251
17
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252
17
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253
17
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254
17
  if (LHSSigned == RHSSigned) {
1255
    // Same signedness; use the higher-ranked type
1256
16
    if (order >= 0) {
1257
10
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258
10
      return LHSType;
1259
6
    } else if (!IsCompAssign)
1260
5
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261
6
    return RHSType;
1262
1
  } else if (order != (LHSSigned ? 
10
: -1)) {
1263
    // The unsigned type has greater than or equal rank to the
1264
    // signed type, so use the unsigned type
1265
1
    if (RHSSigned) {
1266
1
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267
1
      return LHSType;
1268
0
    } else if (!IsCompAssign)
1269
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270
0
    return RHSType;
1271
0
  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272
    // The two types are different widths; if we are here, that
1273
    // means the signed type is larger than the unsigned type, so
1274
    // use the signed type.
1275
0
    if (LHSSigned) {
1276
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277
0
      return LHSType;
1278
0
    } else if (!IsCompAssign)
1279
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280
0
    return RHSType;
1281
0
  } else {
1282
    // The signed type is higher-ranked than the unsigned type,
1283
    // but isn't actually any bigger (like unsigned int and long
1284
    // on most 32-bit systems).  Use the unsigned type corresponding
1285
    // to the signed type.
1286
0
    QualType result =
1287
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1288
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1289
0
    if (!IsCompAssign)
1290
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1291
0
    return result;
1292
0
  }
1293
17
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1249
53
                                        QualType RHSType, bool IsCompAssign) {
1250
  // The rules for this case are in C99 6.3.1.8
1251
53
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252
53
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253
53
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254
53
  if (LHSSigned == RHSSigned) {
1255
    // Same signedness; use the higher-ranked type
1256
45
    if (order >= 0) {
1257
38
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258
38
      return LHSType;
1259
7
    } else if (!IsCompAssign)
1260
6
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261
7
    return RHSType;
1262
8
  } else if (order != (LHSSigned ? 
12
:
-16
)) {
1263
    // The unsigned type has greater than or equal rank to the
1264
    // signed type, so use the unsigned type
1265
5
    if (RHSSigned) {
1266
3
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267
3
      return LHSType;
1268
2
    } else if (!IsCompAssign)
1269
2
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270
2
    return RHSType;
1271
3
  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272
    // The two types are different widths; if we are here, that
1273
    // means the signed type is larger than the unsigned type, so
1274
    // use the signed type.
1275
3
    if (LHSSigned) {
1276
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277
0
      return LHSType;
1278
3
    } else if (!IsCompAssign)
1279
3
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280
3
    return RHSType;
1281
0
  } else {
1282
    // The signed type is higher-ranked than the unsigned type,
1283
    // but isn't actually any bigger (like unsigned int and long
1284
    // on most 32-bit systems).  Use the unsigned type corresponding
1285
    // to the signed type.
1286
0
    QualType result =
1287
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1288
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1289
0
    if (!IsCompAssign)
1290
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1291
0
    return result;
1292
0
  }
1293
53
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1249
94
                                        QualType RHSType, bool IsCompAssign) {
1250
  // The rules for this case are in C99 6.3.1.8
1251
94
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252
94
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253
94
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254
94
  if (LHSSigned == RHSSigned) {
1255
    // Same signedness; use the higher-ranked type
1256
85
    if (order >= 0) {
1257
83
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258
83
      return LHSType;
1259
2
    } else if (!IsCompAssign)
1260
2
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261
2
    return RHSType;
1262
9
  } else if (order != (LHSSigned ? 
17
:
-12
)) {
1263
    // The unsigned type has greater than or equal rank to the
1264
    // signed type, so use the unsigned type
1265
6
    if (RHSSigned) {
1266
2
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267
2
      return LHSType;
1268
4
    } else if (!IsCompAssign)
1269
4
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270
4
    return RHSType;
1271
3
  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272
    // The two types are different widths; if we are here, that
1273
    // means the signed type is larger than the unsigned type, so
1274
    // use the signed type.
1275
3
    if (LHSSigned) {
1276
3
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277
3
      return LHSType;
1278
0
    } else if (!IsCompAssign)
1279
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280
0
    return RHSType;
1281
0
  } else {
1282
    // The signed type is higher-ranked than the unsigned type,
1283
    // but isn't actually any bigger (like unsigned int and long
1284
    // on most 32-bit systems).  Use the unsigned type corresponding
1285
    // to the signed type.
1286
0
    QualType result =
1287
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1288
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1289
0
    if (!IsCompAssign)
1290
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1291
0
    return result;
1292
0
  }
1293
94
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1249
493k
                                        QualType RHSType, bool IsCompAssign) {
1250
  // The rules for this case are in C99 6.3.1.8
1251
493k
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252
493k
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253
493k
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254
493k
  if (LHSSigned == RHSSigned) {
1255
    // Same signedness; use the higher-ranked type
1256
93.6k
    if (order >= 0) {
1257
77.7k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258
77.7k
      return LHSType;
1259
15.8k
    } else if (!IsCompAssign)
1260
15.6k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261
15.8k
    return RHSType;
1262
399k
  } else if (order != (LHSSigned ? 
1106k
:
-1293k
)) {
1263
    // The unsigned type has greater than or equal rank to the
1264
    // signed type, so use the unsigned type
1265
395k
    if (RHSSigned) {
1266
290k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267
290k
      return LHSType;
1268
104k
    } else if (!IsCompAssign)
1269
104k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270
104k
    return RHSType;
1271
4.59k
  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272
    // The two types are different widths; if we are here, that
1273
    // means the signed type is larger than the unsigned type, so
1274
    // use the signed type.
1275
4.22k
    if (LHSSigned) {
1276
1.62k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277
1.62k
      return LHSType;
1278
2.60k
    } else if (!IsCompAssign)
1279
2.59k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280
2.60k
    return RHSType;
1281
371
  } else {
1282
    // The signed type is higher-ranked than the unsigned type,
1283
    // but isn't actually any bigger (like unsigned int and long
1284
    // on most 32-bit systems).  Use the unsigned type corresponding
1285
    // to the signed type.
1286
371
    QualType result =
1287
249
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : 
RHSType122
);
1288
371
    RHS = (*doRHSCast)(S, RHS.get(), result);
1289
371
    if (!IsCompAssign)
1290
371
      LHS = (*doLHSCast)(S, LHS.get(), result);
1291
371
    return result;
1292
371
  }
1293
493k
}
1294
1295
/// Handle conversions with GCC complex int extension.  Helper function
1296
/// of UsualArithmeticConversions()
1297
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1298
                                           ExprResult &RHS, QualType LHSType,
1299
                                           QualType RHSType,
1300
164
                                           bool IsCompAssign) {
1301
164
  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1302
164
  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1303
1304
164
  if (LHSComplexInt && 
RHSComplexInt70
) {
1305
17
    QualType LHSEltType = LHSComplexInt->getElementType();
1306
17
    QualType RHSEltType = RHSComplexInt->getElementType();
1307
17
    QualType ScalarType =
1308
17
      handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1309
17
        (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1310
1311
17
    return S.Context.getComplexType(ScalarType);
1312
17
  }
1313
1314
147
  if (LHSComplexInt) {
1315
53
    QualType LHSEltType = LHSComplexInt->getElementType();
1316
53
    QualType ScalarType =
1317
53
      handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1318
53
        (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1319
53
    QualType ComplexType = S.Context.getComplexType(ScalarType);
1320
53
    RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1321
53
                              CK_IntegralRealToComplex);
1322
1323
53
    return ComplexType;
1324
53
  }
1325
1326
94
  assert(RHSComplexInt);
1327
1328
94
  QualType RHSEltType = RHSComplexInt->getElementType();
1329
94
  QualType ScalarType =
1330
94
    handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1331
94
      (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1332
94
  QualType ComplexType = S.Context.getComplexType(ScalarType);
1333
1334
94
  if (!IsCompAssign)
1335
92
    LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1336
92
                              CK_IntegralRealToComplex);
1337
94
  return ComplexType;
1338
94
}
1339
1340
/// Return the rank of a given fixed point or integer type. The value itself
1341
/// doesn't matter, but the values must be increasing with proper increasing
1342
/// rank as described in N1169 4.1.1.
1343
1.05k
static unsigned GetFixedPointRank(QualType Ty) {
1344
1.05k
  const auto *BTy = Ty->getAs<BuiltinType>();
1345
1.05k
  assert(BTy && "Expected a builtin type.");
1346
1347
1.05k
  switch (BTy->getKind()) {
1348
53
  case BuiltinType::ShortFract:
1349
61
  case BuiltinType::UShortFract:
1350
65
  case BuiltinType::SatShortFract:
1351
65
  case BuiltinType::SatUShortFract:
1352
65
    return 1;
1353
26
  case BuiltinType::Fract:
1354
36
  case BuiltinType::UFract:
1355
38
  case BuiltinType::SatFract:
1356
38
  case BuiltinType::SatUFract:
1357
38
    return 2;
1358
45
  case BuiltinType::LongFract:
1359
45
  case BuiltinType::ULongFract:
1360
45
  case BuiltinType::SatLongFract:
1361
45
  case BuiltinType::SatULongFract:
1362
45
    return 3;
1363
321
  case BuiltinType::ShortAccum:
1364
411
  case BuiltinType::UShortAccum:
1365
475
  case BuiltinType::SatShortAccum:
1366
523
  case BuiltinType::SatUShortAccum:
1367
523
    return 4;
1368
93
  case BuiltinType::Accum:
1369
117
  case BuiltinType::UAccum:
1370
129
  case BuiltinType::SatAccum:
1371
129
  case BuiltinType::SatUAccum:
1372
129
    return 5;
1373
14
  case BuiltinType::LongAccum:
1374
20
  case BuiltinType::ULongAccum:
1375
20
  case BuiltinType::SatLongAccum:
1376
22
  case BuiltinType::SatULongAccum:
1377
22
    return 6;
1378
236
  default:
1379
236
    if (BTy->isInteger())
1380
236
      return 0;
1381
1.05k
    
llvm_unreachable0
("Unexpected fixed point or integer type");
1382
1.05k
  }
1383
1.05k
}
1384
1385
/// handleFixedPointConversion - Fixed point operations between fixed
1386
/// point types and integers or other fixed point types do not fall under
1387
/// usual arithmetic conversion since these conversions could result in loss
1388
/// of precsision (N1169 4.1.4). These operations should be calculated with
1389
/// the full precision of their result type (N1169 4.1.6.2.1).
1390
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1391
529
                                           QualType RHSTy) {
1392
529
  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1393
529
         "Expected at least one of the operands to be a fixed point type");
1394
529
  assert((LHSTy->isFixedPointOrIntegerType() ||
1395
529
          RHSTy->isFixedPointOrIntegerType()) &&
1396
529
         "Special fixed point arithmetic operation conversions are only "
1397
529
         "applied to ints or other fixed point types");
1398
1399
  // If one operand has signed fixed-point type and the other operand has
1400
  // unsigned fixed-point type, then the unsigned fixed-point operand is
1401
  // converted to its corresponding signed fixed-point type and the resulting
1402
  // type is the type of the converted operand.
1403
529
  if (RHSTy->isSignedFixedPointType() && 
LHSTy->isUnsignedFixedPointType()194
)
1404
12
    LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1405
517
  else if (RHSTy->isUnsignedFixedPointType() && 
LHSTy->isSignedFixedPointType()148
)
1406
76
    RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1407
1408
  // The result type is the type with the highest rank, whereby a fixed-point
1409
  // conversion rank is always greater than an integer conversion rank; if the
1410
  // type of either of the operands is a saturating fixedpoint type, the result
1411
  // type shall be the saturating fixed-point type corresponding to the type
1412
  // with the highest rank; the resulting value is converted (taking into
1413
  // account rounding and overflow) to the precision of the resulting type.
1414
  // Same ranks between signed and unsigned types are resolved earlier, so both
1415
  // types are either signed or both unsigned at this point.
1416
529
  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1417
529
  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1418
1419
280
  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : 
RHSTy249
;
1420
1421
529
  if (LHSTy->isSaturatedFixedPointType() || 
RHSTy->isSaturatedFixedPointType()435
)
1422
126
    ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1423
1424
529
  return ResultTy;
1425
529
}
1426
1427
/// Check that the usual arithmetic conversions can be performed on this pair of
1428
/// expressions that might be of enumeration type.
1429
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1430
                                           SourceLocation Loc,
1431
3.87M
                                           Sema::ArithConvKind ACK) {
1432
  // C++2a [expr.arith.conv]p1:
1433
  //   If one operand is of enumeration type and the other operand is of a
1434
  //   different enumeration type or a floating-point type, this behavior is
1435
  //   deprecated ([depr.arith.conv.enum]).
1436
  //
1437
  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1438
  // Eventually we will presumably reject these cases (in C++23 onwards?).
1439
3.87M
  QualType L = LHS->getType(), R = RHS->getType();
1440
3.87M
  bool LEnum = L->isUnscopedEnumerationType(),
1441
3.87M
       REnum = R->isUnscopedEnumerationType();
1442
3.87M
  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1443
3.87M
  if ((!IsCompAssign && 
LEnum3.80M
&&
R->isFloatingType()29.6k
) ||
1444
3.87M
      (REnum && 
L->isFloatingType()30.2k
)) {
1445
40
    S.Diag(Loc, S.getLangOpts().CPlusPlus20
1446
14
                    ? diag::warn_arith_conv_enum_float_cxx20
1447
26
                    : diag::warn_arith_conv_enum_float)
1448
40
        << LHS->getSourceRange() << RHS->getSourceRange()
1449
40
        << (int)ACK << LEnum << L << R;
1450
3.87M
  } else if (!IsCompAssign && 
LEnum3.80M
&&
REnum29.6k
&&
1451
25.5k
             !S.Context.hasSameUnqualifiedType(L, R)) {
1452
2.21k
    unsigned DiagID;
1453
2.21k
    if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1454
1.91k
        
!R->castAs<EnumType>()->getDecl()->hasNameForLinkage()307
) {
1455
      // If either enumeration type is unnamed, it's less likely that the
1456
      // user cares about this, but this situation is still deprecated in
1457
      // C++2a. Use a different warning group.
1458
1.91k
      DiagID = S.getLangOpts().CPlusPlus20
1459
0
                    ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1460
1.91k
                    : diag::warn_arith_conv_mixed_anon_enum_types;
1461
301
    } else if (ACK == Sema::ACK_Conditional) {
1462
      // Conditional expressions are separated out because they have
1463
      // historically had a different warning flag.
1464
13
      DiagID = S.getLangOpts().CPlusPlus20
1465
2
                   ? diag::warn_conditional_mixed_enum_types_cxx20
1466
11
                   : diag::warn_conditional_mixed_enum_types;
1467
288
    } else if (ACK == Sema::ACK_Comparison) {
1468
      // Comparison expressions are separated out because they have
1469
      // historically had a different warning flag.
1470
284
      DiagID = S.getLangOpts().CPlusPlus20
1471
3
                   ? diag::warn_comparison_mixed_enum_types_cxx20
1472
281
                   : diag::warn_comparison_mixed_enum_types;
1473
4
    } else {
1474
4
      DiagID = S.getLangOpts().CPlusPlus20
1475
2
                   ? diag::warn_arith_conv_mixed_enum_types_cxx20
1476
2
                   : diag::warn_arith_conv_mixed_enum_types;
1477
4
    }
1478
2.21k
    S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1479
2.21k
                        << (int)ACK << L << R;
1480
2.21k
  }
1481
3.87M
}
1482
1483
/// UsualArithmeticConversions - Performs various conversions that are common to
1484
/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1485
/// routine returns the first non-arithmetic type found. The client is
1486
/// responsible for emitting appropriate error diagnostics.
1487
QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1488
                                          SourceLocation Loc,
1489
3.87M
                                          ArithConvKind ACK) {
1490
3.87M
  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1491
1492
3.87M
  if (ACK != ACK_CompAssign) {
1493
3.80M
    LHS = UsualUnaryConversions(LHS.get());
1494
3.80M
    if (LHS.isInvalid())
1495
0
      return QualType();
1496
3.87M
  }
1497
1498
3.87M
  RHS = UsualUnaryConversions(RHS.get());
1499
3.87M
  if (RHS.isInvalid())
1500
0
    return QualType();
1501
1502
  // For conversion purposes, we ignore any qualifiers.
1503
  // For example, "const float" and "float" are equivalent.
1504
3.87M
  QualType LHSType =
1505
3.87M
    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1506
3.87M
  QualType RHSType =
1507
3.87M
    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1508
1509
  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1510
3.87M
  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1511
54
    LHSType = AtomicLHS->getValueType();
1512
1513
  // If both types are identical, no conversion is needed.
1514
3.87M
  if (LHSType == RHSType)
1515
3.30M
    return LHSType;
1516
1517
  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1518
  // The caller can deal with this (e.g. pointer + int).
1519
570k
  if (!LHSType->isArithmeticType() || 
!RHSType->isArithmeticType()510k
)
1520
60.1k
    return QualType();
1521
1522
  // Apply unary and bitfield promotions to the LHS's type.
1523
510k
  QualType LHSUnpromotedType = LHSType;
1524
510k
  if (LHSType->isPromotableIntegerType())
1525
4.52k
    LHSType = Context.getPromotedIntegerType(LHSType);
1526
510k
  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1527
510k
  if (!LHSBitfieldPromoteTy.isNull())
1528
113
    LHSType = LHSBitfieldPromoteTy;
1529
510k
  if (LHSType != LHSUnpromotedType && 
ACK != ACK_CompAssign4.57k
)
1530
0
    LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1531
1532
  // If both types are identical, no conversion is needed.
1533
510k
  if (LHSType == RHSType)
1534
4.33k
    return LHSType;
1535
1536
  // ExtInt types aren't subject to conversions between them or normal integers,
1537
  // so this fails.
1538
505k
  if(LHSType->isExtIntType() || 
RHSType->isExtIntType()505k
)
1539
33
    return QualType();
1540
1541
  // At this point, we have two different arithmetic types.
1542
1543
  // Diagnose attempts to convert between __float128 and long double where
1544
  // such conversions currently can't be handled.
1545
505k
  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1546
13
    return QualType();
1547
1548
  // Handle complex types first (C99 6.3.1.8p1).
1549
505k
  if (LHSType->isComplexType() || 
RHSType->isComplexType()505k
)
1550
662
    return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1551
662
                                        ACK == ACK_CompAssign);
1552
1553
  // Now handle "real" floating types (i.e. float, double, long double).
1554
505k
  if (LHSType->isRealFloatingType() || 
RHSType->isRealFloatingType()498k
)
1555
10.8k
    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1556
10.8k
                                 ACK == ACK_CompAssign);
1557
1558
  // Handle GCC complex int extension.
1559
494k
  if (LHSType->isComplexIntegerType() || 
RHSType->isComplexIntegerType()494k
)
1560
164
    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1561
164
                                      ACK == ACK_CompAssign);
1562
1563
494k
  if (LHSType->isFixedPointType() || 
RHSType->isFixedPointType()493k
)
1564
529
    return handleFixedPointConversion(*this, LHSType, RHSType);
1565
1566
  // Finally, we have two differing integer types.
1567
493k
  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1568
493k
           (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1569
493k
}
1570
1571
//===----------------------------------------------------------------------===//
1572
//  Semantic Analysis for various Expression Types
1573
//===----------------------------------------------------------------------===//
1574
1575
1576
ExprResult
1577
Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1578
                                SourceLocation DefaultLoc,
1579
                                SourceLocation RParenLoc,
1580
                                Expr *ControllingExpr,
1581
                                ArrayRef<ParsedType> ArgTypes,
1582
430
                                ArrayRef<Expr *> ArgExprs) {
1583
430
  unsigned NumAssocs = ArgTypes.size();
1584
430
  assert(NumAssocs == ArgExprs.size());
1585
1586
430
  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1587
1.65k
  for (unsigned i = 0; i < NumAssocs; 
++i1.22k
) {
1588
1.22k
    if (ArgTypes[i])
1589
1.16k
      (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1590
62
    else
1591
62
      Types[i] = nullptr;
1592
1.22k
  }
1593
1594
430
  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1595
430
                                             ControllingExpr,
1596
430
                                             llvm::makeArrayRef(Types, NumAssocs),
1597
430
                                             ArgExprs);
1598
430
  delete [] Types;
1599
430
  return ER;
1600
430
}
1601
1602
ExprResult
1603
Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1604
                                 SourceLocation DefaultLoc,
1605
                                 SourceLocation RParenLoc,
1606
                                 Expr *ControllingExpr,
1607
                                 ArrayRef<TypeSourceInfo *> Types,
1608
447
                                 ArrayRef<Expr *> Exprs) {
1609
447
  unsigned NumAssocs = Types.size();
1610
447
  assert(NumAssocs == Exprs.size());
1611
1612
  // Decay and strip qualifiers for the controlling expression type, and handle
1613
  // placeholder type replacement. See committee discussion from WG14 DR423.
1614
447
  {
1615
447
    EnterExpressionEvaluationContext Unevaluated(
1616
447
        *this, Sema::ExpressionEvaluationContext::Unevaluated);
1617
447
    ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1618
447
    if (R.isInvalid())
1619
0
      return ExprError();
1620
447
    ControllingExpr = R.get();
1621
447
  }
1622
1623
  // The controlling expression is an unevaluated operand, so side effects are
1624
  // likely unintended.
1625
447
  if (!inTemplateInstantiation() &&
1626
430
      ControllingExpr->HasSideEffects(Context, false))
1627
5
    Diag(ControllingExpr->getExprLoc(),
1628
5
         diag::warn_side_effects_unevaluated_context);
1629
1630
447
  bool TypeErrorFound = false,
1631
447
       IsResultDependent = ControllingExpr->isTypeDependent(),
1632
447
       ContainsUnexpandedParameterPack
1633
447
         = ControllingExpr->containsUnexpandedParameterPack();
1634
1635
1.72k
  for (unsigned i = 0; i < NumAssocs; 
++i1.27k
) {
1636
1.27k
    if (Exprs[i]->containsUnexpandedParameterPack())
1637
0
      ContainsUnexpandedParameterPack = true;
1638
1639
1.27k
    if (Types[i]) {
1640
1.21k
      if (Types[i]->getType()->containsUnexpandedParameterPack())
1641
0
        ContainsUnexpandedParameterPack = true;
1642
1643
1.21k
      if (Types[i]->getType()->isDependentType()) {
1644
2
        IsResultDependent = true;
1645
1.21k
      } else {
1646
        // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1647
        // complete object type other than a variably modified type."
1648
1.21k
        unsigned D = 0;
1649
1.21k
        if (Types[i]->getType()->isIncompleteType())
1650
2
          D = diag::err_assoc_type_incomplete;
1651
1.21k
        else if (!Types[i]->getType()->isObjectType())
1652
2
          D = diag::err_assoc_type_nonobject;
1653
1.21k
        else if (Types[i]->getType()->isVariablyModifiedType())
1654
2
          D = diag::err_assoc_type_variably_modified;
1655
1656
1.21k
        if (D != 0) {
1657
6
          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1658
6
            << Types[i]->getTypeLoc().getSourceRange()
1659
6
            << Types[i]->getType();
1660
6
          TypeErrorFound = true;
1661
6
        }
1662
1663
        // C11 6.5.1.1p2 "No two generic associations in the same generic
1664
        // selection shall specify compatible types."
1665
2.66k
        for (unsigned j = i+1; j < NumAssocs; 
++j1.44k
)
1666
1.44k
          if (Types[j] && 
!Types[j]->getType()->isDependentType()1.37k
&&
1667
1.37k
              Context.typesAreCompatible(Types[i]->getType(),
1668
6
                                         Types[j]->getType())) {
1669
6
            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1670
6
                 diag::err_assoc_compatible_types)
1671
6
              << Types[j]->getTypeLoc().getSourceRange()
1672
6
              << Types[j]->getType()
1673
6
              << Types[i]->getType();
1674
6
            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1675
6
                 diag::note_compat_assoc)
1676
6
              << Types[i]->getTypeLoc().getSourceRange()
1677
6
              << Types[i]->getType();
1678
6
            TypeErrorFound = true;
1679
6
          }
1680
1.21k
      }
1681
1.21k
    }
1682
1.27k
  }
1683
447
  if (TypeErrorFound)
1684
8
    return ExprError();
1685
1686
  // If we determined that the generic selection is result-dependent, don't
1687
  // try to compute the result expression.
1688
439
  if (IsResultDependent)
1689
9
    return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1690
9
                                        Exprs, DefaultLoc, RParenLoc,
1691
9
                                        ContainsUnexpandedParameterPack);
1692
1693
430
  SmallVector<unsigned, 1> CompatIndices;
1694
430
  unsigned DefaultIndex = -1U;
1695
1.66k
  for (unsigned i = 0; i < NumAssocs; 
++i1.23k
) {
1696
1.23k
    if (!Types[i])
1697
58
      DefaultIndex = i;
1698
1.17k
    else if (Context.typesAreCompatible(ControllingExpr->getType(),
1699
1.17k
                                        Types[i]->getType()))
1700
407
      CompatIndices.push_back(i);
1701
1.23k
  }
1702
1703
  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1704
  // type compatible with at most one of the types named in its generic
1705
  // association list."
1706
430
  if (CompatIndices.size() > 1) {
1707
    // We strip parens here because the controlling expression is typically
1708
    // parenthesized in macro definitions.
1709
2
    ControllingExpr = ControllingExpr->IgnoreParens();
1710
2
    Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1711
2
        << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1712
2
        << (unsigned)CompatIndices.size();
1713
4
    for (unsigned I : CompatIndices) {
1714
4
      Diag(Types[I]->getTypeLoc().getBeginLoc(),
1715
4
           diag::note_compat_assoc)
1716
4
        << Types[I]->getTypeLoc().getSourceRange()
1717
4
        << Types[I]->getType();
1718
4
    }
1719
2
    return ExprError();
1720
2
  }
1721
1722
  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1723
  // its controlling expression shall have type compatible with exactly one of
1724
  // the types named in its generic association list."
1725
428
  if (DefaultIndex == -1U && 
CompatIndices.size() == 0370
) {
1726
    // We strip parens here because the controlling expression is typically
1727
    // parenthesized in macro definitions.
1728
3
    ControllingExpr = ControllingExpr->IgnoreParens();
1729
3
    Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1730
3
        << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1731
3
    return ExprError();
1732
3
  }
1733
1734
  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1735
  // type name that is compatible with the type of the controlling expression,
1736
  // then the result expression of the generic selection is the expression
1737
  // in that generic association. Otherwise, the result expression of the
1738
  // generic selection is the expression in the default generic association."
1739
425
  unsigned ResultIndex =
1740
403
    CompatIndices.size() ? CompatIndices[0] : 
DefaultIndex22
;
1741
1742
425
  return GenericSelectionExpr::Create(
1743
425
      Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1744
425
      ContainsUnexpandedParameterPack, ResultIndex);
1745
425
}
1746
1747
/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1748
/// location of the token and the offset of the ud-suffix within it.
1749
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1750
370
                                     unsigned Offset) {
1751
370
  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1752
370
                                        S.getLangOpts());
1753
370
}
1754
1755
/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1756
/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1757
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1758
                                                 IdentifierInfo *UDSuffix,
1759
                                                 SourceLocation UDSuffixLoc,
1760
                                                 ArrayRef<Expr*> Args,
1761
57
                                                 SourceLocation LitEndLoc) {
1762
57
  assert(Args.size() <= 2 && "too many arguments for literal operator");
1763
1764
57
  QualType ArgTy[2];
1765
114
  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); 
++ArgIdx57
) {
1766
57
    ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1767
57
    if (ArgTy[ArgIdx]->isArrayType())
1768
0
      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1769
57
  }
1770
1771
57
  DeclarationName OpName =
1772
57
    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1773
57
  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1774
57
  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1775
1776
57
  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1777
57
  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1778
57
                              /*AllowRaw*/ false, /*AllowTemplate*/ false,
1779
57
                              /*AllowStringTemplatePack*/ false,
1780
57
                              /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1781
10
    return ExprError();
1782
1783
47
  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1784
47
}
1785
1786
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1787
/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1788
/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1789
/// multiple tokens.  However, the common case is that StringToks points to one
1790
/// string.
1791
///
1792
ExprResult
1793
4.05M
Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1794
4.05M
  assert(!StringToks.empty() && "Must have at least one string!");
1795
1796
4.05M
  StringLiteralParser Literal(StringToks, PP);
1797
4.05M
  if (Literal.hadError)
1798
83
    return ExprError();
1799
1800
4.05M
  SmallVector<SourceLocation, 4> StringTokLocs;
1801
4.05M
  for (const Token &Tok : StringToks)
1802
4.26M
    StringTokLocs.push_back(Tok.getLocation());
1803
1804
4.05M
  QualType CharTy = Context.CharTy;
1805
4.05M
  StringLiteral::StringKind Kind = StringLiteral::Ascii;
1806
4.05M
  if (Literal.isWide()) {
1807
1.07k
    CharTy = Context.getWideCharType();
1808
1.07k
    Kind = StringLiteral::Wide;
1809
4.05M
  } else if (Literal.isUTF8()) {
1810
279
    if (getLangOpts().Char8)
1811
196
      CharTy = Context.Char8Ty;
1812
279
    Kind = StringLiteral::UTF8;
1813
4.05M
  } else if (Literal.isUTF16()) {
1814
129
    CharTy = Context.Char16Ty;
1815
129
    Kind = StringLiteral::UTF16;
1816
4.05M
  } else if (Literal.isUTF32()) {
1817
125
    CharTy = Context.Char32Ty;
1818
125
    Kind = StringLiteral::UTF32;
1819
4.05M
  } else if (Literal.isPascal()) {
1820
11
    CharTy = Context.UnsignedCharTy;
1821
11
  }
1822
1823
  // Warn on initializing an array of char from a u8 string literal; this
1824
  // becomes ill-formed in C++2a.
1825
4.05M
  if (getLangOpts().CPlusPlus && 
!getLangOpts().CPlusPlus201.77M
&&
1826
1.77M
      !getLangOpts().Char8 && 
Kind == StringLiteral::UTF81.77M
) {
1827
62
    Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1828
1829
    // Create removals for all 'u8' prefixes in the string literal(s). This
1830
    // ensures C++2a compatibility (but may change the program behavior when
1831
    // built by non-Clang compilers for which the execution character set is
1832
    // not always UTF-8).
1833
62
    auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1834
62
    SourceLocation RemovalDiagLoc;
1835
65
    for (const Token &Tok : StringToks) {
1836
65
      if (Tok.getKind() == tok::utf8_string_literal) {
1837
64
        if (RemovalDiagLoc.isInvalid())
1838
62
          RemovalDiagLoc = Tok.getLocation();
1839
64
        RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1840
64
            Tok.getLocation(),
1841
64
            Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1842
64
                                           getSourceManager(), getLangOpts())));
1843
64
      }
1844
65
    }
1845
62
    Diag(RemovalDiagLoc, RemovalDiag);
1846
62
  }
1847
1848
4.05M
  QualType StrTy =
1849
4.05M
      Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1850
1851
  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1852
4.05M
  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1853
4.05M
                                             Kind, Literal.Pascal, StrTy,
1854
4.05M
                                             &StringTokLocs[0],
1855
4.05M
                                             StringTokLocs.size());
1856
4.05M
  if (Literal.getUDSuffix().empty())
1857
4.05M
    return Lit;
1858
1859
  // We're building a user-defined literal.
1860
102
  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1861
102
  SourceLocation UDSuffixLoc =
1862
102
    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1863
102
                   Literal.getUDSuffixOffset());
1864
1865
  // Make sure we're allowed user-defined literals here.
1866
102
  if (!UDLScope)
1867
6
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1868
1869
  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1870
  //   operator "" X (str, len)
1871
96
  QualType SizeType = Context.getSizeType();
1872
1873
96
  DeclarationName OpName =
1874
96
    Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1875
96
  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1876
96
  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1877
1878
96
  QualType ArgTy[] = {
1879
96
    Context.getArrayDecayedType(StrTy), SizeType
1880
96
  };
1881
1882
96
  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1883
96
  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1884
96
                                /*AllowRaw*/ false, /*AllowTemplate*/ true,
1885
96
                                /*AllowStringTemplatePack*/ true,
1886
96
                                /*DiagnoseMissing*/ true, Lit)) {
1887
1888
60
  case LOLR_Cooked: {
1889
60
    llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1890
60
    IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1891
60
                                                    StringTokLocs[0]);
1892
60
    Expr *Args[] = { Lit, LenArg };
1893
1894
60
    return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1895
0
  }
1896
1897
9
  case LOLR_Template: {
1898
9
    TemplateArgumentListInfo ExplicitArgs;
1899
9
    TemplateArgument Arg(Lit);
1900
9
    TemplateArgumentLocInfo ArgInfo(Lit);
1901
9
    ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1902
9
    return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1903
9
                                    &ExplicitArgs);
1904
0
  }
1905
1906
9
  case LOLR_StringTemplatePack: {
1907
9
    TemplateArgumentListInfo ExplicitArgs;
1908
1909
9
    unsigned CharBits = Context.getIntWidth(CharTy);
1910
9
    bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1911
9
    llvm::APSInt Value(CharBits, CharIsUnsigned);
1912
1913
9
    TemplateArgument TypeArg(CharTy);
1914
9
    TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1915
9
    ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1916
1917
76
    for (unsigned I = 0, N = Lit->getLength(); I != N; 
++I67
) {
1918
67
      Value = Lit->getCodeUnit(I);
1919
67
      TemplateArgument Arg(Context, Value, CharTy);
1920
67
      TemplateArgumentLocInfo ArgInfo;
1921
67
      ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1922
67
    }
1923
9
    return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1924
9
                                    &ExplicitArgs);
1925
0
  }
1926
0
  case LOLR_Raw:
1927
0
  case LOLR_ErrorNoDiagnostic:
1928
0
    llvm_unreachable("unexpected literal operator lookup result");
1929
18
  case LOLR_Error:
1930
18
    return ExprError();
1931
0
  }
1932
0
  llvm_unreachable("unexpected literal operator lookup result");
1933
0
}
1934
1935
DeclRefExpr *
1936
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1937
                       SourceLocation Loc,
1938
27.4k
                       const CXXScopeSpec *SS) {
1939
27.4k
  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1940
27.4k
  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1941
27.4k
}
1942
1943
DeclRefExpr *
1944
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1945
                       const DeclarationNameInfo &NameInfo,
1946
                       const CXXScopeSpec *SS, NamedDecl *FoundD,
1947
                       SourceLocation TemplateKWLoc,
1948
16.0M
                       const TemplateArgumentListInfo *TemplateArgs) {
1949
16.0M
  NestedNameSpecifierLoc NNS =
1950
16.0M
      SS ? SS->getWithLocInContext(Context) : 
NestedNameSpecifierLoc()27.4k
;
1951
16.0M
  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1952
16.0M
                          TemplateArgs);
1953
16.0M
}
1954
1955
// CUDA/HIP: Check whether a captured reference variable is referencing a
1956
// host variable in a device or host device lambda.
1957
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1958
859k
                                                            VarDecl *VD) {
1959
859k
  if (!S.getLangOpts().CUDA || 
!VD->hasInit()199
)
1960
859k
    return false;
1961
112
  assert(VD->getType()->isReferenceType());
1962
1963
  // Check whether the reference variable is referencing a host variable.
1964
112
  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1965
112
  if (!DRE)
1966
0
    return false;
1967
112
  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1968
112
  if (!Referee || !Referee->hasGlobalStorage() ||
1969
112
      Referee->hasAttr<CUDADeviceAttr>())
1970
26
    return false;
1971
1972
  // Check whether the current function is a device or host device lambda.
1973
  // Check whether the reference variable is a capture by getDeclContext()
1974
  // since refersToEnclosingVariableOrCapture() is not ready at this point.
1975
86
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1976
86
  if (MD && 
MD->getParent()->isLambda()32
&&
1977
32
      MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1978
32
      VD->getDeclContext() != MD)
1979
12
    return true;
1980
1981
74
  return false;
1982
74
}
1983
1984
17.8M
NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1985
  // A declaration named in an unevaluated operand never constitutes an odr-use.
1986
17.8M
  if (isUnevaluatedContext())
1987
153k
    return NOUR_Unevaluated;
1988
1989
  // C++2a [basic.def.odr]p4:
1990
  //   A variable x whose name appears as a potentially-evaluated expression e
1991
  //   is odr-used by e unless [...] x is a reference that is usable in
1992
  //   constant expressions.
1993
  // CUDA/HIP:
1994
  //   If a reference variable referencing a host variable is captured in a
1995
  //   device or host device lambda, the value of the referee must be copied
1996
  //   to the capture and the reference variable must be treated as odr-use
1997
  //   since the value of the referee is not known at compile time and must
1998
  //   be loaded from the captured.
1999
17.6M
  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2000
12.6M
    if (VD->getType()->isReferenceType() &&
2001
879k
        !(getLangOpts().OpenMP && 
isOpenMPCapturedDecl(D)49.3k
) &&
2002
859k
        !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2003
859k
        VD->isUsableInConstantExpressions(Context))
2004
3.02k
      return NOUR_Constant;
2005
17.6M
  }
2006
2007
  // All remaining non-variable cases constitute an odr-use. For variables, we
2008
  // need to wait and see how the expression is used.
2009
17.6M
  return NOUR_None;
2010
17.6M
}
2011
2012
/// BuildDeclRefExpr - Build an expression that references a
2013
/// declaration that does not require a closure capture.
2014
DeclRefExpr *
2015
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2016
                       const DeclarationNameInfo &NameInfo,
2017
                       NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2018
                       SourceLocation TemplateKWLoc,
2019
16.6M
                       const TemplateArgumentListInfo *TemplateArgs) {
2020
16.6M
  bool RefersToCapturedVariable =
2021
16.6M
      isa<VarDecl>(D) &&
2022
12.7M
      NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2023
2024
16.6M
  DeclRefExpr *E = DeclRefExpr::Create(
2025
16.6M
      Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2026
16.6M
      VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2027
16.6M
  MarkDeclRefReferenced(E);
2028
2029
  // C++ [except.spec]p17:
2030
  //   An exception-specification is considered to be needed when:
2031
  //   - in an expression, the function is the unique lookup result or
2032
  //     the selected member of a set of overloaded functions.
2033
  //
2034
  // We delay doing this until after we've built the function reference and
2035
  // marked it as used so that:
2036
  //  a) if the function is defaulted, we get errors from defining it before /
2037
  //     instead of errors from computing its exception specification, and
2038
  //  b) if the function is a defaulted comparison, we can use the body we
2039
  //     build when defining it as input to the exception specification
2040
  //     computation rather than computing a new body.
2041
16.6M
  if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2042
1.46M
    if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2043
1.50k
      if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2044
1.50k
        E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2045
1.50k
    }
2046
1.46M
  }
2047
2048
16.6M
  if (getLangOpts().ObjCWeak && 
isa<VarDecl>(D)27.0k
&&
2049
16.3k
      Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 
!isUnevaluatedContext()287
&&
2050
280
      !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2051
26
    getCurFunction()->recordUseOfWeak(E);
2052
2053
16.6M
  FieldDecl *FD = dyn_cast<FieldDecl>(D);
2054
16.6M
  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2055
40
    FD = IFD->getAnonField();
2056
16.6M
  if (FD) {
2057
944
    UnusedPrivateFields.remove(FD);
2058
    // Just in case we're building an illegal pointer-to-member.
2059
944
    if (FD->isBitField())
2060
2
      E->setObjectKind(OK_BitField);
2061
944
  }
2062
2063
  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2064
  // designates a bit-field.
2065
16.6M
  if (auto *BD = dyn_cast<BindingDecl>(D))
2066
386
    if (auto *BE = BD->getBinding())
2067
358
      E->setObjectKind(BE->getObjectKind());
2068
2069
16.6M
  return E;
2070
16.6M
}
2071
2072
/// Decomposes the given name into a DeclarationNameInfo, its location, and
2073
/// possibly a list of template arguments.
2074
///
2075
/// If this produces template arguments, it is permitted to call
2076
/// DecomposeTemplateName.
2077
///
2078
/// This actually loses a lot of source location information for
2079
/// non-standard name kinds; we should consider preserving that in
2080
/// some way.
2081
void
2082
Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2083
                             TemplateArgumentListInfo &Buffer,
2084
                             DeclarationNameInfo &NameInfo,
2085
15.1M
                             const TemplateArgumentListInfo *&TemplateArgs) {
2086
15.1M
  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2087
233k
    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2088
233k
    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2089
2090
233k
    ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2091
233k
                                       Id.TemplateId->NumArgs);
2092
233k
    translateTemplateArguments(TemplateArgsPtr, Buffer);
2093
2094
233k
    TemplateName TName = Id.TemplateId->Template.get();
2095
233k
    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2096
233k
    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2097
233k
    TemplateArgs = &Buffer;
2098
14.8M
  } else {
2099
14.8M
    NameInfo = GetNameFromUnqualifiedId(Id);
2100
14.8M
    TemplateArgs = nullptr;
2101
14.8M
  }
2102
15.1M
}
2103
2104
static void emitEmptyLookupTypoDiagnostic(
2105
    const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2106
    DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2107
2.91k
    unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2108
2.91k
  DeclContext *Ctx =
2109
2.78k
      SS.isEmpty() ? nullptr : 
SemaRef.computeDeclContext(SS, false)126
;
2110
2.91k
  if (!TC) {
2111
    // Emit a special diagnostic for failed member lookups.
2112
    // FIXME: computing the declaration context might fail here (?)
2113
2.62k
    if (Ctx)
2114
48
      SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2115
48
                                                 << SS.getRange();
2116
2.58k
    else
2117
2.58k
      SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2118
2.62k
    return;
2119
2.62k
  }
2120
2121
285
  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2122
285
  bool DroppedSpecifier =
2123
285
      TC.WillReplaceSpecifier() && 
Typo.getAsString() == CorrectedStr93
;
2124
285
  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2125
1
                        ? diag::note_implicit_param_decl
2126
284
                        : diag::note_previous_decl;
2127
285
  if (!Ctx)
2128
207
    SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2129
207
                         SemaRef.PDiag(NoteID));
2130
78
  else
2131
78
    SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2132
78
                                 << Typo << Ctx << DroppedSpecifier
2133
78
                                 << SS.getRange(),
2134
78
                         SemaRef.PDiag(NoteID));
2135
285
}
2136
2137
/// Diagnose a lookup that found results in an enclosing class during error
2138
/// recovery. This usually indicates that the results were found in a dependent
2139
/// base class that could not be searched as part of a template definition.
2140
/// Always issues a diagnostic (though this may be only a warning in MS
2141
/// compatibility mode).
2142
///
2143
/// Return \c true if the error is unrecoverable, or \c false if the caller
2144
/// should attempt to recover using these lookup results.
2145
36
bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2146
  // During a default argument instantiation the CurContext points
2147
  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2148
  // function parameter list, hence add an explicit check.
2149
36
  bool isDefaultArgument =
2150
36
      !CodeSynthesisContexts.empty() &&
2151
36
      CodeSynthesisContexts.back().Kind ==
2152
36
          CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2153
36
  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2154
36
  bool isInstance = CurMethod && 
CurMethod->isInstance()34
&&
2155
30
                    R.getNamingClass() == CurMethod->getParent() &&
2156
4
                    !isDefaultArgument;
2157
2158
  // There are two ways we can find a class-scope declaration during template
2159
  // instantiation that we did not find in the template definition: if it is a
2160
  // member of a dependent base class, or if it is declared after the point of
2161
  // use in the same class. Distinguish these by comparing the class in which
2162
  // the member was found to the naming class of the lookup.
2163
36
  unsigned DiagID = diag::err_found_in_dependent_base;
2164
36
  unsigned NoteID = diag::note_member_declared_at;
2165
36
  if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2166
0
    DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2167
4
                                      : diag::err_found_later_in_class;
2168
32
  } else if (getLangOpts().MSVCCompat) {
2169
22
    DiagID = diag::ext_found_in_dependent_base;
2170
22
    NoteID = diag::note_dependent_member_use;
2171
22
  }
2172
2173
36
  if (isInstance) {
2174
    // Give a code modification hint to insert 'this->'.
2175
4
    Diag(R.getNameLoc(), DiagID)
2176
4
        << R.getLookupName()
2177
4
        << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2178
4
    CheckCXXThisCapture(R.getNameLoc());
2179
32
  } else {
2180
    // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2181
    // they're not shadowed).
2182
32
    Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2183
32
  }
2184
2185
36
  for (NamedDecl *D : R)
2186
36
    Diag(D->getLocation(), NoteID);
2187
2188
  // Return true if we are inside a default argument instantiation
2189
  // and the found name refers to an instance member function, otherwise
2190
  // the caller will try to create an implicit member call and this is wrong
2191
  // for default arguments.
2192
  //
2193
  // FIXME: Is this special case necessary? We could allow the caller to
2194
  // diagnose this.
2195
36
  if (isDefaultArgument && 
((*R.begin())->isCXXInstanceMember())4
) {
2196
2
    Diag(R.getNameLoc(), diag::err_member_call_without_object);
2197
2
    return true;
2198
2
  }
2199
2200
  // Tell the callee to try to recover.
2201
34
  return false;
2202
34
}
2203
2204
/// Diagnose an empty lookup.
2205
///
2206
/// \return false if new lookup candidates were found
2207
bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2208
                               CorrectionCandidateCallback &CCC,
2209
                               TemplateArgumentListInfo *ExplicitTemplateArgs,
2210
5.25k
                               ArrayRef<Expr *> Args, TypoExpr **Out) {
2211
5.25k
  DeclarationName Name = R.getLookupName();
2212
2213
5.25k
  unsigned diagnostic = diag::err_undeclared_var_use;
2214
5.25k
  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2215
5.25k
  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2216
5.24k
      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2217
5.24k
      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2218
9
    diagnostic = diag::err_undeclared_use;
2219
9
    diagnostic_suggest = diag::err_undeclared_use_suggest;
2220
9
  }
2221
2222
  // If the original lookup was an unqualified lookup, fake an
2223
  // unqualified lookup.  This is useful when (for example) the
2224
  // original lookup would not have found something because it was a
2225
  // dependent name.
2226
5.08k
  DeclContext *DC = SS.isEmpty() ? CurContext : 
nullptr167
;
2227
17.5k
  while (DC) {
2228
12.2k
    if (isa<CXXRecordDecl>(DC)) {
2229
347
      LookupQualifiedName(R, DC);
2230
2231
347
      if (!R.empty()) {
2232
        // Don't give errors about ambiguities in this lookup.
2233
34
        R.suppressDiagnostics();
2234
2235
        // If there's a best viable function among the results, only mention
2236
        // that one in the notes.
2237
34
        OverloadCandidateSet Candidates(R.getNameLoc(),
2238
34
                                        OverloadCandidateSet::CSK_Normal);
2239
34
        AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2240
34
        OverloadCandidateSet::iterator Best;
2241
34
        if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2242
30
            OR_Success) {
2243
30
          R.clear();
2244
30
          R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2245
30
          R.resolveKind();
2246
30
        }
2247
2248
34
        return DiagnoseDependentMemberLookup(R);
2249
34
      }
2250
2251
313
      R.clear();
2252
313
    }
2253
2254
12.2k
    DC = DC->getLookupParent();
2255
12.2k
  }
2256
2257
  // We didn't find anything, so try to correct for a typo.
2258
5.21k
  TypoCorrection Corrected;
2259
5.21k
  if (S && 
Out5.19k
) {
2260
4.82k
    SourceLocation TypoLoc = R.getNameLoc();
2261
4.82k
    assert(!ExplicitTemplateArgs &&
2262
4.82k
           "Diagnosing an empty lookup with explicit template args!");
2263
4.82k
    *Out = CorrectTypoDelayed(
2264
4.82k
        R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2265
2.91k
        [=](const TypoCorrection &TC) {
2266
2.91k
          emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2267
2.91k
                                        diagnostic, diagnostic_suggest);
2268
2.91k
        },
2269
4.82k
        nullptr, CTK_ErrorRecovery);
2270
4.82k
    if (*Out)
2271
2.91k
      return true;
2272
390
  } else if (S &&
2273
369
             (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2274
120
                                      S, &SS, CCC, CTK_ErrorRecovery))) {
2275
120
    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2276
120
    bool DroppedSpecifier =
2277
120
        Corrected.WillReplaceSpecifier() && 
Name.getAsString() == CorrectedStr43
;
2278
120
    R.setLookupName(Corrected.getCorrection());
2279
2280
120
    bool AcceptableWithRecovery = false;
2281
120
    bool AcceptableWithoutRecovery = false;
2282
120
    NamedDecl *ND = Corrected.getFoundDecl();
2283
120
    if (ND) {
2284
108
      if (Corrected.isOverloaded()) {
2285
16
        OverloadCandidateSet OCS(R.getNameLoc(),
2286
16
                                 OverloadCandidateSet::CSK_Normal);
2287
16
        OverloadCandidateSet::iterator Best;
2288
60
        for (NamedDecl *CD : Corrected) {
2289
60
          if (FunctionTemplateDecl *FTD =
2290
20
                   dyn_cast<FunctionTemplateDecl>(CD))
2291
20
            AddTemplateOverloadCandidate(
2292
20
                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2293
20
                Args, OCS);
2294
40
          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2295
32
            if (!ExplicitTemplateArgs || 
ExplicitTemplateArgs->size() == 00
)
2296
32
              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2297
32
                                   Args, OCS);
2298
60
        }
2299
16
        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2300
12
        case OR_Success:
2301
12
          ND = Best->FoundDecl;
2302
12
          Corrected.setCorrectionDecl(ND);
2303
12
          break;
2304
4
        default:
2305
          // FIXME: Arbitrarily pick the first declaration for the note.
2306
4
          Corrected.setCorrectionDecl(ND);
2307
4
          break;
2308
108
        }
2309
108
      }
2310
108
      R.addDecl(ND);
2311
108
      if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2312
8
        CXXRecordDecl *Record = nullptr;
2313
8
        if (Corrected.getCorrectionSpecifier()) {
2314
3
          const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2315
3
          Record = Ty->getAsCXXRecordDecl();
2316
3
        }
2317
8
        if (!Record)
2318
5
          Record = cast<CXXRecordDecl>(
2319
5
              ND->getDeclContext()->getRedeclContext());
2320
8
        R.setNamingClass(Record);
2321
8
      }
2322
2323
108
      auto *UnderlyingND = ND->getUnderlyingDecl();
2324
108
      AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2325
34
                               isa<FunctionTemplateDecl>(UnderlyingND);
2326
      // FIXME: If we ended up with a typo for a type name or
2327
      // Objective-C class name, we're in trouble because the parser
2328
      // is in the wrong place to recover. Suggest the typo
2329
      // correction, but don't make it a fix-it since we're not going
2330
      // to recover well anyway.
2331
108
      AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2332
106
                                  getAsTypeTemplateDecl(UnderlyingND) ||
2333
93
                                  isa<ObjCInterfaceDecl>(UnderlyingND);
2334
12
    } else {
2335
      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2336
      // because we aren't able to recover.
2337
12
      AcceptableWithoutRecovery = true;
2338
12
    }
2339
2340
120
    if (AcceptableWithRecovery || 
AcceptableWithoutRecovery27
) {
2341
120
      unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2342
0
                            ? diag::note_implicit_param_decl
2343
120
                            : diag::note_previous_decl;
2344
120
      if (SS.isEmpty())
2345
120
        diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2346
120
                     PDiag(NoteID), AcceptableWithRecovery);
2347
0
      else
2348
0
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2349
0
                                  << Name << computeDeclContext(SS, false)
2350
0
                                  << DroppedSpecifier << SS.getRange(),
2351
0
                     PDiag(NoteID), AcceptableWithRecovery);
2352
2353
      // Tell the callee whether to try to recover.
2354
120
      return !AcceptableWithRecovery;
2355
120
    }
2356
2.18k
  }
2357
2.18k
  R.clear();
2358
2359
  // Emit a special diagnostic for failed member lookups.
2360
  // FIXME: computing the declaration context might fail here (?)
2361
2.18k
  if (!SS.isEmpty()) {
2362
41
    Diag(R.getNameLoc(), diag::err_no_member)
2363
41
      << Name << computeDeclContext(SS, false)
2364
41
      << SS.getRange();
2365
41
    return true;
2366
41
  }
2367
2368
  // Give up, we can't recover.
2369
2.14k
  Diag(R.getNameLoc(), diagnostic) << Name;
2370
2.14k
  return true;
2371
2.14k
}
2372
2373
/// In Microsoft mode, if we are inside a template class whose parent class has
2374
/// dependent base classes, and we can't resolve an unqualified identifier, then
2375
/// assume the identifier is a member of a dependent base class.  We can only
2376
/// recover successfully in static methods, instance methods, and other contexts
2377
/// where 'this' is available.  This doesn't precisely match MSVC's
2378
/// instantiation model, but it's close enough.
2379
static Expr *
2380
recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2381
                               DeclarationNameInfo &NameInfo,
2382
                               SourceLocation TemplateKWLoc,
2383
61
                               const TemplateArgumentListInfo *TemplateArgs) {
2384
  // Only try to recover from lookup into dependent bases in static methods or
2385
  // contexts where 'this' is available.
2386
61
  QualType ThisType = S.getCurrentThisType();
2387
61
  const CXXRecordDecl *RD = nullptr;
2388
61
  if (!ThisType.isNull())
2389
30
    RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2390
31
  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2391
4
    RD = MD->getParent();
2392
61
  if (!RD || 
!RD->hasAnyDependentBases()34
)
2393
35
    return nullptr;
2394
2395
  // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2396
  // is available, suggest inserting 'this->' as a fixit.
2397
26
  SourceLocation Loc = NameInfo.getLoc();
2398
26
  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2399
26
  DB << NameInfo.getName() << RD;
2400
2401
26
  if (!ThisType.isNull()) {
2402
22
    DB << FixItHint::CreateInsertion(Loc, "this->");
2403
22
    return CXXDependentScopeMemberExpr::Create(
2404
22
        Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2405
22
        /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2406
22
        /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2407
22
  }
2408
2409
  // Synthesize a fake NNS that points to the derived class.  This will
2410
  // perform name lookup during template instantiation.
2411
4
  CXXScopeSpec SS;
2412
4
  auto *NNS =
2413
4
      NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2414
4
  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2415
4
  return DependentScopeDeclRefExpr::Create(
2416
4
      Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2417
4
      TemplateArgs);
2418
4
}
2419
2420
ExprResult
2421
Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2422
                        SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2423
                        bool HasTrailingLParen, bool IsAddressOfOperand,
2424
                        CorrectionCandidateCallback *CCC,
2425
13.9M
                        bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2426
13.9M
  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2427
13.9M
         "cannot be direct & operand and have a trailing lparen");
2428
13.9M
  if (SS.isInvalid())
2429
64
    return ExprError();
2430
2431
13.9M
  TemplateArgumentListInfo TemplateArgsBuffer;
2432
2433
  // Decompose the UnqualifiedId into the following data.
2434
13.9M
  DeclarationNameInfo NameInfo;
2435
13.9M
  const TemplateArgumentListInfo *TemplateArgs;
2436
13.9M
  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2437
2438
13.9M
  DeclarationName Name = NameInfo.getName();
2439
13.9M
  IdentifierInfo *II = Name.getAsIdentifierInfo();
2440
13.9M
  SourceLocation NameLoc = NameInfo.getLoc();
2441
2442
13.9M
  if (II && 
II->isEditorPlaceholder()13.9M
) {
2443
    // FIXME: When typed placeholders are supported we can create a typed
2444
    // placeholder expression node.
2445
16
    return ExprError();
2446
16
  }
2447
2448
  // C++ [temp.dep.expr]p3:
2449
  //   An id-expression is type-dependent if it contains:
2450
  //     -- an identifier that was declared with a dependent type,
2451
  //        (note: handled after lookup)
2452
  //     -- a template-id that is dependent,
2453
  //        (note: handled in BuildTemplateIdExpr)
2454
  //     -- a conversion-function-id that specifies a dependent type,
2455
  //     -- a nested-name-specifier that contains a class-name that
2456
  //        names a dependent type.
2457
  // Determine whether this is a member of an unknown specialization;
2458
  // we need to handle these differently.
2459
13.9M
  bool DependentID = false;
2460
13.9M
  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2461
25
      Name.getCXXNameType()->isDependentType()) {
2462
3
    DependentID = true;
2463
13.9M
  } else if (SS.isSet()) {
2464
1.03M
    if (DeclContext *DC = computeDeclContext(SS, false)) {
2465
426k
      if (RequireCompleteDeclContext(SS, DC))
2466
2
        return ExprError();
2467
608k
    } else {
2468
608k
      DependentID = true;
2469
608k
    }
2470
1.03M
  }
2471
2472
13.9M
  if (DependentID)
2473
608k
    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2474
608k
                                      IsAddressOfOperand, TemplateArgs);
2475
2476
  // Perform the required lookup.
2477
13.3M
  LookupResult R(*this, NameInfo,
2478
13.3M
                 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2479
2.18k
                     ? LookupObjCImplicitSelfParam
2480
13.3M
                     : LookupOrdinaryName);
2481
13.3M
  if (TemplateKWLoc.isValid() || 
TemplateArgs13.3M
) {
2482
    // Lookup the template name again to correctly establish the context in
2483
    // which it was found. This is really unfortunate as we already did the
2484
    // lookup to determine that it was a template name in the first place. If
2485
    // this becomes a performance hit, we can work harder to preserve those
2486
    // results until we get here but it's likely not worth it.
2487
213k
    bool MemberOfUnknownSpecialization;
2488
213k
    AssumedTemplateKind AssumedTemplate;
2489
213k
    if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2490
213k
                           MemberOfUnknownSpecialization, TemplateKWLoc,
2491
213k
                           &AssumedTemplate))
2492
0
      return ExprError();
2493
2494
213k
    if (MemberOfUnknownSpecialization ||
2495
213k
        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2496
0
      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2497
0
                                        IsAddressOfOperand, TemplateArgs);
2498
13.1M
  } else {
2499
13.1M
    bool IvarLookupFollowUp = II && 
!SS.isSet()13.1M
&&
getCurMethodDecl()12.8M
;
2500
13.1M
    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2501
2502
    // If the result might be in a dependent base class, this is a dependent
2503
    // id-expression.
2504
13.1M
    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2505
13
      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2506
13
                                        IsAddressOfOperand, TemplateArgs);
2507
2508
    // If this reference is in an Objective-C method, then we need to do
2509
    // some special Objective-C lookup, too.
2510
13.1M
    if (IvarLookupFollowUp) {
2511
10.4k
      ExprResult E(LookupInObjCMethod(R, S, II, true));
2512
10.4k
      if (E.isInvalid())
2513
5
        return ExprError();
2514
2515
10.4k
      if (Expr *Ex = E.getAs<Expr>())
2516
1.25k
        return Ex;
2517
13.3M
    }
2518
13.1M
  }
2519
2520
13.3M
  if (R.isAmbiguous())
2521
56
    return ExprError();
2522
2523
  // This could be an implicitly declared function reference (legal in C90,
2524
  // extension in C99, forbidden in C++).
2525
13.3M
  if (R.empty() && 
HasTrailingLParen14.0k
&&
II9.21k
&&
!getLangOpts().CPlusPlus8.74k
) {
2526
4.84k
    NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2527
4.84k
    if (D) R.addDecl(D);
2528
4.84k
  }
2529
2530
  // Determine whether this name might be a candidate for
2531
  // argument-dependent lookup.
2532
13.3M
  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2533
2534
13.3M
  if (R.empty() && 
!ADL9.17k
) {
2535
4.87k
    if (SS.isEmpty() && 
getLangOpts().MSVCCompat4.70k
) {
2536
61
      if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2537
26
                                                   TemplateKWLoc, TemplateArgs))
2538
26
        return E;
2539
4.84k
    }
2540
2541
    // Don't diagnose an empty lookup for inline assembly.
2542
4.84k
    if (IsInlineAsmIdentifier)
2543
20
      return ExprError();
2544
2545
    // If this name wasn't predeclared and if this is not a function
2546
    // call, diagnose the problem.
2547
4.82k
    TypoExpr *TE = nullptr;
2548
167
    DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2549
4.66k
                                                       : nullptr);
2550
4.82k
    DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2551
4.82k
    assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2552
4.82k
           "Typo correction callback misconfigured");
2553
4.82k
    if (CCC) {
2554
      // Make sure the callback knows what the typo being diagnosed is.
2555
4.65k
      CCC->setTypoName(II);
2556
4.65k
      if (SS.isValid())
2557
0
        CCC->setTypoNNS(SS.getScopeRep());
2558
4.65k
    }
2559
    // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2560
    // a template name, but we happen to have always already looked up the name
2561
    // before we get here if it must be a template name.
2562
4.82k
    if (DiagnoseEmptyLookup(S, SS, R, CCC ? 
*CCC4.65k
:
DefaultValidator171
, nullptr,
2563
4.82k
                            None, &TE)) {
2564
4.82k
      if (TE && 
KeywordReplacement2.91k
) {
2565
2.07k
        auto &State = getTypoExprState(TE);
2566
2.07k
        auto BestTC = State.Consumer->getNextCorrection();
2567
2.07k
        if (BestTC.isKeyword()) {
2568
6
          auto *II = BestTC.getCorrectionAsIdentifierInfo();
2569
6
          if (State.DiagHandler)
2570
6
            State.DiagHandler(BestTC);
2571
6
          KeywordReplacement->startToken();
2572
6
          KeywordReplacement->setKind(II->getTokenID());
2573
6
          KeywordReplacement->setIdentifierInfo(II);
2574
6
          KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2575
          // Clean up the state associated with the TypoExpr, since it has
2576
          // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2577
6
          clearDelayedTypo(TE);
2578
          // Signal that a correction to a keyword was performed by returning a
2579
          // valid-but-null ExprResult.
2580
6
          return (Expr*)nullptr;
2581
6
        }
2582
2.06k
        State.Consumer->resetCorrectionStream();
2583
2.06k
      }
2584
4.82k
      return TE ? 
TE2.90k
:
ExprError()1.91k
;
2585
0
    }
2586
2587
0
    assert(!R.empty() &&
2588
0
           "DiagnoseEmptyLookup returned false but added no results");
2589
2590
    // If we found an Objective-C instance variable, let
2591
    // LookupInObjCMethod build the appropriate expression to
2592
    // reference the ivar.
2593
0
    if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2594
0
      R.clear();
2595
0
      ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2596
      // In a hopelessly buggy code, Objective-C instance variable
2597
      // lookup fails and no expression will be built to reference it.
2598
0
      if (!E.isInvalid() && !E.get())
2599
0
        return ExprError();
2600
0
      return E;
2601
0
    }
2602
0
  }
2603
2604
  // This is guaranteed from this point on.
2605
13.3M
  assert(!R.empty() || ADL);
2606
2607
  // Check whether this might be a C++ implicit instance member access.
2608
  // C++ [class.mfct.non-static]p3:
2609
  //   When an id-expression that is not part of a class member access
2610
  //   syntax and not used to form a pointer to member is used in the
2611
  //   body of a non-static member function of class X, if name lookup
2612
  //   resolves the name in the id-expression to a non-static non-type
2613
  //   member of some class C, the id-expression is transformed into a
2614
  //   class member access expression using (*this) as the
2615
  //   postfix-expression to the left of the . operator.
2616
  //
2617
  // But we don't actually need to do this for '&' operands if R
2618
  // resolved to a function or overloaded function set, because the
2619
  // expression is ill-formed if it actually works out to be a
2620
  // non-static member function:
2621
  //
2622
  // C++ [expr.ref]p4:
2623
  //   Otherwise, if E1.E2 refers to a non-static member function. . .
2624
  //   [t]he expression can be used only as the left-hand operand of a
2625
  //   member function call.
2626
  //
2627
  // There are other safeguards against such uses, but it's important
2628
  // to get this right here so that we don't end up making a
2629
  // spuriously dependent expression if we're inside a dependent
2630
  // instance method.
2631
13.3M
  if (!R.empty() && 
(*R.begin())->isCXXClassMember()13.3M
) {
2632
687k
    bool MightBeImplicitMember;
2633
687k
    if (!IsAddressOfOperand)
2634
661k
      MightBeImplicitMember = true;
2635
25.7k
    else if (!SS.isEmpty())
2636
2.64k
      MightBeImplicitMember = false;
2637
23.0k
    else if (R.isOverloadedResult())
2638
1.19k
      MightBeImplicitMember = false;
2639
21.8k
    else if (R.isUnresolvableResult())
2640
7
      MightBeImplicitMember = true;
2641
21.8k
    else
2642
21.8k
      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2643
426
                              isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2644
422
                              isa<MSPropertyDecl>(R.getFoundDecl());
2645
2646
687k
    if (MightBeImplicitMember)
2647
683k
      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2648
683k
                                             R, TemplateArgs, S);
2649
12.6M
  }
2650
2651
12.6M
  if (TemplateArgs || 
TemplateKWLoc.isValid()12.4M
) {
2652
2653
    // In C++1y, if this is a variable template id, then check it
2654
    // in BuildTemplateIdExpr().
2655
    // The single lookup result must be a variable template declaration.
2656
200k
    if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && 
Id.TemplateId200k
&&
2657
200k
        Id.TemplateId->Kind == TNK_Var_template) {
2658
1.36k
      assert(R.getAsSingle<VarTemplateDecl>() &&
2659
1.36k
             "There should only be one declaration found.");
2660
1.36k
    }
2661
2662
200k
    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2663
200k
  }
2664
2665
12.4M
  return BuildDeclarationNameExpr(SS, R, ADL);
2666
12.4M
}
2667
2668
/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2669
/// declaration name, generally during template instantiation.
2670
/// There's a large number of things which don't need to be done along
2671
/// this path.
2672
ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2673
    CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2674
1.13M
    bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2675
1.13M
  DeclContext *DC = computeDeclContext(SS, false);
2676
1.13M
  if (!DC)
2677
442k
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2678
442k
                                     NameInfo, /*TemplateArgs=*/nullptr);
2679
2680
695k
  if (RequireCompleteDeclContext(SS, DC))
2681
14
    return ExprError();
2682
2683
695k
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2684
695k
  LookupQualifiedName(R, DC);
2685
2686
695k
  if (R.isAmbiguous())
2687
0
    return ExprError();
2688
2689
695k
  if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2690
0
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2691
0
                                     NameInfo, /*TemplateArgs=*/nullptr);
2692
2693
695k
  if (R.empty()) {
2694
    // Don't diagnose problems with invalid record decl, the secondary no_member
2695
    // diagnostic during template instantiation is likely bogus, e.g. if a class
2696
    // is invalid because it's derived from an invalid base class, then missing
2697
    // members were likely supposed to be inherited.
2698
833
    if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2699
832
      if (CD->isInvalidDecl())
2700
2
        return ExprError();
2701
831
    Diag(NameInfo.getLoc(), diag::err_no_member)
2702
831
      << NameInfo.getName() << DC << SS.getRange();
2703
831
    return ExprError();
2704
831
  }
2705
2706
694k
  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2707
    // Diagnose a missing typename if this resolved unambiguously to a type in
2708
    // a dependent context.  If we can recover with a type, downgrade this to
2709
    // a warning in Microsoft compatibility mode.
2710
36
    unsigned DiagID = diag::err_typename_missing;
2711
36
    if (RecoveryTSI && 
getLangOpts().MSVCCompat3
)
2712
3
      DiagID = diag::ext_typename_missing;
2713
36
    SourceLocation Loc = SS.getBeginLoc();
2714
36
    auto D = Diag(Loc, DiagID);
2715
36
    D << SS.getScopeRep() << NameInfo.getName().getAsString()
2716
36
      << SourceRange(Loc, NameInfo.getEndLoc());
2717
2718
    // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2719
    // context.
2720
36
    if (!RecoveryTSI)
2721
33
      return ExprError();
2722
2723
    // Only issue the fixit if we're prepared to recover.
2724
3
    D << FixItHint::CreateInsertion(Loc, "typename ");
2725
2726
    // Recover by pretending this was an elaborated type.
2727
3
    QualType Ty = Context.getTypeDeclType(TD);
2728
3
    TypeLocBuilder TLB;
2729
3
    TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2730
2731
3
    QualType ET = getElaboratedType(ETK_None, SS, Ty);
2732
3
    ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2733
3
    QTL.setElaboratedKeywordLoc(SourceLocation());
2734
3
    QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2735
2736
3
    *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2737
2738
3
    return ExprEmpty();
2739
3
  }
2740
2741
  // Defend against this resolving to an implicit member access. We usually
2742
  // won't get here if this might be a legitimate a class member (we end up in
2743
  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2744
  // a pointer-to-member or in an unevaluated context in C++11.
2745
694k
  if (!R.empty() && (*R.begin())->isCXXClassMember() && 
!IsAddressOfOperand694k
)
2746
694k
    return BuildPossibleImplicitMemberExpr(SS,
2747
694k
                                           /*TemplateKWLoc=*/SourceLocation(),
2748
694k
                                           R, /*TemplateArgs=*/nullptr, S);
2749
2750
84
  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2751
84
}
2752
2753
/// The parser has read a name in, and Sema has detected that we're currently
2754
/// inside an ObjC method. Perform some additional checks and determine if we
2755
/// should form a reference to an ivar.
2756
///
2757
/// Ideally, most of this would be done by lookup, but there's
2758
/// actually quite a lot of extra work involved.
2759
DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2760
14.3k
                                        IdentifierInfo *II) {
2761
14.3k
  SourceLocation Loc = Lookup.getNameLoc();
2762
14.3k
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2763
2764
  // Check for error condition which is already reported.
2765
14.3k
  if (!CurMethod)
2766
0
    return DeclResult(true);
2767
2768
  // There are two cases to handle here.  1) scoped lookup could have failed,
2769
  // in which case we should look for an ivar.  2) scoped lookup could have
2770
  // found a decl, but that decl is outside the current instance method (i.e.
2771
  // a global variable).  In these two cases, we do a lookup for an ivar with
2772
  // this name, if the lookup sucedes, we replace it our current decl.
2773
2774
  // If we're in a class method, we don't normally want to look for
2775
  // ivars.  But if we don't find anything else, and there's an
2776
  // ivar, that's an error.
2777
14.3k
  bool IsClassMethod = CurMethod->isClassMethod();
2778
2779
14.3k
  bool LookForIvars;
2780
14.3k
  if (Lookup.empty())
2781
2.17k
    LookForIvars = true;
2782
12.1k
  else if (IsClassMethod)
2783
854
    LookForIvars = false;
2784
11.3k
  else
2785
11.3k
    LookForIvars = (Lookup.isSingleResult() &&
2786
11.3k
                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2787
14.3k
  ObjCInterfaceDecl *IFace = nullptr;
2788
14.3k
  if (LookForIvars) {
2789
3.88k
    IFace = CurMethod->getClassInterface();
2790
3.88k
    ObjCInterfaceDecl *ClassDeclared;
2791
3.88k
    ObjCIvarDecl *IV = nullptr;
2792
3.88k
    if (IFace && 
(IV = IFace->lookupInstanceVariable(II, ClassDeclared))3.87k
) {
2793
      // Diagnose using an ivar in a class method.
2794
2.19k
      if (IsClassMethod) {
2795
8
        Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2796
8
        return DeclResult(true);
2797
8
      }
2798
2799
      // Diagnose the use of an ivar outside of the declaring class.
2800
2.18k
      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2801
674
          !declaresSameEntity(ClassDeclared, IFace) &&
2802
9
          !getLangOpts().DebuggerSupport)
2803
3
        Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2804
2805
      // Success.
2806
2.18k
      return IV;
2807
2.18k
    }
2808
10.4k
  } else if (CurMethod->isInstanceMethod()) {
2809
    // We should warn if a local variable hides an ivar.
2810
9.62k
    if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2811
9.61k
      ObjCInterfaceDecl *ClassDeclared;
2812
9.61k
      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2813
2
        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2814
0
            declaresSameEntity(IFace, ClassDeclared))
2815
2
          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2816
2
      }
2817
9.61k
    }
2818
854
  } else if (Lookup.isSingleResult() &&
2819
854
             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2820
    // If accessing a stand-alone ivar in a class method, this is an error.
2821
187
    if (const ObjCIvarDecl *IV =
2822
1
            dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2823
1
      Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2824
1
      return DeclResult(true);
2825
1
    }
2826
12.1k
  }
2827
2828
  // Didn't encounter an error, didn't find an ivar.
2829
12.1k
  return DeclResult(false);
2830
12.1k
}
2831
2832
ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2833
2.18k
                                  ObjCIvarDecl *IV) {
2834
2.18k
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2835
2.18k
  assert(CurMethod && CurMethod->isInstanceMethod() &&
2836
2.18k
         "should not reference ivar from this context");
2837
2838
2.18k
  ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2839
2.18k
  assert(IFace && "should not reference ivar from this context");
2840
2841
  // If we're referencing an invalid decl, just return this as a silent
2842
  // error node.  The error diagnostic was already emitted on the decl.
2843
2.18k
  if (IV->isInvalidDecl())
2844
2
    return ExprError();
2845
2846
  // Check if referencing a field with __attribute__((deprecated)).
2847
2.18k
  if (DiagnoseUseOfDecl(IV, Loc))
2848
0
    return ExprError();
2849
2850
  // FIXME: This should use a new expr for a direct reference, don't
2851
  // turn this into Self->ivar, just return a BareIVarExpr or something.
2852
2.18k
  IdentifierInfo &II = Context.Idents.get("self");
2853
2.18k
  UnqualifiedId SelfName;
2854
2.18k
  SelfName.setImplicitSelfParam(&II);
2855
2.18k
  CXXScopeSpec SelfScopeSpec;
2856
2.18k
  SourceLocation TemplateKWLoc;
2857
2.18k
  ExprResult SelfExpr =
2858
2.18k
      ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2859
2.18k
                        /*HasTrailingLParen=*/false,
2860
2.18k
                        /*IsAddressOfOperand=*/false);
2861
2.18k
  if (SelfExpr.isInvalid())
2862
0
    return ExprError();
2863
2864
2.18k
  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2865
2.18k
  if (SelfExpr.isInvalid())
2866
0
    return ExprError();
2867
2868
2.18k
  MarkAnyDeclReferenced(Loc, IV, true);
2869
2870
2.18k
  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2871
2.18k
  if (MF != OMF_init && 
MF != OMF_dealloc1.80k
&&
MF != OMF_finalize1.60k
&&
2872
1.60k
      !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2873
1.57k
    Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2874
2875
2.18k
  ObjCIvarRefExpr *Result = new (Context)
2876
2.18k
      ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2877
2.18k
                      IV->getLocation(), SelfExpr.get(), true, true);
2878
2879
2.18k
  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2880
15
    if (!isUnevaluatedContext() &&
2881
15
        !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2882
4
      getCurFunction()->recordUseOfWeak(Result);
2883
15
  }
2884
2.18k
  if (getLangOpts().ObjCAutoRefCount)
2885
260
    if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2886
24
      ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2887
2888
2.18k
  return Result;
2889
2.18k
}
2890
2891
/// The parser has read a name in, and Sema has detected that we're currently
2892
/// inside an ObjC method. Perform some additional checks and determine if we
2893
/// should form a reference to an ivar. If so, build an expression referencing
2894
/// that ivar.
2895
ExprResult
2896
Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2897
10.4k
                         IdentifierInfo *II, bool AllowBuiltinCreation) {
2898
  // FIXME: Integrate this lookup step into LookupParsedName.
2899
10.4k
  DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2900
10.4k
  if (Ivar.isInvalid())
2901
3
    return ExprError();
2902
10.4k
  if (Ivar.isUsable())
2903
1.27k
    return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2904
1.27k
                            cast<ObjCIvarDecl>(Ivar.get()));
2905
2906
9.19k
  if (Lookup.empty() && 
II173
&&
AllowBuiltinCreation173
)
2907
173
    LookupBuiltin(Lookup);
2908
2909
  // Sentinel value saying that we didn't do anything special.
2910
9.19k
  return ExprResult(false);
2911
9.19k
}
2912
2913
/// Cast a base object to a member's actual type.
2914
///
2915
/// There are two relevant checks:
2916
///
2917
/// C++ [class.access.base]p7:
2918
///
2919
///   If a class member access operator [...] is used to access a non-static
2920
///   data member or non-static member function, the reference is ill-formed if
2921
///   the left operand [...] cannot be implicitly converted to a pointer to the
2922
///   naming class of the right operand.
2923
///
2924
/// C++ [expr.ref]p7:
2925
///
2926
///   If E2 is a non-static data member or a non-static member function, the
2927
///   program is ill-formed if the class of which E2 is directly a member is an
2928
///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2929
///
2930
/// Note that the latter check does not consider access; the access of the
2931
/// "real" base class is checked as appropriate when checking the access of the
2932
/// member name.
2933
ExprResult
2934
Sema::PerformObjectMemberConversion(Expr *From,
2935
                                    NestedNameSpecifier *Qualifier,
2936
                                    NamedDecl *FoundDecl,
2937
815k
                                    NamedDecl *Member) {
2938
815k
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2939
815k
  if (!RD)
2940
127k
    return From;
2941
2942
688k
  QualType DestRecordType;
2943
688k
  QualType DestType;
2944
688k
  QualType FromRecordType;
2945
688k
  QualType FromType = From->getType();
2946
688k
  bool PointerConversions = false;
2947
688k
  if (isa<FieldDecl>(Member)) {
2948
678k
    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2949
678k
    auto FromPtrType = FromType->getAs<PointerType>();
2950
678k
    DestRecordType = Context.getAddrSpaceQualType(
2951
678k
        DestRecordType, FromPtrType
2952
528k
                            ? FromType->getPointeeType().getAddressSpace()
2953
150k
                            : FromType.getAddressSpace());
2954
2955
678k
    if (FromPtrType) {
2956
528k
      DestType = Context.getPointerType(DestRecordType);
2957
528k
      FromRecordType = FromPtrType->getPointeeType();
2958
528k
      PointerConversions = true;
2959
150k
    } else {
2960
150k
      DestType = DestRecordType;
2961
150k
      FromRecordType = FromType;
2962
150k
    }
2963
9.21k
  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2964
9.21k
    if (Method->isStatic())
2965
0
      return From;
2966
2967
9.21k
    DestType = Method->getThisType();
2968
9.21k
    DestRecordType = DestType->getPointeeType();
2969
2970
9.21k
    if (FromType->getAs<PointerType>()) {
2971
7.47k
      FromRecordType = FromType->getPointeeType();
2972
7.47k
      PointerConversions = true;
2973
1.74k
    } else {
2974
1.74k
      FromRecordType = FromType;
2975
1.74k
      DestType = DestRecordType;
2976
1.74k
    }
2977
2978
9.21k
    LangAS FromAS = FromRecordType.getAddressSpace();
2979
9.21k
    LangAS DestAS = DestRecordType.getAddressSpace();
2980
9.21k
    if (FromAS != DestAS) {
2981
4
      QualType FromRecordTypeWithoutAS =
2982
4
          Context.removeAddrSpaceQualType(FromRecordType);
2983
4
      QualType FromTypeWithDestAS =
2984
4
          Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2985
4
      if (PointerConversions)
2986
1
        FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2987
4
      From = ImpCastExprToType(From, FromTypeWithDestAS,
2988
4
                               CK_AddressSpaceConversion, From->getValueKind())
2989
4
                 .get();
2990
4
    }
2991
0
  } else {
2992
    // No conversion necessary.
2993
0
    return From;
2994
0
  }
2995
2996
688k
  if (DestType->isDependentType() || 
FromType->isDependentType()336k
)
2997
351k
    return From;
2998
2999
  // If the unqualified types are the same, no conversion is necessary.
3000
336k
  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3001
317k
    return From;
3002
3003
18.9k
  SourceRange FromRange = From->getSourceRange();
3004
18.9k
  SourceLocation FromLoc = FromRange.getBegin();
3005
3006
18.9k
  ExprValueKind VK = From->getValueKind();
3007
3008
  // C++ [class.member.lookup]p8:
3009
  //   [...] Ambiguities can often be resolved by qualifying a name with its
3010
  //   class name.
3011
  //
3012
  // If the member was a qualified name and the qualified referred to a
3013
  // specific base subobject type, we'll cast to that intermediate type
3014
  // first and then to the object in which the member is declared. That allows
3015
  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3016
  //
3017
  //   class Base { public: int x; };
3018
  //   class Derived1 : public Base { };
3019
  //   class Derived2 : public Base { };
3020
  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3021
  //
3022
  //   void VeryDerived::f() {
3023
  //     x = 17; // error: ambiguous base subobjects
3024
  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3025
  //   }
3026
18.9k
  if (Qualifier && 
Qualifier->getAsType()5.92k
) {
3027
5.91k
    QualType QType = QualType(Qualifier->getAsType(), 0);
3028
5.91k
    assert(QType->isRecordType() && "lookup done with non-record type");
3029
3030
5.91k
    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3031
3032
    // In C++98, the qualifier type doesn't actually have to be a base
3033
    // type of the object type, in which case we just ignore it.
3034
    // Otherwise build the appropriate casts.
3035
5.91k
    if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3036
5.88k
      CXXCastPath BasePath;
3037
5.88k
      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3038
5.88k
                                       FromLoc, FromRange, &BasePath))
3039
16
        return ExprError();
3040
3041
5.86k
      if (PointerConversions)
3042
5.70k
        QType = Context.getPointerType(QType);
3043
5.86k
      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3044
5.86k
                               VK, &BasePath).get();
3045
3046
5.86k
      FromType = QType;
3047
5.86k
      FromRecordType = QRecordType;
3048
3049
      // If the qualifier type was the same as the destination type,
3050
      // we're done.
3051
5.86k
      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3052
5.71k
        return From;
3053
13.1k
    }
3054
5.91k
  }
3055
3056
13.1k
  CXXCastPath BasePath;
3057
13.1k
  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3058
13.1k
                                   FromLoc, FromRange, &BasePath,
3059
13.1k
                                   /*IgnoreAccess=*/true))
3060
6
    return ExprError();
3061
3062
13.1k
  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3063
13.1k
                           VK, &BasePath);
3064
13.1k
}
3065
3066
bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3067
                                      const LookupResult &R,
3068
17.5M
                                      bool HasTrailingLParen) {
3069
  // Only when used directly as the postfix-expression of a call.
3070
17.5M
  if (!HasTrailingLParen)
3071
13.5M
    return false;
3072
3073
  // Never if a scope specifier was provided.
3074
3.94M
  if (SS.isSet())
3075
446k
    return false;
3076
3077
  // Only in C++ or ObjC++.
3078
3.49M
  if (!getLangOpts().CPlusPlus)
3079
2.31M
    return false;
3080
3081
  // Turn off ADL when we find certain kinds of declarations during
3082
  // normal lookup:
3083
1.53M
  
for (NamedDecl *D : R)1.18M
{
3084
    // C++0x [basic.lookup.argdep]p3:
3085
    //     -- a declaration of a class member
3086
    // Since using decls preserve this property, we check this on the
3087
    // original decl.
3088
1.53M
    if (D->isCXXClassMember())
3089
385k
      return false;
3090
3091
    // C++0x [basic.lookup.argdep]p3:
3092
    //     -- a block-scope function declaration that is not a
3093
    //        using-declaration
3094
    // NOTE: we also trigger this for function templates (in fact, we
3095
    // don't check the decl type at all, since all other decl types
3096
    // turn off ADL anyway).
3097
1.15M
    if (isa<UsingShadowDecl>(D))
3098
35.0k
      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3099
1.11M
    else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3100
113k
      return false;
3101
3102
    // C++0x [basic.lookup.argdep]p3:
3103
    //     -- a declaration that is neither a function or a function
3104
    //        template
3105
    // And also for builtin functions.
3106
1.03M
    if (isa<FunctionDecl>(D)) {
3107
665k
      FunctionDecl *FDecl = cast<FunctionDecl>(D);
3108
3109
      // But also builtin functions.
3110
665k
      if (FDecl->getBuiltinID() && 
FDecl->isImplicit()212k
)
3111
209k
        return false;
3112
372k
    } else if (!isa<FunctionTemplateDecl>(D))
3113
2.86k
      return false;
3114
1.03M
  }
3115
3116
468k
  return true;
3117
1.18M
}
3118
3119
3120
/// Diagnoses obvious problems with the use of the given declaration
3121
/// as an expression.  This is only actually called for lookups that
3122
/// were not overloaded, and it doesn't promise that the declaration
3123
/// will in fact be used.
3124
16.1M
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3125
16.1M
  if (D->isInvalidDecl())
3126
3.56k
    return true;
3127
3128
16.1M
  if (isa<TypedefNameDecl>(D)) {
3129
3
    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3130
3
    return true;
3131
3
  }
3132
3133
16.1M
  if (isa<ObjCInterfaceDecl>(D)) {
3134
2
    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3135
2
    return true;
3136
2
  }
3137
3138
16.1M
  if (isa<NamespaceDecl>(D)) {
3139
4
    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3140
4
    return true;
3141
4
  }
3142
3143
16.1M
  return false;
3144
16.1M
}
3145
3146
// Certain multiversion types should be treated as overloaded even when there is
3147
// only one result.
3148
14.9M
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3149
14.9M
  assert(R.isSingleResult() && "Expected only a single result");
3150
14.9M
  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3151
14.9M
  return FD &&
3152
2.56M
         (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3153
14.9M
}
3154
3155
ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3156
                                          LookupResult &R, bool NeedsADL,
3157
15.3M
                                          bool AcceptInvalidDecl) {
3158
  // If this is a single, fully-resolved result and we don't need ADL,
3159
  // just build an ordinary singleton decl ref.
3160
15.3M
  if (!NeedsADL && 
R.isSingleResult()15.0M
&&
3161
14.7M
      !R.getAsSingle<FunctionTemplateDecl>() &&
3162
14.7M
      !ShouldLookupResultBeMultiVersionOverload(R))
3163
14.7M
    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3164
14.7M
                                    R.getRepresentativeDecl(), nullptr,
3165
14.7M
                                    AcceptInvalidDecl);
3166
3167
  // We only need to check the declaration if there's exactly one
3168
  // result, because in the overloaded case the results can only be
3169
  // functions and function templates.
3170
566k
  if (R.isSingleResult() && 
!ShouldLookupResultBeMultiVersionOverload(R)138k
&&
3171
138k
      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3172
6
    return ExprError();
3173
3174
  // Otherwise, just build an unresolved lookup expression.  Suppress
3175
  // any lookup-related diagnostics; we'll hash these out later, when
3176
  // we've picked a target.
3177
566k
  R.suppressDiagnostics();
3178
3179
566k
  UnresolvedLookupExpr *ULE
3180
566k
    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3181
566k
                                   SS.getWithLocInContext(Context),
3182
566k
                                   R.getLookupNameInfo(),
3183
566k
                                   NeedsADL, R.isOverloadedResult(),
3184
566k
                                   R.begin(), R.end());
3185
3186
566k
  return ULE;
3187
566k
}
3188
3189
static void
3190
diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3191
                                   ValueDecl *var, DeclContext *DC);
3192
3193
/// Complete semantic analysis for a reference to the given declaration.
3194
ExprResult Sema::BuildDeclarationNameExpr(
3195
    const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3196
    NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3197
16.0M
    bool AcceptInvalidDecl) {
3198
16.0M
  assert(D && "Cannot refer to a NULL declaration");
3199
16.0M
  assert(!isa<FunctionTemplateDecl>(D) &&
3200
16.0M
         "Cannot refer unambiguously to a function template");
3201
3202
16.0M
  SourceLocation Loc = NameInfo.getLoc();
3203
16.0M
  if (CheckDeclInExpr(*this, Loc, D))
3204
3.56k
    return ExprError();
3205
3206
16.0M
  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3207
    // Specifically diagnose references to class templates that are missing
3208
    // a template argument list.
3209
12
    diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3210
12
    return ExprError();
3211
12
  }
3212
3213
  // Make sure that we're referring to a value.
3214
16.0M
  ValueDecl *VD = dyn_cast<ValueDecl>(D);
3215
16.0M
  if (!VD) {
3216
3.14k
    Diag(Loc, diag::err_ref_non_value)
3217
3.14k
      << D << SS.getRange();
3218
3.14k
    Diag(D->getLocation(), diag::note_declared_at);
3219
3.14k
    return ExprError();
3220
3.14k
  }
3221
3222
  // Check whether this declaration can be used. Note that we suppress
3223
  // this check when we're going to perform argument-dependent lookup
3224
  // on this function name, because this might not be the function
3225
  // that overload resolution actually selects.
3226
16.0M
  if (DiagnoseUseOfDecl(VD, Loc))
3227
156
    return ExprError();
3228
3229
  // Only create DeclRefExpr's for valid Decl's.
3230
16.0M
  if (VD->isInvalidDecl() && 
!AcceptInvalidDecl0
)
3231
0
    return ExprError();
3232
3233
  // Handle members of anonymous structs and unions.  If we got here,
3234
  // and the reference is to a class member indirect field, then this
3235
  // must be the subject of a pointer-to-member expression.
3236
16.0M
  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3237
112
    if (!indirectField->isCXXClassMember())
3238
72
      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3239
72
                                                      indirectField);
3240
3241
16.0M
  {
3242
16.0M
    QualType type = VD->getType();
3243
16.0M
    if (type.isNull())
3244
1
      return ExprError();
3245
16.0M
    ExprValueKind valueKind = VK_RValue;
3246
3247
    // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3248
    // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3249
    // is expanded by some outer '...' in the context of the use.
3250
16.0M
    type = type.getNonPackExpansionType();
3251
3252
16.0M
    switch (D->getKind()) {
3253
    // Ignore all the non-ValueDecl kinds.
3254
0
#define ABSTRACT_DECL(kind)
3255
0
#define VALUE(type, base)
3256
0
#define DECL(type, base) \
3257
0
    case Decl::type:
3258
0
#include "clang/AST/DeclNodes.inc"
3259
0
      llvm_unreachable("invalid value decl kind");
3260
3261
    // These shouldn't make it here.
3262
0
    case Decl::ObjCAtDefsField:
3263
0
      llvm_unreachable("forming non-member reference to ivar?");
3264
3265
    // Enum constants are always r-values and never references.
3266
    // Unresolved using declarations are dependent.
3267
494k
    case Decl::EnumConstant:
3268
494k
    case Decl::UnresolvedUsingValue:
3269
494k
    case Decl::OMPDeclareReduction:
3270
494k
    case Decl::OMPDeclareMapper:
3271
494k
      valueKind = VK_RValue;
3272
494k
      break;
3273
3274
    // Fields and indirect fields that got here must be for
3275
    // pointer-to-member expressions; we just call them l-values for
3276
    // internal consistency, because this subexpression doesn't really
3277
    // exist in the high-level semantics.
3278
897
    case Decl::Field:
3279
937
    case Decl::IndirectField:
3280
944
    case Decl::ObjCIvar:
3281
944
      assert(getLangOpts().CPlusPlus &&
3282
944
             "building reference to field in C?");
3283
3284
      // These can't have reference type in well-formed programs, but
3285
      // for internal consistency we do this anyway.
3286
944
      type = type.getNonReferenceType();
3287
944
      valueKind = VK_LValue;
3288
944
      break;
3289
3290
    // Non-type template parameters are either l-values or r-values
3291
    // depending on the type.
3292
332k
    case Decl::NonTypeTemplateParm: {
3293
332k
      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3294
53
        type = reftype->getPointeeType();
3295
53
        valueKind = VK_LValue; // even if the parameter is an r-value reference
3296
53
        break;
3297
53
      }
3298
3299
      // [expr.prim.id.unqual]p2:
3300
      //   If the entity is a template parameter object for a template
3301
      //   parameter of type T, the type of the expression is const T.
3302
      //   [...] The expression is an lvalue if the entity is a [...] template
3303
      //   parameter object.
3304
332k
      if (type->isRecordType()) {
3305
32
        type = type.getUnqualifiedType().withConst();
3306
32
        valueKind = VK_LValue;
3307
32
        break;
3308
32
      }
3309
3310
      // For non-references, we need to strip qualifiers just in case
3311
      // the template parameter was declared as 'const int' or whatever.
3312
332k
      valueKind = VK_RValue;
3313
332k
      type = type.getUnqualifiedType();
3314
332k
      break;
3315
332k
    }
3316
3317
4.75M
    case Decl::Var:
3318
4.75M
    case Decl::VarTemplateSpecialization:
3319
4.75M
    case Decl::VarTemplatePartialSpecialization:
3320
4.75M
    case Decl::Decomposition:
3321
4.76M
    case Decl::OMPCapturedExpr:
3322
      // In C, "extern void blah;" is valid and is an r-value.
3323
4.76M
      if (!getLangOpts().CPlusPlus &&
3324
1.05M
          !type.hasQualifiers() &&
3325
1.02M
          type->isVoidType()) {
3326
9
        valueKind = VK_RValue;
3327
9
        break;
3328
9
      }
3329
4.76M
      LLVM_FALLTHROUGH;
3330
3331
4.77M
    case Decl::ImplicitParam:
3332
12.7M
    case Decl::ParmVar: {
3333
      // These are always l-values.
3334
12.7M
      valueKind = VK_LValue;
3335
12.7M
      type = type.getNonReferenceType();
3336
3337
      // FIXME: Does the addition of const really only apply in
3338
      // potentially-evaluated contexts? Since the variable isn't actually
3339
      // captured in an unevaluated context, it seems that the answer is no.
3340
12.7M
      if (!isUnevaluatedContext()) {
3341
12.6M
        QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3342
12.6M
        if (!CapturedType.isNull())
3343
557k
          type = CapturedType;
3344
12.6M
      }
3345
3346
12.7M
      break;
3347
4.77M
    }
3348
3349
386
    case Decl::Binding: {
3350
      // These are always lvalues.
3351
386
      valueKind = VK_LValue;
3352
386
      type = type.getNonReferenceType();
3353
      // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3354
      // decides how that's supposed to work.
3355
386
      auto *BD = cast<BindingDecl>(VD);
3356
386
      if (BD->getDeclContext() != CurContext) {
3357
17
        auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3358
17
        if (DD && DD->hasLocalStorage())
3359
2
          diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3360
17
      }
3361
386
      break;
3362
4.77M
    }
3363
3364
2.36M
    case Decl::Function: {
3365
2.36M
      if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3366
1.59M
        if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3367
1.58M
          type = Context.BuiltinFnTy;
3368
1.58M
          valueKind = VK_RValue;
3369
1.58M
          break;
3370
1.58M
        }
3371
778k
      }
3372
3373
778k
      const FunctionType *fty = type->castAs<FunctionType>();
3374
3375
      // If we're referring to a function with an __unknown_anytype
3376
      // result type, make the entire expression __unknown_anytype.
3377
778k
      if (fty->getReturnType() == Context.UnknownAnyTy) {
3378
6
        type = Context.UnknownAnyTy;
3379
6
        valueKind = VK_RValue;
3380
6
        break;
3381
6
      }
3382
3383
      // Functions are l-values in C++.
3384
778k
      if (getLangOpts().CPlusPlus) {
3385
33.8k
        valueKind = VK_LValue;
3386
33.8k
        break;
3387
33.8k
      }
3388
3389
      // C99 DR 316 says that, if a function type comes from a
3390
      // function definition (without a prototype), that type is only
3391
      // used for checking compatibility. Therefore, when referencing
3392
      // the function, we pretend that we don't have the full function
3393
      // type.
3394
744k
      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3395
10.3k
          isa<FunctionProtoType>(fty))
3396
93
        type = Context.getFunctionNoProtoType(fty->getReturnType(),
3397
93
                                              fty->getExtInfo());
3398
3399
      // Functions are r-values in C.
3400
744k
      valueKind = VK_RValue;
3401
744k
      break;
3402
744k
    }
3403
3404
0
    case Decl::CXXDeductionGuide:
3405
0
      llvm_unreachable("building reference to deduction guide");
3406
3407
3
    case Decl::MSProperty:
3408
16
    case Decl::MSGuid:
3409
174
    case Decl::TemplateParamObject:
3410
      // FIXME: Should MSGuidDecl and template parameter objects be subject to
3411
      // capture in OpenMP, or duplicated between host and device?
3412
174
      valueKind = VK_LValue;
3413
174
      break;
3414
3415
75.0k
    case Decl::CXXMethod:
3416
      // If we're referring to a method with an __unknown_anytype
3417
      // result type, make the entire expression __unknown_anytype.
3418
      // This should only be possible with a type written directly.
3419
75.0k
      if (const FunctionProtoType *proto
3420
74.9k
            = dyn_cast<FunctionProtoType>(VD->getType()))
3421
74.9k
        if (proto->getReturnType() == Context.UnknownAnyTy) {
3422
0
          type = Context.UnknownAnyTy;
3423
0
          valueKind = VK_RValue;
3424
0
          break;
3425
0
        }
3426
3427
      // C++ methods are l-values if static, r-values if non-static.
3428
75.0k
      if (cast<CXXMethodDecl>(VD)->isStatic()) {
3429
73.4k
        valueKind = VK_LValue;
3430
73.4k
        break;
3431
73.4k
      }
3432
1.56k
      LLVM_FALLTHROUGH;
3433
3434
1.58k
    case Decl::CXXConversion:
3435
1.58k
    case Decl::CXXDestructor:
3436
1.58k
    case Decl::CXXConstructor:
3437
1.58k
      valueKind = VK_RValue;
3438
1.58k
      break;
3439
16.0M
    }
3440
3441
16.0M
    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3442
16.0M
                            /*FIXME: TemplateKWLoc*/ SourceLocation(),
3443
16.0M
                            TemplateArgs);
3444
16.0M
  }
3445
16.0M
}
3446
3447
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3448
14
                                    SmallString<32> &Target) {
3449
14
  Target.resize(CharByteWidth * (Source.size() + 1));
3450
14
  char *ResultPtr = &Target[0];
3451
14
  const llvm::UTF8 *ErrorPtr;
3452
14
  bool success =
3453
14
      llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3454
14
  (void)success;
3455
14
  assert(success);
3456
14
  Target.resize(ResultPtr - &Target[0]);
3457
14
}
3458
3459
ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3460
826
                                     PredefinedExpr::IdentKind IK) {
3461
  // Pick the current block, lambda, captured statement or function.
3462
826
  Decl *currentDecl = nullptr;
3463
826
  if (const BlockScopeInfo *BSI = getCurBlock())
3464
41
    currentDecl = BSI->TheDecl;
3465
785
  else if (const LambdaScopeInfo *LSI = getCurLambda())
3466
13
    currentDecl = LSI->CallOperator;
3467
772
  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3468
23
    currentDecl = CSI->TheCapturedDecl;
3469
749
  else
3470
749
    currentDecl = getCurFunctionOrMethodDecl();
3471
3472
826
  if (!currentDecl) {
3473
5
    Diag(Loc, diag::ext_predef_outside_function);
3474
5
    currentDecl = Context.getTranslationUnitDecl();
3475
5
  }
3476
3477
826
  QualType ResTy;
3478
826
  StringLiteral *SL = nullptr;
3479
826
  if (cast<DeclContext>(currentDecl)->isDependentContext())
3480
68
    ResTy = Context.DependentTy;
3481
758
  else {
3482
    // Pre-defined identifiers are of type char[x], where x is the length of
3483
    // the string.
3484
758
    auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3485
758
    unsigned Length = Str.length();
3486
3487
758
    llvm::APInt LengthI(32, Length + 1);
3488
758
    if (IK == PredefinedExpr::LFunction || 
IK == PredefinedExpr::LFuncSig750
) {
3489
14
      ResTy =
3490
14
          Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3491
14
      SmallString<32> RawChars;
3492
14
      ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3493
14
                              Str, RawChars);
3494
14
      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3495
14
                                           ArrayType::Normal,
3496
14
                                           /*IndexTypeQuals*/ 0);
3497
14
      SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3498
14
                                 /*Pascal*/ false, ResTy, Loc);
3499
744
    } else {
3500
744
      ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3501
744
      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3502
744
                                           ArrayType::Normal,
3503
744
                                           /*IndexTypeQuals*/ 0);
3504
744
      SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3505
744
                                 /*Pascal*/ false, ResTy, Loc);
3506
744
    }
3507
758
  }
3508
3509
826
  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3510
826
}
3511
3512
742
ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3513
742
  PredefinedExpr::IdentKind IK;
3514
3515
742
  switch (Kind) {
3516
0
  default: llvm_unreachable("Unknown simple primary expr!");
3517
300
  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3518
197
  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3519
9
  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3520
13
  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3521
8
  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3522
6
  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3523
209
  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3524
742
  }
3525
3526
742
  return BuildPredefinedExpr(Loc, IK);
3527
742
}
3528
3529
709k
ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3530
709k
  SmallString<16> CharBuffer;
3531
709k
  bool Invalid = false;
3532
709k
  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3533
709k
  if (Invalid)
3534
0
    return ExprError();
3535
3536
709k
  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3537
709k
                            PP, Tok.getKind());
3538
709k
  if (Literal.hadError())
3539
53
    return ExprError();
3540
3541
709k
  QualType Ty;
3542
709k
  if (Literal.isWide())
3543
1.07k
    Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3544
708k
  else if (Literal.isUTF8() && 
getLangOpts().Char8143
)
3545
133
    Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3546
708k
  else if (Literal.isUTF16())
3547
92
    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3548
708k
  else if (Literal.isUTF32())
3549
85
    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3550
708k
  else if (!getLangOpts().CPlusPlus || 
Literal.isMultiChar()99.2k
)
3551
683k
    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3552
24.5k
  else
3553
24.5k
    Ty = Context.CharTy;  // 'x' -> char in C++
3554
3555
709k
  CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3556
709k
  if (Literal.isWide())
3557
1.07k
    Kind = CharacterLiteral::Wide;
3558
708k
  else if (Literal.isUTF16())
3559
92
    Kind = CharacterLiteral::UTF16;
3560
708k
  else if (Literal.isUTF32())
3561
85
    Kind = CharacterLiteral::UTF32;
3562
708k
  else if (Literal.isUTF8())
3563
143
    Kind = CharacterLiteral::UTF8;
3564
3565
709k
  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3566
709k
                                             Tok.getLocation());
3567
3568
709k
  if (Literal.getUDSuffix().empty())
3569
709k
    return Lit;
3570
3571
  // We're building a user-defined literal.
3572
57
  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3573
57
  SourceLocation UDSuffixLoc =
3574
57
    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3575
3576
  // Make sure we're allowed user-defined literals here.
3577
57
  if (!UDLScope)
3578
0
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3579
3580
  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3581
  //   operator "" X (ch)
3582
57
  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3583
57
                                        Lit, Tok.getLocation());
3584
57
}
3585
3586
4.98M
ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3587
4.98M
  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3588
4.98M
  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3589
4.98M
                                Context.IntTy, Loc);
3590
4.98M
}
3591
3592
static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3593
36.2k
                                  QualType Ty, SourceLocation Loc) {
3594
36.2k
  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3595
3596
36.2k
  using llvm::APFloat;
3597
36.2k
  APFloat Val(Format);
3598
3599
36.2k
  APFloat::opStatus result = Literal.GetFloatValue(Val);
3600
3601
  // Overflow is always an error, but underflow is only an error if
3602
  // we underflowed to zero (APFloat reports denormals as underflow).
3603
36.2k
  if ((result & APFloat::opOverflow) ||
3604
36.2k
      ((result & APFloat::opUnderflow) && 
Val.isZero()1.31k
)) {
3605
14
    unsigned diagnostic;
3606
14
    SmallString<20> buffer;
3607
14
    if (result & APFloat::opOverflow) {
3608
8
      diagnostic = diag::warn_float_overflow;
3609
8
      APFloat::getLargest(Format).toString(buffer);
3610
6
    } else {
3611
6
      diagnostic = diag::warn_float_underflow;
3612
6
      APFloat::getSmallest(Format).toString(buffer);
3613
6
    }
3614
3615
14
    S.Diag(Loc, diagnostic)
3616
14
      << Ty
3617
14
      << StringRef(buffer.data(), buffer.size());
3618
14
  }
3619
3620
36.2k
  bool isExact = (result == APFloat::opOK);
3621
36.2k
  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3622
36.2k
}
3623
3624
286
bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3625
286
  assert(E && "Invalid expression");
3626
3627
286
  if (E->isValueDependent())
3628
66
    return false;
3629
3630
220
  QualType QT = E->getType();
3631
220
  if (!QT->isIntegerType() || 
QT->isBooleanType()219
||
QT->isCharType()218
) {
3632
3
    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3633
3
    return true;
3634
3
  }
3635
3636
217
  llvm::APSInt ValueAPS;
3637
217
  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3638
3639
217
  if (R.isInvalid())
3640
1
    return true;
3641
3642
216
  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3643
216
  if (!ValueIsPositive || 
ValueAPS.getActiveBits() > 31202
) {
3644
19
    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3645
19
        << ValueAPS.toString(10) << ValueIsPositive;
3646
19
    return true;
3647
19
  }
3648
3649
197
  return false;
3650
197
}
3651
3652
8.87M
ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3653
  // Fast path for a single digit (which is quite common).  A single digit
3654
  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3655
8.87M
  if (Tok.getLength() == 1) {
3656
3.98M
    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3657
3.98M
    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3658
3.98M
  }
3659
3660
4.89M
  SmallString<128> SpellingBuffer;
3661
  // NumericLiteralParser wants to overread by one character.  Add padding to
3662
  // the buffer in case the token is copied to the buffer.  If getSpelling()
3663
  // returns a StringRef to the memory buffer, it should have a null char at
3664
  // the EOF, so it is also safe.
3665
4.89M
  SpellingBuffer.resize(Tok.getLength() + 1);
3666
3667
  // Get the spelling of the token, which eliminates trigraphs, etc.
3668
4.89M
  bool Invalid = false;
3669
4.89M
  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3670
4.89M
  if (Invalid)
3671
0
    return ExprError();
3672
3673
4.89M
  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3674
4.89M
                               PP.getSourceManager(), PP.getLangOpts(),
3675
4.89M
                               PP.getTargetInfo(), PP.getDiagnostics());
3676
4.89M
  if (Literal.hadError)
3677
148
    return ExprError();
3678
3679
4.89M
  if (Literal.hasUDSuffix()) {
3680
    // We're building a user-defined literal.
3681
211
    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3682
211
    SourceLocation UDSuffixLoc =
3683
211
      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3684
3685
    // Make sure we're allowed user-defined literals here.
3686
211
    if (!UDLScope)
3687
0
      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3688
3689
211
    QualType CookedTy;
3690
211
    if (Literal.isFloatingLiteral()) {
3691
      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3692
      // long double, the literal is treated as a call of the form
3693
      //   operator "" X (f L)
3694
75
      CookedTy = Context.LongDoubleTy;
3695
136
    } else {
3696
      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3697
      // unsigned long long, the literal is treated as a call of the form
3698
      //   operator "" X (n ULL)
3699
136
      CookedTy = Context.UnsignedLongLongTy;
3700
136
    }
3701
3702
211
    DeclarationName OpName =
3703
211
      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3704
211
    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3705
211
    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3706
3707
211
    SourceLocation TokLoc = Tok.getLocation();
3708
3709
    // Perform literal operator lookup to determine if we're building a raw
3710
    // literal or a cooked one.
3711
211
    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3712
211
    switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3713
211
                                  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3714
211
                                  /*AllowStringTemplatePack*/ false,
3715
211
                                  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3716
32
    case LOLR_ErrorNoDiagnostic:
3717
      // Lookup failure for imaginary constants isn't fatal, there's still the
3718
      // GNU extension producing _Complex types.
3719
32
      break;
3720
18
    case LOLR_Error:
3721
18
      return ExprError();
3722
99
    case LOLR_Cooked: {
3723
99
      Expr *Lit;
3724
99
      if (Literal.isFloatingLiteral()) {
3725
33
        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3726
66
      } else {
3727
66
        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3728
66
        if (Literal.GetIntegerValue(ResultVal))
3729
1
          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3730
1
              << /* Unsigned */ 1;
3731
66
        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3732
66
                                     Tok.getLocation());
3733
66
      }
3734
99
      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3735
0
    }
3736
3737
33
    case LOLR_Raw: {
3738
      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3739
      // literal is treated as a call of the form
3740
      //   operator "" X ("n")
3741
33
      unsigned Length = Literal.getUDSuffixOffset();
3742
33
      QualType StrTy = Context.getConstantArrayType(
3743
33
          Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3744
33
          llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3745
33
      Expr *Lit = StringLiteral::Create(
3746
33
          Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3747
33
          /*Pascal*/false, StrTy, &TokLoc, 1);
3748
33
      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3749
0
    }
3750
3751
29
    case LOLR_Template: {
3752
      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3753
      // template), L is treated as a call fo the form
3754
      //   operator "" X <'c1', 'c2', ... 'ck'>()
3755
      // where n is the source character sequence c1 c2 ... ck.
3756
29
      TemplateArgumentListInfo ExplicitArgs;
3757
29
      unsigned CharBits = Context.getIntWidth(Context.CharTy);
3758
29
      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3759
29
      llvm::APSInt Value(CharBits, CharIsUnsigned);
3760
184
      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; 
++I155
) {
3761
155
        Value = TokSpelling[I];
3762
155
        TemplateArgument Arg(Context, Value, Context.CharTy);
3763
155
        TemplateArgumentLocInfo ArgInfo;
3764
155
        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3765
155
      }
3766
29
      return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3767
29
                                      &ExplicitArgs);
3768
0
    }
3769
0
    case LOLR_StringTemplatePack:
3770
0
      llvm_unreachable("unexpected literal operator lookup result");
3771
4.89M
    }
3772
4.89M
  }
3773
3774
4.89M
  Expr *Res;
3775
3776
4.89M
  if (Literal.isFixedPointLiteral()) {
3777
808
    QualType Ty;
3778
3779
808
    if (Literal.isAccum) {
3780
607
      if (Literal.isHalf) {
3781
416
        Ty = Context.ShortAccumTy;
3782
191
      } else if (Literal.isLong) {
3783
51
        Ty = Context.LongAccumTy;
3784
140
      } else {
3785
140
        Ty = Context.AccumTy;
3786
140
      }
3787
201
    } else if (Literal.isFract) {
3788
201
      if (Literal.isHalf) {
3789
63
        Ty = Context.ShortFractTy;
3790
138
      } else if (Literal.isLong) {
3791
59
        Ty = Context.LongFractTy;
3792
79
      } else {
3793
79
        Ty = Context.FractTy;
3794
79
      }
3795
201
    }
3796
3797
808
    if (Literal.isUnsigned) 
Ty = Context.getCorrespondingUnsignedType(Ty)229
;
3798
3799
808
    bool isSigned = !Literal.isUnsigned;
3800
808
    unsigned scale = Context.getFixedPointScale(Ty);
3801
808
    unsigned bit_width = Context.getTypeInfo(Ty).Width;
3802
3803
808
    llvm::APInt Val(bit_width, 0, isSigned);
3804
808
    bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3805
808
    bool ValIsZero = Val.isNullValue() && 
!Overflowed55
;
3806
3807
808
    auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3808
808
    if (Literal.isFract && 
Val == MaxVal + 1201
&&
!ValIsZero36
)
3809
      // Clause 6.4.4 - The value of a constant shall be in the range of
3810
      // representable values for its type, with exception for constants of a
3811
      // fract type with a value of exactly 1; such a constant shall denote
3812
      // the maximal value for the type.
3813
32
      --Val;
3814
776
    else if (Val.ugt(MaxVal) || 
Overflowed761
)
3815
31
      Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3816
3817
808
    Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3818
808
                                              Tok.getLocation(), scale);
3819
4.89M
  } else if (Literal.isFloatingLiteral()) {
3820
36.2k
    QualType Ty;
3821
36.2k
    if (Literal.isHalf){
3822
16
      if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3823
10
        Ty = Context.HalfTy;
3824
6
      else {
3825
6
        Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3826
6
        return ExprError();
3827
6
      }
3828
36.2k
    } else if (Literal.isFloat)
3829
6.80k
      Ty = Context.FloatTy;
3830
29.4k
    else if (Literal.isLong)
3831
3.17k
      Ty = Context.LongDoubleTy;
3832
26.2k
    else if (Literal.isFloat16)
3833
141
      Ty = Context.Float16Ty;
3834
26.1k
    else if (Literal.isFloat128)
3835
172
      Ty = Context.Float128Ty;
3836
25.9k
    else
3837
25.9k
      Ty = Context.DoubleTy;
3838
3839
36.2k
    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3840
3841
36.2k
    if (Ty == Context.DoubleTy) {
3842
25.9k
      if (getLangOpts().SinglePrecisionConstants) {
3843
2
        if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3844
2
          Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3845
2
        }
3846
25.9k
      } else if (getLangOpts().OpenCL &&
3847
113
                 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3848
        // Impose single-precision float type when cl_khr_fp64 is not enabled.
3849
20
        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3850
20
        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3851
20
      }
3852
25.9k
    }
3853
4.85M
  } else if (!Literal.isIntegerLiteral()) {
3854
0
    return ExprError();
3855
4.85M
  } else {
3856
4.85M
    QualType Ty;
3857
3858
    // 'long long' is a C99 or C++11 feature.
3859
4.85M
    if (!getLangOpts().C99 && 
Literal.isLongLong847k
) {
3860
23.7k
      if (getLangOpts().CPlusPlus)
3861
23.7k
        Diag(Tok.getLocation(),
3862
23.7k
             getLangOpts().CPlusPlus11 ?
3863
23.7k
             diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong38
);
3864
9
      else
3865
9
        Diag(Tok.getLocation(), diag::ext_c99_longlong);
3866
23.7k
    }
3867
3868
    // Get the value in the widest-possible width.
3869
4.85M
    unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3870
4.85M
    llvm::APInt ResultVal(MaxWidth, 0);
3871
3872
4.85M
    if (Literal.GetIntegerValue(ResultVal)) {
3873
      // If this value didn't fit into uintmax_t, error and force to ull.
3874
3
      Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3875
3
          << /* Unsigned */ 1;
3876
3
      Ty = Context.UnsignedLongLongTy;
3877
3
      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3878
3
             "long long is not intmax_t?");
3879
4.85M
    } else {
3880
      // If this value fits into a ULL, try to figure out what else it fits into
3881
      // according to the rules of C99 6.4.4.1p5.
3882
3883
      // Octal, Hexadecimal, and integers with a U suffix are allowed to
3884
      // be an unsigned int.
3885
4.85M
      bool AllowUnsigned = Literal.isUnsigned || 
Literal.getRadix() != 104.72M
;
3886
3887
      // Check from smallest to largest, picking the smallest type we can.
3888
4.85M
      unsigned Width = 0;
3889
3890
      // Microsoft specific integer suffixes are explicitly sized.
3891
4.85M
      if (Literal.MicrosoftInteger) {
3892
47
        if (Literal.MicrosoftInteger == 8 && 
!Literal.isUnsigned9
) {
3893
5
          Width = 8;
3894
5
          Ty = Context.CharTy;
3895
42
        } else {
3896
42
          Width = Literal.MicrosoftInteger;
3897
42
          Ty = Context.getIntTypeForBitwidth(Width,
3898
42
                                             /*Signed=*/!Literal.isUnsigned);
3899
42
        }
3900
47
      }
3901
3902
4.85M
      if (Ty.isNull() && 
!Literal.isLong4.85M
&&
!Literal.isLongLong4.68M
) {
3903
        // Are int/unsigned possibilities?
3904
4.64M
        unsigned IntSize = Context.getTargetInfo().getIntWidth();
3905
3906
        // Does it fit in a unsigned int?
3907
4.64M
        if (ResultVal.isIntN(IntSize)) {
3908
          // Does it fit in a signed int?
3909
4.63M
          if (!Literal.isUnsigned && 
ResultVal[IntSize-1] == 04.61M
)
3910
4.57M
            Ty = Context.IntTy;
3911
63.5k
          else if (AllowUnsigned)
3912
63.4k
            Ty = Context.UnsignedIntTy;
3913
4.63M
          Width = IntSize;
3914
4.63M
        }
3915
4.64M
      }
3916
3917
      // Are long/unsigned long possibilities?
3918
4.85M
      if (Ty.isNull() && 
!Literal.isLongLong215k
) {
3919
168k
        unsigned LongSize = Context.getTargetInfo().getLongWidth();
3920
3921
        // Does it fit in a unsigned long?
3922
168k
        if (ResultVal.isIntN(LongSize)) {
3923
          // Does it fit in a signed long?
3924
168k
          if (!Literal.isUnsigned && 
ResultVal[LongSize-1] == 093.0k
)
3925
92.8k
            Ty = Context.LongTy;
3926
75.2k
          else if (AllowUnsigned)
3927
75.0k
            Ty = Context.UnsignedLongTy;
3928
          // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3929
          // is compatible.
3930
132
          else if (!getLangOpts().C99 && 
!getLangOpts().CPlusPlus1147
) {
3931
18
            const unsigned LongLongSize =
3932
18
                Context.getTargetInfo().getLongLongWidth();
3933
18
            Diag(Tok.getLocation(),
3934
18
                 getLangOpts().CPlusPlus
3935
6
                     ? Literal.isLong
3936
4
                           ? diag::warn_old_implicitly_unsigned_long_cxx
3937
2
                           : /*C++98 UB*/ diag::
3938
2
                                 ext_old_implicitly_unsigned_long_cxx
3939
12
                     : diag::warn_old_implicitly_unsigned_long)
3940
9
                << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3941
9
                                            : /*will be ill-formed*/ 1);
3942
18
            Ty = Context.UnsignedLongTy;
3943
18
          }
3944
168k
          Width = LongSize;
3945
168k
        }
3946
168k
      }
3947
3948
      // Check long long if needed.
3949
4.85M
      if (Ty.isNull()) {
3950
47.9k
        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3951
3952
        // Does it fit in a unsigned long long?
3953
47.9k
        if (ResultVal.isIntN(LongLongSize)) {
3954
          // Does it fit in a signed long long?
3955
          // To be compatible with MSVC, hex integer literals ending with the
3956
          // LL or i64 suffix are always signed in Microsoft mode.
3957
47.9k
          if (!Literal.isUnsigned && 
(20.6k
ResultVal[LongLongSize-1] == 020.6k
||
3958
45
              (getLangOpts().MSVCCompat && 
Literal.isLongLong2
)))
3959
20.6k
            Ty = Context.LongLongTy;
3960
27.3k
          else if (AllowUnsigned)
3961
27.3k
            Ty = Context.UnsignedLongLongTy;
3962
47.9k
          Width = LongLongSize;
3963
47.9k
        }
3964
47.9k
      }
3965
3966
      // If we still couldn't decide a type, we probably have something that
3967
      // does not fit in a signed long long, but has no U suffix.
3968
4.85M
      if (Ty.isNull()) {
3969
16
        Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3970
16
        Ty = Context.UnsignedLongLongTy;
3971
16
        Width = Context.getTargetInfo().getLongLongWidth();
3972
16
      }
3973
3974
4.85M
      if (ResultVal.getBitWidth() != Width)
3975
4.63M
        ResultVal = ResultVal.trunc(Width);
3976
4.85M
    }
3977
4.85M
    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3978
4.85M
  }
3979
3980
  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3981
4.89M
  if (Literal.isImaginary) {
3982
398
    Res = new (Context) ImaginaryLiteral(Res,
3983
398
                                        Context.getComplexType(Res->getType()));
3984
3985
398
    Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3986
398
  }
3987
4.89M
  return Res;
3988
4.89M
}
3989
3990
2.34M
ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3991
2.34M
  assert(E && "ActOnParenExpr() missing expr");
3992
2.34M
  return new (Context) ParenExpr(L, R, E);
3993
2.34M
}
3994
3995
static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3996
                                         SourceLocation Loc,
3997
45
                                         SourceRange ArgRange) {
3998
  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3999
  // scalar or vector data type argument..."
4000
  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4001
  // type (C99 6.2.5p18) or void.
4002
45
  if (!(T->isArithmeticType() || 
T->isVoidType()43
||
T->isVectorType()42
)) {
4003
3
    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4004
3
      << T << ArgRange;
4005
3
    return true;
4006
3
  }
4007
4008
42
  assert((T->isVoidType() || !T->isIncompleteType()) &&
4009
42
         "Scalar types should always be complete");
4010
42
  return false;
4011
42
}
4012
4013
static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4014
                                           SourceLocation Loc,
4015
                                           SourceRange ArgRange,
4016
74.1k
                                           UnaryExprOrTypeTrait TraitKind) {
4017
  // Invalid types must be hard errors for SFINAE in C++.
4018
74.1k
  if (S.LangOpts.CPlusPlus)
4019
59.9k
    return true;
4020
4021
  // C99 6.5.3.4p1:
4022
14.2k
  if (T->isFunctionType() &&
4023
11
      (TraitKind == UETT_SizeOf || 
TraitKind == UETT_AlignOf1
||
4024
11
       
TraitKind == UETT_PreferredAlignOf1
)) {
4025
    // sizeof(function)/alignof(function) is allowed as an extension.
4026
11
    S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4027
11
        << getTraitSpelling(TraitKind) << ArgRange;
4028
11
    return false;
4029
11
  }
4030
4031
  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4032
  // this is an error (OpenCL v1.1 s6.3.k)
4033
14.2k
  if (T->isVoidType()) {
4034
1
    unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4035
10
                                        : diag::ext_sizeof_alignof_void_type;
4036
11
    S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4037
11
    return false;
4038
11
  }
4039
4040
14.1k
  return true;
4041
14.1k
}
4042
4043
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4044
                                             SourceLocation Loc,
4045
                                             SourceRange ArgRange,
4046
73.9k
                                             UnaryExprOrTypeTrait TraitKind) {
4047
  // Reject sizeof(interface) and sizeof(interface<proto>) if the
4048
  // runtime doesn't allow it.
4049
73.9k
  if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && 
T->isObjCObjectType()73.9k
) {
4050
3
    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4051
3
      << T << (TraitKind == UETT_SizeOf)
4052
3
      << ArgRange;
4053
3
    return true;
4054
3
  }
4055
4056
73.9k
  return false;
4057
73.9k
}
4058
4059
/// Check whether E is a pointer from a decayed array type (the decayed
4060
/// pointer type is equal to T) and emit a warning if it is.
4061
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4062
180
                                     Expr *E) {
4063
  // Don't warn if the operation changed the type.
4064
180
  if (T != E->getType())
4065
63
    return;
4066
4067
  // Now look for array decays.
4068
117
  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4069
117
  if (!ICE || 
ICE->getCastKind() != CK_ArrayToPointerDecay45
)
4070
108
    return;
4071
4072
9
  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4073
9
                                             << ICE->getType()
4074
9
                                             << ICE->getSubExpr()->getType();
4075
9
}
4076
4077
/// Check the constraints on expression operands to unary type expression
4078
/// and type traits.
4079
///
4080
/// Completes any types necessary and validates the constraints on the operand
4081
/// expression. The logic mostly mirrors the type-based overload, but may modify
4082
/// the expression as it completes the type for that expression through template
4083
/// instantiation, etc.
4084
bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4085
10.7k
                                            UnaryExprOrTypeTrait ExprKind) {
4086
10.7k
  QualType ExprTy = E->getType();
4087
10.7k
  assert(!ExprTy->isReferenceType());
4088
4089
10.7k
  bool IsUnevaluatedOperand =
4090
10.7k
      (ExprKind == UETT_SizeOf || 
ExprKind == UETT_AlignOf175
||
4091
141
       ExprKind == UETT_PreferredAlignOf || 
ExprKind == UETT_VecStep36
);
4092
10.7k
  if (IsUnevaluatedOperand) {
4093
10.7k
    ExprResult Result = CheckUnevaluatedOperand(E);
4094
10.7k
    if (Result.isInvalid())
4095
0
      return true;
4096
10.7k
    E = Result.get();
4097
10.7k
  }
4098
4099
  // The operand for sizeof and alignof is in an unevaluated expression context,
4100
  // so side effects could result in unintended consequences.
4101
  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4102
  // used to build SFINAE gadgets.
4103
  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4104
10.7k
  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4105
6.71k
      !E->isInstantiationDependent() &&
4106
4.49k
      E->HasSideEffects(Context, false))
4107
46
    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4108
4109
10.7k
  if (ExprKind == UETT_VecStep)
4110
36
    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4111
36
                                        E->getSourceRange());
4112
4113
  // Explicitly list some types as extensions.
4114
10.7k
  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4115
10.7k
                                      E->getSourceRange(), ExprKind))
4116
6
    return false;
4117
4118
  // 'alignof' applied to an expression only requires the base element type of
4119
  // the expression to be complete. 'sizeof' requires the expression's type to
4120
  // be complete (and will attempt to complete it if it's an array of unknown
4121
  // bound).
4122
10.7k
  if (ExprKind == UETT_AlignOf || 
ExprKind == UETT_PreferredAlignOf10.6k
) {
4123
137
    if (RequireCompleteSizedType(
4124
137
            E->getExprLoc(), Context.getBaseElementType(E->getType()),
4125
137
            diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4126
137
            getTraitSpelling(ExprKind), E->getSourceRange()))
4127
12
      return true;
4128
10.5k
  } else {
4129
10.5k
    if (RequireCompleteSizedExprType(
4130
10.5k
            E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4131
10.5k
            getTraitSpelling(ExprKind), E->getSourceRange()))
4132
47
      return true;
4133
10.6k
  }
4134
4135
  // Completing the expression's type may have changed it.
4136
10.6k
  ExprTy = E->getType();
4137
10.6k
  assert(!ExprTy->isReferenceType());
4138
4139
10.6k
  if (ExprTy->isFunctionType()) {
4140
2
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4141
2
        << getTraitSpelling(ExprKind) << E->getSourceRange();
4142
2
    return true;
4143
2
  }
4144
4145
10.6k
  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4146
10.6k
                                       E->getSourceRange(), ExprKind))
4147
0
    return true;
4148
4149
10.6k
  if (ExprKind == UETT_SizeOf) {
4150
10.5k
    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4151
6.25k
      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4152
1.11k
        QualType OType = PVD->getOriginalType();
4153
1.11k
        QualType Type = PVD->getType();
4154
1.11k
        if (Type->isPointerType() && 
OType->isArrayType()123
) {
4155
5
          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4156
5
            << Type << OType;
4157
5
          Diag(PVD->getLocation(), diag::note_declared_at);
4158
5
        }
4159
1.11k
      }
4160
6.25k
    }
4161
4162
    // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4163
    // decays into a pointer and returns an unintended result. This is most
4164
    // likely a typo for "sizeof(array) op x".
4165
10.5k
    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4166
90
      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4167
90
                               BO->getLHS());
4168
90
      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4169
90
                               BO->getRHS());
4170
90
    }
4171
10.5k
  }
4172
4173
10.6k
  return false;
4174
10.6k
}
4175
4176
/// Check the constraints on operands to unary expression and type
4177
/// traits.
4178
///
4179
/// This will complete any types necessary, and validate the various constraints
4180
/// on those operands.
4181
///
4182
/// The UsualUnaryConversions() function is *not* called by this routine.
4183
/// C99 6.3.2.1p[2-4] all state:
4184
///   Except when it is the operand of the sizeof operator ...
4185
///
4186
/// C++ [expr.sizeof]p4
4187
///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4188
///   standard conversions are not applied to the operand of sizeof.
4189
///
4190
/// This policy is followed for all of the unary trait expressions.
4191
bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4192
                                            SourceLocation OpLoc,
4193
                                            SourceRange ExprRange,
4194
63.4k
                                            UnaryExprOrTypeTrait ExprKind) {
4195
63.4k
  if (ExprType->isDependentType())
4196
0
    return false;
4197
4198
  // C++ [expr.sizeof]p2:
4199
  //     When applied to a reference or a reference type, the result
4200
  //     is the size of the referenced type.
4201
  // C++11 [expr.alignof]p3:
4202
  //     When alignof is applied to a reference type, the result
4203
  //     shall be the alignment of the referenced type.
4204
63.4k
  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4205
34
    ExprType = Ref->getPointeeType();
4206
4207
  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4208
  //   When alignof or _Alignof is applied to an array type, the result
4209
  //   is the alignment of the element type.
4210
63.4k
  if (ExprKind == UETT_AlignOf || 
ExprKind == UETT_PreferredAlignOf60.7k
||
4211
55.8k
      ExprKind == UETT_OpenMPRequiredSimdAlign)
4212
7.64k
    ExprType = Context.getBaseElementType(ExprType);
4213
4214
63.4k
  if (ExprKind == UETT_VecStep)
4215
9
    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4216
4217
  // Explicitly list some types as extensions.
4218
63.4k
  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4219
63.4k
                                      ExprKind))
4220
16
    return false;
4221
4222
63.4k
  if (RequireCompleteSizedType(
4223
63.4k
          OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4224
63.4k
          getTraitSpelling(ExprKind), ExprRange))
4225
107
    return true;
4226
4227
63.3k
  if (ExprType->isFunctionType()) {
4228
8
    Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4229
8
        << getTraitSpelling(ExprKind) << ExprRange;
4230
8
    return true;
4231
8
  }
4232
4233
63.3k
  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4234
63.3k
                                       ExprKind))
4235
3
    return true;
4236
4237
63.2k
  return false;
4238
63.2k
}
4239
4240
172
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4241
  // Cannot know anything else if the expression is dependent.
4242
172
  if (E->isTypeDependent())
4243
0
    return false;
4244
4245
172
  if (E->getObjectKind() == OK_BitField) {
4246
1
    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4247
1
       << 1 << E->getSourceRange();
4248
1
    return true;
4249
1
  }
4250
4251
171
  ValueDecl *D = nullptr;
4252
171
  Expr *Inner = E->IgnoreParens();
4253
171
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4254
105
    D = DRE->getDecl();
4255
66
  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4256
30
    D = ME->getMemberDecl();
4257
30
  }
4258
4259
  // If it's a field, require the containing struct to have a
4260
  // complete definition so that we can compute the layout.
4261
  //
4262
  // This can happen in C++11 onwards, either by naming the member
4263
  // in a way that is not transformed into a member access expression
4264
  // (in an unevaluated operand, for instance), or by naming the member
4265
  // in a trailing-return-type.
4266
  //
4267
  // For the record, since __alignof__ on expressions is a GCC
4268
  // extension, GCC seems to permit this but always gives the
4269
  // nonsensical answer 0.
4270
  //
4271
  // We don't really need the layout here --- we could instead just
4272
  // directly check for all the appropriate alignment-lowing
4273
  // attributes --- but that would require duplicating a lot of
4274
  // logic that just isn't worth duplicating for such a marginal
4275
  // use-case.
4276
171
  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4277
    // Fast path this check, since we at least know the record has a
4278
    // definition if we can find a member of it.
4279
36
    if (!FD->getParent()->isCompleteDefinition()) {
4280
3
      S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4281
3
        << E->getSourceRange();
4282
3
      return true;
4283
3
    }
4284
4285
    // Otherwise, if it's a field, and the field doesn't have
4286
    // reference type, then it must have a complete type (or be a
4287
    // flexible array member, which we explicitly want to
4288
    // white-list anyway), which makes the following checks trivial.
4289
33
    if (!FD->getType()->isReferenceType())
4290
29
      return false;
4291
139
  }
4292
4293
139
  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4294
139
}
4295
4296
36
bool Sema::CheckVecStepExpr(Expr *E) {
4297
36
  E = E->IgnoreParens();
4298
4299
  // Cannot know anything else if the expression is dependent.
4300
36
  if (E->isTypeDependent())
4301
0
    return false;
4302
4303
36
  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4304
36
}
4305
4306
static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4307
18.2k
                                        CapturingScopeInfo *CSI) {
4308
18.2k
  assert(T->isVariablyModifiedType());
4309
18.2k
  assert(CSI != nullptr);
4310
4311
  // We're going to walk down into the type and look for VLA expressions.
4312
26.0k
  do {
4313
26.0k
    const Type *Ty = T.getTypePtr();
4314
26.0k
    switch (Ty->getTypeClass()) {
4315
0
#define TYPE(Class, Base)
4316
0
#define ABSTRACT_TYPE(Class, Base)
4317
0
#define NON_CANONICAL_TYPE(Class, Base)
4318
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4319
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4320
0
#include "clang/AST/TypeNodes.inc"
4321
0
      T = QualType();
4322
0
      break;
4323
    // These types are never variably-modified.
4324
0
    case Type::Builtin:
4325
0
    case Type::Complex:
4326
0
    case Type::Vector:
4327
0
    case Type::ExtVector:
4328
0
    case Type::ConstantMatrix:
4329
0
    case Type::Record:
4330
0
    case Type::Enum:
4331
0
    case Type::Elaborated:
4332
0
    case Type::TemplateSpecialization:
4333
0
    case Type::ObjCObject:
4334
0
    case Type::ObjCInterface:
4335
0
    case Type::ObjCObjectPointer:
4336
0
    case Type::ObjCTypeParam:
4337
0
    case Type::Pipe:
4338
0
    case Type::ExtInt:
4339
0
      llvm_unreachable("type class is never variably-modified!");
4340
0
    case Type::Adjusted:
4341
0
      T = cast<AdjustedType>(Ty)->getOriginalType();
4342
0
      break;
4343
0
    case Type::Decayed:
4344
0
      T = cast<DecayedType>(Ty)->getPointeeType();
4345
0
      break;
4346
35
    case Type::Pointer:
4347
35
      T = cast<PointerType>(Ty)->getPointeeType();
4348
35
      break;
4349
0
    case Type::BlockPointer:
4350
0
      T = cast<BlockPointerType>(Ty)->getPointeeType();
4351
0
      break;
4352
0
    case Type::LValueReference:
4353
0
    case Type::RValueReference:
4354
0
      T = cast<ReferenceType>(Ty)->getPointeeType();
4355
0
      break;
4356
0
    case Type::MemberPointer:
4357
0
      T = cast<MemberPointerType>(Ty)->getPointeeType();
4358
0
      break;
4359
0
    case Type::ConstantArray:
4360
0
    case Type::IncompleteArray:
4361
      // Losing element qualification here is fine.
4362
0
      T = cast<ArrayType>(Ty)->getElementType();
4363
0
      break;
4364
25.9k
    case Type::VariableArray: {
4365
      // Losing element qualification here is fine.
4366
25.9k
      const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4367
4368
      // Unknown size indication requires no size computation.
4369
      // Otherwise, evaluate and record it.
4370
25.9k
      auto Size = VAT->getSizeExpr();
4371
25.9k
      if (Size && !CSI->isVLATypeCaptured(VAT) &&
4372
8.82k
          (isa<CapturedRegionScopeInfo>(CSI) || 
isa<LambdaScopeInfo>(CSI)52
))
4373
8.82k
        CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4374
4375
25.9k
      T = VAT->getElementType();
4376
25.9k
      break;
4377
0
    }
4378
0
    case Type::FunctionProto:
4379
0
    case Type::FunctionNoProto:
4380
0
      T = cast<FunctionType>(Ty)->getReturnType();
4381
0
      break;
4382
32
    case Type::Paren:
4383
32
    case Type::TypeOf:
4384
32
    case Type::UnaryTransform:
4385
32
    case Type::Attributed:
4386
32
    case Type::SubstTemplateTypeParm:
4387
32
    case Type::MacroQualified:
4388
      // Keep walking after single level desugaring.
4389
32
      T = T.getSingleStepDesugaredType(Context);
4390
32
      break;
4391
46
    case Type::Typedef:
4392
46
      T = cast<TypedefType>(Ty)->desugar();
4393
46
      break;
4394
0
    case Type::Decltype:
4395
0
      T = cast<DecltypeType>(Ty)->desugar();
4396
0
      break;
4397
0
    case Type::Auto:
4398
0
    case Type::DeducedTemplateSpecialization:
4399
0
      T = cast<DeducedType>(Ty)->getDeducedType();
4400
0
      break;
4401
0
    case Type::TypeOfExpr:
4402
0
      T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4403
0
      break;
4404
0
    case Type::Atomic:
4405
0
      T = cast<AtomicType>(Ty)->getValueType();
4406
0
      break;
4407
26.0k
    }
4408
26.0k
  } while (!T.isNull() && T->isVariablyModifiedType());
4409
18.2k
}
4410
4411
/// Build a sizeof or alignof expression given a type operand.
4412
ExprResult
4413
Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4414
                                     SourceLocation OpLoc,
4415
                                     UnaryExprOrTypeTrait ExprKind,
4416
98.7k
                                     SourceRange R) {
4417
98.7k
  if (!TInfo)
4418
0
    return ExprError();
4419
4420
98.7k
  QualType T = TInfo->getType();
4421
4422
98.7k
  if (!T->isDependentType() &&
4423
63.4k
      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4424
120
    return ExprError();
4425
4426
98.6k
  if (T->isVariablyModifiedType() && 
FunctionScopes.size() > 147
) {
4427
12
    if (auto *TT = T->getAs<TypedefType>()) {
4428
6
      for (auto I = FunctionScopes.rbegin(),
4429
6
                E = std::prev(FunctionScopes.rend());
4430
12
           I != E; 
++I6
) {
4431
10
        auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4432
10
        if (CSI == nullptr)
4433
0
          break;
4434
10
        DeclContext *DC = nullptr;
4435
10
        if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4436
10
          DC = LSI->CallOperator;
4437
0
        else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4438
0
          DC = CRSI->TheCapturedDecl;
4439
0
        else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4440
0
          DC = BSI->TheDecl;
4441
10
        if (DC) {
4442
10
          if (DC->containsDecl(TT->getDecl()))
4443
4
            break;
4444
6
          captureVariablyModifiedType(Context, T, CSI);
4445
6
        }
4446
10
      }
4447
6
    }
4448
12
  }
4449
4450
  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4451
98.6k
  return new (Context) UnaryExprOrTypeTraitExpr(
4452
98.6k
      ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4453
98.6k
}
4454
4455
/// Build a sizeof or alignof expression given an expression
4456
/// operand.
4457
ExprResult
4458
Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4459
17.8k
                                     UnaryExprOrTypeTrait ExprKind) {
4460
17.8k
  ExprResult PE = CheckPlaceholderExpr(E);
4461
17.8k
  if (PE.isInvalid())
4462
2
    return ExprError();
4463
4464
17.8k
  E = PE.get();
4465
4466
  // Verify that the operand is valid.
4467
17.8k
  bool isInvalid = false;
4468
17.8k
  if (E->isTypeDependent()) {
4469
    // Delay type-checking for type-dependent expressions.
4470
10.8k
  } else if (ExprKind == UETT_AlignOf || 
ExprKind == UETT_PreferredAlignOf10.7k
) {
4471
172
    isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4472
10.6k
  } else if (ExprKind == UETT_VecStep) {
4473
36
    isInvalid = CheckVecStepExpr(E);
4474
10.5k
  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4475
1
      Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4476
1
      isInvalid = true;
4477
10.5k
  } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4478
9
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4479
9
    isInvalid = true;
4480
10.5k
  } else {
4481
10.5k
    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4482
10.5k
  }
4483
4484
17.8k
  if (isInvalid)
4485
76
    return ExprError();
4486
4487
17.8k
  if (ExprKind == UETT_SizeOf && 
E->getType()->isVariableArrayType()17.6k
) {
4488
377
    PE = TransformToPotentiallyEvaluated(E);
4489
377
    if (PE.isInvalid()) 
return ExprError()0
;
4490
377
    E = PE.get();
4491
377
  }
4492
4493
  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4494
17.8k
  return new (Context) UnaryExprOrTypeTraitExpr(
4495
17.8k
      ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4496
17.8k
}
4497
4498
/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4499
/// expr and the same for @c alignof and @c __alignof
4500
/// Note that the ArgRange is invalid if isType is false.
4501
ExprResult
4502
Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4503
                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
4504
85.0k
                                    void *TyOrEx, SourceRange ArgRange) {
4505
  // If error parsing type, ignore.
4506
85.0k
  if (!TyOrEx) 
return ExprError()35
;
4507
4508
85.0k
  if (IsType) {
4509
71.4k
    TypeSourceInfo *TInfo;
4510
71.4k
    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4511
71.4k
    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4512
71.4k
  }
4513
4514
13.5k
  Expr *ArgEx = (Expr *)TyOrEx;
4515
13.5k
  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4516
13.5k
  return Result;
4517
13.5k
}
4518
4519
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4520
423
                                     bool IsReal) {
4521
423
  if (V.get()->isTypeDependent())
4522
0
    return S.Context.DependentTy;
4523
4524
  // _Real and _Imag are only l-values for normal l-values.
4525
423
  if (V.get()->getObjectKind() != OK_Ordinary) {
4526
0
    V = S.DefaultLvalueConversion(V.get());
4527
0
    if (V.isInvalid())
4528
0
      return QualType();
4529
423
  }
4530
4531
  // These operators return the element type of a complex type.
4532
423
  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4533
318
    return CT->getElementType();
4534
4535
  // Otherwise they pass through real integer and floating point types here.
4536
105
  if (V.get()->getType()->isArithmeticType())
4537
88
    return V.get()->getType();
4538
4539
  // Test for placeholders.
4540
17
  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4541
17
  if (PR.isInvalid()) 
return QualType()0
;
4542
17
  if (PR.get() != V.get()) {
4543
0
    V = PR;
4544
0
    return CheckRealImagOperand(S, V, Loc, IsReal);
4545
0
  }
4546
4547
  // Reject anything else.
4548
17
  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4549
9
    << (IsReal ? "__real" : 
"__imag"8
);
4550
17
  return QualType();
4551
17
}
4552
4553
4554
4555
ExprResult
4556
Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4557
42.1k
                          tok::TokenKind Kind, Expr *Input) {
4558
42.1k
  UnaryOperatorKind Opc;
4559
42.1k
  switch (Kind) {
4560
0
  default: llvm_unreachable("Unknown unary op!");
4561
40.7k
  case tok::plusplus:   Opc = UO_PostInc; break;
4562
1.35k
  case tok::minusminus: Opc = UO_PostDec; break;
4563
42.1k
  }
4564
4565
  // Since this might is a postfix expression, get rid of ParenListExprs.
4566
42.1k
  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4567
42.1k
  if (Result.isInvalid()) 
return ExprError()0
;
4568
42.1k
  Input = Result.get();
4569
4570
42.1k
  return BuildUnaryOp(S, OpLoc, Opc, Input);
4571
42.1k
}
4572
4573
/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4574
///
4575
/// \return true on error
4576
static bool checkArithmeticOnObjCPointer(Sema &S,
4577
                                         SourceLocation opLoc,
4578
16
                                         Expr *op) {
4579
16
  assert(op->getType()->isObjCObjectPointerType());
4580
16
  if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4581
11
      !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4582
11
    return false;
4583
4584
5
  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4585
5
    << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4586
5
    << op->getSourceRange();
4587
5
  return true;
4588
5
}
4589
4590
159
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4591
159
  auto *BaseNoParens = Base->IgnoreParens();
4592
159
  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4593
76
    return MSProp->getPropertyDecl()->getType()->isArrayType();
4594
83
  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4595
83
}
4596
4597
ExprResult
4598
Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4599
318k
                              Expr *idx, SourceLocation rbLoc) {
4600
318k
  if (base && !base->getType().isNull() &&
4601
318k
      base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4602
192
    return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4603
192
                                    SourceLocation(), /*Length*/ nullptr,
4604
192
                                    /*Stride=*/nullptr, rbLoc);
4605
4606
  // Since this might be a postfix expression, get rid of ParenListExprs.
4607
318k
  if (isa<ParenListExpr>(base)) {
4608
739
    ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4609
739
    if (result.isInvalid()) 
return ExprError()0
;
4610
739
    base = result.get();
4611
739
  }
4612
4613
  // Check if base and idx form a MatrixSubscriptExpr.
4614
  //
4615
  // Helper to check for comma expressions, which are not allowed as indices for
4616
  // matrix subscript expressions.
4617
318k
  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4618
187
    if (isa<BinaryOperator>(E) && 
cast<BinaryOperator>(E)->isCommaOp()9
) {
4619
2
      Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4620
2
          << SourceRange(base->getBeginLoc(), rbLoc);
4621
2
      return true;
4622
2
    }
4623
185
    return false;
4624
185
  };
4625
  // The matrix subscript operator ([][])is considered a single operator.
4626
  // Separating the index expressions by parenthesis is not allowed.
4627
318k
  if (base->getType()->isSpecificPlaceholderType(
4628
318k
          BuiltinType::IncompleteMatrixIdx) &&
4629
89
      !isa<MatrixSubscriptExpr>(base)) {
4630
2
    Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4631
2
        << SourceRange(base->getBeginLoc(), rbLoc);
4632
2
    return ExprError();
4633
2
  }
4634
  // If the base is a MatrixSubscriptExpr, try to create a new
4635
  // MatrixSubscriptExpr.
4636
318k
  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4637
318k
  if (matSubscriptE) {
4638
87
    if (CheckAndReportCommaError(idx))
4639
0
      return ExprError();
4640
4641
87
    assert(matSubscriptE->isIncomplete() &&
4642
87
           "base has to be an incomplete matrix subscript");
4643
87
    return CreateBuiltinMatrixSubscriptExpr(
4644
87
        matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4645
87
  }
4646
4647
  // Handle any non-overload placeholder types in the base and index
4648
  // expressions.  We can't handle overloads here because the other
4649
  // operand might be an overloadable type, in which case the overload
4650
  // resolution for the operator overload should get the first crack
4651
  // at the overload.
4652
318k
  bool IsMSPropertySubscript = false;
4653
318k
  if (base->getType()->isNonOverloadPlaceholderType()) {
4654
159
    IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4655
159
    if (!IsMSPropertySubscript) {
4656
13
      ExprResult result = CheckPlaceholderExpr(base);
4657
13
      if (result.isInvalid())
4658
0
        return ExprError();
4659
13
      base = result.get();
4660
13
    }
4661
159
  }
4662
4663
  // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4664
318k
  if (base->getType()->isMatrixType()) {
4665
100
    if (CheckAndReportCommaError(idx))
4666
2
      return ExprError();
4667
4668
98
    return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4669
98
  }
4670
4671
  // A comma-expression as the index is deprecated in C++2a onwards.
4672
318k
  if (getLangOpts().CPlusPlus20 &&
4673
624
      ((isa<BinaryOperator>(idx) && 
cast<BinaryOperator>(idx)->isCommaOp()5
) ||
4674
622
       (isa<CXXOperatorCallExpr>(idx) &&
4675
4
        
cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma2
))) {
4676
4
    Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4677
4
        << SourceRange(base->getBeginLoc(), rbLoc);
4678
4
  }
4679
4680
318k
  if (idx->getType()->isNonOverloadPlaceholderType()) {
4681
22
    ExprResult result = CheckPlaceholderExpr(idx);
4682
22
    if (result.isInvalid()) 
return ExprError()0
;
4683
22
    idx = result.get();
4684
22
  }
4685
4686
  // Build an unanalyzed expression if either operand is type-dependent.
4687
318k
  if (getLangOpts().CPlusPlus &&
4688
230k
      (base->isTypeDependent() || 
idx->isTypeDependent()167k
)) {
4689
63.3k
    return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4690
63.3k
                                            VK_LValue, OK_Ordinary, rbLoc);
4691
63.3k
  }
4692
4693
  // MSDN, property (C++)
4694
  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4695
  // This attribute can also be used in the declaration of an empty array in a
4696
  // class or structure definition. For example:
4697
  // __declspec(property(get=GetX, put=PutX)) int x[];
4698
  // The above statement indicates that x[] can be used with one or more array
4699
  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4700
  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4701
255k
  if (IsMSPropertySubscript) {
4702
    // Build MS property subscript expression if base is MS property reference
4703
    // or MS property subscript.
4704
146
    return new (Context) MSPropertySubscriptExpr(
4705
146
        base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4706
146
  }
4707
4708
  // Use C++ overloaded-operator rules if either operand has record
4709
  // type.  The spec says to do this if either type is *overloadable*,
4710
  // but enum types can't declare subscript operators or conversion
4711
  // operators, so there's nothing interesting for overload resolution
4712
  // to do if there aren't any record types involved.
4713
  //
4714
  // ObjC pointers have their own subscripting logic that is not tied
4715
  // to overload resolution and so should not take this path.
4716
255k
  if (getLangOpts().CPlusPlus &&
4717
166k
      (base->getType()->isRecordType() ||
4718
164k
       (!base->getType()->isObjCObjectPointerType() &&
4719
164k
        idx->getType()->isRecordType()))) {
4720
2.54k
    return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4721
2.54k
  }
4722
4723
252k
  ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4724
4725
252k
  if (!Res.isInvalid() && 
isa<ArraySubscriptExpr>(Res.get())252k
)
4726
252k
    CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4727
4728
252k
  return Res;
4729
252k
}
4730
4731
363
ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4732
363
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4733
363
  InitializationKind Kind =
4734
363
      InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4735
363
  InitializationSequence InitSeq(*this, Entity, Kind, E);
4736
363
  return InitSeq.Perform(*this, Entity, Kind, E);
4737
363
}
4738
4739
ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4740
                                                  Expr *ColumnIdx,
4741
188
                                                  SourceLocation RBLoc) {
4742
188
  ExprResult BaseR = CheckPlaceholderExpr(Base);
4743
188
  if (BaseR.isInvalid())
4744
0
    return BaseR;
4745
188
  Base = BaseR.get();
4746
4747
188
  ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4748
188
  if (RowR.isInvalid())
4749
0
    return RowR;
4750
188
  RowIdx = RowR.get();
4751
4752
188
  if (!ColumnIdx)
4753
98
    return new (Context) MatrixSubscriptExpr(
4754
98
        Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4755
4756
  // Build an unanalyzed expression if any of the operands is type-dependent.
4757
90
  if (Base->isTypeDependent() || 
RowIdx->isTypeDependent()89
||
4758
88
      ColumnIdx->isTypeDependent())
4759
2
    return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4760
2
                                             Context.DependentTy, RBLoc);
4761
4762
88
  ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4763
88
  if (ColumnR.isInvalid())
4764
0
    return ColumnR;
4765
88
  ColumnIdx = ColumnR.get();
4766
4767
  // Check that IndexExpr is an integer expression. If it is a constant
4768
  // expression, check that it is less than Dim (= the number of elements in the
4769
  // corresponding dimension).
4770
88
  auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4771
176
                          bool IsColumnIdx) -> Expr * {
4772
176
    if (!IndexExpr->getType()->isIntegerType() &&
4773
26
        !IndexExpr->isTypeDependent()) {
4774
26
      Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4775
26
          << IsColumnIdx;
4776
26
      return nullptr;
4777
26
    }
4778
4779
150
    if (Optional<llvm::APSInt> Idx =
4780
116
            IndexExpr->getIntegerConstantExpr(Context)) {
4781
116
      if ((*Idx < 0 || 
*Idx >= Dim108
)) {
4782
29
        Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4783
29
            << IsColumnIdx << Dim;
4784
29
        return nullptr;
4785
29
      }
4786
121
    }
4787
4788
121
    ExprResult ConvExpr =
4789
121
        tryConvertExprToType(IndexExpr, Context.getSizeType());
4790
121
    assert(!ConvExpr.isInvalid() &&
4791
121
           "should be able to convert any integer type to size type");
4792
121
    return ConvExpr.get();
4793
121
  };
4794
4795
88
  auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4796
88
  RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4797
88
  ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4798
88
  if (!RowIdx || 
!ColumnIdx59
)
4799
45
    return ExprError();
4800
4801
43
  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4802
43
                                           MTy->getElementType(), RBLoc);
4803
43
}
4804
4805
139k
void Sema::CheckAddressOfNoDeref(const Expr *E) {
4806
139k
  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4807
139k
  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4808
4809
  // For expressions like `&(*s).b`, the base is recorded and what should be
4810
  // checked.
4811
139k
  const MemberExpr *Member = nullptr;
4812
144k
  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && 
!Member->isArrow()24.8k
)
4813
5.15k
    StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4814
4815
139k
  LastRecord.PossibleDerefs.erase(StrippedExpr);
4816
139k
}
4817
4818
252k
void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4819
252k
  if (isUnevaluatedContext())
4820
221
    return;
4821
4822
251k
  QualType ResultTy = E->getType();
4823
251k
  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4824
4825
  // Bail if the element is an array since it is not memory access.
4826
251k
  if (isa<ArrayType>(ResultTy))
4827
3.71k
    return;
4828
4829
248k
  if (ResultTy->hasAttr(attr::NoDeref)) {
4830
9
    LastRecord.PossibleDerefs.insert(E);
4831
9
    return;
4832
9
  }
4833
4834
  // Check if the base type is a pointer to a member access of a struct
4835
  // marked with noderef.
4836
248k
  const Expr *Base = E->getBase();
4837
248k
  QualType BaseTy = Base->getType();
4838
248k
  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4839
    // Not a pointer access
4840
55.7k
    return;
4841
4842
192k
  const MemberExpr *Member = nullptr;
4843
198k
  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4844
45.0k
         Member->isArrow())
4845
5.62k
    Base = Member->getBase();
4846
4847
192k
  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4848
192k
    if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4849
2
      LastRecord.PossibleDerefs.insert(E);
4850
192k
  }
4851
192k
}
4852
4853
ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4854
                                          Expr *LowerBound,
4855
                                          SourceLocation ColonLocFirst,
4856
                                          SourceLocation ColonLocSecond,
4857
                                          Expr *Length, Expr *Stride,
4858
13.5k
                                          SourceLocation RBLoc) {
4859
13.5k
  if (Base->getType()->isPlaceholderType() &&
4860
2.90k
      !Base->getType()->isSpecificPlaceholderType(
4861
0
          BuiltinType::OMPArraySection)) {
4862
0
    ExprResult Result = CheckPlaceholderExpr(Base);
4863
0
    if (Result.isInvalid())
4864
0
      return ExprError();
4865
0
    Base = Result.get();
4866
0
  }
4867
13.5k
  if (LowerBound && 
LowerBound->getType()->isNonOverloadPlaceholderType()5.57k
) {
4868
70
    ExprResult Result = CheckPlaceholderExpr(LowerBound);
4869
70
    if (Result.isInvalid())
4870
70
      return ExprError();
4871
0
    Result = DefaultLvalueConversion(Result.get());
4872
0
    if (Result.isInvalid())
4873
0
      return ExprError();
4874
0
    LowerBound = Result.get();
4875
0
  }
4876
13.5k
  if (Length && 
Length->getType()->isNonOverloadPlaceholderType()10.3k
) {
4877
0
    ExprResult Result = CheckPlaceholderExpr(Length);
4878
0
    if (Result.isInvalid())
4879
0
      return ExprError();
4880
0
    Result = DefaultLvalueConversion(Result.get());
4881
0
    if (Result.isInvalid())
4882
0
      return ExprError();
4883
0
    Length = Result.get();
4884
0
  }
4885
13.5k
  if (Stride && 
Stride->getType()->isNonOverloadPlaceholderType()224
) {
4886
0
    ExprResult Result = CheckPlaceholderExpr(Stride);
4887
0
    if (Result.isInvalid())
4888
0
      return ExprError();
4889
0
    Result = DefaultLvalueConversion(Result.get());
4890
0
    if (Result.isInvalid())
4891
0
      return ExprError();
4892
0
    Stride = Result.get();
4893
0
  }
4894
4895
  // Build an unanalyzed expression if either operand is type-dependent.
4896
13.5k
  if (Base->isTypeDependent() ||
4897
11.6k
      (LowerBound &&
4898
4.87k
       (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4899
11.6k
      (Length && 
(8.90k
Length->isTypeDependent()8.90k
||
Length->isValueDependent()8.90k
)) ||
4900
11.6k
      (Stride && 
(216
Stride->isTypeDependent()216
||
Stride->isValueDependent()216
))) {
4901
1.88k
    return new (Context) OMPArraySectionExpr(
4902
1.88k
        Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4903
1.88k
        OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4904
1.88k
  }
4905
4906
  // Perform default conversions.
4907
11.6k
  QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4908
11.6k
  QualType ResultTy;
4909
11.6k
  if (OriginalTy->isAnyPointerType()) {
4910
3.79k
    ResultTy = OriginalTy->getPointeeType();
4911
7.82k
  } else if (OriginalTy->isArrayType()) {
4912
7.58k
    ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4913
240
  } else {
4914
240
    return ExprError(
4915
240
        Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4916
240
        << Base->getSourceRange());
4917
240
  }
4918
  // C99 6.5.2.1p1
4919
11.3k
  if (LowerBound) {
4920
4.68k
    auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4921
4.68k
                                                      LowerBound);
4922
4.68k
    if