SourceManager.cpp 79 KB

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