SourceManager.cpp 68 KB

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