Coverage Report

Created: 2019-02-21 13:17

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Sema/SemaInternal.h
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
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 provides common API and #includes for the internal
10
// implementation of Sema.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
15
#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
16
17
#include "clang/AST/ASTContext.h"
18
#include "clang/Sema/Lookup.h"
19
#include "clang/Sema/Sema.h"
20
#include "clang/Sema/SemaDiagnostic.h"
21
22
namespace clang {
23
24
1.43M
inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
25
1.43M
  return PartialDiagnostic(DiagID, Context.getDiagAllocator());
26
1.43M
}
27
28
inline bool
29
4.69M
FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
30
4.69M
  return FTI.NumParams == 1 && 
!FTI.isVariadic2.00M
&&
31
4.69M
         
FTI.Params[0].Ident == nullptr1.99M
&&
FTI.Params[0].Param810k
&&
32
4.69M
         
cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()810k
;
33
4.69M
}
34
35
inline bool
36
5.64M
FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
37
5.64M
  // Assume FTI is well-formed.
38
5.64M
  return FTI.NumParams && 
!FTIHasSingleVoidParameter(FTI)4.69M
;
39
5.64M
}
40
41
// This requires the variable to be non-dependent and the initializer
42
// to not be value dependent.
43
8.63M
inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) {
44
8.63M
  const VarDecl *DefVD = nullptr;
45
8.63M
  return !isa<ParmVarDecl>(Var) &&
46
8.63M
    
Var->isUsableInConstantExpressions(Context)4.20M
&&
47
8.63M
    
Var->getAnyInitializer(DefVD)1.07M
&&
DefVD->checkInitIsICE()1.06M
;
48
8.63M
}
49
50
// Helper function to check whether D's attributes match current CUDA mode.
51
// Decls with mismatched attributes and related diagnostics may have to be
52
// ignored during this CUDA compilation pass.
53
23.0k
inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
54
23.0k
  if (!LangOpts.CUDA || 
!D28
)
55
22.9k
    return true;
56
28
  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
57
28
                          
D->hasAttr<CUDASharedAttr>()12
||
58
28
                          
D->hasAttr<CUDAGlobalAttr>()10
;
59
28
  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
60
28
}
61
62
// Directly mark a variable odr-used. Given a choice, prefer to use
63
// MarkVariableReferenced since it does additional checks and then
64
// calls MarkVarDeclODRUsed.
65
// If the variable must be captured:
66
//  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
67
//  - else capture it in the DeclContext that maps to the
68
//    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
69
inline void MarkVarDeclODRUsed(VarDecl *Var,
70
    SourceLocation Loc, Sema &SemaRef,
71
7.73M
    const unsigned *const FunctionScopeIndexToStopAt) {
72
7.73M
  // Keep track of used but undefined variables.
73
7.73M
  // FIXME: We shouldn't suppress this warning for static data members.
74
7.73M
  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
75
7.73M
      
(151k
!Var->isExternallyVisible()151k
||
Var->isInline()151k
||
76
151k
       
SemaRef.isExternalWithNoLinkageType(Var)151k
) &&
77
7.73M
      
!(146
Var->isStaticDataMember()146
&&
Var->hasInit()76
)) {
78
114
    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
79
114
    if (old.isInvalid())
80
87
      old = Loc;
81
114
  }
82
7.73M
  QualType CaptureType, DeclRefType;
83
7.73M
  SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
84
7.73M
    /*EllipsisLoc*/ SourceLocation(),
85
7.73M
    /*BuildAndDiagnose*/ true,
86
7.73M
    CaptureType, DeclRefType,
87
7.73M
    FunctionScopeIndexToStopAt);
88
7.73M
89
7.73M
  Var->markUsed(SemaRef.Context);
90
7.73M
}
91
92
/// Return a DLL attribute from the declaration.
93
12.2M
inline InheritableAttr *getDLLAttr(Decl *D) {
94
12.2M
  assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
95
12.2M
         "A declaration cannot be both dllimport and dllexport.");
96
12.2M
  if (auto *Import = D->getAttr<DLLImportAttr>())
97
5.53k
    return Import;
98
12.2M
  if (auto *Export = D->getAttr<DLLExportAttr>())
99
6.38k
    return Export;
100
12.2M
  return nullptr;
101
12.2M
}
102
103
/// Retrieve the depth and index of a template parameter.
104
119k
inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
105
119k
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
106
40.3k
    return std::make_pair(TTP->getDepth(), TTP->getIndex());
107
79.0k
108
79.0k
  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
109
78.9k
    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
110
131
111
131
  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
112
131
  return std::make_pair(TTP->getDepth(), TTP->getIndex());
