SourceManager.cpp 81 KB

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