SourceManager.cpp 83 KB

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