ASTUnit.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721
  1. //===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // ASTUnit Implementation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Frontend/ASTUnit.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CommentCommandTraits.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclBase.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclGroup.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/ExternalASTSource.h"
  24. #include "clang/AST/PrettyPrinter.h"
  25. #include "clang/AST/Type.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/Diagnostic.h"
  28. #include "clang/Basic/FileManager.h"
  29. #include "clang/Basic/IdentifierTable.h"
  30. #include "clang/Basic/LLVM.h"
  31. #include "clang/Basic/LangOptions.h"
  32. #include "clang/Basic/LangStandard.h"
  33. #include "clang/Basic/Module.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Basic/TargetOptions.h"
  38. #include "clang/Frontend/CompilerInstance.h"
  39. #include "clang/Frontend/CompilerInvocation.h"
  40. #include "clang/Frontend/FrontendAction.h"
  41. #include "clang/Frontend/FrontendActions.h"
  42. #include "clang/Frontend/FrontendDiagnostic.h"
  43. #include "clang/Frontend/FrontendOptions.h"
  44. #include "clang/Frontend/MultiplexConsumer.h"
  45. #include "clang/Frontend/PrecompiledPreamble.h"
  46. #include "clang/Frontend/Utils.h"
  47. #include "clang/Lex/HeaderSearch.h"
  48. #include "clang/Lex/HeaderSearchOptions.h"
  49. #include "clang/Lex/Lexer.h"
  50. #include "clang/Lex/PPCallbacks.h"
  51. #include "clang/Lex/PreprocessingRecord.h"
  52. #include "clang/Lex/Preprocessor.h"
  53. #include "clang/Lex/PreprocessorOptions.h"
  54. #include "clang/Lex/Token.h"
  55. #include "clang/Sema/CodeCompleteConsumer.h"
  56. #include "clang/Sema/CodeCompleteOptions.h"
  57. #include "clang/Sema/Sema.h"
  58. #include "clang/Serialization/ASTBitCodes.h"
  59. #include "clang/Serialization/ASTReader.h"
  60. #include "clang/Serialization/ASTWriter.h"
  61. #include "clang/Serialization/ContinuousRangeMap.h"
  62. #include "clang/Serialization/InMemoryModuleCache.h"
  63. #include "clang/Serialization/ModuleFile.h"
  64. #include "clang/Serialization/PCHContainerOperations.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  68. #include "llvm/ADT/STLExtras.h"
  69. #include "llvm/ADT/ScopeExit.h"
  70. #include "llvm/ADT/SmallString.h"
  71. #include "llvm/ADT/SmallVector.h"
  72. #include "llvm/ADT/StringMap.h"
  73. #include "llvm/ADT/StringRef.h"
  74. #include "llvm/ADT/StringSet.h"
  75. #include "llvm/ADT/Twine.h"
  76. #include "llvm/ADT/iterator_range.h"
  77. #include "llvm/Bitstream/BitstreamWriter.h"
  78. #include "llvm/Support/Allocator.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/CrashRecoveryContext.h"
  81. #include "llvm/Support/DJB.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/ErrorOr.h"
  84. #include "llvm/Support/FileSystem.h"
  85. #include "llvm/Support/FileUtilities.h"
  86. #include "llvm/Support/MemoryBuffer.h"
  87. #include "llvm/Support/SaveAndRestore.h"
  88. #include "llvm/Support/Timer.h"
  89. #include "llvm/Support/VirtualFileSystem.h"
  90. #include "llvm/Support/raw_ostream.h"
  91. #include <algorithm>
  92. #include <atomic>
  93. #include <cassert>
  94. #include <cstdint>
  95. #include <cstdio>
  96. #include <cstdlib>
  97. #include <memory>
  98. #include <mutex>
  99. #include <optional>
  100. #include <string>
  101. #include <tuple>
  102. #include <utility>
  103. #include <vector>
  104. using namespace clang;
  105. using llvm::TimeRecord;
  106. namespace {
  107. class SimpleTimer {
  108. bool WantTiming;
  109. TimeRecord Start;
  110. std::string Output;
  111. public:
  112. explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
  113. if (WantTiming)
  114. Start = TimeRecord::getCurrentTime();
  115. }
  116. ~SimpleTimer() {
  117. if (WantTiming) {
  118. TimeRecord Elapsed = TimeRecord::getCurrentTime();
  119. Elapsed -= Start;
  120. llvm::errs() << Output << ':';
  121. Elapsed.print(Elapsed, llvm::errs());
  122. llvm::errs() << '\n';
  123. }
  124. }
  125. void setOutput(const Twine &Output) {
  126. if (WantTiming)
  127. this->Output = Output.str();
  128. }
  129. };
  130. } // namespace
  131. template <class T>
  132. static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
  133. if (!Val)
  134. return nullptr;
  135. return std::move(*Val);
  136. }
  137. template <class T>
  138. static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
  139. if (!Val)
  140. return false;
  141. Output = std::move(*Val);
  142. return true;
  143. }
  144. /// Get a source buffer for \p MainFilePath, handling all file-to-file
  145. /// and file-to-buffer remappings inside \p Invocation.
  146. static std::unique_ptr<llvm::MemoryBuffer>
  147. getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
  148. llvm::vfs::FileSystem *VFS,
  149. StringRef FilePath, bool isVolatile) {
  150. const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
  151. // Try to determine if the main file has been remapped, either from the
  152. // command line (to another file) or directly through the compiler
  153. // invocation (to a memory buffer).
  154. llvm::MemoryBuffer *Buffer = nullptr;
  155. std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
  156. auto FileStatus = VFS->status(FilePath);
  157. if (FileStatus) {
  158. llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
  159. // Check whether there is a file-file remapping of the main file
  160. for (const auto &RF : PreprocessorOpts.RemappedFiles) {
  161. std::string MPath(RF.first);
  162. auto MPathStatus = VFS->status(MPath);
  163. if (MPathStatus) {
  164. llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
  165. if (MainFileID == MID) {
  166. // We found a remapping. Try to load the resulting, remapped source.
  167. BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
  168. if (!BufferOwner)
  169. return nullptr;
  170. }
  171. }
  172. }
  173. // Check whether there is a file-buffer remapping. It supercedes the
  174. // file-file remapping.
  175. for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
  176. std::string MPath(RB.first);
  177. auto MPathStatus = VFS->status(MPath);
  178. if (MPathStatus) {
  179. llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
  180. if (MainFileID == MID) {
  181. // We found a remapping.
  182. BufferOwner.reset();
  183. Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
  184. }
  185. }
  186. }
  187. }
  188. // If the main source file was not remapped, load it now.
  189. if (!Buffer && !BufferOwner) {
  190. BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
  191. if (!BufferOwner)
  192. return nullptr;
  193. }
  194. if (BufferOwner)
  195. return BufferOwner;
  196. if (!Buffer)
  197. return nullptr;
  198. return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
  199. }
  200. struct ASTUnit::ASTWriterData {
  201. SmallString<128> Buffer;
  202. llvm::BitstreamWriter Stream;
  203. ASTWriter Writer;
  204. ASTWriterData(InMemoryModuleCache &ModuleCache)
  205. : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
  206. };
  207. void ASTUnit::clearFileLevelDecls() {
  208. FileDecls.clear();
  209. }
  210. /// After failing to build a precompiled preamble (due to
  211. /// errors in the source that occurs in the preamble), the number of
  212. /// reparses during which we'll skip even trying to precompile the
  213. /// preamble.
  214. const unsigned DefaultPreambleRebuildInterval = 5;
  215. /// Tracks the number of ASTUnit objects that are currently active.
  216. ///
  217. /// Used for debugging purposes only.
  218. static std::atomic<unsigned> ActiveASTUnitObjects;
  219. ASTUnit::ASTUnit(bool _MainFileIsAST)
  220. : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
  221. ShouldCacheCodeCompletionResults(false),
  222. IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
  223. UnsafeToFree(false) {
  224. if (getenv("LIBCLANG_OBJTRACKING"))
  225. fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
  226. }
  227. ASTUnit::~ASTUnit() {
  228. // If we loaded from an AST file, balance out the BeginSourceFile call.
  229. if (MainFileIsAST && getDiagnostics().getClient()) {
  230. getDiagnostics().getClient()->EndSourceFile();
  231. }
  232. clearFileLevelDecls();
  233. // Free the buffers associated with remapped files. We are required to
  234. // perform this operation here because we explicitly request that the
  235. // compiler instance *not* free these buffers for each invocation of the
  236. // parser.
  237. if (Invocation && OwnsRemappedFileBuffers) {
  238. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  239. for (const auto &RB : PPOpts.RemappedFileBuffers)
  240. delete RB.second;
  241. }
  242. ClearCachedCompletionResults();
  243. if (getenv("LIBCLANG_OBJTRACKING"))
  244. fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
  245. }
  246. void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
  247. this->PP = std::move(PP);
  248. }
  249. void ASTUnit::enableSourceFileDiagnostics() {
  250. assert(getDiagnostics().getClient() && Ctx &&
  251. "Bad context for source file");
  252. getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
  253. }
  254. /// Determine the set of code-completion contexts in which this
  255. /// declaration should be shown.
  256. static uint64_t getDeclShowContexts(const NamedDecl *ND,
  257. const LangOptions &LangOpts,
  258. bool &IsNestedNameSpecifier) {
  259. IsNestedNameSpecifier = false;
  260. if (isa<UsingShadowDecl>(ND))
  261. ND = ND->getUnderlyingDecl();
  262. if (!ND)
  263. return 0;
  264. uint64_t Contexts = 0;
  265. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
  266. isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
  267. isa<TypeAliasTemplateDecl>(ND)) {
  268. // Types can appear in these contexts.
  269. if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
  270. Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
  271. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  272. | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
  273. | (1LL << CodeCompletionContext::CCC_Statement)
  274. | (1LL << CodeCompletionContext::CCC_Type)
  275. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
  276. // In C++, types can appear in expressions contexts (for functional casts).
  277. if (LangOpts.CPlusPlus)
  278. Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
  279. // In Objective-C, message sends can send interfaces. In Objective-C++,
  280. // all types are available due to functional casts.
  281. if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
  282. Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
  283. // In Objective-C, you can only be a subclass of another Objective-C class
  284. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
  285. // Objective-C interfaces can be used in a class property expression.
  286. if (ID->getDefinition())
  287. Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
  288. Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
  289. }
  290. // Deal with tag names.
  291. if (isa<EnumDecl>(ND)) {
  292. Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
  293. // Part of the nested-name-specifier in C++0x.
  294. if (LangOpts.CPlusPlus11)
  295. IsNestedNameSpecifier = true;
  296. } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
  297. if (Record->isUnion())
  298. Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
  299. else
  300. Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
  301. if (LangOpts.CPlusPlus)
  302. IsNestedNameSpecifier = true;
  303. } else if (isa<ClassTemplateDecl>(ND))
  304. IsNestedNameSpecifier = true;
  305. } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  306. // Values can appear in these contexts.
  307. Contexts = (1LL << CodeCompletionContext::CCC_Statement)
  308. | (1LL << CodeCompletionContext::CCC_Expression)
  309. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
  310. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
  311. } else if (isa<ObjCProtocolDecl>(ND)) {
  312. Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
  313. } else if (isa<ObjCCategoryDecl>(ND)) {
  314. Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
  315. } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
  316. Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
  317. // Part of the nested-name-specifier.
  318. IsNestedNameSpecifier = true;
  319. }
  320. return Contexts;
  321. }
  322. void ASTUnit::CacheCodeCompletionResults() {
  323. if (!TheSema)
  324. return;
  325. SimpleTimer Timer(WantTiming);
  326. Timer.setOutput("Cache global code completions for " + getMainFileName());
  327. // Clear out the previous results.
  328. ClearCachedCompletionResults();
  329. // Gather the set of global code completions.
  330. using Result = CodeCompletionResult;
  331. SmallVector<Result, 8> Results;
  332. CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
  333. CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
  334. TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
  335. CCTUInfo, Results);
  336. // Translate global code completions into cached completions.
  337. llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
  338. CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
  339. for (auto &R : Results) {
  340. switch (R.Kind) {
  341. case Result::RK_Declaration: {
  342. bool IsNestedNameSpecifier = false;
  343. CachedCodeCompletionResult CachedResult;
  344. CachedResult.Completion = R.CreateCodeCompletionString(
  345. *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
  346. IncludeBriefCommentsInCodeCompletion);
  347. CachedResult.ShowInContexts = getDeclShowContexts(
  348. R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
  349. CachedResult.Priority = R.Priority;
  350. CachedResult.Kind = R.CursorKind;
  351. CachedResult.Availability = R.Availability;
  352. // Keep track of the type of this completion in an ASTContext-agnostic
  353. // way.
  354. QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
  355. if (UsageType.isNull()) {
  356. CachedResult.TypeClass = STC_Void;
  357. CachedResult.Type = 0;
  358. } else {
  359. CanQualType CanUsageType
  360. = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
  361. CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
  362. // Determine whether we have already seen this type. If so, we save
  363. // ourselves the work of formatting the type string by using the
  364. // temporary, CanQualType-based hash table to find the associated value.
  365. unsigned &TypeValue = CompletionTypes[CanUsageType];
  366. if (TypeValue == 0) {
  367. TypeValue = CompletionTypes.size();
  368. CachedCompletionTypes[QualType(CanUsageType).getAsString()]
  369. = TypeValue;
  370. }
  371. CachedResult.Type = TypeValue;
  372. }
  373. CachedCompletionResults.push_back(CachedResult);
  374. /// Handle nested-name-specifiers in C++.
  375. if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
  376. !R.StartsNestedNameSpecifier) {
  377. // The contexts in which a nested-name-specifier can appear in C++.
  378. uint64_t NNSContexts
  379. = (1LL << CodeCompletionContext::CCC_TopLevel)
  380. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  381. | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
  382. | (1LL << CodeCompletionContext::CCC_Statement)
  383. | (1LL << CodeCompletionContext::CCC_Expression)
  384. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
  385. | (1LL << CodeCompletionContext::CCC_EnumTag)
  386. | (1LL << CodeCompletionContext::CCC_UnionTag)
  387. | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
  388. | (1LL << CodeCompletionContext::CCC_Type)
  389. | (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
  390. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
  391. if (isa<NamespaceDecl>(R.Declaration) ||
  392. isa<NamespaceAliasDecl>(R.Declaration))
  393. NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
  394. if (uint64_t RemainingContexts
  395. = NNSContexts & ~CachedResult.ShowInContexts) {
  396. // If there any contexts where this completion can be a
  397. // nested-name-specifier but isn't already an option, create a
  398. // nested-name-specifier completion.
  399. R.StartsNestedNameSpecifier = true;
  400. CachedResult.Completion = R.CreateCodeCompletionString(
  401. *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
  402. IncludeBriefCommentsInCodeCompletion);
  403. CachedResult.ShowInContexts = RemainingContexts;
  404. CachedResult.Priority = CCP_NestedNameSpecifier;
  405. CachedResult.TypeClass = STC_Void;
  406. CachedResult.Type = 0;
  407. CachedCompletionResults.push_back(CachedResult);
  408. }
  409. }
  410. break;
  411. }
  412. case Result::RK_Keyword:
  413. case Result::RK_Pattern:
  414. // Ignore keywords and patterns; we don't care, since they are so
  415. // easily regenerated.
  416. break;
  417. case Result::RK_Macro: {
  418. CachedCodeCompletionResult CachedResult;
  419. CachedResult.Completion = R.CreateCodeCompletionString(
  420. *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
  421. IncludeBriefCommentsInCodeCompletion);
  422. CachedResult.ShowInContexts
  423. = (1LL << CodeCompletionContext::CCC_TopLevel)
  424. | (1LL << CodeCompletionContext::CCC_ObjCInterface)
  425. | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
  426. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  427. | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
  428. | (1LL << CodeCompletionContext::CCC_Statement)
  429. | (1LL << CodeCompletionContext::CCC_Expression)
  430. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
  431. | (1LL << CodeCompletionContext::CCC_MacroNameUse)
  432. | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
  433. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
  434. | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
  435. CachedResult.Priority = R.Priority;
  436. CachedResult.Kind = R.CursorKind;
  437. CachedResult.Availability = R.Availability;
  438. CachedResult.TypeClass = STC_Void;
  439. CachedResult.Type = 0;
  440. CachedCompletionResults.push_back(CachedResult);
  441. break;
  442. }
  443. }
  444. }
  445. // Save the current top-level hash value.
  446. CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
  447. }
  448. void ASTUnit::ClearCachedCompletionResults() {
  449. CachedCompletionResults.clear();
  450. CachedCompletionTypes.clear();
  451. CachedCompletionAllocator = nullptr;
  452. }
  453. namespace {
  454. /// Gathers information from ASTReader that will be used to initialize
  455. /// a Preprocessor.
  456. class ASTInfoCollector : public ASTReaderListener {
  457. Preprocessor &PP;
  458. ASTContext *Context;
  459. HeaderSearchOptions &HSOpts;
  460. PreprocessorOptions &PPOpts;
  461. LangOptions &LangOpt;
  462. std::shared_ptr<TargetOptions> &TargetOpts;
  463. IntrusiveRefCntPtr<TargetInfo> &Target;
  464. unsigned &Counter;
  465. bool InitializedLanguage = false;
  466. bool InitializedHeaderSearchPaths = false;
  467. public:
  468. ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
  469. HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
  470. LangOptions &LangOpt,
  471. std::shared_ptr<TargetOptions> &TargetOpts,
  472. IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
  473. : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
  474. LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
  475. Counter(Counter) {}
  476. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  477. bool AllowCompatibleDifferences) override {
  478. if (InitializedLanguage)
  479. return false;
  480. LangOpt = LangOpts;
  481. InitializedLanguage = true;
  482. updated();
  483. return false;
  484. }
  485. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  486. StringRef SpecificModuleCachePath,
  487. bool Complain) override {
  488. // Preserve previously set header search paths.
  489. llvm::SaveAndRestore X(this->HSOpts.UserEntries);
  490. llvm::SaveAndRestore Y(this->HSOpts.SystemHeaderPrefixes);
  491. llvm::SaveAndRestore Z(this->HSOpts.VFSOverlayFiles);
  492. this->HSOpts = HSOpts;
  493. return false;
  494. }
  495. bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts,
  496. bool Complain) override {
  497. if (InitializedHeaderSearchPaths)
  498. return false;
  499. this->HSOpts.UserEntries = HSOpts.UserEntries;
  500. this->HSOpts.SystemHeaderPrefixes = HSOpts.SystemHeaderPrefixes;
  501. this->HSOpts.VFSOverlayFiles = HSOpts.VFSOverlayFiles;
  502. // Initialize the FileManager. We can't do this in update(), since that
  503. // performs the initialization too late (once both target and language
  504. // options are read).
  505. PP.getFileManager().setVirtualFileSystem(createVFSFromOverlayFiles(
  506. HSOpts.VFSOverlayFiles, PP.getDiagnostics(),
  507. PP.getFileManager().getVirtualFileSystemPtr()));
  508. InitializedHeaderSearchPaths = true;
  509. return false;
  510. }
  511. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
  512. std::string &SuggestedPredefines) override {
  513. this->PPOpts = PPOpts;
  514. return false;
  515. }
  516. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  517. bool AllowCompatibleDifferences) override {
  518. // If we've already initialized the target, don't do it again.
  519. if (Target)
  520. return false;
  521. this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
  522. Target =
  523. TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
  524. updated();
  525. return false;
  526. }
  527. void ReadCounter(const serialization::ModuleFile &M,
  528. unsigned Value) override {
  529. Counter = Value;
  530. }
  531. private:
  532. void updated() {
  533. if (!Target || !InitializedLanguage)
  534. return;
  535. // Inform the target of the language options.
  536. //
  537. // FIXME: We shouldn't need to do this, the target should be immutable once
  538. // created. This complexity should be lifted elsewhere.
  539. Target->adjust(PP.getDiagnostics(), LangOpt);
  540. // Initialize the preprocessor.
  541. PP.Initialize(*Target);
  542. if (!Context)
  543. return;
  544. // Initialize the ASTContext
  545. Context->InitBuiltinTypes(*Target);
  546. // Adjust printing policy based on language options.
  547. Context->setPrintingPolicy(PrintingPolicy(LangOpt));
  548. // We didn't have access to the comment options when the ASTContext was
  549. // constructed, so register them now.
  550. Context->getCommentCommandTraits().registerCommentOptions(
  551. LangOpt.CommentOpts);
  552. }
  553. };
  554. /// Diagnostic consumer that saves each diagnostic it is given.
  555. class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
  556. SmallVectorImpl<StoredDiagnostic> *StoredDiags;
  557. SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
  558. bool CaptureNonErrorsFromIncludes = true;
  559. const LangOptions *LangOpts = nullptr;
  560. SourceManager *SourceMgr = nullptr;
  561. public:
  562. FilterAndStoreDiagnosticConsumer(
  563. SmallVectorImpl<StoredDiagnostic> *StoredDiags,
  564. SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags,
  565. bool CaptureNonErrorsFromIncludes)
  566. : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
  567. CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
  568. assert((StoredDiags || StandaloneDiags) &&
  569. "No output collections were passed to StoredDiagnosticConsumer.");
  570. }
  571. void BeginSourceFile(const LangOptions &LangOpts,
  572. const Preprocessor *PP = nullptr) override {
  573. this->LangOpts = &LangOpts;
  574. if (PP)
  575. SourceMgr = &PP->getSourceManager();
  576. }
  577. void HandleDiagnostic(DiagnosticsEngine::Level Level,
  578. const Diagnostic &Info) override;
  579. };
  580. /// RAII object that optionally captures and filters diagnostics, if
  581. /// there is no diagnostic client to capture them already.
  582. class CaptureDroppedDiagnostics {
  583. DiagnosticsEngine &Diags;
  584. FilterAndStoreDiagnosticConsumer Client;
  585. DiagnosticConsumer *PreviousClient = nullptr;
  586. std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
  587. public:
  588. CaptureDroppedDiagnostics(
  589. CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
  590. SmallVectorImpl<StoredDiagnostic> *StoredDiags,
  591. SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
  592. : Diags(Diags),
  593. Client(StoredDiags, StandaloneDiags,
  594. CaptureDiagnostics !=
  595. CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) {
  596. if (CaptureDiagnostics != CaptureDiagsKind::None ||
  597. Diags.getClient() == nullptr) {
  598. OwningPreviousClient = Diags.takeClient();
  599. PreviousClient = Diags.getClient();
  600. Diags.setClient(&Client, false);
  601. }
  602. }
  603. ~CaptureDroppedDiagnostics() {
  604. if (Diags.getClient() == &Client)
  605. Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
  606. }
  607. };
  608. } // namespace
  609. static ASTUnit::StandaloneDiagnostic
  610. makeStandaloneDiagnostic(const LangOptions &LangOpts,
  611. const StoredDiagnostic &InDiag);
  612. static bool isInMainFile(const clang::Diagnostic &D) {
  613. if (!D.hasSourceManager() || !D.getLocation().isValid())
  614. return false;
  615. auto &M = D.getSourceManager();
  616. return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
  617. }
  618. void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
  619. DiagnosticsEngine::Level Level, const Diagnostic &Info) {
  620. // Default implementation (Warnings/errors count).
  621. DiagnosticConsumer::HandleDiagnostic(Level, Info);
  622. // Only record the diagnostic if it's part of the source manager we know
  623. // about. This effectively drops diagnostics from modules we're building.
  624. // FIXME: In the long run, ee don't want to drop source managers from modules.
  625. if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
  626. if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning &&
  627. !isInMainFile(Info)) {
  628. return;
  629. }
  630. StoredDiagnostic *ResultDiag = nullptr;
  631. if (StoredDiags) {
  632. StoredDiags->emplace_back(Level, Info);
  633. ResultDiag = &StoredDiags->back();
  634. }
  635. if (StandaloneDiags) {
  636. std::optional<StoredDiagnostic> StoredDiag;
  637. if (!ResultDiag) {
  638. StoredDiag.emplace(Level, Info);
  639. ResultDiag = &*StoredDiag;
  640. }
  641. StandaloneDiags->push_back(
  642. makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
  643. }
  644. }
  645. }
  646. IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
  647. return Reader;
  648. }
  649. ASTMutationListener *ASTUnit::getASTMutationListener() {
  650. if (WriterData)
  651. return &WriterData->Writer;
  652. return nullptr;
  653. }
  654. ASTDeserializationListener *ASTUnit::getDeserializationListener() {
  655. if (WriterData)
  656. return &WriterData->Writer;
  657. return nullptr;
  658. }
  659. std::unique_ptr<llvm::MemoryBuffer>
  660. ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
  661. assert(FileMgr);
  662. auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
  663. if (Buffer)
  664. return std::move(*Buffer);
  665. if (ErrorStr)
  666. *ErrorStr = Buffer.getError().message();
  667. return nullptr;
  668. }
  669. /// Configure the diagnostics object for use with ASTUnit.
  670. void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  671. ASTUnit &AST,
  672. CaptureDiagsKind CaptureDiagnostics) {
  673. assert(Diags.get() && "no DiagnosticsEngine was provided");
  674. if (CaptureDiagnostics != CaptureDiagsKind::None)
  675. Diags->setClient(new FilterAndStoreDiagnosticConsumer(
  676. &AST.StoredDiagnostics, nullptr,
  677. CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes));
  678. }
  679. std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
  680. const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
  681. WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  682. const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
  683. bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
  684. bool AllowASTWithCompilerErrors, bool UserFilesAreVolatile,
  685. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  686. std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
  687. // Recover resources if we crash before exiting this method.
  688. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  689. ASTUnitCleanup(AST.get());
  690. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  691. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  692. DiagCleanup(Diags.get());
  693. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  694. AST->LangOpts = std::make_shared<LangOptions>();
  695. AST->OnlyLocalDecls = OnlyLocalDecls;
  696. AST->CaptureDiagnostics = CaptureDiagnostics;
  697. AST->Diagnostics = Diags;
  698. AST->FileMgr = new FileManager(FileSystemOpts, VFS);
  699. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  700. AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
  701. AST->getFileManager(),
  702. UserFilesAreVolatile);
  703. AST->ModuleCache = new InMemoryModuleCache;
  704. AST->HSOpts = std::make_shared<HeaderSearchOptions>();
  705. AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormat());
  706. AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
  707. AST->getSourceManager(),
  708. AST->getDiagnostics(),
  709. AST->getLangOpts(),
  710. /*Target=*/nullptr));
  711. AST->PPOpts = std::make_shared<PreprocessorOptions>();
  712. // Gather Info for preprocessor construction later on.
  713. HeaderSearch &HeaderInfo = *AST->HeaderInfo;
  714. unsigned Counter;
  715. AST->PP = std::make_shared<Preprocessor>(
  716. AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
  717. AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
  718. /*IILookup=*/nullptr,
  719. /*OwnsHeaderSearch=*/false);
  720. Preprocessor &PP = *AST->PP;
  721. if (ToLoad >= LoadASTOnly)
  722. AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
  723. PP.getIdentifierTable(), PP.getSelectorTable(),
  724. PP.getBuiltinInfo(),
  725. AST->getTranslationUnitKind());
  726. DisableValidationForModuleKind disableValid =
  727. DisableValidationForModuleKind::None;
  728. if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
  729. disableValid = DisableValidationForModuleKind::All;
  730. AST->Reader = new ASTReader(
  731. PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
  732. /*isysroot=*/"",
  733. /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors);
  734. AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
  735. *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
  736. AST->TargetOpts, AST->Target, Counter));
  737. // Attach the AST reader to the AST context as an external AST
  738. // source, so that declarations will be deserialized from the
  739. // AST file as needed.
  740. // We need the external source to be set up before we read the AST, because
  741. // eagerly-deserialized declarations may use it.
  742. if (AST->Ctx)
  743. AST->Ctx->setExternalSource(AST->Reader);
  744. switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
  745. SourceLocation(), ASTReader::ARR_None)) {
  746. case ASTReader::Success:
  747. break;
  748. case ASTReader::Failure:
  749. case ASTReader::Missing:
  750. case ASTReader::OutOfDate:
  751. case ASTReader::VersionMismatch:
  752. case ASTReader::ConfigurationMismatch:
  753. case ASTReader::HadErrors:
  754. AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
  755. return nullptr;
  756. }
  757. AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
  758. PP.setCounterValue(Counter);
  759. // Create an AST consumer, even though it isn't used.
  760. if (ToLoad >= LoadASTOnly)
  761. AST->Consumer.reset(new ASTConsumer);
  762. // Create a semantic analysis object and tell the AST reader about it.
  763. if (ToLoad >= LoadEverything) {
  764. AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
  765. AST->TheSema->Initialize();
  766. AST->Reader->InitializeSema(*AST->TheSema);
  767. }
  768. // Tell the diagnostic client that we have started a source file.
  769. AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
  770. return AST;
  771. }
  772. /// Add the given macro to the hash of all top-level entities.
  773. static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
  774. Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
  775. }
  776. namespace {
  777. /// Preprocessor callback class that updates a hash value with the names
  778. /// of all macros that have been defined by the translation unit.
  779. class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
  780. unsigned &Hash;
  781. public:
  782. explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
  783. void MacroDefined(const Token &MacroNameTok,
  784. const MacroDirective *MD) override {
  785. AddDefinedMacroToHash(MacroNameTok, Hash);
  786. }
  787. };
  788. } // namespace
  789. /// Add the given declaration to the hash of all top-level entities.
  790. static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
  791. if (!D)
  792. return;
  793. DeclContext *DC = D->getDeclContext();
  794. if (!DC)
  795. return;
  796. if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
  797. return;
  798. if (const auto *ND = dyn_cast<NamedDecl>(D)) {
  799. if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
  800. // For an unscoped enum include the enumerators in the hash since they
  801. // enter the top-level namespace.
  802. if (!EnumD->isScoped()) {
  803. for (const auto *EI : EnumD->enumerators()) {
  804. if (EI->getIdentifier())
  805. Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
  806. }
  807. }
  808. }
  809. if (ND->getIdentifier())
  810. Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
  811. else if (DeclarationName Name = ND->getDeclName()) {
  812. std::string NameStr = Name.getAsString();
  813. Hash = llvm::djbHash(NameStr, Hash);
  814. }
  815. return;
  816. }
  817. if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
  818. if (const Module *Mod = ImportD->getImportedModule()) {
  819. std::string ModName = Mod->getFullModuleName();
  820. Hash = llvm::djbHash(ModName, Hash);
  821. }
  822. return;
  823. }
  824. }
  825. namespace {
  826. class TopLevelDeclTrackerConsumer : public ASTConsumer {
  827. ASTUnit &Unit;
  828. unsigned &Hash;
  829. public:
  830. TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
  831. : Unit(_Unit), Hash(Hash) {
  832. Hash = 0;
  833. }
  834. void handleTopLevelDecl(Decl *D) {
  835. if (!D)
  836. return;
  837. // FIXME: Currently ObjC method declarations are incorrectly being
  838. // reported as top-level declarations, even though their DeclContext
  839. // is the containing ObjC @interface/@implementation. This is a
  840. // fundamental problem in the parser right now.
  841. if (isa<ObjCMethodDecl>(D))
  842. return;
  843. AddTopLevelDeclarationToHash(D, Hash);
  844. Unit.addTopLevelDecl(D);
  845. handleFileLevelDecl(D);
  846. }
  847. void handleFileLevelDecl(Decl *D) {
  848. Unit.addFileLevelDecl(D);
  849. if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
  850. for (auto *I : NSD->decls())
  851. handleFileLevelDecl(I);
  852. }
  853. }
  854. bool HandleTopLevelDecl(DeclGroupRef D) override {
  855. for (auto *TopLevelDecl : D)
  856. handleTopLevelDecl(TopLevelDecl);
  857. return true;
  858. }
  859. // We're not interested in "interesting" decls.
  860. void HandleInterestingDecl(DeclGroupRef) override {}
  861. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  862. for (auto *TopLevelDecl : D)
  863. handleTopLevelDecl(TopLevelDecl);
  864. }
  865. ASTMutationListener *GetASTMutationListener() override {
  866. return Unit.getASTMutationListener();
  867. }
  868. ASTDeserializationListener *GetASTDeserializationListener() override {
  869. return Unit.getDeserializationListener();
  870. }
  871. };
  872. class TopLevelDeclTrackerAction : public ASTFrontendAction {
  873. public:
  874. ASTUnit &Unit;
  875. std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
  876. StringRef InFile) override {
  877. CI.getPreprocessor().addPPCallbacks(
  878. std::make_unique<MacroDefinitionTrackerPPCallbacks>(
  879. Unit.getCurrentTopLevelHashValue()));
  880. return std::make_unique<TopLevelDeclTrackerConsumer>(
  881. Unit, Unit.getCurrentTopLevelHashValue());
  882. }
  883. public:
  884. TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
  885. bool hasCodeCompletionSupport() const override { return false; }
  886. TranslationUnitKind getTranslationUnitKind() override {
  887. return Unit.getTranslationUnitKind();
  888. }
  889. };
  890. class ASTUnitPreambleCallbacks : public PreambleCallbacks {
  891. public:
  892. unsigned getHash() const { return Hash; }
  893. std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
  894. std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
  895. return std::move(TopLevelDeclIDs);
  896. }
  897. void AfterPCHEmitted(ASTWriter &Writer) override {
  898. TopLevelDeclIDs.reserve(TopLevelDecls.size());
  899. for (const auto *D : TopLevelDecls) {
  900. // Invalid top-level decls may not have been serialized.
  901. if (D->isInvalidDecl())
  902. continue;
  903. TopLevelDeclIDs.push_back(Writer.getDeclID(D));
  904. }
  905. }
  906. void HandleTopLevelDecl(DeclGroupRef DG) override {
  907. for (auto *D : DG) {
  908. // FIXME: Currently ObjC method declarations are incorrectly being
  909. // reported as top-level declarations, even though their DeclContext
  910. // is the containing ObjC @interface/@implementation. This is a
  911. // fundamental problem in the parser right now.
  912. if (isa<ObjCMethodDecl>(D))
  913. continue;
  914. AddTopLevelDeclarationToHash(D, Hash);
  915. TopLevelDecls.push_back(D);
  916. }
  917. }
  918. std::unique_ptr<PPCallbacks> createPPCallbacks() override {
  919. return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
  920. }
  921. private:
  922. unsigned Hash = 0;
  923. std::vector<Decl *> TopLevelDecls;
  924. std::vector<serialization::DeclID> TopLevelDeclIDs;
  925. llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
  926. };
  927. } // namespace
  928. static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
  929. return StoredDiag.getLocation().isValid();
  930. }
  931. static void
  932. checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
  933. // Get rid of stored diagnostics except the ones from the driver which do not
  934. // have a source location.
  935. llvm::erase_if(StoredDiags, isNonDriverDiag);
  936. }
  937. static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
  938. StoredDiagnostics,
  939. SourceManager &SM) {
  940. // The stored diagnostic has the old source manager in it; update
  941. // the locations to refer into the new source manager. Since we've
  942. // been careful to make sure that the source manager's state
  943. // before and after are identical, so that we can reuse the source
  944. // location itself.
  945. for (auto &SD : StoredDiagnostics) {
  946. if (SD.getLocation().isValid()) {
  947. FullSourceLoc Loc(SD.getLocation(), SM);
  948. SD.setLocation(Loc);
  949. }
  950. }
  951. }
  952. /// Parse the source file into a translation unit using the given compiler
  953. /// invocation, replacing the current translation unit.
  954. ///
  955. /// \returns True if a failure occurred that causes the ASTUnit not to
  956. /// contain any translation-unit information, false otherwise.
  957. bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  958. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
  959. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  960. if (!Invocation)
  961. return true;
  962. if (VFS && FileMgr)
  963. assert(VFS == &FileMgr->getVirtualFileSystem() &&
  964. "VFS passed to Parse and VFS in FileMgr are different");
  965. auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
  966. if (OverrideMainBuffer) {
  967. assert(Preamble &&
  968. "No preamble was built, but OverrideMainBuffer is not null");
  969. Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
  970. // VFS may have changed...
  971. }
  972. // Create the compiler instance to use for building the AST.
  973. std::unique_ptr<CompilerInstance> Clang(
  974. new CompilerInstance(std::move(PCHContainerOps)));
  975. // Clean up on error, disengage it if the function returns successfully.
  976. auto CleanOnError = llvm::make_scope_exit([&]() {
  977. // Remove the overridden buffer we used for the preamble.
  978. SavedMainFileBuffer = nullptr;
  979. // Keep the ownership of the data in the ASTUnit because the client may
  980. // want to see the diagnostics.
  981. transferASTDataFromCompilerInstance(*Clang);
  982. FailedParseDiagnostics.swap(StoredDiagnostics);
  983. StoredDiagnostics.clear();
  984. NumStoredDiagnosticsFromDriver = 0;
  985. });
  986. // Ensure that Clang has a FileManager with the right VFS, which may have
  987. // changed above in AddImplicitPreamble. If VFS is nullptr, rely on
  988. // createFileManager to create one.
  989. if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
  990. Clang->setFileManager(&*FileMgr);
  991. else
  992. FileMgr = Clang->createFileManager(std::move(VFS));
  993. // Recover resources if we crash before exiting this method.
  994. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  995. CICleanup(Clang.get());
  996. Clang->setInvocation(CCInvocation);
  997. OriginalSourceFile =
  998. std::string(Clang->getFrontendOpts().Inputs[0].getFile());
  999. // Set up diagnostics, capturing any diagnostics that would
  1000. // otherwise be dropped.
  1001. Clang->setDiagnostics(&getDiagnostics());
  1002. // Create the target instance.
  1003. if (!Clang->createTarget())
  1004. return true;
  1005. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1006. "Invocation must have exactly one source file!");
  1007. assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
  1008. InputKind::Source &&
  1009. "FIXME: AST inputs not yet supported here!");
  1010. assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
  1011. Language::LLVM_IR &&
  1012. "IR inputs not support here!");
  1013. // Configure the various subsystems.
  1014. LangOpts = Clang->getInvocation().LangOpts;
  1015. FileSystemOpts = Clang->getFileSystemOpts();
  1016. ResetForParse();
  1017. SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
  1018. UserFilesAreVolatile);
  1019. if (!OverrideMainBuffer) {
  1020. checkAndRemoveNonDriverDiags(StoredDiagnostics);
  1021. TopLevelDeclsInPreamble.clear();
  1022. }
  1023. // Create the source manager.
  1024. Clang->setSourceManager(&getSourceManager());
  1025. // If the main file has been overridden due to the use of a preamble,
  1026. // make that override happen and introduce the preamble.
  1027. if (OverrideMainBuffer) {
  1028. // The stored diagnostic has the old source manager in it; update
  1029. // the locations to refer into the new source manager. Since we've
  1030. // been careful to make sure that the source manager's state
  1031. // before and after are identical, so that we can reuse the source
  1032. // location itself.
  1033. checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
  1034. // Keep track of the override buffer;
  1035. SavedMainFileBuffer = std::move(OverrideMainBuffer);
  1036. }
  1037. std::unique_ptr<TopLevelDeclTrackerAction> Act(
  1038. new TopLevelDeclTrackerAction(*this));
  1039. // Recover resources if we crash before exiting this method.
  1040. llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
  1041. ActCleanup(Act.get());
  1042. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
  1043. return true;
  1044. if (SavedMainFileBuffer)
  1045. TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
  1046. PreambleDiagnostics, StoredDiagnostics);
  1047. else
  1048. PreambleSrcLocCache.clear();
  1049. if (llvm::Error Err = Act->Execute()) {
  1050. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  1051. return true;
  1052. }
  1053. transferASTDataFromCompilerInstance(*Clang);
  1054. Act->EndSourceFile();
  1055. FailedParseDiagnostics.clear();
  1056. CleanOnError.release();
  1057. return false;
  1058. }
  1059. static std::pair<unsigned, unsigned>
  1060. makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
  1061. const LangOptions &LangOpts) {
  1062. CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
  1063. unsigned Offset = SM.getFileOffset(FileRange.getBegin());
  1064. unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
  1065. return std::make_pair(Offset, EndOffset);
  1066. }
  1067. static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
  1068. const LangOptions &LangOpts,
  1069. const FixItHint &InFix) {
  1070. ASTUnit::StandaloneFixIt OutFix;
  1071. OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
  1072. OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
  1073. LangOpts);
  1074. OutFix.CodeToInsert = InFix.CodeToInsert;
  1075. OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
  1076. return OutFix;
  1077. }
  1078. static ASTUnit::StandaloneDiagnostic
  1079. makeStandaloneDiagnostic(const LangOptions &LangOpts,
  1080. const StoredDiagnostic &InDiag) {
  1081. ASTUnit::StandaloneDiagnostic OutDiag;
  1082. OutDiag.ID = InDiag.getID();
  1083. OutDiag.Level = InDiag.getLevel();
  1084. OutDiag.Message = std::string(InDiag.getMessage());
  1085. OutDiag.LocOffset = 0;
  1086. if (InDiag.getLocation().isInvalid())
  1087. return OutDiag;
  1088. const SourceManager &SM = InDiag.getLocation().getManager();
  1089. SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
  1090. OutDiag.Filename = std::string(SM.getFilename(FileLoc));
  1091. if (OutDiag.Filename.empty())
  1092. return OutDiag;
  1093. OutDiag.LocOffset = SM.getFileOffset(FileLoc);
  1094. for (const auto &Range : InDiag.getRanges())
  1095. OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
  1096. for (const auto &FixIt : InDiag.getFixIts())
  1097. OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
  1098. return OutDiag;
  1099. }
  1100. /// Attempt to build or re-use a precompiled preamble when (re-)parsing
  1101. /// the source file.
  1102. ///
  1103. /// This routine will compute the preamble of the main source file. If a
  1104. /// non-trivial preamble is found, it will precompile that preamble into a
  1105. /// precompiled header so that the precompiled preamble can be used to reduce
  1106. /// reparsing time. If a precompiled preamble has already been constructed,
  1107. /// this routine will determine if it is still valid and, if so, avoid
  1108. /// rebuilding the precompiled preamble.
  1109. ///
  1110. /// \param AllowRebuild When true (the default), this routine is
  1111. /// allowed to rebuild the precompiled preamble if it is found to be
  1112. /// out-of-date.
  1113. ///
  1114. /// \param MaxLines When non-zero, the maximum number of lines that
  1115. /// can occur within the preamble.
  1116. ///
  1117. /// \returns If the precompiled preamble can be used, returns a newly-allocated
  1118. /// buffer that should be used in place of the main file when doing so.
  1119. /// Otherwise, returns a NULL pointer.
  1120. std::unique_ptr<llvm::MemoryBuffer>
  1121. ASTUnit::getMainBufferWithPrecompiledPreamble(
  1122. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1123. CompilerInvocation &PreambleInvocationIn,
  1124. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
  1125. unsigned MaxLines) {
  1126. auto MainFilePath =
  1127. PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
  1128. std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
  1129. getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
  1130. MainFilePath, UserFilesAreVolatile);
  1131. if (!MainFileBuffer)
  1132. return nullptr;
  1133. PreambleBounds Bounds = ComputePreambleBounds(
  1134. *PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
  1135. if (!Bounds.Size)
  1136. return nullptr;
  1137. if (Preamble) {
  1138. if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
  1139. *VFS)) {
  1140. // Okay! We can re-use the precompiled preamble.
  1141. // Set the state of the diagnostic object to mimic its state
  1142. // after parsing the preamble.
  1143. getDiagnostics().Reset();
  1144. ProcessWarningOptions(getDiagnostics(),
  1145. PreambleInvocationIn.getDiagnosticOpts());
  1146. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  1147. PreambleRebuildCountdown = 1;
  1148. return MainFileBuffer;
  1149. } else {
  1150. Preamble.reset();
  1151. PreambleDiagnostics.clear();
  1152. TopLevelDeclsInPreamble.clear();
  1153. PreambleSrcLocCache.clear();
  1154. PreambleRebuildCountdown = 1;
  1155. }
  1156. }
  1157. // If the preamble rebuild counter > 1, it's because we previously
  1158. // failed to build a preamble and we're not yet ready to try
  1159. // again. Decrement the counter and return a failure.
  1160. if (PreambleRebuildCountdown > 1) {
  1161. --PreambleRebuildCountdown;
  1162. return nullptr;
  1163. }
  1164. assert(!Preamble && "No Preamble should be stored at that point");
  1165. // If we aren't allowed to rebuild the precompiled preamble, just
  1166. // return now.
  1167. if (!AllowRebuild)
  1168. return nullptr;
  1169. ++PreambleCounter;
  1170. SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
  1171. SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
  1172. ASTUnitPreambleCallbacks Callbacks;
  1173. {
  1174. std::optional<CaptureDroppedDiagnostics> Capture;
  1175. if (CaptureDiagnostics != CaptureDiagsKind::None)
  1176. Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
  1177. &NewPreambleDiagsStandalone);
  1178. // We did not previously compute a preamble, or it can't be reused anyway.
  1179. SimpleTimer PreambleTimer(WantTiming);
  1180. PreambleTimer.setOutput("Precompiling preamble");
  1181. const bool PreviousSkipFunctionBodies =
  1182. PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
  1183. if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
  1184. PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
  1185. llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
  1186. PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
  1187. PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
  1188. PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
  1189. PreviousSkipFunctionBodies;
  1190. if (NewPreamble) {
  1191. Preamble = std::move(*NewPreamble);
  1192. PreambleRebuildCountdown = 1;
  1193. } else {
  1194. switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
  1195. case BuildPreambleError::CouldntCreateTempFile:
  1196. // Try again next time.
  1197. PreambleRebuildCountdown = 1;
  1198. return nullptr;
  1199. case BuildPreambleError::CouldntCreateTargetInfo:
  1200. case BuildPreambleError::BeginSourceFileFailed:
  1201. case BuildPreambleError::CouldntEmitPCH:
  1202. case BuildPreambleError::BadInputs:
  1203. // These erros are more likely to repeat, retry after some period.
  1204. PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
  1205. return nullptr;
  1206. }
  1207. llvm_unreachable("unexpected BuildPreambleError");
  1208. }
  1209. }
  1210. assert(Preamble && "Preamble wasn't built");
  1211. TopLevelDecls.clear();
  1212. TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
  1213. PreambleTopLevelHashValue = Callbacks.getHash();
  1214. NumWarningsInPreamble = getDiagnostics().getNumWarnings();
  1215. checkAndRemoveNonDriverDiags(NewPreambleDiags);
  1216. StoredDiagnostics = std::move(NewPreambleDiags);
  1217. PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
  1218. // If the hash of top-level entities differs from the hash of the top-level
  1219. // entities the last time we rebuilt the preamble, clear out the completion
  1220. // cache.
  1221. if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
  1222. CompletionCacheTopLevelHashValue = 0;
  1223. PreambleTopLevelHashValue = CurrentTopLevelHashValue;
  1224. }
  1225. return MainFileBuffer;
  1226. }
  1227. void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
  1228. assert(Preamble && "Should only be called when preamble was built");
  1229. std::vector<Decl *> Resolved;
  1230. Resolved.reserve(TopLevelDeclsInPreamble.size());
  1231. ExternalASTSource &Source = *getASTContext().getExternalSource();
  1232. for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
  1233. // Resolve the declaration ID to an actual declaration, possibly
  1234. // deserializing the declaration in the process.
  1235. if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
  1236. Resolved.push_back(D);
  1237. }
  1238. TopLevelDeclsInPreamble.clear();
  1239. TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
  1240. }
  1241. void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
  1242. // Steal the created target, context, and preprocessor if they have been
  1243. // created.
  1244. assert(CI.hasInvocation() && "missing invocation");
  1245. LangOpts = CI.getInvocation().LangOpts;
  1246. TheSema = CI.takeSema();
  1247. Consumer = CI.takeASTConsumer();
  1248. if (CI.hasASTContext())
  1249. Ctx = &CI.getASTContext();
  1250. if (CI.hasPreprocessor())
  1251. PP = CI.getPreprocessorPtr();
  1252. CI.setSourceManager(nullptr);
  1253. CI.setFileManager(nullptr);
  1254. if (CI.hasTarget())
  1255. Target = &CI.getTarget();
  1256. Reader = CI.getASTReader();
  1257. HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
  1258. }
  1259. StringRef ASTUnit::getMainFileName() const {
  1260. if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
  1261. const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
  1262. if (Input.isFile())
  1263. return Input.getFile();
  1264. else
  1265. return Input.getBuffer().getBufferIdentifier();
  1266. }
  1267. if (SourceMgr) {
  1268. if (const FileEntry *
  1269. FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
  1270. return FE->getName();
  1271. }
  1272. return {};
  1273. }
  1274. StringRef ASTUnit::getASTFileName() const {
  1275. if (!isMainFileAST())
  1276. return {};
  1277. serialization::ModuleFile &
  1278. Mod = Reader->getModuleManager().getPrimaryModule();
  1279. return Mod.FileName;
  1280. }
  1281. std::unique_ptr<ASTUnit>
  1282. ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
  1283. IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  1284. CaptureDiagsKind CaptureDiagnostics,
  1285. bool UserFilesAreVolatile) {
  1286. std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
  1287. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1288. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
  1289. createVFSFromCompilerInvocation(*CI, *Diags);
  1290. AST->Diagnostics = Diags;
  1291. AST->FileSystemOpts = CI->getFileSystemOpts();
  1292. AST->Invocation = std::move(CI);
  1293. AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
  1294. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  1295. AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
  1296. UserFilesAreVolatile);
  1297. AST->ModuleCache = new InMemoryModuleCache;
  1298. return AST;
  1299. }
  1300. ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
  1301. std::shared_ptr<CompilerInvocation> CI,
  1302. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1303. IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
  1304. ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
  1305. bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
  1306. unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
  1307. bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
  1308. assert(CI && "A CompilerInvocation is required");
  1309. std::unique_ptr<ASTUnit> OwnAST;
  1310. ASTUnit *AST = Unit;
  1311. if (!AST) {
  1312. // Create the AST unit.
  1313. OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
  1314. AST = OwnAST.get();
  1315. if (!AST)
  1316. return nullptr;
  1317. }
  1318. if (!ResourceFilesPath.empty()) {
  1319. // Override the resources path.
  1320. CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
  1321. }
  1322. AST->OnlyLocalDecls = OnlyLocalDecls;
  1323. AST->CaptureDiagnostics = CaptureDiagnostics;
  1324. if (PrecompilePreambleAfterNParses > 0)
  1325. AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
  1326. AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
  1327. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1328. AST->IncludeBriefCommentsInCodeCompletion = false;
  1329. // Recover resources if we crash before exiting this method.
  1330. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1331. ASTUnitCleanup(OwnAST.get());
  1332. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  1333. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  1334. DiagCleanup(Diags.get());
  1335. // We'll manage file buffers ourselves.
  1336. CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1337. CI->getFrontendOpts().DisableFree = false;
  1338. ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
  1339. // Create the compiler instance to use for building the AST.
  1340. std::unique_ptr<CompilerInstance> Clang(
  1341. new CompilerInstance(std::move(PCHContainerOps)));
  1342. // Recover resources if we crash before exiting this method.
  1343. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1344. CICleanup(Clang.get());
  1345. Clang->setInvocation(std::move(CI));
  1346. AST->OriginalSourceFile =
  1347. std::string(Clang->getFrontendOpts().Inputs[0].getFile());
  1348. // Set up diagnostics, capturing any diagnostics that would
  1349. // otherwise be dropped.
  1350. Clang->setDiagnostics(&AST->getDiagnostics());
  1351. // Create the target instance.
  1352. if (!Clang->createTarget())
  1353. return nullptr;
  1354. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1355. "Invocation must have exactly one source file!");
  1356. assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
  1357. InputKind::Source &&
  1358. "FIXME: AST inputs not yet supported here!");
  1359. assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
  1360. Language::LLVM_IR &&
  1361. "IR inputs not support here!");
  1362. // Configure the various subsystems.
  1363. AST->TheSema.reset();
  1364. AST->Ctx = nullptr;
  1365. AST->PP = nullptr;
  1366. AST->Reader = nullptr;
  1367. // Create a file manager object to provide access to and cache the filesystem.
  1368. Clang->setFileManager(&AST->getFileManager());
  1369. // Create the source manager.
  1370. Clang->setSourceManager(&AST->getSourceManager());
  1371. FrontendAction *Act = Action;
  1372. std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
  1373. if (!Act) {
  1374. TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
  1375. Act = TrackerAct.get();
  1376. }
  1377. // Recover resources if we crash before exiting this method.
  1378. llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
  1379. ActCleanup(TrackerAct.get());
  1380. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
  1381. AST->transferASTDataFromCompilerInstance(*Clang);
  1382. if (OwnAST && ErrAST)
  1383. ErrAST->swap(OwnAST);
  1384. return nullptr;
  1385. }
  1386. if (Persistent && !TrackerAct) {
  1387. Clang->getPreprocessor().addPPCallbacks(
  1388. std::make_unique<MacroDefinitionTrackerPPCallbacks>(
  1389. AST->getCurrentTopLevelHashValue()));
  1390. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  1391. if (Clang->hasASTConsumer())
  1392. Consumers.push_back(Clang->takeASTConsumer());
  1393. Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
  1394. *AST, AST->getCurrentTopLevelHashValue()));
  1395. Clang->setASTConsumer(
  1396. std::make_unique<MultiplexConsumer>(std::move(Consumers)));
  1397. }
  1398. if (llvm::Error Err = Act->Execute()) {
  1399. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  1400. AST->transferASTDataFromCompilerInstance(*Clang);
  1401. if (OwnAST && ErrAST)
  1402. ErrAST->swap(OwnAST);
  1403. return nullptr;
  1404. }
  1405. // Steal the created target, context, and preprocessor.
  1406. AST->transferASTDataFromCompilerInstance(*Clang);
  1407. Act->EndSourceFile();
  1408. if (OwnAST)
  1409. return OwnAST.release();
  1410. else
  1411. return AST;
  1412. }
  1413. bool ASTUnit::LoadFromCompilerInvocation(
  1414. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1415. unsigned PrecompilePreambleAfterNParses,
  1416. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  1417. if (!Invocation)
  1418. return true;
  1419. assert(VFS && "VFS is null");
  1420. // We'll manage file buffers ourselves.
  1421. Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1422. Invocation->getFrontendOpts().DisableFree = false;
  1423. getDiagnostics().Reset();
  1424. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1425. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
  1426. if (PrecompilePreambleAfterNParses > 0) {
  1427. PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
  1428. OverrideMainBuffer =
  1429. getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
  1430. getDiagnostics().Reset();
  1431. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1432. }
  1433. SimpleTimer ParsingTimer(WantTiming);
  1434. ParsingTimer.setOutput("Parsing " + getMainFileName());
  1435. // Recover resources if we crash before exiting this method.
  1436. llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
  1437. MemBufferCleanup(OverrideMainBuffer.get());
  1438. return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
  1439. }
  1440. std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
  1441. std::shared_ptr<CompilerInvocation> CI,
  1442. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1443. IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
  1444. bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
  1445. unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
  1446. bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
  1447. bool UserFilesAreVolatile) {
  1448. // Create the AST unit.
  1449. std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
  1450. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1451. AST->Diagnostics = Diags;
  1452. AST->OnlyLocalDecls = OnlyLocalDecls;
  1453. AST->CaptureDiagnostics = CaptureDiagnostics;
  1454. AST->TUKind = TUKind;
  1455. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1456. AST->IncludeBriefCommentsInCodeCompletion
  1457. = IncludeBriefCommentsInCodeCompletion;
  1458. AST->Invocation = std::move(CI);
  1459. AST->FileSystemOpts = FileMgr->getFileSystemOpts();
  1460. AST->FileMgr = FileMgr;
  1461. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  1462. // Recover resources if we crash before exiting this method.
  1463. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1464. ASTUnitCleanup(AST.get());
  1465. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  1466. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  1467. DiagCleanup(Diags.get());
  1468. if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
  1469. PrecompilePreambleAfterNParses,
  1470. &AST->FileMgr->getVirtualFileSystem()))
  1471. return nullptr;
  1472. return AST;
  1473. }
  1474. ASTUnit *ASTUnit::LoadFromCommandLine(
  1475. const char **ArgBegin, const char **ArgEnd,
  1476. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1477. IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
  1478. bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
  1479. ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
  1480. unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
  1481. bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
  1482. bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
  1483. bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
  1484. bool RetainExcludedConditionalBlocks, std::optional<StringRef> ModuleFormat,
  1485. std::unique_ptr<ASTUnit> *ErrAST,
  1486. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  1487. assert(Diags.get() && "no DiagnosticsEngine was provided");
  1488. SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
  1489. std::shared_ptr<CompilerInvocation> CI;
  1490. {
  1491. CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
  1492. &StoredDiagnostics, nullptr);
  1493. CreateInvocationOptions CIOpts;
  1494. CIOpts.VFS = VFS;
  1495. CIOpts.Diags = Diags;
  1496. CIOpts.ProbePrecompiled = true; // FIXME: historical default. Needed?
  1497. CI = createInvocation(llvm::ArrayRef(ArgBegin, ArgEnd), std::move(CIOpts));
  1498. if (!CI)
  1499. return nullptr;
  1500. }
  1501. // Override any files that need remapping
  1502. for (const auto &RemappedFile : RemappedFiles) {
  1503. CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
  1504. RemappedFile.second);
  1505. }
  1506. PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
  1507. PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
  1508. PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
  1509. PPOpts.SingleFileParseMode = SingleFileParse;
  1510. PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
  1511. // Override the resources path.
  1512. CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
  1513. CI->getFrontendOpts().SkipFunctionBodies =
  1514. SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
  1515. if (ModuleFormat)
  1516. CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat);
  1517. // Create the AST unit.
  1518. std::unique_ptr<ASTUnit> AST;
  1519. AST.reset(new ASTUnit(false));
  1520. AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
  1521. AST->StoredDiagnostics.swap(StoredDiagnostics);
  1522. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1523. AST->Diagnostics = Diags;
  1524. AST->FileSystemOpts = CI->getFileSystemOpts();
  1525. if (!VFS)
  1526. VFS = llvm::vfs::getRealFileSystem();
  1527. VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
  1528. AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
  1529. AST->ModuleCache = new InMemoryModuleCache;
  1530. AST->OnlyLocalDecls = OnlyLocalDecls;
  1531. AST->CaptureDiagnostics = CaptureDiagnostics;
  1532. AST->TUKind = TUKind;
  1533. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1534. AST->IncludeBriefCommentsInCodeCompletion
  1535. = IncludeBriefCommentsInCodeCompletion;
  1536. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  1537. AST->Invocation = CI;
  1538. AST->SkipFunctionBodies = SkipFunctionBodies;
  1539. if (ForSerialization)
  1540. AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
  1541. // Zero out now to ease cleanup during crash recovery.
  1542. CI = nullptr;
  1543. Diags = nullptr;
  1544. // Recover resources if we crash before exiting this method.
  1545. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1546. ASTUnitCleanup(AST.get());
  1547. if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
  1548. PrecompilePreambleAfterNParses,
  1549. VFS)) {
  1550. // Some error occurred, if caller wants to examine diagnostics, pass it the
  1551. // ASTUnit.
  1552. if (ErrAST) {
  1553. AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
  1554. ErrAST->swap(AST);
  1555. }
  1556. return nullptr;
  1557. }
  1558. return AST.release();
  1559. }
  1560. bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1561. ArrayRef<RemappedFile> RemappedFiles,
  1562. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  1563. if (!Invocation)
  1564. return true;
  1565. if (!VFS) {
  1566. assert(FileMgr && "FileMgr is null on Reparse call");
  1567. VFS = &FileMgr->getVirtualFileSystem();
  1568. }
  1569. clearFileLevelDecls();
  1570. SimpleTimer ParsingTimer(WantTiming);
  1571. ParsingTimer.setOutput("Reparsing " + getMainFileName());
  1572. // Remap files.
  1573. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  1574. for (const auto &RB : PPOpts.RemappedFileBuffers)
  1575. delete RB.second;
  1576. Invocation->getPreprocessorOpts().clearRemappedFiles();
  1577. for (const auto &RemappedFile : RemappedFiles) {
  1578. Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
  1579. RemappedFile.second);
  1580. }
  1581. // If we have a preamble file lying around, or if we might try to
  1582. // build a precompiled preamble, do so now.
  1583. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
  1584. if (Preamble || PreambleRebuildCountdown > 0)
  1585. OverrideMainBuffer =
  1586. getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
  1587. // Clear out the diagnostics state.
  1588. FileMgr.reset();
  1589. getDiagnostics().Reset();
  1590. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1591. if (OverrideMainBuffer)
  1592. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  1593. // Parse the sources
  1594. bool Result =
  1595. Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
  1596. // If we're caching global code-completion results, and the top-level
  1597. // declarations have changed, clear out the code-completion cache.
  1598. if (!Result && ShouldCacheCodeCompletionResults &&
  1599. CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
  1600. CacheCodeCompletionResults();
  1601. // We now need to clear out the completion info related to this translation
  1602. // unit; it'll be recreated if necessary.
  1603. CCTUInfo.reset();
  1604. return Result;
  1605. }
  1606. void ASTUnit::ResetForParse() {
  1607. SavedMainFileBuffer.reset();
  1608. SourceMgr.reset();
  1609. TheSema.reset();
  1610. Ctx.reset();
  1611. PP.reset();
  1612. Reader.reset();
  1613. TopLevelDecls.clear();
  1614. clearFileLevelDecls();
  1615. }
  1616. //----------------------------------------------------------------------------//
  1617. // Code completion
  1618. //----------------------------------------------------------------------------//
  1619. namespace {
  1620. /// Code completion consumer that combines the cached code-completion
  1621. /// results from an ASTUnit with the code-completion results provided to it,
  1622. /// then passes the result on to
  1623. class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
  1624. uint64_t NormalContexts;
  1625. ASTUnit &AST;
  1626. CodeCompleteConsumer &Next;
  1627. public:
  1628. AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
  1629. const CodeCompleteOptions &CodeCompleteOpts)
  1630. : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
  1631. // Compute the set of contexts in which we will look when we don't have
  1632. // any information about the specific context.
  1633. NormalContexts
  1634. = (1LL << CodeCompletionContext::CCC_TopLevel)
  1635. | (1LL << CodeCompletionContext::CCC_ObjCInterface)
  1636. | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
  1637. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  1638. | (1LL << CodeCompletionContext::CCC_Statement)
  1639. | (1LL << CodeCompletionContext::CCC_Expression)
  1640. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
  1641. | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
  1642. | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
  1643. | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
  1644. | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
  1645. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
  1646. | (1LL << CodeCompletionContext::CCC_Recovery);
  1647. if (AST.getASTContext().getLangOpts().CPlusPlus)
  1648. NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
  1649. | (1LL << CodeCompletionContext::CCC_UnionTag)
  1650. | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
  1651. }
  1652. void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
  1653. CodeCompletionResult *Results,
  1654. unsigned NumResults) override;
  1655. void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
  1656. OverloadCandidate *Candidates,
  1657. unsigned NumCandidates,
  1658. SourceLocation OpenParLoc,
  1659. bool Braced) override {
  1660. Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
  1661. OpenParLoc, Braced);
  1662. }
  1663. CodeCompletionAllocator &getAllocator() override {
  1664. return Next.getAllocator();
  1665. }
  1666. CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
  1667. return Next.getCodeCompletionTUInfo();
  1668. }
  1669. };
  1670. } // namespace
  1671. /// Helper function that computes which global names are hidden by the
  1672. /// local code-completion results.
  1673. static void CalculateHiddenNames(const CodeCompletionContext &Context,
  1674. CodeCompletionResult *Results,
  1675. unsigned NumResults,
  1676. ASTContext &Ctx,
  1677. llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
  1678. bool OnlyTagNames = false;
  1679. switch (Context.getKind()) {
  1680. case CodeCompletionContext::CCC_Recovery:
  1681. case CodeCompletionContext::CCC_TopLevel:
  1682. case CodeCompletionContext::CCC_ObjCInterface:
  1683. case CodeCompletionContext::CCC_ObjCImplementation:
  1684. case CodeCompletionContext::CCC_ObjCIvarList:
  1685. case CodeCompletionContext::CCC_ClassStructUnion:
  1686. case CodeCompletionContext::CCC_Statement:
  1687. case CodeCompletionContext::CCC_Expression:
  1688. case CodeCompletionContext::CCC_ObjCMessageReceiver:
  1689. case CodeCompletionContext::CCC_DotMemberAccess:
  1690. case CodeCompletionContext::CCC_ArrowMemberAccess:
  1691. case CodeCompletionContext::CCC_ObjCPropertyAccess:
  1692. case CodeCompletionContext::CCC_Namespace:
  1693. case CodeCompletionContext::CCC_Type:
  1694. case CodeCompletionContext::CCC_Symbol:
  1695. case CodeCompletionContext::CCC_SymbolOrNewName:
  1696. case CodeCompletionContext::CCC_ParenthesizedExpression:
  1697. case CodeCompletionContext::CCC_ObjCInterfaceName:
  1698. break;
  1699. case CodeCompletionContext::CCC_EnumTag:
  1700. case CodeCompletionContext::CCC_UnionTag:
  1701. case CodeCompletionContext::CCC_ClassOrStructTag:
  1702. OnlyTagNames = true;
  1703. break;
  1704. case CodeCompletionContext::CCC_ObjCProtocolName:
  1705. case CodeCompletionContext::CCC_MacroName:
  1706. case CodeCompletionContext::CCC_MacroNameUse:
  1707. case CodeCompletionContext::CCC_PreprocessorExpression:
  1708. case CodeCompletionContext::CCC_PreprocessorDirective:
  1709. case CodeCompletionContext::CCC_NaturalLanguage:
  1710. case CodeCompletionContext::CCC_SelectorName:
  1711. case CodeCompletionContext::CCC_TypeQualifiers:
  1712. case CodeCompletionContext::CCC_Other:
  1713. case CodeCompletionContext::CCC_OtherWithMacros:
  1714. case CodeCompletionContext::CCC_ObjCInstanceMessage:
  1715. case CodeCompletionContext::CCC_ObjCClassMessage:
  1716. case CodeCompletionContext::CCC_ObjCCategoryName:
  1717. case CodeCompletionContext::CCC_IncludedFile:
  1718. case CodeCompletionContext::CCC_Attribute:
  1719. case CodeCompletionContext::CCC_NewName:
  1720. // We're looking for nothing, or we're looking for names that cannot
  1721. // be hidden.
  1722. return;
  1723. }
  1724. using Result = CodeCompletionResult;
  1725. for (unsigned I = 0; I != NumResults; ++I) {
  1726. if (Results[I].Kind != Result::RK_Declaration)
  1727. continue;
  1728. unsigned IDNS
  1729. = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
  1730. bool Hiding = false;
  1731. if (OnlyTagNames)
  1732. Hiding = (IDNS & Decl::IDNS_Tag);
  1733. else {
  1734. unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
  1735. Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
  1736. Decl::IDNS_NonMemberOperator);
  1737. if (Ctx.getLangOpts().CPlusPlus)
  1738. HiddenIDNS |= Decl::IDNS_Tag;
  1739. Hiding = (IDNS & HiddenIDNS);
  1740. }
  1741. if (!Hiding)
  1742. continue;
  1743. DeclarationName Name = Results[I].Declaration->getDeclName();
  1744. if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
  1745. HiddenNames.insert(Identifier->getName());
  1746. else
  1747. HiddenNames.insert(Name.getAsString());
  1748. }
  1749. }
  1750. void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
  1751. CodeCompletionContext Context,
  1752. CodeCompletionResult *Results,
  1753. unsigned NumResults) {
  1754. // Merge the results we were given with the results we cached.
  1755. bool AddedResult = false;
  1756. uint64_t InContexts =
  1757. Context.getKind() == CodeCompletionContext::CCC_Recovery
  1758. ? NormalContexts : (1LL << Context.getKind());
  1759. // Contains the set of names that are hidden by "local" completion results.
  1760. llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
  1761. using Result = CodeCompletionResult;
  1762. SmallVector<Result, 8> AllResults;
  1763. for (ASTUnit::cached_completion_iterator
  1764. C = AST.cached_completion_begin(),
  1765. CEnd = AST.cached_completion_end();
  1766. C != CEnd; ++C) {
  1767. // If the context we are in matches any of the contexts we are
  1768. // interested in, we'll add this result.
  1769. if ((C->ShowInContexts & InContexts) == 0)
  1770. continue;
  1771. // If we haven't added any results previously, do so now.
  1772. if (!AddedResult) {
  1773. CalculateHiddenNames(Context, Results, NumResults, S.Context,
  1774. HiddenNames);
  1775. AllResults.insert(AllResults.end(), Results, Results + NumResults);
  1776. AddedResult = true;
  1777. }
  1778. // Determine whether this global completion result is hidden by a local
  1779. // completion result. If so, skip it.
  1780. if (C->Kind != CXCursor_MacroDefinition &&
  1781. HiddenNames.count(C->Completion->getTypedText()))
  1782. continue;
  1783. // Adjust priority based on similar type classes.
  1784. unsigned Priority = C->Priority;
  1785. CodeCompletionString *Completion = C->Completion;
  1786. if (!Context.getPreferredType().isNull()) {
  1787. if (C->Kind == CXCursor_MacroDefinition) {
  1788. Priority = getMacroUsagePriority(C->Completion->getTypedText(),
  1789. S.getLangOpts(),
  1790. Context.getPreferredType()->isAnyPointerType());
  1791. } else if (C->Type) {
  1792. CanQualType Expected
  1793. = S.Context.getCanonicalType(
  1794. Context.getPreferredType().getUnqualifiedType());
  1795. SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
  1796. if (ExpectedSTC == C->TypeClass) {
  1797. // We know this type is similar; check for an exact match.
  1798. llvm::StringMap<unsigned> &CachedCompletionTypes
  1799. = AST.getCachedCompletionTypes();
  1800. llvm::StringMap<unsigned>::iterator Pos
  1801. = CachedCompletionTypes.find(QualType(Expected).getAsString());
  1802. if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
  1803. Priority /= CCF_ExactTypeMatch;
  1804. else
  1805. Priority /= CCF_SimilarTypeMatch;
  1806. }
  1807. }
  1808. }
  1809. // Adjust the completion string, if required.
  1810. if (C->Kind == CXCursor_MacroDefinition &&
  1811. Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
  1812. // Create a new code-completion string that just contains the
  1813. // macro name, without its arguments.
  1814. CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
  1815. CCP_CodePattern, C->Availability);
  1816. Builder.AddTypedTextChunk(C->Completion->getTypedText());
  1817. Priority = CCP_CodePattern;
  1818. Completion = Builder.TakeString();
  1819. }
  1820. AllResults.push_back(Result(Completion, Priority, C->Kind,
  1821. C->Availability));
  1822. }
  1823. // If we did not add any cached completion results, just forward the
  1824. // results we were given to the next consumer.
  1825. if (!AddedResult) {
  1826. Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
  1827. return;
  1828. }
  1829. Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
  1830. AllResults.size());
  1831. }
  1832. void ASTUnit::CodeComplete(
  1833. StringRef File, unsigned Line, unsigned Column,
  1834. ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
  1835. bool IncludeCodePatterns, bool IncludeBriefComments,
  1836. CodeCompleteConsumer &Consumer,
  1837. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1838. DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
  1839. FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
  1840. SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
  1841. if (!Invocation)
  1842. return;
  1843. SimpleTimer CompletionTimer(WantTiming);
  1844. CompletionTimer.setOutput("Code completion @ " + File + ":" +
  1845. Twine(Line) + ":" + Twine(Column));
  1846. auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
  1847. FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
  1848. CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
  1849. PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
  1850. CodeCompleteOpts.IncludeMacros = IncludeMacros &&
  1851. CachedCompletionResults.empty();
  1852. CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
  1853. CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
  1854. CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
  1855. CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
  1856. CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
  1857. assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
  1858. FrontendOpts.CodeCompletionAt.FileName = std::string(File);
  1859. FrontendOpts.CodeCompletionAt.Line = Line;
  1860. FrontendOpts.CodeCompletionAt.Column = Column;
  1861. // Set the language options appropriately.
  1862. LangOpts = *CCInvocation->getLangOpts();
  1863. // Spell-checking and warnings are wasteful during code-completion.
  1864. LangOpts.SpellChecking = false;
  1865. CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
  1866. std::unique_ptr<CompilerInstance> Clang(
  1867. new CompilerInstance(PCHContainerOps));
  1868. // Recover resources if we crash before exiting this method.
  1869. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1870. CICleanup(Clang.get());
  1871. auto &Inv = *CCInvocation;
  1872. Clang->setInvocation(std::move(CCInvocation));
  1873. OriginalSourceFile =
  1874. std::string(Clang->getFrontendOpts().Inputs[0].getFile());
  1875. // Set up diagnostics, capturing any diagnostics produced.
  1876. Clang->setDiagnostics(&Diag);
  1877. CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
  1878. Clang->getDiagnostics(),
  1879. &StoredDiagnostics, nullptr);
  1880. ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
  1881. // Create the target instance.
  1882. if (!Clang->createTarget()) {
  1883. Clang->setInvocation(nullptr);
  1884. return;
  1885. }
  1886. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1887. "Invocation must have exactly one source file!");
  1888. assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
  1889. InputKind::Source &&
  1890. "FIXME: AST inputs not yet supported here!");
  1891. assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
  1892. Language::LLVM_IR &&
  1893. "IR inputs not support here!");
  1894. // Use the source and file managers that we were given.
  1895. Clang->setFileManager(&FileMgr);
  1896. Clang->setSourceManager(&SourceMgr);
  1897. // Remap files.
  1898. PreprocessorOpts.clearRemappedFiles();
  1899. PreprocessorOpts.RetainRemappedFileBuffers = true;
  1900. for (const auto &RemappedFile : RemappedFiles) {
  1901. PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
  1902. OwnedBuffers.push_back(RemappedFile.second);
  1903. }
  1904. // Use the code completion consumer we were given, but adding any cached
  1905. // code-completion results.
  1906. AugmentedCodeCompleteConsumer *AugmentedConsumer
  1907. = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
  1908. Clang->setCodeCompletionConsumer(AugmentedConsumer);
  1909. auto getUniqueID =
  1910. [&FileMgr](StringRef Filename) -> std::optional<llvm::sys::fs::UniqueID> {
  1911. if (auto Status = FileMgr.getVirtualFileSystem().status(Filename))
  1912. return Status->getUniqueID();
  1913. return std::nullopt;
  1914. };
  1915. auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
  1916. if (LHS == RHS)
  1917. return true;
  1918. if (auto LHSID = getUniqueID(LHS))
  1919. if (auto RHSID = getUniqueID(RHS))
  1920. return *LHSID == *RHSID;
  1921. return false;
  1922. };
  1923. // If we have a precompiled preamble, try to use it. We only allow
  1924. // the use of the precompiled preamble if we're if the completion
  1925. // point is within the main file, after the end of the precompiled
  1926. // preamble.
  1927. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
  1928. if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) {
  1929. OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
  1930. PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1);
  1931. }
  1932. // If the main file has been overridden due to the use of a preamble,
  1933. // make that override happen and introduce the preamble.
  1934. if (OverrideMainBuffer) {
  1935. assert(Preamble &&
  1936. "No preamble was built, but OverrideMainBuffer is not null");
  1937. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
  1938. &FileMgr.getVirtualFileSystem();
  1939. Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
  1940. OverrideMainBuffer.get());
  1941. // FIXME: there is no way to update VFS if it was changed by
  1942. // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
  1943. // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
  1944. // PCH files are always readable.
  1945. OwnedBuffers.push_back(OverrideMainBuffer.release());
  1946. } else {
  1947. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  1948. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  1949. }
  1950. // Disable the preprocessing record if modules are not enabled.
  1951. if (!Clang->getLangOpts().Modules)
  1952. PreprocessorOpts.DetailedRecord = false;
  1953. std::unique_ptr<SyntaxOnlyAction> Act;
  1954. Act.reset(new SyntaxOnlyAction);
  1955. if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
  1956. if (llvm::Error Err = Act->Execute()) {
  1957. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  1958. }
  1959. Act->EndSourceFile();
  1960. }
  1961. }
  1962. bool ASTUnit::Save(StringRef File) {
  1963. if (HadModuleLoaderFatalFailure)
  1964. return true;
  1965. // Write to a temporary file and later rename it to the actual file, to avoid
  1966. // possible race conditions.
  1967. SmallString<128> TempPath;
  1968. TempPath = File;
  1969. TempPath += "-%%%%%%%%";
  1970. // FIXME: Can we somehow regenerate the stat cache here, or do we need to
  1971. // unconditionally create a stat cache when we parse the file?
  1972. if (llvm::Error Err = llvm::writeFileAtomically(
  1973. TempPath, File, [this](llvm::raw_ostream &Out) {
  1974. return serialize(Out) ? llvm::make_error<llvm::StringError>(
  1975. "ASTUnit serialization failed",
  1976. llvm::inconvertibleErrorCode())
  1977. : llvm::Error::success();
  1978. })) {
  1979. consumeError(std::move(Err));
  1980. return true;
  1981. }
  1982. return false;
  1983. }
  1984. static bool serializeUnit(ASTWriter &Writer,
  1985. SmallVectorImpl<char> &Buffer,
  1986. Sema &S,
  1987. bool hasErrors,
  1988. raw_ostream &OS) {
  1989. Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
  1990. // Write the generated bitstream to "Out".
  1991. if (!Buffer.empty())
  1992. OS.write(Buffer.data(), Buffer.size());
  1993. return false;
  1994. }
  1995. bool ASTUnit::serialize(raw_ostream &OS) {
  1996. // For serialization we are lenient if the errors were only warn-as-error kind.
  1997. bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
  1998. if (WriterData)
  1999. return serializeUnit(WriterData->Writer, WriterData->Buffer,
  2000. getSema(), hasErrors, OS);
  2001. SmallString<128> Buffer;
  2002. llvm::BitstreamWriter Stream(Buffer);
  2003. InMemoryModuleCache ModuleCache;
  2004. ASTWriter Writer(Stream, Buffer, ModuleCache, {});
  2005. return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
  2006. }
  2007. using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
  2008. void ASTUnit::TranslateStoredDiagnostics(
  2009. FileManager &FileMgr,
  2010. SourceManager &SrcMgr,
  2011. const SmallVectorImpl<StandaloneDiagnostic> &Diags,
  2012. SmallVectorImpl<StoredDiagnostic> &Out) {
  2013. // Map the standalone diagnostic into the new source manager. We also need to
  2014. // remap all the locations to the new view. This includes the diag location,
  2015. // any associated source ranges, and the source ranges of associated fix-its.
  2016. // FIXME: There should be a cleaner way to do this.
  2017. SmallVector<StoredDiagnostic, 4> Result;
  2018. Result.reserve(Diags.size());
  2019. for (const auto &SD : Diags) {
  2020. // Rebuild the StoredDiagnostic.
  2021. if (SD.Filename.empty())
  2022. continue;
  2023. auto FE = FileMgr.getFile(SD.Filename);
  2024. if (!FE)
  2025. continue;
  2026. SourceLocation FileLoc;
  2027. auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
  2028. if (ItFileID == PreambleSrcLocCache.end()) {
  2029. FileID FID = SrcMgr.translateFile(*FE);
  2030. FileLoc = SrcMgr.getLocForStartOfFile(FID);
  2031. PreambleSrcLocCache[SD.Filename] = FileLoc;
  2032. } else {
  2033. FileLoc = ItFileID->getValue();
  2034. }
  2035. if (FileLoc.isInvalid())
  2036. continue;
  2037. SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
  2038. FullSourceLoc Loc(L, SrcMgr);
  2039. SmallVector<CharSourceRange, 4> Ranges;
  2040. Ranges.reserve(SD.Ranges.size());
  2041. for (const auto &Range : SD.Ranges) {
  2042. SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
  2043. SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
  2044. Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
  2045. }
  2046. SmallVector<FixItHint, 2> FixIts;
  2047. FixIts.reserve(SD.FixIts.size());
  2048. for (const auto &FixIt : SD.FixIts) {
  2049. FixIts.push_back(FixItHint());
  2050. FixItHint &FH = FixIts.back();
  2051. FH.CodeToInsert = FixIt.CodeToInsert;
  2052. SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
  2053. SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
  2054. FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
  2055. }
  2056. Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
  2057. SD.Message, Loc, Ranges, FixIts));
  2058. }
  2059. Result.swap(Out);
  2060. }
  2061. void ASTUnit::addFileLevelDecl(Decl *D) {
  2062. assert(D);
  2063. // We only care about local declarations.
  2064. if (D->isFromASTFile())
  2065. return;
  2066. SourceManager &SM = *SourceMgr;
  2067. SourceLocation Loc = D->getLocation();
  2068. if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
  2069. return;
  2070. // We only keep track of the file-level declarations of each file.
  2071. if (!D->getLexicalDeclContext()->isFileContext())
  2072. return;
  2073. SourceLocation FileLoc = SM.getFileLoc(Loc);
  2074. assert(SM.isLocalSourceLocation(FileLoc));
  2075. FileID FID;
  2076. unsigned Offset;
  2077. std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  2078. if (FID.isInvalid())
  2079. return;
  2080. std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
  2081. if (!Decls)
  2082. Decls = std::make_unique<LocDeclsTy>();
  2083. std::pair<unsigned, Decl *> LocDecl(Offset, D);
  2084. if (Decls->empty() || Decls->back().first <= Offset) {
  2085. Decls->push_back(LocDecl);
  2086. return;
  2087. }
  2088. LocDeclsTy::iterator I =
  2089. llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
  2090. Decls->insert(I, LocDecl);
  2091. }
  2092. void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
  2093. SmallVectorImpl<Decl *> &Decls) {
  2094. if (File.isInvalid())
  2095. return;
  2096. if (SourceMgr->isLoadedFileID(File)) {
  2097. assert(Ctx->getExternalSource() && "No external source!");
  2098. return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
  2099. Decls);
  2100. }
  2101. FileDeclsTy::iterator I = FileDecls.find(File);
  2102. if (I == FileDecls.end())
  2103. return;
  2104. LocDeclsTy &LocDecls = *I->second;
  2105. if (LocDecls.empty())
  2106. return;
  2107. LocDeclsTy::iterator BeginIt =
  2108. llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
  2109. return LD.first < Offset;
  2110. });
  2111. if (BeginIt != LocDecls.begin())
  2112. --BeginIt;
  2113. // If we are pointing at a top-level decl inside an objc container, we need
  2114. // to backtrack until we find it otherwise we will fail to report that the
  2115. // region overlaps with an objc container.
  2116. while (BeginIt != LocDecls.begin() &&
  2117. BeginIt->second->isTopLevelDeclInObjCContainer())
  2118. --BeginIt;
  2119. LocDeclsTy::iterator EndIt = llvm::upper_bound(
  2120. LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
  2121. llvm::less_first());
  2122. if (EndIt != LocDecls.end())
  2123. ++EndIt;
  2124. for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
  2125. Decls.push_back(DIt->second);
  2126. }
  2127. SourceLocation ASTUnit::getLocation(const FileEntry *File,
  2128. unsigned Line, unsigned Col) const {
  2129. const SourceManager &SM = getSourceManager();
  2130. SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
  2131. return SM.getMacroArgExpandedLocation(Loc);
  2132. }
  2133. SourceLocation ASTUnit::getLocation(const FileEntry *File,
  2134. unsigned Offset) const {
  2135. const SourceManager &SM = getSourceManager();
  2136. SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
  2137. return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
  2138. }
  2139. /// If \arg Loc is a loaded location from the preamble, returns
  2140. /// the corresponding local location of the main file, otherwise it returns
  2141. /// \arg Loc.
  2142. SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
  2143. FileID PreambleID;
  2144. if (SourceMgr)
  2145. PreambleID = SourceMgr->getPreambleFileID();
  2146. if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
  2147. return Loc;
  2148. unsigned Offs;
  2149. if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
  2150. SourceLocation FileLoc
  2151. = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
  2152. return FileLoc.getLocWithOffset(Offs);
  2153. }
  2154. return Loc;
  2155. }
  2156. /// If \arg Loc is a local location of the main file but inside the
  2157. /// preamble chunk, returns the corresponding loaded location from the
  2158. /// preamble, otherwise it returns \arg Loc.
  2159. SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
  2160. FileID PreambleID;
  2161. if (SourceMgr)
  2162. PreambleID = SourceMgr->getPreambleFileID();
  2163. if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
  2164. return Loc;
  2165. unsigned Offs;
  2166. if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
  2167. Offs < Preamble->getBounds().Size) {
  2168. SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
  2169. return FileLoc.getLocWithOffset(Offs);
  2170. }
  2171. return Loc;
  2172. }
  2173. bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
  2174. FileID FID;
  2175. if (SourceMgr)
  2176. FID = SourceMgr->getPreambleFileID();
  2177. if (Loc.isInvalid() || FID.isInvalid())
  2178. return false;
  2179. return SourceMgr->isInFileID(Loc, FID);
  2180. }
  2181. bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
  2182. FileID FID;
  2183. if (SourceMgr)
  2184. FID = SourceMgr->getMainFileID();
  2185. if (Loc.isInvalid() || FID.isInvalid())
  2186. return false;
  2187. return SourceMgr->isInFileID(Loc, FID);
  2188. }
  2189. SourceLocation ASTUnit::getEndOfPreambleFileID() const {
  2190. FileID FID;
  2191. if (SourceMgr)
  2192. FID = SourceMgr->getPreambleFileID();
  2193. if (FID.isInvalid())
  2194. return {};
  2195. return SourceMgr->getLocForEndOfFile(FID);
  2196. }
  2197. SourceLocation ASTUnit::getStartOfMainFileID() const {
  2198. FileID FID;
  2199. if (SourceMgr)
  2200. FID = SourceMgr->getMainFileID();
  2201. if (FID.isInvalid())
  2202. return {};
  2203. return SourceMgr->getLocForStartOfFile(FID);
  2204. }
  2205. llvm::iterator_range<PreprocessingRecord::iterator>
  2206. ASTUnit::getLocalPreprocessingEntities() const {
  2207. if (isMainFileAST()) {
  2208. serialization::ModuleFile &
  2209. Mod = Reader->getModuleManager().getPrimaryModule();
  2210. return Reader->getModulePreprocessedEntities(Mod);
  2211. }
  2212. if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
  2213. return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
  2214. return llvm::make_range(PreprocessingRecord::iterator(),
  2215. PreprocessingRecord::iterator());
  2216. }
  2217. bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
  2218. if (isMainFileAST()) {
  2219. serialization::ModuleFile &
  2220. Mod = Reader->getModuleManager().getPrimaryModule();
  2221. for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
  2222. if (!Fn(context, D))
  2223. return false;
  2224. }
  2225. return true;
  2226. }
  2227. for (ASTUnit::top_level_iterator TL = top_level_begin(),
  2228. TLEnd = top_level_end();
  2229. TL != TLEnd; ++TL) {
  2230. if (!Fn(context, *TL))
  2231. return false;
  2232. }
  2233. return true;
  2234. }
  2235. const FileEntry *ASTUnit::getPCHFile() {
  2236. if (!Reader)
  2237. return nullptr;
  2238. serialization::ModuleFile *Mod = nullptr;
  2239. Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
  2240. switch (M.Kind) {
  2241. case serialization::MK_ImplicitModule:
  2242. case serialization::MK_ExplicitModule:
  2243. case serialization::MK_PrebuiltModule:
  2244. return true; // skip dependencies.
  2245. case serialization::MK_PCH:
  2246. Mod = &M;
  2247. return true; // found it.
  2248. case serialization::MK_Preamble:
  2249. return false; // look in dependencies.
  2250. case serialization::MK_MainFile:
  2251. return false; // look in dependencies.
  2252. }
  2253. return true;
  2254. });
  2255. if (Mod)
  2256. return Mod->File;
  2257. return nullptr;
  2258. }
  2259. bool ASTUnit::isModuleFile() const {
  2260. return isMainFileAST() && getLangOpts().isCompilingModule();
  2261. }
  2262. InputKind ASTUnit::getInputKind() const {
  2263. auto &LangOpts = getLangOpts();
  2264. Language Lang;
  2265. if (LangOpts.OpenCL)
  2266. Lang = Language::OpenCL;
  2267. else if (LangOpts.CUDA)
  2268. Lang = Language::CUDA;
  2269. else if (LangOpts.RenderScript)
  2270. Lang = Language::RenderScript;
  2271. else if (LangOpts.CPlusPlus)
  2272. Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
  2273. else
  2274. Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
  2275. InputKind::Format Fmt = InputKind::Source;
  2276. if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
  2277. Fmt = InputKind::ModuleMap;
  2278. // We don't know if input was preprocessed. Assume not.
  2279. bool PP = false;
  2280. return InputKind(Lang, Fmt, PP);
  2281. }
  2282. #ifndef NDEBUG
  2283. ASTUnit::ConcurrencyState::ConcurrencyState() {
  2284. Mutex = new std::recursive_mutex;
  2285. }
  2286. ASTUnit::ConcurrencyState::~ConcurrencyState() {
  2287. delete static_cast<std::recursive_mutex *>(Mutex);
  2288. }
  2289. void ASTUnit::ConcurrencyState::start() {
  2290. bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
  2291. assert(acquired && "Concurrent access to ASTUnit!");
  2292. }
  2293. void ASTUnit::ConcurrencyState::finish() {
  2294. static_cast<std::recursive_mutex *>(Mutex)->unlock();
  2295. }
  2296. #else // NDEBUG
  2297. ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
  2298. ASTUnit::ConcurrencyState::~ConcurrencyState() {}
  2299. void ASTUnit::ConcurrencyState::start() {}
  2300. void ASTUnit::ConcurrencyState::finish() {}
  2301. #endif // NDEBUG