Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
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
// This file implements the inline assembler pieces of the AsmPrinter class.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "llvm/ADT/SmallString.h"
14
#include "llvm/ADT/Twine.h"
15
#include "llvm/CodeGen/AsmPrinter.h"
16
#include "llvm/CodeGen/MachineBasicBlock.h"
17
#include "llvm/CodeGen/MachineFunction.h"
18
#include "llvm/CodeGen/MachineModuleInfo.h"
19
#include "llvm/CodeGen/TargetInstrInfo.h"
20
#include "llvm/CodeGen/TargetRegisterInfo.h"
21
#include "llvm/IR/Constants.h"
22
#include "llvm/IR/DataLayout.h"
23
#include "llvm/IR/InlineAsm.h"
24
#include "llvm/IR/LLVMContext.h"
25
#include "llvm/IR/Module.h"
26
#include "llvm/MC/MCAsmInfo.h"
27
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
28
#include "llvm/MC/MCStreamer.h"
29
#include "llvm/MC/MCSubtargetInfo.h"
30
#include "llvm/MC/MCSymbol.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include "llvm/Support/MemoryBuffer.h"
33
#include "llvm/Support/SourceMgr.h"
34
#include "llvm/Support/TargetRegistry.h"
35
#include "llvm/Support/raw_ostream.h"
36
#include "llvm/Target/TargetMachine.h"
37
using namespace llvm;
38
39
#define DEBUG_TYPE "asm-printer"
40
41
/// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
42
/// inline asm has an error in it.  diagInfo is a pointer to the SrcMgrDiagInfo
43
/// struct above.
44
327
static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
45
327
  AsmPrinter::SrcMgrDiagInfo *DiagInfo =
46
327
      static_cast<AsmPrinter::SrcMgrDiagInfo *>(diagInfo);
47
327
  assert(DiagInfo && "Diagnostic context not passed down?");
48
327
49
327
  // Look up a LocInfo for the buffer this diagnostic is coming from.
50
327
  unsigned BufNum = DiagInfo->SrcMgr.FindBufferContainingLoc(Diag.getLoc());
51
327
  const MDNode *LocInfo = nullptr;
52
327
  if (BufNum > 0 && BufNum <= DiagInfo->LocInfos.size())
53
10
    LocInfo = DiagInfo->LocInfos[BufNum-1];
54
327
55
327
  // If the inline asm had metadata associated with it, pull out a location
56
327
  // cookie corresponding to which line the error occurred on.
57
327
  unsigned LocCookie = 0;
58
327
  if (LocInfo) {
59
10
    unsigned ErrorLine = Diag.getLineNo()-1;
60
10
    if (ErrorLine >= LocInfo->getNumOperands())
61
0
      ErrorLine = 0;
62
10
63
10
    if (LocInfo->getNumOperands() != 0)
64
10
      if (const ConstantInt *CI =
65
10
              mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
66
10
        LocCookie = CI->getZExtValue();
67
10
  }
68
327
69
327
  DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
70
327
}
71
72
unsigned AsmPrinter::addInlineAsmDiagBuffer(StringRef AsmStr,
73
7.12k
                                            const MDNode *LocMDNode) const {
74
7.12k
  if (!DiagInfo) {
75
1.71k
    DiagInfo = make_unique<SrcMgrDiagInfo>();
76
1.71k
77
1.71k
    MCContext &Context = MMI->getContext();
78
1.71k
    Context.setInlineSourceManager(&DiagInfo->SrcMgr);
79
1.71k
80
1.71k
    LLVMContext &LLVMCtx = MMI->getModule()->getContext();
81
1.71k
    if (LLVMCtx.getInlineAsmDiagnosticHandler()) {
82
1.68k
      DiagInfo->DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
83
1.68k
      DiagInfo->DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
84
1.68k
      DiagInfo->SrcMgr.setDiagHandler(srcMgrDiagHandler, DiagInfo.get());
85
1.68k
    }
86
1.71k
  }
87
7.12k
88
7.12k
  SourceMgr &SrcMgr = DiagInfo->SrcMgr;
89
7.12k
90
7.12k
  std::unique_ptr<MemoryBuffer> Buffer;
91
7.12k
  // The inline asm source manager will outlive AsmStr, so make a copy of the
92
7.12k
  // string for SourceMgr to own.
93
7.12k
  Buffer = MemoryBuffer::getMemBufferCopy(AsmStr, "<inline asm>");
94
7.12k
95
7.12k
  // Tell SrcMgr about this buffer, it takes ownership of the buffer.
96
7.12k
  unsigned BufNum = SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
97
7.12k
98
7.12k
  // Store LocMDNode in DiagInfo, using BufNum as an identifier.
99
7.12k
  if (LocMDNode) {
100
2.62k
    DiagInfo->LocInfos.resize(BufNum);
101
2.62k
    DiagInfo->LocInfos[BufNum - 1] = LocMDNode;
102
2.62k
  }
103
7.12k
104
7.12k
  return BufNum;
105
7.12k
}
106
107
108
/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
109
void AsmPrinter::EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
110
                               const MCTargetOptions &MCOptions,
