SourceManager.cpp 85 KB

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