SourceManager.cpp 82 KB

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