SourceManager.cpp 82 KB

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