111
                               const MDNode *LocMDNode,
112
9.21k
                               InlineAsm::AsmDialect Dialect) const {
113
9.21k
  assert(!Str.empty() && "Can't emit empty inline asm block");
114
9.21k
115
9.21k
  // Remember if the buffer is nul terminated or not so we can avoid a copy.
116
9.21k
  bool isNullTerminated = Str.back() == 0;
117
9.21k
  if (isNullTerminated)
118
8.10k
    Str = Str.substr(0, Str.size()-1);
119
9.21k
120
9.21k
  // If the output streamer does not have mature MC support or the integrated
121
9.21k
  // assembler has been disabled, just emit the blob textually.
122
9.21k
  // Otherwise parse the asm and emit it via MC support.
123
9.21k
  // This is useful in case the asm parser doesn't handle something but the
124
9.21k
  // system assembler does.
125
9.21k
  const MCAsmInfo *MCAI = TM.getMCAsmInfo();
126
9.21k
  assert(MCAI && "No MCAsmInfo");
127
9.21k
  if (!MCAI->useIntegratedAssembler() &&
128
9.21k
      
!OutStreamer->isIntegratedAssemblerRequired()2.17k
) {
129
2.15k
    emitInlineAsmStart();
130
2.15k
    OutStreamer->EmitRawText(Str);
131
2.15k
    emitInlineAsmEnd(STI, nullptr);
132
2.15k
    return;
133
2.15k
  }
134
7.06k
135
7.06k
  unsigned BufNum = addInlineAsmDiagBuffer(Str, LocMDNode);
136
7.06k
  DiagInfo->SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths);
137
7.06k
138
7.06k
  std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(
139
7.06k
          DiagInfo->SrcMgr, OutContext, *OutStreamer, *MAI, BufNum));
140
7.06k
141
7.06k
  // Do not use assembler-level information for parsing inline assembly.
142
7.06k
  OutStreamer->setUseAssemblerInfoForParsing(false);
143
7.06k
144
7.06k
  // We create a new MCInstrInfo here since we might be at the module level
145
7.06k
  // and not have a MachineFunction to initialize the TargetInstrInfo from and
146
7.06k
  // we only need MCInstrInfo for asm parsing. We create one unconditionally
147
7.06k
  // because it's not subtarget dependent.
148
7.06k
  std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
149
7.06k
  std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
150
7.06k
      STI, *Parser, *MII, MCOptions));
151
7.06k
  if (!TAP)
152
0
    report_fatal_error("Inline asm not supported by this streamer because"
153
0
                       " we don't have an asm parser for this target\n");
154
7.06k
  Parser->setAssemblerDialect(Dialect);
155
7.06k
  Parser->setTargetParser(*TAP.get());
156
7.06k
  // Enable lexing Masm binary and hex integer literals in intel inline
157
7.06k
  // assembly.
158
7.06k
  if (Dialect == InlineAsm::AD_Intel)
159
21
    Parser->getLexer().setLexMasmIntegers(true);
160
7.06k
161
7.06k
  emitInlineAsmStart();
