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