blob: 8e6b81472f8710e36237f2cd9aeda47af6b15cef [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"
Chad Rosier802f9372012-10-25 21:49:22 +000019#include "clang/AST/RecordLayout.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000020#include "clang/AST/TypeLoc.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Basic/TargetInfo.h"
23#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"
29#include "llvm/MC/MCRegisterInfo.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/MC/MCSubtargetInfo.h"
32#include "llvm/MC/MCTargetAsmParser.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000033#include "llvm/MC/MCParser/MCAsmParser.h"
34#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);
182 }
183
184 // Check that the clobbers are valid.
185 for (unsigned i = 0; i != NumClobbers; i++) {
186 StringLiteral *Literal = Clobbers[i];
187 if (!Literal->isAscii())
188 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
189 << Literal->getSourceRange());
190
191 StringRef Clobber = Literal->getString();
192
193 if (!Context.getTargetInfo().isValidClobber(Clobber))
194 return StmtError(Diag(Literal->getLocStart(),
195 diag::err_asm_unknown_register_name) << Clobber);
196 }
197
Chad Rosierdf5faf52012-08-25 00:11:56 +0000198 GCCAsmStmt *NS =
199 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
200 NumInputs, Names, Constraints, Exprs, AsmString,
201 NumClobbers, Clobbers, RParenLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000202 // Validate the asm string, ensuring it makes sense given the operands we
203 // have.
Chad Rosierdf5faf52012-08-25 00:11:56 +0000204 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000205 unsigned DiagOffs;
206 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
207 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
208 << AsmString->getSourceRange();
209 return StmtError();
210 }
211
212 // Validate tied input operands for type mismatches.
213 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
214 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
215
216 // If this is a tied constraint, verify that the output and input have
217 // either exactly the same type, or that they are int/ptr operands with the
218 // same size (int/long, int*/long, are ok etc).
219 if (!Info.hasTiedOperand()) continue;
220
221 unsigned TiedTo = Info.getTiedOperand();
222 unsigned InputOpNo = i+NumOutputs;
223 Expr *OutputExpr = Exprs[TiedTo];
224 Expr *InputExpr = Exprs[InputOpNo];
225
226 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
227 continue;
228
229 QualType InTy = InputExpr->getType();
230 QualType OutTy = OutputExpr->getType();
231 if (Context.hasSameType(InTy, OutTy))
232 continue; // All types can be tied to themselves.
233
234 // Decide if the input and output are in the same domain (integer/ptr or
235 // floating point.
236 enum AsmDomain {
237 AD_Int, AD_FP, AD_Other
238 } InputDomain, OutputDomain;
239
240 if (InTy->isIntegerType() || InTy->isPointerType())
241 InputDomain = AD_Int;
242 else if (InTy->isRealFloatingType())
243 InputDomain = AD_FP;
244 else
245 InputDomain = AD_Other;
246
247 if (OutTy->isIntegerType() || OutTy->isPointerType())
248 OutputDomain = AD_Int;
249 else if (OutTy->isRealFloatingType())
250 OutputDomain = AD_FP;
251 else
252 OutputDomain = AD_Other;
253
254 // They are ok if they are the same size and in the same domain. This
255 // allows tying things like:
256 // void* to int*
257 // void* to int if they are the same size.
258 // double to long double if they are the same size.
259 //
260 uint64_t OutSize = Context.getTypeSize(OutTy);
261 uint64_t InSize = Context.getTypeSize(InTy);
262 if (OutSize == InSize && InputDomain == OutputDomain &&
263 InputDomain != AD_Other)
264 continue;
265
266 // If the smaller input/output operand is not mentioned in the asm string,
267 // then we can promote the smaller one to a larger input and the asm string
268 // won't notice.
269 bool SmallerValueMentioned = false;
270
271 // If this is a reference to the input and if the input was the smaller
272 // one, then we have to reject this asm.
273 if (isOperandMentioned(InputOpNo, Pieces)) {
274 // This is a use in the asm string of the smaller operand. Since we
275 // codegen this by promoting to a wider value, the asm will get printed
276 // "wrong".
277 SmallerValueMentioned |= InSize < OutSize;
278 }
279 if (isOperandMentioned(TiedTo, Pieces)) {
280 // If this is a reference to the output, and if the output is the larger
281 // value, then it's ok because we'll promote the input to the larger type.
282 SmallerValueMentioned |= OutSize < InSize;
283 }
284
285 // If the smaller value wasn't mentioned in the asm string, and if the
286 // output was a register, just extend the shorter one to the size of the
287 // larger one.
288 if (!SmallerValueMentioned && InputDomain != AD_Other &&
289 OutputConstraintInfos[TiedTo].allowsRegister())
290 continue;
291
292 // Either both of the operands were mentioned or the smaller one was
293 // mentioned. One more special case that we'll allow: if the tied input is
294 // integer, unmentioned, and is a constant, then we'll allow truncating it
295 // down to the size of the destination.
296 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
297 !isOperandMentioned(InputOpNo, Pieces) &&
298 InputExpr->isEvaluatable(Context)) {
299 CastKind castKind =
300 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
301 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
302 Exprs[InputOpNo] = InputExpr;
303 NS->setInputExpr(i, InputExpr);
304 continue;
305 }
306
307 Diag(InputExpr->getLocStart(),
308 diag::err_asm_tying_incompatible_types)
309 << InTy << OutTy << OutputExpr->getSourceRange()
310 << InputExpr->getSourceRange();
311 return StmtError();
312 }
313
314 return Owned(NS);
315}
316
Chad Rosier358ab762012-08-22 21:08:06 +0000317// getSpelling - Get the spelling of the AsmTok token.
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000318static StringRef getSpelling(Sema &SemaRef, Token AsmTok) {
319 StringRef Asm;
320 SmallString<512> TokenBuf;
321 TokenBuf.resize(512);
322 bool StringInvalid = false;
323 Asm = SemaRef.PP.getSpelling(AsmTok, TokenBuf, &StringInvalid);
324 assert (!StringInvalid && "Expected valid string!");
325 return Asm;
326}
327
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000328// Build the inline assembly string. Returns true on error.
329static bool buildMSAsmString(Sema &SemaRef,
330 SourceLocation AsmLoc,
331 ArrayRef<Token> AsmToks,
Eli Friedman5f1385b2012-10-23 02:43:30 +0000332 llvm::SmallVectorImpl<unsigned> &TokOffsets,
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000333 std::string &AsmString) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000334 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000335
336 SmallString<512> Asm;
337 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
Bob Wilson40d39e32012-09-24 19:57:55 +0000338 bool isNewAsm = ((i == 0) ||
339 AsmToks[i].isAtStartOfLine() ||
340 AsmToks[i].is(tok::kw_asm));
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000341 if (isNewAsm) {
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000342 if (i != 0)
343 Asm += "\n\t";
344
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000345 if (AsmToks[i].is(tok::kw_asm)) {
346 i++; // Skip __asm
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000347 if (i == e) {
348 SemaRef.Diag(AsmLoc, diag::err_asm_empty);
349 return true;
350 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000351
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000352 }
353 }
354
Chad Rosierb55e6022012-09-13 00:06:55 +0000355 if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000356 Asm += ' ';
Chad Rosier4de97162012-09-11 00:51:28 +0000357
358 StringRef Spelling = getSpelling(SemaRef, AsmToks[i]);
359 Asm += Spelling;
Eli Friedman5f1385b2012-10-23 02:43:30 +0000360 TokOffsets.push_back(Asm.size());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000361 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000362 AsmString = Asm.str();
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000363 return false;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000364}
365
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +0000366namespace {
367
Chad Rosier7fd00b12012-10-18 15:49:40 +0000368class MCAsmParserSemaCallbackImpl : public llvm::MCAsmParserSemaCallback {
Eli Friedman5f1385b2012-10-23 02:43:30 +0000369 Sema &SemaRef;
370 SourceLocation AsmLoc;
371 ArrayRef<Token> AsmToks;
372 ArrayRef<unsigned> TokOffsets;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000373
374public:
Eli Friedman5f1385b2012-10-23 02:43:30 +0000375 MCAsmParserSemaCallbackImpl(Sema &Ref, SourceLocation Loc,
376 ArrayRef<Token> Toks,
377 ArrayRef<unsigned> Offsets)
378 : SemaRef(Ref), AsmLoc(Loc), AsmToks(Toks), TokOffsets(Offsets) { }
Chad Rosier7fd00b12012-10-18 15:49:40 +0000379 ~MCAsmParserSemaCallbackImpl() {}
380
Chad Rosierc337d142012-10-18 20:27:06 +0000381 void *LookupInlineAsmIdentifier(StringRef Name, void *SrcLoc, unsigned &Size){
Chad Rosier7fd00b12012-10-18 15:49:40 +0000382 SourceLocation Loc = SourceLocation::getFromPtrEncoding(SrcLoc);
Eli Friedman5f1385b2012-10-23 02:43:30 +0000383 NamedDecl *OpDecl = SemaRef.LookupInlineAsmIdentifier(Name, Loc, Size);
Chad Rosierd052ebf2012-10-18 19:39:37 +0000384 return static_cast<void *>(OpDecl);
Chad Rosier7fd00b12012-10-18 15:49:40 +0000385 }
Eli Friedman5f1385b2012-10-23 02:43:30 +0000386
Chad Rosier802f9372012-10-25 21:49:22 +0000387 bool LookupInlineAsmField(StringRef Base, StringRef Member,
388 unsigned &Offset) {
389 return SemaRef.LookupInlineAsmField(Base, Member, Offset, AsmLoc);
390 }
391
Eli Friedman5f1385b2012-10-23 02:43:30 +0000392 static void MSAsmDiagHandlerCallback(const llvm::SMDiagnostic &D,
393 void *Context) {
394 ((MCAsmParserSemaCallbackImpl*)Context)->MSAsmDiagHandler(D);
395 }
396 void MSAsmDiagHandler(const llvm::SMDiagnostic &D) {
397 // Compute an offset into the inline asm buffer.
398 // FIXME: This isn't right if .macro is involved (but hopefully, no
399 // real-world code does that).
400 const llvm::SourceMgr &LSM = *D.getSourceMgr();
401 const llvm::MemoryBuffer *LBuf =
402 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
403 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
404
405 // Figure out which token that offset points into.
406 const unsigned *OffsetPtr =
407 std::lower_bound(TokOffsets.begin(), TokOffsets.end(), Offset);
408 unsigned TokIndex = OffsetPtr - TokOffsets.begin();
409
410 // If we come up with an answer which seems sane, use it; otherwise,
411 // just point at the __asm keyword.
412 // FIXME: Assert the answer is sane once we handle .macro correctly.
413 SourceLocation Loc = AsmLoc;
414 if (TokIndex < AsmToks.size()) {
415 const Token *Tok = &AsmToks[TokIndex];
416 Loc = Tok->getLocation();
417 Loc = Loc.getLocWithOffset(Offset - (*OffsetPtr - Tok->getLength()));
418 }
419 SemaRef.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
420 }
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000421};
422
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +0000423}
424
Chad Rosierc337d142012-10-18 20:27:06 +0000425NamedDecl *Sema::LookupInlineAsmIdentifier(StringRef Name, SourceLocation Loc,
426 unsigned &Size) {
427 Size = 0;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000428 LookupResult Result(*this, &Context.Idents.get(Name), Loc,
429 Sema::LookupOrdinaryName);
430
431 if (!LookupName(Result, getCurScope())) {
432 // If we don't find anything, return null; the AsmParser will assume
433 // it is a label of some sort.
434 return 0;
435 }
436
437 if (!Result.isSingleResult()) {
438 // FIXME: Diagnose result.
439 return 0;
440 }
441
442 NamedDecl *ND = Result.getFoundDecl();
443 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
Chad Rosierc337d142012-10-18 20:27:06 +0000444 if (VarDecl *Var = dyn_cast<VarDecl>(ND))
445 Size = Context.getTypeInfo(Var->getType()).first;
446
Chad Rosier7fd00b12012-10-18 15:49:40 +0000447 return ND;
448 }
449
450 // FIXME: Handle other kinds of results? (FieldDecl, etc.)
451 // FIXME: Diagnose if we find something we can't handle, like a typedef.
452 return 0;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000453}
Chad Rosier2735df22012-08-22 19:18:30 +0000454
Chad Rosier802f9372012-10-25 21:49:22 +0000455bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
456 unsigned &Offset, SourceLocation AsmLoc) {
457 Offset = 0;
458 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
459 LookupOrdinaryName);
460
461 if (!LookupName(BaseResult, getCurScope()))
462 return true;
463
464 if (!BaseResult.isSingleResult())
465 return true;
466
467 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
468 const RecordType *RT = 0;
469 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl)) {
470 RT = VD->getType()->getAs<RecordType>();
471 } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(FoundDecl)) {
472 RT = TD->getUnderlyingType()->getAs<RecordType>();
473 }
474 if (!RT)
475 return true;
476
477 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
478 return true;
479
480 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
481 LookupMemberName);
482
483 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
484 return true;
485
486 // FIXME: Handle IndirectFieldDecl?
487 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
488 if (!FD)
489 return true;
490
491 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
492 unsigned i = FD->getFieldIndex();
493 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
494 Offset = (unsigned)Result.getQuantity();
495
496 return false;
497}
498
Chad Rosierb55e6022012-09-13 00:06:55 +0000499StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
500 ArrayRef<Token> AsmToks,SourceLocation EndLoc) {
Chad Rosiere54cba12012-10-16 21:55:39 +0000501 SmallVector<IdentifierInfo*, 4> Names;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000502 SmallVector<StringRef, 4> ConstraintRefs;
Chad Rosiere54cba12012-10-16 21:55:39 +0000503 SmallVector<Expr*, 4> Exprs;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000504 SmallVector<StringRef, 4> ClobberRefs;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000505
506 // Empty asm statements don't need to instantiate the AsmParser, etc.
Chad Rosier7fd00b12012-10-18 15:49:40 +0000507 if (AsmToks.empty()) {
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000508 StringRef EmptyAsmStr;
509 MSAsmStmt *NS =
510 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
Chad Rosiere54cba12012-10-16 21:55:39 +0000511 /*IsVolatile*/ true, AsmToks, /*NumOutputs*/ 0,
Chad Rosier7fd00b12012-10-18 15:49:40 +0000512 /*NumInputs*/ 0, Names, ConstraintRefs, Exprs,
513 EmptyAsmStr, ClobberRefs, EndLoc);
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000514 return Owned(NS);
515 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000516
Chad Rosier7fd00b12012-10-18 15:49:40 +0000517 std::string AsmString;
Eli Friedman5f1385b2012-10-23 02:43:30 +0000518 llvm::SmallVector<unsigned, 8> TokOffsets;
519 if (buildMSAsmString(*this, AsmLoc, AsmToks, TokOffsets, AsmString))
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000520 return StmtError();
Chad Rosier38c71d32012-08-21 21:56:39 +0000521
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000522 // Get the target specific parser.
523 std::string Error;
524 const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
525 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
526
527 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
528 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
529 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
530 OwningPtr<llvm::MCSubtargetInfo>
531 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
532
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000533 llvm::SourceMgr SrcMgr;
534 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
535 llvm::MemoryBuffer *Buffer =
536 llvm::MemoryBuffer::getMemBuffer(AsmString, "<inline asm>");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000537
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000538 // Tell SrcMgr about this buffer, which is what the parser will pick up.
539 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000540
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000541 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
542 OwningPtr<llvm::MCAsmParser>
543 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
544 OwningPtr<llvm::MCTargetAsmParser>
545 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000546
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000547 // Get the instruction descriptor.
548 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
549 llvm::MCInstPrinter *IP =
550 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000551
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000552 // Change to the Intel dialect.
553 Parser->setAssemblerDialect(1);
554 Parser->setTargetParser(*TargetParser.get());
555 Parser->setParsingInlineAsm(true);
Chad Rosiercf81cd22012-10-19 17:58:45 +0000556 TargetParser->setParsingInlineAsm(true);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000557
Eli Friedman5f1385b2012-10-23 02:43:30 +0000558 MCAsmParserSemaCallbackImpl MCAPSI(*this, AsmLoc, AsmToks, TokOffsets);
Chad Rosier793c4052012-10-19 20:36:37 +0000559 TargetParser->setSemaCallback(&MCAPSI);
Eli Friedman5f1385b2012-10-23 02:43:30 +0000560 SrcMgr.setDiagHandler(MCAsmParserSemaCallbackImpl::MSAsmDiagHandlerCallback,
561 &MCAPSI);
Chad Rosier793c4052012-10-19 20:36:37 +0000562
Chad Rosier7fd00b12012-10-18 15:49:40 +0000563 unsigned NumOutputs;
564 unsigned NumInputs;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000565 std::string AsmStringIR;
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000566 SmallVector<std::pair<void *, bool>, 4> OpDecls;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000567 SmallVector<std::string, 4> Constraints;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000568 SmallVector<std::string, 4> Clobbers;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000569 if (Parser->ParseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
Chad Rosierd052ebf2012-10-18 19:39:37 +0000570 NumOutputs, NumInputs, OpDecls, Constraints,
571 Clobbers, MII, IP, MCAPSI))
Chad Rosier7fd00b12012-10-18 15:49:40 +0000572 return StmtError();
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000573
Chad Rosier7fd00b12012-10-18 15:49:40 +0000574 // Build the vector of clobber StringRefs.
575 unsigned NumClobbers = Clobbers.size();
576 ClobberRefs.resize(NumClobbers);
577 for (unsigned i = 0; i != NumClobbers; ++i)
578 ClobberRefs[i] = StringRef(Clobbers[i]);
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000579
Chad Rosier7fd00b12012-10-18 15:49:40 +0000580 // Recast the void pointers and build the vector of constraint StringRefs.
581 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000582 Names.resize(NumExprs);
583 ConstraintRefs.resize(NumExprs);
584 Exprs.resize(NumExprs);
585 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000586 NamedDecl *OpDecl = static_cast<NamedDecl *>(OpDecls[i].first);
Chad Rosierd052ebf2012-10-18 19:39:37 +0000587 if (!OpDecl)
588 return StmtError();
589
590 DeclarationNameInfo NameInfo(OpDecl->getDeclName(), AsmLoc);
591 ExprResult OpExpr = BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo,
592 OpDecl);
593 if (OpExpr.isInvalid())
594 return StmtError();
Chad Rosier4d5dd7c2012-10-23 17:44:40 +0000595
596 // Need offset of variable.
597 if (OpDecls[i].second)
598 OpExpr = BuildUnaryOp(getCurScope(), AsmLoc, clang::UO_AddrOf,
599 OpExpr.take());
600
Chad Rosierd052ebf2012-10-18 19:39:37 +0000601 Names[i] = OpDecl->getIdentifier();
Chad Rosier7fd00b12012-10-18 15:49:40 +0000602 ConstraintRefs[i] = StringRef(Constraints[i]);
Chad Rosierd052ebf2012-10-18 19:39:37 +0000603 Exprs[i] = OpExpr.take();
Chad Rosieracc22b62012-09-06 19:35:00 +0000604 }
Chad Rosierb55e6022012-09-13 00:06:55 +0000605
Chad Rosier7fd00b12012-10-18 15:49:40 +0000606 bool IsSimple = NumExprs > 0;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000607 MSAsmStmt *NS =
Chad Rosier7fd00b12012-10-18 15:49:40 +0000608 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
609 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
610 Names, ConstraintRefs, Exprs, AsmStringIR,
611 ClobberRefs, EndLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000612 return Owned(NS);
613}