162
7.06k
  // Don't implicitly switch to the text section before the asm.
163
7.06k
  int Res = Parser->Run(/*NoInitialTextSection*/ true,
164
7.06k
                        /*NoFinalize*/ true);
165
7.06k
  emitInlineAsmEnd(STI, &TAP->getSTI());
166
7.06k
167
7.06k
  if (Res && 
!DiagInfo->DiagHandler43
)
168
0
    report_fatal_error("Error parsing inline asm\n");
169
7.06k
}
170
171
static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
172
                               MachineModuleInfo *MMI, AsmPrinter *AP,
173
31
                               unsigned LocCookie, raw_ostream &OS) {
174
31
  // Switch to the inline assembly variant.
175
31
  OS << "\t.intel_syntax\n\t";
176
31
177
31
  const char *LastEmitted = AsmStr; // One past the last character emitted.
178
31
  unsigned NumOperands = MI->getNumOperands();
179
31
180
196
  while (*LastEmitted) {
181
165
    switch (*LastEmitted) {
182
165
    default: {
183
90
      // Not a special case, emit the string section literally.
184
90
      const char *LiteralEnd = LastEmitted+1;
185
914
      while (*LiteralEnd && 
*LiteralEnd != '{'889
&&
*LiteralEnd != '|'889
&&
186
914
             
*LiteralEnd != '}'889
&&
*LiteralEnd != '$'888
&&
*LiteralEnd != '\n'853
)
187
824
        ++LiteralEnd;
188
90
189
90
      OS.write(LastEmitted, LiteralEnd-LastEmitted);
190
90
      LastEmitted = LiteralEnd;
191
90
      break;
192
165
    }
193
165
    case '\n':
194
40
      ++LastEmitted;   // Consume newline character.
195
40
      OS << '\n';      // Indent code with newline.
196
40
      break;
197
165
    case '$': {
198
35
      ++LastEmitted;   // Consume '$' character.
199
35
      bool Done = true;
200
35
201
35
      // Handle escapes.
202
35
      switch (*LastEmitted) {
203
35
      
default: Done = false; break32
;
204
35
      case '$':
205
3
        ++LastEmitted;  // Consume second '$' character.
206
3
        break;
207
35
      }
208
35
      if (Done) 
break3
;
209
32
210
32
      // If we have ${:foo}, then this is not a real operand reference, it is a
211
32
      // "magic" string reference, just like in .td files.  Arrange to call
212
32
      // PrintSpecial.
213
32
      if (LastEmitted[0] == '{' && 
LastEmitted[1] == ':'2
) {
214
2
        LastEmitted += 2;
215
2
        const char *StrStart = LastEmitted;
216
2
        const char *StrEnd = strchr(StrStart, '}');
217
2
        if (!StrEnd)
218
0
          report_fatal_error("Unterminated ${:foo} operand in inline asm"
219
0
                             " string: '" + Twine(AsmStr) + "'");
220
2
221
2
        std::string Val(StrStart, StrEnd);
222
2
        AP->PrintSpecial(MI, OS, Val.c_str());
223
2
        LastEmitted = StrEnd+1;
224
2
        break;
225
2
      }
226
30
227
30
      const char *IDStart = LastEmitted;
228
30
      const char *IDEnd = IDStart;
229
60
      while (*IDEnd >= '0' && 
*IDEnd <= '9'32
)
++IDEnd30
;
230
30
231
30
      unsigned Val;
232
30
      if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
233
0
        report_fatal_error("Bad $ operand number in inline asm string: '" +
234
0
                           Twine(AsmStr) + "'");
235
30
      LastEmitted = IDEnd;
236
30
237
30
      if (Val >= NumOperands-1)
238
0
        report_fatal_error("Invalid $ operand number in inline asm string: '" +
239
0
                           Twine(AsmStr) + "'");
240
30
241
30
      // Okay, we finally have a value number.  Ask the target to print this
242
30
      // operand!
243
30
      unsigned OpNo = InlineAsm::MIOp_FirstOperand;
244
30
245
30
      bool Error = false;
246
30
247
30
      // Scan to find the machine operand number for the operand.
248
62
      for (; Val; 
--Val32
) {
249
32
        if (OpNo >= MI->getNumOperands()) 
break0
;
250
32
        unsigned OpFlags = MI->getOperand(OpNo).getImm();
251
32
        OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
252
32
      }
253
30
254
30
      // We may have a location metadata attached to the end of the
255
30
      // instruction, and at no point should see metadata at any
256
30
      // other point while processing. It's an error if so.
257
30
      if (OpNo >= MI->getNumOperands() ||
258
30
          MI->getOperand(OpNo).isMetadata()) {
259
0
        Error = true;
260
30
      } else {
261
30
        unsigned OpFlags = MI->getOperand(OpNo).getImm();
262
30
        ++OpNo;  // Skip over the ID number.
263
30
264
30
        if (InlineAsm::isMemKind(OpFlags)) {
265
27
          Error = AP->PrintAsmMemoryOperand(MI, OpNo, /*Modifier*/ nullptr, OS);
266
27
        } else {
267
3
          Error = AP->PrintAsmOperand(MI, OpNo, /*Modifier*/ nullptr, OS);
268
3
        }
269
30
      }
270
30
      if (Error) {
271
0
        std::string msg;
272
0
        raw_string_ostream Msg(msg);
273
0
        Msg << "invalid operand in inline asm: '" << AsmStr << "'";
274
0
        MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
275
0
      }
276
30
      break;
277
30
    }
278
165
    }
279
165
  }
280
31
  OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
281
31
}
282
283
static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
284
                                MachineModuleInfo *MMI, int AsmPrinterVariant,
