ASTUnit.cpp 102 KB

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