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