ASTUnit.cpp 105 KB

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