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