113
131
}
114
115
/// Retrieve the depth and index of an unexpanded parameter pack.
116
inline std::pair<unsigned, unsigned>
117
73.6k
getDepthAndIndex(UnexpandedParameterPack UPP) {
118
73.6k
  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
119
69.3k
    return std::make_pair(TTP->getDepth(), TTP->getIndex());
120
4.28k
121
4.28k
  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
122
4.28k
}
123
124
class TypoCorrectionConsumer : public VisibleDeclConsumer {
125
  typedef SmallVector<TypoCorrection, 1> TypoResultList;
126
  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
127
  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
128
129
public:
130
  TypoCorrectionConsumer(Sema &SemaRef,
131
                         const DeclarationNameInfo &TypoName,
132
                         Sema::LookupNameKind LookupKind,
133
                         Scope *S, CXXScopeSpec *SS,
134
                         std::unique_ptr<CorrectionCandidateCallback> CCC,
135
                         DeclContext *MemberContext,
136
                         bool EnteringContext)
137
      : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
138
        SavedTCIndex(0), SemaRef(SemaRef), S(S),
139
        SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
140
        CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
141
        Result(SemaRef, TypoName, LookupKind),
142
        Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
143
3.61k
        EnteringContext(EnteringContext), SearchNamespaces(false) {
144
3.61k
    Result.suppressDiagnostics();
145
3.61k
    // Arrange for ValidatedCorrections[0] to always be an empty correction.
146
3.61k
    ValidatedCorrections.push_back(TypoCorrection());
147
3.61k
  }
148
149
603
  bool includeHiddenDecls() const override { return true; }
150
151
  // Methods for adding potential corrections to the consumer.
152
  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
153
                 bool InBaseClass) override;
154
  void FoundName(StringRef Name);
155
  void addKeywordResult(StringRef Keyword);
156
  void addCorrection(TypoCorrection Correction);
157
158
3.45k
  bool empty() const {
159
3.45k
    return CorrectionResults.empty() && 
ValidatedCorrections.size() == 1112
;
160
3.45k
  }
161
162
  /// Return the list of TypoCorrections for the given identifier from
163
  /// the set of corrections that have the closest edit distance, if any.
164
0
  TypoResultList &operator[](StringRef Name) {
165
0
    return CorrectionResults.begin()->second[Name];
166
0
  }
167
168
  /// Return the edit distance of the corrections that have the
169
  /// closest/best edit distance from the original typop.
170
3.34k
  unsigned getBestEditDistance(bool Normalized) {
171
3.34k
    if (CorrectionResults.empty())
172
0
      return (std::numeric_limits<unsigned>::max)();
173
3.34k
174
3.34k
    unsigned BestED = CorrectionResults.begin()->first;
175
3.34k
    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : 
BestED0
;
176
3.34k
  }
177
178
  /// Set-up method to add to the consumer the set of namespaces to use
179
  /// in performing corrections to nested name specifiers. This method also
180
  /// implicitly adds all of the known classes in the current AST context to the
181
  /// to the consumer for correcting nested name specifiers.
182
  void
183
  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
184
185
  /// Return the next typo correction that passes all internal filters
186
  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
187
  /// starting with the corrections that have the closest edit distance. An
188
  /// empty TypoCorrection is returned once no more viable corrections remain
189
  /// in the consumer.
190
  const TypoCorrection &getNextCorrection();
191
192
  /// Get the last correction returned by getNextCorrection().
193
1.09k
  const TypoCorrection &getCurrentCorrection() {
194
1.09k
    return CurrentTCIndex < ValidatedCorrections.size()
195
1.09k
               ? ValidatedCorrections[CurrentTCIndex]
196
1.09k
               : 
ValidatedCorrections[0]0
; // The empty correction.
197
1.09k
  }
198
199
  /// Return the next typo correction like getNextCorrection, but keep
200
  /// the internal state pointed to the current correction (i.e. the next time
201
  /// getNextCorrection is called, it will return the same correction returned
202
  /// by peekNextcorrection).
203
512
  const TypoCorrection &peekNextCorrection() {
204
512
    auto Current = CurrentTCIndex;
205
512
    const TypoCorrection &TC = getNextCorrection();
206
512
    CurrentTCIndex = Current;
207
512
    return TC;
208
512
  }
209
210
  /// Reset the consumer's position in the stream of viable corrections
211
  /// (i.e. getNextCorrection() will return each of the previously returned
212
  /// corrections in order before returning any new corrections).
213
1.45k
  void resetCorrectionStream() {
214
1.45k
    CurrentTCIndex = 0;
215
1.45k
  }
216
217
  /// Return whether the end of the stream of corrections has been
218
  /// reached.
219
918
  bool finished() {
220
918
    return CorrectionResults.empty() &&
221
918
           
CurrentTCIndex >= ValidatedCorrections.size()825
;
222
918
  }
223
224
  /// Save the current position in the correction stream (overwriting any
225
  /// previously saved position).
226
40
  void saveCurrentPosition() {
227
40
    SavedTCIndex = CurrentTCIndex;
228
40
  }
229
230
  /// Restore the saved position in the correction stream.
231
4
  void restoreSavedPosition() {
232
4
    CurrentTCIndex = SavedTCIndex;
233
4
  }
234
235
0
  ASTContext &getContext() const { return SemaRef.Context; }
