blob: 7b34cb65e368464758c23cc51b803a5cf4871edf [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner133db8a2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner4b009652007-07-25 00:24:17 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/MacroInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
Chris Lattner545f39e2009-01-29 05:15:15 +000033#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000034#include "clang/Basic/SourceManager.h"
Ted Kremenek40003a72009-02-12 03:26:59 +000035#include "clang/Basic/FileManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000036#include "clang/Basic/TargetInfo.h"
Chris Lattnercbed2992008-10-05 20:40:30 +000037#include "llvm/ADT/APFloat.h"
Chris Lattner4b009652007-07-25 00:24:17 +000038#include "llvm/ADT/SmallVector.h"
39#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekce4c64e2008-01-14 16:44:48 +000040#include "llvm/Support/Streams.h"
Chris Lattner4b009652007-07-25 00:24:17 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Ted Kremenek5ab36b02008-04-17 21:23:07 +000045PreprocessorFactory::~PreprocessorFactory() {}
46
Chris Lattner4b009652007-07-25 00:24:17 +000047Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
48 TargetInfo &target, SourceManager &SM,
Ted Kremenekd976c3d2009-01-15 18:47:46 +000049 HeaderSearch &Headers,
50 IdentifierInfoLookup* IILookup)
Chris Lattner4b009652007-07-25 00:24:17 +000051 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
Ted Kremenekd976c3d2009-01-15 18:47:46 +000052 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts, IILookup),
Ted Kremenek94dcef72008-11-19 00:44:06 +000053 CurPPLexer(0), CurDirLookup(0), Callbacks(0) {
Chris Lattner4b009652007-07-25 00:24:17 +000054 ScratchBuf = new ScratchBuffer(SourceMgr);
55
56 // Clear stats.
57 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
58 NumIf = NumElse = NumEndif = 0;
59 NumEnteredSourceFiles = 0;
60 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
61 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
62 MaxIncludeStackDepth = 0;
63 NumSkipped = 0;
64
65 // Default to discarding comments.
66 KeepComments = false;
67 KeepMacroComments = false;
68
69 // Macro expansion is enabled.
70 DisableMacroExpansion = false;
71 InMacroArgs = false;
Chris Lattner5b54ed92008-03-09 02:26:03 +000072 NumCachedTokenLexers = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000073
Argiris Kirtzidisf55b1102008-08-10 13:15:22 +000074 CachedLexPos = 0;
75
Chris Lattner4b009652007-07-25 00:24:17 +000076 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
77 // This gets unpoisoned where it is allowed.
78 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
79
80 // Initialize the pragma handlers.
81 PragmaHandlers = new PragmaNamespace(0);
82 RegisterBuiltinPragmas();
83
84 // Initialize builtin macros like __LINE__ and friends.
85 RegisterBuiltinMacros();
86}
87
88Preprocessor::~Preprocessor() {
Argiris Kirtzidis1370cf12008-08-23 12:12:06 +000089 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
90
Chris Lattner4b009652007-07-25 00:24:17 +000091 while (!IncludeMacroStack.empty()) {
92 delete IncludeMacroStack.back().TheLexer;
Chris Lattner5b54ed92008-03-09 02:26:03 +000093 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner4b009652007-07-25 00:24:17 +000094 IncludeMacroStack.pop_back();
95 }
Chris Lattner7a1b0882007-10-07 08:44:20 +000096
97 // Free any macro definitions.
98 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
99 Macros.begin(), E = Macros.end(); I != E; ++I) {
Ted Kremenek5f9fb3f2008-12-15 19:56:42 +0000100 // We don't need to free the MacroInfo objects directly. These
101 // will be released when the BumpPtrAllocator 'BP' object gets
Ted Kremenek334035f2009-01-19 07:45:44 +0000102 // destroyed. We still need to run the dstor, however, to free
103 // memory alocated by MacroInfo.
Chris Lattnerf7566562009-02-20 22:19:20 +0000104 I->second->Destroy();
Ted Kremenek334035f2009-01-19 07:45:44 +0000105 I->second->~MacroInfo();
Chris Lattner7a1b0882007-10-07 08:44:20 +0000106 I->first->setHasMacroDefinition(false);
107 }
Chris Lattner4b009652007-07-25 00:24:17 +0000108
109 // Free any cached macro expanders.
Chris Lattner5b54ed92008-03-09 02:26:03 +0000110 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
111 delete TokenLexerCache[i];
Chris Lattner4b009652007-07-25 00:24:17 +0000112
113 // Release pragma information.
114 delete PragmaHandlers;
115
116 // Delete the scratch buffer info.
117 delete ScratchBuf;
Chris Lattner65829812008-03-14 06:07:05 +0000118
119 delete Callbacks;
Chris Lattner4b009652007-07-25 00:24:17 +0000120}
121
Ted Kremenek40003a72009-02-12 03:26:59 +0000122void Preprocessor::setPTHManager(PTHManager* pm) {
123 PTH.reset(pm);
124 FileMgr.setStatCache(PTH->createStatCache());
125}
126
Chris Lattner4b009652007-07-25 00:24:17 +0000127void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000128 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
129 << getSpelling(Tok) << "'";
Chris Lattner4b009652007-07-25 00:24:17 +0000130
131 if (!DumpFlags) return;
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000132
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000133 llvm::cerr << "\t";
Chris Lattner4b009652007-07-25 00:24:17 +0000134 if (Tok.isAtStartOfLine())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000135 llvm::cerr << " [StartOfLine]";
Chris Lattner4b009652007-07-25 00:24:17 +0000136 if (Tok.hasLeadingSpace())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000137 llvm::cerr << " [LeadingSpace]";
Chris Lattner4b009652007-07-25 00:24:17 +0000138 if (Tok.isExpandDisabled())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000139 llvm::cerr << " [ExpandDisabled]";
Chris Lattner4b009652007-07-25 00:24:17 +0000140 if (Tok.needsCleaning()) {
141 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000142 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
143 << "']";
Chris Lattner4b009652007-07-25 00:24:17 +0000144 }
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000145
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000146 llvm::cerr << "\tLoc=<";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000147 DumpLocation(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000148 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000149}
150
151void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattner836774b2009-01-27 07:57:44 +0000152 Loc.dump(SourceMgr);
Chris Lattner4b009652007-07-25 00:24:17 +0000153}
154
155void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000156 llvm::cerr << "MACRO: ";
Chris Lattner4b009652007-07-25 00:24:17 +0000157 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
158 DumpToken(MI.getReplacementToken(i));
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000159 llvm::cerr << " ";
Chris Lattner4b009652007-07-25 00:24:17 +0000160 }
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000161 llvm::cerr << "\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000162}
163
164void Preprocessor::PrintStats() {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000165 llvm::cerr << "\n*** Preprocessor Stats:\n";
166 llvm::cerr << NumDirectives << " directives found:\n";
167 llvm::cerr << " " << NumDefined << " #define.\n";
168 llvm::cerr << " " << NumUndefined << " #undef.\n";
169 llvm::cerr << " #include/#include_next/#import:\n";
170 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
171 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
172 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
173 llvm::cerr << " " << NumElse << " #else/#elif.\n";
174 llvm::cerr << " " << NumEndif << " #endif.\n";
175 llvm::cerr << " " << NumPragma << " #pragma.\n";
176 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000177
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000178 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
179 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
180 << NumFastMacroExpanded << " on the fast path.\n";
181 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
182 << " token paste (##) operations performed, "
183 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000184}
185
186//===----------------------------------------------------------------------===//
187// Token Spelling
188//===----------------------------------------------------------------------===//
189
190
191/// getSpelling() - Return the 'spelling' of this token. The spelling of a
192/// token are the characters used to represent the token in the source file
193/// after trigraph expansion and escaped-newline folding. In particular, this
194/// wants to get the true, uncanonicalized, spelling of things like digraphs
195/// UCNs, etc.
196std::string Preprocessor::getSpelling(const Token &Tok) const {
197 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Ted Kremenek562db7f2009-01-27 00:01:05 +0000198
Chris Lattner4b009652007-07-25 00:24:17 +0000199 // If this token contains nothing interesting, return it directly.
Ted Kremenek562db7f2009-01-27 00:01:05 +0000200 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000201 if (!Tok.needsCleaning())
202 return std::string(TokStart, TokStart+Tok.getLength());
203
204 std::string Result;
205 Result.reserve(Tok.getLength());
206
207 // Otherwise, hard case, relex the characters into the string.
208 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
209 Ptr != End; ) {
210 unsigned CharSize;
211 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
212 Ptr += CharSize;
213 }
214 assert(Result.size() != unsigned(Tok.getLength()) &&
215 "NeedsCleaning flag set on something that didn't need cleaning!");
216 return Result;
217}
218
219/// getSpelling - This method is used to get the spelling of a token into a
220/// preallocated buffer, instead of as an std::string. The caller is required
221/// to allocate enough space for the token, which is guaranteed to be at least
222/// Tok.getLength() bytes long. The actual length of the token is returned.
223///
224/// Note that this method may do two possible things: it may either fill in
225/// the buffer specified with characters, or it may *change the input pointer*
226/// to point to a constant buffer with the data already in it (avoiding a
227/// copy). The caller is not allowed to modify the returned buffer pointer
228/// if an internal buffer is returned.
229unsigned Preprocessor::getSpelling(const Token &Tok,
230 const char *&Buffer) const {
231 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
232
233 // If this token is an identifier, just return the string from the identifier
234 // table, which is very quick.
235 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
236 Buffer = II->getName();
Chris Lattner9c47fe62009-01-05 19:44:41 +0000237 return II->getLength();
Chris Lattner4b009652007-07-25 00:24:17 +0000238 }
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000239
Chris Lattner4b009652007-07-25 00:24:17 +0000240 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner6ad1f502009-01-26 19:29:26 +0000241 const char *TokStart = 0;
242
243 if (Tok.isLiteral())
244 TokStart = Tok.getLiteralData();
245
246 if (TokStart == 0)
247 TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000248
249 // If this token contains nothing interesting, return it directly.
250 if (!Tok.needsCleaning()) {
251 Buffer = TokStart;
252 return Tok.getLength();
253 }
Chris Lattner6ad1f502009-01-26 19:29:26 +0000254
Chris Lattner4b009652007-07-25 00:24:17 +0000255 // Otherwise, hard case, relex the characters into the string.
256 char *OutBuf = const_cast<char*>(Buffer);
257 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
258 Ptr != End; ) {
259 unsigned CharSize;
260 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
261 Ptr += CharSize;
262 }
263 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
264 "NeedsCleaning flag set on something that didn't need cleaning!");
265
266 return OutBuf-Buffer;
267}
268
269
270/// CreateString - Plop the specified string into a scratch buffer and return a
271/// location for it. If specified, the source location provides a source
272/// location for the token.
Chris Lattner6ad1f502009-01-26 19:29:26 +0000273void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
274 SourceLocation InstantiationLoc) {
275 Tok.setLength(Len);
276
277 const char *DestPtr;
278 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
279
280 if (InstantiationLoc.isValid())
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000281 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
282 InstantiationLoc, Len);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000283 Tok.setLocation(Loc);
284
285 // If this is a literal token, set the pointer data.
286 if (Tok.isLiteral())
287 Tok.setLiteralData(DestPtr);
Chris Lattner4b009652007-07-25 00:24:17 +0000288}
289
290
291/// AdvanceToTokenCharacter - Given a location that specifies the start of a
292/// token, return a new location that specifies a character within the token.
293SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
294 unsigned CharNo) {
Chris Lattner29e840e2009-02-18 18:56:29 +0000295 // If they request the first char of the token, we're trivially done.
Chris Lattner81df8462009-02-18 18:52:52 +0000296 if (CharNo == 0) return TokStart;
Chris Lattner4b009652007-07-25 00:24:17 +0000297
Chris Lattner18c8dc02009-01-16 07:36:28 +0000298 // Figure out how many physical characters away the specified instantiation
Chris Lattner4b009652007-07-25 00:24:17 +0000299 // character is. This needs to take into consideration newlines and
300 // trigraphs.
301 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
302 unsigned PhysOffset = 0;
303
304 // The usual case is that tokens don't contain anything interesting. Skip
305 // over the uninteresting characters. If a token only consists of simple
306 // chars, this method is extremely fast.
307 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
308 ++TokPtr, --CharNo, ++PhysOffset;
309
Chris Lattnerbed5ce72009-01-17 07:57:25 +0000310 // If we have a character that may be a trigraph or escaped newline, use a
Chris Lattner4b009652007-07-25 00:24:17 +0000311 // lexer to parse it correctly.
312 if (CharNo != 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000313 // Skip over characters the remaining characters.
Chris Lattnerbed5ce72009-01-17 07:57:25 +0000314 for (; CharNo; --CharNo) {
315 unsigned Size;
316 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
317 TokPtr += Size;
318 PhysOffset += Size;
319 }
Chris Lattner4b009652007-07-25 00:24:17 +0000320 }
321
322 return TokStart.getFileLocWithOffset(PhysOffset);
323}
324
325
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000326//===----------------------------------------------------------------------===//
327// Preprocessor Initialization Methods
328//===----------------------------------------------------------------------===//
329
330// Append a #define line to Buf for Macro. Macro should be of the form XXX,
331// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
332// "#define XXX Y z W". To get a #define with no value, use "XXX=".
333static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
334 const char *Command = "#define ") {
335 Buf.insert(Buf.end(), Command, Command+strlen(Command));
336 if (const char *Equal = strchr(Macro, '=')) {
337 // Turn the = into ' '.
338 Buf.insert(Buf.end(), Macro, Equal);
339 Buf.push_back(' ');
340 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
341 } else {
342 // Push "macroname 1".
343 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
344 Buf.push_back(' ');
345 Buf.push_back('1');
346 }
347 Buf.push_back('\n');
348}
349
Chris Lattnercbed2992008-10-05 20:40:30 +0000350/// PickFP - This is used to pick a value based on the FP semantics of the
351/// specified FP model.
352template <typename T>
353static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
354 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
355 if (Sem == &llvm::APFloat::IEEEsingle)
356 return IEEESingleVal;
357 if (Sem == &llvm::APFloat::IEEEdouble)
358 return IEEEDoubleVal;
359 if (Sem == &llvm::APFloat::x87DoubleExtended)
360 return X87DoubleExtendedVal;
361 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
362 return PPCDoubleDoubleVal;
363}
364
365static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
366 const llvm::fltSemantics *Sem) {
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000367 const char *DenormMin, *Epsilon, *Max, *Min;
368 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
369 "3.64519953188247460253e-4951L",
370 "4.94065645841246544176568792868221e-324L");
371 int Digits = PickFP(Sem, 6, 15, 18, 31);
372 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
373 "1.08420217248550443401e-19L",
374 "4.94065645841246544176568792868221e-324L");
375 int HasInifinity = 1, HasQuietNaN = 1;
376 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
377 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
378 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
379 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
380 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
381 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
382 "3.36210314311209350626e-4932L",
383 "2.00416836000897277799610805135016e-292L");
384 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
385 "1.18973149535723176502e+4932L",
386 "1.79769313486231580793728971405301e+308L");
Chris Lattnercbed2992008-10-05 20:40:30 +0000387
388 char MacroBuf[60];
389 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
390 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000391 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
392 DefineBuiltinMacro(Buf, MacroBuf);
393 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
394 DefineBuiltinMacro(Buf, MacroBuf);
395 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
396 DefineBuiltinMacro(Buf, MacroBuf);
397 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
398 DefineBuiltinMacro(Buf, MacroBuf);
399 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
400 DefineBuiltinMacro(Buf, MacroBuf);
401 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
402 DefineBuiltinMacro(Buf, MacroBuf);
403 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
404 DefineBuiltinMacro(Buf, MacroBuf);
405 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
406 DefineBuiltinMacro(Buf, MacroBuf);
407 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
408 DefineBuiltinMacro(Buf, MacroBuf);
409 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
410 DefineBuiltinMacro(Buf, MacroBuf);
411 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
412 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner8405e092009-02-05 07:19:24 +0000413 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
414 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnercbed2992008-10-05 20:40:30 +0000415}
416
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000417
Chris Lattnerd8ed1cf2009-02-06 04:50:25 +0000418/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
419/// named MacroName with the max value for a type with width 'TypeWidth' a
420/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
421static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
422 const char *ValSuffix, bool isSigned,
423 std::vector<char> &Buf) {
424 char MacroBuf[60];
425 uint64_t MaxVal;
426 if (isSigned)
427 MaxVal = (1LL << (TypeWidth - 1)) - 1;
428 else
429 MaxVal = ~0LL >> (64-TypeWidth);
430
431 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix);
432 DefineBuiltinMacro(Buf, MacroBuf);
433}
434
Chris Lattner534234c2009-02-06 05:04:11 +0000435static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
436 std::vector<char> &Buf) {
437 char MacroBuf[60];
438 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
439 DefineBuiltinMacro(Buf, MacroBuf);
440}
441
442
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000443static void InitializePredefinedMacros(Preprocessor &PP,
444 std::vector<char> &Buf) {
Chris Lattner2ac88e02009-02-06 22:59:26 +0000445 char MacroBuf[60];
Chris Lattnera023ec52008-10-05 19:32:22 +0000446 // Compiler version introspection macros.
447 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
448 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
449
450 // Currently claim to be compatible with GCC 4.2.1-5621.
451 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
452 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
453 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
454 DefineBuiltinMacro(Buf, "__GNUC__=4");
455 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
456 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
457 "build 5621) (dot 3)\"");
458
459
460 // Initialize language-specific preprocessor defines.
461
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000462 // These should all be defined in the preprocessor according to the
463 // current language configuration.
Steve Naroff19d04012008-12-18 22:37:25 +0000464 if (!PP.getLangOptions().Microsoft)
465 DefineBuiltinMacro(Buf, "__STDC__=1");
Daniel Dunbar20b88022008-12-01 18:55:22 +0000466 if (PP.getLangOptions().AsmPreprocessor)
467 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000468 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
469 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
470 else if (0) // STDC94 ?
471 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
472
473 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000474 if (PP.getLangOptions().ObjC1) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000475 DefineBuiltinMacro(Buf, "__OBJC__=1");
Fariborz Jahanian09110502009-02-16 18:28:48 +0000476 if (PP.getLangOptions().ObjCNonFragileABI)
477 DefineBuiltinMacro(Buf, "__OBJC2__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000478
479 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
480 DefineBuiltinMacro(Buf, "__weak=");
481 DefineBuiltinMacro(Buf, "__strong=");
482 } else {
483 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
484 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
485 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
486 }
487
488 if (PP.getLangOptions().NeXTRuntime)
489 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000490 }
Chris Lattner5edfe012008-10-05 19:44:25 +0000491
Chris Lattnerd5e60992008-10-06 07:43:09 +0000492 // darwin_constant_cfstrings controls this. This is also dependent
493 // on other things like the runtime I believe. This is set even for C code.
494 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
495
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000496 if (PP.getLangOptions().ObjC2)
497 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroffae84af82007-10-31 18:42:27 +0000498
Chris Lattner9b96b152008-09-30 00:48:48 +0000499 if (PP.getLangOptions().PascalStrings)
500 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
501
Chris Lattnera023ec52008-10-05 19:32:22 +0000502 if (PP.getLangOptions().Blocks) {
503 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
504 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattnerce296f82008-10-05 19:32:52 +0000505 }
Chris Lattnera023ec52008-10-05 19:32:22 +0000506
507 if (PP.getLangOptions().CPlusPlus) {
508 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
509 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
510 DefineBuiltinMacro(Buf, "__GNUG__=4");
511 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
512 DefineBuiltinMacro(Buf, "__cplusplus=1");
513 DefineBuiltinMacro(Buf, "__private_extern__=extern");
514 }
515
516 // Filter out some microsoft extensions when trying to parse in ms-compat
517 // mode.
518 if (PP.getLangOptions().Microsoft) {
Steve Naroffedd04d52008-12-25 14:16:32 +0000519 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
Chris Lattner2ac88e02009-02-06 22:59:26 +0000520 DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
521 DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
522 DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
523 DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
Chris Lattnera023ec52008-10-05 19:32:22 +0000524 }
525
Chris Lattnera023ec52008-10-05 19:32:22 +0000526 // Initialize target-specific preprocessor defines.
Chris Lattner5edfe012008-10-05 19:44:25 +0000527 const TargetInfo &TI = PP.getTargetInfo();
528
529 // Define type sizing macros based on the target properties.
530 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
531 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
Chris Lattnercbed2992008-10-05 20:40:30 +0000532
Chris Lattnere9415232009-02-05 07:27:41 +0000533 unsigned IntMaxWidth;
534 const char *IntMaxSuffix;
535 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) {
536 IntMaxWidth = TI.getLongLongWidth();
537 IntMaxSuffix = "LL";
538 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) {
539 IntMaxWidth = TI.getLongWidth();
540 IntMaxSuffix = "L";
541 } else {
542 assert(TI.getIntMaxType() == TargetInfo::SignedInt);
543 IntMaxWidth = TI.getIntWidth();
544 IntMaxSuffix = "";
545 }
546
Chris Lattnerd5aa2e52009-02-06 04:55:18 +0000547 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
548 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf);
549 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf);
550 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf);
551 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf);
552 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf);
Chris Lattnerd8ed1cf2009-02-06 04:50:25 +0000553 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf);
554
Chris Lattner534234c2009-02-06 05:04:11 +0000555 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
556 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
557 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
Chris Lattnerd9ef7242009-02-13 22:28:55 +0000558 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
Chris Lattner534234c2009-02-06 05:04:11 +0000559 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
Chris Lattner31bd8502009-02-06 05:06:07 +0000560 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
561 // FIXME: TargetInfo hookize __WINT_TYPE__.
562 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
563
Chris Lattnercbed2992008-10-05 20:40:30 +0000564 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
565 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
566 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner2ac88e02009-02-06 22:59:26 +0000567
568 // Define a __POINTER_WIDTH__ macro for stdint.h.
569 sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
570 DefineBuiltinMacro(Buf, MacroBuf);
571
572 if (!TI.isCharSigned())
573 DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");
574
575 // Define fixed-sized integer types for stdint.h
576 assert(TI.getCharWidth() == 8 && "unsupported target types");
577 assert(TI.getShortWidth() == 16 && "unsupported target types");
578 DefineBuiltinMacro(Buf, "__INT8_TYPE__=char");
579 DefineBuiltinMacro(Buf, "__INT16_TYPE__=short");
580
581 if (TI.getIntWidth() == 32)
582 DefineBuiltinMacro(Buf, "__INT32_TYPE__=int");
583 else {
584 assert(TI.getLongLongWidth() == 32 && "unsupported target types");
585 DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long");
586 }
587
588 // 16-bit targets doesn't necessarily have a 64-bit type.
589 if (TI.getLongLongWidth() == 64)
590 DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long");
Chris Lattner1be8bb92008-10-05 20:06:37 +0000591
Chris Lattner77cec472007-10-10 17:48:53 +0000592 // Add __builtin_va_list typedef.
593 {
Chris Lattner5edfe012008-10-05 19:44:25 +0000594 const char *VAList = TI.getVAListDeclaration();
Chris Lattner77cec472007-10-10 17:48:53 +0000595 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
596 Buf.push_back('\n');
597 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000598
Chris Lattner5edfe012008-10-05 19:44:25 +0000599 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner3da35682008-10-05 21:49:27 +0000600 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
601 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner3f6d8cf2008-10-05 19:22:37 +0000602 }
603
Chris Lattner5edfe012008-10-05 19:44:25 +0000604 // Build configuration options. FIXME: these should be controlled by
605 // command line options or something.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000606 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
607 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
608 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
609 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner5edfe012008-10-05 19:44:25 +0000610
Chris Lattner3da35682008-10-05 21:49:27 +0000611 // Macros to control C99 numerics and <float.h>
612 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
613 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
614 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
615 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
616 DefineBuiltinMacro(Buf, MacroBuf);
617
Chris Lattner5edfe012008-10-05 19:44:25 +0000618 // Get other target #defines.
619 TI.getTargetDefines(Buf);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000620
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000621 // FIXME: Should emit a #line directive here.
622}
623
624
625/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman886bf132008-01-07 04:01:26 +0000626/// which implicitly adds the builtin defines etc.
Ted Kremenek17861c52007-12-19 22:51:13 +0000627void Preprocessor::EnterMainSourceFile() {
Chris Lattner5a0d2272009-02-13 19:33:24 +0000628 // We do not allow the preprocessor to reenter the main file. Doing so will
629 // cause FileID's to accumulate information from both runs (e.g. #line
630 // information) and predefined macros aren't guaranteed to be set properly.
631 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000632 FileID MainFileID = SourceMgr.getMainFileID();
Ted Kremenek17861c52007-12-19 22:51:13 +0000633
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000634 // Enter the main file source buffer.
635 EnterSourceFile(MainFileID, 0);
636
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000637 // Tell the header info that the main file was entered. If the file is later
638 // #imported, it won't be re-entered.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000639 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000640 HeaderInfo.IncrementIncludeCount(FE);
641
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000642 std::vector<char> PrologFile;
643 PrologFile.reserve(4080);
644
645 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
646 InitializePredefinedMacros(*this, PrologFile);
647
648 // Add on the predefines from the driver.
Chris Lattner47b6a162008-04-19 23:09:31 +0000649 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000650
651 // Memory buffer must end with a null byte!
652 PrologFile.push_back(0);
653
654 // Now that we have emitted the predefined macros, #includes, etc into
655 // PrologFile, preprocess it to populate the initial preprocessor state.
656 llvm::MemoryBuffer *SB =
657 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
658 "<predefines>");
659 assert(SB && "Cannot fail to create predefined source buffer");
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000660 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
661 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000662
663 // Start parsing the predefines.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000664 EnterSourceFile(FID, 0);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000665}
Chris Lattner4b009652007-07-25 00:24:17 +0000666
Chris Lattner4b009652007-07-25 00:24:17 +0000667
668//===----------------------------------------------------------------------===//
669// Lexer Event Handling.
670//===----------------------------------------------------------------------===//
671
672/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
673/// identifier information for the token and install it into the token.
674IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
675 const char *BufPtr) {
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000676 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +0000677 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
678
679 // Look up this token, see if it is a macro, or if it is a language keyword.
680 IdentifierInfo *II;
681 if (BufPtr && !Identifier.needsCleaning()) {
682 // No cleaning needed, just use the characters from the lexed buffer.
683 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
684 } else {
685 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
686 llvm::SmallVector<char, 64> IdentifierBuffer;
687 IdentifierBuffer.resize(Identifier.getLength());
688 const char *TmpBuf = &IdentifierBuffer[0];
689 unsigned Size = getSpelling(Identifier, TmpBuf);
690 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
691 }
692 Identifier.setIdentifierInfo(II);
693 return II;
694}
695
696
697/// HandleIdentifier - This callback is invoked when the lexer reads an
698/// identifier. This callback looks up the identifier in the map and/or
699/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner5b747d02009-01-21 07:43:11 +0000700///
701/// Note that callers of this method are guarded by checking the
702/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
703/// IdentifierInfo methods that compute these properties will need to change to
704/// match.
Chris Lattner4b009652007-07-25 00:24:17 +0000705void Preprocessor::HandleIdentifier(Token &Identifier) {
706 assert(Identifier.getIdentifierInfo() &&
707 "Can't handle identifiers without identifier info!");
708
709 IdentifierInfo &II = *Identifier.getIdentifierInfo();
710
711 // If this identifier was poisoned, and if it was not produced from a macro
712 // expansion, emit an error.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000713 if (II.isPoisoned() && CurPPLexer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000714 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
715 Diag(Identifier, diag::err_pp_used_poisoned_id);
716 else
717 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
718 }
719
720 // If this is a macro to be expanded, do it.
Chris Lattner7a1b0882007-10-07 08:44:20 +0000721 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000722 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
723 if (MI->isEnabled()) {
724 if (!HandleMacroExpandedIdentifier(Identifier, MI))
725 return;
726 } else {
727 // C99 6.10.3.4p2 says that a disabled macro may never again be
728 // expanded, even if it's in a context where it could be expanded in the
729 // future.
730 Identifier.setFlag(Token::DisableExpand);
731 }
732 }
Chris Lattner4b009652007-07-25 00:24:17 +0000733 }
734
735 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
736 // then we act as if it is the actual operator and not the textual
737 // representation of it.
738 if (II.isCPlusPlusOperatorKeyword())
739 Identifier.setIdentifierInfo(0);
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741 // If this is an extension token, diagnose its use.
Steve Naroff892bc0e2008-09-02 18:50:17 +0000742 // We avoid diagnosing tokens that originate from macro definitions.
743 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Chris Lattner4b009652007-07-25 00:24:17 +0000744 Diag(Identifier, diag::ext_token_used);
745}