blob: 339ff7a953634b5479a72b729d04d00264a11f98 [file] [log] [blame]
Chad Rosier3d45a772012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier4b5e48d2012-08-17 21:19:40 +00002//
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 semantic analysis for inline asm statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Scope.h"
16#include "clang/Sema/ScopeInfo.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
Chad Rosier6e97be72012-08-22 23:42:09 +000027#include "llvm/MC/MCExpr.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000028#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
30#include "llvm/MC/MCInstrInfo.h"
31#include "llvm/MC/MCObjectFileInfo.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSubtargetInfo.h"
Chad Rosier6e97be72012-08-22 23:42:09 +000035#include "llvm/MC/MCSymbol.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000036#include "llvm/MC/MCTargetAsmParser.h"
37#include "llvm/MC/MCParser/MCAsmLexer.h"
38#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosierfb700262012-09-11 23:13:15 +000039#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000040#include "llvm/Support/SourceMgr.h"
41#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/TargetSelect.h"
43using namespace clang;
44using namespace sema;
45
46/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
47/// ignore "noop" casts in places where an lvalue is required by an inline asm.
48/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
49/// provide a strong guidance to not use it.
50///
51/// This method checks to see if the argument is an acceptable l-value and
52/// returns false if it is a case we can handle.
53static bool CheckAsmLValue(const Expr *E, Sema &S) {
54 // Type dependent expressions will be checked during instantiation.
55 if (E->isTypeDependent())
56 return false;
57
58 if (E->isLValue())
59 return false; // Cool, this is an lvalue.
60
61 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
62 // are supposed to allow.
63 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
64 if (E != E2 && E2->isLValue()) {
65 if (!S.getLangOpts().HeinousExtensions)
66 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
67 << E->getSourceRange();
68 else
69 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
70 << E->getSourceRange();
71 // Accept, even if we emitted an error diagnostic.
72 return false;
73 }
74
75 // None of the above, just randomly invalid non-lvalue.
76 return true;
77}
78
79/// isOperandMentioned - Return true if the specified operand # is mentioned
80/// anywhere in the decomposed asm string.
81static bool isOperandMentioned(unsigned OpNo,
Chad Rosierdf5faf52012-08-25 00:11:56 +000082 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +000083 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierdf5faf52012-08-25 00:11:56 +000084 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier4b5e48d2012-08-17 21:19:40 +000085 if (!Piece.isOperand()) continue;
86
87 // If this is a reference to the input and if the input was the smaller
88 // one, then we have to reject this asm.
89 if (Piece.getOperandNo() == OpNo)
90 return true;
91 }
92 return false;
93}
94
Chad Rosierdf5faf52012-08-25 00:11:56 +000095StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
96 bool IsVolatile, unsigned NumOutputs,
97 unsigned NumInputs, IdentifierInfo **Names,
98 MultiExprArg constraints, MultiExprArg exprs,
99 Expr *asmString, MultiExprArg clobbers,
100 SourceLocation RParenLoc) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000101 unsigned NumClobbers = clobbers.size();
102 StringLiteral **Constraints =
Benjamin Kramer5354e772012-08-23 23:38:35 +0000103 reinterpret_cast<StringLiteral**>(constraints.data());
104 Expr **Exprs = exprs.data();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000105 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000106 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000107
108 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
109
110 // The parser verifies that there is a string literal here.
111 if (!AsmString->isAscii())
112 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
113 << AsmString->getSourceRange());
114
115 for (unsigned i = 0; i != NumOutputs; i++) {
116 StringLiteral *Literal = Constraints[i];
117 if (!Literal->isAscii())
118 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
119 << Literal->getSourceRange());
120
121 StringRef OutputName;
122 if (Names[i])
123 OutputName = Names[i]->getName();
124
125 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
126 if (!Context.getTargetInfo().validateOutputConstraint(Info))
127 return StmtError(Diag(Literal->getLocStart(),
128 diag::err_asm_invalid_output_constraint)
129 << Info.getConstraintStr());
130
131 // Check that the output exprs are valid lvalues.
132 Expr *OutputExpr = Exprs[i];
133 if (CheckAsmLValue(OutputExpr, *this)) {
134 return StmtError(Diag(OutputExpr->getLocStart(),
135 diag::err_asm_invalid_lvalue_in_output)
136 << OutputExpr->getSourceRange());
137 }
138
139 OutputConstraintInfos.push_back(Info);
140 }
141
142 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
143
144 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
145 StringLiteral *Literal = Constraints[i];
146 if (!Literal->isAscii())
147 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
148 << Literal->getSourceRange());
149
150 StringRef InputName;
151 if (Names[i])
152 InputName = Names[i]->getName();
153
154 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
155 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
156 NumOutputs, Info)) {
157 return StmtError(Diag(Literal->getLocStart(),
158 diag::err_asm_invalid_input_constraint)
159 << Info.getConstraintStr());
160 }
161
162 Expr *InputExpr = Exprs[i];
163
164 // Only allow void types for memory constraints.
165 if (Info.allowsMemory() && !Info.allowsRegister()) {
166 if (CheckAsmLValue(InputExpr, *this))
167 return StmtError(Diag(InputExpr->getLocStart(),
168 diag::err_asm_invalid_lvalue_in_input)
169 << Info.getConstraintStr()
170 << InputExpr->getSourceRange());
171 }
172
173 if (Info.allowsRegister()) {
174 if (InputExpr->getType()->isVoidType()) {
175 return StmtError(Diag(InputExpr->getLocStart(),
176 diag::err_asm_invalid_type_in_input)
177 << InputExpr->getType() << Info.getConstraintStr()
178 << InputExpr->getSourceRange());
179 }
180 }
181
182 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
183 if (Result.isInvalid())
184 return StmtError();
185
186 Exprs[i] = Result.take();
187 InputConstraintInfos.push_back(Info);
188 }
189
190 // Check that the clobbers are valid.
191 for (unsigned i = 0; i != NumClobbers; i++) {
192 StringLiteral *Literal = Clobbers[i];
193 if (!Literal->isAscii())
194 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
195 << Literal->getSourceRange());
196
197 StringRef Clobber = Literal->getString();
198
199 if (!Context.getTargetInfo().isValidClobber(Clobber))
200 return StmtError(Diag(Literal->getLocStart(),
201 diag::err_asm_unknown_register_name) << Clobber);
202 }
203
Chad Rosierdf5faf52012-08-25 00:11:56 +0000204 GCCAsmStmt *NS =
205 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
206 NumInputs, Names, Constraints, Exprs, AsmString,
207 NumClobbers, Clobbers, RParenLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000208 // Validate the asm string, ensuring it makes sense given the operands we
209 // have.
Chad Rosierdf5faf52012-08-25 00:11:56 +0000210 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000211 unsigned DiagOffs;
212 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
213 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
214 << AsmString->getSourceRange();
215 return StmtError();
216 }
217
218 // Validate tied input operands for type mismatches.
219 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
220 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
221
222 // If this is a tied constraint, verify that the output and input have
223 // either exactly the same type, or that they are int/ptr operands with the
224 // same size (int/long, int*/long, are ok etc).
225 if (!Info.hasTiedOperand()) continue;
226
227 unsigned TiedTo = Info.getTiedOperand();
228 unsigned InputOpNo = i+NumOutputs;
229 Expr *OutputExpr = Exprs[TiedTo];
230 Expr *InputExpr = Exprs[InputOpNo];
231
232 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
233 continue;
234
235 QualType InTy = InputExpr->getType();
236 QualType OutTy = OutputExpr->getType();
237 if (Context.hasSameType(InTy, OutTy))
238 continue; // All types can be tied to themselves.
239
240 // Decide if the input and output are in the same domain (integer/ptr or
241 // floating point.
242 enum AsmDomain {
243 AD_Int, AD_FP, AD_Other
244 } InputDomain, OutputDomain;
245
246 if (InTy->isIntegerType() || InTy->isPointerType())
247 InputDomain = AD_Int;
248 else if (InTy->isRealFloatingType())
249 InputDomain = AD_FP;
250 else
251 InputDomain = AD_Other;
252
253 if (OutTy->isIntegerType() || OutTy->isPointerType())
254 OutputDomain = AD_Int;
255 else if (OutTy->isRealFloatingType())
256 OutputDomain = AD_FP;
257 else
258 OutputDomain = AD_Other;
259
260 // They are ok if they are the same size and in the same domain. This
261 // allows tying things like:
262 // void* to int*
263 // void* to int if they are the same size.
264 // double to long double if they are the same size.
265 //
266 uint64_t OutSize = Context.getTypeSize(OutTy);
267 uint64_t InSize = Context.getTypeSize(InTy);
268 if (OutSize == InSize && InputDomain == OutputDomain &&
269 InputDomain != AD_Other)
270 continue;
271
272 // If the smaller input/output operand is not mentioned in the asm string,
273 // then we can promote the smaller one to a larger input and the asm string
274 // won't notice.
275 bool SmallerValueMentioned = false;
276
277 // If this is a reference to the input and if the input was the smaller
278 // one, then we have to reject this asm.
279 if (isOperandMentioned(InputOpNo, Pieces)) {
280 // This is a use in the asm string of the smaller operand. Since we
281 // codegen this by promoting to a wider value, the asm will get printed
282 // "wrong".
283 SmallerValueMentioned |= InSize < OutSize;
284 }
285 if (isOperandMentioned(TiedTo, Pieces)) {
286 // If this is a reference to the output, and if the output is the larger
287 // value, then it's ok because we'll promote the input to the larger type.
288 SmallerValueMentioned |= OutSize < InSize;
289 }
290
291 // If the smaller value wasn't mentioned in the asm string, and if the
292 // output was a register, just extend the shorter one to the size of the
293 // larger one.
294 if (!SmallerValueMentioned && InputDomain != AD_Other &&
295 OutputConstraintInfos[TiedTo].allowsRegister())
296 continue;
297
298 // Either both of the operands were mentioned or the smaller one was
299 // mentioned. One more special case that we'll allow: if the tied input is
300 // integer, unmentioned, and is a constant, then we'll allow truncating it
301 // down to the size of the destination.
302 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
303 !isOperandMentioned(InputOpNo, Pieces) &&
304 InputExpr->isEvaluatable(Context)) {
305 CastKind castKind =
306 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
307 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
308 Exprs[InputOpNo] = InputExpr;
309 NS->setInputExpr(i, InputExpr);
310 continue;
311 }
312
313 Diag(InputExpr->getLocStart(),
314 diag::err_asm_tying_incompatible_types)
315 << InTy << OutTy << OutputExpr->getSourceRange()
316 << InputExpr->getSourceRange();
317 return StmtError();
318 }
319
320 return Owned(NS);
321}
322
Chad Rosier358ab762012-08-22 21:08:06 +0000323// getSpelling - Get the spelling of the AsmTok token.
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000324static StringRef getSpelling(Sema &SemaRef, Token AsmTok) {
325 StringRef Asm;
326 SmallString<512> TokenBuf;
327 TokenBuf.resize(512);
328 bool StringInvalid = false;
329 Asm = SemaRef.PP.getSpelling(AsmTok, TokenBuf, &StringInvalid);
330 assert (!StringInvalid && "Expected valid string!");
331 return Asm;
332}
333
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000334// Build the inline assembly string. Returns true on error.
335static bool buildMSAsmString(Sema &SemaRef,
336 SourceLocation AsmLoc,
337 ArrayRef<Token> AsmToks,
338 std::string &AsmString) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000339 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000340
341 SmallString<512> Asm;
342 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
Bob Wilson40d39e32012-09-24 19:57:55 +0000343 bool isNewAsm = ((i == 0) ||
344 AsmToks[i].isAtStartOfLine() ||
345 AsmToks[i].is(tok::kw_asm));
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000346 if (isNewAsm) {
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000347 if (i != 0)
348 Asm += "\n\t";
349
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000350 if (AsmToks[i].is(tok::kw_asm)) {
351 i++; // Skip __asm
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000352 if (i == e) {
353 SemaRef.Diag(AsmLoc, diag::err_asm_empty);
354 return true;
355 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000356
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000357 }
358 }
359
Chad Rosierb55e6022012-09-13 00:06:55 +0000360 if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000361 Asm += ' ';
Chad Rosier4de97162012-09-11 00:51:28 +0000362
363 StringRef Spelling = getSpelling(SemaRef, AsmToks[i]);
364 Asm += Spelling;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000365 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000366 AsmString = Asm.str();
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000367 return false;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000368}
369
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000370namespace {
371enum AsmOpRewriteKind {
372 AOK_Imm,
373 AOK_Input,
374 AOK_Output
375};
376
377struct AsmOpRewrite {
378 AsmOpRewriteKind Kind;
379 llvm::SMLoc Loc;
380 unsigned Len;
381
382public:
383 AsmOpRewrite(AsmOpRewriteKind kind, llvm::SMLoc loc, unsigned len)
384 : Kind(kind), Loc(loc), Len(len) { }
385};
386
387}
Chad Rosier2735df22012-08-22 19:18:30 +0000388
Chad Rosierb55e6022012-09-13 00:06:55 +0000389StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
390 ArrayRef<Token> AsmToks,SourceLocation EndLoc) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000391 SmallVector<IdentifierInfo*, 4> Inputs;
392 SmallVector<IdentifierInfo*, 4> Outputs;
Chad Rosier633abb02012-08-24 00:07:09 +0000393 SmallVector<Expr*, 4> InputExprs;
394 SmallVector<Expr*, 4> OutputExprs;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000395 SmallVector<StringRef, 4> Constraints;
396 SmallVector<std::string, 4> InputConstraints;
397 SmallVector<std::string, 4> OutputConstraints;
398
399 SmallVector<StringRef, 4> Clobbers;
400 std::set<std::string> ClobberRegs;
401
402 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000403
404 // Empty asm statements don't need to instantiate the AsmParser, etc.
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000405 if (AsmToks.empty()) {
406 StringRef EmptyAsmStr;
407 MSAsmStmt *NS =
408 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
409 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
410 InputExprs, OutputExprs, EmptyAsmStr, Constraints,
411 Clobbers, EndLoc);
412 return Owned(NS);
413 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000414
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000415 std::string AsmString;
416 if (buildMSAsmString(*this, AsmLoc, AsmToks, AsmString))
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000417 return StmtError();
Chad Rosier38c71d32012-08-21 21:56:39 +0000418
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000419 // Get the target specific parser.
420 std::string Error;
421 const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
422 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
423
424 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
425 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
426 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
427 OwningPtr<llvm::MCSubtargetInfo>
428 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
429
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000430 llvm::SourceMgr SrcMgr;
431 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
432 llvm::MemoryBuffer *Buffer =
433 llvm::MemoryBuffer::getMemBuffer(AsmString, "<inline asm>");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000434
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000435 // Tell SrcMgr about this buffer, which is what the parser will pick up.
436 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000437
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000438 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
439 OwningPtr<llvm::MCAsmParser>
440 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
441 OwningPtr<llvm::MCTargetAsmParser>
442 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
Chad Rosier67bd78f2012-10-13 00:26:22 +0000443 Parser->setParsingInlineAsm(true);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000444
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000445 // Get the instruction descriptor.
446 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
447 llvm::MCInstPrinter *IP =
448 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000449
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000450 // Change to the Intel dialect.
451 Parser->setAssemblerDialect(1);
452 Parser->setTargetParser(*TargetParser.get());
453 Parser->setParsingInlineAsm(true);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000454
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000455 // Prime the lexer.
456 Parser->Lex();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000457
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000458 // While we have input, parse each statement.
459 unsigned InputIdx = 0;
460 unsigned OutputIdx = 0;
461 while (Parser->getLexer().isNot(llvm::AsmToken::Eof)) {
462 if (Parser->ParseStatement()) {
463 // FIXME: The AsmParser should report errors, but we could potentially be
464 // more verbose here.
465 break;
466 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000467
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000468 if (Parser->isInstruction()) {
469 const llvm::MCInstrDesc &Desc = MII->get(Parser->getOpcode());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000470
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000471 // Build the list of clobbers, outputs and inputs.
472 for (unsigned i = 1, e = Parser->getNumParsedOperands(); i != e; ++i) {
473 llvm::MCParsedAsmOperand &Operand = Parser->getParsedOperand(i);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000474
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000475 // Immediate.
476 if (Operand.isImm()) {
477 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
478 Operand.getStartLoc(),
479 Operand.getNameLen()));
480 continue;
Chad Rosier1b497f22012-09-03 20:40:52 +0000481 }
Chad Rosier3034d882012-10-01 23:45:59 +0000482
Chad Rosier3034d882012-10-01 23:45:59 +0000483
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000484 // Register operand.
485 if (Operand.isReg()) {
486 unsigned NumDefs = Desc.getNumDefs();
487 // Clobber.
488 if (NumDefs && Operand.getMCOperandNum() < NumDefs) {
489 std::string Reg;
490 llvm::raw_string_ostream OS(Reg);
491 IP->printRegName(OS, Operand.getReg());
492 StringRef Clobber(OS.str());
493 if (!Context.getTargetInfo().isValidClobber(Clobber))
494 return StmtError(
495 Diag(AsmLoc, diag::err_asm_unknown_register_name) << Clobber);
496 ClobberRegs.insert(Reg);
497 }
498 continue;
499 }
500
501
502 // Expr/Input or Output.
503 StringRef Name = Operand.getName();
504 if (IdentifierInfo *II = &Context.Idents.get(Name)) {
505 CXXScopeSpec SS;
506 UnqualifiedId Id;
507 SourceLocation Loc;
508 Id.setIdentifier(II, AsmLoc);
509 ExprResult Result = ActOnIdExpression(getCurScope(), SS, Loc, Id,
510 false, false);
511 if (!Result.isInvalid()) {
512 bool isOutput = (i == 1) && Desc.mayStore();
513 if (isOutput) {
514 std::string Constraint = "=";
515 ++InputIdx;
516 Outputs.push_back(II);
517 OutputExprs.push_back(Result.take());
518 Constraint += Operand.getConstraint().str();
519 OutputConstraints.push_back(Constraint);
520 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
521 Operand.getStartLoc(),
522 Operand.getNameLen()));
523 } else {
524 Inputs.push_back(II);
525 InputExprs.push_back(Result.take());
526 InputConstraints.push_back(Operand.getConstraint().str());
527 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
528 Operand.getStartLoc(),
529 Operand.getNameLen()));
530 }
Chad Rosier633abb02012-08-24 00:07:09 +0000531 }
Chad Rosier6e97be72012-08-22 23:42:09 +0000532 }
Chad Rosierfd5e56e2012-08-22 22:10:51 +0000533 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000534 Parser->freeParsedOperands();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000535 }
536 }
537 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
538 E = ClobberRegs.end(); I != E; ++I)
539 Clobbers.push_back(*I);
540
Chad Rosier89fb6d72012-08-28 20:28:20 +0000541 // Merge the output and input constraints. Output constraints are expected
542 // first.
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000543 for (SmallVectorImpl<std::string>::iterator I = OutputConstraints.begin(),
Chad Rosier89fb6d72012-08-28 20:28:20 +0000544 E = OutputConstraints.end(); I != E; ++I)
545 Constraints.push_back(*I);
546
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000547 for (SmallVectorImpl<std::string>::iterator I = InputConstraints.begin(),
Chad Rosier89fb6d72012-08-28 20:28:20 +0000548 E = InputConstraints.end(); I != E; ++I)
549 Constraints.push_back(*I);
550
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000551 // Build the IR assembly string.
552 std::string AsmStringIR;
553 llvm::raw_string_ostream OS(AsmStringIR);
554 const char *Start = AsmString.c_str();
555 for (SmallVectorImpl<struct AsmOpRewrite>::iterator I = AsmStrRewrites.begin(),
556 E = AsmStrRewrites.end(); I != E; ++I) {
557 const char *Loc = (*I).Loc.getPointer();
558
559 // Emit everything up to the immediate/expression.
560 OS << StringRef(Start, Loc - Start);
561
562 // Rewrite expressions in $N notation.
563 switch ((*I).Kind) {
564 case AOK_Imm:
565 OS << Twine("$$") + StringRef(Loc, (*I).Len);
566 break;
567 case AOK_Input:
568 OS << '$';
569 OS << InputIdx++;
570 break;
571 case AOK_Output:
572 OS << '$';
573 OS << OutputIdx++;
574 break;
Chad Rosierb55e6022012-09-13 00:06:55 +0000575 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000576
577 // Skip the original expression.
578 Start = Loc + (*I).Len;
Chad Rosieracc22b62012-09-06 19:35:00 +0000579 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000580 // Emit the remainder of the asm string.
581 const char *AsmEnd = AsmString.c_str() + AsmString.size();
582 if (Start != AsmEnd)
583 OS << StringRef(Start, AsmEnd - Start);
Chad Rosierb55e6022012-09-13 00:06:55 +0000584
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000585 AsmString = OS.str();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000586 MSAsmStmt *NS =
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000587 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ false,
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000588 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
Chad Rosier89fb6d72012-08-28 20:28:20 +0000589 InputExprs, OutputExprs, AsmString, Constraints,
590 Clobbers, EndLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000591 return Owned(NS);
592}