ASTUnit.cpp 95 KB

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