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