2
0

ASTUnit.cpp 105 KB

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