ASTUnit.cpp 102 KB

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