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