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