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