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