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