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