ASTUnit.cpp 106 KB

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