SourceManager.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  1. //===- SourceManager.cpp - Track and cache source files -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the SourceManager interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/SourceManager.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/LLVM.h"
  16. #include "clang/Basic/SourceLocation.h"
  17. #include "clang/Basic/SourceManagerInternals.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Support/Allocator.h"
  26. #include "llvm/Support/Capacity.h"
  27. #include "llvm/Support/Compiler.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/MathExtras.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/Path.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstddef>
  37. #include <cstdint>
  38. #include <memory>
  39. #include <tuple>
  40. #include <utility>
  41. #include <vector>
  42. using namespace clang;
  43. using namespace SrcMgr;
  44. using llvm::MemoryBuffer;
  45. //===----------------------------------------------------------------------===//
  46. // SourceManager Helper Classes
  47. //===----------------------------------------------------------------------===//
  48. ContentCache::~ContentCache() {
  49. if (shouldFreeBuffer())
  50. delete Buffer.getPointer();
  51. }
  52. /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
  53. /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
  54. unsigned ContentCache::getSizeBytesMapped() const {
  55. return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
  56. }
  57. /// Returns the kind of memory used to back the memory buffer for
  58. /// this content cache. This is used for performance analysis.
  59. llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
  60. assert(Buffer.getPointer());
  61. // Should be unreachable, but keep for sanity.
  62. if (!Buffer.getPointer())
  63. return llvm::MemoryBuffer::MemoryBuffer_Malloc;
  64. const llvm::MemoryBuffer *buf = Buffer.getPointer();
  65. return buf->getBufferKind();
  66. }
  67. /// getSize - Returns the size of the content encapsulated by this ContentCache.
  68. /// This can be the size of the source file or the size of an arbitrary
  69. /// scratch buffer. If the ContentCache encapsulates a source file, that
  70. /// file is not lazily brought in from disk to satisfy this query.
  71. unsigned ContentCache::getSize() const {
  72. return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
  73. : (unsigned) ContentsEntry->getSize();
  74. }
  75. void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
  76. if (B && B == Buffer.getPointer()) {
  77. assert(0 && "Replacing with the same buffer");
  78. Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
  79. return;
  80. }
  81. if (shouldFreeBuffer())
  82. delete Buffer.getPointer();
  83. Buffer.setPointer(B);
  84. Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
  85. }
  86. const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
  87. const SourceManager &SM,
  88. SourceLocation Loc,
  89. bool *Invalid) const {
  90. // Lazily create the Buffer for ContentCaches that wrap files. If we already
  91. // computed it, just return what we have.
  92. if (Buffer.getPointer() || !ContentsEntry) {
  93. if (Invalid)
  94. *Invalid = isBufferInvalid();
  95. return Buffer.getPointer();
  96. }
  97. // Check that the file's size fits in an 'unsigned' (with room for a
  98. // past-the-end value). This is deeply regrettable, but various parts of
  99. // Clang (including elsewhere in this file!) use 'unsigned' to represent file
  100. // offsets, line numbers, string literal lengths, and so on, and fail
  101. // miserably on large source files.
  102. if ((uint64_t)ContentsEntry->getSize() >=
  103. std::numeric_limits<unsigned>::max()) {
  104. // We can't make a memory buffer of the required size, so just make a small
  105. // one. We should never hit a situation where we've already parsed to a
  106. // later offset of the file, so it shouldn't matter that the buffer is
  107. // smaller than the file.
  108. Buffer.setPointer(
  109. llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
  110. .release());
  111. if (Diag.isDiagnosticInFlight())
  112. Diag.SetDelayedDiagnostic(diag::err_file_too_large,
  113. ContentsEntry->getName());
  114. else
  115. Diag.Report(Loc, diag::err_file_too_large)
  116. << ContentsEntry->getName();
  117. Buffer.setInt(Buffer.getInt() | InvalidFlag);
  118. if (Invalid) *Invalid = true;
  119. return Buffer.getPointer();
  120. }
  121. bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
  122. auto BufferOrError =
  123. SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
  124. // If we were unable to open the file, then we are in an inconsistent
  125. // situation where the content cache referenced a file which no longer
  126. // exists. Most likely, we were using a stat cache with an invalid entry but
  127. // the file could also have been removed during processing. Since we can't
  128. // really deal with this situation, just create an empty buffer.
  129. //
  130. // FIXME: This is definitely not ideal, but our immediate clients can't
  131. // currently handle returning a null entry here. Ideally we should detect
  132. // that we are in an inconsistent situation and error out as quickly as
  133. // possible.
  134. if (!BufferOrError) {
  135. StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
  136. auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
  137. ContentsEntry->getSize(), "<invalid>");
  138. char *Ptr = BackupBuffer->getBufferStart();
  139. for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
  140. Ptr[i] = FillStr[i % FillStr.size()];
  141. Buffer.setPointer(BackupBuffer.release());
  142. if (Diag.isDiagnosticInFlight())
  143. Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
  144. ContentsEntry->getName(),
  145. BufferOrError.getError().message());
  146. else
  147. Diag.Report(Loc, diag::err_cannot_open_file)
  148. << ContentsEntry->getName() << BufferOrError.getError().message();
  149. Buffer.setInt(Buffer.getInt() | InvalidFlag);
  150. if (Invalid) *Invalid = true;
  151. return Buffer.getPointer();
  152. }
  153. Buffer.setPointer(BufferOrError->release());
  154. // Check that the file's size is the same as in the file entry (which may
  155. // have come from a stat cache).
  156. if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
  157. if (Diag.isDiagnosticInFlight())
  158. Diag.SetDelayedDiagnostic(diag::err_file_modified,
  159. ContentsEntry->getName());
  160. else
  161. Diag.Report(Loc, diag::err_file_modified)
  162. << ContentsEntry->getName();
  163. Buffer.setInt(Buffer.getInt() | InvalidFlag);
  164. if (Invalid) *Invalid = true;
  165. return Buffer.getPointer();
  166. }
  167. // If the buffer is valid, check to see if it has a UTF Byte Order Mark
  168. // (BOM). We only support UTF-8 with and without a BOM right now. See
  169. // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
  170. StringRef BufStr = Buffer.getPointer()->getBuffer();
  171. const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
  172. .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
  173. "UTF-32 (BE)")
  174. .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
  175. "UTF-32 (LE)")
  176. .StartsWith("\xFE\xFF", "UTF-16 (BE)")
  177. .StartsWith("\xFF\xFE", "UTF-16 (LE)")
  178. .StartsWith("\x2B\x2F\x76", "UTF-7")
  179. .StartsWith("\xF7\x64\x4C", "UTF-1")
  180. .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
  181. .StartsWith("\x0E\xFE\xFF", "SCSU")
  182. .StartsWith("\xFB\xEE\x28", "BOCU-1")
  183. .StartsWith("\x84\x31\x95\x33", "GB-18030")
  184. .Default(nullptr);
  185. if (InvalidBOM) {
  186. Diag.Report(Loc, diag::err_unsupported_bom)
  187. << InvalidBOM << ContentsEntry->getName();
  188. Buffer.setInt(Buffer.getInt() | InvalidFlag);
  189. }
  190. if (Invalid)
  191. *Invalid = isBufferInvalid();
  192. return Buffer.getPointer();
  193. }
  194. unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
  195. auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
  196. if (IterBool.second)
  197. FilenamesByID.push_back(&*IterBool.first);
  198. return IterBool.first->second;
  199. }
  200. /// Add a line note to the line table that indicates that there is a \#line or
  201. /// GNU line marker at the specified FID/Offset location which changes the
  202. /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
  203. /// change the presumed \#include stack. If it is 1, this is a file entry, if
  204. /// it is 2 then this is a file exit. FileKind specifies whether this is a
  205. /// system header or extern C system header.
  206. void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
  207. int FilenameID, unsigned EntryExit,
  208. SrcMgr::CharacteristicKind FileKind) {
  209. std::vector<LineEntry> &Entries = LineEntries[FID];
  210. // An unspecified FilenameID means use the last filename if available, or the
  211. // main source file otherwise.
  212. if (FilenameID == -1 && !Entries.empty())
  213. FilenameID = Entries.back().FilenameID;
  214. assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
  215. "Adding line entries out of order!");
  216. unsigned IncludeOffset = 0;
  217. if (EntryExit == 0) { // No #include stack change.
  218. IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
  219. } else if (EntryExit == 1) {
  220. IncludeOffset = Offset-1;
  221. } else if (EntryExit == 2) {
  222. assert(!Entries.empty() && Entries.back().IncludeOffset &&
  223. "PPDirectives should have caught case when popping empty include stack");
  224. // Get the include loc of the last entries' include loc as our include loc.
  225. IncludeOffset = 0;
  226. if (const LineEntry *PrevEntry =
  227. FindNearestLineEntry(FID, Entries.back().IncludeOffset))
  228. IncludeOffset = PrevEntry->IncludeOffset;
  229. }
  230. Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
  231. IncludeOffset));
  232. }
  233. /// FindNearestLineEntry - Find the line entry nearest to FID that is before
  234. /// it. If there is no line entry before Offset in FID, return null.
  235. const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
  236. unsigned Offset) {
  237. const std::vector<LineEntry> &Entries = LineEntries[FID];
  238. assert(!Entries.empty() && "No #line entries for this FID after all!");
  239. // It is very common for the query to be after the last #line, check this
  240. // first.
  241. if (Entries.back().FileOffset <= Offset)
  242. return &Entries.back();
  243. // Do a binary search to find the maximal element that is still before Offset.
  244. std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
  245. if (I == Entries.begin())
  246. return nullptr;
  247. return &*--I;
  248. }
  249. /// Add a new line entry that has already been encoded into
  250. /// the internal representation of the line table.
  251. void LineTableInfo::AddEntry(FileID FID,
  252. const std::vector<LineEntry> &Entries) {
  253. LineEntries[FID] = Entries;
  254. }
  255. /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
  256. unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
  257. return getLineTable().getLineTableFilenameID(Name);
  258. }
  259. /// AddLineNote - Add a line note to the line table for the FileID and offset
  260. /// specified by Loc. If FilenameID is -1, it is considered to be
  261. /// unspecified.
  262. void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
  263. int FilenameID, bool IsFileEntry,
  264. bool IsFileExit,
  265. SrcMgr::CharacteristicKind FileKind) {
  266. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  267. bool Invalid = false;
  268. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
  269. if (!Entry.isFile() || Invalid)
  270. return;
  271. const SrcMgr::FileInfo &FileInfo = Entry.getFile();
  272. // Remember that this file has #line directives now if it doesn't already.
  273. const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
  274. (void) getLineTable();
  275. unsigned EntryExit = 0;
  276. if (IsFileEntry)
  277. EntryExit = 1;
  278. else if (IsFileExit)
  279. EntryExit = 2;
  280. LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
  281. EntryExit, FileKind);
  282. }
  283. LineTableInfo &SourceManager::getLineTable() {
  284. if (!LineTable)
  285. LineTable.reset(new LineTableInfo());
  286. return *LineTable;
  287. }
  288. //===----------------------------------------------------------------------===//
  289. // Private 'Create' methods.
  290. //===----------------------------------------------------------------------===//
  291. SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
  292. bool UserFilesAreVolatile)
  293. : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
  294. clearIDTables();
  295. Diag.setSourceManager(this);
  296. }
  297. SourceManager::~SourceManager() {
  298. // Delete FileEntry objects corresponding to content caches. Since the actual
  299. // content cache objects are bump pointer allocated, we just have to run the
  300. // dtors, but we call the deallocate method for completeness.
  301. for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
  302. if (MemBufferInfos[i]) {
  303. MemBufferInfos[i]->~ContentCache();
  304. ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
  305. }
  306. }
  307. for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
  308. I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
  309. if (I->second) {
  310. I->second->~ContentCache();
  311. ContentCacheAlloc.Deallocate(I->second);
  312. }
  313. }
  314. }
  315. void SourceManager::clearIDTables() {
  316. MainFileID = FileID();
  317. LocalSLocEntryTable.clear();
  318. LoadedSLocEntryTable.clear();
  319. SLocEntryLoaded.clear();
  320. LastLineNoFileIDQuery = FileID();
  321. LastLineNoContentCache = nullptr;
  322. LastFileIDLookup = FileID();
  323. if (LineTable)
  324. LineTable->clear();
  325. // Use up FileID #0 as an invalid expansion.
  326. NextLocalOffset = 0;
  327. CurrentLoadedOffset = MaxLoadedOffset;
  328. createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
  329. }
  330. void SourceManager::initializeForReplay(const SourceManager &Old) {
  331. assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
  332. auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
  333. auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
  334. Clone->OrigEntry = Cache->OrigEntry;
  335. Clone->ContentsEntry = Cache->ContentsEntry;
  336. Clone->BufferOverridden = Cache->BufferOverridden;
  337. Clone->IsSystemFile = Cache->IsSystemFile;
  338. Clone->IsTransient = Cache->IsTransient;
  339. Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
  340. return Clone;
  341. };
  342. // Ensure all SLocEntries are loaded from the external source.
  343. for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
  344. if (!Old.SLocEntryLoaded[I])
  345. Old.loadSLocEntry(I, nullptr);
  346. // Inherit any content cache data from the old source manager.
  347. for (auto &FileInfo : Old.FileInfos) {
  348. SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
  349. if (Slot)
  350. continue;
  351. Slot = CloneContentCache(FileInfo.second);
  352. }
  353. }
  354. /// getOrCreateContentCache - Create or return a cached ContentCache for the
  355. /// specified file.
  356. const ContentCache *
  357. SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
  358. bool isSystemFile) {
  359. assert(FileEnt && "Didn't specify a file entry to use?");
  360. // Do we already have information about this file?
  361. ContentCache *&Entry = FileInfos[FileEnt];
  362. if (Entry) return Entry;
  363. // Nope, create a new Cache entry.
  364. Entry = ContentCacheAlloc.Allocate<ContentCache>();
  365. if (OverriddenFilesInfo) {
  366. // If the file contents are overridden with contents from another file,
  367. // pass that file to ContentCache.
  368. llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
  369. overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
  370. if (overI == OverriddenFilesInfo->OverriddenFiles.end())
  371. new (Entry) ContentCache(FileEnt);
  372. else
  373. new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
  374. : overI->second,
  375. overI->second);
  376. } else {
  377. new (Entry) ContentCache(FileEnt);
  378. }
  379. Entry->IsSystemFile = isSystemFile;
  380. Entry->IsTransient = FilesAreTransient;
  381. return Entry;
  382. }
  383. /// Create a new ContentCache for the specified memory buffer.
  384. /// This does no caching.
  385. const ContentCache *
  386. SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
  387. bool DoNotFree) {
  388. // Add a new ContentCache to the MemBufferInfos list and return it.
  389. ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
  390. new (Entry) ContentCache();
  391. MemBufferInfos.push_back(Entry);
  392. Entry->replaceBuffer(Buffer, DoNotFree);
  393. return Entry;
  394. }
  395. const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
  396. bool *Invalid) const {
  397. assert(!SLocEntryLoaded[Index]);
  398. if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
  399. if (Invalid)
  400. *Invalid = true;
  401. // If the file of the SLocEntry changed we could still have loaded it.
  402. if (!SLocEntryLoaded[Index]) {
  403. // Try to recover; create a SLocEntry so the rest of clang can handle it.
  404. LoadedSLocEntryTable[Index] = SLocEntry::get(0,
  405. FileInfo::get(SourceLocation(),
  406. getFakeContentCacheForRecovery(),
  407. SrcMgr::C_User));
  408. }
  409. }
  410. return LoadedSLocEntryTable[Index];
  411. }
  412. std::pair<int, unsigned>
  413. SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
  414. unsigned TotalSize) {
  415. assert(ExternalSLocEntries && "Don't have an external sloc source");
  416. // Make sure we're not about to run out of source locations.
  417. if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
  418. return std::make_pair(0, 0);
  419. LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
  420. SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
  421. CurrentLoadedOffset -= TotalSize;
  422. int ID = LoadedSLocEntryTable.size();
  423. return std::make_pair(-ID - 1, CurrentLoadedOffset);
  424. }
  425. /// As part of recovering from missing or changed content, produce a
  426. /// fake, non-empty buffer.
  427. llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
  428. if (!FakeBufferForRecovery)
  429. FakeBufferForRecovery =
  430. llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
  431. return FakeBufferForRecovery.get();
  432. }
  433. /// As part of recovering from missing or changed content, produce a
  434. /// fake content cache.
  435. const SrcMgr::ContentCache *
  436. SourceManager::getFakeContentCacheForRecovery() const {
  437. if (!FakeContentCacheForRecovery) {
  438. FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
  439. FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
  440. /*DoNotFree=*/true);
  441. }
  442. return FakeContentCacheForRecovery.get();
  443. }
  444. /// Returns the previous in-order FileID or an invalid FileID if there
  445. /// is no previous one.
  446. FileID SourceManager::getPreviousFileID(FileID FID) const {
  447. if (FID.isInvalid())
  448. return FileID();
  449. int ID = FID.ID;
  450. if (ID == -1)
  451. return FileID();
  452. if (ID > 0) {
  453. if (ID-1 == 0)
  454. return FileID();
  455. } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
  456. return FileID();
  457. }
  458. return FileID::get(ID-1);
  459. }
  460. /// Returns the next in-order FileID or an invalid FileID if there is
  461. /// no next one.
  462. FileID SourceManager::getNextFileID(FileID FID) const {
  463. if (FID.isInvalid())
  464. return FileID();
  465. int ID = FID.ID;
  466. if (ID > 0) {
  467. if (unsigned(ID+1) >= local_sloc_entry_size())
  468. return FileID();
  469. } else if (ID+1 >= -1) {
  470. return FileID();
  471. }
  472. return FileID::get(ID+1);
  473. }
  474. //===----------------------------------------------------------------------===//
  475. // Methods to create new FileID's and macro expansions.
  476. //===----------------------------------------------------------------------===//
  477. /// createFileID - Create a new FileID for the specified ContentCache and
  478. /// include position. This works regardless of whether the ContentCache
  479. /// corresponds to a file or some other input source.
  480. FileID SourceManager::createFileID(const ContentCache *File,
  481. SourceLocation IncludePos,
  482. SrcMgr::CharacteristicKind FileCharacter,
  483. int LoadedID, unsigned LoadedOffset) {
  484. if (LoadedID < 0) {
  485. assert(LoadedID != -1 && "Loading sentinel FileID");
  486. unsigned Index = unsigned(-LoadedID) - 2;
  487. assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
  488. assert(!SLocEntryLoaded[Index] && "FileID already loaded");
  489. LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
  490. FileInfo::get(IncludePos, File, FileCharacter));
  491. SLocEntryLoaded[Index] = true;
  492. return FileID::get(LoadedID);
  493. }
  494. LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
  495. FileInfo::get(IncludePos, File,
  496. FileCharacter)));
  497. unsigned FileSize = File->getSize();
  498. assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
  499. NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
  500. "Ran out of source locations!");
  501. // We do a +1 here because we want a SourceLocation that means "the end of the
  502. // file", e.g. for the "no newline at the end of the file" diagnostic.
  503. NextLocalOffset += FileSize + 1;
  504. // Set LastFileIDLookup to the newly created file. The next getFileID call is
  505. // almost guaranteed to be from that file.
  506. FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
  507. return LastFileIDLookup = FID;
  508. }
  509. SourceLocation
  510. SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
  511. SourceLocation ExpansionLoc,
  512. unsigned TokLength) {
  513. ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
  514. ExpansionLoc);
  515. return createExpansionLocImpl(Info, TokLength);
  516. }
  517. SourceLocation
  518. SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
  519. SourceLocation ExpansionLocStart,
  520. SourceLocation ExpansionLocEnd,
  521. unsigned TokLength,
  522. bool ExpansionIsTokenRange,
  523. int LoadedID,
  524. unsigned LoadedOffset) {
  525. ExpansionInfo Info = ExpansionInfo::create(
  526. SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
  527. return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
  528. }
  529. SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
  530. SourceLocation TokenStart,
  531. SourceLocation TokenEnd) {
  532. assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
  533. "token spans multiple files");
  534. return createExpansionLocImpl(
  535. ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
  536. TokenEnd.getOffset() - TokenStart.getOffset());
  537. }
  538. SourceLocation
  539. SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
  540. unsigned TokLength,
  541. int LoadedID,
  542. unsigned LoadedOffset) {
  543. if (LoadedID < 0) {
  544. assert(LoadedID != -1 && "Loading sentinel FileID");
  545. unsigned Index = unsigned(-LoadedID) - 2;
  546. assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
  547. assert(!SLocEntryLoaded[Index] && "FileID already loaded");
  548. LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
  549. SLocEntryLoaded[Index] = true;
  550. return SourceLocation::getMacroLoc(LoadedOffset);
  551. }
  552. LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
  553. assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
  554. NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
  555. "Ran out of source locations!");
  556. // See createFileID for that +1.
  557. NextLocalOffset += TokLength + 1;
  558. return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
  559. }
  560. const llvm::MemoryBuffer *
  561. SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
  562. const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
  563. assert(IR && "getOrCreateContentCache() cannot return NULL");
  564. return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
  565. }
  566. void SourceManager::overrideFileContents(const FileEntry *SourceFile,
  567. llvm::MemoryBuffer *Buffer,
  568. bool DoNotFree) {
  569. const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
  570. assert(IR && "getOrCreateContentCache() cannot return NULL");
  571. const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
  572. const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
  573. getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
  574. }
  575. void SourceManager::overrideFileContents(const FileEntry *SourceFile,
  576. const FileEntry *NewFile) {
  577. assert(SourceFile->getSize() == NewFile->getSize() &&
  578. "Different sizes, use the FileManager to create a virtual file with "
  579. "the correct size");
  580. assert(FileInfos.count(SourceFile) == 0 &&
  581. "This function should be called at the initialization stage, before "
  582. "any parsing occurs.");
  583. getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
  584. }
  585. void SourceManager::disableFileContentsOverride(const FileEntry *File) {
  586. if (!isFileOverridden(File))
  587. return;
  588. const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
  589. const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
  590. const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
  591. assert(OverriddenFilesInfo);
  592. OverriddenFilesInfo->OverriddenFiles.erase(File);
  593. OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
  594. }
  595. void SourceManager::setFileIsTransient(const FileEntry *File) {
  596. const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
  597. const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
  598. }
  599. StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
  600. bool MyInvalid = false;
  601. const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
  602. if (!SLoc.isFile() || MyInvalid) {
  603. if (Invalid)
  604. *Invalid = true;
  605. return "<<<<<INVALID SOURCE LOCATION>>>>>";
  606. }
  607. const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
  608. Diag, *this, SourceLocation(), &MyInvalid);
  609. if (Invalid)
  610. *Invalid = MyInvalid;
  611. if (MyInvalid)
  612. return "<<<<<INVALID SOURCE LOCATION>>>>>";
  613. return Buf->getBuffer();
  614. }
  615. //===----------------------------------------------------------------------===//
  616. // SourceLocation manipulation methods.
  617. //===----------------------------------------------------------------------===//
  618. /// Return the FileID for a SourceLocation.
  619. ///
  620. /// This is the cache-miss path of getFileID. Not as hot as that function, but
  621. /// still very important. It is responsible for finding the entry in the
  622. /// SLocEntry tables that contains the specified location.
  623. FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
  624. if (!SLocOffset)
  625. return FileID::get(0);
  626. // Now it is time to search for the correct file. See where the SLocOffset
  627. // sits in the global view and consult local or loaded buffers for it.
  628. if (SLocOffset < NextLocalOffset)
  629. return getFileIDLocal(SLocOffset);
  630. return getFileIDLoaded(SLocOffset);
  631. }
  632. /// Return the FileID for a SourceLocation with a low offset.
  633. ///
  634. /// This function knows that the SourceLocation is in a local buffer, not a
  635. /// loaded one.
  636. FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
  637. assert(SLocOffset < NextLocalOffset && "Bad function choice");
  638. // After the first and second level caches, I see two common sorts of
  639. // behavior: 1) a lot of searched FileID's are "near" the cached file
  640. // location or are "near" the cached expansion location. 2) others are just
  641. // completely random and may be a very long way away.
  642. //
  643. // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
  644. // then we fall back to a less cache efficient, but more scalable, binary
  645. // search to find the location.
  646. // See if this is near the file point - worst case we start scanning from the
  647. // most newly created FileID.
  648. const SrcMgr::SLocEntry *I;
  649. if (LastFileIDLookup.ID < 0 ||
  650. LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
  651. // Neither loc prunes our search.
  652. I = LocalSLocEntryTable.end();
  653. } else {
  654. // Perhaps it is near the file point.
  655. I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
  656. }
  657. // Find the FileID that contains this. "I" is an iterator that points to a
  658. // FileID whose offset is known to be larger than SLocOffset.
  659. unsigned NumProbes = 0;
  660. while (true) {
  661. --I;
  662. if (I->getOffset() <= SLocOffset) {
  663. FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
  664. // If this isn't an expansion, remember it. We have good locality across
  665. // FileID lookups.
  666. if (!I->isExpansion())
  667. LastFileIDLookup = Res;
  668. NumLinearScans += NumProbes+1;
  669. return Res;
  670. }
  671. if (++NumProbes == 8)
  672. break;
  673. }
  674. // Convert "I" back into an index. We know that it is an entry whose index is
  675. // larger than the offset we are looking for.
  676. unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
  677. // LessIndex - This is the lower bound of the range that we're searching.
  678. // We know that the offset corresponding to the FileID is is less than
  679. // SLocOffset.
  680. unsigned LessIndex = 0;
  681. NumProbes = 0;
  682. while (true) {
  683. bool Invalid = false;
  684. unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
  685. unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
  686. if (Invalid)
  687. return FileID::get(0);
  688. ++NumProbes;
  689. // If the offset of the midpoint is too large, chop the high side of the
  690. // range to the midpoint.
  691. if (MidOffset > SLocOffset) {
  692. GreaterIndex = MiddleIndex;
  693. continue;
  694. }
  695. // If the middle index contains the value, succeed and return.
  696. // FIXME: This could be made faster by using a function that's aware of
  697. // being in the local area.
  698. if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
  699. FileID Res = FileID::get(MiddleIndex);
  700. // If this isn't a macro expansion, remember it. We have good locality
  701. // across FileID lookups.
  702. if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
  703. LastFileIDLookup = Res;
  704. NumBinaryProbes += NumProbes;
  705. return Res;
  706. }
  707. // Otherwise, move the low-side up to the middle index.
  708. LessIndex = MiddleIndex;
  709. }
  710. }
  711. /// Return the FileID for a SourceLocation with a high offset.
  712. ///
  713. /// This function knows that the SourceLocation is in a loaded buffer, not a
  714. /// local one.
  715. FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
  716. // Sanity checking, otherwise a bug may lead to hanging in release build.
  717. if (SLocOffset < CurrentLoadedOffset) {
  718. assert(0 && "Invalid SLocOffset or bad function choice");
  719. return FileID();
  720. }
  721. // Essentially the same as the local case, but the loaded array is sorted
  722. // in the other direction.
  723. // First do a linear scan from the last lookup position, if possible.
  724. unsigned I;
  725. int LastID = LastFileIDLookup.ID;
  726. if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
  727. I = 0;
  728. else
  729. I = (-LastID - 2) + 1;
  730. unsigned NumProbes;
  731. for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
  732. // Make sure the entry is loaded!
  733. const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
  734. if (E.getOffset() <= SLocOffset) {
  735. FileID Res = FileID::get(-int(I) - 2);
  736. if (!E.isExpansion())
  737. LastFileIDLookup = Res;
  738. NumLinearScans += NumProbes + 1;
  739. return Res;
  740. }
  741. }
  742. // Linear scan failed. Do the binary search. Note the reverse sorting of the
  743. // table: GreaterIndex is the one where the offset is greater, which is
  744. // actually a lower index!
  745. unsigned GreaterIndex = I;
  746. unsigned LessIndex = LoadedSLocEntryTable.size();
  747. NumProbes = 0;
  748. while (true) {
  749. ++NumProbes;
  750. unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
  751. const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
  752. if (E.getOffset() == 0)
  753. return FileID(); // invalid entry.
  754. ++NumProbes;
  755. if (E.getOffset() > SLocOffset) {
  756. // Sanity checking, otherwise a bug may lead to hanging in release build.
  757. if (GreaterIndex == MiddleIndex) {
  758. assert(0 && "binary search missed the entry");
  759. return FileID();
  760. }
  761. GreaterIndex = MiddleIndex;
  762. continue;
  763. }
  764. if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
  765. FileID Res = FileID::get(-int(MiddleIndex) - 2);
  766. if (!E.isExpansion())
  767. LastFileIDLookup = Res;
  768. NumBinaryProbes += NumProbes;
  769. return Res;
  770. }
  771. // Sanity checking, otherwise a bug may lead to hanging in release build.
  772. if (LessIndex == MiddleIndex) {
  773. assert(0 && "binary search missed the entry");
  774. return FileID();
  775. }
  776. LessIndex = MiddleIndex;
  777. }
  778. }
  779. SourceLocation SourceManager::
  780. getExpansionLocSlowCase(SourceLocation Loc) const {
  781. do {
  782. // Note: If Loc indicates an offset into a token that came from a macro
  783. // expansion (e.g. the 5th character of the token) we do not want to add
  784. // this offset when going to the expansion location. The expansion
  785. // location is the macro invocation, which the offset has nothing to do
  786. // with. This is unlike when we get the spelling loc, because the offset
  787. // directly correspond to the token whose spelling we're inspecting.
  788. Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
  789. } while (!Loc.isFileID());
  790. return Loc;
  791. }
  792. SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
  793. do {
  794. std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
  795. Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
  796. Loc = Loc.getLocWithOffset(LocInfo.second);
  797. } while (!Loc.isFileID());
  798. return Loc;
  799. }
  800. SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
  801. do {
  802. if (isMacroArgExpansion(Loc))
  803. Loc = getImmediateSpellingLoc(Loc);
  804. else
  805. Loc = getImmediateExpansionRange(Loc).getBegin();
  806. } while (!Loc.isFileID());
  807. return Loc;
  808. }
  809. std::pair<FileID, unsigned>
  810. SourceManager::getDecomposedExpansionLocSlowCase(
  811. const SrcMgr::SLocEntry *E) const {
  812. // If this is an expansion record, walk through all the expansion points.
  813. FileID FID;
  814. SourceLocation Loc;
  815. unsigned Offset;
  816. do {
  817. Loc = E->getExpansion().getExpansionLocStart();
  818. FID = getFileID(Loc);
  819. E = &getSLocEntry(FID);
  820. Offset = Loc.getOffset()-E->getOffset();
  821. } while (!Loc.isFileID());
  822. return std::make_pair(FID, Offset);
  823. }
  824. std::pair<FileID, unsigned>
  825. SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
  826. unsigned Offset) const {
  827. // If this is an expansion record, walk through all the expansion points.
  828. FileID FID;
  829. SourceLocation Loc;
  830. do {
  831. Loc = E->getExpansion().getSpellingLoc();
  832. Loc = Loc.getLocWithOffset(Offset);
  833. FID = getFileID(Loc);
  834. E = &getSLocEntry(FID);
  835. Offset = Loc.getOffset()-E->getOffset();
  836. } while (!Loc.isFileID());
  837. return std::make_pair(FID, Offset);
  838. }
  839. /// getImmediateSpellingLoc - Given a SourceLocation object, return the
  840. /// spelling location referenced by the ID. This is the first level down
  841. /// towards the place where the characters that make up the lexed token can be
  842. /// found. This should not generally be used by clients.
  843. SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
  844. if (Loc.isFileID()) return Loc;
  845. std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
  846. Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
  847. return Loc.getLocWithOffset(LocInfo.second);
  848. }
  849. /// getImmediateExpansionRange - Loc is required to be an expansion location.
  850. /// Return the start/end of the expansion information.
  851. CharSourceRange
  852. SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
  853. assert(Loc.isMacroID() && "Not a macro expansion loc!");
  854. const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
  855. return Expansion.getExpansionLocRange();
  856. }
  857. SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
  858. while (isMacroArgExpansion(Loc))
  859. Loc = getImmediateSpellingLoc(Loc);
  860. return Loc;
  861. }
  862. /// getExpansionRange - Given a SourceLocation object, return the range of
  863. /// tokens covered by the expansion in the ultimate file.
  864. CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
  865. if (Loc.isFileID())
  866. return CharSourceRange(SourceRange(Loc, Loc), true);
  867. CharSourceRange Res = getImmediateExpansionRange(Loc);
  868. // Fully resolve the start and end locations to their ultimate expansion
  869. // points.
  870. while (!Res.getBegin().isFileID())
  871. Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
  872. while (!Res.getEnd().isFileID()) {
  873. CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
  874. Res.setEnd(EndRange.getEnd());
  875. Res.setTokenRange(EndRange.isTokenRange());
  876. }
  877. return Res;
  878. }
  879. bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
  880. SourceLocation *StartLoc) const {
  881. if (!Loc.isMacroID()) return false;
  882. FileID FID = getFileID(Loc);
  883. const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
  884. if (!Expansion.isMacroArgExpansion()) return false;
  885. if (StartLoc)
  886. *StartLoc = Expansion.getExpansionLocStart();
  887. return true;
  888. }
  889. bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
  890. if (!Loc.isMacroID()) return false;
  891. FileID FID = getFileID(Loc);
  892. const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
  893. return Expansion.isMacroBodyExpansion();
  894. }
  895. bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
  896. SourceLocation *MacroBegin) const {
  897. assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
  898. std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
  899. if (DecompLoc.second > 0)
  900. return false; // Does not point at the start of expansion range.
  901. bool Invalid = false;
  902. const SrcMgr::ExpansionInfo &ExpInfo =
  903. getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
  904. if (Invalid)
  905. return false;
  906. SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
  907. if (ExpInfo.isMacroArgExpansion()) {
  908. // For macro argument expansions, check if the previous FileID is part of
  909. // the same argument expansion, in which case this Loc is not at the
  910. // beginning of the expansion.
  911. FileID PrevFID = getPreviousFileID(DecompLoc.first);
  912. if (!PrevFID.isInvalid()) {
  913. const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
  914. if (Invalid)
  915. return false;
  916. if (PrevEntry.isExpansion() &&
  917. PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
  918. return false;
  919. }
  920. }
  921. if (MacroBegin)
  922. *MacroBegin = ExpLoc;
  923. return true;
  924. }
  925. bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
  926. SourceLocation *MacroEnd) const {
  927. assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
  928. FileID FID = getFileID(Loc);
  929. SourceLocation NextLoc = Loc.getLocWithOffset(1);
  930. if (isInFileID(NextLoc, FID))
  931. return false; // Does not point at the end of expansion range.
  932. bool Invalid = false;
  933. const SrcMgr::ExpansionInfo &ExpInfo =
  934. getSLocEntry(FID, &Invalid).getExpansion();
  935. if (Invalid)
  936. return false;
  937. if (ExpInfo.isMacroArgExpansion()) {
  938. // For macro argument expansions, check if the next FileID is part of the
  939. // same argument expansion, in which case this Loc is not at the end of the
  940. // expansion.
  941. FileID NextFID = getNextFileID(FID);
  942. if (!NextFID.isInvalid()) {
  943. const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
  944. if (Invalid)
  945. return false;
  946. if (NextEntry.isExpansion() &&
  947. NextEntry.getExpansion().getExpansionLocStart() ==
  948. ExpInfo.getExpansionLocStart())
  949. return false;
  950. }
  951. }
  952. if (MacroEnd)
  953. *MacroEnd = ExpInfo.getExpansionLocEnd();
  954. return true;
  955. }
  956. //===----------------------------------------------------------------------===//
  957. // Queries about the code at a SourceLocation.
  958. //===----------------------------------------------------------------------===//
  959. /// getCharacterData - Return a pointer to the start of the specified location
  960. /// in the appropriate MemoryBuffer.
  961. const char *SourceManager::getCharacterData(SourceLocation SL,
  962. bool *Invalid) const {
  963. // Note that this is a hot function in the getSpelling() path, which is
  964. // heavily used by -E mode.
  965. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
  966. // Note that calling 'getBuffer()' may lazily page in a source file.
  967. bool CharDataInvalid = false;
  968. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
  969. if (CharDataInvalid || !Entry.isFile()) {
  970. if (Invalid)
  971. *Invalid = true;
  972. return "<<<<INVALID BUFFER>>>>";
  973. }
  974. const llvm::MemoryBuffer *Buffer =
  975. Entry.getFile().getContentCache()->getBuffer(
  976. Diag, *this, SourceLocation(), &CharDataInvalid);
  977. if (Invalid)
  978. *Invalid = CharDataInvalid;
  979. return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
  980. }
  981. /// getColumnNumber - Return the column # for the specified file position.
  982. /// this is significantly cheaper to compute than the line number.
  983. unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
  984. bool *Invalid) const {
  985. bool MyInvalid = false;
  986. const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
  987. if (Invalid)
  988. *Invalid = MyInvalid;
  989. if (MyInvalid)
  990. return 1;
  991. // It is okay to request a position just past the end of the buffer.
  992. if (FilePos > MemBuf->getBufferSize()) {
  993. if (Invalid)
  994. *Invalid = true;
  995. return 1;
  996. }
  997. const char *Buf = MemBuf->getBufferStart();
  998. // See if we just calculated the line number for this FilePos and can use
  999. // that to lookup the start of the line instead of searching for it.
  1000. if (LastLineNoFileIDQuery == FID &&
  1001. LastLineNoContentCache->SourceLineCache != nullptr &&
  1002. LastLineNoResult < LastLineNoContentCache->NumLines) {
  1003. unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
  1004. unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
  1005. unsigned LineEnd = SourceLineCache[LastLineNoResult];
  1006. if (FilePos >= LineStart && FilePos < LineEnd) {
  1007. // LineEnd is the LineStart of the next line.
  1008. // A line ends with separator LF or CR+LF on Windows.
  1009. // FilePos might point to the last separator,
  1010. // but we need a column number at most 1 + the last column.
  1011. if (FilePos + 1 == LineEnd && FilePos > LineStart) {
  1012. if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
  1013. --FilePos;
  1014. }
  1015. return FilePos - LineStart + 1;
  1016. }
  1017. }
  1018. unsigned LineStart = FilePos;
  1019. while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
  1020. --LineStart;
  1021. return FilePos-LineStart+1;
  1022. }
  1023. // isInvalid - Return the result of calling loc.isInvalid(), and
  1024. // if Invalid is not null, set its value to same.
  1025. template<typename LocType>
  1026. static bool isInvalid(LocType Loc, bool *Invalid) {
  1027. bool MyInvalid = Loc.isInvalid();
  1028. if (Invalid)
  1029. *Invalid = MyInvalid;
  1030. return MyInvalid;
  1031. }
  1032. unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
  1033. bool *Invalid) const {
  1034. if (isInvalid(Loc, Invalid)) return 0;
  1035. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
  1036. return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
  1037. }
  1038. unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
  1039. bool *Invalid) const {
  1040. if (isInvalid(Loc, Invalid)) return 0;
  1041. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1042. return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
  1043. }
  1044. unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
  1045. bool *Invalid) const {
  1046. PresumedLoc PLoc = getPresumedLoc(Loc);
  1047. if (isInvalid(PLoc, Invalid)) return 0;
  1048. return PLoc.getColumn();
  1049. }
  1050. #ifdef __SSE2__
  1051. #include <emmintrin.h>
  1052. #endif
  1053. static LLVM_ATTRIBUTE_NOINLINE void
  1054. ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
  1055. llvm::BumpPtrAllocator &Alloc,
  1056. const SourceManager &SM, bool &Invalid);
  1057. static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
  1058. llvm::BumpPtrAllocator &Alloc,
  1059. const SourceManager &SM, bool &Invalid) {
  1060. // Note that calling 'getBuffer()' may lazily page in the file.
  1061. const MemoryBuffer *Buffer =
  1062. FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
  1063. if (Invalid)
  1064. return;
  1065. // Find the file offsets of all of the *physical* source lines. This does
  1066. // not look at trigraphs, escaped newlines, or anything else tricky.
  1067. SmallVector<unsigned, 256> LineOffsets;
  1068. // Line #1 starts at char 0.
  1069. LineOffsets.push_back(0);
  1070. const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
  1071. const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
  1072. unsigned I = 0;
  1073. while (true) {
  1074. // Skip over the contents of the line.
  1075. while (Buf[I] != '\n' && Buf[I] != '\r' && Buf[I] != '\0')
  1076. ++I;
  1077. if (Buf[I] == '\n' || Buf[I] == '\r') {
  1078. // If this is \r\n, skip both characters.
  1079. if (Buf[I] == '\r' && Buf[I+1] == '\n')
  1080. ++I;
  1081. ++I;
  1082. LineOffsets.push_back(I);
  1083. } else {
  1084. // Otherwise, this is a NUL. If end of file, exit.
  1085. if (Buf+I == End) break;
  1086. ++I;
  1087. }
  1088. }
  1089. // Copy the offsets into the FileInfo structure.
  1090. FI->NumLines = LineOffsets.size();
  1091. FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
  1092. std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
  1093. }
  1094. /// getLineNumber - Given a SourceLocation, return the spelling line number
  1095. /// for the position indicated. This requires building and caching a table of
  1096. /// line offsets for the MemoryBuffer, so this is not cheap: use only when
  1097. /// about to emit a diagnostic.
  1098. unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
  1099. bool *Invalid) const {
  1100. if (FID.isInvalid()) {
  1101. if (Invalid)
  1102. *Invalid = true;
  1103. return 1;
  1104. }
  1105. ContentCache *Content;
  1106. if (LastLineNoFileIDQuery == FID)
  1107. Content = LastLineNoContentCache;
  1108. else {
  1109. bool MyInvalid = false;
  1110. const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
  1111. if (MyInvalid || !Entry.isFile()) {
  1112. if (Invalid)
  1113. *Invalid = true;
  1114. return 1;
  1115. }
  1116. Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
  1117. }
  1118. // If this is the first use of line information for this buffer, compute the
  1119. /// SourceLineCache for it on demand.
  1120. if (!Content->SourceLineCache) {
  1121. bool MyInvalid = false;
  1122. ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
  1123. if (Invalid)
  1124. *Invalid = MyInvalid;
  1125. if (MyInvalid)
  1126. return 1;
  1127. } else if (Invalid)
  1128. *Invalid = false;
  1129. // Okay, we know we have a line number table. Do a binary search to find the
  1130. // line number that this character position lands on.
  1131. unsigned *SourceLineCache = Content->SourceLineCache;
  1132. unsigned *SourceLineCacheStart = SourceLineCache;
  1133. unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
  1134. unsigned QueriedFilePos = FilePos+1;
  1135. // FIXME: I would like to be convinced that this code is worth being as
  1136. // complicated as it is, binary search isn't that slow.
  1137. //
  1138. // If it is worth being optimized, then in my opinion it could be more
  1139. // performant, simpler, and more obviously correct by just "galloping" outward
  1140. // from the queried file position. In fact, this could be incorporated into a
  1141. // generic algorithm such as lower_bound_with_hint.
  1142. //
  1143. // If someone gives me a test case where this matters, and I will do it! - DWD
  1144. // If the previous query was to the same file, we know both the file pos from
  1145. // that query and the line number returned. This allows us to narrow the
  1146. // search space from the entire file to something near the match.
  1147. if (LastLineNoFileIDQuery == FID) {
  1148. if (QueriedFilePos >= LastLineNoFilePos) {
  1149. // FIXME: Potential overflow?
  1150. SourceLineCache = SourceLineCache+LastLineNoResult-1;
  1151. // The query is likely to be nearby the previous one. Here we check to
  1152. // see if it is within 5, 10 or 20 lines. It can be far away in cases
  1153. // where big comment blocks and vertical whitespace eat up lines but
  1154. // contribute no tokens.
  1155. if (SourceLineCache+5 < SourceLineCacheEnd) {
  1156. if (SourceLineCache[5] > QueriedFilePos)
  1157. SourceLineCacheEnd = SourceLineCache+5;
  1158. else if (SourceLineCache+10 < SourceLineCacheEnd) {
  1159. if (SourceLineCache[10] > QueriedFilePos)
  1160. SourceLineCacheEnd = SourceLineCache+10;
  1161. else if (SourceLineCache+20 < SourceLineCacheEnd) {
  1162. if (SourceLineCache[20] > QueriedFilePos)
  1163. SourceLineCacheEnd = SourceLineCache+20;
  1164. }
  1165. }
  1166. }
  1167. } else {
  1168. if (LastLineNoResult < Content->NumLines)
  1169. SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
  1170. }
  1171. }
  1172. unsigned *Pos
  1173. = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
  1174. unsigned LineNo = Pos-SourceLineCacheStart;
  1175. LastLineNoFileIDQuery = FID;
  1176. LastLineNoContentCache = Content;
  1177. LastLineNoFilePos = QueriedFilePos;
  1178. LastLineNoResult = LineNo;
  1179. return LineNo;
  1180. }
  1181. unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
  1182. bool *Invalid) const {
  1183. if (isInvalid(Loc, Invalid)) return 0;
  1184. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
  1185. return getLineNumber(LocInfo.first, LocInfo.second);
  1186. }
  1187. unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
  1188. bool *Invalid) const {
  1189. if (isInvalid(Loc, Invalid)) return 0;
  1190. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1191. return getLineNumber(LocInfo.first, LocInfo.second);
  1192. }
  1193. unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
  1194. bool *Invalid) const {
  1195. PresumedLoc PLoc = getPresumedLoc(Loc);
  1196. if (isInvalid(PLoc, Invalid)) return 0;
  1197. return PLoc.getLine();
  1198. }
  1199. /// getFileCharacteristic - return the file characteristic of the specified
  1200. /// source location, indicating whether this is a normal file, a system
  1201. /// header, or an "implicit extern C" system header.
  1202. ///
  1203. /// This state can be modified with flags on GNU linemarker directives like:
  1204. /// # 4 "foo.h" 3
  1205. /// which changes all source locations in the current file after that to be
  1206. /// considered to be from a system header.
  1207. SrcMgr::CharacteristicKind
  1208. SourceManager::getFileCharacteristic(SourceLocation Loc) const {
  1209. assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
  1210. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1211. bool Invalid = false;
  1212. const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
  1213. if (Invalid || !SEntry.isFile())
  1214. return C_User;
  1215. const SrcMgr::FileInfo &FI = SEntry.getFile();
  1216. // If there are no #line directives in this file, just return the whole-file
  1217. // state.
  1218. if (!FI.hasLineDirectives())
  1219. return FI.getFileCharacteristic();
  1220. assert(LineTable && "Can't have linetable entries without a LineTable!");
  1221. // See if there is a #line directive before the location.
  1222. const LineEntry *Entry =
  1223. LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
  1224. // If this is before the first line marker, use the file characteristic.
  1225. if (!Entry)
  1226. return FI.getFileCharacteristic();
  1227. return Entry->FileKind;
  1228. }
  1229. /// Return the filename or buffer identifier of the buffer the location is in.
  1230. /// Note that this name does not respect \#line directives. Use getPresumedLoc
  1231. /// for normal clients.
  1232. StringRef SourceManager::getBufferName(SourceLocation Loc,
  1233. bool *Invalid) const {
  1234. if (isInvalid(Loc, Invalid)) return "<invalid loc>";
  1235. return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
  1236. }
  1237. /// getPresumedLoc - This method returns the "presumed" location of a
  1238. /// SourceLocation specifies. A "presumed location" can be modified by \#line
  1239. /// or GNU line marker directives. This provides a view on the data that a
  1240. /// user should see in diagnostics, for example.
  1241. ///
  1242. /// Note that a presumed location is always given as the expansion point of an
  1243. /// expansion location, not at the spelling location.
  1244. PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
  1245. bool UseLineDirectives) const {
  1246. if (Loc.isInvalid()) return PresumedLoc();
  1247. // Presumed locations are always for expansion points.
  1248. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1249. bool Invalid = false;
  1250. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
  1251. if (Invalid || !Entry.isFile())
  1252. return PresumedLoc();
  1253. const SrcMgr::FileInfo &FI = Entry.getFile();
  1254. const SrcMgr::ContentCache *C = FI.getContentCache();
  1255. // To get the source name, first consult the FileEntry (if one exists)
  1256. // before the MemBuffer as this will avoid unnecessarily paging in the
  1257. // MemBuffer.
  1258. FileID FID = LocInfo.first;
  1259. StringRef Filename;
  1260. if (C->OrigEntry)
  1261. Filename = C->OrigEntry->getName();
  1262. else
  1263. Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
  1264. unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
  1265. if (Invalid)
  1266. return PresumedLoc();
  1267. unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
  1268. if (Invalid)
  1269. return PresumedLoc();
  1270. SourceLocation IncludeLoc = FI.getIncludeLoc();
  1271. // If we have #line directives in this file, update and overwrite the physical
  1272. // location info if appropriate.
  1273. if (UseLineDirectives && FI.hasLineDirectives()) {
  1274. assert(LineTable && "Can't have linetable entries without a LineTable!");
  1275. // See if there is a #line directive before this. If so, get it.
  1276. if (const LineEntry *Entry =
  1277. LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
  1278. // If the LineEntry indicates a filename, use it.
  1279. if (Entry->FilenameID != -1) {
  1280. Filename = LineTable->getFilename(Entry->FilenameID);
  1281. // The contents of files referenced by #line are not in the
  1282. // SourceManager
  1283. FID = FileID::get(0);
  1284. }
  1285. // Use the line number specified by the LineEntry. This line number may
  1286. // be multiple lines down from the line entry. Add the difference in
  1287. // physical line numbers from the query point and the line marker to the
  1288. // total.
  1289. unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
  1290. LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
  1291. // Note that column numbers are not molested by line markers.
  1292. // Handle virtual #include manipulation.
  1293. if (Entry->IncludeOffset) {
  1294. IncludeLoc = getLocForStartOfFile(LocInfo.first);
  1295. IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
  1296. }
  1297. }
  1298. }
  1299. return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
  1300. }
  1301. /// Returns whether the PresumedLoc for a given SourceLocation is
  1302. /// in the main file.
  1303. ///
  1304. /// This computes the "presumed" location for a SourceLocation, then checks
  1305. /// whether it came from a file other than the main file. This is different
  1306. /// from isWrittenInMainFile() because it takes line marker directives into
  1307. /// account.
  1308. bool SourceManager::isInMainFile(SourceLocation Loc) const {
  1309. if (Loc.isInvalid()) return false;
  1310. // Presumed locations are always for expansion points.
  1311. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1312. bool Invalid = false;
  1313. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
  1314. if (Invalid || !Entry.isFile())
  1315. return false;
  1316. const SrcMgr::FileInfo &FI = Entry.getFile();
  1317. // Check if there is a line directive for this location.
  1318. if (FI.hasLineDirectives())
  1319. if (const LineEntry *Entry =
  1320. LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
  1321. if (Entry->IncludeOffset)
  1322. return false;
  1323. return FI.getIncludeLoc().isInvalid();
  1324. }
  1325. /// The size of the SLocEntry that \p FID represents.
  1326. unsigned SourceManager::getFileIDSize(FileID FID) const {
  1327. bool Invalid = false;
  1328. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1329. if (Invalid)
  1330. return 0;
  1331. int ID = FID.ID;
  1332. unsigned NextOffset;
  1333. if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
  1334. NextOffset = getNextLocalOffset();
  1335. else if (ID+1 == -1)
  1336. NextOffset = MaxLoadedOffset;
  1337. else
  1338. NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
  1339. return NextOffset - Entry.getOffset() - 1;
  1340. }
  1341. //===----------------------------------------------------------------------===//
  1342. // Other miscellaneous methods.
  1343. //===----------------------------------------------------------------------===//
  1344. /// Get the source location for the given file:line:col triplet.
  1345. ///
  1346. /// If the source file is included multiple times, the source location will
  1347. /// be based upon an arbitrary inclusion.
  1348. SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
  1349. unsigned Line,
  1350. unsigned Col) const {
  1351. assert(SourceFile && "Null source file!");
  1352. assert(Line && Col && "Line and column should start from 1!");
  1353. FileID FirstFID = translateFile(SourceFile);
  1354. return translateLineCol(FirstFID, Line, Col);
  1355. }
  1356. /// Get the FileID for the given file.
  1357. ///
  1358. /// If the source file is included multiple times, the FileID will be the
  1359. /// first inclusion.
  1360. FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
  1361. assert(SourceFile && "Null source file!");
  1362. // First, check the main file ID, since it is common to look for a
  1363. // location in the main file.
  1364. if (MainFileID.isValid()) {
  1365. bool Invalid = false;
  1366. const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
  1367. if (Invalid)
  1368. return FileID();
  1369. if (MainSLoc.isFile()) {
  1370. const ContentCache *MainContentCache =
  1371. MainSLoc.getFile().getContentCache();
  1372. if (MainContentCache && MainContentCache->OrigEntry == SourceFile)
  1373. return MainFileID;
  1374. }
  1375. }
  1376. // The location we're looking for isn't in the main file; look
  1377. // through all of the local source locations.
  1378. for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
  1379. bool Invalid = false;
  1380. const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
  1381. if (Invalid)
  1382. return FileID();
  1383. if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
  1384. SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
  1385. return FileID::get(I);
  1386. }
  1387. // If that still didn't help, try the modules.
  1388. for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
  1389. const SLocEntry &SLoc = getLoadedSLocEntry(I);
  1390. if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
  1391. SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
  1392. return FileID::get(-int(I) - 2);
  1393. }
  1394. return FileID();
  1395. }
  1396. /// Get the source location in \arg FID for the given line:col.
  1397. /// Returns null location if \arg FID is not a file SLocEntry.
  1398. SourceLocation SourceManager::translateLineCol(FileID FID,
  1399. unsigned Line,
  1400. unsigned Col) const {
  1401. // Lines are used as a one-based index into a zero-based array. This assert
  1402. // checks for possible buffer underruns.
  1403. assert(Line && Col && "Line and column should start from 1!");
  1404. if (FID.isInvalid())
  1405. return SourceLocation();
  1406. bool Invalid = false;
  1407. const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1408. if (Invalid)
  1409. return SourceLocation();
  1410. if (!Entry.isFile())
  1411. return SourceLocation();
  1412. SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
  1413. if (Line == 1 && Col == 1)
  1414. return FileLoc;
  1415. ContentCache *Content
  1416. = const_cast<ContentCache *>(Entry.getFile().getContentCache());
  1417. if (!Content)
  1418. return SourceLocation();
  1419. // If this is the first use of line information for this buffer, compute the
  1420. // SourceLineCache for it on demand.
  1421. if (!Content->SourceLineCache) {
  1422. bool MyInvalid = false;
  1423. ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
  1424. if (MyInvalid)
  1425. return SourceLocation();
  1426. }
  1427. if (Line > Content->NumLines) {
  1428. unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
  1429. if (Size > 0)
  1430. --Size;
  1431. return FileLoc.getLocWithOffset(Size);
  1432. }
  1433. const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
  1434. unsigned FilePos = Content->SourceLineCache[Line - 1];
  1435. const char *Buf = Buffer->getBufferStart() + FilePos;
  1436. unsigned BufLength = Buffer->getBufferSize() - FilePos;
  1437. if (BufLength == 0)
  1438. return FileLoc.getLocWithOffset(FilePos);
  1439. unsigned i = 0;
  1440. // Check that the given column is valid.
  1441. while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
  1442. ++i;
  1443. return FileLoc.getLocWithOffset(FilePos + i);
  1444. }
  1445. /// Compute a map of macro argument chunks to their expanded source
  1446. /// location. Chunks that are not part of a macro argument will map to an
  1447. /// invalid source location. e.g. if a file contains one macro argument at
  1448. /// offset 100 with length 10, this is how the map will be formed:
  1449. /// 0 -> SourceLocation()
  1450. /// 100 -> Expanded macro arg location
  1451. /// 110 -> SourceLocation()
  1452. void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
  1453. FileID FID) const {
  1454. assert(FID.isValid());
  1455. // Initially no macro argument chunk is present.
  1456. MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
  1457. int ID = FID.ID;
  1458. while (true) {
  1459. ++ID;
  1460. // Stop if there are no more FileIDs to check.
  1461. if (ID > 0) {
  1462. if (unsigned(ID) >= local_sloc_entry_size())
  1463. return;
  1464. } else if (ID == -1) {
  1465. return;
  1466. }
  1467. bool Invalid = false;
  1468. const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
  1469. if (Invalid)
  1470. return;
  1471. if (Entry.isFile()) {
  1472. SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
  1473. if (IncludeLoc.isInvalid())
  1474. continue;
  1475. if (!isInFileID(IncludeLoc, FID))
  1476. return; // No more files/macros that may be "contained" in this file.
  1477. // Skip the files/macros of the #include'd file, we only care about macros
  1478. // that lexed macro arguments from our file.
  1479. if (Entry.getFile().NumCreatedFIDs)
  1480. ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
  1481. continue;
  1482. }
  1483. const ExpansionInfo &ExpInfo = Entry.getExpansion();
  1484. if (ExpInfo.getExpansionLocStart().isFileID()) {
  1485. if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
  1486. return; // No more files/macros that may be "contained" in this file.
  1487. }
  1488. if (!ExpInfo.isMacroArgExpansion())
  1489. continue;
  1490. associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
  1491. ExpInfo.getSpellingLoc(),
  1492. SourceLocation::getMacroLoc(Entry.getOffset()),
  1493. getFileIDSize(FileID::get(ID)));
  1494. }
  1495. }
  1496. void SourceManager::associateFileChunkWithMacroArgExp(
  1497. MacroArgsMap &MacroArgsCache,
  1498. FileID FID,
  1499. SourceLocation SpellLoc,
  1500. SourceLocation ExpansionLoc,
  1501. unsigned ExpansionLength) const {
  1502. if (!SpellLoc.isFileID()) {
  1503. unsigned SpellBeginOffs = SpellLoc.getOffset();
  1504. unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
  1505. // The spelling range for this macro argument expansion can span multiple
  1506. // consecutive FileID entries. Go through each entry contained in the
  1507. // spelling range and if one is itself a macro argument expansion, recurse
  1508. // and associate the file chunk that it represents.
  1509. FileID SpellFID; // Current FileID in the spelling range.
  1510. unsigned SpellRelativeOffs;
  1511. std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
  1512. while (true) {
  1513. const SLocEntry &Entry = getSLocEntry(SpellFID);
  1514. unsigned SpellFIDBeginOffs = Entry.getOffset();
  1515. unsigned SpellFIDSize = getFileIDSize(SpellFID);
  1516. unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
  1517. const ExpansionInfo &Info = Entry.getExpansion();
  1518. if (Info.isMacroArgExpansion()) {
  1519. unsigned CurrSpellLength;
  1520. if (SpellFIDEndOffs < SpellEndOffs)
  1521. CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
  1522. else
  1523. CurrSpellLength = ExpansionLength;
  1524. associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
  1525. Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
  1526. ExpansionLoc, CurrSpellLength);
  1527. }
  1528. if (SpellFIDEndOffs >= SpellEndOffs)
  1529. return; // we covered all FileID entries in the spelling range.
  1530. // Move to the next FileID entry in the spelling range.
  1531. unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
  1532. ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
  1533. ExpansionLength -= advance;
  1534. ++SpellFID.ID;
  1535. SpellRelativeOffs = 0;
  1536. }
  1537. }
  1538. assert(SpellLoc.isFileID());
  1539. unsigned BeginOffs;
  1540. if (!isInFileID(SpellLoc, FID, &BeginOffs))
  1541. return;
  1542. unsigned EndOffs = BeginOffs + ExpansionLength;
  1543. // Add a new chunk for this macro argument. A previous macro argument chunk
  1544. // may have been lexed again, so e.g. if the map is
  1545. // 0 -> SourceLocation()
  1546. // 100 -> Expanded loc #1
  1547. // 110 -> SourceLocation()
  1548. // and we found a new macro FileID that lexed from offset 105 with length 3,
  1549. // the new map will be:
  1550. // 0 -> SourceLocation()
  1551. // 100 -> Expanded loc #1
  1552. // 105 -> Expanded loc #2
  1553. // 108 -> Expanded loc #1
  1554. // 110 -> SourceLocation()
  1555. //
  1556. // Since re-lexed macro chunks will always be the same size or less of
  1557. // previous chunks, we only need to find where the ending of the new macro
  1558. // chunk is mapped to and update the map with new begin/end mappings.
  1559. MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
  1560. --I;
  1561. SourceLocation EndOffsMappedLoc = I->second;
  1562. MacroArgsCache[BeginOffs] = ExpansionLoc;
  1563. MacroArgsCache[EndOffs] = EndOffsMappedLoc;
  1564. }
  1565. /// If \arg Loc points inside a function macro argument, the returned
  1566. /// location will be the macro location in which the argument was expanded.
  1567. /// If a macro argument is used multiple times, the expanded location will
  1568. /// be at the first expansion of the argument.
  1569. /// e.g.
  1570. /// MY_MACRO(foo);
  1571. /// ^
  1572. /// Passing a file location pointing at 'foo', will yield a macro location
  1573. /// where 'foo' was expanded into.
  1574. SourceLocation
  1575. SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
  1576. if (Loc.isInvalid() || !Loc.isFileID())
  1577. return Loc;
  1578. FileID FID;
  1579. unsigned Offset;
  1580. std::tie(FID, Offset) = getDecomposedLoc(Loc);
  1581. if (FID.isInvalid())
  1582. return Loc;
  1583. std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
  1584. if (!MacroArgsCache) {
  1585. MacroArgsCache = std::make_unique<MacroArgsMap>();
  1586. computeMacroArgsCache(*MacroArgsCache, FID);
  1587. }
  1588. assert(!MacroArgsCache->empty());
  1589. MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
  1590. --I;
  1591. unsigned MacroArgBeginOffs = I->first;
  1592. SourceLocation MacroArgExpandedLoc = I->second;
  1593. if (MacroArgExpandedLoc.isValid())
  1594. return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
  1595. return Loc;
  1596. }
  1597. std::pair<FileID, unsigned>
  1598. SourceManager::getDecomposedIncludedLoc(FileID FID) const {
  1599. if (FID.isInvalid())
  1600. return std::make_pair(FileID(), 0);
  1601. // Uses IncludedLocMap to retrieve/cache the decomposed loc.
  1602. using DecompTy = std::pair<FileID, unsigned>;
  1603. auto InsertOp = IncludedLocMap.try_emplace(FID);
  1604. DecompTy &DecompLoc = InsertOp.first->second;
  1605. if (!InsertOp.second)
  1606. return DecompLoc; // already in map.
  1607. SourceLocation UpperLoc;
  1608. bool Invalid = false;
  1609. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1610. if (!Invalid) {
  1611. if (Entry.isExpansion())
  1612. UpperLoc = Entry.getExpansion().getExpansionLocStart();
  1613. else
  1614. UpperLoc = Entry.getFile().getIncludeLoc();
  1615. }
  1616. if (UpperLoc.isValid())
  1617. DecompLoc = getDecomposedLoc(UpperLoc);
  1618. return DecompLoc;
  1619. }
  1620. /// Given a decomposed source location, move it up the include/expansion stack
  1621. /// to the parent source location. If this is possible, return the decomposed
  1622. /// version of the parent in Loc and return false. If Loc is the top-level
  1623. /// entry, return true and don't modify it.
  1624. static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
  1625. const SourceManager &SM) {
  1626. std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
  1627. if (UpperLoc.first.isInvalid())
  1628. return true; // We reached the top.
  1629. Loc = UpperLoc;
  1630. return false;
  1631. }
  1632. /// Return the cache entry for comparing the given file IDs
  1633. /// for isBeforeInTranslationUnit.
  1634. InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
  1635. FileID RFID) const {
  1636. // This is a magic number for limiting the cache size. It was experimentally
  1637. // derived from a small Objective-C project (where the cache filled
  1638. // out to ~250 items). We can make it larger if necessary.
  1639. enum { MagicCacheSize = 300 };
  1640. IsBeforeInTUCacheKey Key(LFID, RFID);
  1641. // If the cache size isn't too large, do a lookup and if necessary default
  1642. // construct an entry. We can then return it to the caller for direct
  1643. // use. When they update the value, the cache will get automatically
  1644. // updated as well.
  1645. if (IBTUCache.size() < MagicCacheSize)
  1646. return IBTUCache[Key];
  1647. // Otherwise, do a lookup that will not construct a new value.
  1648. InBeforeInTUCache::iterator I = IBTUCache.find(Key);
  1649. if (I != IBTUCache.end())
  1650. return I->second;
  1651. // Fall back to the overflow value.
  1652. return IBTUCacheOverflow;
  1653. }
  1654. /// Determines the order of 2 source locations in the translation unit.
  1655. ///
  1656. /// \returns true if LHS source location comes before RHS, false otherwise.
  1657. bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
  1658. SourceLocation RHS) const {
  1659. assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
  1660. if (LHS == RHS)
  1661. return false;
  1662. std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
  1663. std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
  1664. // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
  1665. // is a serialized one referring to a file that was removed after we loaded
  1666. // the PCH.
  1667. if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
  1668. return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
  1669. std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
  1670. if (InSameTU.first)
  1671. return InSameTU.second;
  1672. // If we arrived here, the location is either in a built-ins buffer or
  1673. // associated with global inline asm. PR5662 and PR22576 are examples.
  1674. StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
  1675. StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
  1676. bool LIsBuiltins = LB == "<built-in>";
  1677. bool RIsBuiltins = RB == "<built-in>";
  1678. // Sort built-in before non-built-in.
  1679. if (LIsBuiltins || RIsBuiltins) {
  1680. if (LIsBuiltins != RIsBuiltins)
  1681. return LIsBuiltins;
  1682. // Both are in built-in buffers, but from different files. We just claim that
  1683. // lower IDs come first.
  1684. return LOffs.first < ROffs.first;
  1685. }
  1686. bool LIsAsm = LB == "<inline asm>";
  1687. bool RIsAsm = RB == "<inline asm>";
  1688. // Sort assembler after built-ins, but before the rest.
  1689. if (LIsAsm || RIsAsm) {
  1690. if (LIsAsm != RIsAsm)
  1691. return RIsAsm;
  1692. assert(LOffs.first == ROffs.first);
  1693. return false;
  1694. }
  1695. bool LIsScratch = LB == "<scratch space>";
  1696. bool RIsScratch = RB == "<scratch space>";
  1697. // Sort scratch after inline asm, but before the rest.
  1698. if (LIsScratch || RIsScratch) {
  1699. if (LIsScratch != RIsScratch)
  1700. return LIsScratch;
  1701. return LOffs.second < ROffs.second;
  1702. }
  1703. llvm_unreachable("Unsortable locations found");
  1704. }
  1705. std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
  1706. std::pair<FileID, unsigned> &LOffs,
  1707. std::pair<FileID, unsigned> &ROffs) const {
  1708. // If the source locations are in the same file, just compare offsets.
  1709. if (LOffs.first == ROffs.first)
  1710. return std::make_pair(true, LOffs.second < ROffs.second);
  1711. // If we are comparing a source location with multiple locations in the same
  1712. // file, we get a big win by caching the result.
  1713. InBeforeInTUCacheEntry &IsBeforeInTUCache =
  1714. getInBeforeInTUCache(LOffs.first, ROffs.first);
  1715. // If we are comparing a source location with multiple locations in the same
  1716. // file, we get a big win by caching the result.
  1717. if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
  1718. return std::make_pair(
  1719. true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
  1720. // Okay, we missed in the cache, start updating the cache for this query.
  1721. IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
  1722. /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
  1723. // We need to find the common ancestor. The only way of doing this is to
  1724. // build the complete include chain for one and then walking up the chain
  1725. // of the other looking for a match.
  1726. // We use a map from FileID to Offset to store the chain. Easier than writing
  1727. // a custom set hash info that only depends on the first part of a pair.
  1728. using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
  1729. LocSet LChain;
  1730. do {
  1731. LChain.insert(LOffs);
  1732. // We catch the case where LOffs is in a file included by ROffs and
  1733. // quit early. The other way round unfortunately remains suboptimal.
  1734. } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
  1735. LocSet::iterator I;
  1736. while((I = LChain.find(ROffs.first)) == LChain.end()) {
  1737. if (MoveUpIncludeHierarchy(ROffs, *this))
  1738. break; // Met at topmost file.
  1739. }
  1740. if (I != LChain.end())
  1741. LOffs = *I;
  1742. // If we exited because we found a nearest common ancestor, compare the
  1743. // locations within the common file and cache them.
  1744. if (LOffs.first == ROffs.first) {
  1745. IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
  1746. return std::make_pair(
  1747. true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
  1748. }
  1749. // Clear the lookup cache, it depends on a common location.
  1750. IsBeforeInTUCache.clear();
  1751. return std::make_pair(false, false);
  1752. }
  1753. void SourceManager::PrintStats() const {
  1754. llvm::errs() << "\n*** Source Manager Stats:\n";
  1755. llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
  1756. << " mem buffers mapped.\n";
  1757. llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
  1758. << llvm::capacity_in_bytes(LocalSLocEntryTable)
  1759. << " bytes of capacity), "
  1760. << NextLocalOffset << "B of Sloc address space used.\n";
  1761. llvm::errs() << LoadedSLocEntryTable.size()
  1762. << " loaded SLocEntries allocated, "
  1763. << MaxLoadedOffset - CurrentLoadedOffset
  1764. << "B of Sloc address space used.\n";
  1765. unsigned NumLineNumsComputed = 0;
  1766. unsigned NumFileBytesMapped = 0;
  1767. for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
  1768. NumLineNumsComputed += I->second->SourceLineCache != nullptr;
  1769. NumFileBytesMapped += I->second->getSizeBytesMapped();
  1770. }
  1771. unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
  1772. llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
  1773. << NumLineNumsComputed << " files with line #'s computed, "
  1774. << NumMacroArgsComputed << " files with macro args computed.\n";
  1775. llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
  1776. << NumBinaryProbes << " binary.\n";
  1777. }
  1778. LLVM_DUMP_METHOD void SourceManager::dump() const {
  1779. llvm::raw_ostream &out = llvm::errs();
  1780. auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
  1781. llvm::Optional<unsigned> NextStart) {
  1782. out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
  1783. << " <SourceLocation " << Entry.getOffset() << ":";
  1784. if (NextStart)
  1785. out << *NextStart << ">\n";
  1786. else
  1787. out << "???\?>\n";
  1788. if (Entry.isFile()) {
  1789. auto &FI = Entry.getFile();
  1790. if (FI.NumCreatedFIDs)
  1791. out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
  1792. << ">\n";
  1793. if (FI.getIncludeLoc().isValid())
  1794. out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
  1795. if (auto *CC = FI.getContentCache()) {
  1796. out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
  1797. << "\n";
  1798. if (CC->BufferOverridden)
  1799. out << " contents overridden\n";
  1800. if (CC->ContentsEntry != CC->OrigEntry) {
  1801. out << " contents from "
  1802. << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
  1803. << "\n";
  1804. }
  1805. }
  1806. } else {
  1807. auto &EI = Entry.getExpansion();
  1808. out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
  1809. out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
  1810. << " range <" << EI.getExpansionLocStart().getOffset() << ":"
  1811. << EI.getExpansionLocEnd().getOffset() << ">\n";
  1812. }
  1813. };
  1814. // Dump local SLocEntries.
  1815. for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
  1816. DumpSLocEntry(ID, LocalSLocEntryTable[ID],
  1817. ID == NumIDs - 1 ? NextLocalOffset
  1818. : LocalSLocEntryTable[ID + 1].getOffset());
  1819. }
  1820. // Dump loaded SLocEntries.
  1821. llvm::Optional<unsigned> NextStart;
  1822. for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
  1823. int ID = -(int)Index - 2;
  1824. if (SLocEntryLoaded[Index]) {
  1825. DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
  1826. NextStart = LoadedSLocEntryTable[Index].getOffset();
  1827. } else {
  1828. NextStart = None;
  1829. }
  1830. }
  1831. }
  1832. ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
  1833. /// Return the amount of memory used by memory buffers, breaking down
  1834. /// by heap-backed versus mmap'ed memory.
  1835. SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
  1836. size_t malloc_bytes = 0;
  1837. size_t mmap_bytes = 0;
  1838. for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
  1839. if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
  1840. switch (MemBufferInfos[i]->getMemoryBufferKind()) {
  1841. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  1842. mmap_bytes += sized_mapped;
  1843. break;
  1844. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  1845. malloc_bytes += sized_mapped;
  1846. break;
  1847. }
  1848. return MemoryBufferSizes(malloc_bytes, mmap_bytes);
  1849. }
  1850. size_t SourceManager::getDataStructureSizes() const {
  1851. size_t size = llvm::capacity_in_bytes(MemBufferInfos)
  1852. + llvm::capacity_in_bytes(LocalSLocEntryTable)
  1853. + llvm::capacity_in_bytes(LoadedSLocEntryTable)
  1854. + llvm::capacity_in_bytes(SLocEntryLoaded)
  1855. + llvm::capacity_in_bytes(FileInfos);
  1856. if (OverriddenFilesInfo)
  1857. size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
  1858. return size;
  1859. }
  1860. SourceManagerForFile::SourceManagerForFile(StringRef FileName,
  1861. StringRef Content) {
  1862. // This is referenced by `FileMgr` and will be released by `FileMgr` when it
  1863. // is deleted.
  1864. IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
  1865. new llvm::vfs::InMemoryFileSystem);
  1866. InMemoryFileSystem->addFile(
  1867. FileName, 0,
  1868. llvm::MemoryBuffer::getMemBuffer(Content, FileName,
  1869. /*RequiresNullTerminator=*/false));
  1870. // This is passed to `SM` as reference, so the pointer has to be referenced
  1871. // in `Environment` so that `FileMgr` can out-live this function scope.
  1872. FileMgr =
  1873. std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
  1874. // This is passed to `SM` as reference, so the pointer has to be referenced
  1875. // by `Environment` due to the same reason above.
  1876. Diagnostics = std::make_unique<DiagnosticsEngine>(
  1877. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
  1878. new DiagnosticOptions);
  1879. SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
  1880. FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
  1881. SourceLocation(), clang::SrcMgr::C_User);
  1882. assert(ID.isValid());
  1883. SourceMgr->setMainFileID(ID);
  1884. }