Coverage Report

Created: 2021-08-24 07:12

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