Coverage Report

Created: 2019-07-24 05:18

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