285
                                AsmPrinter *AP, unsigned LocCookie,
286
8.07k
                                raw_ostream &OS) {
287
8.07k
  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
288
8.07k
  const char *LastEmitted = AsmStr; // One past the last character emitted.
289
8.07k
  unsigned NumOperands = MI->getNumOperands();
290
8.07k
291
8.07k
  OS << '\t';
292
8.07k
293
28.4k
  while (*LastEmitted) {
294
20.3k
    switch (*LastEmitted) {
295
20.3k
    default: {
296
12.9k
      // Not a special case, emit the string section literally.
297
12.9k
      const char *LiteralEnd = LastEmitted+1;
298
74.9k
      while (*LiteralEnd && 
*LiteralEnd != '{'69.2k
&&
*LiteralEnd != '|'69.1k
&&
299
74.9k
             
*LiteralEnd != '}'69.1k
&&
*LiteralEnd != '$'69.1k
&&
*LiteralEnd != '\n'63.4k
)
300
62.0k
        ++LiteralEnd;
301
12.9k
      if (CurVariant == -1 || 
CurVariant == AsmPrinterVariant15
)
302
12.9k
        OS.write(LastEmitted, LiteralEnd-LastEmitted);
303
12.9k
      LastEmitted = LiteralEnd;
304
12.9k
      break;
305
20.3k
    }
306
20.3k
    case '\n':
307
1.64k
      ++LastEmitted;   // Consume newline character.
308
1.64k
      OS << '\n';      // Indent code with newline.
309
1.64k
      break;
310
20.3k
    case '$': {
311
5.74k
      ++LastEmitted;   // Consume '$' character.
312
5.74k
      bool Done = true;
313
5.74k
314
5.74k
      // Handle escapes.
315
5.74k
      switch (*LastEmitted) {
316
5.74k
      
default: Done = false; break4.99k
;
317
5.74k
      case '$':     // $$ -> $
318
715
        if (CurVariant == -1 || 
CurVariant == AsmPrinterVariant0
)
319
715
          OS << '$';
320
715
        ++LastEmitted;  // Consume second '$' character.
321
715
        break;
322
5.74k
      case '(':             // $( -> same as GCC's { character.
323
6
        ++LastEmitted;      // Consume '(' character.
324
6
        if (CurVariant != -1)
325
0
          report_fatal_error("Nested variants found in inline asm string: '" +
326
0
                             Twine(AsmStr) + "'");
327
6
        CurVariant = 0;     // We're in the first variant now.
328
6
        break;
329
22
      case '|':
330
22
        ++LastEmitted;  // consume '|' character.
331
22
        if (CurVariant == -1)
332
16
          OS << '|';       // this is gcc's behavior for | outside a variant
333
6
        else
334
6
          ++CurVariant;   // We're in the next variant.
335
22
        break;
336
6
      case ')':         // $) -> same as GCC's } char.
337
6
        ++LastEmitted;  // consume ')' character.
338
6
        if (CurVariant == -1)
339
0
          OS << '}';     // this is gcc's behavior for } outside a variant
340
6
        else
341
6
          CurVariant = -1;
342
6
        break;
343
5.74k
      }
344
5.74k
      if (Done) 
break749
;
345
4.99k
346
4.99k
      bool HasCurlyBraces = false;
347
4.99k
      if (*LastEmitted == '{') {     // ${variable}
348
451
        ++LastEmitted;               // Consume '{' character.
349
451
        HasCurlyBraces = true;
350
451
      }
351
4.99k
352
4.99k
      // If we have ${:foo}, then this is not a real operand reference, it is a
353
4.99k
      // "magic" string reference, just like in .td files.  Arrange to call
354
4.99k
      // PrintSpecial.
355
4.99k
      if (HasCurlyBraces && 
*LastEmitted == ':'451
) {
356
4
        ++LastEmitted;
357
4
        const char *StrStart = LastEmitted;
358
4
        const char *StrEnd = strchr(StrStart, '}');
359
4
        if (!StrEnd)
360
0
          report_fatal_error("Unterminated ${:foo} operand in inline asm"
361
0
                             " string: '" + Twine(AsmStr) + "'");
362
4
363
4
        std::string Val(StrStart, StrEnd);
364
4
        AP->PrintSpecial(MI, OS, Val.c_str());
365
4
        LastEmitted = StrEnd+1;
366
4
        break;
367
4
      }
368
4.98k
369
4.98k
      const char *IDStart = LastEmitted;
370
4.98k
      const char *IDEnd = IDStart;
371
9.98k
      while (*IDEnd >= '0' && 
*IDEnd <= '9'5.56k
)
++IDEnd5.00k
;
372
4.98k
373
4.98k
      unsigned Val;
374
4.98k
      if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
375
0
        report_fatal_error("Bad $ operand number in inline asm string: '" +
376
0
                           Twine(AsmStr) + "'");
377
4.98k
      LastEmitted = IDEnd;
378
4.98k
379
4.98k
      char Modifier[2] = { 0, 0 };
380
4.98k
381
4.98k
      if (HasCurlyBraces) {
382
447
        // If we have curly braces, check for a modifier character.  This
383
447
        // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
384
447
        if (*LastEmitted == ':') {
385
437
          ++LastEmitted;    // Consume ':' character.
386
437
          if (*LastEmitted == 0)
387
0
            report_fatal_error("Bad ${:} expression in inline asm string: '" +
388
0
                               Twine(AsmStr) + "'");
389
437
390
437
          Modifier[0] = *LastEmitted;
391
437
          ++LastEmitted;    // Consume modifier character.
392
437
        }
393
447
394
447
        if (*LastEmitted != '}')
395
0
          report_fatal_error("Bad ${} expression in inline asm string: '" +
396
0
                             Twine(AsmStr) + "'");
397
447
        ++LastEmitted;    // Consume '}' character.
398
447
      }
399
4.98k
400
4.98k
      if (Val >= NumOperands-1)
401
0
        report_fatal_error("Invalid $ operand number in inline asm string: '" +
402
0
                           Twine(AsmStr) + "'");
403
4.98k
404
4.98k
      // Okay, we finally have a value number.  Ask the target to print this
405
4.98k
      // operand!
406
4.98k
      if (CurVariant == -1 || 
CurVariant == AsmPrinterVariant4
) {
407
4.98k
        unsigned OpNo = InlineAsm::MIOp_FirstOperand;
408
4.98k
409
4.98k
        bool Error = false;
410
4.98k
411
4.98k
        // Scan to find the machine operand number for the operand.
412
8.73k
        for (; Val; 
--Val3.74k
) {
413
3.74k
          if (OpNo >= MI->getNumOperands()) 
break0
;
414
3.74k
          unsigned OpFlags = MI->getOperand(OpNo).getImm();
415
3.74k
          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
416
3.74k
        }
417
4.98k
418
4.98k
        // We may have a location metadata attached to the end of the
419
4.98k
        // instruction, and at no point should see metadata at any
420
4.98k
        // other point while processing. It's an error if so.
421
4.98k
        if (OpNo >= MI->getNumOperands() ||
422
4.98k
            MI->getOperand(OpNo).isMetadata()) {
423
0
          Error = true;
424
4.98k
        } else {
425
4.98k
          unsigned OpFlags = MI->getOperand(OpNo).getImm();
426
4.98k
          ++OpNo;  // Skip over the ID number.
427
4.98k
428
4.98k
          // FIXME: Shouldn't arch-independent output template handling go into
429
4.98k
          // PrintAsmOperand?
430
4.98k
          if (Modifier[0] == 'l') { // Labels are target independent.
431
10
            if (MI->getOperand(OpNo).isBlockAddress()) {
432
8
              const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
433
8
              MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
434
8
              Sym->print(OS, AP->MAI);
435
8
            } else 
if (2
MI->getOperand(OpNo).isMBB()2
) {
436
2
              const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
437
2
              Sym->print(OS, AP->MAI);
438
2
            } else {
439
0
              Error = true;
440
0
            }
441
4.97k
          } else {
442
4.97k
            if (InlineAsm::isMemKind(OpFlags)) {
443
404
              Error = AP->PrintAsmMemoryOperand(
444
404
                  MI, OpNo, Modifier[0] ? 
Modifier17
:
nullptr387
, OS);
445
4.57k
            } else {
446
4.57k
              Error = AP->PrintAsmOperand(MI, OpNo,
447
4.57k
                                          Modifier[0] ? 
Modifier410
:
nullptr4.16k
, OS);
448
4.57k
            }
449
4.97k
          }
450
4.98k
        }
451
4.98k
        if (Error) {
452
2
          std::string msg;
453
2
          raw_string_ostream Msg(msg);
454
2
          Msg << "invalid operand in inline asm: '" << AsmStr << "'";
455
2
          MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
456
2
        }
457
4.98k
      }
458
4.98k
      break;
459
4.98k
    }
460
20.3k
    }
461
20.3k
  }
462
8.07k
  OS << '\n' << (char)0;  // null terminate string.
463
8.07k
}
464
465
/// EmitInlineAsm - This method formats and emits the specified machine
466
/// instruction that is an inline asm.
467
20.2k
void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
468
20.2k
  assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
