Preprocessor.cpp revision 47246be8ac5b0ddde6c402b8fc6946b6135487b5
1//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15//   -H       - Print the name of each header file used.
16//   -d[MDNI] - Dump various things.
17//   -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"
31#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
33#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "llvm/ADT/APFloat.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/Support/Streams.h"
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
44PreprocessorFactory::~PreprocessorFactory() {}
45
46Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47                           TargetInfo &target, SourceManager &SM,
48                           HeaderSearch &Headers,
49                           IdentifierInfoLookup* IILookup)
50  : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
51    SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts, IILookup),
52    CurPPLexer(0), CurDirLookup(0), Callbacks(0) {
53  ScratchBuf = new ScratchBuffer(SourceMgr);
54
55  // Clear stats.
56  NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
57  NumIf = NumElse = NumEndif = 0;
58  NumEnteredSourceFiles = 0;
59  NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
60  NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
61  MaxIncludeStackDepth = 0;
62  NumSkipped = 0;
63
64  // Default to discarding comments.
65  KeepComments = false;
66  KeepMacroComments = false;
67
68  // Macro expansion is enabled.
69  DisableMacroExpansion = false;
70  InMacroArgs = false;
71  NumCachedTokenLexers = 0;
72
73  CachedLexPos = 0;
74
75  // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
76  // This gets unpoisoned where it is allowed.
77  (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
78
79  // Initialize the pragma handlers.
80  PragmaHandlers = new PragmaNamespace(0);
81  RegisterBuiltinPragmas();
82
83  // Initialize builtin macros like __LINE__ and friends.
84  RegisterBuiltinMacros();
85}
86
87Preprocessor::~Preprocessor() {
88  assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
89
90  while (!IncludeMacroStack.empty()) {
91    delete IncludeMacroStack.back().TheLexer;
92    delete IncludeMacroStack.back().TheTokenLexer;
93    IncludeMacroStack.pop_back();
94  }
95
96  // Free any macro definitions.
97  for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
98       Macros.begin(), E = Macros.end(); I != E; ++I) {
99    // We don't need to free the MacroInfo objects directly.  These
100    // will be released when the BumpPtrAllocator 'BP' object gets
101    // destroyed. We still need to run the dstor, however, to free
102    // memory alocated by MacroInfo.
103    I->second->~MacroInfo();
104    I->first->setHasMacroDefinition(false);
105  }
106
107  // Free any cached macro expanders.
108  for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
109    delete TokenLexerCache[i];
110
111  // Release pragma information.
112  delete PragmaHandlers;
113
114  // Delete the scratch buffer info.
115  delete ScratchBuf;
116
117  delete Callbacks;
118}
119
120void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
121  llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
122             << getSpelling(Tok) << "'";
123
124  if (!DumpFlags) return;
125
126  llvm::cerr << "\t";
127  if (Tok.isAtStartOfLine())
128    llvm::cerr << " [StartOfLine]";
129  if (Tok.hasLeadingSpace())
130    llvm::cerr << " [LeadingSpace]";
131  if (Tok.isExpandDisabled())
132    llvm::cerr << " [ExpandDisabled]";
133  if (Tok.needsCleaning()) {
134    const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
135    llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
136               << "']";
137  }
138
139  llvm::cerr << "\tLoc=<";
140  DumpLocation(Tok.getLocation());
141  llvm::cerr << ">";
142}
143
144void Preprocessor::DumpLocation(SourceLocation Loc) const {
145  SourceLocation LogLoc = SourceMgr.getInstantiationLoc(Loc);
146  llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
147             << SourceMgr.getLineNumber(LogLoc) << ':'
148             << SourceMgr.getColumnNumber(LogLoc);
149
150  SourceLocation SpellingLoc = SourceMgr.getSpellingLoc(Loc);
151  if (SpellingLoc != LogLoc) {
152    llvm::cerr << " <SpellingLoc=";
153    DumpLocation(SpellingLoc);
154    llvm::cerr << ">";
155  }
156}
157
158void Preprocessor::DumpMacro(const MacroInfo &MI) const {
159  llvm::cerr << "MACRO: ";
160  for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
161    DumpToken(MI.getReplacementToken(i));
162    llvm::cerr << "  ";
163  }
164  llvm::cerr << "\n";
165}
166
167void Preprocessor::PrintStats() {
168  llvm::cerr << "\n*** Preprocessor Stats:\n";
169  llvm::cerr << NumDirectives << " directives found:\n";
170  llvm::cerr << "  " << NumDefined << " #define.\n";
171  llvm::cerr << "  " << NumUndefined << " #undef.\n";
172  llvm::cerr << "  #include/#include_next/#import:\n";
173  llvm::cerr << "    " << NumEnteredSourceFiles << " source files entered.\n";
174  llvm::cerr << "    " << MaxIncludeStackDepth << " max include stack depth\n";
175  llvm::cerr << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
176  llvm::cerr << "  " << NumElse << " #else/#elif.\n";
177  llvm::cerr << "  " << NumEndif << " #endif.\n";
178  llvm::cerr << "  " << NumPragma << " #pragma.\n";
179  llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
180
181  llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
182             << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
183             << NumFastMacroExpanded << " on the fast path.\n";
184  llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
185             << " token paste (##) operations performed, "
186             << NumFastTokenPaste << " on the fast path.\n";
187}
188
189//===----------------------------------------------------------------------===//
190// Token Spelling
191//===----------------------------------------------------------------------===//
192
193
194/// getSpelling() - Return the 'spelling' of this token.  The spelling of a
195/// token are the characters used to represent the token in the source file
196/// after trigraph expansion and escaped-newline folding.  In particular, this
197/// wants to get the true, uncanonicalized, spelling of things like digraphs
198/// UCNs, etc.
199std::string Preprocessor::getSpelling(const Token &Tok) const {
200  assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
201  const char* TokStart;
202
203  if (PTH) {
204    if (unsigned Len = PTH->getSpelling(Tok.getLocation(), TokStart)) {
205      assert(!Tok.needsCleaning());
206      return std::string(TokStart, TokStart+Len);
207    }
208  }
209
210  // If this token contains nothing interesting, return it directly.
211  TokStart = SourceMgr.getCharacterData(Tok.getLocation());
212  if (!Tok.needsCleaning())
213    return std::string(TokStart, TokStart+Tok.getLength());
214
215  std::string Result;
216  Result.reserve(Tok.getLength());
217
218  // Otherwise, hard case, relex the characters into the string.
219  for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
220       Ptr != End; ) {
221    unsigned CharSize;
222    Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
223    Ptr += CharSize;
224  }
225  assert(Result.size() != unsigned(Tok.getLength()) &&
226         "NeedsCleaning flag set on something that didn't need cleaning!");
227  return Result;
228}
229
230/// getSpelling - This method is used to get the spelling of a token into a
231/// preallocated buffer, instead of as an std::string.  The caller is required
232/// to allocate enough space for the token, which is guaranteed to be at least
233/// Tok.getLength() bytes long.  The actual length of the token is returned.
234///
235/// Note that this method may do two possible things: it may either fill in
236/// the buffer specified with characters, or it may *change the input pointer*
237/// to point to a constant buffer with the data already in it (avoiding a
238/// copy).  The caller is not allowed to modify the returned buffer pointer
239/// if an internal buffer is returned.
240unsigned Preprocessor::getSpelling(const Token &Tok,
241                                   const char *&Buffer) const {
242  assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
243
244  // If this token is an identifier, just return the string from the identifier
245  // table, which is very quick.
246  if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
247    Buffer = II->getName();
248    return II->getLength();
249  }
250
251  // If using PTH, try and get the spelling from the PTH file.
252  if (PTH) {
253    unsigned Len;
254
255    if (CurPTHLexer) {
256      Len = CurPTHLexer.get()->getSpelling(Tok.getLocation(), Buffer);
257    } else {
258      Len = PTH->getSpelling(Tok.getLocation(), Buffer);
259    }
260
261    // Did we find a spelling?  If so return its length.  Otherwise fall
262    // back to the default behavior for getting the spelling by looking at
263    // at the source code.
264    if (Len)
265      return Len;
266  }
267
268  // Otherwise, compute the start of the token in the input lexer buffer.
269  const char *TokStart = 0;
270
271  if (Tok.isLiteral())
272    TokStart = Tok.getLiteralData();
273
274  if (TokStart == 0)
275    TokStart = SourceMgr.getCharacterData(Tok.getLocation());
276
277  // If this token contains nothing interesting, return it directly.
278  if (!Tok.needsCleaning()) {
279    Buffer = TokStart;
280    return Tok.getLength();
281  }
282
283  // Otherwise, hard case, relex the characters into the string.
284  char *OutBuf = const_cast<char*>(Buffer);
285  for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
286       Ptr != End; ) {
287    unsigned CharSize;
288    *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
289    Ptr += CharSize;
290  }
291  assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
292         "NeedsCleaning flag set on something that didn't need cleaning!");
293
294  return OutBuf-Buffer;
295}
296
297
298/// CreateString - Plop the specified string into a scratch buffer and return a
299/// location for it.  If specified, the source location provides a source
300/// location for the token.
301void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
302                                SourceLocation InstantiationLoc) {
303  Tok.setLength(Len);
304
305  const char *DestPtr;
306  SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
307
308  if (InstantiationLoc.isValid())
309    Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc, Len);
310  Tok.setLocation(Loc);
311
312  // If this is a literal token, set the pointer data.
313  if (Tok.isLiteral())
314    Tok.setLiteralData(DestPtr);
315}
316
317
318/// AdvanceToTokenCharacter - Given a location that specifies the start of a
319/// token, return a new location that specifies a character within the token.
320SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
321                                                     unsigned CharNo) {
322  // If they request the first char of the token, we're trivially done.  If this
323  // is a macro expansion, it doesn't make sense to point to a character within
324  // the instantiation point (the name).  We could point to the source
325  // character, but without also pointing to instantiation info, this is
326  // confusing.
327  if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
328
329  // Figure out how many physical characters away the specified instantiation
330  // character is.  This needs to take into consideration newlines and
331  // trigraphs.
332  const char *TokPtr = SourceMgr.getCharacterData(TokStart);
333  unsigned PhysOffset = 0;
334
335  // The usual case is that tokens don't contain anything interesting.  Skip
336  // over the uninteresting characters.  If a token only consists of simple
337  // chars, this method is extremely fast.
338  while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
339    ++TokPtr, --CharNo, ++PhysOffset;
340
341  // If we have a character that may be a trigraph or escaped newline, use a
342  // lexer to parse it correctly.
343  if (CharNo != 0) {
344    // Skip over characters the remaining characters.
345    for (; CharNo; --CharNo) {
346      unsigned Size;
347      Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
348      TokPtr += Size;
349      PhysOffset += Size;
350    }
351  }
352
353  return TokStart.getFileLocWithOffset(PhysOffset);
354}
355
356
357//===----------------------------------------------------------------------===//
358// Preprocessor Initialization Methods
359//===----------------------------------------------------------------------===//
360
361// Append a #define line to Buf for Macro.  Macro should be of the form XXX,
362// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
363// "#define XXX Y z W".  To get a #define with no value, use "XXX=".
364static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
365                               const char *Command = "#define ") {
366  Buf.insert(Buf.end(), Command, Command+strlen(Command));
367  if (const char *Equal = strchr(Macro, '=')) {
368    // Turn the = into ' '.
369    Buf.insert(Buf.end(), Macro, Equal);
370    Buf.push_back(' ');
371    Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
372  } else {
373    // Push "macroname 1".
374    Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
375    Buf.push_back(' ');
376    Buf.push_back('1');
377  }
378  Buf.push_back('\n');
379}
380
381/// PickFP - This is used to pick a value based on the FP semantics of the
382/// specified FP model.
383template <typename T>
384static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
385                T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
386  if (Sem == &llvm::APFloat::IEEEsingle)
387    return IEEESingleVal;
388  if (Sem == &llvm::APFloat::IEEEdouble)
389    return IEEEDoubleVal;
390  if (Sem == &llvm::APFloat::x87DoubleExtended)
391    return X87DoubleExtendedVal;
392  assert(Sem == &llvm::APFloat::PPCDoubleDouble);
393  return PPCDoubleDoubleVal;
394}
395
396static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
397                              const llvm::fltSemantics *Sem) {
398  const char *DenormMin, *Epsilon, *Max, *Min;
399  DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
400                     "3.64519953188247460253e-4951L",
401                     "4.94065645841246544176568792868221e-324L");
402  int Digits = PickFP(Sem, 6, 15, 18, 31);
403  Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
404                   "1.08420217248550443401e-19L",
405                   "4.94065645841246544176568792868221e-324L");
406  int HasInifinity = 1, HasQuietNaN = 1;
407  int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
408  int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
409  int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
410  int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
411  int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
412  Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
413               "3.36210314311209350626e-4932L",
414               "2.00416836000897277799610805135016e-292L");
415  Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
416               "1.18973149535723176502e+4932L",
417               "1.79769313486231580793728971405301e+308L");
418
419  char MacroBuf[60];
420  sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
421  DefineBuiltinMacro(Buf, MacroBuf);
422  sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
423  DefineBuiltinMacro(Buf, MacroBuf);
424  sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
425  DefineBuiltinMacro(Buf, MacroBuf);
426  sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
427  DefineBuiltinMacro(Buf, MacroBuf);
428  sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
429  DefineBuiltinMacro(Buf, MacroBuf);
430  sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
431  DefineBuiltinMacro(Buf, MacroBuf);
432  sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
433  DefineBuiltinMacro(Buf, MacroBuf);
434  sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
435  DefineBuiltinMacro(Buf, MacroBuf);
436  sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
437  DefineBuiltinMacro(Buf, MacroBuf);
438  sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
439  DefineBuiltinMacro(Buf, MacroBuf);
440  sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
441  DefineBuiltinMacro(Buf, MacroBuf);
442  sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
443  DefineBuiltinMacro(Buf, MacroBuf);
444}
445
446
447static void InitializePredefinedMacros(Preprocessor &PP,
448                                       std::vector<char> &Buf) {
449  // Compiler version introspection macros.
450  DefineBuiltinMacro(Buf, "__llvm__=1");   // LLVM Backend
451  DefineBuiltinMacro(Buf, "__clang__=1");  // Clang Frontend
452
453  // Currently claim to be compatible with GCC 4.2.1-5621.
454  DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
455  DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
456  DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
457  DefineBuiltinMacro(Buf, "__GNUC__=4");
458  DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
459  DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
460                     "build 5621) (dot 3)\"");
461
462
463  // Initialize language-specific preprocessor defines.
464
465  // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
466  // and __DATE__ etc.
467  // These should all be defined in the preprocessor according to the
468  // current language configuration.
469  if (!PP.getLangOptions().Microsoft)
470    DefineBuiltinMacro(Buf, "__STDC__=1");
471  if (PP.getLangOptions().AsmPreprocessor)
472    DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
473  if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
474    DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
475  else if (0) // STDC94 ?
476    DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
477
478  DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
479  if (PP.getLangOptions().ObjC1) {
480    DefineBuiltinMacro(Buf, "__OBJC__=1");
481
482    if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
483      DefineBuiltinMacro(Buf, "__weak=");
484      DefineBuiltinMacro(Buf, "__strong=");
485    } else {
486      DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
487      DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
488      DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
489    }
490
491    if (PP.getLangOptions().NeXTRuntime)
492      DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
493  }
494
495  // darwin_constant_cfstrings controls this. This is also dependent
496  // on other things like the runtime I believe.  This is set even for C code.
497  DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
498
499  if (PP.getLangOptions().ObjC2)
500    DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
501
502  if (PP.getLangOptions().PascalStrings)
503    DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
504
505  if (PP.getLangOptions().Blocks) {
506    DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
507    DefineBuiltinMacro(Buf, "__BLOCKS__=1");
508  }
509
510  if (PP.getLangOptions().CPlusPlus) {
511    DefineBuiltinMacro(Buf, "__DEPRECATED=1");
512    DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
513    DefineBuiltinMacro(Buf, "__GNUG__=4");
514    DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
515    DefineBuiltinMacro(Buf, "__cplusplus=1");
516    DefineBuiltinMacro(Buf, "__private_extern__=extern");
517  }
518
519  // Filter out some microsoft extensions when trying to parse in ms-compat
520  // mode.
521  if (PP.getLangOptions().Microsoft) {
522    DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
523    DefineBuiltinMacro(Buf, "__int8=char");
524    DefineBuiltinMacro(Buf, "__int16=short");
525    DefineBuiltinMacro(Buf, "__int32=int");
526    DefineBuiltinMacro(Buf, "__int64=long long");
527  }
528
529
530  // Initialize target-specific preprocessor defines.
531  const TargetInfo &TI = PP.getTargetInfo();
532
533  // Define type sizing macros based on the target properties.
534  assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
535  DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
536  DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127");
537
538  assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far");
539  DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647");
540  DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int");
541  DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
542
543  assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far");
544  DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767");
545
546  if (TI.getIntWidth() == 32)
547    DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647");
548  else if (TI.getIntWidth() == 16)
549    DefineBuiltinMacro(Buf, "__INT_MAX__=32767");
550  else
551    assert(0 && "Unknown integer size");
552
553  if (TI.getLongLongWidth() == 64)
554    DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL");
555  else if (TI.getLongLongWidth() == 32)
556    DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=2147483647L");
557
558  if (TI.getLongWidth() == 32)
559    DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L");
560  else if (TI.getLongWidth() == 64)
561    DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L");
562  else if (TI.getLongWidth() == 16)
563    DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L");
564  else
565    assert(0 && "Unknown long size");
566  char MacroBuf[60];
567  sprintf(MacroBuf, "__INTMAX_MAX__=%lld",
568          (TI.getIntMaxType() == TargetInfo::UnsignedLongLong?
569           (1LL << (TI.getLongLongWidth() - 1)) :
570           ((1LL << (TI.getLongLongWidth() - 2)) - 1)));
571  DefineBuiltinMacro(Buf, MacroBuf);
572
573  if (TI.getIntMaxType() == TargetInfo::UnsignedLongLong)
574    DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long long int");
575  else if (TI.getIntMaxType() == TargetInfo::SignedLongLong)
576    DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int");
577  else if (TI.getIntMaxType() == TargetInfo::UnsignedLong)
578    DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long int");
579  else if (TI.getIntMaxType() == TargetInfo::SignedLong)
580    DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int");
581  else if (TI.getIntMaxType() == TargetInfo::UnsignedInt)
582    DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned int");
583  else
584    DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=int");
585
586  if (TI.getUIntMaxType() == TargetInfo::UnsignedLongLong)
587    DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long long int");
588  else if (TI.getUIntMaxType() == TargetInfo::SignedLongLong)
589    DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long int");
590  else if (TI.getUIntMaxType() == TargetInfo::UnsignedLong)
591    DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long int");
592  else if (TI.getUIntMaxType() == TargetInfo::SignedLong)
593    DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long int");
594  else if (TI.getUIntMaxType() == TargetInfo::UnsignedInt)
595    DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned int");
596  else
597    DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=int");
598
599  if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLongLong)
600    DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long long int");
601  else if (TI.getPtrDiffType(0) == TargetInfo::SignedLongLong)
602    DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long long int");
603  else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLong)
604    DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long int");
605  else if (TI.getPtrDiffType(0) == TargetInfo::SignedLong)
606    DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int");
607  else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedInt)
608    DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned int");
609  else
610    DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int");
611
612  if (TI.getSizeType() == TargetInfo::UnsignedLongLong)
613    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long long int");
614  else if (TI.getSizeType() == TargetInfo::SignedLongLong)
615    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long long int");
616  else if (TI.getSizeType() == TargetInfo::UnsignedLong)
617    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long int");
618  else if (TI.getSizeType() == TargetInfo::SignedLong)
619    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long int");
620  else if (TI.getSizeType() == TargetInfo::UnsignedInt)
621    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned int");
622  else if (TI.getSizeType() == TargetInfo::SignedInt)
623    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=int");
624  else
625    DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned short");
626
627  DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
628  DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
629  DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
630
631
632  // Add __builtin_va_list typedef.
633  {
634    const char *VAList = TI.getVAListDeclaration();
635    Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
636    Buf.push_back('\n');
637  }
638
639  if (const char *Prefix = TI.getUserLabelPrefix()) {
640    sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
641    DefineBuiltinMacro(Buf, MacroBuf);
642  }
643
644  // Build configuration options.  FIXME: these should be controlled by
645  // command line options or something.
646  DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
647  DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
648  DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
649  DefineBuiltinMacro(Buf, "__PIC__=1");
650
651  // Macros to control C99 numerics and <float.h>
652  DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
653  DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
654  sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
655          PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
656  DefineBuiltinMacro(Buf, MacroBuf);
657
658  // Get other target #defines.
659  TI.getTargetDefines(Buf);
660
661  // FIXME: Should emit a #line directive here.
662}
663
664
665/// EnterMainSourceFile - Enter the specified FileID as the main source file,
666/// which implicitly adds the builtin defines etc.
667void Preprocessor::EnterMainSourceFile() {
668
669  FileID MainFileID = SourceMgr.getMainFileID();
670
671  // Enter the main file source buffer.
672  EnterSourceFile(MainFileID, 0);
673
674  // Tell the header info that the main file was entered.  If the file is later
675  // #imported, it won't be re-entered.
676  if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
677    HeaderInfo.IncrementIncludeCount(FE);
678
679  std::vector<char> PrologFile;
680  PrologFile.reserve(4080);
681
682  // Install things like __POWERPC__, __GNUC__, etc into the macro table.
683  InitializePredefinedMacros(*this, PrologFile);
684
685  // Add on the predefines from the driver.
686  PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
687
688  // Memory buffer must end with a null byte!
689  PrologFile.push_back(0);
690
691  // Now that we have emitted the predefined macros, #includes, etc into
692  // PrologFile, preprocess it to populate the initial preprocessor state.
693  llvm::MemoryBuffer *SB =
694    llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
695                                         "<predefines>");
696  assert(SB && "Cannot fail to create predefined source buffer");
697  FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
698  assert(!FID.isInvalid() && "Could not create FileID for predefines?");
699
700  // Start parsing the predefines.
701  EnterSourceFile(FID, 0);
702}
703
704
705//===----------------------------------------------------------------------===//
706// Lexer Event Handling.
707//===----------------------------------------------------------------------===//
708
709/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
710/// identifier information for the token and install it into the token.
711IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
712                                                   const char *BufPtr) {
713  assert(Identifier.is(tok::identifier) && "Not an identifier!");
714  assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
715
716  // Look up this token, see if it is a macro, or if it is a language keyword.
717  IdentifierInfo *II;
718  if (BufPtr && !Identifier.needsCleaning()) {
719    // No cleaning needed, just use the characters from the lexed buffer.
720    II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
721  } else {
722    // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
723    llvm::SmallVector<char, 64> IdentifierBuffer;
724    IdentifierBuffer.resize(Identifier.getLength());
725    const char *TmpBuf = &IdentifierBuffer[0];
726    unsigned Size = getSpelling(Identifier, TmpBuf);
727    II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
728  }
729  Identifier.setIdentifierInfo(II);
730  return II;
731}
732
733
734/// HandleIdentifier - This callback is invoked when the lexer reads an
735/// identifier.  This callback looks up the identifier in the map and/or
736/// potentially macro expands it or turns it into a named token (like 'for').
737///
738/// Note that callers of this method are guarded by checking the
739/// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
740/// IdentifierInfo methods that compute these properties will need to change to
741/// match.
742void Preprocessor::HandleIdentifier(Token &Identifier) {
743  assert(Identifier.getIdentifierInfo() &&
744         "Can't handle identifiers without identifier info!");
745
746  IdentifierInfo &II = *Identifier.getIdentifierInfo();
747
748  // If this identifier was poisoned, and if it was not produced from a macro
749  // expansion, emit an error.
750  if (II.isPoisoned() && CurPPLexer) {
751    if (&II != Ident__VA_ARGS__)   // We warn about __VA_ARGS__ with poisoning.
752      Diag(Identifier, diag::err_pp_used_poisoned_id);
753    else
754      Diag(Identifier, diag::ext_pp_bad_vaargs_use);
755  }
756
757  // If this is a macro to be expanded, do it.
758  if (MacroInfo *MI = getMacroInfo(&II)) {
759    if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
760      if (MI->isEnabled()) {
761        if (!HandleMacroExpandedIdentifier(Identifier, MI))
762          return;
763      } else {
764        // C99 6.10.3.4p2 says that a disabled macro may never again be
765        // expanded, even if it's in a context where it could be expanded in the
766        // future.
767        Identifier.setFlag(Token::DisableExpand);
768      }
769    }
770  }
771
772  // C++ 2.11p2: If this is an alternative representation of a C++ operator,
773  // then we act as if it is the actual operator and not the textual
774  // representation of it.
775  if (II.isCPlusPlusOperatorKeyword())
776    Identifier.setIdentifierInfo(0);
777
778  // If this is an extension token, diagnose its use.
779  // We avoid diagnosing tokens that originate from macro definitions.
780  if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
781    Diag(Identifier, diag::ext_token_used);
782}
783