Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DependencyDirectivesSourceMinimizer.cpp -  -------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// \file
10
/// This is the implementation for minimizing header and source files to the
11
/// minimum necessary preprocessor directives for evaluating includes. It
12
/// reduces the source down to #define, #include, #import, @import, and any
13
/// conditional preprocessor logic that contains one of those.
14
///
15
//===----------------------------------------------------------------------===//
16
17
#include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
18
#include "clang/Basic/CharInfo.h"
19
#include "clang/Basic/Diagnostic.h"
20
#include "clang/Lex/LexDiagnostic.h"
21
#include "llvm/ADT/StringMap.h"
22
#include "llvm/ADT/StringSwitch.h"
23
#include "llvm/Support/MemoryBuffer.h"
24
25
using namespace llvm;
26
using namespace clang;
27
using namespace clang::minimize_source_to_dependency_directives;
28
29
namespace {
30
31
struct Minimizer {
32
  /// Minimized output.
33
  SmallVectorImpl<char> &Out;
34
  /// The known tokens encountered during the minimization.
35
  SmallVectorImpl<Token> &Tokens;
36
37
  Minimizer(SmallVectorImpl<char> &Out, SmallVectorImpl<Token> &Tokens,
38
            StringRef Input, DiagnosticsEngine *Diags,
39
            SourceLocation InputSourceLoc)
40
      : Out(Out), Tokens(Tokens), Input(Input), Diags(Diags),
41
1.63k
        InputSourceLoc(InputSourceLoc) {}
42
43
  /// Lex the provided source and emit the minimized output.
44
  ///
45
  /// \returns True on error.
46
  bool minimize();
47
48
private:
49
  struct IdInfo {
50
    const char *Last;
51
    StringRef Name;
52
  };
53
54
  /// Lex an identifier.
55
  ///
56
  /// \pre First points at a valid identifier head.
57
  LLVM_NODISCARD IdInfo lexIdentifier(const char *First, const char *const End);
58
  LLVM_NODISCARD bool isNextIdentifier(StringRef Id, const char *&First,
59
                                       const char *const End);
60
  LLVM_NODISCARD bool minimizeImpl(const char *First, const char *const End);
61
  LLVM_NODISCARD bool lexPPLine(const char *&First, const char *const End);
62
  LLVM_NODISCARD bool lexAt(const char *&First, const char *const End);
63
  LLVM_NODISCARD bool lexModule(const char *&First, const char *const End);
64
  LLVM_NODISCARD bool lexDefine(const char *&First, const char *const End);
65
  LLVM_NODISCARD bool lexPragma(const char *&First, const char *const End);
66
  LLVM_NODISCARD bool lexEndif(const char *&First, const char *const End);
67
  LLVM_NODISCARD bool lexDefault(TokenKind Kind, StringRef Directive,
68
                                 const char *&First, const char *const End);
69
185k
  Token &makeToken(TokenKind K) {
70
185k
    Tokens.emplace_back(K, Out.size());
71
185k
    return Tokens.back();
72
185k
  }
73
14.6k
  void popToken() {
74
14.6k
    Out.resize(Tokens.back().Offset);
75
14.6k
    Tokens.pop_back();
76
14.6k
  }
77
84.6k
  TokenKind top() const { return Tokens.empty() ? 
pp_none0
: Tokens.back().K; }
78
79
582k
  Minimizer &put(char Byte) {
80
582k
    Out.push_back(Byte);
81
582k
    return *this;
82
582k
  }
83
300k
  Minimizer &append(StringRef S) { return append(S.begin(), S.end()); }
84
858k
  Minimizer &append(const char *First, const char *Last) {
85
858k
    Out.append(First, Last);
86
858k
    return *this;
87
858k
  }
88
89
  void printToNewline(const char *&First, const char *const End);
90
  void printAdjacentModuleNameParts(const char *&First, const char *const End);
91
  LLVM_NODISCARD bool printAtImportBody(const char *&First,
92
                                        const char *const End);
93
  void printDirectiveBody(const char *&First, const char *const End);
94
  void printAdjacentMacroArgs(const char *&First, const char *const End);
95
  LLVM_NODISCARD bool printMacroArgs(const char *&First, const char *const End);
96
97
  /// Reports a diagnostic if the diagnostic engine is provided. Always returns
98
  /// true at the end.
99
  bool reportError(const char *CurPtr, unsigned Err);
100
101
  StringMap<char> SplitIds;
102
  StringRef Input;
103
  DiagnosticsEngine *Diags;
104
  SourceLocation InputSourceLoc;
105
};
106
107
} // end anonymous namespace
108
109
8
bool Minimizer::reportError(const char *CurPtr, unsigned Err) {
110
8
  if (!Diags)
111
5
    return true;
112
3
  assert(CurPtr >= Input.data() && "invalid buffer ptr");
113
0
  Diags->Report(InputSourceLoc.getLocWithOffset(CurPtr - Input.data()), Err);
114
3
  return true;
115
8
}
116
117
2.09M
static void skipOverSpaces(const char *&First, const char *const End) {
118
4.42M
  while (First != End && 
isHorizontalWhitespace(*First)4.42M
)
119
2.32M
    ++First;
120
2.09M
}
121
122
LLVM_NODISCARD static bool isRawStringLiteral(const char *First,
123
12.4k
                                              const char *Current) {
124
12.4k
  assert(First <= Current);
125
126
  // Check if we can even back up.
127
12.4k
  if (*Current != '"' || 
First == Current7.24k
)
128
6.77k
    return false;
129
130
  // Check for an "R".
131
5.67k
  --Current;
132
5.67k
  if (*Current != 'R')
133
5.67k
    return false;
134
5
  if (First == Current || 
!isIdentifierBody(*--Current)2
)
135
3
    return true;
136
137
  // Check for a prefix of "u", "U", or "L".
138
2
  if (*Current == 'u' || 
*Current == 'U'0
||
*Current == 'L'0
)
139
0
    return First == Current || !isIdentifierBody(*--Current);
140
141
  // Check for a prefix of "u8".
142
2
  if (*Current != '8' || 
First == Current0
||
*Current-- != 'u'0
)
143
0
    return false;
144
2
  return First == Current || 
!isIdentifierBody(*--Current)0
;
145
2
}
146
147
3
static void skipRawString(const char *&First, const char *const End) {
148
3
  assert(First[0] == '"');
149
0
  assert(First[-1] == 'R');
150
151
0
  const char *Last = ++First;
152
6
  while (Last != End && *Last != '(')
153
3
    ++Last;
154
3
  if (Last == End) {
155
0
    First = Last; // Hit the end... just give up.
156
0
    return;
157
0
  }
158
159
3
  StringRef Terminator(First, Last - First);
160
3
  for (;;) {
161
    // Move First to just past the next ")".
162
3
    First = Last;
163
46
    while (First != End && *First != ')')
164
43
      ++First;
165
3
    if (First == End)
166
0
      return;
167
3
    ++First;
168
169
    // Look ahead for the terminator sequence.
170
3
    Last = First;
171
6
    while (Last != End && size_t(Last - First) < Terminator.size() &&
172
6
           
Terminator[Last - First] == *Last3
)
173
3
      ++Last;
174
175
    // Check if we hit it (or the end of the file).
176
3
    if (Last == End) {
177
0
      First = Last;
178
0
      return;
179
0
    }
180
3
    if (size_t(Last - First) < Terminator.size())
181
0
      continue;
182
3
    if (*Last != '"')
183
0
      continue;
184
3
    First = Last + 1;
185
3
    return;
186
3
  }
187
3
}
188
189
// Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
190
2.62M
static unsigned isEOL(const char *First, const char *const End) {
191
2.62M
  if (First == End)
192
0
    return 0;
193
2.62M
  if (End - First > 1 && 
isVerticalWhitespace(First[0])2.62M
&&
194
2.62M
      
isVerticalWhitespace(First[1])1.02M
&&
First[0] != First[1]126k
)
195
20
    return 2;
196
2.62M
  return !!isVerticalWhitespace(First[0]);
197
2.62M
}
198
199
12.4k
static void skipString(const char *&First, const char *const End) {
200
12.4k
  assert(*First == '\'' || *First == '"' || *First == '<');
201
12.4k
  const char Terminator = *First == '<' ? 
'>'4.52k
:
*First7.92k
;
202
180k
  for (++First; First != End && 
*First != Terminator180k
;
++First167k
) {
203
    // String and character literals don't extend past the end of the line.
204
167k
    if (isVerticalWhitespace(*First))
205
3
      return;
206
167k
    if (*First != '\\')
207
167k
      continue;
208
    // Skip past backslash to the next character. This ensures that the
209
    // character right after it is skipped as well, which matters if it's
210
    // the terminator.
211
219
    if (++First == End)
212
0
      return;
213
219
    if (!isWhitespace(*First))
214
186
      continue;
215
    // Whitespace after the backslash might indicate a line continuation.
216
33
    const char *FirstAfterBackslashPastSpace = First;
217
33
    skipOverSpaces(FirstAfterBackslashPastSpace, End);
218
33
    if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
219
      // Advance the character pointer to the next line for the next
220
      // iteration.
221
31
      First = FirstAfterBackslashPastSpace + NLSize - 1;
222
31
    }
223
33
  }
