ASTUnit.cpp 104 KB

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