SourceManager.cpp 83 KB

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