ASTUnit.cpp 106 KB

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