469
20.2k
470
20.2k
  // Count the number of register definitions to find the asm string.
471
20.2k
  unsigned NumDefs = 0;
472
20.2k
  for (; MI->getOperand(NumDefs).isReg() && 
MI->getOperand(NumDefs).isDef()0
;
473
20.2k
       
++NumDefs0
)
474
20.2k
    assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
475
20.2k
476
20.2k
  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
477
20.2k
478
20.2k
  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
479
20.2k
  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
480
20.2k
481
20.2k
  // If this asmstr is empty, just print the #APP/#NOAPP markers.
482
20.2k
  // These are useful to see where empty asm's wound up.
483
20.2k
  if (AsmStr[0] == 0) {
484
12.1k
    OutStreamer->emitRawComment(MAI->getInlineAsmStart());
485
12.1k
    OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
486
12.1k
    return;
487
12.1k
  }
488
8.10k
489
8.10k
  // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
490
8.10k
  // enabled, so we use emitRawComment.
491
8.10k
  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
492
8.10k
493
8.10k
  // Get the !srcloc metadata node if we have it, and decode the loc cookie from
494
8.10k
  // it.
495
8.10k
  unsigned LocCookie = 0;
496
8.10k
  const MDNode *LocMD = nullptr;
497
134k
  for (unsigned i = MI->getNumOperands(); i != 0; 
--i126k
) {
498
129k
    if (MI->getOperand(i-1).isMetadata() &&
499
129k
        
(LocMD = MI->getOperand(i-1).getMetadata())2.66k
&&
500
129k
        
LocMD->getNumOperands() != 02.66k
) {
501
2.66k
      if (const ConstantInt *CI =
502
2.66k
              mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
503
2.66k
        LocCookie = CI->getZExtValue();
504
2.66k
        break;
505
2.66k
      }
506
2.66k
    }
507
129k
  }
