SourceManager.cpp 74 KB

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