blob: 95964e20a7ea5b4cbe4eb72450238914a16370a8 [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"
Chad Rosier802f9372012-10-25 21:49:22 +000015#include "clang/AST/RecordLayout.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000016#include "clang/AST/TypeLoc.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000017#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/BitVector.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000028#include "llvm/MC/MCObjectFileInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000029#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000030#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/MC/MCTargetAsmParser.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000034#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
37using namespace clang;
38using namespace sema;
39
40/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
41/// ignore "noop" casts in places where an lvalue is required by an inline asm.
42/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
43/// provide a strong guidance to not use it.
44///
45/// This method checks to see if the argument is an acceptable l-value and
46/// returns false if it is a case we can handle.
47static bool CheckAsmLValue(const Expr *E, Sema &S) {
48 // Type dependent expressions will be checked during instantiation.
49 if (E->isTypeDependent())
50 return false;
51
52 if (E->isLValue())
53 return false; // Cool, this is an lvalue.
54
55 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
56 // are supposed to allow.
57 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
58 if (E != E2 && E2->isLValue()) {
59 if (!S.getLangOpts().HeinousExtensions)
60 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
61 << E->getSourceRange();
62 else
63 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
64 << E->getSourceRange();
65 // Accept, even if we emitted an error diagnostic.
66 return false;
67 }
68
69 // None of the above, just randomly invalid non-lvalue.
70 return true;
71}
72
73/// isOperandMentioned - Return true if the specified operand # is mentioned
74/// anywhere in the decomposed asm string.
75static bool isOperandMentioned(unsigned OpNo,
Chad Rosierdf5faf52012-08-25 00:11:56 +000076 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +000077 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierdf5faf52012-08-25 00:11:56 +000078 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier4b5e48d2012-08-17 21:19:40 +000079 if (!Piece.isOperand()) continue;
80
81 // If this is a reference to the input and if the input was the smaller
82 // one, then we have to reject this asm.
83 if (Piece.getOperandNo() == OpNo)
84 return true;
85 }
86 return false;
87}
88
Chad Rosierdf5faf52012-08-25 00:11:56 +000089StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
90 bool IsVolatile, unsigned NumOutputs,
91 unsigned NumInputs, IdentifierInfo **Names,
92 MultiExprArg constraints, MultiExprArg exprs,
93 Expr *asmString, MultiExprArg clobbers,
94 SourceLocation RParenLoc) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +000095 unsigned NumClobbers = clobbers.size();
96 StringLiteral **Constraints =
Benjamin Kramer5354e772012-08-23 23:38:35 +000097 reinterpret_cast<StringLiteral**>(constraints.data());
98 Expr **Exprs = exprs.data();
Chad Rosier4b5e48d2012-08-17 21:19:40 +000099 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000100 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000101
102 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
103
104 // The parser verifies that there is a string literal here.
105 if (!AsmString->isAscii())
106 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
107 << AsmString->getSourceRange());
108
109 for (unsigned i = 0; i != NumOutputs; i++) {
110 StringLiteral *Literal = Constraints[i];
111 if (!Literal->isAscii())
112 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
113 << Literal->getSourceRange());
114
115 StringRef OutputName;
116 if (Names[i])
117 OutputName = Names[i]->getName();
118
119 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
120 if (!Context.getTargetInfo().validateOutputConstraint(Info))
121 return StmtError(Diag(Literal->getLocStart(),
122 diag::err_asm_invalid_output_constraint)
123 << Info.getConstraintStr());
124
125 // Check that the output exprs are valid lvalues.
126 Expr *OutputExpr = Exprs[i];
127 if (CheckAsmLValue(OutputExpr, *this)) {
128 return StmtError(Diag(OutputExpr->getLocStart(),
129 diag::err_asm_invalid_lvalue_in_output)
130 << OutputExpr->getSourceRange());
131 }
132
133 OutputConstraintInfos.push_back(Info);
134 }
135
136 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
137
138 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
139 StringLiteral *Literal = Constraints[i];
140 if (!Literal->isAscii())
141 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
142 << Literal->getSourceRange());
143
144 StringRef InputName;
145 if (Names[i])
146 InputName = Names[i]->getName();
147
148 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
149 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
150 NumOutputs, Info)) {
151 return StmtError(Diag(Literal->getLocStart(),
152 diag::err_asm_invalid_input_constraint)
153 << Info.getConstraintStr());
154 }
155
156 Expr *InputExpr = Exprs[i];
157
158 // Only allow void types for memory constraints.
159 if (Info.allowsMemory() && !Info.allowsRegister()) {
160 if (CheckAsmLValue(InputExpr, *this))
161 return StmtError(Diag(InputExpr->getLocStart(),
162 diag::err_asm_invalid_lvalue_in_input)
163 << Info.getConstraintStr()
164 << InputExpr->getSourceRange());
165 }
166
167 if (Info.allowsRegister()) {
168 if (InputExpr->getType()->isVoidType()) {
169 return StmtError(Diag(InputExpr->getLocStart(),
170 diag::err_asm_invalid_type_in_input)
171 << InputExpr->getType() << Info.getConstraintStr()
172 << InputExpr->getSourceRange());
173 }
174 }
175
176 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
177 if (Result.isInvalid())
178 return StmtError();
179
180 Exprs[i] = Result.take();
181 InputConstraintInfos.push_back(Info);
Bill Wendling68fd6082012-11-12 06:42:51 +0000182
183 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendling984f2782013-03-22 21:33:46 +0000184 if (Ty->isDependentType() ||
185 RequireCompleteType(InputExpr->getLocStart(),
186 Exprs[i]->getType(), 0))
Eric Christopher6ceb3772012-11-12 23:13:34 +0000187 continue;
188
Bill Wendling68fd6082012-11-12 06:42:51 +0000189 unsigned Size = Context.getTypeSize(Ty);
190 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
191 Size))
192 return StmtError(Diag(InputExpr->getLocStart(),
193 diag::err_asm_invalid_input_size)
194 << Info.getConstraintStr());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000195 }
196
197 // Check that the clobbers are valid.
198 for (unsigned i = 0; i != NumClobbers; i++) {
199 StringLiteral *Literal = Clobbers[i];
200 if (!Literal->isAscii())
201 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
202 << Literal->getSourceRange());
203
204 StringRef Clobber = Literal->getString();
205
206 if (!Context.getTargetInfo().isValidClobber(Clobber))
207 return StmtError(Diag(Literal->getLocStart(),
208 diag::err_asm_unknown_register_name) << Clobber);
209 }
210
Chad Rosierdf5faf52012-08-25 00:11:56 +0000211 GCCAsmStmt *NS =
212 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
213 NumInputs, Names, Constraints, Exprs, AsmString,
214 NumClobbers, Clobbers, RParenLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000215 // Validate the asm string, ensuring it makes sense given the operands we
216 // have.
Chad Rosierdf5faf52012-08-25 00:11:56 +0000217 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000218 unsigned DiagOffs;
219 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
220 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
221 << AsmString->getSourceRange();
222 return StmtError();
223 }
224
Bill Wendling50d46ca2012-10-25 23:28:48 +0000225 // Validate constraints and modifiers.
226 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
227 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
228 if (!Piece.isOperand()) continue;
229
230 // Look for the correct constraint index.
231 unsigned Idx = 0;
232 unsigned ConstraintIdx = 0;
233 for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
234 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
235 if (Idx == Piece.getOperandNo())
236 break;
237 ++Idx;
238
239 if (Info.isReadWrite()) {
240 if (Idx == Piece.getOperandNo())
241 break;
242 ++Idx;
243 }
244 }
245
246 for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
247 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
248 if (Idx == Piece.getOperandNo())
249 break;
250 ++Idx;
251
252 if (Info.isReadWrite()) {
253 if (Idx == Piece.getOperandNo())
254 break;
255 ++Idx;
256 }
257 }
258
259 // Now that we have the right indexes go ahead and check.
260 StringLiteral *Literal = Constraints[ConstraintIdx];
261 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
262 if (Ty->isDependentType() || Ty->isIncompleteType())
263 continue;
264
265 unsigned Size = Context.getTypeSize(Ty);
266 if (!Context.getTargetInfo()
267 .validateConstraintModifier(Literal->getString(), Piece.getModifier(),
268 Size))
269 Diag(Exprs[ConstraintIdx]->getLocStart(),
270 diag::warn_asm_mismatched_size_modifier);
271 }
272
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000273 // Validate tied input operands for type mismatches.
274 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
275 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
276
277 // If this is a tied constraint, verify that the output and input have
278 // either exactly the same type, or that they are int/ptr operands with the
279 // same size (int/long, int*/long, are ok etc).
280 if (!Info.hasTiedOperand()) continue;
281
282 unsigned TiedTo = Info.getTiedOperand();
283 unsigned InputOpNo = i+NumOutputs;
284 Expr *OutputExpr = Exprs[TiedTo];
285 Expr *InputExpr = Exprs[InputOpNo];
286
287 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
288 continue;
289
290 QualType InTy = InputExpr->getType();
291 QualType OutTy = OutputExpr->getType();
292 if (Context.hasSameType(InTy, OutTy))
293 continue; // All types can be tied to themselves.
294
295 // Decide if the input and output are in the same domain (integer/ptr or
296 // floating point.
297 enum AsmDomain {
298 AD_Int, AD_FP, AD_Other
299 } InputDomain, OutputDomain;
300
301 if (InTy->isIntegerType() || InTy->isPointerType())
302 InputDomain = AD_Int;
303 else if (InTy->isRealFloatingType())
304 InputDomain = AD_FP;
305 else
306 InputDomain = AD_Other;
307
308 if (OutTy->isIntegerType() || OutTy->isPointerType())
309 OutputDomain = AD_Int;
310 else if (OutTy->isRealFloatingType())
311 OutputDomain = AD_FP;
312 else
313 OutputDomain = AD_Other;
314
315 // They are ok if they are the same size and in the same domain. This
316 // allows tying things like:
317 // void* to int*
318 // void* to int if they are the same size.
319 // double to long double if they are the same size.
320 //
321 uint64_t OutSize = Context.getTypeSize(OutTy);
322 uint64_t InSize = Context.getTypeSize(InTy);
323 if (OutSize == InSize && InputDomain == OutputDomain &&
324 InputDomain != AD_Other)
325 continue;
326
327 // If the smaller input/output operand is not mentioned in the asm string,
328 // then we can promote the smaller one to a larger input and the asm string
329 // won't notice.
330 bool SmallerValueMentioned = false;
331
332 // If this is a reference to the input and if the input was the smaller
333 // one, then we have to reject this asm.
334 if (isOperandMentioned(InputOpNo, Pieces)) {
335 // This is a use in the asm string of the smaller operand. Since we
336 // codegen this by promoting to a wider value, the asm will get printed
337 // "wrong".
338 SmallerValueMentioned |= InSize < OutSize;
339 }
340 if (isOperandMentioned(TiedTo, Pieces)) {
341 // If this is a reference to the output, and if the output is the larger
342 // value, then it's ok because we'll promote the input to the larger type.
343 SmallerValueMentioned |= OutSize < InSize;
344 }
345
346 // If the smaller value wasn't mentioned in the asm string, and if the
347 // output was a register, just extend the shorter one to the size of the
348 // larger one.
349 if (!SmallerValueMentioned && InputDomain != AD_Other &&
350 OutputConstraintInfos[TiedTo].allowsRegister())
351 continue;
352
353 // Either both of the operands were mentioned or the smaller one was
354 // mentioned. One more special case that we'll allow: if the tied input is
355 // integer, unmentioned, and is a constant, then we'll allow truncating it
356 // down to the size of the destination.
357 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
358 !isOperandMentioned(InputOpNo, Pieces) &&
359 InputExpr->isEvaluatable(Context)) {
360 CastKind castKind =
361 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
362 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
363 Exprs[InputOpNo] = InputExpr;
364 NS->setInputExpr(i, InputExpr);
365 continue;
366 }
367
368 Diag(InputExpr->getLocStart(),
369 diag::err_asm_tying_incompatible_types)
370 << InTy << OutTy << OutputExpr->getSourceRange()
371 << InputExpr->getSourceRange();
372 return StmtError();
373 }
374
375 return Owned(NS);
376}
377
Chad Rosier358ab762012-08-22 21:08:06 +0000378// getSpelling - Get the spelling of the AsmTok token.
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000379static StringRef getSpelling(Sema &SemaRef, Token AsmTok) {
380 StringRef Asm;
381 SmallString<512> TokenBuf;
382 TokenBuf.resize(512);
383 bool StringInvalid = false;
384 Asm = SemaRef.PP.getSpelling(AsmTok, TokenBuf, &StringInvalid);
385 assert (!StringInvalid && "Expected valid string!");
386 return Asm;
387}
388
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000389// Build the inline assembly string. Returns true on error.
390static bool buildMSAsmString(Sema &SemaRef,
391 SourceLocation AsmLoc,
392 ArrayRef<Token> AsmToks,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000393 SmallVectorImpl<unsigned> &TokOffsets,
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000394 std::string &AsmString) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000395 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000396
397 SmallString<512> Asm;
398 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
Bob Wilson40d39e32012-09-24 19:57:55 +0000399 bool isNewAsm = ((i == 0) ||
400 AsmToks[i].isAtStartOfLine() ||
401 AsmToks[i].is(tok::kw_asm));
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000402 if (isNewAsm) {
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000403 if (i != 0)
404 Asm += "\n\t";
405
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000406 if (AsmToks[i].is(tok::kw_asm)) {
407 i++; // Skip __asm
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000408 if (i == e) {
409 SemaRef.Diag(AsmLoc, diag::err_asm_empty);
410 return true;
411 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000412
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000413 }
414 }
415
Chad Rosierb55e6022012-09-13 00:06:55 +0000416 if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000417 Asm += ' ';
Chad Rosier4de97162012-09-11 00:51:28 +0000418
419 StringRef Spelling = getSpelling(SemaRef, AsmToks[i]);
420 Asm += Spelling;
Eli Friedman5f1385b2012-10-23 02:43:30 +0000421 TokOffsets.push_back(Asm.size());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000422 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000423 AsmString = Asm.str();
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000424 return false;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000425}
426
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +0000427namespace {
428
Chad Rosier7fd00b12012-10-18 15:49:40 +0000429class MCAsmParserSemaCallbackImpl : public llvm::MCAsmParserSemaCallback {
Eli Friedman5f1385b2012-10-23 02:43:30 +0000430 Sema &SemaRef;
431 SourceLocation AsmLoc;
432 ArrayRef<Token> AsmToks;
433 ArrayRef<unsigned> TokOffsets;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000434
435public:
Eli Friedman5f1385b2012-10-23 02:43:30 +0000436 MCAsmParserSemaCallbackImpl(Sema &Ref, SourceLocation Loc,
437 ArrayRef<Token> Toks,
438 ArrayRef<unsigned> Offsets)
439 : SemaRef(Ref), AsmLoc(Loc), AsmToks(Toks), TokOffsets(Offsets) { }
Chad Rosier7fd00b12012-10-18 15:49:40 +0000440 ~MCAsmParserSemaCallbackImpl() {}
441
Chad Rosierb8b5cbc2013-01-17 19:21:24 +0000442 void *LookupInlineAsmIdentifier(StringRef Name, void *SrcLoc,
443 unsigned &Length, unsigned &Size,
444 unsigned &Type, bool &IsVarDecl){
Chad Rosier7fd00b12012-10-18 15:49:40 +0000445 SourceLocation Loc = SourceLocation::getFromPtrEncoding(SrcLoc);
Chad Rosierb8b5cbc2013-01-17 19:21:24 +0000446
447 NamedDecl *OpDecl = SemaRef.LookupInlineAsmIdentifier(Name, Loc, Length,
448 Size, Type,
Chad Rosier3973f282013-01-10 22:10:16 +0000449 IsVarDecl);
Chad Rosierd052ebf2012-10-18 19:39:37 +0000450 return static_cast<void *>(OpDecl);
Chad Rosier7fd00b12012-10-18 15:49:40 +0000451 }
Eli Friedman5f1385b2012-10-23 02:43:30 +0000452
Chad Rosier802f9372012-10-25 21:49:22 +0000453 bool LookupInlineAsmField(StringRef Base, StringRef Member,
454 unsigned &Offset) {
455 return SemaRef.LookupInlineAsmField(Base, Member, Offset, AsmLoc);
456 }
457
Eli Friedman5f1385b2012-10-23 02:43:30 +0000458 static void MSAsmDiagHandlerCallback(const llvm::SMDiagnostic &D,
459 void *Context) {
460 ((MCAsmParserSemaCallbackImpl*)Context)->MSAsmDiagHandler(D);
461 }
462 void MSAsmDiagHandler(const llvm::SMDiagnostic &D) {
463 // Compute an offset into the inline asm buffer.
464 // FIXME: This isn't right if .macro is involved (but hopefully, no
465 // real-world code does that).
466 const llvm::SourceMgr &LSM = *D.getSourceMgr();
467 const llvm::MemoryBuffer *LBuf =
468 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
469 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
470
471 // Figure out which token that offset points into.
472 const unsigned *OffsetPtr =
473 std::lower_bound(TokOffsets.begin(), TokOffsets.end(), Offset);
474 unsigned TokIndex = OffsetPtr - TokOffsets.begin();
475
476 // If we come up with an answer which seems sane, use it; otherwise,
477 // just point at the __asm keyword.
478 // FIXME: Assert the answer is sane once we handle .macro correctly.
479 SourceLocation Loc = AsmLoc;
480 if (TokIndex < AsmToks.size()) {
481 const Token *Tok = &AsmToks[TokIndex];
482 Loc = Tok->getLocation();
483 Loc = Loc.getLocWithOffset(Offset - (*OffsetPtr - Tok->getLength()));
484 }
485 SemaRef.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
486 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000487};
488
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +0000489}
490
Chad Rosierc337d142012-10-18 20:27:06 +0000491NamedDecl *Sema::LookupInlineAsmIdentifier(StringRef Name, SourceLocation Loc,
Chad Rosierb8b5cbc2013-01-17 19:21:24 +0000492 unsigned &Length, unsigned &Size,
493 unsigned &Type, bool &IsVarDecl) {
494 Length = 1;
Chad Rosierc337d142012-10-18 20:27:06 +0000495 Size = 0;
Chad Rosierb8b5cbc2013-01-17 19:21:24 +0000496 Type = 0;
Chad Rosier3973f282013-01-10 22:10:16 +0000497 IsVarDecl = false;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000498 LookupResult Result(*this, &Context.Idents.get(Name), Loc,
499 Sema::LookupOrdinaryName);
500
501 if (!LookupName(Result, getCurScope())) {
502 // If we don't find anything, return null; the AsmParser will assume
503 // it is a label of some sort.
504 return 0;
505 }
506
507 if (!Result.isSingleResult()) {
508 // FIXME: Diagnose result.
509 return 0;
510 }
511
512 NamedDecl *ND = Result.getFoundDecl();
513 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
Chad Rosier3973f282013-01-10 22:10:16 +0000514 if (VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Chad Rosierb8b5cbc2013-01-17 19:21:24 +0000515 Type = Context.getTypeInfo(Var->getType()).first;
516 QualType Ty = Var->getType();
517 if (Ty->isArrayType()) {
518 const ArrayType *ATy = Context.getAsArrayType(Ty);
519 Length = Type / Context.getTypeInfo(ATy->getElementType()).first;
520 Type /= Length; // Type is in terms of a single element.
521 }
522 Type /= 8; // Type is in terms of bits, but we want bytes.
523 Size = Length * Type;
Chad Rosier3973f282013-01-10 22:10:16 +0000524 IsVarDecl = true;
525 }
Chad Rosier7fd00b12012-10-18 15:49:40 +0000526 return ND;
527 }
528
529 // FIXME: Handle other kinds of results? (FieldDecl, etc.)
530 // FIXME: Diagnose if we find something we can't handle, like a typedef.
531 return 0;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000532}
Chad Rosier2735df22012-08-22 19:18:30 +0000533
Chad Rosier802f9372012-10-25 21:49:22 +0000534bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
535 unsigned &Offset, SourceLocation AsmLoc) {
536 Offset = 0;
537 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
538 LookupOrdinaryName);
539
540 if (!LookupName(BaseResult, getCurScope()))
541 return true;
542
543 if (!BaseResult.isSingleResult())
544 return true;
545
546 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
547 const RecordType *RT = 0;
548 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl)) {
549 RT = VD->getType()->getAs<RecordType>();
550 } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(FoundDecl)) {
551 RT = TD->getUnderlyingType()->getAs<RecordType>();
552 }
553 if (!RT)
554 return true;
555
556 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
557 return true;
558
559 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
560 LookupMemberName);
561
562 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
563 return true;
564
565 // FIXME: Handle IndirectFieldDecl?
566 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
567 if (!FD)
568 return true;
569
570 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
571 unsigned i = FD->getFieldIndex();
572 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
573 Offset = (unsigned)Result.getQuantity();
574
575 return false;
576}
577
Chad Rosierb55e6022012-09-13 00:06:55 +0000578StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
579 ArrayRef<Token> AsmToks,SourceLocation EndLoc) {
Chad Rosiere54cba12012-10-16 21:55:39 +0000580 SmallVector<IdentifierInfo*, 4> Names;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000581 SmallVector<StringRef, 4> ConstraintRefs;
Chad Rosiere54cba12012-10-16 21:55:39 +0000582 SmallVector<Expr*, 4> Exprs;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000583 SmallVector<StringRef, 4> ClobberRefs;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000584
Chad Rosierae073782013-01-24 20:24:34 +0000585 llvm::Triple TheTriple = Context.getTargetInfo().getTriple();
586 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
587 bool UnsupportedArch = ArchTy != llvm::Triple::x86 &&
588 ArchTy != llvm::Triple::x86_64;
589 if (UnsupportedArch)
590 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
591
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000592 // Empty asm statements don't need to instantiate the AsmParser, etc.
Chad Rosierae073782013-01-24 20:24:34 +0000593 if (UnsupportedArch || AsmToks.empty()) {
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000594 StringRef EmptyAsmStr;
595 MSAsmStmt *NS =
596 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
Chad Rosiere54cba12012-10-16 21:55:39 +0000597 /*IsVolatile*/ true, AsmToks, /*NumOutputs*/ 0,
Chad Rosier7fd00b12012-10-18 15:49:40 +0000598 /*NumInputs*/ 0, Names, ConstraintRefs, Exprs,
599 EmptyAsmStr, ClobberRefs, EndLoc);
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000600 return Owned(NS);
601 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000602
Chad Rosier7fd00b12012-10-18 15:49:40 +0000603 std::string AsmString;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000604 SmallVector<unsigned, 8> TokOffsets;
Eli Friedman5f1385b2012-10-23 02:43:30 +0000605 if (buildMSAsmString(*this, AsmLoc, AsmToks, TokOffsets, AsmString))
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000606 return StmtError();
Chad Rosier38c71d32012-08-21 21:56:39 +0000607
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000608 // Get the target specific parser.
609 std::string Error;
Chad Rosierae073782013-01-24 20:24:34 +0000610 const std::string &TT = TheTriple.getTriple();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000611 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
612
613 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
614 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
615 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
616 OwningPtr<llvm::MCSubtargetInfo>
617 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
618
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000619 llvm::SourceMgr SrcMgr;
620 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
621 llvm::MemoryBuffer *Buffer =
622 llvm::MemoryBuffer::getMemBuffer(AsmString, "<inline asm>");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000623
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000624 // Tell SrcMgr about this buffer, which is what the parser will pick up.
625 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000626
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000627 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
628 OwningPtr<llvm::MCAsmParser>
629 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
630 OwningPtr<llvm::MCTargetAsmParser>
631 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000632
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000633 // Get the instruction descriptor.
634 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
635 llvm::MCInstPrinter *IP =
636 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000637
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000638 // Change to the Intel dialect.
639 Parser->setAssemblerDialect(1);
640 Parser->setTargetParser(*TargetParser.get());
641 Parser->setParsingInlineAsm(true);
Chad Rosiercf81cd22012-10-19 17:58:45 +0000642 TargetParser->setParsingInlineAsm(true);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000643
Eli Friedman5f1385b2012-10-23 02:43:30 +0000644 MCAsmParserSemaCallbackImpl MCAPSI(*this, AsmLoc, AsmToks, TokOffsets);
Chad Rosier793c4052012-10-19 20:36:37 +0000645 TargetParser->setSemaCallback(&MCAPSI);
Eli Friedman5f1385b2012-10-23 02:43:30 +0000646 SrcMgr.setDiagHandler(MCAsmParserSemaCallbackImpl::MSAsmDiagHandlerCallback,
647 &MCAPSI);
Chad Rosier793c4052012-10-19 20:36:37 +0000648
Chad Rosier7fd00b12012-10-18 15:49:40 +0000649 unsigned NumOutputs;
650 unsigned NumInputs;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000651 std::string AsmStringIR;
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000652 SmallVector<std::pair<void *, bool>, 4> OpDecls;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000653 SmallVector<std::string, 4> Constraints;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000654 SmallVector<std::string, 4> Clobbers;
Jim Grosbachd6d864f2013-02-20 22:25:15 +0000655 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
Chad Rosierd052ebf2012-10-18 19:39:37 +0000656 NumOutputs, NumInputs, OpDecls, Constraints,
657 Clobbers, MII, IP, MCAPSI))
Chad Rosier7fd00b12012-10-18 15:49:40 +0000658 return StmtError();
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000659
Chad Rosier7fd00b12012-10-18 15:49:40 +0000660 // Build the vector of clobber StringRefs.
661 unsigned NumClobbers = Clobbers.size();
662 ClobberRefs.resize(NumClobbers);
663 for (unsigned i = 0; i != NumClobbers; ++i)
664 ClobberRefs[i] = StringRef(Clobbers[i]);
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000665
Chad Rosier7fd00b12012-10-18 15:49:40 +0000666 // Recast the void pointers and build the vector of constraint StringRefs.
667 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000668 Names.resize(NumExprs);
669 ConstraintRefs.resize(NumExprs);
670 Exprs.resize(NumExprs);
671 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000672 NamedDecl *OpDecl = static_cast<NamedDecl *>(OpDecls[i].first);
Chad Rosierd052ebf2012-10-18 19:39:37 +0000673 if (!OpDecl)
674 return StmtError();
675
676 DeclarationNameInfo NameInfo(OpDecl->getDeclName(), AsmLoc);
677 ExprResult OpExpr = BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo,
678 OpDecl);
679 if (OpExpr.isInvalid())
680 return StmtError();
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000681
Chad Rosier3973f282013-01-10 22:10:16 +0000682 // Need address of variable.
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000683 if (OpDecls[i].second)
684 OpExpr = BuildUnaryOp(getCurScope(), AsmLoc, clang::UO_AddrOf,
685 OpExpr.take());
686
Chad Rosierd052ebf2012-10-18 19:39:37 +0000687 Names[i] = OpDecl->getIdentifier();
Chad Rosier7fd00b12012-10-18 15:49:40 +0000688 ConstraintRefs[i] = StringRef(Constraints[i]);
Chad Rosierd052ebf2012-10-18 19:39:37 +0000689 Exprs[i] = OpExpr.take();
Chad Rosieracc22b62012-09-06 19:35:00 +0000690 }
Chad Rosierb55e6022012-09-13 00:06:55 +0000691
Chad Rosier7fd00b12012-10-18 15:49:40 +0000692 bool IsSimple = NumExprs > 0;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000693 MSAsmStmt *NS =
Chad Rosier7fd00b12012-10-18 15:49:40 +0000694 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
695 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
696 Names, ConstraintRefs, Exprs, AsmStringIR,
697 ClobberRefs, EndLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000698 return Owned(NS);
699}