236
806
  const LookupResult &getLookupResult() const { return Result; }
237
238
64
  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
239
403
  const CXXScopeSpec *getSS() const { return SS.get(); }
240
17
  Scope *getScope() const { return S; }
241
86
  CorrectionCandidateCallback *getCorrectionValidator() const {
242
86
    return CorrectionValidator.get();
243
86
  }
244
245
private:
246
  class NamespaceSpecifierSet {
247
    struct SpecifierInfo {
248
      DeclContext* DeclCtx;
249
      NestedNameSpecifier* NameSpecifier;
250
      unsigned EditDistance;
251
    };
252
253
    typedef SmallVector<DeclContext*, 4> DeclContextList;
254
    typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
255
256
    ASTContext &Context;
257
    DeclContextList CurContextChain;
258
    std::string CurNameSpecifier;
259
    SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
260
    SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
261
262
    std::map<unsigned, SpecifierInfoList> DistanceMap;
263
264
    /// Helper for building the list of DeclContexts between the current
265
    /// context and the top of the translation unit
266
    static DeclContextList buildContextChain(DeclContext *Start);
267
268
    unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
269
                                      NestedNameSpecifier *&NNS);
270
271
   public:
272
    NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
273
                          CXXScopeSpec *CurScopeSpec);
274
275
    /// Add the DeclContext (a namespace or record) to the set, computing
276
    /// the corresponding NestedNameSpecifier and its distance in the process.
277
    void addNameSpecifier(DeclContext *Ctx);
278
279
    /// Provides flat iteration over specifiers, sorted by distance.
280
    class iterator
281
        : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
282
                                            SpecifierInfo> {
283
      /// Always points to the last element in the distance map.
284
      const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
285
      /// Iterator on the distance map.
286
      std::map<unsigned, SpecifierInfoList>::iterator Outer;
287
      /// Iterator on an element in the distance map.
288
      SpecifierInfoList::iterator Inner;
289
290
    public:
291
      iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
292
          : OuterBack(std::prev(Set.DistanceMap.end())),
293
            Outer(Set.DistanceMap.begin()),
294
6.07k
            Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
295
6.07k
        assert(!Set.DistanceMap.empty());
296
6.07k
      }
297
298
86.3k
      iterator &operator++() {
299
86.3k
        ++Inner;
300
86.3k
        if (Inner == Outer->second.end() && 
Outer != OuterBack5.57k
) {
301
2.54k
          ++Outer;
302
2.54k
          Inner = Outer->second.begin();
303
2.54k
        }
304
86.3k
        return *this;
305
86.3k
      }
306
307
86.3k
      SpecifierInfo &operator*() { return *Inner; }
308
89.3k
      bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
309
    };
310
311
3.03k
    iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
312
3.03k
    iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
313
  };
314
315
  void addName(StringRef Name, NamedDecl *ND,
316
               NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
317
318
  /// Find any visible decls for the given typo correction candidate.
319
  /// If none are found, it to the set of candidates for which qualified lookups
320
  /// will be performed to find possible nested name specifier changes.
321
  bool resolveCorrection(TypoCorrection &Candidate);
322
323
  /// Perform qualified lookups on the queued set of typo correction
324
  /// candidates and add the nested name specifier changes to each candidate if
325
  /// a lookup succeeds (at which point the candidate will be returned to the
326
  /// main pool of potential corrections).
327
  void performQualifiedLookups();
328
329
  /// The name written that is a typo in the source.
330
  IdentifierInfo *Typo;
331
332
  /// The results found that have the smallest edit distance
333
  /// found (so far) with the typo name.
334
  ///
335
  /// The pointer value being set to the current DeclContext indicates
336
  /// whether there is a keyword with this name.
337
  TypoEditDistanceMap CorrectionResults;
338
339
  SmallVector<TypoCorrection, 4> ValidatedCorrections;
340
  size_t CurrentTCIndex;
341
  size_t SavedTCIndex;
342
343
  Sema &SemaRef;
344
  Scope *S;
345
  std::unique_ptr<CXXScopeSpec> SS;
346
  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
347
  DeclContext *MemberContext;
348
  LookupResult Result;
349
  NamespaceSpecifierSet Namespaces;
350
  SmallVector<TypoCorrection, 2> QualifiedResults;
351
  bool EnteringContext;
352
  bool SearchNamespaces;
353
};
354
355
1.10k
inline Sema::TypoExprState::TypoExprState() {}
356
357
2.23k
inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
358
2.23k
  *this = std::move(other);
359
2.23k
}
360
361
inline Sema::TypoExprState &Sema::TypoExprState::
362
2.28k
operator=(Sema::TypoExprState &&other) noexcept {
363
2.28k
  Consumer = std::move(other.Consumer);
364
2.28k
  DiagHandler = std::move(other.DiagHandler);
365
2.28k
  RecoveryHandler = std::move(other.RecoveryHandler);
366
2.28k
  return *this;
367
2.28k
}
368
369
} // end namespace clang
370
371
#endif