224
12.4k
  if (First != End)
225
12.4k
    ++First; // Finish off the string.
226
12.4k
}
227
228
// Returns the length of the skipped newline
229
988k
static unsigned skipNewline(const char *&First, const char *End) {
230
988k
  if (First == End)
231
12
    return 0;
232
988k
  assert(isVerticalWhitespace(*First));
233
0
  unsigned Len = isEOL(First, End);
234
988k
  assert(Len && "expected newline");
235
0
  First += Len;
236
988k
  return Len;
237
988k
}
238
239
487k
static bool wasLineContinuation(const char *First, unsigned EOLLen) {
240
487k
  return *(First - (int)EOLLen - 1) == '\\';
241
487k
}
242
243
40.7k
static void skipToNewlineRaw(const char *&First, const char *const End) {
244
41.1k
  for (;;) {
245
41.1k
    if (First == End)
246
0
      return;
247
248
41.1k
    unsigned Len = isEOL(First, End);
249
41.1k
    if (Len)
250
354
      return;
251
252
1.59M
    
do 40.7k
{
253
1.59M
      if (++First == End)
254
0
        return;
255
1.59M
      Len = isEOL(First, End);
256
1.59M
    } while (!Len);
257
258
40.7k
    if (First[-1] != '\\')
259
40.3k
      return;
260
261
433
    First += Len;
262
    // Keep skipping lines...
263
433
  }
264
40.7k
}
265
266
278k
static const char *findLastNonSpace(const char *First, const char *Last) {
267
278k
  assert(First <= Last);
268
612k
  while (First != Last && 
isHorizontalWhitespace(Last[-1])599k
)
269
334k
    --Last;
270
278k
  return Last;
271
278k
}
272
273
static const char *findFirstTrailingSpace(const char *First,
274
71.6k
                                          const char *Last) {
275
71.6k
  const char *LastNonSpace = findLastNonSpace(First, Last);
276
71.6k
  if (Last == LastNonSpace)
277
1.35k
    return Last;
278
70.2k
  assert(isHorizontalWhitespace(LastNonSpace[0]));
279
0
  return LastNonSpace + 1;
280
71.6k
}
281
282
40.3k
static void skipLineComment(const char *&First, const char *const End) {
283
40.3k
  assert(First[0] == '/' && First[1] == '/');
284
0
  First += 2;
285
40.3k
  skipToNewlineRaw(First, End);
286
40.3k
}
287
288
57.8k
static void skipBlockComment(const char *&First, const char *const End) {
289
57.8k
  assert(First[0] == '/' && First[1] == '*');
290
57.8k
  if (End - First < 4) {
291
0
    First = End;
292
0
    return;
293
0
  }
294
7.21M
  
for (First += 3; 57.8k
First != End;
++First7.15M
)
295
7.21M
    if (First[-1] == '*' && 
First[0] == '/'215k
) {
296
57.8k
      ++First;
297
57.8k
      return;
298
57.8k
    }
299
57.8k
}
300
301
/// \returns True if the current single quotation mark character is a C++ 14
302
/// digit separator.
303
static bool isQuoteCppDigitSeparator(const char *const Start,
304
                                     const char *const Cur,
305
47
                                     const char *const End) {
306
47
  assert(*Cur == '\'' && "expected quotation character");
307
  // skipLine called in places where we don't expect a valid number
308
  // body before `start` on the same line, so always return false at the start.
309
47
  if (Start == Cur)
310
0
    return false;
311
  // The previous character must be a valid PP number character.
312
  // Make sure that the L, u, U, u8 prefixes don't get marked as a
313
  // separator though.
314
47
  char Prev = *(Cur - 1);
315
47
  if (Prev == 'L' || 
Prev == 'U'46
||
Prev == 'u'45
)
316
3
    return false;
317
44
  if (Prev == '8' && 
(Cur - 1 != Start)2
&&
*(Cur - 2) == 'u'2
)
318
1
    return false;
319
43
  if (!isPreprocessingNumberBody(Prev))
320
39
    return false;
321
  // The next character should be a valid identifier body character.
322
4
  return (Cur + 1) < End && isIdentifierBody(*(Cur + 1));
323
43
}
324
325
723k
static void skipLine(const char *&First, const char *const End) {
326
723k
  for (;;) {
327
723k
    assert(First <= End);
328
723k
    if (First == End)
329
1
      return;
330
331
723k
    if (isVerticalWhitespace(*First)) {
332
235k
      skipNewline(First, End);
333
235k
      return;
334
235k
    }
335
487k
    const char *Start = First;
336
27.4M
    while (First != End && 
!isVerticalWhitespace(*First)27.4M
) {
337
      // Iterate over strings correctly to avoid comments and newlines.
338
26.9M
      if (*First == '"' ||
339
26.9M
          
(26.9M
*First == '\''26.9M
&&
!isQuoteCppDigitSeparator(Start, First, End)47
)) {
340
3.85k
        if (isRawStringLiteral(Start, First))
341
3
          skipRawString(First, End);
342
3.84k
        else
343
3.84k
          skipString(First, End);
344
3.85k
        continue;
345
3.85k
      }
346
347
      // Iterate over comments correctly.
348
26.9M
      if (*First != '/' || 
End - First < 217.0k
) {
349
26.9M
        ++First;
350
26.9M
        continue;
351
26.9M
      }
352
353
17.0k
      if (First[1] == '/') {
354
        // "//...".
355
1.18k
        skipLineComment(First, End);
356
1.18k
        continue;
357
1.18k
      }
358
359
15.8k
      if (First[1] != '*') {
360
198
        ++First;
361
198
        continue;
362
198
      }
363
364
      // "/*...*/".
365
15.6k
      skipBlockComment(First, End);
366
15.6k
    }
367
487k
    if (First == End)
368
12
      return;
369
370
    // Skip over the newline.
371
487k
    unsigned Len = skipNewline(First, End);
372
487k
    if (!wasLineContinuation(First, Len)) // Continue past line-continuations.
373
487k
      break;
374
487k
  }
375
723k
}
376
377
static void skipDirective(StringRef Name, const char *&First,
378
388
                          const char *const End) {
379
388
  if (llvm::StringSwitch<bool>(Name)
380
388
          .Case("warning", true)
381
388
          .Case("error", true)
382
388
          .Default(false))
383
    // Do not process quotes or comments.
384
388
    skipToNewlineRaw(First, End);
385
0
  else
386
0
    skipLine(First, End);
387
388
}
388
389
183k
void Minimizer::printToNewline(const char *&First, const char *const End) {
390
243k
  while (First != End && 
!isVerticalWhitespace(*First)243k
) {
391
206k
    const char *Last = First;
392
12.0M
    do {
393
      // Iterate over strings correctly to avoid comments and newlines.
394
12.0M
      if (*Last == '"' || 
*Last == '\''12.0M
||
395
12.0M
          
(12.0M
*Last == '<'12.0M
&&
top() == pp_include8.01k
)) {
396
8.60k
        if (LLVM_UNLIKELY(isRawStringLiteral(First, Last)))
397
0
          skipRawString(Last, End);
398
8.60k
        else
399
8.60k
          skipString(Last, End);
400
8.60k
        continue;
401
8.60k
      }
402
12.0M
      if (*Last != '/' || 
End - Last < 212.3k
) {
403
12.0M
        ++Last;
404
12.0M
        continue; // Gather the rest up to print verbatim.
405
12.0M
      }
406
407
12.3k
      if (Last[1] != '/' && 
Last[1] != '*'12.2k
) {
408
240
        ++Last;
409
240
        continue;
410
240
      }
411
412
      // Deal with "//..." and "/*...*/".
413
12.0k
      append(First, findFirstTrailingSpace(First, Last));
414
12.0k
      First = Last;
415
416
12.0k
      if (Last[1] == '/') {
417
10
        skipLineComment(First, End);
418
10
        return;
419
10
      }
420
421
12.0k
      put(' ');
422
12.0k
      skipBlockComment(First, End);
423
12.0k
      skipOverSpaces(First, End);
424
12.0k
      Last = First;
425
12.0M
    } while (Last != End && 
!isVerticalWhitespace(*Last)12.0M
);
426
427
    // Print out the string.
428
206k
    const char *LastBeforeTrailingSpace = findLastNonSpace(First, Last);
429
206k
    if (Last == End || 
LastBeforeTrailingSpace == First206k
||
430
206k
        
LastBeforeTrailingSpace[-1] != '\\'194k
) {
431
147k
      append(First, LastBeforeTrailingSpace);
432
147k
      First = Last;
433
147k
      skipNewline(First, End);
434
147k
      return;
435
147k
    }
436
437
    // Print up to the backslash, backing up over spaces. Preserve at least one
438
    // space, as the space matters when tokens are separated by a line
439
    // continuation.
440
59.5k
    append(First, findFirstTrailingSpace(
441
59.5k
                      First, LastBeforeTrailingSpace - 1));
442
443
59.5k
    First = Last;
444
59.5k
    skipNewline(First, End);
445
59.5k
    skipOverSpaces(First, End);
446
59.5k
  }
447
183k
}
448
449
1.93M
static void skipWhitespace(const char *&First, const char *const End) {
450
2.02M
  for (;;) {
451
2.02M
    assert(First <= End);
452
0
    skipOverSpaces(First, End);
453
454
2.02M
    if (End - First < 2)
455
2.64k
      return;
456
457
2.01M
    if (First[0] == '\\' && 
isVerticalWhitespace(First[1])58.6k
) {
458
58.6k
      skipNewline(++First, End);
459
58.6k
      continue;
460
58.6k
    }
461
462
    // Check for a non-comment character.
463
1.96M
    if (First[0] != '/')
464
1.89M
      return;
465
466
    // "// ...".
467
69.2k
    if (First[1] == '/') {
468
39.1k
      skipLineComment(First, End);
469
39.1k
      return;
470
39.1k
    }
471
472
    // Cannot be a comment.
473
30.1k
    if (First[1] != '*')
474
0
      return;
475
476
    // "/*...*/".
477
30.1k
    skipBlockComment(First, End);
478
30.1k
  }
479
1.93M
}
480
481
void Minimizer::printAdjacentModuleNameParts(const char *&First,
482
12
                                             const char *const End) {
483
  // Skip over parts of the body.
484
12
  const char *Last = First;
485
12
  do
486
18
    ++Last;
487
18
  while (Last != End && (isIdentifierBody(*Last) || 
*Last == '.'13
));
488
12
  append(First, Last);
489
12
  First = Last;
490
12
}
491
492
11
bool Minimizer::printAtImportBody(const char *&First, const char *const End) {
493
27
  for (;;) {
494
27
    skipWhitespace(First, End);
495
27
    if (First == End)
496
2
      return true;
497
498
25
    if (isVerticalWhitespace(*First)) {
499
4
      skipNewline(First, End);
500
4
      continue;
501
4
    }
502
503
    // Found a semicolon.
504
21
    if (*First == ';') {
505
7
      put(*First++).put('\n');
506
7
      return false;
507
7
    }
508
509
    // Don't handle macro expansions inside @import for now.
510
14
    if (!isIdentifierBody(*First) && 
*First != '.'3
)
511
2
      return true;
512
513
12
    printAdjacentModuleNameParts(First, End);
514
12
  }
515
11
}
516
517
183k
void Minimizer::printDirectiveBody(const char *&First, const char *const End) {
518
183k
  skipWhitespace(First, End); // Skip initial whitespace.
519
183k
  printToNewline(First, End);
520
235k
  while (Out.back() == ' ')
521
51.9k
    Out.pop_back();
522
183k
  put('\n');
523
183k
}
524
525
LLVM_NODISCARD static const char *lexRawIdentifier(const char *First,
526
354k
                                                   const char *const End) {
527
354k
  assert(isIdentifierBody(*First) && "invalid identifer");
528
0
  const char *Last = First + 1;
529
3.69M
  while (Last != End && 
isIdentifierBody(*Last)3.69M
)
530
3.33M
    ++Last;
531
354k
  return Last;
532
354k
}
533
534
LLVM_NODISCARD static const char *
535
354k
getIdentifierContinuation(const char *First, const char *const End) {
536
354k
  if (End - First < 3 || 
First[0] != '\\'353k
||
!isVerticalWhitespace(First[1])6
)
537
354k
    return nullptr;
538
539
6
  ++First;
540
6
  skipNewline(First, End);
541
6
  if (First == End)
542
0
    return nullptr;
543
6
  return isIdentifierBody(First[0]) ? 
First4
:
nullptr2
;
544
6
}
545
546
Minimizer::IdInfo Minimizer::lexIdentifier(const char *First,
547
354k
                                           const char *const End) {
548
354k
  const char *Last = lexRawIdentifier(First, End);
549
354k
  const char *Next = getIdentifierContinuation(Last, End);
550
354k
  if (LLVM_LIKELY(!Next))
551
354k
    return IdInfo{Last, StringRef(First, Last - First)};
552
553
  // Slow path, where identifiers are split over lines.
554
6
  SmallVector<char, 64> Id(First, Last);
555
10
  while (Next) {
556
4
    Last = lexRawIdentifier(Next, End);
557
4
    Id.append(Next, Last);
558
4
    Next = getIdentifierContinuation(Last, End);
559
4
  }
560
6
  return IdInfo{
561
6
      Last,
562
6
      SplitIds.try_emplace(StringRef(Id.begin(), Id.size()), 0).first->first()};
563
354k
}
564
565
void Minimizer::printAdjacentMacroArgs(const char *&First,
566
339k
                                       const char *const End) {
567
  // Skip over parts of the body.
568
339k
  const char *Last = First;
569
339k
  do
570
1.33M
    ++Last;
571
1.33M
  while (Last != End &&
572
1.33M
         (isIdentifierBody(*Last) || 
*Last == '.'611k
||
*Last == ','610k
));
573
339k
  append(First, Last);
574
339k
  First = Last;
575
339k
}
576
577
71.2k
bool Minimizer::printMacroArgs(const char *&First, const char *const End) {
578
71.2k
  assert(*First == '(');
579
0
  put(*First++);
580
410k
  for (;;) {
581
410k
    skipWhitespace(First, End);
582
410k
    if (First == End)
583
1
      return true;
584
585
410k
    if (*First == ')') {
586
71.2k
      put(*First++);
587
71.2k
      return false;
588
71.2k
    }
589
590
    // This is intentionally fairly liberal.
591
339k
    if (!(isIdentifierBody(*First) || 
*First == '.'644
||
*First == ','16
))
592
2
      return true;
593
594
339k
    printAdjacentMacroArgs(First, End);
595
339k
  }
596
71.2k
}
597
598
/// Looks for an identifier starting from Last.
599
///
600
/// Updates "First" to just past the next identifier, if any.  Returns true iff
601
/// the identifier matches "Id".
602
bool Minimizer::isNextIdentifier(StringRef Id, const char *&First,
603
88
                                 const char *const End) {
604
88
  skipWhitespace(First, End);
605
88
  if (First == End || !isIdentifierHead(*First))
606
2
    return false;
607
608
86
  IdInfo FoundId = lexIdentifier(First, End);
609
86
  First = FoundId.Last;
610
86
  return FoundId.Name == Id;
611
88
}
612
613
61
bool Minimizer::lexAt(const char *&First, const char *const End) {
614
  // Handle "@import".
615
61
  const char *ImportLoc = First++;
616
61
  if (!isNextIdentifier("import", First, End)) {
617
50
    skipLine(First, End);
618
50
    return false;
619
50
  }
620
11
  makeToken(decl_at_import);
621
11
  append("@import ");
622
11
  if (printAtImportBody(First, End))
623
4
    return reportError(
624
4
        ImportLoc, diag::err_dep_source_minimizer_missing_sema_after_at_import);
625
7
  skipWhitespace(First, End);
626
7
  if (First == End)
627
2
    return false;
628
5
  if (!isVerticalWhitespace(*First))
629
1
    return reportError(
630
1
        ImportLoc, diag::err_dep_source_minimizer_unexpected_tokens_at_import);
631
4
  skipNewline(First, End);
632
4
  return false;
633
5
}
634
635
39.1k
bool Minimizer::lexModule(const char *&First, const char *const End) {
636
39.1k
  IdInfo Id = lexIdentifier(First, End);
637
39.1k
  First = Id.Last;
638
39.1k
  bool Export = false;
639
39.1k
  if (Id.Name == "export") {
640
4
    Export = true;
641
4
    skipWhitespace(First, End);
642
4
    if (!isIdentifierBody(*First)) {
643
0
      skipLine(First, End);
644
0
      return false;
645
0
    }
646
4
    Id = lexIdentifier(First, End);
647
4
    First = Id.Last;
648
4
  }
649
650
39.1k
  if (Id.Name != "module" && 
Id.Name != "import"39.1k
) {
651
39.0k
    skipLine(First, End);
652
39.0k
    return false;
653
39.0k
  }
654
655
16
  skipWhitespace(First, End);
656
657
  // Ignore this as a module directive if the next character can't be part of
658
  // an import.
659
660
16
  switch (*First) {
661
1
  case ':':
662
2
  case '<':
663
2
  case '"':
664
2
    break;
665
14
  default:
666
14
    if (!isIdentifierBody(*First)) {
667
6
      skipLine(First, End);
668
6
      return false;
669
6
    }
670
16
  }
671
672
10
  if (Export) {
673
3
    makeToken(cxx_export_decl);
674
3
    append("export ");
675
3
  }
676
677
10
  if (Id.Name == "module")
678
2
    makeToken(cxx_module_decl);
679
8
  else
680
8
    makeToken(cxx_import_decl);
681
10
  append(Id.Name);
682
10
  append(" ");
683
10
  printToNewline(First, End);
684
10
  append("\n");
685
10
  return false;
686
16
}
687
688
116k
bool Minimizer::lexDefine(const char *&First, const char *const End) {
689
116k
  makeToken(pp_define);
690
116k
  append("#define ");
691
116k
  skipWhitespace(First, End);
692
693
116k
  if (!isIdentifierHead(*First))
694
3
    return reportError(First, diag::err_pp_macro_not_identifier);
695
696
116k
  IdInfo Id = lexIdentifier(First, End);
697
116k
  const char *Last = Id.Last;
698
116k
  append(Id.Name);
699
116k
  if (Last == End)
700
1
    return false;
701
116k
  if (*Last == '(') {
702
71.2k
    size_t Size = Out.size();
703
71.2k
    if (printMacroArgs(Last, End)) {
704
      // Be robust to bad macro arguments, since they can show up in disabled
705
      // code.
706
3
      Out.resize(Size);
707
3
      append("(/* invalid */\n");
708
3
      skipLine(Last, End);
709
3
      return false;
710
3
    }
711
71.2k
  }
712
116k
  skipWhitespace(Last, End);
713
116k
  if (Last == End)
714
3
    return false;
715
116k
  if (!isVerticalWhitespace(*Last))
716
111k
    put(' ');
717
116k
  printDirectiveBody(Last, End);
718
116k
  First = Last;
719
116k
  return false;
720
116k
}
721
722
2.55k
bool Minimizer::lexPragma(const char *&First, const char *const End) {
723
  // #pragma.
724
2.55k
  skipWhitespace(First, End);
725
2.55k
  if (First == End || !isIdentifierHead(*First))
726
0
    return false;
727
728
2.55k
  IdInfo FoundId = lexIdentifier(First, End);
729
2.55k
  First = FoundId.Last;
730
2.55k
  if (FoundId.Name == "once") {
731
    // #pragma once
732
4
    skipLine(First, End);
733
4
    makeToken(pp_pragma_once);
734
4
    append("#pragma once\n");
735
4
    return false;
736
4
  }
737
738
2.54k
  if (FoundId.Name != "clang") {
739
2.52k
    skipLine(First, End);
740
2.52k
    return false;
741
2.52k
  }
742
743
  // #pragma clang.
744
23
  if (!isNextIdentifier("module", First, End)) {
745
19
    skipLine(First, End);
746
19
    return false;
747
19
  }
748
749
  // #pragma clang module.
750
4
  if (!isNextIdentifier("import", First, End)) {
751
2
    skipLine(First, End);
752
2
    return false;
753
2
  }
754
755
  // #pragma clang module import.
756
2
  makeToken(pp_pragma_import);
757
2
  append("#pragma clang module import ");
758
2
  printDirectiveBody(First, End);
759
2
  return false;
760
4
}
761
762
28.5k
bool Minimizer::lexEndif(const char *&First, const char *const End) {
763
  // Strip out "#else" if it's empty.
764
28.5k
  if (top() == pp_else)
765
5.32k
    popToken();
766
767
  // If "#ifdef" is empty, strip it and skip the "#endif".
768
  //
769
  // FIXME: Once/if Clang starts disallowing __has_include in macro expansions,
770
  // we can skip empty `#if` and `#elif` blocks as well after scanning for a
771
  // literal __has_include in the condition.  Even without that rule we could
772
  // drop the tokens if we scan for identifiers in the condition and find none.
773
28.5k
  if (top() == pp_ifdef || 
top() == pp_ifndef19.5k
) {
774
9.27k
    popToken();
775
9.27k
    skipLine(First, End);
776
9.27k
    return false;
777
9.27k
  }
778
779
19.2k
  return lexDefault(pp_endif, "endif", First, End);
780
28.5k
}
781
782
bool Minimizer::lexDefault(TokenKind Kind, StringRef Directive,
783
66.7k
                           const char *&First, const char *const End) {
784
66.7k
  makeToken(Kind);
785
66.7k
  put('#').append(Directive).put(' ');
786
66.7k
  printDirectiveBody(First, End);
787
66.7k
  return false;
788
66.7k
}
789
790
906k
static bool isStartOfRelevantLine(char First) {
791
906k
  switch (First) {
792
195k
  case '#':
793
195k
  case '@':
794
222k
  case 'i':
795
229k
  case 'e':
796
234k
  case 'm':
797
234k
    return true;
798
906k
  }
799
672k
  return false;
800
906k
}
801
802
906k
bool Minimizer::lexPPLine(const char *&First, const char *const End) {
803
906k
  assert(First != End);
804
805
0
  skipWhitespace(First, End);
806
906k
  assert(First <= End);
807
906k
  if (First == End)
808
3
    return false;
809
810
906k
  if (!isStartOfRelevantLine(*First)) {
811
672k
    skipLine(First, End);
812
672k
    assert(First <= End);
813
0
    return false;
814
672k
  }
815
816
  // Handle "@import".
817
234k
  if (*First == '@')
818
61
    return lexAt(First, End);
819
820
234k
  if (*First == 'i' || 
*First == 'e'207k
||
*First == 'm'201k
)
821
39.1k
    return lexModule(First, End);
822
823
  // Handle preprocessing directives.
824
195k
  ++First; // Skip over '#'.
825
195k
  skipWhitespace(First, End);
826
827
195k
  if (First == End)
828
0
    return reportError(First, diag::err_pp_expected_eol);
829
830
195k
  if (!isIdentifierHead(*First)) {
831
0
    skipLine(First, End);
832
0
    return false;
833
0
  }
834
835
  // Figure out the token.
836
195k
  IdInfo Id = lexIdentifier(First, End);
837
195k
  First = Id.Last;
838
195k
  auto Kind = llvm::StringSwitch<TokenKind>(Id.Name)
839
195k
                  .Case("include", pp_include)
840
195k
                  .Case("__include_macros", pp___include_macros)
841
195k
                  .Case("define", pp_define)
842
195k
                  .Case("undef", pp_undef)
843
195k
                  .Case("import", pp_import)
844
195k
                  .Case("include_next", pp_include_next)
845
195k
                  .Case("if", pp_if)
846
195k
                  .Case("ifdef", pp_ifdef)
847
195k
                  .Case("ifndef", pp_ifndef)
848
195k
                  .Case("elif", pp_elif)
849
195k
                  .Case("elifdef", pp_elifdef)
850
195k
                  .Case("elifndef", pp_elifndef)
851
195k
                  .Case("else", pp_else)
852
195k
                  .Case("endif", pp_endif)
853
195k
                  .Case("pragma", pp_pragma_import)
854
195k
                  .Default(pp_none);
855
195k
  if (Kind == pp_none) {
856
388
    skipDirective(Id.Name, First, End);
857
388
    return false;
858
388
  }
859
860
195k
  if (Kind == pp_endif)
861
28.5k
    return lexEndif(First, End);
862
863
166k
  if (Kind == pp_define)
864
116k
    return lexDefine(First, End);
865
866
50.0k
  if (Kind == pp_pragma_import)
867
2.55k
    return lexPragma(First, End);
868
869
  // Everything else.
870
47.4k
  return lexDefault(Kind, Id.Name, First, End);
871
50.0k
}
872
873
1.63k
static void skipUTF8ByteOrderMark(const char *&First, const char *const End) {
874
1.63k
  if ((End - First) >= 3 && 
First[0] == '\xef'1.63k
&&
First[1] == '\xbb'1
&&
875
1.63k
      
First[2] == '\xbf'1
)
876
1
    First += 3;
877
1.63k
}
878
879
1.63k
bool Minimizer::minimizeImpl(const char *First, const char *const End) {
880
1.63k
  skipUTF8ByteOrderMark(First, End);
881
908k
  while (First != End)
882
906k
    if (lexPPLine(First, End))
883
8
      return true;
884
1.63k
  return false;
885
1.63k
}
886
887
1.63k
bool Minimizer::minimize() {
888
1.63k
  bool Error = minimizeImpl(Input.begin(), Input.end());
889
890
1.63k
  if (!Error) {
891
    // Add a trailing newline and an EOF on success.
892
1.62k
    if (!Out.empty() && 
Out.back() != '\n'1.58k
)
893
4
      Out.push_back('\n');
894
1.62k
    makeToken(pp_eof);
895
1.62k
  }
896
897
  // Null-terminate the output. This way the memory buffer that's passed to
898
  // Clang will not have to worry about the terminating '\0'.
899
1.63k
  Out.push_back(0);
900
1.63k
  Out.pop_back();
901
1.63k
  return Error;
902
1.63k
}
903
904
bool clang::minimize_source_to_dependency_directives::computeSkippedRanges(
905
1.53k
    ArrayRef<Token> Input, llvm::SmallVectorImpl<SkippedRange> &Range) {
906
1.53k
  struct Directive {
907
1.53k
    enum DirectiveKind {
908
1.53k
      If,  // if/ifdef/ifndef
909
1.53k
      Else // elif/elifdef/elifndef, else
910
1.53k
    };
911
1.53k
    int Offset;
912
1.53k
    DirectiveKind Kind;
913
1.53k
  };
914
1.53k
  llvm::SmallVector<Directive, 32> Offsets;
915
170k
  for (const Token &T : Input) {
916
170k
    switch (T.K) {
917
7.64k
    case pp_if:
918
11.8k
    case pp_ifdef:
919
19.2k
    case pp_ifndef:
920
19.2k
      Offsets.push_back({T.Offset, Directive::If});
921
19.2k
      break;
922
923
853
    case pp_elif:
924
854
    case pp_elifdef:
925
855
    case pp_elifndef:
926
7.15k
    case pp_else: {
927
7.15k
      if (Offsets.empty())
928
0
        return true;
929
7.15k
      int PreviousOffset = Offsets.back().Offset;
930
7.15k
      Range.push_back({PreviousOffset, T.Offset - PreviousOffset});
931
7.15k
      Offsets.push_back({T.Offset, Directive::Else});
932
7.15k
      break;
933
7.15k
    }
934
935
19.2k
    case pp_endif: {
936
19.2k
      if (Offsets.empty())
937
0
        return true;
938
19.2k
      int PreviousOffset = Offsets.back().Offset;
939
19.2k
      Range.push_back({PreviousOffset, T.Offset - PreviousOffset});
940
26.4k
      do {
941
26.4k
        Directive::DirectiveKind Kind = Offsets.pop_back_val().Kind;
942
26.4k
        if (Kind == Directive::If)
943
19.2k
          break;
944
26.4k
      } while (
!Offsets.empty()7.15k
);
945
0
      break;
946
19.2k
    }
947
124k
    default:
948
124k
      break;
949
170k
    }
950
170k
  }
951
1.53k
  return false;
952
1.53k
}
953
954
bool clang::minimizeSourceToDependencyDirectives(
955
    StringRef Input, SmallVectorImpl<char> &Output,
956
    SmallVectorImpl<Token> &Tokens, DiagnosticsEngine *Diags,
957
1.63k
    SourceLocation InputSourceLoc) {
958
1.63k
  Output.clear();
959
1.63k
  Tokens.clear();
960
1.63k
  return Minimizer(Output, Tokens, Input, Diags, InputSourceLoc).minimize();
961
1.63k
}