ASTUnit.cpp 105 KB

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