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