xref: /llvm-project/clang/lib/Basic/SourceManager.cpp (revision 408efffbe4a52bae05f1677a47eb3ccfd5cdc1d3)
1 //===- SourceManager.cpp - Track and cache source files -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the SourceManager interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManagerInternals.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Capacity.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <memory>
40 #include <tuple>
41 #include <utility>
42 #include <vector>
43 
44 using namespace clang;
45 using namespace SrcMgr;
46 using llvm::MemoryBuffer;
47 
48 //===----------------------------------------------------------------------===//
49 // SourceManager Helper Classes
50 //===----------------------------------------------------------------------===//
51 
52 ContentCache::~ContentCache() {
53   if (shouldFreeBuffer())
54     delete Buffer.getPointer();
55 }
56 
57 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
58 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
59 unsigned ContentCache::getSizeBytesMapped() const {
60   return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
61 }
62 
63 /// Returns the kind of memory used to back the memory buffer for
64 /// this content cache.  This is used for performance analysis.
65 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
66   assert(Buffer.getPointer());
67 
68   // Should be unreachable, but keep for sanity.
69   if (!Buffer.getPointer())
70     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
71 
72   const llvm::MemoryBuffer *buf = Buffer.getPointer();
73   return buf->getBufferKind();
74 }
75 
76 /// getSize - Returns the size of the content encapsulated by this ContentCache.
77 ///  This can be the size of the source file or the size of an arbitrary
78 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
79 ///  file is not lazily brought in from disk to satisfy this query.
80 unsigned ContentCache::getSize() const {
81   return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
82                              : (unsigned) ContentsEntry->getSize();
83 }
84 
85 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
86   if (B && B == Buffer.getPointer()) {
87     assert(0 && "Replacing with the same buffer");
88     Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
89     return;
90   }
91 
92   if (shouldFreeBuffer())
93     delete Buffer.getPointer();
94   Buffer.setPointer(B);
95   Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
96 }
97 
98 const char *ContentCache::getInvalidBOM(StringRef BufStr) {
99   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
100   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
101   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
102   const char *InvalidBOM =
103       llvm::StringSwitch<const char *>(BufStr)
104           .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
105                       "UTF-32 (BE)")
106           .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
107                       "UTF-32 (LE)")
108           .StartsWith("\xFE\xFF", "UTF-16 (BE)")
109           .StartsWith("\xFF\xFE", "UTF-16 (LE)")
110           .StartsWith("\x2B\x2F\x76", "UTF-7")
111           .StartsWith("\xF7\x64\x4C", "UTF-1")
112           .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
113           .StartsWith("\x0E\xFE\xFF", "SCSU")
114           .StartsWith("\xFB\xEE\x28", "BOCU-1")
115           .StartsWith("\x84\x31\x95\x33", "GB-18030")
116           .Default(nullptr);
117 
118   return InvalidBOM;
119 }
120 
121 const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
122                                                   FileManager &FM,
123                                                   SourceLocation Loc,
124                                                   bool *Invalid) const {
125   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
126   // computed it, just return what we have.
127   if (Buffer.getPointer() || !ContentsEntry) {
128     if (Invalid)
129       *Invalid = isBufferInvalid();
130 
131     return Buffer.getPointer();
132   }
133 
134   // Check that the file's size fits in an 'unsigned' (with room for a
135   // past-the-end value). This is deeply regrettable, but various parts of
136   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
137   // offsets, line numbers, string literal lengths, and so on, and fail
138   // miserably on large source files.
139   if ((uint64_t)ContentsEntry->getSize() >=
140       std::numeric_limits<unsigned>::max()) {
141     // We can't make a memory buffer of the required size, so just make a small
142     // one. We should never hit a situation where we've already parsed to a
143     // later offset of the file, so it shouldn't matter that the buffer is
144     // smaller than the file.
145     Buffer.setPointer(
146         llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
147             .release());
148     if (Diag.isDiagnosticInFlight())
149       Diag.SetDelayedDiagnostic(diag::err_file_too_large,
150                                 ContentsEntry->getName());
151     else
152       Diag.Report(Loc, diag::err_file_too_large)
153         << ContentsEntry->getName();
154 
155     Buffer.setInt(Buffer.getInt() | InvalidFlag);
156     if (Invalid) *Invalid = true;
157     return Buffer.getPointer();
158   }
159 
160   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
161 
162   // If we were unable to open the file, then we are in an inconsistent
163   // situation where the content cache referenced a file which no longer
164   // exists. Most likely, we were using a stat cache with an invalid entry but
165   // the file could also have been removed during processing. Since we can't
166   // really deal with this situation, just create an empty buffer.
167   //
168   // FIXME: This is definitely not ideal, but our immediate clients can't
169   // currently handle returning a null entry here. Ideally we should detect
170   // that we are in an inconsistent situation and error out as quickly as
171   // possible.
172   if (!BufferOrError) {
173     StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
174     auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
175         ContentsEntry->getSize(), "<invalid>");
176     char *Ptr = BackupBuffer->getBufferStart();
177     for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
178       Ptr[i] = FillStr[i % FillStr.size()];
179     Buffer.setPointer(BackupBuffer.release());
180 
181     if (Diag.isDiagnosticInFlight())
182       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
183                                 ContentsEntry->getName(),
184                                 BufferOrError.getError().message());
185     else
186       Diag.Report(Loc, diag::err_cannot_open_file)
187           << ContentsEntry->getName() << BufferOrError.getError().message();
188 
189     Buffer.setInt(Buffer.getInt() | InvalidFlag);
190 
191     if (Invalid) *Invalid = true;
192     return Buffer.getPointer();
193   }
194 
195   Buffer.setPointer(BufferOrError->release());
196 
197   // Check that the file's size is the same as in the file entry (which may
198   // have come from a stat cache).
199   if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
200     if (Diag.isDiagnosticInFlight())
201       Diag.SetDelayedDiagnostic(diag::err_file_modified,
202                                 ContentsEntry->getName());
203     else
204       Diag.Report(Loc, diag::err_file_modified)
205         << ContentsEntry->getName();
206 
207     Buffer.setInt(Buffer.getInt() | InvalidFlag);
208     if (Invalid) *Invalid = true;
209     return Buffer.getPointer();
210   }
211 
212   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
213   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
214   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
215   StringRef BufStr = Buffer.getPointer()->getBuffer();
216   const char *InvalidBOM = getInvalidBOM(BufStr);
217 
218   if (InvalidBOM) {
219     Diag.Report(Loc, diag::err_unsupported_bom)
220       << InvalidBOM << ContentsEntry->getName();
221     Buffer.setInt(Buffer.getInt() | InvalidFlag);
222   }
223 
224   if (Invalid)
225     *Invalid = isBufferInvalid();
226 
227   return Buffer.getPointer();
228 }
229 
230 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
231   auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
232   if (IterBool.second)
233     FilenamesByID.push_back(&*IterBool.first);
234   return IterBool.first->second;
235 }
236 
237 /// Add a line note to the line table that indicates that there is a \#line or
238 /// GNU line marker at the specified FID/Offset location which changes the
239 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
240 /// change the presumed \#include stack.  If it is 1, this is a file entry, if
241 /// it is 2 then this is a file exit. FileKind specifies whether this is a
242 /// system header or extern C system header.
243 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
244                                 int FilenameID, unsigned EntryExit,
245                                 SrcMgr::CharacteristicKind FileKind) {
246   std::vector<LineEntry> &Entries = LineEntries[FID];
247 
248   // An unspecified FilenameID means use the last filename if available, or the
249   // main source file otherwise.
250   if (FilenameID == -1 && !Entries.empty())
251     FilenameID = Entries.back().FilenameID;
252 
253   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
254          "Adding line entries out of order!");
255 
256   unsigned IncludeOffset = 0;
257   if (EntryExit == 0) {  // No #include stack change.
258     IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
259   } else if (EntryExit == 1) {
260     IncludeOffset = Offset-1;
261   } else if (EntryExit == 2) {
262     assert(!Entries.empty() && Entries.back().IncludeOffset &&
263        "PPDirectives should have caught case when popping empty include stack");
264 
265     // Get the include loc of the last entries' include loc as our include loc.
266     IncludeOffset = 0;
267     if (const LineEntry *PrevEntry =
268           FindNearestLineEntry(FID, Entries.back().IncludeOffset))
269       IncludeOffset = PrevEntry->IncludeOffset;
270   }
271 
272   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
273                                    IncludeOffset));
274 }
275 
276 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
277 /// it.  If there is no line entry before Offset in FID, return null.
278 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
279                                                      unsigned Offset) {
280   const std::vector<LineEntry> &Entries = LineEntries[FID];
281   assert(!Entries.empty() && "No #line entries for this FID after all!");
282 
283   // It is very common for the query to be after the last #line, check this
284   // first.
285   if (Entries.back().FileOffset <= Offset)
286     return &Entries.back();
287 
288   // Do a binary search to find the maximal element that is still before Offset.
289   std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
290   if (I == Entries.begin())
291     return nullptr;
292   return &*--I;
293 }
294 
295 /// Add a new line entry that has already been encoded into
296 /// the internal representation of the line table.
297 void LineTableInfo::AddEntry(FileID FID,
298                              const std::vector<LineEntry> &Entries) {
299   LineEntries[FID] = Entries;
300 }
301 
302 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
303 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
304   return getLineTable().getLineTableFilenameID(Name);
305 }
306 
307 /// AddLineNote - Add a line note to the line table for the FileID and offset
308 /// specified by Loc.  If FilenameID is -1, it is considered to be
309 /// unspecified.
310 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311                                 int FilenameID, bool IsFileEntry,
312                                 bool IsFileExit,
313                                 SrcMgr::CharacteristicKind FileKind) {
314   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
315 
316   bool Invalid = false;
317   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
318   if (!Entry.isFile() || Invalid)
319     return;
320 
321   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
322 
323   // Remember that this file has #line directives now if it doesn't already.
324   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
325 
326   (void) getLineTable();
327 
328   unsigned EntryExit = 0;
329   if (IsFileEntry)
330     EntryExit = 1;
331   else if (IsFileExit)
332     EntryExit = 2;
333 
334   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
335                          EntryExit, FileKind);
336 }
337 
338 LineTableInfo &SourceManager::getLineTable() {
339   if (!LineTable)
340     LineTable.reset(new LineTableInfo());
341   return *LineTable;
342 }
343 
344 //===----------------------------------------------------------------------===//
345 // Private 'Create' methods.
346 //===----------------------------------------------------------------------===//
347 
348 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
349                              bool UserFilesAreVolatile)
350   : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
351   clearIDTables();
352   Diag.setSourceManager(this);
353 }
354 
355 SourceManager::~SourceManager() {
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     if (MemBufferInfos[i]) {
361       MemBufferInfos[i]->~ContentCache();
362       ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
363     }
364   }
365   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
366        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
367     if (I->second) {
368       I->second->~ContentCache();
369       ContentCacheAlloc.Deallocate(I->second);
370     }
371   }
372 }
373 
374 void SourceManager::clearIDTables() {
375   MainFileID = FileID();
376   LocalSLocEntryTable.clear();
377   LoadedSLocEntryTable.clear();
378   SLocEntryLoaded.clear();
379   LastLineNoFileIDQuery = FileID();
380   LastLineNoContentCache = nullptr;
381   LastFileIDLookup = FileID();
382 
383   if (LineTable)
384     LineTable->clear();
385 
386   // Use up FileID #0 as an invalid expansion.
387   NextLocalOffset = 0;
388   CurrentLoadedOffset = MaxLoadedOffset;
389   createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
390 }
391 
392 bool SourceManager::isMainFile(FileEntryRef SourceFile) {
393   assert(MainFileID.isValid() && "expected initialized SourceManager");
394   auto FE = getFileEntryRefForID(MainFileID);
395   if (!FE)
396     return false;
397   return FE->getUID() == SourceFile.getUID();
398 }
399 
400 void SourceManager::initializeForReplay(const SourceManager &Old) {
401   assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
402 
403   auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
404     auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
405     Clone->OrigEntry = Cache->OrigEntry;
406     Clone->ContentsEntry = Cache->ContentsEntry;
407     Clone->BufferOverridden = Cache->BufferOverridden;
408     Clone->IsFileVolatile = Cache->IsFileVolatile;
409     Clone->IsTransient = Cache->IsTransient;
410     Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
411     return Clone;
412   };
413 
414   // Ensure all SLocEntries are loaded from the external source.
415   for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
416     if (!Old.SLocEntryLoaded[I])
417       Old.loadSLocEntry(I, nullptr);
418 
419   // Inherit any content cache data from the old source manager.
420   for (auto &FileInfo : Old.FileInfos) {
421     SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
422     if (Slot)
423       continue;
424     Slot = CloneContentCache(FileInfo.second);
425   }
426 }
427 
428 /// getOrCreateContentCache - Create or return a cached ContentCache for the
429 /// specified file.
430 const ContentCache *
431 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
432                                        bool isSystemFile) {
433   assert(FileEnt && "Didn't specify a file entry to use?");
434 
435   // Do we already have information about this file?
436   ContentCache *&Entry = FileInfos[FileEnt];
437   if (Entry) return Entry;
438 
439   // Nope, create a new Cache entry.
440   Entry = ContentCacheAlloc.Allocate<ContentCache>();
441 
442   if (OverriddenFilesInfo) {
443     // If the file contents are overridden with contents from another file,
444     // pass that file to ContentCache.
445     llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
446         overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
447     if (overI == OverriddenFilesInfo->OverriddenFiles.end())
448       new (Entry) ContentCache(FileEnt);
449     else
450       new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
451                                                               : overI->second,
452                                overI->second);
453   } else {
454     new (Entry) ContentCache(FileEnt);
455   }
456 
457   Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
458   Entry->IsTransient = FilesAreTransient;
459 
460   return Entry;
461 }
462 
463 /// Create a new ContentCache for the specified memory buffer.
464 /// This does no caching.
465 const ContentCache *
466 SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
467                                            bool DoNotFree) {
468   // Add a new ContentCache to the MemBufferInfos list and return it.
469   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
470   new (Entry) ContentCache();
471   MemBufferInfos.push_back(Entry);
472   Entry->replaceBuffer(Buffer, DoNotFree);
473   return Entry;
474 }
475 
476 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
477                                                       bool *Invalid) const {
478   assert(!SLocEntryLoaded[Index]);
479   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
480     if (Invalid)
481       *Invalid = true;
482     // If the file of the SLocEntry changed we could still have loaded it.
483     if (!SLocEntryLoaded[Index]) {
484       // Try to recover; create a SLocEntry so the rest of clang can handle it.
485       LoadedSLocEntryTable[Index] = SLocEntry::get(
486           0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
487                            SrcMgr::C_User, ""));
488     }
489   }
490 
491   return LoadedSLocEntryTable[Index];
492 }
493 
494 std::pair<int, unsigned>
495 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
496                                          unsigned TotalSize) {
497   assert(ExternalSLocEntries && "Don't have an external sloc source");
498   // Make sure we're not about to run out of source locations.
499   if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
500     return std::make_pair(0, 0);
501   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
502   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
503   CurrentLoadedOffset -= TotalSize;
504   int ID = LoadedSLocEntryTable.size();
505   return std::make_pair(-ID - 1, CurrentLoadedOffset);
506 }
507 
508 /// As part of recovering from missing or changed content, produce a
509 /// fake, non-empty buffer.
510 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
511   if (!FakeBufferForRecovery)
512     FakeBufferForRecovery =
513         llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
514 
515   return FakeBufferForRecovery.get();
516 }
517 
518 /// As part of recovering from missing or changed content, produce a
519 /// fake content cache.
520 const SrcMgr::ContentCache *
521 SourceManager::getFakeContentCacheForRecovery() const {
522   if (!FakeContentCacheForRecovery) {
523     FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
524     FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
525                                                /*DoNotFree=*/true);
526   }
527   return FakeContentCacheForRecovery.get();
528 }
529 
530 /// Returns the previous in-order FileID or an invalid FileID if there
531 /// is no previous one.
532 FileID SourceManager::getPreviousFileID(FileID FID) const {
533   if (FID.isInvalid())
534     return FileID();
535 
536   int ID = FID.ID;
537   if (ID == -1)
538     return FileID();
539 
540   if (ID > 0) {
541     if (ID-1 == 0)
542       return FileID();
543   } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
544     return FileID();
545   }
546 
547   return FileID::get(ID-1);
548 }
549 
550 /// Returns the next in-order FileID or an invalid FileID if there is
551 /// no next one.
552 FileID SourceManager::getNextFileID(FileID FID) const {
553   if (FID.isInvalid())
554     return FileID();
555 
556   int ID = FID.ID;
557   if (ID > 0) {
558     if (unsigned(ID+1) >= local_sloc_entry_size())
559       return FileID();
560   } else if (ID+1 >= -1) {
561     return FileID();
562   }
563 
564   return FileID::get(ID+1);
565 }
566 
567 //===----------------------------------------------------------------------===//
568 // Methods to create new FileID's and macro expansions.
569 //===----------------------------------------------------------------------===//
570 
571 /// Create a new FileID that represents the specified file
572 /// being \#included from the specified IncludePosition.
573 ///
574 /// This translates NULL into standard input.
575 FileID SourceManager::createFileID(const FileEntry *SourceFile,
576                                    SourceLocation IncludePos,
577                                    SrcMgr::CharacteristicKind FileCharacter,
578                                    int LoadedID, unsigned LoadedOffset) {
579   assert(SourceFile && "Null source file!");
580   const SrcMgr::ContentCache *IR =
581       getOrCreateContentCache(SourceFile, isSystem(FileCharacter));
582   assert(IR && "getOrCreateContentCache() cannot return NULL");
583   return createFileID(IR, SourceFile->getName(), IncludePos, FileCharacter,
584 		      LoadedID, LoadedOffset);
585 }
586 
587 FileID SourceManager::createFileID(FileEntryRef SourceFile,
588                                    SourceLocation IncludePos,
589                                    SrcMgr::CharacteristicKind FileCharacter,
590                                    int LoadedID, unsigned LoadedOffset) {
591   const SrcMgr::ContentCache *IR = getOrCreateContentCache(
592       &SourceFile.getFileEntry(), isSystem(FileCharacter));
593   assert(IR && "getOrCreateContentCache() cannot return NULL");
594   return createFileID(IR, SourceFile.getName(), IncludePos, FileCharacter,
595 		      LoadedID, LoadedOffset);
596 }
597 
598 /// Create a new FileID that represents the specified memory buffer.
599 ///
600 /// This does no caching of the buffer and takes ownership of the
601 /// MemoryBuffer, so only pass a MemoryBuffer to this once.
602 FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
603                                    SrcMgr::CharacteristicKind FileCharacter,
604                                    int LoadedID, unsigned LoadedOffset,
605                                    SourceLocation IncludeLoc) {
606   StringRef Name = Buffer->getBufferIdentifier();
607   return createFileID(
608       createMemBufferContentCache(Buffer.release(), /*DoNotFree*/ false),
609       Name, IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
610 }
611 
612 /// Create a new FileID that represents the specified memory buffer.
613 ///
614 /// This does not take ownership of the MemoryBuffer. The memory buffer must
615 /// outlive the SourceManager.
616 FileID SourceManager::createFileID(UnownedTag, const llvm::MemoryBuffer *Buffer,
617                                    SrcMgr::CharacteristicKind FileCharacter,
618                                    int LoadedID, unsigned LoadedOffset,
619                                    SourceLocation IncludeLoc) {
620   return createFileID(createMemBufferContentCache(Buffer, /*DoNotFree*/ true),
621 		      Buffer->getBufferIdentifier(), IncludeLoc,
622 		      FileCharacter, LoadedID, LoadedOffset);
623 }
624 
625 /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
626 /// new FileID for the \p SourceFile.
627 FileID
628 SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
629                                  SrcMgr::CharacteristicKind FileCharacter) {
630   FileID ID = translateFile(SourceFile);
631   return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
632 					  FileCharacter);
633 }
634 
635 /// createFileID - Create a new FileID for the specified ContentCache and
636 /// include position.  This works regardless of whether the ContentCache
637 /// corresponds to a file or some other input source.
638 FileID SourceManager::createFileID(const ContentCache *File, StringRef Filename,
639                                    SourceLocation IncludePos,
640                                    SrcMgr::CharacteristicKind FileCharacter,
641                                    int LoadedID, unsigned LoadedOffset) {
642   if (LoadedID < 0) {
643     assert(LoadedID != -1 && "Loading sentinel FileID");
644     unsigned Index = unsigned(-LoadedID) - 2;
645     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
646     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
647     LoadedSLocEntryTable[Index] = SLocEntry::get(
648         LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
649     SLocEntryLoaded[Index] = true;
650     return FileID::get(LoadedID);
651   }
652   unsigned FileSize = File->getSize();
653   if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
654         NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
655     Diag.Report(IncludePos, diag::err_include_too_large);
656     return FileID();
657   }
658   LocalSLocEntryTable.push_back(
659       SLocEntry::get(NextLocalOffset,
660                      FileInfo::get(IncludePos, File, FileCharacter, Filename)));
661   // We do a +1 here because we want a SourceLocation that means "the end of the
662   // file", e.g. for the "no newline at the end of the file" diagnostic.
663   NextLocalOffset += FileSize + 1;
664 
665   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
666   // almost guaranteed to be from that file.
667   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
668   return LastFileIDLookup = FID;
669 }
670 
671 SourceLocation
672 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
673                                           SourceLocation ExpansionLoc,
674                                           unsigned TokLength) {
675   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
676                                                         ExpansionLoc);
677   return createExpansionLocImpl(Info, TokLength);
678 }
679 
680 SourceLocation
681 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
682                                   SourceLocation ExpansionLocStart,
683                                   SourceLocation ExpansionLocEnd,
684                                   unsigned TokLength,
685                                   bool ExpansionIsTokenRange,
686                                   int LoadedID,
687                                   unsigned LoadedOffset) {
688   ExpansionInfo Info = ExpansionInfo::create(
689       SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
690   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
691 }
692 
693 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
694                                                   SourceLocation TokenStart,
695                                                   SourceLocation TokenEnd) {
696   assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
697          "token spans multiple files");
698   return createExpansionLocImpl(
699       ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
700       TokenEnd.getOffset() - TokenStart.getOffset());
701 }
702 
703 SourceLocation
704 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
705                                       unsigned TokLength,
706                                       int LoadedID,
707                                       unsigned LoadedOffset) {
708   if (LoadedID < 0) {
709     assert(LoadedID != -1 && "Loading sentinel FileID");
710     unsigned Index = unsigned(-LoadedID) - 2;
711     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
712     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
713     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
714     SLocEntryLoaded[Index] = true;
715     return SourceLocation::getMacroLoc(LoadedOffset);
716   }
717   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
718   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
719          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
720          "Ran out of source locations!");
721   // See createFileID for that +1.
722   NextLocalOffset += TokLength + 1;
723   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
724 }
725 
726 const llvm::MemoryBuffer *
727 SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
728   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
729   assert(IR && "getOrCreateContentCache() cannot return NULL");
730   return IR->getBuffer(Diag, getFileManager(), SourceLocation(), Invalid);
731 }
732 
733 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
734                                          llvm::MemoryBuffer *Buffer,
735                                          bool DoNotFree) {
736   const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
737   assert(IR && "getOrCreateContentCache() cannot return NULL");
738 
739   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
740   const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
741 
742   getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
743 }
744 
745 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
746                                          const FileEntry *NewFile) {
747   assert(SourceFile->getSize() == NewFile->getSize() &&
748          "Different sizes, use the FileManager to create a virtual file with "
749          "the correct size");
750   assert(FileInfos.count(SourceFile) == 0 &&
751          "This function should be called at the initialization stage, before "
752          "any parsing occurs.");
753   getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
754 }
755 
756 const FileEntry *
757 SourceManager::bypassFileContentsOverride(const FileEntry &File) {
758   assert(isFileOverridden(&File));
759   llvm::Optional<FileEntryRef> BypassFile =
760       FileMgr.getBypassFile(FileEntryRef(File.getName(), File));
761 
762   // If the file can't be found in the FS, give up.
763   if (!BypassFile)
764     return nullptr;
765 
766   const FileEntry *FE = &BypassFile->getFileEntry();
767   (void)getOrCreateContentCache(FE);
768   return FE;
769 }
770 
771 void SourceManager::setFileIsTransient(const FileEntry *File) {
772   const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
773   const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
774 }
775 
776 Optional<FileEntryRef> SourceManager::getFileEntryRefForID(FileID FID) const {
777   bool Invalid = false;
778   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
779   if (Invalid || !Entry.isFile())
780     return None;
781 
782   const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
783   if (!Content || !Content->OrigEntry)
784     return None;
785   return FileEntryRef(Entry.getFile().getName(), *Content->OrigEntry);
786 }
787 
788 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
789   bool MyInvalid = false;
790   const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
791   if (!SLoc.isFile() || MyInvalid) {
792     if (Invalid)
793       *Invalid = true;
794     return "<<<<<INVALID SOURCE LOCATION>>>>>";
795   }
796 
797   const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
798       Diag, getFileManager(), SourceLocation(), &MyInvalid);
799   if (Invalid)
800     *Invalid = MyInvalid;
801 
802   if (MyInvalid)
803     return "<<<<<INVALID SOURCE LOCATION>>>>>";
804 
805   return Buf->getBuffer();
806 }
807 
808 //===----------------------------------------------------------------------===//
809 // SourceLocation manipulation methods.
810 //===----------------------------------------------------------------------===//
811 
812 /// Return the FileID for a SourceLocation.
813 ///
814 /// This is the cache-miss path of getFileID. Not as hot as that function, but
815 /// still very important. It is responsible for finding the entry in the
816 /// SLocEntry tables that contains the specified location.
817 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
818   if (!SLocOffset)
819     return FileID::get(0);
820 
821   // Now it is time to search for the correct file. See where the SLocOffset
822   // sits in the global view and consult local or loaded buffers for it.
823   if (SLocOffset < NextLocalOffset)
824     return getFileIDLocal(SLocOffset);
825   return getFileIDLoaded(SLocOffset);
826 }
827 
828 /// Return the FileID for a SourceLocation with a low offset.
829 ///
830 /// This function knows that the SourceLocation is in a local buffer, not a
831 /// loaded one.
832 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
833   assert(SLocOffset < NextLocalOffset && "Bad function choice");
834 
835   // After the first and second level caches, I see two common sorts of
836   // behavior: 1) a lot of searched FileID's are "near" the cached file
837   // location or are "near" the cached expansion location. 2) others are just
838   // completely random and may be a very long way away.
839   //
840   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
841   // then we fall back to a less cache efficient, but more scalable, binary
842   // search to find the location.
843 
844   // See if this is near the file point - worst case we start scanning from the
845   // most newly created FileID.
846   const SrcMgr::SLocEntry *I;
847 
848   if (LastFileIDLookup.ID < 0 ||
849       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
850     // Neither loc prunes our search.
851     I = LocalSLocEntryTable.end();
852   } else {
853     // Perhaps it is near the file point.
854     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
855   }
856 
857   // Find the FileID that contains this.  "I" is an iterator that points to a
858   // FileID whose offset is known to be larger than SLocOffset.
859   unsigned NumProbes = 0;
860   while (true) {
861     --I;
862     if (I->getOffset() <= SLocOffset) {
863       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
864 
865       // If this isn't an expansion, remember it.  We have good locality across
866       // FileID lookups.
867       if (!I->isExpansion())
868         LastFileIDLookup = Res;
869       NumLinearScans += NumProbes+1;
870       return Res;
871     }
872     if (++NumProbes == 8)
873       break;
874   }
875 
876   // Convert "I" back into an index.  We know that it is an entry whose index is
877   // larger than the offset we are looking for.
878   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
879   // LessIndex - This is the lower bound of the range that we're searching.
880   // We know that the offset corresponding to the FileID is is less than
881   // SLocOffset.
882   unsigned LessIndex = 0;
883   NumProbes = 0;
884   while (true) {
885     bool Invalid = false;
886     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
887     unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
888     if (Invalid)
889       return FileID::get(0);
890 
891     ++NumProbes;
892 
893     // If the offset of the midpoint is too large, chop the high side of the
894     // range to the midpoint.
895     if (MidOffset > SLocOffset) {
896       GreaterIndex = MiddleIndex;
897       continue;
898     }
899 
900     // If the middle index contains the value, succeed and return.
901     if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
902         SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
903       FileID Res = FileID::get(MiddleIndex);
904 
905       // If this isn't a macro expansion, remember it.  We have good locality
906       // across FileID lookups.
907       if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
908         LastFileIDLookup = Res;
909       NumBinaryProbes += NumProbes;
910       return Res;
911     }
912 
913     // Otherwise, move the low-side up to the middle index.
914     LessIndex = MiddleIndex;
915   }
916 }
917 
918 /// Return the FileID for a SourceLocation with a high offset.
919 ///
920 /// This function knows that the SourceLocation is in a loaded buffer, not a
921 /// local one.
922 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
923   // Sanity checking, otherwise a bug may lead to hanging in release build.
924   if (SLocOffset < CurrentLoadedOffset) {
925     assert(0 && "Invalid SLocOffset or bad function choice");
926     return FileID();
927   }
928 
929   // Essentially the same as the local case, but the loaded array is sorted
930   // in the other direction.
931 
932   // First do a linear scan from the last lookup position, if possible.
933   unsigned I;
934   int LastID = LastFileIDLookup.ID;
935   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
936     I = 0;
937   else
938     I = (-LastID - 2) + 1;
939 
940   unsigned NumProbes;
941   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
942     // Make sure the entry is loaded!
943     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
944     if (E.getOffset() <= SLocOffset) {
945       FileID Res = FileID::get(-int(I) - 2);
946 
947       if (!E.isExpansion())
948         LastFileIDLookup = Res;
949       NumLinearScans += NumProbes + 1;
950       return Res;
951     }
952   }
953 
954   // Linear scan failed. Do the binary search. Note the reverse sorting of the
955   // table: GreaterIndex is the one where the offset is greater, which is
956   // actually a lower index!
957   unsigned GreaterIndex = I;
958   unsigned LessIndex = LoadedSLocEntryTable.size();
959   NumProbes = 0;
960   while (true) {
961     ++NumProbes;
962     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
963     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
964     if (E.getOffset() == 0)
965       return FileID(); // invalid entry.
966 
967     ++NumProbes;
968 
969     if (E.getOffset() > SLocOffset) {
970       // Sanity checking, otherwise a bug may lead to hanging in release build.
971       if (GreaterIndex == MiddleIndex) {
972         assert(0 && "binary search missed the entry");
973         return FileID();
974       }
975       GreaterIndex = MiddleIndex;
976       continue;
977     }
978 
979     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
980       FileID Res = FileID::get(-int(MiddleIndex) - 2);
981       if (!E.isExpansion())
982         LastFileIDLookup = Res;
983       NumBinaryProbes += NumProbes;
984       return Res;
985     }
986 
987     // Sanity checking, otherwise a bug may lead to hanging in release build.
988     if (LessIndex == MiddleIndex) {
989       assert(0 && "binary search missed the entry");
990       return FileID();
991     }
992     LessIndex = MiddleIndex;
993   }
994 }
995 
996 SourceLocation SourceManager::
997 getExpansionLocSlowCase(SourceLocation Loc) const {
998   do {
999     // Note: If Loc indicates an offset into a token that came from a macro
1000     // expansion (e.g. the 5th character of the token) we do not want to add
1001     // this offset when going to the expansion location.  The expansion
1002     // location is the macro invocation, which the offset has nothing to do
1003     // with.  This is unlike when we get the spelling loc, because the offset
1004     // directly correspond to the token whose spelling we're inspecting.
1005     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
1006   } while (!Loc.isFileID());
1007 
1008   return Loc;
1009 }
1010 
1011 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
1012   do {
1013     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1014     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1015     Loc = Loc.getLocWithOffset(LocInfo.second);
1016   } while (!Loc.isFileID());
1017   return Loc;
1018 }
1019 
1020 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
1021   do {
1022     if (isMacroArgExpansion(Loc))
1023       Loc = getImmediateSpellingLoc(Loc);
1024     else
1025       Loc = getImmediateExpansionRange(Loc).getBegin();
1026   } while (!Loc.isFileID());
1027   return Loc;
1028 }
1029 
1030 
1031 std::pair<FileID, unsigned>
1032 SourceManager::getDecomposedExpansionLocSlowCase(
1033                                              const SrcMgr::SLocEntry *E) const {
1034   // If this is an expansion record, walk through all the expansion points.
1035   FileID FID;
1036   SourceLocation Loc;
1037   unsigned Offset;
1038   do {
1039     Loc = E->getExpansion().getExpansionLocStart();
1040 
1041     FID = getFileID(Loc);
1042     E = &getSLocEntry(FID);
1043     Offset = Loc.getOffset()-E->getOffset();
1044   } while (!Loc.isFileID());
1045 
1046   return std::make_pair(FID, Offset);
1047 }
1048 
1049 std::pair<FileID, unsigned>
1050 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1051                                                 unsigned Offset) const {
1052   // If this is an expansion record, walk through all the expansion points.
1053   FileID FID;
1054   SourceLocation Loc;
1055   do {
1056     Loc = E->getExpansion().getSpellingLoc();
1057     Loc = Loc.getLocWithOffset(Offset);
1058 
1059     FID = getFileID(Loc);
1060     E = &getSLocEntry(FID);
1061     Offset = Loc.getOffset()-E->getOffset();
1062   } while (!Loc.isFileID());
1063 
1064   return std::make_pair(FID, Offset);
1065 }
1066 
1067 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
1068 /// spelling location referenced by the ID.  This is the first level down
1069 /// towards the place where the characters that make up the lexed token can be
1070 /// found.  This should not generally be used by clients.
1071 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
1072   if (Loc.isFileID()) return Loc;
1073   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1074   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1075   return Loc.getLocWithOffset(LocInfo.second);
1076 }
1077 
1078 /// Return the filename of the file containing a SourceLocation.
1079 StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1080   if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1081     return F->getName();
1082   return StringRef();
1083 }
1084 
1085 /// getImmediateExpansionRange - Loc is required to be an expansion location.
1086 /// Return the start/end of the expansion information.
1087 CharSourceRange
1088 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
1089   assert(Loc.isMacroID() && "Not a macro expansion loc!");
1090   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
1091   return Expansion.getExpansionLocRange();
1092 }
1093 
1094 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
1095   while (isMacroArgExpansion(Loc))
1096     Loc = getImmediateSpellingLoc(Loc);
1097   return Loc;
1098 }
1099 
1100 /// getExpansionRange - Given a SourceLocation object, return the range of
1101 /// tokens covered by the expansion in the ultimate file.
1102 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1103   if (Loc.isFileID())
1104     return CharSourceRange(SourceRange(Loc, Loc), true);
1105 
1106   CharSourceRange Res = getImmediateExpansionRange(Loc);
1107 
1108   // Fully resolve the start and end locations to their ultimate expansion
1109   // points.
1110   while (!Res.getBegin().isFileID())
1111     Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1112   while (!Res.getEnd().isFileID()) {
1113     CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1114     Res.setEnd(EndRange.getEnd());
1115     Res.setTokenRange(EndRange.isTokenRange());
1116   }
1117   return Res;
1118 }
1119 
1120 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1121                                         SourceLocation *StartLoc) const {
1122   if (!Loc.isMacroID()) return false;
1123 
1124   FileID FID = getFileID(Loc);
1125   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1126   if (!Expansion.isMacroArgExpansion()) return false;
1127 
1128   if (StartLoc)
1129     *StartLoc = Expansion.getExpansionLocStart();
1130   return true;
1131 }
1132 
1133 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1134   if (!Loc.isMacroID()) return false;
1135 
1136   FileID FID = getFileID(Loc);
1137   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1138   return Expansion.isMacroBodyExpansion();
1139 }
1140 
1141 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1142                                              SourceLocation *MacroBegin) const {
1143   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1144 
1145   std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1146   if (DecompLoc.second > 0)
1147     return false; // Does not point at the start of expansion range.
1148 
1149   bool Invalid = false;
1150   const SrcMgr::ExpansionInfo &ExpInfo =
1151       getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1152   if (Invalid)
1153     return false;
1154   SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1155 
1156   if (ExpInfo.isMacroArgExpansion()) {
1157     // For macro argument expansions, check if the previous FileID is part of
1158     // the same argument expansion, in which case this Loc is not at the
1159     // beginning of the expansion.
1160     FileID PrevFID = getPreviousFileID(DecompLoc.first);
1161     if (!PrevFID.isInvalid()) {
1162       const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1163       if (Invalid)
1164         return false;
1165       if (PrevEntry.isExpansion() &&
1166           PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1167         return false;
1168     }
1169   }
1170 
1171   if (MacroBegin)
1172     *MacroBegin = ExpLoc;
1173   return true;
1174 }
1175 
1176 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1177                                                SourceLocation *MacroEnd) const {
1178   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1179 
1180   FileID FID = getFileID(Loc);
1181   SourceLocation NextLoc = Loc.getLocWithOffset(1);
1182   if (isInFileID(NextLoc, FID))
1183     return false; // Does not point at the end of expansion range.
1184 
1185   bool Invalid = false;
1186   const SrcMgr::ExpansionInfo &ExpInfo =
1187       getSLocEntry(FID, &Invalid).getExpansion();
1188   if (Invalid)
1189     return false;
1190 
1191   if (ExpInfo.isMacroArgExpansion()) {
1192     // For macro argument expansions, check if the next FileID is part of the
1193     // same argument expansion, in which case this Loc is not at the end of the
1194     // expansion.
1195     FileID NextFID = getNextFileID(FID);
1196     if (!NextFID.isInvalid()) {
1197       const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1198       if (Invalid)
1199         return false;
1200       if (NextEntry.isExpansion() &&
1201           NextEntry.getExpansion().getExpansionLocStart() ==
1202               ExpInfo.getExpansionLocStart())
1203         return false;
1204     }
1205   }
1206 
1207   if (MacroEnd)
1208     *MacroEnd = ExpInfo.getExpansionLocEnd();
1209   return true;
1210 }
1211 
1212 //===----------------------------------------------------------------------===//
1213 // Queries about the code at a SourceLocation.
1214 //===----------------------------------------------------------------------===//
1215 
1216 /// getCharacterData - Return a pointer to the start of the specified location
1217 /// in the appropriate MemoryBuffer.
1218 const char *SourceManager::getCharacterData(SourceLocation SL,
1219                                             bool *Invalid) const {
1220   // Note that this is a hot function in the getSpelling() path, which is
1221   // heavily used by -E mode.
1222   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1223 
1224   // Note that calling 'getBuffer()' may lazily page in a source file.
1225   bool CharDataInvalid = false;
1226   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1227   if (CharDataInvalid || !Entry.isFile()) {
1228     if (Invalid)
1229       *Invalid = true;
1230 
1231     return "<<<<INVALID BUFFER>>>>";
1232   }
1233   const llvm::MemoryBuffer *Buffer =
1234       Entry.getFile().getContentCache()->getBuffer(
1235           Diag, getFileManager(), SourceLocation(), &CharDataInvalid);
1236   if (Invalid)
1237     *Invalid = CharDataInvalid;
1238   return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1239 }
1240 
1241 /// getColumnNumber - Return the column # for the specified file position.
1242 /// this is significantly cheaper to compute than the line number.
1243 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1244                                         bool *Invalid) const {
1245   bool MyInvalid = false;
1246   const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1247   if (Invalid)
1248     *Invalid = MyInvalid;
1249 
1250   if (MyInvalid)
1251     return 1;
1252 
1253   // It is okay to request a position just past the end of the buffer.
1254   if (FilePos > MemBuf->getBufferSize()) {
1255     if (Invalid)
1256       *Invalid = true;
1257     return 1;
1258   }
1259 
1260   const char *Buf = MemBuf->getBufferStart();
1261   // See if we just calculated the line number for this FilePos and can use
1262   // that to lookup the start of the line instead of searching for it.
1263   if (LastLineNoFileIDQuery == FID &&
1264       LastLineNoContentCache->SourceLineCache != nullptr &&
1265       LastLineNoResult < LastLineNoContentCache->NumLines) {
1266     unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1267     unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1268     unsigned LineEnd = SourceLineCache[LastLineNoResult];
1269     if (FilePos >= LineStart && FilePos < LineEnd) {
1270       // LineEnd is the LineStart of the next line.
1271       // A line ends with separator LF or CR+LF on Windows.
1272       // FilePos might point to the last separator,
1273       // but we need a column number at most 1 + the last column.
1274       if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1275         if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1276           --FilePos;
1277       }
1278       return FilePos - LineStart + 1;
1279     }
1280   }
1281 
1282   unsigned LineStart = FilePos;
1283   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1284     --LineStart;
1285   return FilePos-LineStart+1;
1286 }
1287 
1288 // isInvalid - Return the result of calling loc.isInvalid(), and
1289 // if Invalid is not null, set its value to same.
1290 template<typename LocType>
1291 static bool isInvalid(LocType Loc, bool *Invalid) {
1292   bool MyInvalid = Loc.isInvalid();
1293   if (Invalid)
1294     *Invalid = MyInvalid;
1295   return MyInvalid;
1296 }
1297 
1298 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1299                                                 bool *Invalid) const {
1300   if (isInvalid(Loc, Invalid)) return 0;
1301   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1302   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1303 }
1304 
1305 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1306                                                  bool *Invalid) const {
1307   if (isInvalid(Loc, Invalid)) return 0;
1308   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1309   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1310 }
1311 
1312 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1313                                                 bool *Invalid) const {
1314   PresumedLoc PLoc = getPresumedLoc(Loc);
1315   if (isInvalid(PLoc, Invalid)) return 0;
1316   return PLoc.getColumn();
1317 }
1318 
1319 #ifdef __SSE2__
1320 #include <emmintrin.h>
1321 #endif
1322 
1323 static LLVM_ATTRIBUTE_NOINLINE void
1324 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1325                    llvm::BumpPtrAllocator &Alloc,
1326                    const SourceManager &SM, bool &Invalid);
1327 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1328                                llvm::BumpPtrAllocator &Alloc,
1329                                const SourceManager &SM, bool &Invalid) {
1330   // Note that calling 'getBuffer()' may lazily page in the file.
1331   const MemoryBuffer *Buffer =
1332       FI->getBuffer(Diag, SM.getFileManager(), SourceLocation(), &Invalid);
1333   if (Invalid)
1334     return;
1335 
1336   // Find the file offsets of all of the *physical* source lines.  This does
1337   // not look at trigraphs, escaped newlines, or anything else tricky.
1338   SmallVector<unsigned, 256> LineOffsets;
1339 
1340   // Line #1 starts at char 0.
1341   LineOffsets.push_back(0);
1342 
1343   const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1344   const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1345   const std::size_t BufLen = End - Buf;
1346   unsigned I = 0;
1347   while (I < BufLen) {
1348     if (Buf[I] == '\n') {
1349       LineOffsets.push_back(I + 1);
1350     } else if (Buf[I] == '\r') {
1351       // If this is \r\n, skip both characters.
1352       if (I + 1 < BufLen && Buf[I + 1] == '\n')
1353         ++I;
1354       LineOffsets.push_back(I + 1);
1355     }
1356     ++I;
1357   }
1358 
1359   // Copy the offsets into the FileInfo structure.
1360   FI->NumLines = LineOffsets.size();
1361   FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1362   std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1363 }
1364 
1365 /// getLineNumber - Given a SourceLocation, return the spelling line number
1366 /// for the position indicated.  This requires building and caching a table of
1367 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1368 /// about to emit a diagnostic.
1369 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1370                                       bool *Invalid) const {
1371   if (FID.isInvalid()) {
1372     if (Invalid)
1373       *Invalid = true;
1374     return 1;
1375   }
1376 
1377   ContentCache *Content;
1378   if (LastLineNoFileIDQuery == FID)
1379     Content = LastLineNoContentCache;
1380   else {
1381     bool MyInvalid = false;
1382     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1383     if (MyInvalid || !Entry.isFile()) {
1384       if (Invalid)
1385         *Invalid = true;
1386       return 1;
1387     }
1388 
1389     Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1390   }
1391 
1392   // If this is the first use of line information for this buffer, compute the
1393   /// SourceLineCache for it on demand.
1394   if (!Content->SourceLineCache) {
1395     bool MyInvalid = false;
1396     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1397     if (Invalid)
1398       *Invalid = MyInvalid;
1399     if (MyInvalid)
1400       return 1;
1401   } else if (Invalid)
1402     *Invalid = false;
1403 
1404   // Okay, we know we have a line number table.  Do a binary search to find the
1405   // line number that this character position lands on.
1406   unsigned *SourceLineCache = Content->SourceLineCache;
1407   unsigned *SourceLineCacheStart = SourceLineCache;
1408   unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1409 
1410   unsigned QueriedFilePos = FilePos+1;
1411 
1412   // FIXME: I would like to be convinced that this code is worth being as
1413   // complicated as it is, binary search isn't that slow.
1414   //
1415   // If it is worth being optimized, then in my opinion it could be more
1416   // performant, simpler, and more obviously correct by just "galloping" outward
1417   // from the queried file position. In fact, this could be incorporated into a
1418   // generic algorithm such as lower_bound_with_hint.
1419   //
1420   // If someone gives me a test case where this matters, and I will do it! - DWD
1421 
1422   // If the previous query was to the same file, we know both the file pos from
1423   // that query and the line number returned.  This allows us to narrow the
1424   // search space from the entire file to something near the match.
1425   if (LastLineNoFileIDQuery == FID) {
1426     if (QueriedFilePos >= LastLineNoFilePos) {
1427       // FIXME: Potential overflow?
1428       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1429 
1430       // The query is likely to be nearby the previous one.  Here we check to
1431       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1432       // where big comment blocks and vertical whitespace eat up lines but
1433       // contribute no tokens.
1434       if (SourceLineCache+5 < SourceLineCacheEnd) {
1435         if (SourceLineCache[5] > QueriedFilePos)
1436           SourceLineCacheEnd = SourceLineCache+5;
1437         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1438           if (SourceLineCache[10] > QueriedFilePos)
1439             SourceLineCacheEnd = SourceLineCache+10;
1440           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1441             if (SourceLineCache[20] > QueriedFilePos)
1442               SourceLineCacheEnd = SourceLineCache+20;
1443           }
1444         }
1445       }
1446     } else {
1447       if (LastLineNoResult < Content->NumLines)
1448         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1449     }
1450   }
1451 
1452   unsigned *Pos
1453     = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1454   unsigned LineNo = Pos-SourceLineCacheStart;
1455 
1456   LastLineNoFileIDQuery = FID;
1457   LastLineNoContentCache = Content;
1458   LastLineNoFilePos = QueriedFilePos;
1459   LastLineNoResult = LineNo;
1460   return LineNo;
1461 }
1462 
1463 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1464                                               bool *Invalid) const {
1465   if (isInvalid(Loc, Invalid)) return 0;
1466   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1467   return getLineNumber(LocInfo.first, LocInfo.second);
1468 }
1469 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1470                                                bool *Invalid) const {
1471   if (isInvalid(Loc, Invalid)) return 0;
1472   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1473   return getLineNumber(LocInfo.first, LocInfo.second);
1474 }
1475 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1476                                               bool *Invalid) const {
1477   PresumedLoc PLoc = getPresumedLoc(Loc);
1478   if (isInvalid(PLoc, Invalid)) return 0;
1479   return PLoc.getLine();
1480 }
1481 
1482 /// getFileCharacteristic - return the file characteristic of the specified
1483 /// source location, indicating whether this is a normal file, a system
1484 /// header, or an "implicit extern C" system header.
1485 ///
1486 /// This state can be modified with flags on GNU linemarker directives like:
1487 ///   # 4 "foo.h" 3
1488 /// which changes all source locations in the current file after that to be
1489 /// considered to be from a system header.
1490 SrcMgr::CharacteristicKind
1491 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1492   assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1493   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1494   bool Invalid = false;
1495   const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1496   if (Invalid || !SEntry.isFile())
1497     return C_User;
1498 
1499   const SrcMgr::FileInfo &FI = SEntry.getFile();
1500 
1501   // If there are no #line directives in this file, just return the whole-file
1502   // state.
1503   if (!FI.hasLineDirectives())
1504     return FI.getFileCharacteristic();
1505 
1506   assert(LineTable && "Can't have linetable entries without a LineTable!");
1507   // See if there is a #line directive before the location.
1508   const LineEntry *Entry =
1509     LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1510 
1511   // If this is before the first line marker, use the file characteristic.
1512   if (!Entry)
1513     return FI.getFileCharacteristic();
1514 
1515   return Entry->FileKind;
1516 }
1517 
1518 /// Return the filename or buffer identifier of the buffer the location is in.
1519 /// Note that this name does not respect \#line directives.  Use getPresumedLoc
1520 /// for normal clients.
1521 StringRef SourceManager::getBufferName(SourceLocation Loc,
1522                                        bool *Invalid) const {
1523   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1524 
1525   return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1526 }
1527 
1528 /// getPresumedLoc - This method returns the "presumed" location of a
1529 /// SourceLocation specifies.  A "presumed location" can be modified by \#line
1530 /// or GNU line marker directives.  This provides a view on the data that a
1531 /// user should see in diagnostics, for example.
1532 ///
1533 /// Note that a presumed location is always given as the expansion point of an
1534 /// expansion location, not at the spelling location.
1535 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1536                                           bool UseLineDirectives) const {
1537   if (Loc.isInvalid()) return PresumedLoc();
1538 
1539   // Presumed locations are always for expansion points.
1540   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1541 
1542   bool Invalid = false;
1543   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1544   if (Invalid || !Entry.isFile())
1545     return PresumedLoc();
1546 
1547   const SrcMgr::FileInfo &FI = Entry.getFile();
1548   const SrcMgr::ContentCache *C = FI.getContentCache();
1549 
1550   // To get the source name, first consult the FileEntry (if one exists)
1551   // before the MemBuffer as this will avoid unnecessarily paging in the
1552   // MemBuffer.
1553   FileID FID = LocInfo.first;
1554   StringRef Filename;
1555   if (C->OrigEntry)
1556     Filename = C->OrigEntry->getName();
1557   else
1558     Filename = C->getBuffer(Diag, getFileManager())->getBufferIdentifier();
1559 
1560   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1561   if (Invalid)
1562     return PresumedLoc();
1563   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1564   if (Invalid)
1565     return PresumedLoc();
1566 
1567   SourceLocation IncludeLoc = FI.getIncludeLoc();
1568 
1569   // If we have #line directives in this file, update and overwrite the physical
1570   // location info if appropriate.
1571   if (UseLineDirectives && FI.hasLineDirectives()) {
1572     assert(LineTable && "Can't have linetable entries without a LineTable!");
1573     // See if there is a #line directive before this.  If so, get it.
1574     if (const LineEntry *Entry =
1575           LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1576       // If the LineEntry indicates a filename, use it.
1577       if (Entry->FilenameID != -1) {
1578         Filename = LineTable->getFilename(Entry->FilenameID);
1579         // The contents of files referenced by #line are not in the
1580         // SourceManager
1581         FID = FileID::get(0);
1582       }
1583 
1584       // Use the line number specified by the LineEntry.  This line number may
1585       // be multiple lines down from the line entry.  Add the difference in
1586       // physical line numbers from the query point and the line marker to the
1587       // total.
1588       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1589       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1590 
1591       // Note that column numbers are not molested by line markers.
1592 
1593       // Handle virtual #include manipulation.
1594       if (Entry->IncludeOffset) {
1595         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1596         IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1597       }
1598     }
1599   }
1600 
1601   return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1602 }
1603 
1604 /// Returns whether the PresumedLoc for a given SourceLocation is
1605 /// in the main file.
1606 ///
1607 /// This computes the "presumed" location for a SourceLocation, then checks
1608 /// whether it came from a file other than the main file. This is different
1609 /// from isWrittenInMainFile() because it takes line marker directives into
1610 /// account.
1611 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1612   if (Loc.isInvalid()) return false;
1613 
1614   // Presumed locations are always for expansion points.
1615   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1616 
1617   bool Invalid = false;
1618   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1619   if (Invalid || !Entry.isFile())
1620     return false;
1621 
1622   const SrcMgr::FileInfo &FI = Entry.getFile();
1623 
1624   // Check if there is a line directive for this location.
1625   if (FI.hasLineDirectives())
1626     if (const LineEntry *Entry =
1627             LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1628       if (Entry->IncludeOffset)
1629         return false;
1630 
1631   return FI.getIncludeLoc().isInvalid();
1632 }
1633 
1634 /// The size of the SLocEntry that \p FID represents.
1635 unsigned SourceManager::getFileIDSize(FileID FID) const {
1636   bool Invalid = false;
1637   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1638   if (Invalid)
1639     return 0;
1640 
1641   int ID = FID.ID;
1642   unsigned NextOffset;
1643   if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1644     NextOffset = getNextLocalOffset();
1645   else if (ID+1 == -1)
1646     NextOffset = MaxLoadedOffset;
1647   else
1648     NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1649 
1650   return NextOffset - Entry.getOffset() - 1;
1651 }
1652 
1653 //===----------------------------------------------------------------------===//
1654 // Other miscellaneous methods.
1655 //===----------------------------------------------------------------------===//
1656 
1657 /// Get the source location for the given file:line:col triplet.
1658 ///
1659 /// If the source file is included multiple times, the source location will
1660 /// be based upon an arbitrary inclusion.
1661 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1662                                                   unsigned Line,
1663                                                   unsigned Col) const {
1664   assert(SourceFile && "Null source file!");
1665   assert(Line && Col && "Line and column should start from 1!");
1666 
1667   FileID FirstFID = translateFile(SourceFile);
1668   return translateLineCol(FirstFID, Line, Col);
1669 }
1670 
1671 /// Get the FileID for the given file.
1672 ///
1673 /// If the source file is included multiple times, the FileID will be the
1674 /// first inclusion.
1675 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1676   assert(SourceFile && "Null source file!");
1677 
1678   // First, check the main file ID, since it is common to look for a
1679   // location in the main file.
1680   if (MainFileID.isValid()) {
1681     bool Invalid = false;
1682     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1683     if (Invalid)
1684       return FileID();
1685 
1686     if (MainSLoc.isFile()) {
1687       const ContentCache *MainContentCache =
1688           MainSLoc.getFile().getContentCache();
1689       if (MainContentCache && MainContentCache->OrigEntry == SourceFile)
1690         return MainFileID;
1691     }
1692   }
1693 
1694   // The location we're looking for isn't in the main file; look
1695   // through all of the local source locations.
1696   for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1697     bool Invalid = false;
1698     const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1699     if (Invalid)
1700       return FileID();
1701 
1702     if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
1703         SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1704       return FileID::get(I);
1705   }
1706 
1707   // If that still didn't help, try the modules.
1708   for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1709     const SLocEntry &SLoc = getLoadedSLocEntry(I);
1710     if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
1711         SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1712       return FileID::get(-int(I) - 2);
1713   }
1714 
1715   return FileID();
1716 }
1717 
1718 /// Get the source location in \arg FID for the given line:col.
1719 /// Returns null location if \arg FID is not a file SLocEntry.
1720 SourceLocation SourceManager::translateLineCol(FileID FID,
1721                                                unsigned Line,
1722                                                unsigned Col) const {
1723   // Lines are used as a one-based index into a zero-based array. This assert
1724   // checks for possible buffer underruns.
1725   assert(Line && Col && "Line and column should start from 1!");
1726 
1727   if (FID.isInvalid())
1728     return SourceLocation();
1729 
1730   bool Invalid = false;
1731   const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1732   if (Invalid)
1733     return SourceLocation();
1734 
1735   if (!Entry.isFile())
1736     return SourceLocation();
1737 
1738   SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1739 
1740   if (Line == 1 && Col == 1)
1741     return FileLoc;
1742 
1743   ContentCache *Content
1744     = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1745   if (!Content)
1746     return SourceLocation();
1747 
1748   // If this is the first use of line information for this buffer, compute the
1749   // SourceLineCache for it on demand.
1750   if (!Content->SourceLineCache) {
1751     bool MyInvalid = false;
1752     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1753     if (MyInvalid)
1754       return SourceLocation();
1755   }
1756 
1757   if (Line > Content->NumLines) {
1758     unsigned Size = Content->getBuffer(Diag, getFileManager())->getBufferSize();
1759     if (Size > 0)
1760       --Size;
1761     return FileLoc.getLocWithOffset(Size);
1762   }
1763 
1764   const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, getFileManager());
1765   unsigned FilePos = Content->SourceLineCache[Line - 1];
1766   const char *Buf = Buffer->getBufferStart() + FilePos;
1767   unsigned BufLength = Buffer->getBufferSize() - FilePos;
1768   if (BufLength == 0)
1769     return FileLoc.getLocWithOffset(FilePos);
1770 
1771   unsigned i = 0;
1772 
1773   // Check that the given column is valid.
1774   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1775     ++i;
1776   return FileLoc.getLocWithOffset(FilePos + i);
1777 }
1778 
1779 /// Compute a map of macro argument chunks to their expanded source
1780 /// location. Chunks that are not part of a macro argument will map to an
1781 /// invalid source location. e.g. if a file contains one macro argument at
1782 /// offset 100 with length 10, this is how the map will be formed:
1783 ///     0   -> SourceLocation()
1784 ///     100 -> Expanded macro arg location
1785 ///     110 -> SourceLocation()
1786 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1787                                           FileID FID) const {
1788   assert(FID.isValid());
1789 
1790   // Initially no macro argument chunk is present.
1791   MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1792 
1793   int ID = FID.ID;
1794   while (true) {
1795     ++ID;
1796     // Stop if there are no more FileIDs to check.
1797     if (ID > 0) {
1798       if (unsigned(ID) >= local_sloc_entry_size())
1799         return;
1800     } else if (ID == -1) {
1801       return;
1802     }
1803 
1804     bool Invalid = false;
1805     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1806     if (Invalid)
1807       return;
1808     if (Entry.isFile()) {
1809       SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1810       bool IncludedInFID =
1811           (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1812           // Predefined header doesn't have a valid include location in main
1813           // file, but any files created by it should still be skipped when
1814           // computing macro args expanded in the main file.
1815           (FID == MainFileID && Entry.getFile().Filename == "<built-in>");
1816       if (IncludedInFID) {
1817         // Skip the files/macros of the #include'd file, we only care about
1818         // macros that lexed macro arguments from our file.
1819         if (Entry.getFile().NumCreatedFIDs)
1820           ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1821         continue;
1822       } else if (IncludeLoc.isValid()) {
1823         // If file was included but not from FID, there is no more files/macros
1824         // that may be "contained" in this file.
1825         return;
1826       }
1827       continue;
1828     }
1829 
1830     const ExpansionInfo &ExpInfo = Entry.getExpansion();
1831 
1832     if (ExpInfo.getExpansionLocStart().isFileID()) {
1833       if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1834         return; // No more files/macros that may be "contained" in this file.
1835     }
1836 
1837     if (!ExpInfo.isMacroArgExpansion())
1838       continue;
1839 
1840     associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1841                                  ExpInfo.getSpellingLoc(),
1842                                  SourceLocation::getMacroLoc(Entry.getOffset()),
1843                                  getFileIDSize(FileID::get(ID)));
1844   }
1845 }
1846 
1847 void SourceManager::associateFileChunkWithMacroArgExp(
1848                                          MacroArgsMap &MacroArgsCache,
1849                                          FileID FID,
1850                                          SourceLocation SpellLoc,
1851                                          SourceLocation ExpansionLoc,
1852                                          unsigned ExpansionLength) const {
1853   if (!SpellLoc.isFileID()) {
1854     unsigned SpellBeginOffs = SpellLoc.getOffset();
1855     unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1856 
1857     // The spelling range for this macro argument expansion can span multiple
1858     // consecutive FileID entries. Go through each entry contained in the
1859     // spelling range and if one is itself a macro argument expansion, recurse
1860     // and associate the file chunk that it represents.
1861 
1862     FileID SpellFID; // Current FileID in the spelling range.
1863     unsigned SpellRelativeOffs;
1864     std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1865     while (true) {
1866       const SLocEntry &Entry = getSLocEntry(SpellFID);
1867       unsigned SpellFIDBeginOffs = Entry.getOffset();
1868       unsigned SpellFIDSize = getFileIDSize(SpellFID);
1869       unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1870       const ExpansionInfo &Info = Entry.getExpansion();
1871       if (Info.isMacroArgExpansion()) {
1872         unsigned CurrSpellLength;
1873         if (SpellFIDEndOffs < SpellEndOffs)
1874           CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1875         else
1876           CurrSpellLength = ExpansionLength;
1877         associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1878                       Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1879                       ExpansionLoc, CurrSpellLength);
1880       }
1881 
1882       if (SpellFIDEndOffs >= SpellEndOffs)
1883         return; // we covered all FileID entries in the spelling range.
1884 
1885       // Move to the next FileID entry in the spelling range.
1886       unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1887       ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1888       ExpansionLength -= advance;
1889       ++SpellFID.ID;
1890       SpellRelativeOffs = 0;
1891     }
1892   }
1893 
1894   assert(SpellLoc.isFileID());
1895 
1896   unsigned BeginOffs;
1897   if (!isInFileID(SpellLoc, FID, &BeginOffs))
1898     return;
1899 
1900   unsigned EndOffs = BeginOffs + ExpansionLength;
1901 
1902   // Add a new chunk for this macro argument. A previous macro argument chunk
1903   // may have been lexed again, so e.g. if the map is
1904   //     0   -> SourceLocation()
1905   //     100 -> Expanded loc #1
1906   //     110 -> SourceLocation()
1907   // and we found a new macro FileID that lexed from offset 105 with length 3,
1908   // the new map will be:
1909   //     0   -> SourceLocation()
1910   //     100 -> Expanded loc #1
1911   //     105 -> Expanded loc #2
1912   //     108 -> Expanded loc #1
1913   //     110 -> SourceLocation()
1914   //
1915   // Since re-lexed macro chunks will always be the same size or less of
1916   // previous chunks, we only need to find where the ending of the new macro
1917   // chunk is mapped to and update the map with new begin/end mappings.
1918 
1919   MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1920   --I;
1921   SourceLocation EndOffsMappedLoc = I->second;
1922   MacroArgsCache[BeginOffs] = ExpansionLoc;
1923   MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1924 }
1925 
1926 /// If \arg Loc points inside a function macro argument, the returned
1927 /// location will be the macro location in which the argument was expanded.
1928 /// If a macro argument is used multiple times, the expanded location will
1929 /// be at the first expansion of the argument.
1930 /// e.g.
1931 ///   MY_MACRO(foo);
1932 ///             ^
1933 /// Passing a file location pointing at 'foo', will yield a macro location
1934 /// where 'foo' was expanded into.
1935 SourceLocation
1936 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1937   if (Loc.isInvalid() || !Loc.isFileID())
1938     return Loc;
1939 
1940   FileID FID;
1941   unsigned Offset;
1942   std::tie(FID, Offset) = getDecomposedLoc(Loc);
1943   if (FID.isInvalid())
1944     return Loc;
1945 
1946   std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1947   if (!MacroArgsCache) {
1948     MacroArgsCache = std::make_unique<MacroArgsMap>();
1949     computeMacroArgsCache(*MacroArgsCache, FID);
1950   }
1951 
1952   assert(!MacroArgsCache->empty());
1953   MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1954   --I;
1955 
1956   unsigned MacroArgBeginOffs = I->first;
1957   SourceLocation MacroArgExpandedLoc = I->second;
1958   if (MacroArgExpandedLoc.isValid())
1959     return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1960 
1961   return Loc;
1962 }
1963 
1964 std::pair<FileID, unsigned>
1965 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1966   if (FID.isInvalid())
1967     return std::make_pair(FileID(), 0);
1968 
1969   // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1970 
1971   using DecompTy = std::pair<FileID, unsigned>;
1972   auto InsertOp = IncludedLocMap.try_emplace(FID);
1973   DecompTy &DecompLoc = InsertOp.first->second;
1974   if (!InsertOp.second)
1975     return DecompLoc; // already in map.
1976 
1977   SourceLocation UpperLoc;
1978   bool Invalid = false;
1979   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1980   if (!Invalid) {
1981     if (Entry.isExpansion())
1982       UpperLoc = Entry.getExpansion().getExpansionLocStart();
1983     else
1984       UpperLoc = Entry.getFile().getIncludeLoc();
1985   }
1986 
1987   if (UpperLoc.isValid())
1988     DecompLoc = getDecomposedLoc(UpperLoc);
1989 
1990   return DecompLoc;
1991 }
1992 
1993 /// Given a decomposed source location, move it up the include/expansion stack
1994 /// to the parent source location.  If this is possible, return the decomposed
1995 /// version of the parent in Loc and return false.  If Loc is the top-level
1996 /// entry, return true and don't modify it.
1997 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1998                                    const SourceManager &SM) {
1999   std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
2000   if (UpperLoc.first.isInvalid())
2001     return true; // We reached the top.
2002 
2003   Loc = UpperLoc;
2004   return false;
2005 }
2006 
2007 /// Return the cache entry for comparing the given file IDs
2008 /// for isBeforeInTranslationUnit.
2009 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2010                                                             FileID RFID) const {
2011   // This is a magic number for limiting the cache size.  It was experimentally
2012   // derived from a small Objective-C project (where the cache filled
2013   // out to ~250 items).  We can make it larger if necessary.
2014   enum { MagicCacheSize = 300 };
2015   IsBeforeInTUCacheKey Key(LFID, RFID);
2016 
2017   // If the cache size isn't too large, do a lookup and if necessary default
2018   // construct an entry.  We can then return it to the caller for direct
2019   // use.  When they update the value, the cache will get automatically
2020   // updated as well.
2021   if (IBTUCache.size() < MagicCacheSize)
2022     return IBTUCache[Key];
2023 
2024   // Otherwise, do a lookup that will not construct a new value.
2025   InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2026   if (I != IBTUCache.end())
2027     return I->second;
2028 
2029   // Fall back to the overflow value.
2030   return IBTUCacheOverflow;
2031 }
2032 
2033 /// Determines the order of 2 source locations in the translation unit.
2034 ///
2035 /// \returns true if LHS source location comes before RHS, false otherwise.
2036 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2037                                               SourceLocation RHS) const {
2038   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2039   if (LHS == RHS)
2040     return false;
2041 
2042   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2043   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2044 
2045   // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2046   // is a serialized one referring to a file that was removed after we loaded
2047   // the PCH.
2048   if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2049     return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2050 
2051   std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2052   if (InSameTU.first)
2053     return InSameTU.second;
2054 
2055   // If we arrived here, the location is either in a built-ins buffer or
2056   // associated with global inline asm. PR5662 and PR22576 are examples.
2057 
2058   StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2059   StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2060   bool LIsBuiltins = LB == "<built-in>";
2061   bool RIsBuiltins = RB == "<built-in>";
2062   // Sort built-in before non-built-in.
2063   if (LIsBuiltins || RIsBuiltins) {
2064     if (LIsBuiltins != RIsBuiltins)
2065       return LIsBuiltins;
2066     // Both are in built-in buffers, but from different files. We just claim that
2067     // lower IDs come first.
2068     return LOffs.first < ROffs.first;
2069   }
2070   bool LIsAsm = LB == "<inline asm>";
2071   bool RIsAsm = RB == "<inline asm>";
2072   // Sort assembler after built-ins, but before the rest.
2073   if (LIsAsm || RIsAsm) {
2074     if (LIsAsm != RIsAsm)
2075       return RIsAsm;
2076     assert(LOffs.first == ROffs.first);
2077     return false;
2078   }
2079   bool LIsScratch = LB == "<scratch space>";
2080   bool RIsScratch = RB == "<scratch space>";
2081   // Sort scratch after inline asm, but before the rest.
2082   if (LIsScratch || RIsScratch) {
2083     if (LIsScratch != RIsScratch)
2084       return LIsScratch;
2085     return LOffs.second < ROffs.second;
2086   }
2087   llvm_unreachable("Unsortable locations found");
2088 }
2089 
2090 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2091     std::pair<FileID, unsigned> &LOffs,
2092     std::pair<FileID, unsigned> &ROffs) const {
2093   // If the source locations are in the same file, just compare offsets.
2094   if (LOffs.first == ROffs.first)
2095     return std::make_pair(true, LOffs.second < ROffs.second);
2096 
2097   // If we are comparing a source location with multiple locations in the same
2098   // file, we get a big win by caching the result.
2099   InBeforeInTUCacheEntry &IsBeforeInTUCache =
2100     getInBeforeInTUCache(LOffs.first, ROffs.first);
2101 
2102   // If we are comparing a source location with multiple locations in the same
2103   // file, we get a big win by caching the result.
2104   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2105     return std::make_pair(
2106         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2107 
2108   // Okay, we missed in the cache, start updating the cache for this query.
2109   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2110                           /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2111 
2112   // We need to find the common ancestor. The only way of doing this is to
2113   // build the complete include chain for one and then walking up the chain
2114   // of the other looking for a match.
2115   // We use a map from FileID to Offset to store the chain. Easier than writing
2116   // a custom set hash info that only depends on the first part of a pair.
2117   using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2118   LocSet LChain;
2119   do {
2120     LChain.insert(LOffs);
2121     // We catch the case where LOffs is in a file included by ROffs and
2122     // quit early. The other way round unfortunately remains suboptimal.
2123   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2124   LocSet::iterator I;
2125   while((I = LChain.find(ROffs.first)) == LChain.end()) {
2126     if (MoveUpIncludeHierarchy(ROffs, *this))
2127       break; // Met at topmost file.
2128   }
2129   if (I != LChain.end())
2130     LOffs = *I;
2131 
2132   // If we exited because we found a nearest common ancestor, compare the
2133   // locations within the common file and cache them.
2134   if (LOffs.first == ROffs.first) {
2135     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2136     return std::make_pair(
2137         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2138   }
2139   // Clear the lookup cache, it depends on a common location.
2140   IsBeforeInTUCache.clear();
2141   return std::make_pair(false, false);
2142 }
2143 
2144 void SourceManager::PrintStats() const {
2145   llvm::errs() << "\n*** Source Manager Stats:\n";
2146   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2147                << " mem buffers mapped.\n";
2148   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2149                << llvm::capacity_in_bytes(LocalSLocEntryTable)
2150                << " bytes of capacity), "
2151                << NextLocalOffset << "B of Sloc address space used.\n";
2152   llvm::errs() << LoadedSLocEntryTable.size()
2153                << " loaded SLocEntries allocated, "
2154                << MaxLoadedOffset - CurrentLoadedOffset
2155                << "B of Sloc address space used.\n";
2156 
2157   unsigned NumLineNumsComputed = 0;
2158   unsigned NumFileBytesMapped = 0;
2159   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2160     NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2161     NumFileBytesMapped  += I->second->getSizeBytesMapped();
2162   }
2163   unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2164 
2165   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2166                << NumLineNumsComputed << " files with line #'s computed, "
2167                << NumMacroArgsComputed << " files with macro args computed.\n";
2168   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2169                << NumBinaryProbes << " binary.\n";
2170 }
2171 
2172 LLVM_DUMP_METHOD void SourceManager::dump() const {
2173   llvm::raw_ostream &out = llvm::errs();
2174 
2175   auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2176                            llvm::Optional<unsigned> NextStart) {
2177     out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2178         << " <SourceLocation " << Entry.getOffset() << ":";
2179     if (NextStart)
2180       out << *NextStart << ">\n";
2181     else
2182       out << "???\?>\n";
2183     if (Entry.isFile()) {
2184       auto &FI = Entry.getFile();
2185       if (FI.NumCreatedFIDs)
2186         out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2187             << ">\n";
2188       if (FI.getIncludeLoc().isValid())
2189         out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2190       if (auto *CC = FI.getContentCache()) {
2191         out << "  for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2192             << "\n";
2193         if (CC->BufferOverridden)
2194           out << "  contents overridden\n";
2195         if (CC->ContentsEntry != CC->OrigEntry) {
2196           out << "  contents from "
2197               << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2198               << "\n";
2199         }
2200       }
2201     } else {
2202       auto &EI = Entry.getExpansion();
2203       out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2204       out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2205           << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2206           << EI.getExpansionLocEnd().getOffset() << ">\n";
2207     }
2208   };
2209 
2210   // Dump local SLocEntries.
2211   for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2212     DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2213                   ID == NumIDs - 1 ? NextLocalOffset
2214                                    : LocalSLocEntryTable[ID + 1].getOffset());
2215   }
2216   // Dump loaded SLocEntries.
2217   llvm::Optional<unsigned> NextStart;
2218   for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2219     int ID = -(int)Index - 2;
2220     if (SLocEntryLoaded[Index]) {
2221       DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2222       NextStart = LoadedSLocEntryTable[Index].getOffset();
2223     } else {
2224       NextStart = None;
2225     }
2226   }
2227 }
2228 
2229 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2230 
2231 /// Return the amount of memory used by memory buffers, breaking down
2232 /// by heap-backed versus mmap'ed memory.
2233 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2234   size_t malloc_bytes = 0;
2235   size_t mmap_bytes = 0;
2236 
2237   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2238     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2239       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2240         case llvm::MemoryBuffer::MemoryBuffer_MMap:
2241           mmap_bytes += sized_mapped;
2242           break;
2243         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2244           malloc_bytes += sized_mapped;
2245           break;
2246       }
2247 
2248   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2249 }
2250 
2251 size_t SourceManager::getDataStructureSizes() const {
2252   size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2253     + llvm::capacity_in_bytes(LocalSLocEntryTable)
2254     + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2255     + llvm::capacity_in_bytes(SLocEntryLoaded)
2256     + llvm::capacity_in_bytes(FileInfos);
2257 
2258   if (OverriddenFilesInfo)
2259     size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2260 
2261   return size;
2262 }
2263 
2264 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2265                                            StringRef Content) {
2266   // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2267   // is deleted.
2268   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2269       new llvm::vfs::InMemoryFileSystem);
2270   InMemoryFileSystem->addFile(
2271       FileName, 0,
2272       llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2273                                        /*RequiresNullTerminator=*/false));
2274   // This is passed to `SM` as reference, so the pointer has to be referenced
2275   // in `Environment` so that `FileMgr` can out-live this function scope.
2276   FileMgr =
2277       std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2278   // This is passed to `SM` as reference, so the pointer has to be referenced
2279   // by `Environment` due to the same reason above.
2280   Diagnostics = std::make_unique<DiagnosticsEngine>(
2281       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2282       new DiagnosticOptions);
2283   SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2284   FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2285                                       SourceLocation(), clang::SrcMgr::C_User);
2286   assert(ID.isValid());
2287   SourceMgr->setMainFileID(ID);
2288 }
2289