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