SourceManager.cpp 79 KB

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