Coverage Report

Created: 2020-09-19 12:23

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