ASTReader.h 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ASTReader.h - AST File Reader ----------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the ASTReader class, which reads AST files.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
  18. #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
  19. #include "clang/AST/Type.h"
  20. #include "clang/Basic/Diagnostic.h"
  21. #include "clang/Basic/DiagnosticOptions.h"
  22. #include "clang/Basic/IdentifierTable.h"
  23. #include "clang/Basic/OpenCLOptions.h"
  24. #include "clang/Basic/SourceLocation.h"
  25. #include "clang/Basic/Version.h"
  26. #include "clang/Lex/ExternalPreprocessorSource.h"
  27. #include "clang/Lex/HeaderSearch.h"
  28. #include "clang/Lex/PreprocessingRecord.h"
  29. #include "clang/Lex/PreprocessorOptions.h"
  30. #include "clang/Sema/ExternalSemaSource.h"
  31. #include "clang/Sema/IdentifierResolver.h"
  32. #include "clang/Sema/Sema.h"
  33. #include "clang/Serialization/ASTBitCodes.h"
  34. #include "clang/Serialization/ContinuousRangeMap.h"
  35. #include "clang/Serialization/ModuleFile.h"
  36. #include "clang/Serialization/ModuleFileExtension.h"
  37. #include "clang/Serialization/ModuleManager.h"
  38. #include "llvm/ADT/ArrayRef.h"
  39. #include "llvm/ADT/DenseMap.h"
  40. #include "llvm/ADT/DenseSet.h"
  41. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  42. #include "llvm/ADT/MapVector.h"
  43. #include "llvm/ADT/Optional.h"
  44. #include "llvm/ADT/STLExtras.h"
  45. #include "llvm/ADT/SetVector.h"
  46. #include "llvm/ADT/SmallPtrSet.h"
  47. #include "llvm/ADT/SmallVector.h"
  48. #include "llvm/ADT/StringMap.h"
  49. #include "llvm/ADT/StringRef.h"
  50. #include "llvm/ADT/iterator.h"
  51. #include "llvm/ADT/iterator_range.h"
  52. #include "llvm/Bitstream/BitstreamReader.h"
  53. #include "llvm/Support/MemoryBuffer.h"
  54. #include "llvm/Support/Timer.h"
  55. #include "llvm/Support/VersionTuple.h"
  56. #include <cassert>
  57. #include <cstddef>
  58. #include <cstdint>
  59. #include <ctime>
  60. #include <deque>
  61. #include <memory>
  62. #include <set>
  63. #include <string>
  64. #include <utility>
  65. #include <vector>
  66. namespace clang {
  67. class ASTConsumer;
  68. class ASTContext;
  69. class ASTDeserializationListener;
  70. class ASTReader;
  71. class ASTRecordReader;
  72. class CXXTemporary;
  73. class Decl;
  74. class DeclarationName;
  75. class DeclaratorDecl;
  76. class DeclContext;
  77. class EnumDecl;
  78. class Expr;
  79. class FieldDecl;
  80. class FileEntry;
  81. class FileManager;
  82. class FileSystemOptions;
  83. class FunctionDecl;
  84. class GlobalModuleIndex;
  85. struct HeaderFileInfo;
  86. class HeaderSearchOptions;
  87. class LangOptions;
  88. class MacroInfo;
  89. class InMemoryModuleCache;
  90. class NamedDecl;
  91. class NamespaceDecl;
  92. class ObjCCategoryDecl;
  93. class ObjCInterfaceDecl;
  94. class PCHContainerReader;
  95. class Preprocessor;
  96. class PreprocessorOptions;
  97. class Sema;
  98. class SourceManager;
  99. class Stmt;
  100. class SwitchCase;
  101. class TargetOptions;
  102. class Token;
  103. class TypedefNameDecl;
  104. class ValueDecl;
  105. class VarDecl;
  106. /// Abstract interface for callback invocations by the ASTReader.
  107. ///
  108. /// While reading an AST file, the ASTReader will call the methods of the
  109. /// listener to pass on specific information. Some of the listener methods can
  110. /// return true to indicate to the ASTReader that the information (and
  111. /// consequently the AST file) is invalid.
  112. class ASTReaderListener {
  113. public:
  114. virtual ~ASTReaderListener();
  115. /// Receives the full Clang version information.
  116. ///
  117. /// \returns true to indicate that the version is invalid. Subclasses should
  118. /// generally defer to this implementation.
  119. virtual bool ReadFullVersionInformation(StringRef FullVersion) {
  120. return FullVersion != getClangFullRepositoryVersion();
  121. }
  122. virtual void ReadModuleName(StringRef ModuleName) {}
  123. virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
  124. /// Receives the language options.
  125. ///
  126. /// \returns true to indicate the options are invalid or false otherwise.
  127. virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
  128. bool Complain,
  129. bool AllowCompatibleDifferences) {
  130. return false;
  131. }
  132. /// Receives the target options.
  133. ///
  134. /// \returns true to indicate the target options are invalid, or false
  135. /// otherwise.
  136. virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  137. bool AllowCompatibleDifferences) {
  138. return false;
  139. }
  140. /// Receives the diagnostic options.
  141. ///
  142. /// \returns true to indicate the diagnostic options are invalid, or false
  143. /// otherwise.
  144. virtual bool
  145. ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  146. bool Complain) {
  147. return false;
  148. }
  149. /// Receives the file system options.
  150. ///
  151. /// \returns true to indicate the file system options are invalid, or false
  152. /// otherwise.
  153. virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  154. bool Complain) {
  155. return false;
  156. }
  157. /// Receives the header search options.
  158. ///
  159. /// \returns true to indicate the header search options are invalid, or false
  160. /// otherwise.
  161. virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  162. StringRef SpecificModuleCachePath,
  163. bool Complain) {
  164. return false;
  165. }
  166. /// Receives the preprocessor options.
  167. ///
  168. /// \param SuggestedPredefines Can be filled in with the set of predefines
  169. /// that are suggested by the preprocessor options. Typically only used when
  170. /// loading a precompiled header.
  171. ///
  172. /// \returns true to indicate the preprocessor options are invalid, or false
  173. /// otherwise.
  174. virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  175. bool Complain,
  176. std::string &SuggestedPredefines) {
  177. return false;
  178. }
  179. /// Receives __COUNTER__ value.
  180. virtual void ReadCounter(const serialization::ModuleFile &M,
  181. unsigned Value) {}
  182. /// This is called for each AST file loaded.
  183. virtual void visitModuleFile(StringRef Filename,
  184. serialization::ModuleKind Kind) {}
  185. /// Returns true if this \c ASTReaderListener wants to receive the
  186. /// input files of the AST file via \c visitInputFile, false otherwise.
  187. virtual bool needsInputFileVisitation() { return false; }
  188. /// Returns true if this \c ASTReaderListener wants to receive the
  189. /// system input files of the AST file via \c visitInputFile, false otherwise.
  190. virtual bool needsSystemInputFileVisitation() { return false; }
  191. /// if \c needsInputFileVisitation returns true, this is called for
  192. /// each non-system input file of the AST File. If
  193. /// \c needsSystemInputFileVisitation is true, then it is called for all
  194. /// system input files as well.
  195. ///
  196. /// \returns true to continue receiving the next input file, false to stop.
  197. virtual bool visitInputFile(StringRef Filename, bool isSystem,
  198. bool isOverridden, bool isExplicitModule) {
  199. return true;
  200. }
  201. /// Returns true if this \c ASTReaderListener wants to receive the
  202. /// imports of the AST file via \c visitImport, false otherwise.
  203. virtual bool needsImportVisitation() const { return false; }
  204. /// If needsImportVisitation returns \c true, this is called for each
  205. /// AST file imported by this AST file.
  206. virtual void visitImport(StringRef ModuleName, StringRef Filename) {}
  207. /// Indicates that a particular module file extension has been read.
  208. virtual void readModuleFileExtension(
  209. const ModuleFileExtensionMetadata &Metadata) {}
  210. };
  211. /// Simple wrapper class for chaining listeners.
  212. class ChainedASTReaderListener : public ASTReaderListener {
  213. std::unique_ptr<ASTReaderListener> First;
  214. std::unique_ptr<ASTReaderListener> Second;
  215. public:
  216. /// Takes ownership of \p First and \p Second.
  217. ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
  218. std::unique_ptr<ASTReaderListener> Second)
  219. : First(std::move(First)), Second(std::move(Second)) {}
  220. std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
  221. std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
  222. bool ReadFullVersionInformation(StringRef FullVersion) override;
  223. void ReadModuleName(StringRef ModuleName) override;
  224. void ReadModuleMapFile(StringRef ModuleMapPath) override;
  225. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  226. bool AllowCompatibleDifferences) override;
  227. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  228. bool AllowCompatibleDifferences) override;
  229. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  230. bool Complain) override;
  231. bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  232. bool Complain) override;
  233. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  234. StringRef SpecificModuleCachePath,
  235. bool Complain) override;
  236. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  237. bool Complain,
  238. std::string &SuggestedPredefines) override;
  239. void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
  240. bool needsInputFileVisitation() override;
  241. bool needsSystemInputFileVisitation() override;
  242. void visitModuleFile(StringRef Filename,
  243. serialization::ModuleKind Kind) override;
  244. bool visitInputFile(StringRef Filename, bool isSystem,
  245. bool isOverridden, bool isExplicitModule) override;
  246. void readModuleFileExtension(
  247. const ModuleFileExtensionMetadata &Metadata) override;
  248. };
  249. /// ASTReaderListener implementation to validate the information of
  250. /// the PCH file against an initialized Preprocessor.
  251. class PCHValidator : public ASTReaderListener {
  252. Preprocessor &PP;
  253. ASTReader &Reader;
  254. public:
  255. PCHValidator(Preprocessor &PP, ASTReader &Reader)
  256. : PP(PP), Reader(Reader) {}
  257. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  258. bool AllowCompatibleDifferences) override;
  259. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  260. bool AllowCompatibleDifferences) override;
  261. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  262. bool Complain) override;
  263. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
  264. std::string &SuggestedPredefines) override;
  265. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  266. StringRef SpecificModuleCachePath,
  267. bool Complain) override;
  268. void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
  269. private:
  270. void Error(const char *Msg);
  271. };
  272. /// ASTReaderListenter implementation to set SuggestedPredefines of
  273. /// ASTReader which is required to use a pch file. This is the replacement
  274. /// of PCHValidator or SimplePCHValidator when using a pch file without
  275. /// validating it.
  276. class SimpleASTReaderListener : public ASTReaderListener {
  277. Preprocessor &PP;
  278. public:
  279. SimpleASTReaderListener(Preprocessor &PP) : PP(PP) {}
  280. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
  281. std::string &SuggestedPredefines) override;
  282. };
  283. namespace serialization {
  284. class ReadMethodPoolVisitor;
  285. namespace reader {
  286. class ASTIdentifierLookupTrait;
  287. /// The on-disk hash table(s) used for DeclContext name lookup.
  288. struct DeclContextLookupTable;
  289. } // namespace reader
  290. } // namespace serialization
  291. /// Reads an AST files chain containing the contents of a translation
  292. /// unit.
  293. ///
  294. /// The ASTReader class reads bitstreams (produced by the ASTWriter
  295. /// class) containing the serialized representation of a given
  296. /// abstract syntax tree and its supporting data structures. An
  297. /// instance of the ASTReader can be attached to an ASTContext object,
  298. /// which will provide access to the contents of the AST files.
  299. ///
  300. /// The AST reader provides lazy de-serialization of declarations, as
  301. /// required when traversing the AST. Only those AST nodes that are
  302. /// actually required will be de-serialized.
  303. class ASTReader
  304. : public ExternalPreprocessorSource,
  305. public ExternalPreprocessingRecordSource,
  306. public ExternalHeaderFileInfoSource,
  307. public ExternalSemaSource,
  308. public IdentifierInfoLookup,
  309. public ExternalSLocEntrySource
  310. {
  311. public:
  312. /// Types of AST files.
  313. friend class ASTDeclReader;
  314. friend class ASTIdentifierIterator;
  315. friend class ASTRecordReader;
  316. friend class ASTUnit; // ASTUnit needs to remap source locations.
  317. friend class ASTWriter;
  318. friend class PCHValidator;
  319. friend class serialization::reader::ASTIdentifierLookupTrait;
  320. friend class serialization::ReadMethodPoolVisitor;
  321. friend class TypeLocReader;
  322. using RecordData = SmallVector<uint64_t, 64>;
  323. using RecordDataImpl = SmallVectorImpl<uint64_t>;
  324. /// The result of reading the control block of an AST file, which
  325. /// can fail for various reasons.
  326. enum ASTReadResult {
  327. /// The control block was read successfully. Aside from failures,
  328. /// the AST file is safe to read into the current context.
  329. Success,
  330. /// The AST file itself appears corrupted.
  331. Failure,
  332. /// The AST file was missing.
  333. Missing,
  334. /// The AST file is out-of-date relative to its input files,
  335. /// and needs to be regenerated.
  336. OutOfDate,
  337. /// The AST file was written by a different version of Clang.
  338. VersionMismatch,
  339. /// The AST file was writtten with a different language/target
  340. /// configuration.
  341. ConfigurationMismatch,
  342. /// The AST file has errors.
  343. HadErrors
  344. };
  345. using ModuleFile = serialization::ModuleFile;
  346. using ModuleKind = serialization::ModuleKind;
  347. using ModuleManager = serialization::ModuleManager;
  348. using ModuleIterator = ModuleManager::ModuleIterator;
  349. using ModuleConstIterator = ModuleManager::ModuleConstIterator;
  350. using ModuleReverseIterator = ModuleManager::ModuleReverseIterator;
  351. private:
  352. /// The receiver of some callbacks invoked by ASTReader.
  353. std::unique_ptr<ASTReaderListener> Listener;
  354. /// The receiver of deserialization events.
  355. ASTDeserializationListener *DeserializationListener = nullptr;
  356. bool OwnsDeserializationListener = false;
  357. SourceManager &SourceMgr;
  358. FileManager &FileMgr;
  359. const PCHContainerReader &PCHContainerRdr;
  360. DiagnosticsEngine &Diags;
  361. /// The semantic analysis object that will be processing the
  362. /// AST files and the translation unit that uses it.
  363. Sema *SemaObj = nullptr;
  364. /// The preprocessor that will be loading the source file.
  365. Preprocessor &PP;
  366. /// The AST context into which we'll read the AST files.
  367. ASTContext *ContextObj = nullptr;
  368. /// The AST consumer.
  369. ASTConsumer *Consumer = nullptr;
  370. /// The module manager which manages modules and their dependencies
  371. ModuleManager ModuleMgr;
  372. /// A dummy identifier resolver used to merge TU-scope declarations in
  373. /// C, for the cases where we don't have a Sema object to provide a real
  374. /// identifier resolver.
  375. IdentifierResolver DummyIdResolver;
  376. /// A mapping from extension block names to module file extensions.
  377. llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
  378. /// A timer used to track the time spent deserializing.
  379. std::unique_ptr<llvm::Timer> ReadTimer;
  380. /// The location where the module file will be considered as
  381. /// imported from. For non-module AST types it should be invalid.
  382. SourceLocation CurrentImportLoc;
  383. /// The module kind that is currently deserializing.
  384. Optional<ModuleKind> CurrentDeserializingModuleKind;
  385. /// The global module index, if loaded.
  386. std::unique_ptr<GlobalModuleIndex> GlobalIndex;
  387. /// A map of global bit offsets to the module that stores entities
  388. /// at those bit offsets.
  389. ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
  390. /// A map of negated SLocEntryIDs to the modules containing them.
  391. ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
  392. using GlobalSLocOffsetMapType =
  393. ContinuousRangeMap<unsigned, ModuleFile *, 64>;
  394. /// A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
  395. /// SourceLocation offsets to the modules containing them.
  396. GlobalSLocOffsetMapType GlobalSLocOffsetMap;
  397. /// Types that have already been loaded from the chain.
  398. ///
  399. /// When the pointer at index I is non-NULL, the type with
  400. /// ID = (I + 1) << FastQual::Width has already been loaded
  401. std::vector<QualType> TypesLoaded;
  402. using GlobalTypeMapType =
  403. ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>;
  404. /// Mapping from global type IDs to the module in which the
  405. /// type resides along with the offset that should be added to the
  406. /// global type ID to produce a local ID.
  407. GlobalTypeMapType GlobalTypeMap;
  408. /// Declarations that have already been loaded from the chain.
  409. ///
  410. /// When the pointer at index I is non-NULL, the declaration with ID
  411. /// = I + 1 has already been loaded.
  412. std::vector<Decl *> DeclsLoaded;
  413. using GlobalDeclMapType =
  414. ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>;
  415. /// Mapping from global declaration IDs to the module in which the
  416. /// declaration resides.
  417. GlobalDeclMapType GlobalDeclMap;
  418. using FileOffset = std::pair<ModuleFile *, uint64_t>;
  419. using FileOffsetsTy = SmallVector<FileOffset, 2>;
  420. using DeclUpdateOffsetsMap =
  421. llvm::DenseMap<serialization::DeclID, FileOffsetsTy>;
  422. /// Declarations that have modifications residing in a later file
  423. /// in the chain.
  424. DeclUpdateOffsetsMap DeclUpdateOffsets;
  425. struct PendingUpdateRecord {
  426. Decl *D;
  427. serialization::GlobalDeclID ID;
  428. // Whether the declaration was just deserialized.
  429. bool JustLoaded;
  430. PendingUpdateRecord(serialization::GlobalDeclID ID, Decl *D,
  431. bool JustLoaded)
  432. : D(D), ID(ID), JustLoaded(JustLoaded) {}
  433. };
  434. /// Declaration updates for already-loaded declarations that we need
  435. /// to apply once we finish processing an import.
  436. llvm::SmallVector<PendingUpdateRecord, 16> PendingUpdateRecords;
  437. enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
  438. /// The DefinitionData pointers that we faked up for class definitions
  439. /// that we needed but hadn't loaded yet.
  440. llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
  441. /// Exception specification updates that have been loaded but not yet
  442. /// propagated across the relevant redeclaration chain. The map key is the
  443. /// canonical declaration (used only for deduplication) and the value is a
  444. /// declaration that has an exception specification.
  445. llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
  446. /// Deduced return type updates that have been loaded but not yet propagated
  447. /// across the relevant redeclaration chain. The map key is the canonical
  448. /// declaration and the value is the deduced return type.
  449. llvm::SmallMapVector<FunctionDecl *, QualType, 4> PendingDeducedTypeUpdates;
  450. /// Declarations that have been imported and have typedef names for
  451. /// linkage purposes.
  452. llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
  453. ImportedTypedefNamesForLinkage;
  454. /// Mergeable declaration contexts that have anonymous declarations
  455. /// within them, and those anonymous declarations.
  456. llvm::DenseMap<Decl*, llvm::SmallVector<NamedDecl*, 2>>
  457. AnonymousDeclarationsForMerging;
  458. /// Key used to identify LifetimeExtendedTemporaryDecl for merging,
  459. /// containing the lifetime-extending declaration and the mangling number.
  460. using LETemporaryKey = std::pair<Decl *, unsigned>;
  461. /// Map of already deserialiazed temporaries.
  462. llvm::DenseMap<LETemporaryKey, LifetimeExtendedTemporaryDecl *>
  463. LETemporaryForMerging;
  464. struct FileDeclsInfo {
  465. ModuleFile *Mod = nullptr;
  466. ArrayRef<serialization::LocalDeclID> Decls;
  467. FileDeclsInfo() = default;
  468. FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
  469. : Mod(Mod), Decls(Decls) {}
  470. };
  471. /// Map from a FileID to the file-level declarations that it contains.
  472. llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
  473. /// An array of lexical contents of a declaration context, as a sequence of
  474. /// Decl::Kind, DeclID pairs.
  475. using LexicalContents = ArrayRef<llvm::support::unaligned_uint32_t>;
  476. /// Map from a DeclContext to its lexical contents.
  477. llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
  478. LexicalDecls;
  479. /// Map from the TU to its lexical contents from each module file.
  480. std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
  481. /// Map from a DeclContext to its lookup tables.
  482. llvm::DenseMap<const DeclContext *,
  483. serialization::reader::DeclContextLookupTable> Lookups;
  484. // Updates for visible decls can occur for other contexts than just the
  485. // TU, and when we read those update records, the actual context may not
  486. // be available yet, so have this pending map using the ID as a key. It
  487. // will be realized when the context is actually loaded.
  488. struct PendingVisibleUpdate {
  489. ModuleFile *Mod;
  490. const unsigned char *Data;
  491. };
  492. using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
  493. /// Updates to the visible declarations of declaration contexts that
  494. /// haven't been loaded yet.
  495. llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
  496. PendingVisibleUpdates;
  497. /// The set of C++ or Objective-C classes that have forward
  498. /// declarations that have not yet been linked to their definitions.
  499. llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
  500. using PendingBodiesMap =
  501. llvm::MapVector<Decl *, uint64_t,
  502. llvm::SmallDenseMap<Decl *, unsigned, 4>,
  503. SmallVector<std::pair<Decl *, uint64_t>, 4>>;
  504. /// Functions or methods that have bodies that will be attached.
  505. PendingBodiesMap PendingBodies;
  506. /// Definitions for which we have added merged definitions but not yet
  507. /// performed deduplication.
  508. llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
  509. /// Read the record that describes the lexical contents of a DC.
  510. bool ReadLexicalDeclContextStorage(ModuleFile &M,
  511. llvm::BitstreamCursor &Cursor,
  512. uint64_t Offset, DeclContext *DC);
  513. /// Read the record that describes the visible contents of a DC.
  514. bool ReadVisibleDeclContextStorage(ModuleFile &M,
  515. llvm::BitstreamCursor &Cursor,
  516. uint64_t Offset, serialization::DeclID ID);
  517. /// A vector containing identifiers that have already been
  518. /// loaded.
  519. ///
  520. /// If the pointer at index I is non-NULL, then it refers to the
  521. /// IdentifierInfo for the identifier with ID=I+1 that has already
  522. /// been loaded.
  523. std::vector<IdentifierInfo *> IdentifiersLoaded;
  524. using GlobalIdentifierMapType =
  525. ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>;
  526. /// Mapping from global identifier IDs to the module in which the
  527. /// identifier resides along with the offset that should be added to the
  528. /// global identifier ID to produce a local ID.
  529. GlobalIdentifierMapType GlobalIdentifierMap;
  530. /// A vector containing macros that have already been
  531. /// loaded.
  532. ///
  533. /// If the pointer at index I is non-NULL, then it refers to the
  534. /// MacroInfo for the identifier with ID=I+1 that has already
  535. /// been loaded.
  536. std::vector<MacroInfo *> MacrosLoaded;
  537. using LoadedMacroInfo =
  538. std::pair<IdentifierInfo *, serialization::SubmoduleID>;
  539. /// A set of #undef directives that we have loaded; used to
  540. /// deduplicate the same #undef information coming from multiple module
  541. /// files.
  542. llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
  543. using GlobalMacroMapType =
  544. ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
  545. /// Mapping from global macro IDs to the module in which the
  546. /// macro resides along with the offset that should be added to the
  547. /// global macro ID to produce a local ID.
  548. GlobalMacroMapType GlobalMacroMap;
  549. /// A vector containing submodules that have already been loaded.
  550. ///
  551. /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
  552. /// indicate that the particular submodule ID has not yet been loaded.
  553. SmallVector<Module *, 2> SubmodulesLoaded;
  554. using GlobalSubmoduleMapType =
  555. ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
  556. /// Mapping from global submodule IDs to the module file in which the
  557. /// submodule resides along with the offset that should be added to the
  558. /// global submodule ID to produce a local ID.
  559. GlobalSubmoduleMapType GlobalSubmoduleMap;
  560. /// A set of hidden declarations.
  561. using HiddenNames = SmallVector<Decl *, 2>;
  562. using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
  563. /// A mapping from each of the hidden submodules to the deserialized
  564. /// declarations in that submodule that could be made visible.
  565. HiddenNamesMapType HiddenNamesMap;
  566. /// A module import, export, or conflict that hasn't yet been resolved.
  567. struct UnresolvedModuleRef {
  568. /// The file in which this module resides.
  569. ModuleFile *File;
  570. /// The module that is importing or exporting.
  571. Module *Mod;
  572. /// The kind of module reference.
  573. enum { Import, Export, Conflict } Kind;
  574. /// The local ID of the module that is being exported.
  575. unsigned ID;
  576. /// Whether this is a wildcard export.
  577. unsigned IsWildcard : 1;
  578. /// String data.
  579. StringRef String;
  580. };
  581. /// The set of module imports and exports that still need to be
  582. /// resolved.
  583. SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
  584. /// A vector containing selectors that have already been loaded.
  585. ///
  586. /// This vector is indexed by the Selector ID (-1). NULL selector
  587. /// entries indicate that the particular selector ID has not yet
  588. /// been loaded.
  589. SmallVector<Selector, 16> SelectorsLoaded;
  590. using GlobalSelectorMapType =
  591. ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
  592. /// Mapping from global selector IDs to the module in which the
  593. /// global selector ID to produce a local ID.
  594. GlobalSelectorMapType GlobalSelectorMap;
  595. /// The generation number of the last time we loaded data from the
  596. /// global method pool for this selector.
  597. llvm::DenseMap<Selector, unsigned> SelectorGeneration;
  598. /// Whether a selector is out of date. We mark a selector as out of date
  599. /// if we load another module after the method pool entry was pulled in.
  600. llvm::DenseMap<Selector, bool> SelectorOutOfDate;
  601. struct PendingMacroInfo {
  602. ModuleFile *M;
  603. /// Offset relative to ModuleFile::MacroOffsetsBase.
  604. uint32_t MacroDirectivesOffset;
  605. PendingMacroInfo(ModuleFile *M, uint32_t MacroDirectivesOffset)
  606. : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
  607. };
  608. using PendingMacroIDsMap =
  609. llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
  610. /// Mapping from identifiers that have a macro history to the global
  611. /// IDs have not yet been deserialized to the global IDs of those macros.
  612. PendingMacroIDsMap PendingMacroIDs;
  613. using GlobalPreprocessedEntityMapType =
  614. ContinuousRangeMap<unsigned, ModuleFile *, 4>;
  615. /// Mapping from global preprocessing entity IDs to the module in
  616. /// which the preprocessed entity resides along with the offset that should be
  617. /// added to the global preprocessing entity ID to produce a local ID.
  618. GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
  619. using GlobalSkippedRangeMapType =
  620. ContinuousRangeMap<unsigned, ModuleFile *, 4>;
  621. /// Mapping from global skipped range base IDs to the module in which
  622. /// the skipped ranges reside.
  623. GlobalSkippedRangeMapType GlobalSkippedRangeMap;
  624. /// \name CodeGen-relevant special data
  625. /// Fields containing data that is relevant to CodeGen.
  626. //@{
  627. /// The IDs of all declarations that fulfill the criteria of
  628. /// "interesting" decls.
  629. ///
  630. /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
  631. /// in the chain. The referenced declarations are deserialized and passed to
  632. /// the consumer eagerly.
  633. SmallVector<serialization::DeclID, 16> EagerlyDeserializedDecls;
  634. /// The IDs of all tentative definitions stored in the chain.
  635. ///
  636. /// Sema keeps track of all tentative definitions in a TU because it has to
  637. /// complete them and pass them on to CodeGen. Thus, tentative definitions in
  638. /// the PCH chain must be eagerly deserialized.
  639. SmallVector<serialization::DeclID, 16> TentativeDefinitions;
  640. /// The IDs of all CXXRecordDecls stored in the chain whose VTables are
  641. /// used.
  642. ///
  643. /// CodeGen has to emit VTables for these records, so they have to be eagerly
  644. /// deserialized.
  645. SmallVector<serialization::DeclID, 64> VTableUses;
  646. /// A snapshot of the pending instantiations in the chain.
  647. ///
  648. /// This record tracks the instantiations that Sema has to perform at the
  649. /// end of the TU. It consists of a pair of values for every pending
  650. /// instantiation where the first value is the ID of the decl and the second
  651. /// is the instantiation location.
  652. SmallVector<serialization::DeclID, 64> PendingInstantiations;
  653. //@}
  654. /// \name DiagnosticsEngine-relevant special data
  655. /// Fields containing data that is used for generating diagnostics
  656. //@{
  657. /// A snapshot of Sema's unused file-scoped variable tracking, for
  658. /// generating warnings.
  659. SmallVector<serialization::DeclID, 16> UnusedFileScopedDecls;
  660. /// A list of all the delegating constructors we've seen, to diagnose
  661. /// cycles.
  662. SmallVector<serialization::DeclID, 4> DelegatingCtorDecls;
  663. /// Method selectors used in a @selector expression. Used for
  664. /// implementation of -Wselector.
  665. SmallVector<serialization::SelectorID, 64> ReferencedSelectorsData;
  666. /// A snapshot of Sema's weak undeclared identifier tracking, for
  667. /// generating warnings.
  668. SmallVector<serialization::IdentifierID, 64> WeakUndeclaredIdentifiers;
  669. /// The IDs of type aliases for ext_vectors that exist in the chain.
  670. ///
  671. /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
  672. SmallVector<serialization::DeclID, 4> ExtVectorDecls;
  673. //@}
  674. /// \name Sema-relevant special data
  675. /// Fields containing data that is used for semantic analysis
  676. //@{
  677. /// The IDs of all potentially unused typedef names in the chain.
  678. ///
  679. /// Sema tracks these to emit warnings.
  680. SmallVector<serialization::DeclID, 16> UnusedLocalTypedefNameCandidates;
  681. /// Our current depth in #pragma cuda force_host_device begin/end
  682. /// macros.
  683. unsigned ForceCUDAHostDeviceDepth = 0;
  684. /// The IDs of the declarations Sema stores directly.
  685. ///
  686. /// Sema tracks a few important decls, such as namespace std, directly.
  687. SmallVector<serialization::DeclID, 4> SemaDeclRefs;
  688. /// The IDs of the types ASTContext stores directly.
  689. ///
  690. /// The AST context tracks a few important types, such as va_list, directly.
  691. SmallVector<serialization::TypeID, 16> SpecialTypes;
  692. /// The IDs of CUDA-specific declarations ASTContext stores directly.
  693. ///
  694. /// The AST context tracks a few important decls, currently cudaConfigureCall,
  695. /// directly.
  696. SmallVector<serialization::DeclID, 2> CUDASpecialDeclRefs;
  697. /// The floating point pragma option settings.
  698. SmallVector<uint64_t, 1> FPPragmaOptions;
  699. /// The pragma clang optimize location (if the pragma state is "off").
  700. SourceLocation OptimizeOffPragmaLocation;
  701. /// The PragmaMSStructKind pragma ms_struct state if set, or -1.
  702. int PragmaMSStructState = -1;
  703. /// The PragmaMSPointersToMembersKind pragma pointers_to_members state.
  704. int PragmaMSPointersToMembersState = -1;
  705. SourceLocation PointersToMembersPragmaLocation;
  706. /// The pragma float_control state.
  707. Optional<FPOptionsOverride> FpPragmaCurrentValue;
  708. SourceLocation FpPragmaCurrentLocation;
  709. struct FpPragmaStackEntry {
  710. FPOptionsOverride Value;
  711. SourceLocation Location;
  712. SourceLocation PushLocation;
  713. StringRef SlotLabel;
  714. };
  715. llvm::SmallVector<FpPragmaStackEntry, 2> FpPragmaStack;
  716. llvm::SmallVector<std::string, 2> FpPragmaStrings;
  717. /// The pragma align/pack state.
  718. Optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue;
  719. SourceLocation PragmaAlignPackCurrentLocation;
  720. struct PragmaAlignPackStackEntry {
  721. Sema::AlignPackInfo Value;
  722. SourceLocation Location;
  723. SourceLocation PushLocation;
  724. StringRef SlotLabel;
  725. };
  726. llvm::SmallVector<PragmaAlignPackStackEntry, 2> PragmaAlignPackStack;
  727. llvm::SmallVector<std::string, 2> PragmaAlignPackStrings;
  728. /// The OpenCL extension settings.
  729. OpenCLOptions OpenCLExtensions;
  730. /// Extensions required by an OpenCL type.
  731. llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
  732. /// Extensions required by an OpenCL declaration.
  733. llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
  734. /// A list of the namespaces we've seen.
  735. SmallVector<serialization::DeclID, 4> KnownNamespaces;
  736. /// A list of undefined decls with internal linkage followed by the
  737. /// SourceLocation of a matching ODR-use.
  738. SmallVector<serialization::DeclID, 8> UndefinedButUsed;
  739. /// Delete expressions to analyze at the end of translation unit.
  740. SmallVector<uint64_t, 8> DelayedDeleteExprs;
  741. // A list of late parsed template function data with their module files.
  742. SmallVector<std::pair<ModuleFile *, SmallVector<uint64_t, 1>>, 4>
  743. LateParsedTemplates;
  744. /// The IDs of all decls to be checked for deferred diags.
  745. ///
  746. /// Sema tracks these to emit deferred diags.
  747. llvm::SmallSetVector<serialization::DeclID, 4> DeclsToCheckForDeferredDiags;
  748. public:
  749. struct ImportedSubmodule {
  750. serialization::SubmoduleID ID;
  751. SourceLocation ImportLoc;
  752. ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
  753. : ID(ID), ImportLoc(ImportLoc) {}
  754. };
  755. private:
  756. /// A list of modules that were imported by precompiled headers or
  757. /// any other non-module AST file.
  758. SmallVector<ImportedSubmodule, 2> ImportedModules;
  759. //@}
  760. /// The system include root to be used when loading the
  761. /// precompiled header.
  762. std::string isysroot;
  763. /// Whether to disable the normal validation performed on precompiled
  764. /// headers and module files when they are loaded.
  765. DisableValidationForModuleKind DisableValidationKind;
  766. /// Whether to accept an AST file with compiler errors.
  767. bool AllowASTWithCompilerErrors;
  768. /// Whether to accept an AST file that has a different configuration
  769. /// from the current compiler instance.
  770. bool AllowConfigurationMismatch;
  771. /// Whether validate system input files.
  772. bool ValidateSystemInputs;
  773. /// Whether validate headers and module maps using hash based on contents.
  774. bool ValidateASTInputFilesContent;
  775. /// Whether we are allowed to use the global module index.
  776. bool UseGlobalIndex;
  777. /// Whether we have tried loading the global module index yet.
  778. bool TriedLoadingGlobalIndex = false;
  779. ///Whether we are currently processing update records.
  780. bool ProcessingUpdateRecords = false;
  781. using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
  782. /// Mapping from switch-case IDs in the chain to switch-case statements
  783. ///
  784. /// Statements usually don't have IDs, but switch cases need them, so that the
  785. /// switch statement can refer to them.
  786. SwitchCaseMapTy SwitchCaseStmts;
  787. SwitchCaseMapTy *CurrSwitchCaseStmts;
  788. /// The number of source location entries de-serialized from
  789. /// the PCH file.
  790. unsigned NumSLocEntriesRead = 0;
  791. /// The number of source location entries in the chain.
  792. unsigned TotalNumSLocEntries = 0;
  793. /// The number of statements (and expressions) de-serialized
  794. /// from the chain.
  795. unsigned NumStatementsRead = 0;
  796. /// The total number of statements (and expressions) stored
  797. /// in the chain.
  798. unsigned TotalNumStatements = 0;
  799. /// The number of macros de-serialized from the chain.
  800. unsigned NumMacrosRead = 0;
  801. /// The total number of macros stored in the chain.
  802. unsigned TotalNumMacros = 0;
  803. /// The number of lookups into identifier tables.
  804. unsigned NumIdentifierLookups = 0;
  805. /// The number of lookups into identifier tables that succeed.
  806. unsigned NumIdentifierLookupHits = 0;
  807. /// The number of selectors that have been read.
  808. unsigned NumSelectorsRead = 0;
  809. /// The number of method pool entries that have been read.
  810. unsigned NumMethodPoolEntriesRead = 0;
  811. /// The number of times we have looked up a selector in the method
  812. /// pool.
  813. unsigned NumMethodPoolLookups = 0;
  814. /// The number of times we have looked up a selector in the method
  815. /// pool and found something.
  816. unsigned NumMethodPoolHits = 0;
  817. /// The number of times we have looked up a selector in the method
  818. /// pool within a specific module.
  819. unsigned NumMethodPoolTableLookups = 0;
  820. /// The number of times we have looked up a selector in the method
  821. /// pool within a specific module and found something.
  822. unsigned NumMethodPoolTableHits = 0;
  823. /// The total number of method pool entries in the selector table.
  824. unsigned TotalNumMethodPoolEntries = 0;
  825. /// Number of lexical decl contexts read/total.
  826. unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
  827. /// Number of visible decl contexts read/total.
  828. unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
  829. /// Total size of modules, in bits, currently loaded
  830. uint64_t TotalModulesSizeInBits = 0;
  831. /// Number of Decl/types that are currently deserializing.
  832. unsigned NumCurrentElementsDeserializing = 0;
  833. /// Set true while we are in the process of passing deserialized
  834. /// "interesting" decls to consumer inside FinishedDeserializing().
  835. /// This is used as a guard to avoid recursively repeating the process of
  836. /// passing decls to consumer.
  837. bool PassingDeclsToConsumer = false;
  838. /// The set of identifiers that were read while the AST reader was
  839. /// (recursively) loading declarations.
  840. ///
  841. /// The declarations on the identifier chain for these identifiers will be
  842. /// loaded once the recursive loading has completed.
  843. llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4>>
  844. PendingIdentifierInfos;
  845. /// The set of lookup results that we have faked in order to support
  846. /// merging of partially deserialized decls but that we have not yet removed.
  847. llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
  848. PendingFakeLookupResults;
  849. /// The generation number of each identifier, which keeps track of
  850. /// the last time we loaded information about this identifier.
  851. llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
  852. class InterestingDecl {
  853. Decl *D;
  854. bool DeclHasPendingBody;
  855. public:
  856. InterestingDecl(Decl *D, bool HasBody)
  857. : D(D), DeclHasPendingBody(HasBody) {}
  858. Decl *getDecl() { return D; }
  859. /// Whether the declaration has a pending body.
  860. bool hasPendingBody() { return DeclHasPendingBody; }
  861. };
  862. /// Contains declarations and definitions that could be
  863. /// "interesting" to the ASTConsumer, when we get that AST consumer.
  864. ///
  865. /// "Interesting" declarations are those that have data that may
  866. /// need to be emitted, such as inline function definitions or
  867. /// Objective-C protocols.
  868. std::deque<InterestingDecl> PotentiallyInterestingDecls;
  869. /// The list of deduced function types that we have not yet read, because
  870. /// they might contain a deduced return type that refers to a local type
  871. /// declared within the function.
  872. SmallVector<std::pair<FunctionDecl *, serialization::TypeID>, 16>
  873. PendingFunctionTypes;
  874. /// The list of redeclaration chains that still need to be
  875. /// reconstructed, and the local offset to the corresponding list
  876. /// of redeclarations.
  877. SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
  878. /// The list of canonical declarations whose redeclaration chains
  879. /// need to be marked as incomplete once we're done deserializing things.
  880. SmallVector<Decl *, 16> PendingIncompleteDeclChains;
  881. /// The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
  882. /// been loaded but its DeclContext was not set yet.
  883. struct PendingDeclContextInfo {
  884. Decl *D;
  885. serialization::GlobalDeclID SemaDC;
  886. serialization::GlobalDeclID LexicalDC;
  887. };
  888. /// The set of Decls that have been loaded but their DeclContexts are
  889. /// not set yet.
  890. ///
  891. /// The DeclContexts for these Decls will be set once recursive loading has
  892. /// been completed.
  893. std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
  894. /// The set of NamedDecls that have been loaded, but are members of a
  895. /// context that has been merged into another context where the corresponding
  896. /// declaration is either missing or has not yet been loaded.
  897. ///
  898. /// We will check whether the corresponding declaration is in fact missing
  899. /// once recursing loading has been completed.
  900. llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
  901. using DataPointers =
  902. std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
  903. /// Record definitions in which we found an ODR violation.
  904. llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
  905. PendingOdrMergeFailures;
  906. /// Function definitions in which we found an ODR violation.
  907. llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
  908. PendingFunctionOdrMergeFailures;
  909. /// Enum definitions in which we found an ODR violation.
  910. llvm::SmallDenseMap<EnumDecl *, llvm::SmallVector<EnumDecl *, 2>, 2>
  911. PendingEnumOdrMergeFailures;
  912. /// DeclContexts in which we have diagnosed an ODR violation.
  913. llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
  914. /// The set of Objective-C categories that have been deserialized
  915. /// since the last time the declaration chains were linked.
  916. llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
  917. /// The set of Objective-C class definitions that have already been
  918. /// loaded, for which we will need to check for categories whenever a new
  919. /// module is loaded.
  920. SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
  921. using KeyDeclsMap =
  922. llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2>>;
  923. /// A mapping from canonical declarations to the set of global
  924. /// declaration IDs for key declaration that have been merged with that
  925. /// canonical declaration. A key declaration is a formerly-canonical
  926. /// declaration whose module did not import any other key declaration for that
  927. /// entity. These are the IDs that we use as keys when finding redecl chains.
  928. KeyDeclsMap KeyDecls;
  929. /// A mapping from DeclContexts to the semantic DeclContext that we
  930. /// are treating as the definition of the entity. This is used, for instance,
  931. /// when merging implicit instantiations of class templates across modules.
  932. llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
  933. /// A mapping from canonical declarations of enums to their canonical
  934. /// definitions. Only populated when using modules in C++.
  935. llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
  936. /// A mapping from canonical declarations of records to their canonical
  937. /// definitions. Doesn't cover CXXRecordDecl.
  938. llvm::DenseMap<RecordDecl *, RecordDecl *> RecordDefinitions;
  939. /// When reading a Stmt tree, Stmt operands are placed in this stack.
  940. SmallVector<Stmt *, 16> StmtStack;
  941. /// What kind of records we are reading.
  942. enum ReadingKind {
  943. Read_None, Read_Decl, Read_Type, Read_Stmt
  944. };
  945. /// What kind of records we are reading.
  946. ReadingKind ReadingKind = Read_None;
  947. /// RAII object to change the reading kind.
  948. class ReadingKindTracker {
  949. ASTReader &Reader;
  950. enum ReadingKind PrevKind;
  951. public:
  952. ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
  953. : Reader(reader), PrevKind(Reader.ReadingKind) {
  954. Reader.ReadingKind = newKind;
  955. }
  956. ReadingKindTracker(const ReadingKindTracker &) = delete;
  957. ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
  958. ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
  959. };
  960. /// RAII object to mark the start of processing updates.
  961. class ProcessingUpdatesRAIIObj {
  962. ASTReader &Reader;
  963. bool PrevState;
  964. public:
  965. ProcessingUpdatesRAIIObj(ASTReader &reader)
  966. : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
  967. Reader.ProcessingUpdateRecords = true;
  968. }
  969. ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
  970. ProcessingUpdatesRAIIObj &
  971. operator=(const ProcessingUpdatesRAIIObj &) = delete;
  972. ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
  973. };
  974. /// Suggested contents of the predefines buffer, after this
  975. /// PCH file has been processed.
  976. ///
  977. /// In most cases, this string will be empty, because the predefines
  978. /// buffer computed to build the PCH file will be identical to the
  979. /// predefines buffer computed from the command line. However, when
  980. /// there are differences that the PCH reader can work around, this
  981. /// predefines buffer may contain additional definitions.
  982. std::string SuggestedPredefines;
  983. llvm::DenseMap<const Decl *, bool> DefinitionSource;
  984. bool shouldDisableValidationForFile(const serialization::ModuleFile &M) const;
  985. /// Reads a statement from the specified cursor.
  986. Stmt *ReadStmtFromStream(ModuleFile &F);
  987. struct InputFileInfo {
  988. std::string Filename;
  989. uint64_t ContentHash;
  990. off_t StoredSize;
  991. time_t StoredTime;
  992. bool Overridden;
  993. bool Transient;
  994. bool TopLevelModuleMap;
  995. };
  996. /// Reads the stored information about an input file.
  997. InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
  998. /// Retrieve the file entry and 'overridden' bit for an input
  999. /// file in the given module file.
  1000. serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
  1001. bool Complain = true);
  1002. public:
  1003. void ResolveImportedPath(ModuleFile &M, std::string &Filename);
  1004. static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
  1005. /// Returns the first key declaration for the given declaration. This
  1006. /// is one that is formerly-canonical (or still canonical) and whose module
  1007. /// did not import any other key declaration of the entity.
  1008. Decl *getKeyDeclaration(Decl *D) {
  1009. D = D->getCanonicalDecl();
  1010. if (D->isFromASTFile())
  1011. return D;
  1012. auto I = KeyDecls.find(D);
  1013. if (I == KeyDecls.end() || I->second.empty())
  1014. return D;
  1015. return GetExistingDecl(I->second[0]);
  1016. }
  1017. const Decl *getKeyDeclaration(const Decl *D) {
  1018. return getKeyDeclaration(const_cast<Decl*>(D));
  1019. }
  1020. /// Run a callback on each imported key declaration of \p D.
  1021. template <typename Fn>
  1022. void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
  1023. D = D->getCanonicalDecl();
  1024. if (D->isFromASTFile())
  1025. Visit(D);
  1026. auto It = KeyDecls.find(const_cast<Decl*>(D));
  1027. if (It != KeyDecls.end())
  1028. for (auto ID : It->second)
  1029. Visit(GetExistingDecl(ID));
  1030. }
  1031. /// Get the loaded lookup tables for \p Primary, if any.
  1032. const serialization::reader::DeclContextLookupTable *
  1033. getLoadedLookupTables(DeclContext *Primary) const;
  1034. private:
  1035. struct ImportedModule {
  1036. ModuleFile *Mod;
  1037. ModuleFile *ImportedBy;
  1038. SourceLocation ImportLoc;
  1039. ImportedModule(ModuleFile *Mod,
  1040. ModuleFile *ImportedBy,
  1041. SourceLocation ImportLoc)
  1042. : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
  1043. };
  1044. ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
  1045. SourceLocation ImportLoc, ModuleFile *ImportedBy,
  1046. SmallVectorImpl<ImportedModule> &Loaded,
  1047. off_t ExpectedSize, time_t ExpectedModTime,
  1048. ASTFileSignature ExpectedSignature,
  1049. unsigned ClientLoadCapabilities);
  1050. ASTReadResult ReadControlBlock(ModuleFile &F,
  1051. SmallVectorImpl<ImportedModule> &Loaded,
  1052. const ModuleFile *ImportedBy,
  1053. unsigned ClientLoadCapabilities);
  1054. static ASTReadResult ReadOptionsBlock(
  1055. llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
  1056. bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
  1057. std::string &SuggestedPredefines);
  1058. /// Read the unhashed control block.
  1059. ///
  1060. /// This has no effect on \c F.Stream, instead creating a fresh cursor from
  1061. /// \c F.Data and reading ahead.
  1062. ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
  1063. unsigned ClientLoadCapabilities);
  1064. static ASTReadResult
  1065. readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
  1066. unsigned ClientLoadCapabilities,
  1067. bool AllowCompatibleConfigurationMismatch,
  1068. ASTReaderListener *Listener,
  1069. bool ValidateDiagnosticOptions);
  1070. llvm::Error ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
  1071. llvm::Error ReadExtensionBlock(ModuleFile &F);
  1072. void ReadModuleOffsetMap(ModuleFile &F) const;
  1073. void ParseLineTable(ModuleFile &F, const RecordData &Record);
  1074. llvm::Error ReadSourceManagerBlock(ModuleFile &F);
  1075. llvm::BitstreamCursor &SLocCursorForID(int ID);
  1076. SourceLocation getImportLocation(ModuleFile *F);
  1077. void readIncludedFiles(ModuleFile &F, StringRef Blob, Preprocessor &PP);
  1078. ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
  1079. const ModuleFile *ImportedBy,
  1080. unsigned ClientLoadCapabilities);
  1081. llvm::Error ReadSubmoduleBlock(ModuleFile &F,
  1082. unsigned ClientLoadCapabilities);
  1083. static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
  1084. ASTReaderListener &Listener,
  1085. bool AllowCompatibleDifferences);
  1086. static bool ParseTargetOptions(const RecordData &Record, bool Complain,
  1087. ASTReaderListener &Listener,
  1088. bool AllowCompatibleDifferences);
  1089. static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
  1090. ASTReaderListener &Listener);
  1091. static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
  1092. ASTReaderListener &Listener);
  1093. static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
  1094. ASTReaderListener &Listener);
  1095. static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
  1096. ASTReaderListener &Listener,
  1097. std::string &SuggestedPredefines);
  1098. struct RecordLocation {
  1099. ModuleFile *F;
  1100. uint64_t Offset;
  1101. RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {}
  1102. };
  1103. QualType readTypeRecord(unsigned Index);
  1104. RecordLocation TypeCursorForIndex(unsigned Index);
  1105. void LoadedDecl(unsigned Index, Decl *D);
  1106. Decl *ReadDeclRecord(serialization::DeclID ID);
  1107. void markIncompleteDeclChain(Decl *Canon);
  1108. /// Returns the most recent declaration of a declaration (which must be
  1109. /// of a redeclarable kind) that is either local or has already been loaded
  1110. /// merged into its redecl chain.
  1111. Decl *getMostRecentExistingDecl(Decl *D);
  1112. RecordLocation DeclCursorForID(serialization::DeclID ID,
  1113. SourceLocation &Location);
  1114. void loadDeclUpdateRecords(PendingUpdateRecord &Record);
  1115. void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
  1116. void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
  1117. unsigned PreviousGeneration = 0);
  1118. RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
  1119. uint64_t getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset);
  1120. /// Returns the first preprocessed entity ID that begins or ends after
  1121. /// \arg Loc.
  1122. serialization::PreprocessedEntityID
  1123. findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
  1124. /// Find the next module that contains entities and return the ID
  1125. /// of the first entry.
  1126. ///
  1127. /// \param SLocMapI points at a chunk of a module that contains no
  1128. /// preprocessed entities or the entities it contains are not the
  1129. /// ones we are looking for.
  1130. serialization::PreprocessedEntityID
  1131. findNextPreprocessedEntity(
  1132. GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
  1133. /// Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
  1134. /// preprocessed entity.
  1135. std::pair<ModuleFile *, unsigned>
  1136. getModulePreprocessedEntity(unsigned GlobalIndex);
  1137. /// Returns (begin, end) pair for the preprocessed entities of a
  1138. /// particular module.
  1139. llvm::iterator_range<PreprocessingRecord::iterator>
  1140. getModulePreprocessedEntities(ModuleFile &Mod) const;
  1141. bool canRecoverFromOutOfDate(StringRef ModuleFileName,
  1142. unsigned ClientLoadCapabilities);
  1143. public:
  1144. class ModuleDeclIterator
  1145. : public llvm::iterator_adaptor_base<
  1146. ModuleDeclIterator, const serialization::LocalDeclID *,
  1147. std::random_access_iterator_tag, const Decl *, ptrdiff_t,
  1148. const Decl *, const Decl *> {
  1149. ASTReader *Reader = nullptr;
  1150. ModuleFile *Mod = nullptr;
  1151. public:
  1152. ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
  1153. ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
  1154. const serialization::LocalDeclID *Pos)
  1155. : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
  1156. value_type operator*() const {
  1157. return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
  1158. }
  1159. value_type operator->() const { return **this; }
  1160. bool operator==(const ModuleDeclIterator &RHS) const {
  1161. assert(Reader == RHS.Reader && Mod == RHS.Mod);
  1162. return I == RHS.I;
  1163. }
  1164. };
  1165. llvm::iterator_range<ModuleDeclIterator>
  1166. getModuleFileLevelDecls(ModuleFile &Mod);
  1167. private:
  1168. void PassInterestingDeclsToConsumer();
  1169. void PassInterestingDeclToConsumer(Decl *D);
  1170. void finishPendingActions();
  1171. void diagnoseOdrViolations();
  1172. void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
  1173. void addPendingDeclContextInfo(Decl *D,
  1174. serialization::GlobalDeclID SemaDC,
  1175. serialization::GlobalDeclID LexicalDC) {
  1176. assert(D);
  1177. PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
  1178. PendingDeclContextInfos.push_back(Info);
  1179. }
  1180. /// Produce an error diagnostic and return true.
  1181. ///
  1182. /// This routine should only be used for fatal errors that have to
  1183. /// do with non-routine failures (e.g., corrupted AST file).
  1184. void Error(StringRef Msg) const;
  1185. void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
  1186. StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
  1187. void Error(llvm::Error &&Err) const;
  1188. public:
  1189. /// Load the AST file and validate its contents against the given
  1190. /// Preprocessor.
  1191. ///
  1192. /// \param PP the preprocessor associated with the context in which this
  1193. /// precompiled header will be loaded.
  1194. ///
  1195. /// \param Context the AST context that this precompiled header will be
  1196. /// loaded into, if any.
  1197. ///
  1198. /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
  1199. /// creating modules.
  1200. ///
  1201. /// \param Extensions the list of module file extensions that can be loaded
  1202. /// from the AST files.
  1203. ///
  1204. /// \param isysroot If non-NULL, the system include path specified by the
  1205. /// user. This is only used with relocatable PCH files. If non-NULL,
  1206. /// a relocatable PCH file will use the default path "/".
  1207. ///
  1208. /// \param DisableValidationKind If set, the AST reader will suppress most
  1209. /// of its regular consistency checking, allowing the use of precompiled
  1210. /// headers and module files that cannot be determined to be compatible.
  1211. ///
  1212. /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
  1213. /// AST file the was created out of an AST with compiler errors,
  1214. /// otherwise it will reject it.
  1215. ///
  1216. /// \param AllowConfigurationMismatch If true, the AST reader will not check
  1217. /// for configuration differences between the AST file and the invocation.
  1218. ///
  1219. /// \param ValidateSystemInputs If true, the AST reader will validate
  1220. /// system input files in addition to user input files. This is only
  1221. /// meaningful if \p DisableValidation is false.
  1222. ///
  1223. /// \param UseGlobalIndex If true, the AST reader will try to load and use
  1224. /// the global module index.
  1225. ///
  1226. /// \param ReadTimer If non-null, a timer used to track the time spent
  1227. /// deserializing.
  1228. ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
  1229. ASTContext *Context, const PCHContainerReader &PCHContainerRdr,
  1230. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  1231. StringRef isysroot = "",
  1232. DisableValidationForModuleKind DisableValidationKind =
  1233. DisableValidationForModuleKind::None,
  1234. bool AllowASTWithCompilerErrors = false,
  1235. bool AllowConfigurationMismatch = false,
  1236. bool ValidateSystemInputs = false,
  1237. bool ValidateASTInputFilesContent = false,
  1238. bool UseGlobalIndex = true,
  1239. std::unique_ptr<llvm::Timer> ReadTimer = {});
  1240. ASTReader(const ASTReader &) = delete;
  1241. ASTReader &operator=(const ASTReader &) = delete;
  1242. ~ASTReader() override;
  1243. SourceManager &getSourceManager() const { return SourceMgr; }
  1244. FileManager &getFileManager() const { return FileMgr; }
  1245. DiagnosticsEngine &getDiags() const { return Diags; }
  1246. /// Flags that indicate what kind of AST loading failures the client
  1247. /// of the AST reader can directly handle.
  1248. ///
  1249. /// When a client states that it can handle a particular kind of failure,
  1250. /// the AST reader will not emit errors when producing that kind of failure.
  1251. enum LoadFailureCapabilities {
  1252. /// The client can't handle any AST loading failures.
  1253. ARR_None = 0,
  1254. /// The client can handle an AST file that cannot load because it
  1255. /// is missing.
  1256. ARR_Missing = 0x1,
  1257. /// The client can handle an AST file that cannot load because it
  1258. /// is out-of-date relative to its input files.
  1259. ARR_OutOfDate = 0x2,
  1260. /// The client can handle an AST file that cannot load because it
  1261. /// was built with a different version of Clang.
  1262. ARR_VersionMismatch = 0x4,
  1263. /// The client can handle an AST file that cannot load because it's
  1264. /// compiled configuration doesn't match that of the context it was
  1265. /// loaded into.
  1266. ARR_ConfigurationMismatch = 0x8,
  1267. /// If a module file is marked with errors treat it as out-of-date so the
  1268. /// caller can rebuild it.
  1269. ARR_TreatModuleWithErrorsAsOutOfDate = 0x10
  1270. };
  1271. /// Load the AST file designated by the given file name.
  1272. ///
  1273. /// \param FileName The name of the AST file to load.
  1274. ///
  1275. /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
  1276. /// or preamble.
  1277. ///
  1278. /// \param ImportLoc the location where the module file will be considered as
  1279. /// imported from. For non-module AST types it should be invalid.
  1280. ///
  1281. /// \param ClientLoadCapabilities The set of client load-failure
  1282. /// capabilities, represented as a bitset of the enumerators of
  1283. /// LoadFailureCapabilities.
  1284. ///
  1285. /// \param Imported optional out-parameter to append the list of modules
  1286. /// that were imported by precompiled headers or any other non-module AST file
  1287. ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
  1288. SourceLocation ImportLoc,
  1289. unsigned ClientLoadCapabilities,
  1290. SmallVectorImpl<ImportedSubmodule> *Imported = nullptr);
  1291. /// Make the entities in the given module and any of its (non-explicit)
  1292. /// submodules visible to name lookup.
  1293. ///
  1294. /// \param Mod The module whose names should be made visible.
  1295. ///
  1296. /// \param NameVisibility The level of visibility to give the names in the
  1297. /// module. Visibility can only be increased over time.
  1298. ///
  1299. /// \param ImportLoc The location at which the import occurs.
  1300. void makeModuleVisible(Module *Mod,
  1301. Module::NameVisibilityKind NameVisibility,
  1302. SourceLocation ImportLoc);
  1303. /// Make the names within this set of hidden names visible.
  1304. void makeNamesVisible(const HiddenNames &Names, Module *Owner);
  1305. /// Note that MergedDef is a redefinition of the canonical definition
  1306. /// Def, so Def should be visible whenever MergedDef is.
  1307. void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
  1308. /// Take the AST callbacks listener.
  1309. std::unique_ptr<ASTReaderListener> takeListener() {
  1310. return std::move(Listener);
  1311. }
  1312. /// Set the AST callbacks listener.
  1313. void setListener(std::unique_ptr<ASTReaderListener> Listener) {
  1314. this->Listener = std::move(Listener);
  1315. }
  1316. /// Add an AST callback listener.
  1317. ///
  1318. /// Takes ownership of \p L.
  1319. void addListener(std::unique_ptr<ASTReaderListener> L) {
  1320. if (Listener)
  1321. L = std::make_unique<ChainedASTReaderListener>(std::move(L),
  1322. std::move(Listener));
  1323. Listener = std::move(L);
  1324. }
  1325. /// RAII object to temporarily add an AST callback listener.
  1326. class ListenerScope {
  1327. ASTReader &Reader;
  1328. bool Chained = false;
  1329. public:
  1330. ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
  1331. : Reader(Reader) {
  1332. auto Old = Reader.takeListener();
  1333. if (Old) {
  1334. Chained = true;
  1335. L = std::make_unique<ChainedASTReaderListener>(std::move(L),
  1336. std::move(Old));
  1337. }
  1338. Reader.setListener(std::move(L));
  1339. }
  1340. ~ListenerScope() {
  1341. auto New = Reader.takeListener();
  1342. if (Chained)
  1343. Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
  1344. ->takeSecond());
  1345. }
  1346. };
  1347. /// Set the AST deserialization listener.
  1348. void setDeserializationListener(ASTDeserializationListener *Listener,
  1349. bool TakeOwnership = false);
  1350. /// Get the AST deserialization listener.
  1351. ASTDeserializationListener *getDeserializationListener() {
  1352. return DeserializationListener;
  1353. }
  1354. /// Determine whether this AST reader has a global index.
  1355. bool hasGlobalIndex() const { return (bool)GlobalIndex; }
  1356. /// Return global module index.
  1357. GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
  1358. /// Reset reader for a reload try.
  1359. void resetForReload() { TriedLoadingGlobalIndex = false; }
  1360. /// Attempts to load the global index.
  1361. ///
  1362. /// \returns true if loading the global index has failed for any reason.
  1363. bool loadGlobalIndex();
  1364. /// Determine whether we tried to load the global index, but failed,
  1365. /// e.g., because it is out-of-date or does not exist.
  1366. bool isGlobalIndexUnavailable() const;
  1367. /// Initializes the ASTContext
  1368. void InitializeContext();
  1369. /// Update the state of Sema after loading some additional modules.
  1370. void UpdateSema();
  1371. /// Add in-memory (virtual file) buffer.
  1372. void addInMemoryBuffer(StringRef &FileName,
  1373. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  1374. ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
  1375. }
  1376. /// Finalizes the AST reader's state before writing an AST file to
  1377. /// disk.
  1378. ///
  1379. /// This operation may undo temporary state in the AST that should not be
  1380. /// emitted.
  1381. void finalizeForWriting();
  1382. /// Retrieve the module manager.
  1383. ModuleManager &getModuleManager() { return ModuleMgr; }
  1384. /// Retrieve the preprocessor.
  1385. Preprocessor &getPreprocessor() const { return PP; }
  1386. /// Retrieve the name of the original source file name for the primary
  1387. /// module file.
  1388. StringRef getOriginalSourceFile() {
  1389. return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
  1390. }
  1391. /// Retrieve the name of the original source file name directly from
  1392. /// the AST file, without actually loading the AST file.
  1393. static std::string
  1394. getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
  1395. const PCHContainerReader &PCHContainerRdr,
  1396. DiagnosticsEngine &Diags);
  1397. /// Read the control block for the named AST file.
  1398. ///
  1399. /// \returns true if an error occurred, false otherwise.
  1400. static bool
  1401. readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
  1402. const PCHContainerReader &PCHContainerRdr,
  1403. bool FindModuleFileExtensions,
  1404. ASTReaderListener &Listener,
  1405. bool ValidateDiagnosticOptions);
  1406. /// Determine whether the given AST file is acceptable to load into a
  1407. /// translation unit with the given language and target options.
  1408. static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
  1409. const PCHContainerReader &PCHContainerRdr,
  1410. const LangOptions &LangOpts,
  1411. const TargetOptions &TargetOpts,
  1412. const PreprocessorOptions &PPOpts,
  1413. StringRef ExistingModuleCachePath);
  1414. /// Returns the suggested contents of the predefines buffer,
  1415. /// which contains a (typically-empty) subset of the predefines
  1416. /// build prior to including the precompiled header.
  1417. const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
  1418. /// Read a preallocated preprocessed entity from the external source.
  1419. ///
  1420. /// \returns null if an error occurred that prevented the preprocessed
  1421. /// entity from being loaded.
  1422. PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
  1423. /// Returns a pair of [Begin, End) indices of preallocated
  1424. /// preprocessed entities that \p Range encompasses.
  1425. std::pair<unsigned, unsigned>
  1426. findPreprocessedEntitiesInRange(SourceRange Range) override;
  1427. /// Optionally returns true or false if the preallocated preprocessed
  1428. /// entity with index \p Index came from file \p FID.
  1429. Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
  1430. FileID FID) override;
  1431. /// Read a preallocated skipped range from the external source.
  1432. SourceRange ReadSkippedRange(unsigned Index) override;
  1433. /// Read the header file information for the given file entry.
  1434. HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
  1435. void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
  1436. /// Returns the number of source locations found in the chain.
  1437. unsigned getTotalNumSLocs() const {
  1438. return TotalNumSLocEntries;
  1439. }
  1440. /// Returns the number of identifiers found in the chain.
  1441. unsigned getTotalNumIdentifiers() const {
  1442. return static_cast<unsigned>(IdentifiersLoaded.size());
  1443. }
  1444. /// Returns the number of macros found in the chain.
  1445. unsigned getTotalNumMacros() const {
  1446. return static_cast<unsigned>(MacrosLoaded.size());
  1447. }
  1448. /// Returns the number of types found in the chain.
  1449. unsigned getTotalNumTypes() const {
  1450. return static_cast<unsigned>(TypesLoaded.size());
  1451. }
  1452. /// Returns the number of declarations found in the chain.
  1453. unsigned getTotalNumDecls() const {
  1454. return static_cast<unsigned>(DeclsLoaded.size());
  1455. }
  1456. /// Returns the number of submodules known.
  1457. unsigned getTotalNumSubmodules() const {
  1458. return static_cast<unsigned>(SubmodulesLoaded.size());
  1459. }
  1460. /// Returns the number of selectors found in the chain.
  1461. unsigned getTotalNumSelectors() const {
  1462. return static_cast<unsigned>(SelectorsLoaded.size());
  1463. }
  1464. /// Returns the number of preprocessed entities known to the AST
  1465. /// reader.
  1466. unsigned getTotalNumPreprocessedEntities() const {
  1467. unsigned Result = 0;
  1468. for (const auto &M : ModuleMgr)
  1469. Result += M.NumPreprocessedEntities;
  1470. return Result;
  1471. }
  1472. /// Resolve a type ID into a type, potentially building a new
  1473. /// type.
  1474. QualType GetType(serialization::TypeID ID);
  1475. /// Resolve a local type ID within a given AST file into a type.
  1476. QualType getLocalType(ModuleFile &F, unsigned LocalID);
  1477. /// Map a local type ID within a given AST file into a global type ID.
  1478. serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
  1479. /// Read a type from the current position in the given record, which
  1480. /// was read from the given AST file.
  1481. QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
  1482. if (Idx >= Record.size())
  1483. return {};
  1484. return getLocalType(F, Record[Idx++]);
  1485. }
  1486. /// Map from a local declaration ID within a given module to a
  1487. /// global declaration ID.
  1488. serialization::DeclID getGlobalDeclID(ModuleFile &F,
  1489. serialization::LocalDeclID LocalID) const;
  1490. /// Returns true if global DeclID \p ID originated from module \p M.
  1491. bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
  1492. /// Retrieve the module file that owns the given declaration, or NULL
  1493. /// if the declaration is not from a module file.
  1494. ModuleFile *getOwningModuleFile(const Decl *D);
  1495. /// Get the best name we know for the module that owns the given
  1496. /// declaration, or an empty string if the declaration is not from a module.
  1497. std::string getOwningModuleNameForDiagnostic(const Decl *D);
  1498. /// Returns the source location for the decl \p ID.
  1499. SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
  1500. /// Resolve a declaration ID into a declaration, potentially
  1501. /// building a new declaration.
  1502. Decl *GetDecl(serialization::DeclID ID);
  1503. Decl *GetExternalDecl(uint32_t ID) override;
  1504. /// Resolve a declaration ID into a declaration. Return 0 if it's not
  1505. /// been loaded yet.
  1506. Decl *GetExistingDecl(serialization::DeclID ID);
  1507. /// Reads a declaration with the given local ID in the given module.
  1508. Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
  1509. return GetDecl(getGlobalDeclID(F, LocalID));
  1510. }
  1511. /// Reads a declaration with the given local ID in the given module.
  1512. ///
  1513. /// \returns The requested declaration, casted to the given return type.
  1514. template<typename T>
  1515. T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
  1516. return cast_or_null<T>(GetLocalDecl(F, LocalID));
  1517. }
  1518. /// Map a global declaration ID into the declaration ID used to
  1519. /// refer to this declaration within the given module fule.
  1520. ///
  1521. /// \returns the global ID of the given declaration as known in the given
  1522. /// module file.
  1523. serialization::DeclID
  1524. mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
  1525. serialization::DeclID GlobalID);
  1526. /// Reads a declaration ID from the given position in a record in the
  1527. /// given module.
  1528. ///
  1529. /// \returns The declaration ID read from the record, adjusted to a global ID.
  1530. serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
  1531. unsigned &Idx);
  1532. /// Reads a declaration from the given position in a record in the
  1533. /// given module.
  1534. Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
  1535. return GetDecl(ReadDeclID(F, R, I));
  1536. }
  1537. /// Reads a declaration from the given position in a record in the
  1538. /// given module.
  1539. ///
  1540. /// \returns The declaration read from this location, casted to the given
  1541. /// result type.
  1542. template<typename T>
  1543. T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
  1544. return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
  1545. }
  1546. /// If any redeclarations of \p D have been imported since it was
  1547. /// last checked, this digs out those redeclarations and adds them to the
  1548. /// redeclaration chain for \p D.
  1549. void CompleteRedeclChain(const Decl *D) override;
  1550. CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
  1551. /// Resolve the offset of a statement into a statement.
  1552. ///
  1553. /// This operation will read a new statement from the external
  1554. /// source each time it is called, and is meant to be used via a
  1555. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  1556. Stmt *GetExternalDeclStmt(uint64_t Offset) override;
  1557. /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
  1558. /// specified cursor. Read the abbreviations that are at the top of the block
  1559. /// and then leave the cursor pointing into the block.
  1560. static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
  1561. unsigned BlockID,
  1562. uint64_t *StartOfBlockOffset = nullptr);
  1563. /// Finds all the visible declarations with a given name.
  1564. /// The current implementation of this method just loads the entire
  1565. /// lookup table as unmaterialized references.
  1566. bool FindExternalVisibleDeclsByName(const DeclContext *DC,
  1567. DeclarationName Name) override;
  1568. /// Read all of the declarations lexically stored in a
  1569. /// declaration context.
  1570. ///
  1571. /// \param DC The declaration context whose declarations will be
  1572. /// read.
  1573. ///
  1574. /// \param IsKindWeWant A predicate indicating which declaration kinds
  1575. /// we are interested in.
  1576. ///
  1577. /// \param Decls Vector that will contain the declarations loaded
  1578. /// from the external source. The caller is responsible for merging
  1579. /// these declarations with any declarations already stored in the
  1580. /// declaration context.
  1581. void
  1582. FindExternalLexicalDecls(const DeclContext *DC,
  1583. llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
  1584. SmallVectorImpl<Decl *> &Decls) override;
  1585. /// Get the decls that are contained in a file in the Offset/Length
  1586. /// range. \p Length can be 0 to indicate a point at \p Offset instead of
  1587. /// a range.
  1588. void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
  1589. SmallVectorImpl<Decl *> &Decls) override;
  1590. /// Notify ASTReader that we started deserialization of
  1591. /// a decl or type so until FinishedDeserializing is called there may be
  1592. /// decls that are initializing. Must be paired with FinishedDeserializing.
  1593. void StartedDeserializing() override;
  1594. /// Notify ASTReader that we finished the deserialization of
  1595. /// a decl or type. Must be paired with StartedDeserializing.
  1596. void FinishedDeserializing() override;
  1597. /// Function that will be invoked when we begin parsing a new
  1598. /// translation unit involving this external AST source.
  1599. ///
  1600. /// This function will provide all of the external definitions to
  1601. /// the ASTConsumer.
  1602. void StartTranslationUnit(ASTConsumer *Consumer) override;
  1603. /// Print some statistics about AST usage.
  1604. void PrintStats() override;
  1605. /// Dump information about the AST reader to standard error.
  1606. void dump();
  1607. /// Return the amount of memory used by memory buffers, breaking down
  1608. /// by heap-backed versus mmap'ed memory.
  1609. void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
  1610. /// Initialize the semantic source with the Sema instance
  1611. /// being used to perform semantic analysis on the abstract syntax
  1612. /// tree.
  1613. void InitializeSema(Sema &S) override;
  1614. /// Inform the semantic consumer that Sema is no longer available.
  1615. void ForgetSema() override { SemaObj = nullptr; }
  1616. /// Retrieve the IdentifierInfo for the named identifier.
  1617. ///
  1618. /// This routine builds a new IdentifierInfo for the given identifier. If any
  1619. /// declarations with this name are visible from translation unit scope, their
  1620. /// declarations will be deserialized and introduced into the declaration
  1621. /// chain of the identifier.
  1622. IdentifierInfo *get(StringRef Name) override;
  1623. /// Retrieve an iterator into the set of all identifiers
  1624. /// in all loaded AST files.
  1625. IdentifierIterator *getIdentifiers() override;
  1626. /// Load the contents of the global method pool for a given
  1627. /// selector.
  1628. void ReadMethodPool(Selector Sel) override;
  1629. /// Load the contents of the global method pool for a given
  1630. /// selector if necessary.
  1631. void updateOutOfDateSelector(Selector Sel) override;
  1632. /// Load the set of namespaces that are known to the external source,
  1633. /// which will be used during typo correction.
  1634. void ReadKnownNamespaces(
  1635. SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
  1636. void ReadUndefinedButUsed(
  1637. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
  1638. void ReadMismatchingDeleteExpressions(llvm::MapVector<
  1639. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
  1640. Exprs) override;
  1641. void ReadTentativeDefinitions(
  1642. SmallVectorImpl<VarDecl *> &TentativeDefs) override;
  1643. void ReadUnusedFileScopedDecls(
  1644. SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
  1645. void ReadDelegatingConstructors(
  1646. SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
  1647. void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
  1648. void ReadUnusedLocalTypedefNameCandidates(
  1649. llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
  1650. void ReadDeclsToCheckForDeferredDiags(
  1651. llvm::SmallSetVector<Decl *, 4> &Decls) override;
  1652. void ReadReferencedSelectors(
  1653. SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
  1654. void ReadWeakUndeclaredIdentifiers(
  1655. SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WI) override;
  1656. void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
  1657. void ReadPendingInstantiations(
  1658. SmallVectorImpl<std::pair<ValueDecl *,
  1659. SourceLocation>> &Pending) override;
  1660. void ReadLateParsedTemplates(
  1661. llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
  1662. &LPTMap) override;
  1663. /// Load a selector from disk, registering its ID if it exists.
  1664. void LoadSelector(Selector Sel);
  1665. void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
  1666. void SetGloballyVisibleDecls(IdentifierInfo *II,
  1667. const SmallVectorImpl<uint32_t> &DeclIDs,
  1668. SmallVectorImpl<Decl *> *Decls = nullptr);
  1669. /// Report a diagnostic.
  1670. DiagnosticBuilder Diag(unsigned DiagID) const;
  1671. /// Report a diagnostic.
  1672. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
  1673. IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
  1674. IdentifierInfo *readIdentifier(ModuleFile &M, const RecordData &Record,
  1675. unsigned &Idx) {
  1676. return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
  1677. }
  1678. IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
  1679. // Note that we are loading an identifier.
  1680. Deserializing AnIdentifier(this);
  1681. return DecodeIdentifierInfo(ID);
  1682. }
  1683. IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
  1684. serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
  1685. unsigned LocalID);
  1686. void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
  1687. /// Retrieve the macro with the given ID.
  1688. MacroInfo *getMacro(serialization::MacroID ID);
  1689. /// Retrieve the global macro ID corresponding to the given local
  1690. /// ID within the given module file.
  1691. serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
  1692. /// Read the source location entry with index ID.
  1693. bool ReadSLocEntry(int ID) override;
  1694. /// Retrieve the module import location and module name for the
  1695. /// given source manager entry ID.
  1696. std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
  1697. /// Retrieve the global submodule ID given a module and its local ID
  1698. /// number.
  1699. serialization::SubmoduleID
  1700. getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
  1701. /// Retrieve the submodule that corresponds to a global submodule ID.
  1702. ///
  1703. Module *getSubmodule(serialization::SubmoduleID GlobalID);
  1704. /// Retrieve the module that corresponds to the given module ID.
  1705. ///
  1706. /// Note: overrides method in ExternalASTSource
  1707. Module *getModule(unsigned ID) override;
  1708. /// Retrieve the module file with a given local ID within the specified
  1709. /// ModuleFile.
  1710. ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
  1711. /// Get an ID for the given module file.
  1712. unsigned getModuleFileID(ModuleFile *M);
  1713. /// Return a descriptor for the corresponding module.
  1714. llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
  1715. ExtKind hasExternalDefinitions(const Decl *D) override;
  1716. /// Retrieve a selector from the given module with its local ID
  1717. /// number.
  1718. Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
  1719. Selector DecodeSelector(serialization::SelectorID Idx);
  1720. Selector GetExternalSelector(serialization::SelectorID ID) override;
  1721. uint32_t GetNumExternalSelectors() override;
  1722. Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
  1723. return getLocalSelector(M, Record[Idx++]);
  1724. }
  1725. /// Retrieve the global selector ID that corresponds to this
  1726. /// the local selector ID in a given module.
  1727. serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
  1728. unsigned LocalID) const;
  1729. /// Read the contents of a CXXCtorInitializer array.
  1730. CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
  1731. /// Read a AlignPackInfo from raw form.
  1732. Sema::AlignPackInfo ReadAlignPackInfo(uint32_t Raw) const {
  1733. return Sema::AlignPackInfo::getFromRawEncoding(Raw);
  1734. }
  1735. /// Read a source location from raw form and return it in its
  1736. /// originating module file's source location space.
  1737. SourceLocation
  1738. ReadUntranslatedSourceLocation(SourceLocation::UIntTy Raw) const {
  1739. return SourceLocation::getFromRawEncoding((Raw >> 1) |
  1740. (Raw << (8 * sizeof(Raw) - 1)));
  1741. }
  1742. /// Read a source location from raw form.
  1743. SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
  1744. SourceLocation::UIntTy Raw) const {
  1745. SourceLocation Loc = ReadUntranslatedSourceLocation(Raw);
  1746. return TranslateSourceLocation(ModuleFile, Loc);
  1747. }
  1748. /// Translate a source location from another module file's source
  1749. /// location space into ours.
  1750. SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
  1751. SourceLocation Loc) const {
  1752. if (!ModuleFile.ModuleOffsetMap.empty())
  1753. ReadModuleOffsetMap(ModuleFile);
  1754. assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
  1755. ModuleFile.SLocRemap.end() &&
  1756. "Cannot find offset to remap.");
  1757. SourceLocation::IntTy Remap =
  1758. ModuleFile.SLocRemap.find(Loc.getOffset())->second;
  1759. return Loc.getLocWithOffset(Remap);
  1760. }
  1761. /// Read a source location.
  1762. SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
  1763. const RecordDataImpl &Record,
  1764. unsigned &Idx) {
  1765. return ReadSourceLocation(ModuleFile, Record[Idx++]);
  1766. }
  1767. /// Read a source range.
  1768. SourceRange ReadSourceRange(ModuleFile &F,
  1769. const RecordData &Record, unsigned &Idx);
  1770. // Read a string
  1771. static std::string ReadString(const RecordData &Record, unsigned &Idx);
  1772. // Skip a string
  1773. static void SkipString(const RecordData &Record, unsigned &Idx) {
  1774. Idx += Record[Idx] + 1;
  1775. }
  1776. // Read a path
  1777. std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
  1778. // Read a path
  1779. std::string ReadPath(StringRef BaseDirectory, const RecordData &Record,
  1780. unsigned &Idx);
  1781. // Skip a path
  1782. static void SkipPath(const RecordData &Record, unsigned &Idx) {
  1783. SkipString(Record, Idx);
  1784. }
  1785. /// Read a version tuple.
  1786. static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
  1787. CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
  1788. unsigned &Idx);
  1789. /// Reads a statement.
  1790. Stmt *ReadStmt(ModuleFile &F);
  1791. /// Reads an expression.
  1792. Expr *ReadExpr(ModuleFile &F);
  1793. /// Reads a sub-statement operand during statement reading.
  1794. Stmt *ReadSubStmt() {
  1795. assert(ReadingKind == Read_Stmt &&
  1796. "Should be called only during statement reading!");
  1797. // Subexpressions are stored from last to first, so the next Stmt we need
  1798. // is at the back of the stack.
  1799. assert(!StmtStack.empty() && "Read too many sub-statements!");
  1800. return StmtStack.pop_back_val();
  1801. }
  1802. /// Reads a sub-expression operand during statement reading.
  1803. Expr *ReadSubExpr();
  1804. /// Reads a token out of a record.
  1805. Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
  1806. /// Reads the macro record located at the given offset.
  1807. MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
  1808. /// Determine the global preprocessed entity ID that corresponds to
  1809. /// the given local ID within the given module.
  1810. serialization::PreprocessedEntityID
  1811. getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
  1812. /// Add a macro to deserialize its macro directive history.
  1813. ///
  1814. /// \param II The name of the macro.
  1815. /// \param M The module file.
  1816. /// \param MacroDirectivesOffset Offset of the serialized macro directive
  1817. /// history.
  1818. void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
  1819. uint32_t MacroDirectivesOffset);
  1820. /// Read the set of macros defined by this external macro source.
  1821. void ReadDefinedMacros() override;
  1822. /// Update an out-of-date identifier.
  1823. void updateOutOfDateIdentifier(IdentifierInfo &II) override;
  1824. /// Note that this identifier is up-to-date.
  1825. void markIdentifierUpToDate(IdentifierInfo *II);
  1826. /// Load all external visible decls in the given DeclContext.
  1827. void completeVisibleDeclsMap(const DeclContext *DC) override;
  1828. /// Retrieve the AST context that this AST reader supplements.
  1829. ASTContext &getContext() {
  1830. assert(ContextObj && "requested AST context when not loading AST");
  1831. return *ContextObj;
  1832. }
  1833. // Contains the IDs for declarations that were requested before we have
  1834. // access to a Sema object.
  1835. SmallVector<uint64_t, 16> PreloadedDeclIDs;
  1836. /// Retrieve the semantic analysis object used to analyze the
  1837. /// translation unit in which the precompiled header is being
  1838. /// imported.
  1839. Sema *getSema() { return SemaObj; }
  1840. /// Get the identifier resolver used for name lookup / updates
  1841. /// in the translation unit scope. We have one of these even if we don't
  1842. /// have a Sema object.
  1843. IdentifierResolver &getIdResolver();
  1844. /// Retrieve the identifier table associated with the
  1845. /// preprocessor.
  1846. IdentifierTable &getIdentifierTable();
  1847. /// Record that the given ID maps to the given switch-case
  1848. /// statement.
  1849. void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
  1850. /// Retrieve the switch-case statement with the given ID.
  1851. SwitchCase *getSwitchCaseWithID(unsigned ID);
  1852. void ClearSwitchCaseIDs();
  1853. /// Cursors for comments blocks.
  1854. SmallVector<std::pair<llvm::BitstreamCursor,
  1855. serialization::ModuleFile *>, 8> CommentsCursors;
  1856. /// Loads comments ranges.
  1857. void ReadComments() override;
  1858. /// Visit all the input files of the given module file.
  1859. void visitInputFiles(serialization::ModuleFile &MF,
  1860. bool IncludeSystem, bool Complain,
  1861. llvm::function_ref<void(const serialization::InputFile &IF,
  1862. bool isSystem)> Visitor);
  1863. /// Visit all the top-level module maps loaded when building the given module
  1864. /// file.
  1865. void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
  1866. llvm::function_ref<
  1867. void(const FileEntry *)> Visitor);
  1868. bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
  1869. };
  1870. } // namespace clang
  1871. #endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H
  1872. #ifdef __GNUC__
  1873. #pragma GCC diagnostic pop
  1874. #endif