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