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