ASTUnit.cpp 104 KB

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