ASTUnit.cpp 96 KB

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