blob: 0d32581e8daa8adf63b0f8f2482b311b485dc52f [file] [log] [blame]
Chad Rosier571c5e92012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier0731aff2012-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 Rosier5c563642012-10-25 21:49:22 +000015#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000016#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000017#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000018#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/BitVector.h"
Alp Toker10399272014-06-08 05:11:37 +000025#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000026using namespace clang;
27using namespace sema;
28
29/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
30/// ignore "noop" casts in places where an lvalue is required by an inline asm.
31/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
32/// provide a strong guidance to not use it.
33///
34/// This method checks to see if the argument is an acceptable l-value and
35/// returns false if it is a case we can handle.
36static bool CheckAsmLValue(const Expr *E, Sema &S) {
37 // Type dependent expressions will be checked during instantiation.
38 if (E->isTypeDependent())
39 return false;
40
41 if (E->isLValue())
42 return false; // Cool, this is an lvalue.
43
44 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
45 // are supposed to allow.
46 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
47 if (E != E2 && E2->isLValue()) {
48 if (!S.getLangOpts().HeinousExtensions)
49 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
50 << E->getSourceRange();
51 else
52 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
53 << E->getSourceRange();
54 // Accept, even if we emitted an error diagnostic.
55 return false;
56 }
57
58 // None of the above, just randomly invalid non-lvalue.
59 return true;
60}
61
62/// isOperandMentioned - Return true if the specified operand # is mentioned
63/// anywhere in the decomposed asm string.
64static bool isOperandMentioned(unsigned OpNo,
Chad Rosierde70e0e2012-08-25 00:11:56 +000065 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +000066 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +000067 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier0731aff2012-08-17 21:19:40 +000068 if (!Piece.isOperand()) continue;
69
70 // If this is a reference to the input and if the input was the smaller
71 // one, then we have to reject this asm.
72 if (Piece.getOperandNo() == OpNo)
73 return true;
74 }
75 return false;
76}
77
Hans Wennborge9d240a2014-10-08 01:58:02 +000078static bool CheckNakedParmReference(Expr *E, Sema &S) {
79 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
80 if (!Func)
81 return false;
82 if (!Func->hasAttr<NakedAttr>())
83 return false;
84
85 SmallVector<Expr*, 4> WorkList;
86 WorkList.push_back(E);
87 while (WorkList.size()) {
88 Expr *E = WorkList.pop_back_val();
89 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
90 if (isa<ParmVarDecl>(DRE->getDecl())) {
91 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
95 }
96 for (Stmt *Child : E->children()) {
97 if (Expr *E = dyn_cast_or_null<Expr>(Child))
98 WorkList.push_back(E);
99 }
100 }
101 return false;
102}
103
Chad Rosierde70e0e2012-08-25 00:11:56 +0000104StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
105 bool IsVolatile, unsigned NumOutputs,
106 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000107 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000108 Expr *asmString, MultiExprArg clobbers,
109 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000110 unsigned NumClobbers = clobbers.size();
111 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000112 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000113 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000114 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000115
116 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
117
118 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000119 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000120
121 for (unsigned i = 0; i != NumOutputs; i++) {
122 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000123 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000124
125 StringRef OutputName;
126 if (Names[i])
127 OutputName = Names[i]->getName();
128
129 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
130 if (!Context.getTargetInfo().validateOutputConstraint(Info))
131 return StmtError(Diag(Literal->getLocStart(),
132 diag::err_asm_invalid_output_constraint)
133 << Info.getConstraintStr());
134
David Majnemer0f4d6412014-12-29 09:30:33 +0000135 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
136 if (ER.isInvalid())
137 return StmtError();
138 Exprs[i] = ER.get();
139
Chad Rosier0731aff2012-08-17 21:19:40 +0000140 // Check that the output exprs are valid lvalues.
141 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000142
Hans Wennborge9d240a2014-10-08 01:58:02 +0000143 // Referring to parameters is not allowed in naked functions.
144 if (CheckNakedParmReference(OutputExpr, *this))
145 return StmtError();
146
Chad Rosier0731aff2012-08-17 21:19:40 +0000147 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000148
David Majnemer0f4d6412014-12-29 09:30:33 +0000149 // If this is dependent, just continue.
150 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000151 continue;
152
David Majnemer0f4d6412014-12-29 09:30:33 +0000153 Expr::isModifiableLvalueResult IsLV =
154 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
155 switch (IsLV) {
156 case Expr::MLV_Valid:
157 // Cool, this is an lvalue.
158 break;
David Majnemer04b78412014-12-29 10:29:53 +0000159 case Expr::MLV_ArrayType:
160 // This is OK too.
161 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000162 case Expr::MLV_LValueCast: {
163 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
164 if (!getLangOpts().HeinousExtensions) {
165 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
166 << OutputExpr->getSourceRange();
167 } else {
168 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
169 << OutputExpr->getSourceRange();
170 }
171 // Accept, even if we emitted an error diagnostic.
172 break;
173 }
174 case Expr::MLV_IncompleteType:
175 case Expr::MLV_IncompleteVoidType:
176 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
177 diag::err_dereference_incomplete_type))
178 return StmtError();
179 default:
180 return StmtError(Diag(OutputExpr->getLocStart(),
181 diag::err_asm_invalid_lvalue_in_output)
182 << OutputExpr->getSourceRange());
183 }
184
185 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000186 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
187 Size))
188 return StmtError(Diag(OutputExpr->getLocStart(),
189 diag::err_asm_invalid_output_size)
190 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000191 }
192
193 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
194
195 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
196 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000197 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000198
199 StringRef InputName;
200 if (Names[i])
201 InputName = Names[i]->getName();
202
203 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
204 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
205 NumOutputs, Info)) {
206 return StmtError(Diag(Literal->getLocStart(),
207 diag::err_asm_invalid_input_constraint)
208 << Info.getConstraintStr());
209 }
210
David Majnemer0f4d6412014-12-29 09:30:33 +0000211 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
212 if (ER.isInvalid())
213 return StmtError();
214 Exprs[i] = ER.get();
215
Chad Rosier0731aff2012-08-17 21:19:40 +0000216 Expr *InputExpr = Exprs[i];
217
Hans Wennborge9d240a2014-10-08 01:58:02 +0000218 // Referring to parameters is not allowed in naked functions.
219 if (CheckNakedParmReference(InputExpr, *this))
220 return StmtError();
221
Chad Rosier0731aff2012-08-17 21:19:40 +0000222 // Only allow void types for memory constraints.
223 if (Info.allowsMemory() && !Info.allowsRegister()) {
224 if (CheckAsmLValue(InputExpr, *this))
225 return StmtError(Diag(InputExpr->getLocStart(),
226 diag::err_asm_invalid_lvalue_in_input)
227 << Info.getConstraintStr()
228 << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000229 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
230 llvm::APSInt Result;
231 if (!InputExpr->EvaluateAsInt(Result, Context))
232 return StmtError(
Joerg Sonnenbergera43872c2015-01-22 21:01:00 +0000233 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
234 << Info.getConstraintStr() << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000235 if (Result.slt(Info.getImmConstantMin()) ||
236 Result.sgt(Info.getImmConstantMax()))
237 return StmtError(Diag(InputExpr->getLocStart(),
238 diag::err_invalid_asm_value_for_constraint)
239 << Result.toString(10) << Info.getConstraintStr()
240 << InputExpr->getSourceRange());
241
David Majnemerade4bee2014-07-14 16:27:53 +0000242 } else {
243 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
244 if (Result.isInvalid())
245 return StmtError();
246
247 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000248 }
249
250 if (Info.allowsRegister()) {
251 if (InputExpr->getType()->isVoidType()) {
252 return StmtError(Diag(InputExpr->getLocStart(),
253 diag::err_asm_invalid_type_in_input)
254 << InputExpr->getType() << Info.getConstraintStr()
255 << InputExpr->getSourceRange());
256 }
257 }
258
Chad Rosier0731aff2012-08-17 21:19:40 +0000259 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000260
261 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000262 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000263 continue;
264
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000265 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingb68b7572013-03-27 06:06:26 +0000266 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
267 diag::err_dereference_incomplete_type))
268 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000269
Bill Wendling887b4852012-11-12 06:42:51 +0000270 unsigned Size = Context.getTypeSize(Ty);
271 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
272 Size))
273 return StmtError(Diag(InputExpr->getLocStart(),
274 diag::err_asm_invalid_input_size)
275 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000276 }
277
278 // Check that the clobbers are valid.
279 for (unsigned i = 0; i != NumClobbers; i++) {
280 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000281 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000282
283 StringRef Clobber = Literal->getString();
284
285 if (!Context.getTargetInfo().isValidClobber(Clobber))
286 return StmtError(Diag(Literal->getLocStart(),
287 diag::err_asm_unknown_register_name) << Clobber);
288 }
289
Chad Rosierde70e0e2012-08-25 00:11:56 +0000290 GCCAsmStmt *NS =
291 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000292 NumInputs, Names, Constraints, Exprs.data(),
293 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000294 // Validate the asm string, ensuring it makes sense given the operands we
295 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000296 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000297 unsigned DiagOffs;
298 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
299 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
300 << AsmString->getSourceRange();
301 return StmtError();
302 }
303
Bill Wendling9d1ee112012-10-25 23:28:48 +0000304 // Validate constraints and modifiers.
305 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
306 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
307 if (!Piece.isOperand()) continue;
308
309 // Look for the correct constraint index.
310 unsigned Idx = 0;
311 unsigned ConstraintIdx = 0;
312 for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
313 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
314 if (Idx == Piece.getOperandNo())
315 break;
316 ++Idx;
317
318 if (Info.isReadWrite()) {
319 if (Idx == Piece.getOperandNo())
320 break;
321 ++Idx;
322 }
323 }
324
325 for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
326 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
327 if (Idx == Piece.getOperandNo())
328 break;
329 ++Idx;
330
331 if (Info.isReadWrite()) {
332 if (Idx == Piece.getOperandNo())
333 break;
334 ++Idx;
335 }
336 }
337
338 // Now that we have the right indexes go ahead and check.
339 StringLiteral *Literal = Constraints[ConstraintIdx];
340 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
341 if (Ty->isDependentType() || Ty->isIncompleteType())
342 continue;
343
344 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000345 std::string SuggestedModifier;
346 if (!Context.getTargetInfo().validateConstraintModifier(
347 Literal->getString(), Piece.getModifier(), Size,
348 SuggestedModifier)) {
Bill Wendling9d1ee112012-10-25 23:28:48 +0000349 Diag(Exprs[ConstraintIdx]->getLocStart(),
350 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000351
352 if (!SuggestedModifier.empty()) {
353 auto B = Diag(Piece.getRange().getBegin(),
354 diag::note_asm_missing_constraint_modifier)
355 << SuggestedModifier;
356 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
357 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
358 SuggestedModifier));
359 }
360 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000361 }
362
Chad Rosier0731aff2012-08-17 21:19:40 +0000363 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000364 unsigned NumAlternatives = ~0U;
365 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
366 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
367 StringRef ConstraintStr = Info.getConstraintStr();
368 unsigned AltCount = ConstraintStr.count(',') + 1;
369 if (NumAlternatives == ~0U)
370 NumAlternatives = AltCount;
371 else if (NumAlternatives != AltCount)
372 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
373 diag::err_asm_unexpected_constraint_alternatives)
374 << NumAlternatives << AltCount);
375 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000376 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
377 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000378 StringRef ConstraintStr = Info.getConstraintStr();
379 unsigned AltCount = ConstraintStr.count(',') + 1;
380 if (NumAlternatives == ~0U)
381 NumAlternatives = AltCount;
382 else if (NumAlternatives != AltCount)
383 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
384 diag::err_asm_unexpected_constraint_alternatives)
385 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000386
387 // If this is a tied constraint, verify that the output and input have
388 // either exactly the same type, or that they are int/ptr operands with the
389 // same size (int/long, int*/long, are ok etc).
390 if (!Info.hasTiedOperand()) continue;
391
392 unsigned TiedTo = Info.getTiedOperand();
393 unsigned InputOpNo = i+NumOutputs;
394 Expr *OutputExpr = Exprs[TiedTo];
395 Expr *InputExpr = Exprs[InputOpNo];
396
397 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
398 continue;
399
400 QualType InTy = InputExpr->getType();
401 QualType OutTy = OutputExpr->getType();
402 if (Context.hasSameType(InTy, OutTy))
403 continue; // All types can be tied to themselves.
404
405 // Decide if the input and output are in the same domain (integer/ptr or
406 // floating point.
407 enum AsmDomain {
408 AD_Int, AD_FP, AD_Other
409 } InputDomain, OutputDomain;
410
411 if (InTy->isIntegerType() || InTy->isPointerType())
412 InputDomain = AD_Int;
413 else if (InTy->isRealFloatingType())
414 InputDomain = AD_FP;
415 else
416 InputDomain = AD_Other;
417
418 if (OutTy->isIntegerType() || OutTy->isPointerType())
419 OutputDomain = AD_Int;
420 else if (OutTy->isRealFloatingType())
421 OutputDomain = AD_FP;
422 else
423 OutputDomain = AD_Other;
424
425 // They are ok if they are the same size and in the same domain. This
426 // allows tying things like:
427 // void* to int*
428 // void* to int if they are the same size.
429 // double to long double if they are the same size.
430 //
431 uint64_t OutSize = Context.getTypeSize(OutTy);
432 uint64_t InSize = Context.getTypeSize(InTy);
433 if (OutSize == InSize && InputDomain == OutputDomain &&
434 InputDomain != AD_Other)
435 continue;
436
437 // If the smaller input/output operand is not mentioned in the asm string,
438 // then we can promote the smaller one to a larger input and the asm string
439 // won't notice.
440 bool SmallerValueMentioned = false;
441
442 // If this is a reference to the input and if the input was the smaller
443 // one, then we have to reject this asm.
444 if (isOperandMentioned(InputOpNo, Pieces)) {
445 // This is a use in the asm string of the smaller operand. Since we
446 // codegen this by promoting to a wider value, the asm will get printed
447 // "wrong".
448 SmallerValueMentioned |= InSize < OutSize;
449 }
450 if (isOperandMentioned(TiedTo, Pieces)) {
451 // If this is a reference to the output, and if the output is the larger
452 // value, then it's ok because we'll promote the input to the larger type.
453 SmallerValueMentioned |= OutSize < InSize;
454 }
455
456 // If the smaller value wasn't mentioned in the asm string, and if the
457 // output was a register, just extend the shorter one to the size of the
458 // larger one.
459 if (!SmallerValueMentioned && InputDomain != AD_Other &&
460 OutputConstraintInfos[TiedTo].allowsRegister())
461 continue;
462
463 // Either both of the operands were mentioned or the smaller one was
464 // mentioned. One more special case that we'll allow: if the tied input is
465 // integer, unmentioned, and is a constant, then we'll allow truncating it
466 // down to the size of the destination.
467 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
468 !isOperandMentioned(InputOpNo, Pieces) &&
469 InputExpr->isEvaluatable(Context)) {
470 CastKind castKind =
471 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000472 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000473 Exprs[InputOpNo] = InputExpr;
474 NS->setInputExpr(i, InputExpr);
475 continue;
476 }
477
478 Diag(InputExpr->getLocStart(),
479 diag::err_asm_tying_incompatible_types)
480 << InTy << OutTy << OutputExpr->getSourceRange()
481 << InputExpr->getSourceRange();
482 return StmtError();
483 }
484
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000485 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000486}
487
John McCallf413f5e2013-05-03 00:10:13 +0000488ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
489 SourceLocation TemplateKWLoc,
490 UnqualifiedId &Id,
Alp Toker10399272014-06-08 05:11:37 +0000491 llvm::InlineAsmIdentifierInfo &Info,
John McCallf413f5e2013-05-03 00:10:13 +0000492 bool IsUnevaluatedContext) {
Chad Rosierb18a2852013-04-22 17:01:37 +0000493 Info.clear();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000494
John McCallf413f5e2013-05-03 00:10:13 +0000495 if (IsUnevaluatedContext)
496 PushExpressionEvaluationContext(UnevaluatedAbstract,
497 ReuseLambdaContextDecl);
498
499 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
500 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000501 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000502 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000503 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000504
505 if (IsUnevaluatedContext)
506 PopExpressionEvaluationContext();
507
508 if (!Result.isUsable()) return Result;
509
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000510 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000511 if (!Result.isUsable()) return Result;
512
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000513 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000514 if (CheckNakedParmReference(Result.get(), *this))
515 return ExprError();
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000516
John McCallf413f5e2013-05-03 00:10:13 +0000517 QualType T = Result.get()->getType();
518
519 // For now, reject dependent types.
520 if (T->isDependentType()) {
521 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
522 return ExprError();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000523 }
524
John McCallf413f5e2013-05-03 00:10:13 +0000525 // Any sort of function type is fine.
526 if (T->isFunctionType()) {
527 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000528 }
529
John McCallf413f5e2013-05-03 00:10:13 +0000530 // Otherwise, it needs to be a complete type.
531 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
532 return ExprError();
533 }
534
535 // Compute the type size (and array length if applicable?).
536 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
537 if (T->isArrayType()) {
538 const ArrayType *ATy = Context.getAsArrayType(T);
539 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
540 Info.Length = Info.Size / Info.Type;
541 }
542
543 // We can work with the expression as long as it's not an r-value.
544 if (!Result.get()->isRValue())
Chad Rosierb18a2852013-04-22 17:01:37 +0000545 Info.IsVarDecl = true;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000546
John McCallf413f5e2013-05-03 00:10:13 +0000547 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000548}
Chad Rosierd997bd12012-08-22 19:18:30 +0000549
Chad Rosier5c563642012-10-25 21:49:22 +0000550bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
551 unsigned &Offset, SourceLocation AsmLoc) {
552 Offset = 0;
553 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
554 LookupOrdinaryName);
555
556 if (!LookupName(BaseResult, getCurScope()))
557 return true;
558
559 if (!BaseResult.isSingleResult())
560 return true;
561
Craig Topperc3ec1492014-05-26 06:22:03 +0000562 const RecordType *RT = nullptr;
Chad Rosier10230d42013-04-01 17:58:03 +0000563 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
564 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
Chad Rosier5c563642012-10-25 21:49:22 +0000565 RT = VD->getType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000566 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
567 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Chad Rosier5c563642012-10-25 21:49:22 +0000568 RT = TD->getUnderlyingType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000569 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
Nico Weber9ef9ca42014-05-06 03:13:27 +0000570 RT = TD->getTypeForDecl()->getAs<RecordType>();
Chad Rosier5c563642012-10-25 21:49:22 +0000571 if (!RT)
572 return true;
573
574 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
575 return true;
576
577 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
578 LookupMemberName);
579
580 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
581 return true;
582
583 // FIXME: Handle IndirectFieldDecl?
584 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
585 if (!FD)
586 return true;
587
588 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
589 unsigned i = FD->getFieldIndex();
590 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
591 Offset = (unsigned)Result.getQuantity();
592
593 return false;
594}
595
Chad Rosierb261a502012-09-13 00:06:55 +0000596StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000597 ArrayRef<Token> AsmToks,
598 StringRef AsmString,
599 unsigned NumOutputs, unsigned NumInputs,
600 ArrayRef<StringRef> Constraints,
601 ArrayRef<StringRef> Clobbers,
602 ArrayRef<Expr*> Exprs,
603 SourceLocation EndLoc) {
604 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000605 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000606 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000607 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
608 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000609 Constraints, Exprs, AsmString,
610 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000611 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000612}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000613
614LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
615 SourceLocation Location,
616 bool AlwaysCreate) {
617 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
618 Location);
619
Ehsan Akhgari42924432014-10-08 17:28:34 +0000620 if (Label->isMSAsmLabel()) {
621 // If we have previously created this label implicitly, mark it as used.
622 Label->markUsed(Context);
623 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000624 // Otherwise, insert it, but only resolve it if we have seen the label itself.
625 std::string InternalName;
626 llvm::raw_string_ostream OS(InternalName);
627 // Create an internal name for the label. The name should not be a valid mangled
628 // name, and should be unique. We use a dot to make the name an invalid mangled
629 // name.
630 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
631 Label->setMSAsmLabel(OS.str());
632 }
633 if (AlwaysCreate) {
634 // The label might have been created implicitly from a previously encountered
635 // goto statement. So, for both newly created and looked up labels, we mark
636 // them as resolved.
637 Label->setMSAsmLabelResolved();
638 }
639 // Adjust their location for being able to generate accurate diagnostics.
640 Label->setLocation(Location);
641
642 return Label;
643}