508
8.10k
509
8.10k
  // Emit the inline asm to a temporary string so we can emit it through
510
8.10k
  // EmitInlineAsm.
511
8.10k
  SmallString<256> StringData;
512
8.10k
  raw_svector_ostream OS(StringData);
513
8.10k
514
8.10k
  // The variant of the current asmprinter.
515
8.10k
  int AsmPrinterVariant = MAI->getAssemblerDialect();
516
8.10k
  AsmPrinter *AP = const_cast<AsmPrinter*>(this);
517
8.10k
  if (MI->getInlineAsmDialect() == InlineAsm::AD_ATT)
518
8.07k
    EmitGCCInlineAsmStr(AsmStr, MI, MMI, AsmPrinterVariant, AP, LocCookie, OS);
519
31
  else
520
31
    EmitMSInlineAsmStr(AsmStr, MI, MMI, AP, LocCookie, OS);
521
8.10k
522
8.10k
  // Emit warnings if we use reserved registers on the clobber list, as
523
8.10k
  // that might give surprising results.
524
8.10k
  std::vector<std::string> RestrRegs;
525
8.10k
  // Start with the first operand descriptor, and iterate over them.
526
8.10k
  for (unsigned I = InlineAsm::MIOp_FirstOperand, NumOps = MI->getNumOperands();
527
76.6k
       I < NumOps; 
++I68.5k
) {
528
68.5k
    const MachineOperand &MO = MI->getOperand(I);
529
68.5k
    if (MO.isImm()) {
530
65.7k
      unsigned Flags = MO.getImm();
531
65.7k
      const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
532
65.7k
      if (InlineAsm::getKind(Flags) == InlineAsm::Kind_Clobber &&
533
65.7k
          
!TRI->isAsmClobberable(*MF, MI->getOperand(I + 1).getReg())57.9k
) {
534
140
        RestrRegs.push_back(TRI->getName(MI->getOperand(I + 1).getReg()));
535
140
      }
536
65.7k
      // Skip to one before the next operand descriptor, if it exists.
537
65.7k
      I += InlineAsm::getNumOperandRegisters(Flags);
538
65.7k
    }
539
68.5k
  }
