SourceManager.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384
  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/MapVector.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/Support/Allocator.h"
  25. #include "llvm/Support/Capacity.h"
  26. #include "llvm/Support/Compiler.h"
  27. #include "llvm/Support/Endian.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/MathExtras.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/Path.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstddef>
  37. #include <cstdint>
  38. #include <memory>
  39. #include <optional>
  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. std::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 std::nullopt;
  99. if (Buffer)
  100. return Buffer->getMemBufferRef();
  101. if (!ContentsEntry)
  102. return std::nullopt;
  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 std::nullopt;
  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 std::nullopt;
  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 std::nullopt;
  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 std::nullopt;
  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. auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
  350. if (overI == OverriddenFilesInfo->OverriddenFiles.end())
  351. new (Entry) ContentCache(FileEnt);
  352. else
  353. new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
  354. : overI->second,
  355. overI->second);
  356. } else {
  357. new (Entry) ContentCache(FileEnt);
  358. }
  359. Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
  360. Entry->IsTransient = FilesAreTransient;
  361. Entry->BufferOverridden |= FileEnt.isNamedPipe();
  362. return *Entry;
  363. }
  364. /// Create a new ContentCache for the specified memory buffer.
  365. /// This does no caching.
  366. ContentCache &SourceManager::createMemBufferContentCache(
  367. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  368. // Add a new ContentCache to the MemBufferInfos list and return it.
  369. ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
  370. new (Entry) ContentCache();
  371. MemBufferInfos.push_back(Entry);
  372. Entry->setBuffer(std::move(Buffer));
  373. return *Entry;
  374. }
  375. const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
  376. bool *Invalid) const {
  377. assert(!SLocEntryLoaded[Index]);
  378. if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
  379. if (Invalid)
  380. *Invalid = true;
  381. // If the file of the SLocEntry changed we could still have loaded it.
  382. if (!SLocEntryLoaded[Index]) {
  383. // Try to recover; create a SLocEntry so the rest of clang can handle it.
  384. if (!FakeSLocEntryForRecovery)
  385. FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
  386. 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
  387. SrcMgr::C_User, "")));
  388. return *FakeSLocEntryForRecovery;
  389. }
  390. }
  391. return LoadedSLocEntryTable[Index];
  392. }
  393. std::pair<int, SourceLocation::UIntTy>
  394. SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
  395. SourceLocation::UIntTy TotalSize) {
  396. assert(ExternalSLocEntries && "Don't have an external sloc source");
  397. // Make sure we're not about to run out of source locations.
  398. if (CurrentLoadedOffset < TotalSize ||
  399. CurrentLoadedOffset - TotalSize < NextLocalOffset) {
  400. return std::make_pair(0, 0);
  401. }
  402. LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
  403. SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
  404. CurrentLoadedOffset -= TotalSize;
  405. int ID = LoadedSLocEntryTable.size();
  406. return std::make_pair(-ID - 1, CurrentLoadedOffset);
  407. }
  408. /// As part of recovering from missing or changed content, produce a
  409. /// fake, non-empty buffer.
  410. llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
  411. if (!FakeBufferForRecovery)
  412. FakeBufferForRecovery =
  413. llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
  414. return *FakeBufferForRecovery;
  415. }
  416. /// As part of recovering from missing or changed content, produce a
  417. /// fake content cache.
  418. SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
  419. if (!FakeContentCacheForRecovery) {
  420. FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
  421. FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
  422. }
  423. return *FakeContentCacheForRecovery;
  424. }
  425. /// Returns the previous in-order FileID or an invalid FileID if there
  426. /// is no previous one.
  427. FileID SourceManager::getPreviousFileID(FileID FID) const {
  428. if (FID.isInvalid())
  429. return FileID();
  430. int ID = FID.ID;
  431. if (ID == -1)
  432. return FileID();
  433. if (ID > 0) {
  434. if (ID-1 == 0)
  435. return FileID();
  436. } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
  437. return FileID();
  438. }
  439. return FileID::get(ID-1);
  440. }
  441. /// Returns the next in-order FileID or an invalid FileID if there is
  442. /// no next one.
  443. FileID SourceManager::getNextFileID(FileID FID) const {
  444. if (FID.isInvalid())
  445. return FileID();
  446. int ID = FID.ID;
  447. if (ID > 0) {
  448. if (unsigned(ID+1) >= local_sloc_entry_size())
  449. return FileID();
  450. } else if (ID+1 >= -1) {
  451. return FileID();
  452. }
  453. return FileID::get(ID+1);
  454. }
  455. //===----------------------------------------------------------------------===//
  456. // Methods to create new FileID's and macro expansions.
  457. //===----------------------------------------------------------------------===//
  458. /// Create a new FileID that represents the specified file
  459. /// being \#included from the specified IncludePosition.
  460. ///
  461. /// This translates NULL into standard input.
  462. FileID SourceManager::createFileID(const FileEntry *SourceFile,
  463. SourceLocation IncludePos,
  464. SrcMgr::CharacteristicKind FileCharacter,
  465. int LoadedID,
  466. SourceLocation::UIntTy LoadedOffset) {
  467. return createFileID(SourceFile->getLastRef(), IncludePos, FileCharacter,
  468. LoadedID, LoadedOffset);
  469. }
  470. FileID SourceManager::createFileID(FileEntryRef SourceFile,
  471. SourceLocation IncludePos,
  472. SrcMgr::CharacteristicKind FileCharacter,
  473. int LoadedID,
  474. SourceLocation::UIntTy LoadedOffset) {
  475. SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
  476. isSystem(FileCharacter));
  477. // If this is a named pipe, immediately load the buffer to ensure subsequent
  478. // calls to ContentCache::getSize() are accurate.
  479. if (IR.ContentsEntry->isNamedPipe())
  480. (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
  481. return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
  482. LoadedID, LoadedOffset);
  483. }
  484. /// Create a new FileID that represents the specified memory buffer.
  485. ///
  486. /// This does no caching of the buffer and takes ownership of the
  487. /// MemoryBuffer, so only pass a MemoryBuffer to this once.
  488. FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
  489. SrcMgr::CharacteristicKind FileCharacter,
  490. int LoadedID,
  491. SourceLocation::UIntTy LoadedOffset,
  492. SourceLocation IncludeLoc) {
  493. StringRef Name = Buffer->getBufferIdentifier();
  494. return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
  495. IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
  496. }
  497. /// Create a new FileID that represents the specified memory buffer.
  498. ///
  499. /// This does not take ownership of the MemoryBuffer. The memory buffer must
  500. /// outlive the SourceManager.
  501. FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
  502. SrcMgr::CharacteristicKind FileCharacter,
  503. int LoadedID,
  504. SourceLocation::UIntTy LoadedOffset,
  505. SourceLocation IncludeLoc) {
  506. return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
  507. LoadedID, LoadedOffset, IncludeLoc);
  508. }
  509. /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
  510. /// new FileID for the \p SourceFile.
  511. FileID
  512. SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
  513. SrcMgr::CharacteristicKind FileCharacter) {
  514. FileID ID = translateFile(SourceFile);
  515. return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
  516. FileCharacter);
  517. }
  518. /// createFileID - Create a new FileID for the specified ContentCache and
  519. /// include position. This works regardless of whether the ContentCache
  520. /// corresponds to a file or some other input source.
  521. FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
  522. SourceLocation IncludePos,
  523. SrcMgr::CharacteristicKind FileCharacter,
  524. int LoadedID,
  525. SourceLocation::UIntTy LoadedOffset) {
  526. if (LoadedID < 0) {
  527. assert(LoadedID != -1 && "Loading sentinel FileID");
  528. unsigned Index = unsigned(-LoadedID) - 2;
  529. assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
  530. assert(!SLocEntryLoaded[Index] && "FileID already loaded");
  531. LoadedSLocEntryTable[Index] = SLocEntry::get(
  532. LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
  533. SLocEntryLoaded[Index] = true;
  534. return FileID::get(LoadedID);
  535. }
  536. unsigned FileSize = File.getSize();
  537. if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
  538. NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
  539. Diag.Report(IncludePos, diag::err_include_too_large);
  540. noteSLocAddressSpaceUsage(Diag);
  541. return FileID();
  542. }
  543. LocalSLocEntryTable.push_back(
  544. SLocEntry::get(NextLocalOffset,
  545. FileInfo::get(IncludePos, File, FileCharacter, Filename)));
  546. // We do a +1 here because we want a SourceLocation that means "the end of the
  547. // file", e.g. for the "no newline at the end of the file" diagnostic.
  548. NextLocalOffset += FileSize + 1;
  549. // Set LastFileIDLookup to the newly created file. The next getFileID call is
  550. // almost guaranteed to be from that file.
  551. FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
  552. return LastFileIDLookup = FID;
  553. }
  554. SourceLocation SourceManager::createMacroArgExpansionLoc(
  555. SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
  556. ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
  557. ExpansionLoc);
  558. return createExpansionLocImpl(Info, Length);
  559. }
  560. SourceLocation SourceManager::createExpansionLoc(
  561. SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
  562. SourceLocation ExpansionLocEnd, unsigned Length,
  563. bool ExpansionIsTokenRange, int LoadedID,
  564. SourceLocation::UIntTy LoadedOffset) {
  565. ExpansionInfo Info = ExpansionInfo::create(
  566. SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
  567. return createExpansionLocImpl(Info, Length, 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 Length, 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. // FIXME: Produce a proper diagnostic for this case.
  593. assert(NextLocalOffset + Length + 1 > NextLocalOffset &&
  594. NextLocalOffset + Length + 1 <= CurrentLoadedOffset &&
  595. "Ran out of source locations!");
  596. // See createFileID for that +1.
  597. NextLocalOffset += Length + 1;
  598. return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
  599. }
  600. std::optional<llvm::MemoryBufferRef>
  601. SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
  602. SrcMgr::ContentCache &IR = getOrCreateContentCache(File->getLastRef());
  603. return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
  604. }
  605. void SourceManager::overrideFileContents(
  606. const FileEntry *SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  607. SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile->getLastRef());
  608. IR.setBuffer(std::move(Buffer));
  609. IR.BufferOverridden = true;
  610. getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
  611. }
  612. void SourceManager::overrideFileContents(const FileEntry *SourceFile,
  613. FileEntryRef NewFile) {
  614. assert(SourceFile->getSize() == NewFile.getSize() &&
  615. "Different sizes, use the FileManager to create a virtual file with "
  616. "the correct size");
  617. assert(FileInfos.count(SourceFile) == 0 &&
  618. "This function should be called at the initialization stage, before "
  619. "any parsing occurs.");
  620. // FileEntryRef is not default-constructible.
  621. auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
  622. std::make_pair(SourceFile, NewFile));
  623. if (!Pair.second)
  624. Pair.first->second = NewFile;
  625. }
  626. OptionalFileEntryRef
  627. SourceManager::bypassFileContentsOverride(FileEntryRef File) {
  628. assert(isFileOverridden(&File.getFileEntry()));
  629. OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);
  630. // If the file can't be found in the FS, give up.
  631. if (!BypassFile)
  632. return std::nullopt;
  633. (void)getOrCreateContentCache(*BypassFile);
  634. return BypassFile;
  635. }
  636. void SourceManager::setFileIsTransient(const FileEntry *File) {
  637. getOrCreateContentCache(File->getLastRef()).IsTransient = true;
  638. }
  639. std::optional<StringRef>
  640. SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
  641. if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
  642. if (Entry->getFile().getContentCache().OrigEntry)
  643. return Entry->getFile().getName();
  644. return std::nullopt;
  645. }
  646. StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
  647. auto B = getBufferDataOrNone(FID);
  648. if (Invalid)
  649. *Invalid = !B;
  650. return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
  651. }
  652. std::optional<StringRef>
  653. SourceManager::getBufferDataIfLoaded(FileID FID) const {
  654. if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
  655. return Entry->getFile().getContentCache().getBufferDataIfLoaded();
  656. return std::nullopt;
  657. }
  658. std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
  659. if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
  660. if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
  661. Diag, getFileManager(), SourceLocation()))
  662. return B->getBuffer();
  663. return std::nullopt;
  664. }
  665. //===----------------------------------------------------------------------===//
  666. // SourceLocation manipulation methods.
  667. //===----------------------------------------------------------------------===//
  668. /// Return the FileID for a SourceLocation.
  669. ///
  670. /// This is the cache-miss path of getFileID. Not as hot as that function, but
  671. /// still very important. It is responsible for finding the entry in the
  672. /// SLocEntry tables that contains the specified location.
  673. FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
  674. if (!SLocOffset)
  675. return FileID::get(0);
  676. // Now it is time to search for the correct file. See where the SLocOffset
  677. // sits in the global view and consult local or loaded buffers for it.
  678. if (SLocOffset < NextLocalOffset)
  679. return getFileIDLocal(SLocOffset);
  680. return getFileIDLoaded(SLocOffset);
  681. }
  682. /// Return the FileID for a SourceLocation with a low offset.
  683. ///
  684. /// This function knows that the SourceLocation is in a local buffer, not a
  685. /// loaded one.
  686. FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
  687. assert(SLocOffset < NextLocalOffset && "Bad function choice");
  688. // After the first and second level caches, I see two common sorts of
  689. // behavior: 1) a lot of searched FileID's are "near" the cached file
  690. // location or are "near" the cached expansion location. 2) others are just
  691. // completely random and may be a very long way away.
  692. //
  693. // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
  694. // then we fall back to a less cache efficient, but more scalable, binary
  695. // search to find the location.
  696. // See if this is near the file point - worst case we start scanning from the
  697. // most newly created FileID.
  698. // LessIndex - This is the lower bound of the range that we're searching.
  699. // We know that the offset corresponding to the FileID is less than
  700. // SLocOffset.
  701. unsigned LessIndex = 0;
  702. // upper bound of the search range.
  703. unsigned GreaterIndex = LocalSLocEntryTable.size();
  704. if (LastFileIDLookup.ID >= 0) {
  705. // Use the LastFileIDLookup to prune the search space.
  706. if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
  707. LessIndex = LastFileIDLookup.ID;
  708. else
  709. GreaterIndex = LastFileIDLookup.ID;
  710. }
  711. // Find the FileID that contains this.
  712. unsigned NumProbes = 0;
  713. while (true) {
  714. --GreaterIndex;
  715. assert(GreaterIndex < LocalSLocEntryTable.size());
  716. if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
  717. FileID Res = FileID::get(int(GreaterIndex));
  718. // Remember it. We have good locality across FileID lookups.
  719. LastFileIDLookup = Res;
  720. NumLinearScans += NumProbes+1;
  721. return Res;
  722. }
  723. if (++NumProbes == 8)
  724. break;
  725. }
  726. NumProbes = 0;
  727. while (true) {
  728. unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
  729. SourceLocation::UIntTy MidOffset =
  730. getLocalSLocEntry(MiddleIndex).getOffset();
  731. ++NumProbes;
  732. // If the offset of the midpoint is too large, chop the high side of the
  733. // range to the midpoint.
  734. if (MidOffset > SLocOffset) {
  735. GreaterIndex = MiddleIndex;
  736. continue;
  737. }
  738. // If the middle index contains the value, succeed and return.
  739. if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
  740. SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
  741. FileID Res = FileID::get(MiddleIndex);
  742. // Remember it. We have good locality across FileID lookups.
  743. LastFileIDLookup = Res;
  744. NumBinaryProbes += NumProbes;
  745. return Res;
  746. }
  747. // Otherwise, move the low-side up to the middle index.
  748. LessIndex = MiddleIndex;
  749. }
  750. }
  751. /// Return the FileID for a SourceLocation with a high offset.
  752. ///
  753. /// This function knows that the SourceLocation is in a loaded buffer, not a
  754. /// local one.
  755. FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
  756. if (SLocOffset < CurrentLoadedOffset) {
  757. assert(0 && "Invalid SLocOffset or bad function choice");
  758. return FileID();
  759. }
  760. // Essentially the same as the local case, but the loaded array is sorted
  761. // in the other direction (decreasing order).
  762. // GreaterIndex is the one where the offset is greater, which is actually a
  763. // lower index!
  764. unsigned GreaterIndex = 0;
  765. unsigned LessIndex = LoadedSLocEntryTable.size();
  766. if (LastFileIDLookup.ID < 0) {
  767. // Prune the search space.
  768. int LastID = LastFileIDLookup.ID;
  769. if (getLoadedSLocEntryByID(LastID).getOffset() > SLocOffset)
  770. GreaterIndex =
  771. (-LastID - 2) + 1; // Exclude LastID, else we would have hit the cache
  772. else
  773. LessIndex = -LastID - 2;
  774. }
  775. // First do a linear scan from the last lookup position, if possible.
  776. unsigned NumProbes;
  777. bool Invalid = false;
  778. for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++GreaterIndex) {
  779. // Make sure the entry is loaded!
  780. const SrcMgr::SLocEntry &E = getLoadedSLocEntry(GreaterIndex, &Invalid);
  781. if (Invalid)
  782. return FileID(); // invalid entry.
  783. if (E.getOffset() <= SLocOffset) {
  784. FileID Res = FileID::get(-int(GreaterIndex) - 2);
  785. LastFileIDLookup = Res;
  786. NumLinearScans += NumProbes + 1;
  787. return Res;
  788. }
  789. }
  790. // Linear scan failed. Do the binary search.
  791. NumProbes = 0;
  792. while (true) {
  793. ++NumProbes;
  794. unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
  795. const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex, &Invalid);
  796. if (Invalid)
  797. return FileID(); // invalid entry.
  798. if (E.getOffset() > SLocOffset) {
  799. if (GreaterIndex == MiddleIndex) {
  800. assert(0 && "binary search missed the entry");
  801. return FileID();
  802. }
  803. GreaterIndex = MiddleIndex;
  804. continue;
  805. }
  806. if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
  807. FileID Res = FileID::get(-int(MiddleIndex) - 2);
  808. LastFileIDLookup = Res;
  809. NumBinaryProbes += NumProbes;
  810. return Res;
  811. }
  812. if (LessIndex == MiddleIndex) {
  813. assert(0 && "binary search missed the entry");
  814. return FileID();
  815. }
  816. LessIndex = MiddleIndex;
  817. }
  818. }
  819. SourceLocation SourceManager::
  820. getExpansionLocSlowCase(SourceLocation Loc) const {
  821. do {
  822. // Note: If Loc indicates an offset into a token that came from a macro
  823. // expansion (e.g. the 5th character of the token) we do not want to add
  824. // this offset when going to the expansion location. The expansion
  825. // location is the macro invocation, which the offset has nothing to do
  826. // with. This is unlike when we get the spelling loc, because the offset
  827. // directly correspond to the token whose spelling we're inspecting.
  828. Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
  829. } while (!Loc.isFileID());
  830. return Loc;
  831. }
  832. SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
  833. do {
  834. std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
  835. Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
  836. Loc = Loc.getLocWithOffset(LocInfo.second);
  837. } while (!Loc.isFileID());
  838. return Loc;
  839. }
  840. SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
  841. do {
  842. if (isMacroArgExpansion(Loc))
  843. Loc = getImmediateSpellingLoc(Loc);
  844. else
  845. Loc = getImmediateExpansionRange(Loc).getBegin();
  846. } while (!Loc.isFileID());
  847. return Loc;
  848. }
  849. std::pair<FileID, unsigned>
  850. SourceManager::getDecomposedExpansionLocSlowCase(
  851. const SrcMgr::SLocEntry *E) const {
  852. // If this is an expansion record, walk through all the expansion points.
  853. FileID FID;
  854. SourceLocation Loc;
  855. unsigned Offset;
  856. do {
  857. Loc = E->getExpansion().getExpansionLocStart();
  858. FID = getFileID(Loc);
  859. E = &getSLocEntry(FID);
  860. Offset = Loc.getOffset()-E->getOffset();
  861. } while (!Loc.isFileID());
  862. return std::make_pair(FID, Offset);
  863. }
  864. std::pair<FileID, unsigned>
  865. SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
  866. unsigned Offset) const {
  867. // If this is an expansion record, walk through all the expansion points.
  868. FileID FID;
  869. SourceLocation Loc;
  870. do {
  871. Loc = E->getExpansion().getSpellingLoc();
  872. Loc = Loc.getLocWithOffset(Offset);
  873. FID = getFileID(Loc);
  874. E = &getSLocEntry(FID);
  875. Offset = Loc.getOffset()-E->getOffset();
  876. } while (!Loc.isFileID());
  877. return std::make_pair(FID, Offset);
  878. }
  879. /// getImmediateSpellingLoc - Given a SourceLocation object, return the
  880. /// spelling location referenced by the ID. This is the first level down
  881. /// towards the place where the characters that make up the lexed token can be
  882. /// found. This should not generally be used by clients.
  883. SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
  884. if (Loc.isFileID()) return Loc;
  885. std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
  886. Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
  887. return Loc.getLocWithOffset(LocInfo.second);
  888. }
  889. /// Return the filename of the file containing a SourceLocation.
  890. StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
  891. if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
  892. return F->getName();
  893. return StringRef();
  894. }
  895. /// getImmediateExpansionRange - Loc is required to be an expansion location.
  896. /// Return the start/end of the expansion information.
  897. CharSourceRange
  898. SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
  899. assert(Loc.isMacroID() && "Not a macro expansion loc!");
  900. const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
  901. return Expansion.getExpansionLocRange();
  902. }
  903. SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
  904. while (isMacroArgExpansion(Loc))
  905. Loc = getImmediateSpellingLoc(Loc);
  906. return Loc;
  907. }
  908. /// getExpansionRange - Given a SourceLocation object, return the range of
  909. /// tokens covered by the expansion in the ultimate file.
  910. CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
  911. if (Loc.isFileID())
  912. return CharSourceRange(SourceRange(Loc, Loc), true);
  913. CharSourceRange Res = getImmediateExpansionRange(Loc);
  914. // Fully resolve the start and end locations to their ultimate expansion
  915. // points.
  916. while (!Res.getBegin().isFileID())
  917. Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
  918. while (!Res.getEnd().isFileID()) {
  919. CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
  920. Res.setEnd(EndRange.getEnd());
  921. Res.setTokenRange(EndRange.isTokenRange());
  922. }
  923. return Res;
  924. }
  925. bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
  926. SourceLocation *StartLoc) const {
  927. if (!Loc.isMacroID()) return false;
  928. FileID FID = getFileID(Loc);
  929. const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
  930. if (!Expansion.isMacroArgExpansion()) return false;
  931. if (StartLoc)
  932. *StartLoc = Expansion.getExpansionLocStart();
  933. return true;
  934. }
  935. bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
  936. if (!Loc.isMacroID()) return false;
  937. FileID FID = getFileID(Loc);
  938. const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
  939. return Expansion.isMacroBodyExpansion();
  940. }
  941. bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
  942. SourceLocation *MacroBegin) const {
  943. assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
  944. std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
  945. if (DecompLoc.second > 0)
  946. return false; // Does not point at the start of expansion range.
  947. bool Invalid = false;
  948. const SrcMgr::ExpansionInfo &ExpInfo =
  949. getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
  950. if (Invalid)
  951. return false;
  952. SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
  953. if (ExpInfo.isMacroArgExpansion()) {
  954. // For macro argument expansions, check if the previous FileID is part of
  955. // the same argument expansion, in which case this Loc is not at the
  956. // beginning of the expansion.
  957. FileID PrevFID = getPreviousFileID(DecompLoc.first);
  958. if (!PrevFID.isInvalid()) {
  959. const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
  960. if (Invalid)
  961. return false;
  962. if (PrevEntry.isExpansion() &&
  963. PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
  964. return false;
  965. }
  966. }
  967. if (MacroBegin)
  968. *MacroBegin = ExpLoc;
  969. return true;
  970. }
  971. bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
  972. SourceLocation *MacroEnd) const {
  973. assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
  974. FileID FID = getFileID(Loc);
  975. SourceLocation NextLoc = Loc.getLocWithOffset(1);
  976. if (isInFileID(NextLoc, FID))
  977. return false; // Does not point at the end of expansion range.
  978. bool Invalid = false;
  979. const SrcMgr::ExpansionInfo &ExpInfo =
  980. getSLocEntry(FID, &Invalid).getExpansion();
  981. if (Invalid)
  982. return false;
  983. if (ExpInfo.isMacroArgExpansion()) {
  984. // For macro argument expansions, check if the next FileID is part of the
  985. // same argument expansion, in which case this Loc is not at the end of the
  986. // expansion.
  987. FileID NextFID = getNextFileID(FID);
  988. if (!NextFID.isInvalid()) {
  989. const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
  990. if (Invalid)
  991. return false;
  992. if (NextEntry.isExpansion() &&
  993. NextEntry.getExpansion().getExpansionLocStart() ==
  994. ExpInfo.getExpansionLocStart())
  995. return false;
  996. }
  997. }
  998. if (MacroEnd)
  999. *MacroEnd = ExpInfo.getExpansionLocEnd();
  1000. return true;
  1001. }
  1002. //===----------------------------------------------------------------------===//
  1003. // Queries about the code at a SourceLocation.
  1004. //===----------------------------------------------------------------------===//
  1005. /// getCharacterData - Return a pointer to the start of the specified location
  1006. /// in the appropriate MemoryBuffer.
  1007. const char *SourceManager::getCharacterData(SourceLocation SL,
  1008. bool *Invalid) const {
  1009. // Note that this is a hot function in the getSpelling() path, which is
  1010. // heavily used by -E mode.
  1011. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
  1012. // Note that calling 'getBuffer()' may lazily page in a source file.
  1013. bool CharDataInvalid = false;
  1014. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
  1015. if (CharDataInvalid || !Entry.isFile()) {
  1016. if (Invalid)
  1017. *Invalid = true;
  1018. return "<<<<INVALID BUFFER>>>>";
  1019. }
  1020. std::optional<llvm::MemoryBufferRef> Buffer =
  1021. Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
  1022. SourceLocation());
  1023. if (Invalid)
  1024. *Invalid = !Buffer;
  1025. return Buffer ? Buffer->getBufferStart() + LocInfo.second
  1026. : "<<<<INVALID BUFFER>>>>";
  1027. }
  1028. /// getColumnNumber - Return the column # for the specified file position.
  1029. /// this is significantly cheaper to compute than the line number.
  1030. unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
  1031. bool *Invalid) const {
  1032. std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
  1033. if (Invalid)
  1034. *Invalid = !MemBuf;
  1035. if (!MemBuf)
  1036. return 1;
  1037. // It is okay to request a position just past the end of the buffer.
  1038. if (FilePos > MemBuf->getBufferSize()) {
  1039. if (Invalid)
  1040. *Invalid = true;
  1041. return 1;
  1042. }
  1043. const char *Buf = MemBuf->getBufferStart();
  1044. // See if we just calculated the line number for this FilePos and can use
  1045. // that to lookup the start of the line instead of searching for it.
  1046. if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
  1047. LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
  1048. const unsigned *SourceLineCache =
  1049. LastLineNoContentCache->SourceLineCache.begin();
  1050. unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
  1051. unsigned LineEnd = SourceLineCache[LastLineNoResult];
  1052. if (FilePos >= LineStart && FilePos < LineEnd) {
  1053. // LineEnd is the LineStart of the next line.
  1054. // A line ends with separator LF or CR+LF on Windows.
  1055. // FilePos might point to the last separator,
  1056. // but we need a column number at most 1 + the last column.
  1057. if (FilePos + 1 == LineEnd && FilePos > LineStart) {
  1058. if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
  1059. --FilePos;
  1060. }
  1061. return FilePos - LineStart + 1;
  1062. }
  1063. }
  1064. unsigned LineStart = FilePos;
  1065. while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
  1066. --LineStart;
  1067. return FilePos-LineStart+1;
  1068. }
  1069. // isInvalid - Return the result of calling loc.isInvalid(), and
  1070. // if Invalid is not null, set its value to same.
  1071. template<typename LocType>
  1072. static bool isInvalid(LocType Loc, bool *Invalid) {
  1073. bool MyInvalid = Loc.isInvalid();
  1074. if (Invalid)
  1075. *Invalid = MyInvalid;
  1076. return MyInvalid;
  1077. }
  1078. unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
  1079. bool *Invalid) const {
  1080. if (isInvalid(Loc, Invalid)) return 0;
  1081. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
  1082. return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
  1083. }
  1084. unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
  1085. bool *Invalid) const {
  1086. if (isInvalid(Loc, Invalid)) return 0;
  1087. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1088. return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
  1089. }
  1090. unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
  1091. bool *Invalid) const {
  1092. PresumedLoc PLoc = getPresumedLoc(Loc);
  1093. if (isInvalid(PLoc, Invalid)) return 0;
  1094. return PLoc.getColumn();
  1095. }
  1096. // Check if mutli-byte word x has bytes between m and n, included. This may also
  1097. // catch bytes equal to n + 1.
  1098. // The returned value holds a 0x80 at each byte position that holds a match.
  1099. // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
  1100. template <class T>
  1101. static constexpr inline T likelyhasbetween(T x, unsigned char m,
  1102. unsigned char n) {
  1103. return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
  1104. ((x & ~static_cast<T>(0) / 255 * 127) +
  1105. (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
  1106. ~static_cast<T>(0) / 255 * 128;
  1107. }
  1108. LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
  1109. llvm::BumpPtrAllocator &Alloc) {
  1110. // Find the file offsets of all of the *physical* source lines. This does
  1111. // not look at trigraphs, escaped newlines, or anything else tricky.
  1112. SmallVector<unsigned, 256> LineOffsets;
  1113. // Line #1 starts at char 0.
  1114. LineOffsets.push_back(0);
  1115. const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart();
  1116. const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
  1117. const unsigned char *Buf = Start;
  1118. uint64_t Word;
  1119. // scan sizeof(Word) bytes at a time for new lines.
  1120. // This is much faster than scanning each byte independently.
  1121. if ((unsigned long)(End - Start) > sizeof(Word)) {
  1122. do {
  1123. Word = llvm::support::endian::read64(Buf, llvm::support::little);
  1124. // no new line => jump over sizeof(Word) bytes.
  1125. auto Mask = likelyhasbetween(Word, '\n', '\r');
  1126. if (!Mask) {
  1127. Buf += sizeof(Word);
  1128. continue;
  1129. }
  1130. // At that point, Mask contains 0x80 set at each byte that holds a value
  1131. // in [\n, \r + 1 [
  1132. // Scan for the next newline - it's very likely there's one.
  1133. unsigned N =
  1134. llvm::countTrailingZeros(Mask) - 7; // -7 because 0x80 is the marker
  1135. Word >>= N;
  1136. Buf += N / 8 + 1;
  1137. unsigned char Byte = Word;
  1138. switch (Byte) {
  1139. case '\r':
  1140. // If this is \r\n, skip both characters.
  1141. if (*Buf == '\n') {
  1142. ++Buf;
  1143. }
  1144. LLVM_FALLTHROUGH;
  1145. case '\n':
  1146. LineOffsets.push_back(Buf - Start);
  1147. };
  1148. } while (Buf < End - sizeof(Word) - 1);
  1149. }
  1150. // Handle tail using a regular check.
  1151. while (Buf < End) {
  1152. if (*Buf == '\n') {
  1153. LineOffsets.push_back(Buf - Start + 1);
  1154. } else if (*Buf == '\r') {
  1155. // If this is \r\n, skip both characters.
  1156. if (Buf + 1 < End && Buf[1] == '\n') {
  1157. ++Buf;
  1158. }
  1159. LineOffsets.push_back(Buf - Start + 1);
  1160. }
  1161. ++Buf;
  1162. }
  1163. return LineOffsetMapping(LineOffsets, Alloc);
  1164. }
  1165. LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
  1166. llvm::BumpPtrAllocator &Alloc)
  1167. : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
  1168. Storage[0] = LineOffsets.size();
  1169. std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
  1170. }
  1171. /// getLineNumber - Given a SourceLocation, return the spelling line number
  1172. /// for the position indicated. This requires building and caching a table of
  1173. /// line offsets for the MemoryBuffer, so this is not cheap: use only when
  1174. /// about to emit a diagnostic.
  1175. unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
  1176. bool *Invalid) const {
  1177. if (FID.isInvalid()) {
  1178. if (Invalid)
  1179. *Invalid = true;
  1180. return 1;
  1181. }
  1182. const ContentCache *Content;
  1183. if (LastLineNoFileIDQuery == FID)
  1184. Content = LastLineNoContentCache;
  1185. else {
  1186. bool MyInvalid = false;
  1187. const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
  1188. if (MyInvalid || !Entry.isFile()) {
  1189. if (Invalid)
  1190. *Invalid = true;
  1191. return 1;
  1192. }
  1193. Content = &Entry.getFile().getContentCache();
  1194. }
  1195. // If this is the first use of line information for this buffer, compute the
  1196. /// SourceLineCache for it on demand.
  1197. if (!Content->SourceLineCache) {
  1198. std::optional<llvm::MemoryBufferRef> Buffer =
  1199. Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
  1200. if (Invalid)
  1201. *Invalid = !Buffer;
  1202. if (!Buffer)
  1203. return 1;
  1204. Content->SourceLineCache =
  1205. LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
  1206. } else if (Invalid)
  1207. *Invalid = false;
  1208. // Okay, we know we have a line number table. Do a binary search to find the
  1209. // line number that this character position lands on.
  1210. const unsigned *SourceLineCache = Content->SourceLineCache.begin();
  1211. const unsigned *SourceLineCacheStart = SourceLineCache;
  1212. const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
  1213. unsigned QueriedFilePos = FilePos+1;
  1214. // FIXME: I would like to be convinced that this code is worth being as
  1215. // complicated as it is, binary search isn't that slow.
  1216. //
  1217. // If it is worth being optimized, then in my opinion it could be more
  1218. // performant, simpler, and more obviously correct by just "galloping" outward
  1219. // from the queried file position. In fact, this could be incorporated into a
  1220. // generic algorithm such as lower_bound_with_hint.
  1221. //
  1222. // If someone gives me a test case where this matters, and I will do it! - DWD
  1223. // If the previous query was to the same file, we know both the file pos from
  1224. // that query and the line number returned. This allows us to narrow the
  1225. // search space from the entire file to something near the match.
  1226. if (LastLineNoFileIDQuery == FID) {
  1227. if (QueriedFilePos >= LastLineNoFilePos) {
  1228. // FIXME: Potential overflow?
  1229. SourceLineCache = SourceLineCache+LastLineNoResult-1;
  1230. // The query is likely to be nearby the previous one. Here we check to
  1231. // see if it is within 5, 10 or 20 lines. It can be far away in cases
  1232. // where big comment blocks and vertical whitespace eat up lines but
  1233. // contribute no tokens.
  1234. if (SourceLineCache+5 < SourceLineCacheEnd) {
  1235. if (SourceLineCache[5] > QueriedFilePos)
  1236. SourceLineCacheEnd = SourceLineCache+5;
  1237. else if (SourceLineCache+10 < SourceLineCacheEnd) {
  1238. if (SourceLineCache[10] > QueriedFilePos)
  1239. SourceLineCacheEnd = SourceLineCache+10;
  1240. else if (SourceLineCache+20 < SourceLineCacheEnd) {
  1241. if (SourceLineCache[20] > QueriedFilePos)
  1242. SourceLineCacheEnd = SourceLineCache+20;
  1243. }
  1244. }
  1245. }
  1246. } else {
  1247. if (LastLineNoResult < Content->SourceLineCache.size())
  1248. SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
  1249. }
  1250. }
  1251. const unsigned *Pos =
  1252. std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
  1253. unsigned LineNo = Pos-SourceLineCacheStart;
  1254. LastLineNoFileIDQuery = FID;
  1255. LastLineNoContentCache = Content;
  1256. LastLineNoFilePos = QueriedFilePos;
  1257. LastLineNoResult = LineNo;
  1258. return LineNo;
  1259. }
  1260. unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
  1261. bool *Invalid) const {
  1262. if (isInvalid(Loc, Invalid)) return 0;
  1263. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
  1264. return getLineNumber(LocInfo.first, LocInfo.second);
  1265. }
  1266. unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
  1267. bool *Invalid) const {
  1268. if (isInvalid(Loc, Invalid)) return 0;
  1269. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1270. return getLineNumber(LocInfo.first, LocInfo.second);
  1271. }
  1272. unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
  1273. bool *Invalid) const {
  1274. PresumedLoc PLoc = getPresumedLoc(Loc);
  1275. if (isInvalid(PLoc, Invalid)) return 0;
  1276. return PLoc.getLine();
  1277. }
  1278. /// getFileCharacteristic - return the file characteristic of the specified
  1279. /// source location, indicating whether this is a normal file, a system
  1280. /// header, or an "implicit extern C" system header.
  1281. ///
  1282. /// This state can be modified with flags on GNU linemarker directives like:
  1283. /// # 4 "foo.h" 3
  1284. /// which changes all source locations in the current file after that to be
  1285. /// considered to be from a system header.
  1286. SrcMgr::CharacteristicKind
  1287. SourceManager::getFileCharacteristic(SourceLocation Loc) const {
  1288. assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
  1289. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1290. const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
  1291. if (!SEntry)
  1292. return C_User;
  1293. const SrcMgr::FileInfo &FI = SEntry->getFile();
  1294. // If there are no #line directives in this file, just return the whole-file
  1295. // state.
  1296. if (!FI.hasLineDirectives())
  1297. return FI.getFileCharacteristic();
  1298. assert(LineTable && "Can't have linetable entries without a LineTable!");
  1299. // See if there is a #line directive before the location.
  1300. const LineEntry *Entry =
  1301. LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
  1302. // If this is before the first line marker, use the file characteristic.
  1303. if (!Entry)
  1304. return FI.getFileCharacteristic();
  1305. return Entry->FileKind;
  1306. }
  1307. /// Return the filename or buffer identifier of the buffer the location is in.
  1308. /// Note that this name does not respect \#line directives. Use getPresumedLoc
  1309. /// for normal clients.
  1310. StringRef SourceManager::getBufferName(SourceLocation Loc,
  1311. bool *Invalid) const {
  1312. if (isInvalid(Loc, Invalid)) return "<invalid loc>";
  1313. auto B = getBufferOrNone(getFileID(Loc));
  1314. if (Invalid)
  1315. *Invalid = !B;
  1316. return B ? B->getBufferIdentifier() : "<invalid buffer>";
  1317. }
  1318. /// getPresumedLoc - This method returns the "presumed" location of a
  1319. /// SourceLocation specifies. A "presumed location" can be modified by \#line
  1320. /// or GNU line marker directives. This provides a view on the data that a
  1321. /// user should see in diagnostics, for example.
  1322. ///
  1323. /// Note that a presumed location is always given as the expansion point of an
  1324. /// expansion location, not at the spelling location.
  1325. PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
  1326. bool UseLineDirectives) const {
  1327. if (Loc.isInvalid()) return PresumedLoc();
  1328. // Presumed locations are always for expansion points.
  1329. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1330. bool Invalid = false;
  1331. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
  1332. if (Invalid || !Entry.isFile())
  1333. return PresumedLoc();
  1334. const SrcMgr::FileInfo &FI = Entry.getFile();
  1335. const SrcMgr::ContentCache *C = &FI.getContentCache();
  1336. // To get the source name, first consult the FileEntry (if one exists)
  1337. // before the MemBuffer as this will avoid unnecessarily paging in the
  1338. // MemBuffer.
  1339. FileID FID = LocInfo.first;
  1340. StringRef Filename;
  1341. if (C->OrigEntry)
  1342. Filename = C->OrigEntry->getName();
  1343. else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
  1344. Filename = Buffer->getBufferIdentifier();
  1345. unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
  1346. if (Invalid)
  1347. return PresumedLoc();
  1348. unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
  1349. if (Invalid)
  1350. return PresumedLoc();
  1351. SourceLocation IncludeLoc = FI.getIncludeLoc();
  1352. // If we have #line directives in this file, update and overwrite the physical
  1353. // location info if appropriate.
  1354. if (UseLineDirectives && FI.hasLineDirectives()) {
  1355. assert(LineTable && "Can't have linetable entries without a LineTable!");
  1356. // See if there is a #line directive before this. If so, get it.
  1357. if (const LineEntry *Entry =
  1358. LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
  1359. // If the LineEntry indicates a filename, use it.
  1360. if (Entry->FilenameID != -1) {
  1361. Filename = LineTable->getFilename(Entry->FilenameID);
  1362. // The contents of files referenced by #line are not in the
  1363. // SourceManager
  1364. FID = FileID::get(0);
  1365. }
  1366. // Use the line number specified by the LineEntry. This line number may
  1367. // be multiple lines down from the line entry. Add the difference in
  1368. // physical line numbers from the query point and the line marker to the
  1369. // total.
  1370. unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
  1371. LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
  1372. // Note that column numbers are not molested by line markers.
  1373. // Handle virtual #include manipulation.
  1374. if (Entry->IncludeOffset) {
  1375. IncludeLoc = getLocForStartOfFile(LocInfo.first);
  1376. IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
  1377. }
  1378. }
  1379. }
  1380. return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
  1381. }
  1382. /// Returns whether the PresumedLoc for a given SourceLocation is
  1383. /// in the main file.
  1384. ///
  1385. /// This computes the "presumed" location for a SourceLocation, then checks
  1386. /// whether it came from a file other than the main file. This is different
  1387. /// from isWrittenInMainFile() because it takes line marker directives into
  1388. /// account.
  1389. bool SourceManager::isInMainFile(SourceLocation Loc) const {
  1390. if (Loc.isInvalid()) return false;
  1391. // Presumed locations are always for expansion points.
  1392. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1393. const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
  1394. if (!Entry)
  1395. return false;
  1396. const SrcMgr::FileInfo &FI = Entry->getFile();
  1397. // Check if there is a line directive for this location.
  1398. if (FI.hasLineDirectives())
  1399. if (const LineEntry *Entry =
  1400. LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
  1401. if (Entry->IncludeOffset)
  1402. return false;
  1403. return FI.getIncludeLoc().isInvalid();
  1404. }
  1405. /// The size of the SLocEntry that \p FID represents.
  1406. unsigned SourceManager::getFileIDSize(FileID FID) const {
  1407. bool Invalid = false;
  1408. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1409. if (Invalid)
  1410. return 0;
  1411. int ID = FID.ID;
  1412. SourceLocation::UIntTy NextOffset;
  1413. if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
  1414. NextOffset = getNextLocalOffset();
  1415. else if (ID+1 == -1)
  1416. NextOffset = MaxLoadedOffset;
  1417. else
  1418. NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
  1419. return NextOffset - Entry.getOffset() - 1;
  1420. }
  1421. //===----------------------------------------------------------------------===//
  1422. // Other miscellaneous methods.
  1423. //===----------------------------------------------------------------------===//
  1424. /// Get the source location for the given file:line:col triplet.
  1425. ///
  1426. /// If the source file is included multiple times, the source location will
  1427. /// be based upon an arbitrary inclusion.
  1428. SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
  1429. unsigned Line,
  1430. unsigned Col) const {
  1431. assert(SourceFile && "Null source file!");
  1432. assert(Line && Col && "Line and column should start from 1!");
  1433. FileID FirstFID = translateFile(SourceFile);
  1434. return translateLineCol(FirstFID, Line, Col);
  1435. }
  1436. /// Get the FileID for the given file.
  1437. ///
  1438. /// If the source file is included multiple times, the FileID will be the
  1439. /// first inclusion.
  1440. FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
  1441. assert(SourceFile && "Null source file!");
  1442. // First, check the main file ID, since it is common to look for a
  1443. // location in the main file.
  1444. if (MainFileID.isValid()) {
  1445. bool Invalid = false;
  1446. const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
  1447. if (Invalid)
  1448. return FileID();
  1449. if (MainSLoc.isFile()) {
  1450. if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
  1451. return MainFileID;
  1452. }
  1453. }
  1454. // The location we're looking for isn't in the main file; look
  1455. // through all of the local source locations.
  1456. for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
  1457. const SLocEntry &SLoc = getLocalSLocEntry(I);
  1458. if (SLoc.isFile() &&
  1459. SLoc.getFile().getContentCache().OrigEntry == SourceFile)
  1460. return FileID::get(I);
  1461. }
  1462. // If that still didn't help, try the modules.
  1463. for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
  1464. const SLocEntry &SLoc = getLoadedSLocEntry(I);
  1465. if (SLoc.isFile() &&
  1466. SLoc.getFile().getContentCache().OrigEntry == SourceFile)
  1467. return FileID::get(-int(I) - 2);
  1468. }
  1469. return FileID();
  1470. }
  1471. /// Get the source location in \arg FID for the given line:col.
  1472. /// Returns null location if \arg FID is not a file SLocEntry.
  1473. SourceLocation SourceManager::translateLineCol(FileID FID,
  1474. unsigned Line,
  1475. unsigned Col) const {
  1476. // Lines are used as a one-based index into a zero-based array. This assert
  1477. // checks for possible buffer underruns.
  1478. assert(Line && Col && "Line and column should start from 1!");
  1479. if (FID.isInvalid())
  1480. return SourceLocation();
  1481. bool Invalid = false;
  1482. const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1483. if (Invalid)
  1484. return SourceLocation();
  1485. if (!Entry.isFile())
  1486. return SourceLocation();
  1487. SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
  1488. if (Line == 1 && Col == 1)
  1489. return FileLoc;
  1490. const ContentCache *Content = &Entry.getFile().getContentCache();
  1491. // If this is the first use of line information for this buffer, compute the
  1492. // SourceLineCache for it on demand.
  1493. std::optional<llvm::MemoryBufferRef> Buffer =
  1494. Content->getBufferOrNone(Diag, getFileManager());
  1495. if (!Buffer)
  1496. return SourceLocation();
  1497. if (!Content->SourceLineCache)
  1498. Content->SourceLineCache =
  1499. LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
  1500. if (Line > Content->SourceLineCache.size()) {
  1501. unsigned Size = Buffer->getBufferSize();
  1502. if (Size > 0)
  1503. --Size;
  1504. return FileLoc.getLocWithOffset(Size);
  1505. }
  1506. unsigned FilePos = Content->SourceLineCache[Line - 1];
  1507. const char *Buf = Buffer->getBufferStart() + FilePos;
  1508. unsigned BufLength = Buffer->getBufferSize() - FilePos;
  1509. if (BufLength == 0)
  1510. return FileLoc.getLocWithOffset(FilePos);
  1511. unsigned i = 0;
  1512. // Check that the given column is valid.
  1513. while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
  1514. ++i;
  1515. return FileLoc.getLocWithOffset(FilePos + i);
  1516. }
  1517. /// Compute a map of macro argument chunks to their expanded source
  1518. /// location. Chunks that are not part of a macro argument will map to an
  1519. /// invalid source location. e.g. if a file contains one macro argument at
  1520. /// offset 100 with length 10, this is how the map will be formed:
  1521. /// 0 -> SourceLocation()
  1522. /// 100 -> Expanded macro arg location
  1523. /// 110 -> SourceLocation()
  1524. void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
  1525. FileID FID) const {
  1526. assert(FID.isValid());
  1527. // Initially no macro argument chunk is present.
  1528. MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
  1529. int ID = FID.ID;
  1530. while (true) {
  1531. ++ID;
  1532. // Stop if there are no more FileIDs to check.
  1533. if (ID > 0) {
  1534. if (unsigned(ID) >= local_sloc_entry_size())
  1535. return;
  1536. } else if (ID == -1) {
  1537. return;
  1538. }
  1539. bool Invalid = false;
  1540. const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
  1541. if (Invalid)
  1542. return;
  1543. if (Entry.isFile()) {
  1544. auto& File = Entry.getFile();
  1545. if (File.getFileCharacteristic() == C_User_ModuleMap ||
  1546. File.getFileCharacteristic() == C_System_ModuleMap)
  1547. continue;
  1548. SourceLocation IncludeLoc = File.getIncludeLoc();
  1549. bool IncludedInFID =
  1550. (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
  1551. // Predefined header doesn't have a valid include location in main
  1552. // file, but any files created by it should still be skipped when
  1553. // computing macro args expanded in the main file.
  1554. (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
  1555. if (IncludedInFID) {
  1556. // Skip the files/macros of the #include'd file, we only care about
  1557. // macros that lexed macro arguments from our file.
  1558. if (Entry.getFile().NumCreatedFIDs)
  1559. ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
  1560. continue;
  1561. }
  1562. // If file was included but not from FID, there is no more files/macros
  1563. // that may be "contained" in this file.
  1564. if (IncludeLoc.isValid())
  1565. return;
  1566. continue;
  1567. }
  1568. const ExpansionInfo &ExpInfo = Entry.getExpansion();
  1569. if (ExpInfo.getExpansionLocStart().isFileID()) {
  1570. if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
  1571. return; // No more files/macros that may be "contained" in this file.
  1572. }
  1573. if (!ExpInfo.isMacroArgExpansion())
  1574. continue;
  1575. associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
  1576. ExpInfo.getSpellingLoc(),
  1577. SourceLocation::getMacroLoc(Entry.getOffset()),
  1578. getFileIDSize(FileID::get(ID)));
  1579. }
  1580. }
  1581. void SourceManager::associateFileChunkWithMacroArgExp(
  1582. MacroArgsMap &MacroArgsCache,
  1583. FileID FID,
  1584. SourceLocation SpellLoc,
  1585. SourceLocation ExpansionLoc,
  1586. unsigned ExpansionLength) const {
  1587. if (!SpellLoc.isFileID()) {
  1588. SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
  1589. SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
  1590. // The spelling range for this macro argument expansion can span multiple
  1591. // consecutive FileID entries. Go through each entry contained in the
  1592. // spelling range and if one is itself a macro argument expansion, recurse
  1593. // and associate the file chunk that it represents.
  1594. FileID SpellFID; // Current FileID in the spelling range.
  1595. unsigned SpellRelativeOffs;
  1596. std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
  1597. while (true) {
  1598. const SLocEntry &Entry = getSLocEntry(SpellFID);
  1599. SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
  1600. unsigned SpellFIDSize = getFileIDSize(SpellFID);
  1601. SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
  1602. const ExpansionInfo &Info = Entry.getExpansion();
  1603. if (Info.isMacroArgExpansion()) {
  1604. unsigned CurrSpellLength;
  1605. if (SpellFIDEndOffs < SpellEndOffs)
  1606. CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
  1607. else
  1608. CurrSpellLength = ExpansionLength;
  1609. associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
  1610. Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
  1611. ExpansionLoc, CurrSpellLength);
  1612. }
  1613. if (SpellFIDEndOffs >= SpellEndOffs)
  1614. return; // we covered all FileID entries in the spelling range.
  1615. // Move to the next FileID entry in the spelling range.
  1616. unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
  1617. ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
  1618. ExpansionLength -= advance;
  1619. ++SpellFID.ID;
  1620. SpellRelativeOffs = 0;
  1621. }
  1622. }
  1623. assert(SpellLoc.isFileID());
  1624. unsigned BeginOffs;
  1625. if (!isInFileID(SpellLoc, FID, &BeginOffs))
  1626. return;
  1627. unsigned EndOffs = BeginOffs + ExpansionLength;
  1628. // Add a new chunk for this macro argument. A previous macro argument chunk
  1629. // may have been lexed again, so e.g. if the map is
  1630. // 0 -> SourceLocation()
  1631. // 100 -> Expanded loc #1
  1632. // 110 -> SourceLocation()
  1633. // and we found a new macro FileID that lexed from offset 105 with length 3,
  1634. // the new map will be:
  1635. // 0 -> SourceLocation()
  1636. // 100 -> Expanded loc #1
  1637. // 105 -> Expanded loc #2
  1638. // 108 -> Expanded loc #1
  1639. // 110 -> SourceLocation()
  1640. //
  1641. // Since re-lexed macro chunks will always be the same size or less of
  1642. // previous chunks, we only need to find where the ending of the new macro
  1643. // chunk is mapped to and update the map with new begin/end mappings.
  1644. MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
  1645. --I;
  1646. SourceLocation EndOffsMappedLoc = I->second;
  1647. MacroArgsCache[BeginOffs] = ExpansionLoc;
  1648. MacroArgsCache[EndOffs] = EndOffsMappedLoc;
  1649. }
  1650. /// If \arg Loc points inside a function macro argument, the returned
  1651. /// location will be the macro location in which the argument was expanded.
  1652. /// If a macro argument is used multiple times, the expanded location will
  1653. /// be at the first expansion of the argument.
  1654. /// e.g.
  1655. /// MY_MACRO(foo);
  1656. /// ^
  1657. /// Passing a file location pointing at 'foo', will yield a macro location
  1658. /// where 'foo' was expanded into.
  1659. SourceLocation
  1660. SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
  1661. if (Loc.isInvalid() || !Loc.isFileID())
  1662. return Loc;
  1663. FileID FID;
  1664. unsigned Offset;
  1665. std::tie(FID, Offset) = getDecomposedLoc(Loc);
  1666. if (FID.isInvalid())
  1667. return Loc;
  1668. std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
  1669. if (!MacroArgsCache) {
  1670. MacroArgsCache = std::make_unique<MacroArgsMap>();
  1671. computeMacroArgsCache(*MacroArgsCache, FID);
  1672. }
  1673. assert(!MacroArgsCache->empty());
  1674. MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
  1675. // In case every element in MacroArgsCache is greater than Offset we can't
  1676. // decrement the iterator.
  1677. if (I == MacroArgsCache->begin())
  1678. return Loc;
  1679. --I;
  1680. SourceLocation::UIntTy MacroArgBeginOffs = I->first;
  1681. SourceLocation MacroArgExpandedLoc = I->second;
  1682. if (MacroArgExpandedLoc.isValid())
  1683. return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
  1684. return Loc;
  1685. }
  1686. std::pair<FileID, unsigned>
  1687. SourceManager::getDecomposedIncludedLoc(FileID FID) const {
  1688. if (FID.isInvalid())
  1689. return std::make_pair(FileID(), 0);
  1690. // Uses IncludedLocMap to retrieve/cache the decomposed loc.
  1691. using DecompTy = std::pair<FileID, unsigned>;
  1692. auto InsertOp = IncludedLocMap.try_emplace(FID);
  1693. DecompTy &DecompLoc = InsertOp.first->second;
  1694. if (!InsertOp.second)
  1695. return DecompLoc; // already in map.
  1696. SourceLocation UpperLoc;
  1697. bool Invalid = false;
  1698. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1699. if (!Invalid) {
  1700. if (Entry.isExpansion())
  1701. UpperLoc = Entry.getExpansion().getExpansionLocStart();
  1702. else
  1703. UpperLoc = Entry.getFile().getIncludeLoc();
  1704. }
  1705. if (UpperLoc.isValid())
  1706. DecompLoc = getDecomposedLoc(UpperLoc);
  1707. return DecompLoc;
  1708. }
  1709. /// Given a decomposed source location, move it up the include/expansion stack
  1710. /// to the parent source location. If this is possible, return the decomposed
  1711. /// version of the parent in Loc and return false. If Loc is the top-level
  1712. /// entry, return true and don't modify it.
  1713. static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
  1714. const SourceManager &SM) {
  1715. std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
  1716. if (UpperLoc.first.isInvalid())
  1717. return true; // We reached the top.
  1718. Loc = UpperLoc;
  1719. return false;
  1720. }
  1721. /// Return the cache entry for comparing the given file IDs
  1722. /// for isBeforeInTranslationUnit.
  1723. InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
  1724. FileID RFID) const {
  1725. // This is a magic number for limiting the cache size. It was experimentally
  1726. // derived from a small Objective-C project (where the cache filled
  1727. // out to ~250 items). We can make it larger if necessary.
  1728. // FIXME: this is almost certainly full these days. Use an LRU cache?
  1729. enum { MagicCacheSize = 300 };
  1730. IsBeforeInTUCacheKey Key(LFID, RFID);
  1731. // If the cache size isn't too large, do a lookup and if necessary default
  1732. // construct an entry. We can then return it to the caller for direct
  1733. // use. When they update the value, the cache will get automatically
  1734. // updated as well.
  1735. if (IBTUCache.size() < MagicCacheSize)
  1736. return IBTUCache.try_emplace(Key, LFID, RFID).first->second;
  1737. // Otherwise, do a lookup that will not construct a new value.
  1738. InBeforeInTUCache::iterator I = IBTUCache.find(Key);
  1739. if (I != IBTUCache.end())
  1740. return I->second;
  1741. // Fall back to the overflow value.
  1742. IBTUCacheOverflow.setQueryFIDs(LFID, RFID);
  1743. return IBTUCacheOverflow;
  1744. }
  1745. /// Determines the order of 2 source locations in the translation unit.
  1746. ///
  1747. /// \returns true if LHS source location comes before RHS, false otherwise.
  1748. bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
  1749. SourceLocation RHS) const {
  1750. assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
  1751. if (LHS == RHS)
  1752. return false;
  1753. std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
  1754. std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
  1755. // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
  1756. // is a serialized one referring to a file that was removed after we loaded
  1757. // the PCH.
  1758. if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
  1759. return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
  1760. std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
  1761. if (InSameTU.first)
  1762. return InSameTU.second;
  1763. // If we arrived here, the location is either in a built-ins buffer or
  1764. // associated with global inline asm. PR5662 and PR22576 are examples.
  1765. StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
  1766. StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
  1767. bool LIsBuiltins = LB == "<built-in>";
  1768. bool RIsBuiltins = RB == "<built-in>";
  1769. // Sort built-in before non-built-in.
  1770. if (LIsBuiltins || RIsBuiltins) {
  1771. if (LIsBuiltins != RIsBuiltins)
  1772. return LIsBuiltins;
  1773. // Both are in built-in buffers, but from different files. We just claim that
  1774. // lower IDs come first.
  1775. return LOffs.first < ROffs.first;
  1776. }
  1777. bool LIsAsm = LB == "<inline asm>";
  1778. bool RIsAsm = RB == "<inline asm>";
  1779. // Sort assembler after built-ins, but before the rest.
  1780. if (LIsAsm || RIsAsm) {
  1781. if (LIsAsm != RIsAsm)
  1782. return RIsAsm;
  1783. assert(LOffs.first == ROffs.first);
  1784. return false;
  1785. }
  1786. bool LIsScratch = LB == "<scratch space>";
  1787. bool RIsScratch = RB == "<scratch space>";
  1788. // Sort scratch after inline asm, but before the rest.
  1789. if (LIsScratch || RIsScratch) {
  1790. if (LIsScratch != RIsScratch)
  1791. return LIsScratch;
  1792. return LOffs.second < ROffs.second;
  1793. }
  1794. llvm_unreachable("Unsortable locations found");
  1795. }
  1796. std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
  1797. std::pair<FileID, unsigned> &LOffs,
  1798. std::pair<FileID, unsigned> &ROffs) const {
  1799. // If the source locations are in the same file, just compare offsets.
  1800. if (LOffs.first == ROffs.first)
  1801. return std::make_pair(true, LOffs.second < ROffs.second);
  1802. // If we are comparing a source location with multiple locations in the same
  1803. // file, we get a big win by caching the result.
  1804. InBeforeInTUCacheEntry &IsBeforeInTUCache =
  1805. getInBeforeInTUCache(LOffs.first, ROffs.first);
  1806. // If we are comparing a source location with multiple locations in the same
  1807. // file, we get a big win by caching the result.
  1808. if (IsBeforeInTUCache.isCacheValid())
  1809. return std::make_pair(
  1810. true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
  1811. // Okay, we missed in the cache, we'll compute the answer and populate it.
  1812. // We need to find the common ancestor. The only way of doing this is to
  1813. // build the complete include chain for one and then walking up the chain
  1814. // of the other looking for a match.
  1815. // A location within a FileID on the path up from LOffs to the main file.
  1816. struct Entry {
  1817. unsigned Offset;
  1818. FileID ParentFID; // Used for breaking ties.
  1819. };
  1820. llvm::SmallDenseMap<FileID, Entry, 16> LChain;
  1821. FileID Parent;
  1822. do {
  1823. LChain.try_emplace(LOffs.first, Entry{LOffs.second, Parent});
  1824. // We catch the case where LOffs is in a file included by ROffs and
  1825. // quit early. The other way round unfortunately remains suboptimal.
  1826. if (LOffs.first == ROffs.first)
  1827. break;
  1828. Parent = LOffs.first;
  1829. } while (!MoveUpIncludeHierarchy(LOffs, *this));
  1830. Parent = FileID();
  1831. do {
  1832. auto I = LChain.find(ROffs.first);
  1833. if (I != LChain.end()) {
  1834. // Compare the locations within the common file and cache them.
  1835. LOffs.first = I->first;
  1836. LOffs.second = I->second.Offset;
  1837. // The relative order of LParent and RParent is a tiebreaker when
  1838. // - locs expand to the same location (occurs in macro arg expansion)
  1839. // - one loc is a parent of the other (we consider the parent as "first")
  1840. // For the parent to be first, the invalid file ID must compare smaller.
  1841. // However loaded FileIDs are <0, so we perform *unsigned* comparison!
  1842. // This changes the relative order of local vs loaded FileIDs, but it
  1843. // doesn't matter as these are never mixed in macro expansion.
  1844. unsigned LParent = I->second.ParentFID.ID;
  1845. unsigned RParent = Parent.ID;
  1846. assert(((LOffs.second != ROffs.second) ||
  1847. (LParent == 0 || RParent == 0) ||
  1848. isInSameSLocAddrSpace(getComposedLoc(I->second.ParentFID, 0),
  1849. getComposedLoc(Parent, 0), nullptr)) &&
  1850. "Mixed local/loaded FileIDs with same include location?");
  1851. IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second,
  1852. LParent < RParent);
  1853. return std::make_pair(
  1854. true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
  1855. }
  1856. Parent = ROffs.first;
  1857. } while (!MoveUpIncludeHierarchy(ROffs, *this));
  1858. // If we found no match, we're not in the same TU.
  1859. // We don't cache this, but it is rare.
  1860. return std::make_pair(false, false);
  1861. }
  1862. void SourceManager::PrintStats() const {
  1863. llvm::errs() << "\n*** Source Manager Stats:\n";
  1864. llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
  1865. << " mem buffers mapped.\n";
  1866. llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
  1867. << llvm::capacity_in_bytes(LocalSLocEntryTable)
  1868. << " bytes of capacity), "
  1869. << NextLocalOffset << "B of Sloc address space used.\n";
  1870. llvm::errs() << LoadedSLocEntryTable.size()
  1871. << " loaded SLocEntries allocated, "
  1872. << MaxLoadedOffset - CurrentLoadedOffset
  1873. << "B of Sloc address space used.\n";
  1874. unsigned NumLineNumsComputed = 0;
  1875. unsigned NumFileBytesMapped = 0;
  1876. for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
  1877. NumLineNumsComputed += bool(I->second->SourceLineCache);
  1878. NumFileBytesMapped += I->second->getSizeBytesMapped();
  1879. }
  1880. unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
  1881. llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
  1882. << NumLineNumsComputed << " files with line #'s computed, "
  1883. << NumMacroArgsComputed << " files with macro args computed.\n";
  1884. llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
  1885. << NumBinaryProbes << " binary.\n";
  1886. }
  1887. LLVM_DUMP_METHOD void SourceManager::dump() const {
  1888. llvm::raw_ostream &out = llvm::errs();
  1889. auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
  1890. std::optional<SourceLocation::UIntTy> NextStart) {
  1891. out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
  1892. << " <SourceLocation " << Entry.getOffset() << ":";
  1893. if (NextStart)
  1894. out << *NextStart << ">\n";
  1895. else
  1896. out << "???\?>\n";
  1897. if (Entry.isFile()) {
  1898. auto &FI = Entry.getFile();
  1899. if (FI.NumCreatedFIDs)
  1900. out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
  1901. << ">\n";
  1902. if (FI.getIncludeLoc().isValid())
  1903. out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
  1904. auto &CC = FI.getContentCache();
  1905. out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
  1906. << "\n";
  1907. if (CC.BufferOverridden)
  1908. out << " contents overridden\n";
  1909. if (CC.ContentsEntry != CC.OrigEntry) {
  1910. out << " contents from "
  1911. << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
  1912. << "\n";
  1913. }
  1914. } else {
  1915. auto &EI = Entry.getExpansion();
  1916. out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
  1917. out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
  1918. << " range <" << EI.getExpansionLocStart().getOffset() << ":"
  1919. << EI.getExpansionLocEnd().getOffset() << ">\n";
  1920. }
  1921. };
  1922. // Dump local SLocEntries.
  1923. for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
  1924. DumpSLocEntry(ID, LocalSLocEntryTable[ID],
  1925. ID == NumIDs - 1 ? NextLocalOffset
  1926. : LocalSLocEntryTable[ID + 1].getOffset());
  1927. }
  1928. // Dump loaded SLocEntries.
  1929. std::optional<SourceLocation::UIntTy> NextStart;
  1930. for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
  1931. int ID = -(int)Index - 2;
  1932. if (SLocEntryLoaded[Index]) {
  1933. DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
  1934. NextStart = LoadedSLocEntryTable[Index].getOffset();
  1935. } else {
  1936. NextStart = std::nullopt;
  1937. }
  1938. }
  1939. }
  1940. void SourceManager::noteSLocAddressSpaceUsage(
  1941. DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const {
  1942. struct Info {
  1943. // A location where this file was entered.
  1944. SourceLocation Loc;
  1945. // Number of times this FileEntry was entered.
  1946. unsigned Inclusions = 0;
  1947. // Size usage from the file itself.
  1948. uint64_t DirectSize = 0;
  1949. // Total size usage from the file and its macro expansions.
  1950. uint64_t TotalSize = 0;
  1951. };
  1952. using UsageMap = llvm::MapVector<const FileEntry*, Info>;
  1953. UsageMap Usage;
  1954. uint64_t CountedSize = 0;
  1955. auto AddUsageForFileID = [&](FileID ID) {
  1956. // The +1 here is because getFileIDSize doesn't include the extra byte for
  1957. // the one-past-the-end location.
  1958. unsigned Size = getFileIDSize(ID) + 1;
  1959. // Find the file that used this address space, either directly or by
  1960. // macro expansion.
  1961. SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0));
  1962. FileID FileLocID = getFileID(FileStart);
  1963. const FileEntry *Entry = getFileEntryForID(FileLocID);
  1964. Info &EntryInfo = Usage[Entry];
  1965. if (EntryInfo.Loc.isInvalid())
  1966. EntryInfo.Loc = FileStart;
  1967. if (ID == FileLocID) {
  1968. ++EntryInfo.Inclusions;
  1969. EntryInfo.DirectSize += Size;
  1970. }
  1971. EntryInfo.TotalSize += Size;
  1972. CountedSize += Size;
  1973. };
  1974. // Loaded SLocEntries have indexes counting downwards from -2.
  1975. for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
  1976. AddUsageForFileID(FileID::get(-2 - Index));
  1977. }
  1978. // Local SLocEntries have indexes counting upwards from 0.
  1979. for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {
  1980. AddUsageForFileID(FileID::get(Index));
  1981. }
  1982. // Sort the usage by size from largest to smallest. Break ties by raw source
  1983. // location.
  1984. auto SortedUsage = Usage.takeVector();
  1985. auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) {
  1986. return A.second.TotalSize > B.second.TotalSize ||
  1987. (A.second.TotalSize == B.second.TotalSize &&
  1988. A.second.Loc < B.second.Loc);
  1989. };
  1990. auto SortedEnd = SortedUsage.end();
  1991. if (MaxNotes && SortedUsage.size() > *MaxNotes) {
  1992. SortedEnd = SortedUsage.begin() + *MaxNotes;
  1993. std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp);
  1994. }
  1995. std::sort(SortedUsage.begin(), SortedEnd, Cmp);
  1996. // Produce note on sloc address space usage total.
  1997. uint64_t LocalUsage = NextLocalOffset;
  1998. uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;
  1999. int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) /
  2000. MaxLoadedOffset);
  2001. Diag.Report(SourceLocation(), diag::note_total_sloc_usage)
  2002. << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent;
  2003. // Produce notes on sloc address space usage for each file with a high usage.
  2004. uint64_t ReportedSize = 0;
  2005. for (auto &[Entry, FileInfo] :
  2006. llvm::make_range(SortedUsage.begin(), SortedEnd)) {
  2007. Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage)
  2008. << FileInfo.Inclusions << FileInfo.DirectSize
  2009. << (FileInfo.TotalSize - FileInfo.DirectSize);
  2010. ReportedSize += FileInfo.TotalSize;
  2011. }
  2012. // Describe any remaining usage not reported in the per-file usage.
  2013. if (ReportedSize != CountedSize) {
  2014. Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage)
  2015. << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;
  2016. }
  2017. }
  2018. ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
  2019. /// Return the amount of memory used by memory buffers, breaking down
  2020. /// by heap-backed versus mmap'ed memory.
  2021. SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
  2022. size_t malloc_bytes = 0;
  2023. size_t mmap_bytes = 0;
  2024. for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
  2025. if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
  2026. switch (MemBufferInfos[i]->getMemoryBufferKind()) {
  2027. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  2028. mmap_bytes += sized_mapped;
  2029. break;
  2030. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  2031. malloc_bytes += sized_mapped;
  2032. break;
  2033. }
  2034. return MemoryBufferSizes(malloc_bytes, mmap_bytes);
  2035. }
  2036. size_t SourceManager::getDataStructureSizes() const {
  2037. size_t size = llvm::capacity_in_bytes(MemBufferInfos)
  2038. + llvm::capacity_in_bytes(LocalSLocEntryTable)
  2039. + llvm::capacity_in_bytes(LoadedSLocEntryTable)
  2040. + llvm::capacity_in_bytes(SLocEntryLoaded)
  2041. + llvm::capacity_in_bytes(FileInfos);
  2042. if (OverriddenFilesInfo)
  2043. size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
  2044. return size;
  2045. }
  2046. SourceManagerForFile::SourceManagerForFile(StringRef FileName,
  2047. StringRef Content) {
  2048. // This is referenced by `FileMgr` and will be released by `FileMgr` when it
  2049. // is deleted.
  2050. IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
  2051. new llvm::vfs::InMemoryFileSystem);
  2052. InMemoryFileSystem->addFile(
  2053. FileName, 0,
  2054. llvm::MemoryBuffer::getMemBuffer(Content, FileName,
  2055. /*RequiresNullTerminator=*/false));
  2056. // This is passed to `SM` as reference, so the pointer has to be referenced
  2057. // in `Environment` so that `FileMgr` can out-live this function scope.
  2058. FileMgr =
  2059. std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
  2060. // This is passed to `SM` as reference, so the pointer has to be referenced
  2061. // by `Environment` due to the same reason above.
  2062. Diagnostics = std::make_unique<DiagnosticsEngine>(
  2063. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
  2064. new DiagnosticOptions);
  2065. SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
  2066. FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
  2067. SourceLocation(), clang::SrcMgr::C_User);
  2068. assert(ID.isValid());
  2069. SourceMgr->setMainFileID(ID);
  2070. }