PreprocessingRecord.h revision dc84cd5efdd3430efb22546b4ac656aa0540b210
1//===--- PreprocessingRecord.h - Record of Preprocessing --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the PreprocessingRecord class, which maintains a record
11//  of what occurred during preprocessing.
12//
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_CLANG_LEX_PREPROCESSINGRECORD_H
15#define LLVM_CLANG_LEX_PREPROCESSINGRECORD_H
16
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/Lex/PPCallbacks.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/Support/Allocator.h"
24#include "llvm/Support/Compiler.h"
25#include <vector>
26
27namespace clang {
28  class IdentifierInfo;
29  class PreprocessingRecord;
30}
31
32/// \brief Allocates memory within a Clang preprocessing record.
33void* operator new(size_t bytes, clang::PreprocessingRecord& PR,
34                   unsigned alignment = 8) throw();
35
36/// \brief Frees memory allocated in a Clang preprocessing record.
37void operator delete(void* ptr, clang::PreprocessingRecord& PR,
38                     unsigned) throw();
39
40namespace clang {
41  class MacroDefinition;
42  class FileEntry;
43
44  /// \brief Base class that describes a preprocessed entity, which may be a
45  /// preprocessor directive or macro expansion.
46  class PreprocessedEntity {
47  public:
48    /// \brief The kind of preprocessed entity an object describes.
49    enum EntityKind {
50      /// \brief Indicates a problem trying to load the preprocessed entity.
51      InvalidKind,
52
53      /// \brief A macro expansion.
54      MacroExpansionKind,
55
56      /// \defgroup Preprocessing directives
57      /// @{
58
59      /// \brief A macro definition.
60      MacroDefinitionKind,
61
62      /// \brief An inclusion directive, such as \c \#include, \c
63      /// \#import, or \c \#include_next.
64      InclusionDirectiveKind,
65
66      /// @}
67
68      FirstPreprocessingDirective = MacroDefinitionKind,
69      LastPreprocessingDirective = InclusionDirectiveKind
70    };
71
72  private:
73    /// \brief The kind of preprocessed entity that this object describes.
74    EntityKind Kind;
75
76    /// \brief The source range that covers this preprocessed entity.
77    SourceRange Range;
78
79  protected:
80    PreprocessedEntity(EntityKind Kind, SourceRange Range)
81      : Kind(Kind), Range(Range) { }
82
83    friend class PreprocessingRecord;
84
85  public:
86    /// \brief Retrieve the kind of preprocessed entity stored in this object.
87    EntityKind getKind() const { return Kind; }
88
89    /// \brief Retrieve the source range that covers this entire preprocessed
90    /// entity.
91    SourceRange getSourceRange() const LLVM_READONLY { return Range; }
92
93    /// \brief Returns true if there was a problem loading the preprocessed
94    /// entity.
95    bool isInvalid() const { return Kind == InvalidKind; }
96
97    // Only allow allocation of preprocessed entities using the allocator
98    // in PreprocessingRecord or by doing a placement new.
99    void* operator new(size_t bytes, PreprocessingRecord& PR,
100                       unsigned alignment = 8) throw() {
101      return ::operator new(bytes, PR, alignment);
102    }
103
104    void* operator new(size_t bytes, void* mem) throw() {
105      return mem;
106    }
107
108    void operator delete(void* ptr, PreprocessingRecord& PR,
109                         unsigned alignment) throw() {
110      return ::operator delete(ptr, PR, alignment);
111    }
112
113    void operator delete(void*, std::size_t) throw() { }
114    void operator delete(void*, void*) throw() { }
115
116  private:
117    // Make vanilla 'new' and 'delete' illegal for preprocessed entities.
118    void* operator new(size_t bytes) throw();
119    void operator delete(void* data) throw();
120  };
121
122  /// \brief Records the presence of a preprocessor directive.
123  class PreprocessingDirective : public PreprocessedEntity {
124  public:
125    PreprocessingDirective(EntityKind Kind, SourceRange Range)
126      : PreprocessedEntity(Kind, Range) { }
127
128    // Implement isa/cast/dyncast/etc.
129    static bool classof(const PreprocessedEntity *PD) {
130      return PD->getKind() >= FirstPreprocessingDirective &&
131             PD->getKind() <= LastPreprocessingDirective;
132    }
133  };
134
135  /// \brief Record the location of a macro definition.
136  class MacroDefinition : public PreprocessingDirective {
137    /// \brief The name of the macro being defined.
138    const IdentifierInfo *Name;
139
140  public:
141    explicit MacroDefinition(const IdentifierInfo *Name, SourceRange Range)
142      : PreprocessingDirective(MacroDefinitionKind, Range), Name(Name) { }
143
144    /// \brief Retrieve the name of the macro being defined.
145    const IdentifierInfo *getName() const { return Name; }
146
147    /// \brief Retrieve the location of the macro name in the definition.
148    SourceLocation getLocation() const { return getSourceRange().getBegin(); }
149
150    // Implement isa/cast/dyncast/etc.
151    static bool classof(const PreprocessedEntity *PE) {
152      return PE->getKind() == MacroDefinitionKind;
153    }
154  };
155
156  /// \brief Records the location of a macro expansion.
157  class MacroExpansion : public PreprocessedEntity {
158    /// \brief The definition of this macro or the name of the macro if it is
159    /// a builtin macro.
160    llvm::PointerUnion<IdentifierInfo *, MacroDefinition *> NameOrDef;
161
162  public:
163    MacroExpansion(IdentifierInfo *BuiltinName, SourceRange Range)
164      : PreprocessedEntity(MacroExpansionKind, Range),
165        NameOrDef(BuiltinName) { }
166
167    MacroExpansion(MacroDefinition *Definition, SourceRange Range)
168      : PreprocessedEntity(MacroExpansionKind, Range),
169        NameOrDef(Definition) { }
170
171    /// \brief True if it is a builtin macro.
172    bool isBuiltinMacro() const { return NameOrDef.is<IdentifierInfo *>(); }
173
174    /// \brief The name of the macro being expanded.
175    const IdentifierInfo *getName() const {
176      if (MacroDefinition *Def = getDefinition())
177        return Def->getName();
178      return NameOrDef.get<IdentifierInfo*>();
179    }
180
181    /// \brief The definition of the macro being expanded. May return null if
182    /// this is a builtin macro.
183    MacroDefinition *getDefinition() const {
184      return NameOrDef.dyn_cast<MacroDefinition *>();
185    }
186
187    // Implement isa/cast/dyncast/etc.
188    static bool classof(const PreprocessedEntity *PE) {
189      return PE->getKind() == MacroExpansionKind;
190    }
191  };
192
193  /// \brief Record the location of an inclusion directive, such as an
194  /// \c \#include or \c \#import statement.
195  class InclusionDirective : public PreprocessingDirective {
196  public:
197    /// \brief The kind of inclusion directives known to the
198    /// preprocessor.
199    enum InclusionKind {
200      /// \brief An \c \#include directive.
201      Include,
202      /// \brief An Objective-C \c \#import directive.
203      Import,
204      /// \brief A GNU \c \#include_next directive.
205      IncludeNext,
206      /// \brief A Clang \c \#__include_macros directive.
207      IncludeMacros
208    };
209
210  private:
211    /// \brief The name of the file that was included, as written in
212    /// the source.
213    StringRef FileName;
214
215    /// \brief Whether the file name was in quotation marks; otherwise, it was
216    /// in angle brackets.
217    unsigned InQuotes : 1;
218
219    /// \brief The kind of inclusion directive we have.
220    ///
221    /// This is a value of type InclusionKind.
222    unsigned Kind : 2;
223
224    /// \brief Whether the inclusion directive was automatically turned into
225    /// a module import.
226    unsigned ImportedModule : 1;
227
228    /// \brief The file that was included.
229    const FileEntry *File;
230
231  public:
232    InclusionDirective(PreprocessingRecord &PPRec,
233                       InclusionKind Kind, StringRef FileName,
234                       bool InQuotes, bool ImportedModule,
235                       const FileEntry *File, SourceRange Range);
236
237    /// \brief Determine what kind of inclusion directive this is.
238    InclusionKind getKind() const { return static_cast<InclusionKind>(Kind); }
239
240    /// \brief Retrieve the included file name as it was written in the source.
241    StringRef getFileName() const { return FileName; }
242
243    /// \brief Determine whether the included file name was written in quotes;
244    /// otherwise, it was written in angle brackets.
245    bool wasInQuotes() const { return InQuotes; }
246
247    /// \brief Determine whether the inclusion directive was automatically
248    /// turned into a module import.
249    bool importedModule() const { return ImportedModule; }
250
251    /// \brief Retrieve the file entry for the actual file that was included
252    /// by this directive.
253    const FileEntry *getFile() const { return File; }
254
255    // Implement isa/cast/dyncast/etc.
256    static bool classof(const PreprocessedEntity *PE) {
257      return PE->getKind() == InclusionDirectiveKind;
258    }
259  };
260
261  /// \brief An abstract class that should be subclassed by any external source
262  /// of preprocessing record entries.
263  class ExternalPreprocessingRecordSource {
264  public:
265    virtual ~ExternalPreprocessingRecordSource();
266
267    /// \brief Read a preallocated preprocessed entity from the external source.
268    ///
269    /// \returns null if an error occurred that prevented the preprocessed
270    /// entity from being loaded.
271    virtual PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) = 0;
272
273    /// \brief Returns a pair of [Begin, End) indices of preallocated
274    /// preprocessed entities that \p Range encompasses.
275    virtual std::pair<unsigned, unsigned>
276        findPreprocessedEntitiesInRange(SourceRange Range) = 0;
277
278    /// \brief Optionally returns true or false if the preallocated preprocessed
279    /// entity with index \p Index came from file \p FID.
280    virtual Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
281                                                        FileID FID) {
282      return Optional<bool>();
283    }
284  };
285
286  /// \brief A record of the steps taken while preprocessing a source file,
287  /// including the various preprocessing directives processed, macros
288  /// expanded, etc.
289  class PreprocessingRecord : public PPCallbacks {
290    SourceManager &SourceMgr;
291
292    /// \brief Allocator used to store preprocessing objects.
293    llvm::BumpPtrAllocator BumpAlloc;
294
295    /// \brief The set of preprocessed entities in this record, in order they
296    /// were seen.
297    std::vector<PreprocessedEntity *> PreprocessedEntities;
298
299    /// \brief The set of preprocessed entities in this record that have been
300    /// loaded from external sources.
301    ///
302    /// The entries in this vector are loaded lazily from the external source,
303    /// and are referenced by the iterator using negative indices.
304    std::vector<PreprocessedEntity *> LoadedPreprocessedEntities;
305
306    /// \brief Global (loaded or local) ID for a preprocessed entity.
307    /// Negative values are used to indicate preprocessed entities
308    /// loaded from the external source while non-negative values are used to
309    /// indicate preprocessed entities introduced by the current preprocessor.
310    /// Value -1 corresponds to element 0 in the loaded entities vector,
311    /// value -2 corresponds to element 1 in the loaded entities vector, etc.
312    /// Value 0 is an invalid value, the index to local entities is 1-based,
313    /// value 1 corresponds to element 0 in the local entities vector,
314    /// value 2 corresponds to element 1 in the local entities vector, etc.
315    class PPEntityID {
316      int ID;
317      explicit PPEntityID(int ID) : ID(ID) {}
318      friend class PreprocessingRecord;
319    public:
320      PPEntityID() : ID(0) {}
321    };
322
323    static PPEntityID getPPEntityID(unsigned Index, bool isLoaded) {
324      return isLoaded ? PPEntityID(-int(Index)-1) : PPEntityID(Index+1);
325    }
326
327    /// \brief Mapping from MacroInfo structures to their definitions.
328    llvm::DenseMap<const MacroInfo *, PPEntityID> MacroDefinitions;
329
330    /// \brief External source of preprocessed entities.
331    ExternalPreprocessingRecordSource *ExternalSource;
332
333    /// \brief Retrieve the preprocessed entity at the given ID.
334    PreprocessedEntity *getPreprocessedEntity(PPEntityID PPID);
335
336    /// \brief Retrieve the loaded preprocessed entity at the given index.
337    PreprocessedEntity *getLoadedPreprocessedEntity(unsigned Index);
338
339    /// \brief Determine the number of preprocessed entities that were
340    /// loaded (or can be loaded) from an external source.
341    unsigned getNumLoadedPreprocessedEntities() const {
342      return LoadedPreprocessedEntities.size();
343    }
344
345    /// \brief Returns a pair of [Begin, End) indices of local preprocessed
346    /// entities that \p Range encompasses.
347    std::pair<unsigned, unsigned>
348      findLocalPreprocessedEntitiesInRange(SourceRange Range) const;
349    unsigned findBeginLocalPreprocessedEntity(SourceLocation Loc) const;
350    unsigned findEndLocalPreprocessedEntity(SourceLocation Loc) const;
351
352    /// \brief Allocate space for a new set of loaded preprocessed entities.
353    ///
354    /// \returns The index into the set of loaded preprocessed entities, which
355    /// corresponds to the first newly-allocated entity.
356    unsigned allocateLoadedEntities(unsigned NumEntities);
357
358    /// \brief Register a new macro definition.
359    void RegisterMacroDefinition(MacroInfo *Macro, PPEntityID PPID);
360
361  public:
362    /// \brief Construct a new preprocessing record.
363    explicit PreprocessingRecord(SourceManager &SM);
364
365    /// \brief Allocate memory in the preprocessing record.
366    void *Allocate(unsigned Size, unsigned Align = 8) {
367      return BumpAlloc.Allocate(Size, Align);
368    }
369
370    /// \brief Deallocate memory in the preprocessing record.
371    void Deallocate(void *Ptr) { }
372
373    size_t getTotalMemory() const;
374
375    SourceManager &getSourceManager() const { return SourceMgr; }
376
377    // Iteration over the preprocessed entities.
378    class iterator {
379      PreprocessingRecord *Self;
380
381      /// \brief Position within the preprocessed entity sequence.
382      ///
383      /// In a complete iteration, the Position field walks the range [-M, N),
384      /// where negative values are used to indicate preprocessed entities
385      /// loaded from the external source while non-negative values are used to
386      /// indicate preprocessed entities introduced by the current preprocessor.
387      /// However, to provide iteration in source order (for, e.g., chained
388      /// precompiled headers), dereferencing the iterator flips the negative
389      /// values (corresponding to loaded entities), so that position -M
390      /// corresponds to element 0 in the loaded entities vector, position -M+1
391      /// corresponds to element 1 in the loaded entities vector, etc. This
392      /// gives us a reasonably efficient, source-order walk.
393      int Position;
394
395    public:
396      typedef PreprocessedEntity *value_type;
397      typedef value_type&         reference;
398      typedef value_type*         pointer;
399      typedef std::random_access_iterator_tag iterator_category;
400      typedef int                 difference_type;
401
402      iterator() : Self(0), Position(0) { }
403
404      iterator(PreprocessingRecord *Self, int Position)
405        : Self(Self), Position(Position) { }
406
407      value_type operator*() const {
408        bool isLoaded = Position < 0;
409        unsigned Index = isLoaded ?
410            Self->LoadedPreprocessedEntities.size() + Position : Position;
411        PPEntityID ID = Self->getPPEntityID(Index, isLoaded);
412        return Self->getPreprocessedEntity(ID);
413      }
414
415      value_type operator[](difference_type D) {
416        return *(*this + D);
417      }
418
419      iterator &operator++() {
420        ++Position;
421        return *this;
422      }
423
424      iterator operator++(int) {
425        iterator Prev(*this);
426        ++Position;
427        return Prev;
428      }
429
430      iterator &operator--() {
431        --Position;
432        return *this;
433      }
434
435      iterator operator--(int) {
436        iterator Prev(*this);
437        --Position;
438        return Prev;
439      }
440
441      friend bool operator==(const iterator &X, const iterator &Y) {
442        return X.Position == Y.Position;
443      }
444
445      friend bool operator!=(const iterator &X, const iterator &Y) {
446        return X.Position != Y.Position;
447      }
448
449      friend bool operator<(const iterator &X, const iterator &Y) {
450        return X.Position < Y.Position;
451      }
452
453      friend bool operator>(const iterator &X, const iterator &Y) {
454        return X.Position > Y.Position;
455      }
456
457      friend bool operator<=(const iterator &X, const iterator &Y) {
458        return X.Position < Y.Position;
459      }
460
461      friend bool operator>=(const iterator &X, const iterator &Y) {
462        return X.Position > Y.Position;
463      }
464
465      friend iterator& operator+=(iterator &X, difference_type D) {
466        X.Position += D;
467        return X;
468      }
469
470      friend iterator& operator-=(iterator &X, difference_type D) {
471        X.Position -= D;
472        return X;
473      }
474
475      friend iterator operator+(iterator X, difference_type D) {
476        X.Position += D;
477        return X;
478      }
479
480      friend iterator operator+(difference_type D, iterator X) {
481        X.Position += D;
482        return X;
483      }
484
485      friend difference_type operator-(const iterator &X, const iterator &Y) {
486        return X.Position - Y.Position;
487      }
488
489      friend iterator operator-(iterator X, difference_type D) {
490        X.Position -= D;
491        return X;
492      }
493      friend class PreprocessingRecord;
494    };
495    friend class iterator;
496
497    /// \brief Begin iterator for all preprocessed entities.
498    iterator begin() {
499      return iterator(this, -(int)LoadedPreprocessedEntities.size());
500    }
501
502    /// \brief End iterator for all preprocessed entities.
503    iterator end() {
504      return iterator(this, PreprocessedEntities.size());
505    }
506
507    /// \brief Begin iterator for local, non-loaded, preprocessed entities.
508    iterator local_begin() {
509      return iterator(this, 0);
510    }
511
512    /// \brief End iterator for local, non-loaded, preprocessed entities.
513    iterator local_end() {
514      return iterator(this, PreprocessedEntities.size());
515    }
516
517    /// \brief begin/end iterator pair for the given range of loaded
518    /// preprocessed entities.
519    std::pair<iterator, iterator>
520    getIteratorsForLoadedRange(unsigned start, unsigned count) {
521      unsigned end = start + count;
522      assert(end <= LoadedPreprocessedEntities.size());
523      return std::make_pair(
524                   iterator(this, int(start)-LoadedPreprocessedEntities.size()),
525                   iterator(this, int(end)-LoadedPreprocessedEntities.size()));
526    }
527
528    /// \brief Returns a pair of [Begin, End) iterators of preprocessed entities
529    /// that source range \p R encompasses.
530    ///
531    /// \param R the range to look for preprocessed entities.
532    ///
533    std::pair<iterator, iterator> getPreprocessedEntitiesInRange(SourceRange R);
534
535    /// \brief Returns true if the preprocessed entity that \p PPEI iterator
536    /// points to is coming from the file \p FID.
537    ///
538    /// Can be used to avoid implicit deserializations of preallocated
539    /// preprocessed entities if we only care about entities of a specific file
540    /// and not from files \#included in the range given at
541    /// \see getPreprocessedEntitiesInRange.
542    bool isEntityInFileID(iterator PPEI, FileID FID);
543
544    /// \brief Add a new preprocessed entity to this record.
545    PPEntityID addPreprocessedEntity(PreprocessedEntity *Entity);
546
547    /// \brief Set the external source for preprocessed entities.
548    void SetExternalSource(ExternalPreprocessingRecordSource &Source);
549
550    /// \brief Retrieve the external source for preprocessed entities.
551    ExternalPreprocessingRecordSource *getExternalSource() const {
552      return ExternalSource;
553    }
554
555    /// \brief Retrieve the macro definition that corresponds to the given
556    /// \c MacroInfo.
557    MacroDefinition *findMacroDefinition(const MacroInfo *MI);
558
559  private:
560    virtual void MacroExpands(const Token &Id, const MacroInfo* MI,
561                              SourceRange Range);
562    virtual void MacroDefined(const Token &Id, const MacroInfo *MI);
563    virtual void MacroUndefined(const Token &Id, const MacroInfo *MI);
564    virtual void InclusionDirective(SourceLocation HashLoc,
565                                    const Token &IncludeTok,
566                                    StringRef FileName,
567                                    bool IsAngled,
568                                    CharSourceRange FilenameRange,
569                                    const FileEntry *File,
570                                    StringRef SearchPath,
571                                    StringRef RelativePath,
572                                    const Module *Imported);
573    virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
574                       const MacroInfo *MI);
575    virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
576                        const MacroInfo *MI);
577    /// \brief Hook called whenever the 'defined' operator is seen.
578    virtual void Defined(const Token &MacroNameTok, const MacroInfo *MI);
579
580    void addMacroExpansion(const Token &Id, const MacroInfo *MI,
581                           SourceRange Range);
582
583    /// \brief Cached result of the last \see getPreprocessedEntitiesInRange
584    /// query.
585    struct {
586      SourceRange Range;
587      std::pair<int, int> Result;
588    } CachedRangeQuery;
589
590    std::pair<int, int> getPreprocessedEntitiesInRangeSlow(SourceRange R);
591
592    friend class ASTReader;
593    friend class ASTWriter;
594  };
595} // end namespace clang
596
597inline void* operator new(size_t bytes, clang::PreprocessingRecord& PR,
598                          unsigned alignment) throw() {
599  return PR.Allocate(bytes, alignment);
600}
601
602inline void operator delete(void* ptr, clang::PreprocessingRecord& PR,
603                            unsigned) throw() {
604  PR.Deallocate(ptr);
605}
606
607#endif // LLVM_CLANG_LEX_PREPROCESSINGRECORD_H
608