SourceManager.cpp 83 KB

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