ASTUnit.cpp 104 KB

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