540
8.10k
541
8.10k
  if (!RestrRegs.empty()) {
542
61
    unsigned BufNum = addInlineAsmDiagBuffer(OS.str(), LocMD);
543
61
    auto &SrcMgr = DiagInfo->SrcMgr;
544
61
    SMLoc Loc = SMLoc::getFromPointer(
545
61
        SrcMgr.getMemoryBuffer(BufNum)->getBuffer().begin());
546
61
547
61
    std::string Msg = "inline asm clobber list contains reserved registers: ";
548
201
    for (auto I = RestrRegs.begin(), E = RestrRegs.end(); I != E; 
I++140
) {
549
140
      if(I != RestrRegs.begin())
550
79
        Msg += ", ";
551
140
      Msg += *I;
552
140
    }
553
61
    std::string Note = "Reserved registers on the clobber list may not be "
554
61
                "preserved across the asm statement, and clobbering them may "
555
61
                "lead to undefined behaviour.";
556
61
    SrcMgr.PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
557
61
    SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note, Note);
558
61
  }
559
8.10k
560
8.10k
  EmitInlineAsm(OS.str(), getSubtargetInfo(), TM.Options.MCOptions, LocMD,
561
8.10k
                MI->getInlineAsmDialect());
562
8.10k
563
8.10k
  // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
564
8.10k
  // enabled, so we use emitRawComment.
565
8.10k
  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
