ASTUnit.cpp 96 KB

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