566
8.10k
}
567
568
569
/// PrintSpecial - Print information related to the specified machine instr
570
/// that is independent of the operand, and may be independent of the instr
571
/// itself.  This can be useful for portably encoding the comment character
572
/// or other bits of target-specific knowledge into the asmstrings.  The
573
/// syntax used is ${:comment}.  Targets can override this to add support
574
/// for their own strange codes.
575
void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
576
6
                              const char *Code) const {
577
6
  if (!strcmp(Code, "private")) {
578
0
    const DataLayout &DL = MF->getDataLayout();
579
0
    OS << DL.getPrivateGlobalPrefix();
580
6
  } else if (!strcmp(Code, "comment")) {
581
0
    OS << MAI->getCommentString();
582
6
  } else if (!strcmp(Code, "uid")) {
583
6
    // Comparing the address of MI isn't sufficient, because machineinstrs may
584
6
    // be allocated to the same address across functions.
585
6
586
6
    // If this is a new LastFn instruction, bump the counter.
587
6
    if (LastMI != MI || 
LastFn != getFunctionNumber()3
) {
588
3
      ++Counter;
589
3
      LastMI = MI;
590
3
      LastFn = getFunctionNumber();
591
3
    }
592
6
    OS << Counter;
593
6
  } else {
594
0
    std::string msg;
595
0
    raw_string_ostream Msg(msg);
596
0
    Msg << "Unknown special formatter '" << Code
597
0
         << "' for machine instr: " << *MI;
598
0
    report_fatal_error(Msg.str());
599
0
  }
600
6
}
601
602
25
void AsmPrinter::PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS) {
603
25
  assert(MO.isGlobal() && "caller should check MO.isGlobal");
604
25
  getSymbol(MO.getGlobal())->print(OS, MAI);
605
25
  printOffset(MO.getOffset(), OS);
606
25
}
607
608
/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
609
/// instruction, using the specified assembler variant.  Targets should
610
/// override this to format as appropriate for machine specific ExtraCodes
611
/// or when the arch-independent handling would be too complex otherwise.
612
bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
613
1.04k
                                 const char *ExtraCode, raw_ostream &O) {
614
1.04k
  // Does this asm operand have a single letter operand modifier?
615
1.04k
  if (ExtraCode && 
ExtraCode[0]119
) {
616
119
    if (ExtraCode[1] != 0) 
return true0
; // Unknown modifier.
617
119
618
119
    // https://gcc.gnu.org/onlinedocs/gccint/Output-Template.html
619
119
    const MachineOperand &MO = MI->getOperand(OpNo);
620
119
    switch (ExtraCode[0]) {
621
119
    default:
622
47
      return true;  // Unknown modifier.
623
119
    case 'a': // Print as memory address.
624
3
      if (MO.isReg()) {
625
2
        PrintAsmMemoryOperand(MI, OpNo, nullptr, O);
626
2
        return false;
627
2
      }
628
1
      LLVM_FALLTHROUGH; // GCC allows '%a' to behave like '%c' with immediates.
629
46
    case 'c': // Substitute immediate value without immediate syntax
630
46
      if (MO.isImm()) {
631
31
        O << MO.getImm();
632
31
        return false;
633
31
      }
634
15
      if (MO.isGlobal()) {
635
15
        PrintSymbolOperand(MO, O);
636
15
        return false;
637
15
      }
638
0
      return true;
639
18
    case 'n':  // Negate the immediate constant.
640
18
      if (!MO.isImm())
641
0
        return true;
642
18
      O << -MO.getImm();
643
18
      return false;
644
18
    case 's':  // The GCC deprecated s modifier
645
6
      if (!MO.isImm())
646
5
        return true;
647
1
      O << ((32 - MO.getImm()) & 31);
648
1
      return false;
649
119
    }
650
119
  }
651
922
  return true;
652
922
}
653
654
bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
655
0
                                       const char *ExtraCode, raw_ostream &O) {
656
0
  // Target doesn't support this yet!
657
0
  return true;
658
0
}
659
660
8.73k
void AsmPrinter::emitInlineAsmStart() const {}
661
662
void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
663
8.00k
                                  const MCSubtargetInfo *EndInfo) const {}