1 //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
2 //
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/AST/ExprCXX.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/AST/TypeLoc.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/Initialization.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/ScopeInfo.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 using namespace clang;
28 using namespace sema;
29
30 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
31 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
32 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
33 /// provide a strong guidance to not use it.
34 ///
35 /// This method checks to see if the argument is an acceptable l-value and
36 /// returns false if it is a case we can handle.
CheckAsmLValue(const Expr * E,Sema & S)37 static bool CheckAsmLValue(const Expr *E, Sema &S) {
38 // Type dependent expressions will be checked during instantiation.
39 if (E->isTypeDependent())
40 return false;
41
42 if (E->isLValue())
43 return false; // Cool, this is an lvalue.
44
45 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
46 // are supposed to allow.
47 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
48 if (E != E2 && E2->isLValue()) {
49 if (!S.getLangOpts().HeinousExtensions)
50 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
51 << E->getSourceRange();
52 else
53 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
54 << E->getSourceRange();
55 // Accept, even if we emitted an error diagnostic.
56 return false;
57 }
58
59 // None of the above, just randomly invalid non-lvalue.
60 return true;
61 }
62
63 /// isOperandMentioned - Return true if the specified operand # is mentioned
64 /// anywhere in the decomposed asm string.
isOperandMentioned(unsigned OpNo,ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces)65 static bool isOperandMentioned(unsigned OpNo,
66 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
67 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
68 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
69 if (!Piece.isOperand()) continue;
70
71 // If this is a reference to the input and if the input was the smaller
72 // one, then we have to reject this asm.
73 if (Piece.getOperandNo() == OpNo)
74 return true;
75 }
76 return false;
77 }
78
CheckNakedParmReference(Expr * E,Sema & S)79 static bool CheckNakedParmReference(Expr *E, Sema &S) {
80 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
81 if (!Func)
82 return false;
83 if (!Func->hasAttr<NakedAttr>())
84 return false;
85
86 SmallVector<Expr*, 4> WorkList;
87 WorkList.push_back(E);
88 while (WorkList.size()) {
89 Expr *E = WorkList.pop_back_val();
90 if (isa<CXXThisExpr>(E)) {
91 S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
95 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
96 if (isa<ParmVarDecl>(DRE->getDecl())) {
97 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
98 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
99 return true;
100 }
101 }
102 for (Stmt *Child : E->children()) {
103 if (Expr *E = dyn_cast_or_null<Expr>(Child))
104 WorkList.push_back(E);
105 }
106 }
107 return false;
108 }
109
ActOnGCCAsmStmt(SourceLocation AsmLoc,bool IsSimple,bool IsVolatile,unsigned NumOutputs,unsigned NumInputs,IdentifierInfo ** Names,MultiExprArg constraints,MultiExprArg Exprs,Expr * asmString,MultiExprArg clobbers,SourceLocation RParenLoc)110 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
111 bool IsVolatile, unsigned NumOutputs,
112 unsigned NumInputs, IdentifierInfo **Names,
113 MultiExprArg constraints, MultiExprArg Exprs,
114 Expr *asmString, MultiExprArg clobbers,
115 SourceLocation RParenLoc) {
116 unsigned NumClobbers = clobbers.size();
117 StringLiteral **Constraints =
118 reinterpret_cast<StringLiteral**>(constraints.data());
119 StringLiteral *AsmString = cast<StringLiteral>(asmString);
120 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
121
122 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
123
124 // The parser verifies that there is a string literal here.
125 assert(AsmString->isAscii());
126
127 bool ValidateConstraints =
128 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl());
129
130 for (unsigned i = 0; i != NumOutputs; i++) {
131 StringLiteral *Literal = Constraints[i];
132 assert(Literal->isAscii());
133
134 StringRef OutputName;
135 if (Names[i])
136 OutputName = Names[i]->getName();
137
138 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
139 if (ValidateConstraints &&
140 !Context.getTargetInfo().validateOutputConstraint(Info))
141 return StmtError(Diag(Literal->getLocStart(),
142 diag::err_asm_invalid_output_constraint)
143 << Info.getConstraintStr());
144
145 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
146 if (ER.isInvalid())
147 return StmtError();
148 Exprs[i] = ER.get();
149
150 // Check that the output exprs are valid lvalues.
151 Expr *OutputExpr = Exprs[i];
152
153 // Referring to parameters is not allowed in naked functions.
154 if (CheckNakedParmReference(OutputExpr, *this))
155 return StmtError();
156
157 // Bitfield can't be referenced with a pointer.
158 if (Info.allowsMemory() && OutputExpr->refersToBitField())
159 return StmtError(Diag(OutputExpr->getLocStart(),
160 diag::err_asm_bitfield_in_memory_constraint)
161 << 1
162 << Info.getConstraintStr()
163 << OutputExpr->getSourceRange());
164
165 OutputConstraintInfos.push_back(Info);
166
167 // If this is dependent, just continue.
168 if (OutputExpr->isTypeDependent())
169 continue;
170
171 Expr::isModifiableLvalueResult IsLV =
172 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
173 switch (IsLV) {
174 case Expr::MLV_Valid:
175 // Cool, this is an lvalue.
176 break;
177 case Expr::MLV_ArrayType:
178 // This is OK too.
179 break;
180 case Expr::MLV_LValueCast: {
181 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
182 if (!getLangOpts().HeinousExtensions) {
183 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
184 << OutputExpr->getSourceRange();
185 } else {
186 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
187 << OutputExpr->getSourceRange();
188 }
189 // Accept, even if we emitted an error diagnostic.
190 break;
191 }
192 case Expr::MLV_IncompleteType:
193 case Expr::MLV_IncompleteVoidType:
194 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
195 diag::err_dereference_incomplete_type))
196 return StmtError();
197 default:
198 return StmtError(Diag(OutputExpr->getLocStart(),
199 diag::err_asm_invalid_lvalue_in_output)
200 << OutputExpr->getSourceRange());
201 }
202
203 unsigned Size = Context.getTypeSize(OutputExpr->getType());
204 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
205 Size))
206 return StmtError(Diag(OutputExpr->getLocStart(),
207 diag::err_asm_invalid_output_size)
208 << Info.getConstraintStr());
209 }
210
211 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
212
213 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
214 StringLiteral *Literal = Constraints[i];
215 assert(Literal->isAscii());
216
217 StringRef InputName;
218 if (Names[i])
219 InputName = Names[i]->getName();
220
221 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
222 if (ValidateConstraints &&
223 !Context.getTargetInfo().validateInputConstraint(
224 OutputConstraintInfos.data(), NumOutputs, Info)) {
225 return StmtError(Diag(Literal->getLocStart(),
226 diag::err_asm_invalid_input_constraint)
227 << Info.getConstraintStr());
228 }
229
230 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
231 if (ER.isInvalid())
232 return StmtError();
233 Exprs[i] = ER.get();
234
235 Expr *InputExpr = Exprs[i];
236
237 // Referring to parameters is not allowed in naked functions.
238 if (CheckNakedParmReference(InputExpr, *this))
239 return StmtError();
240
241 // Bitfield can't be referenced with a pointer.
242 if (Info.allowsMemory() && InputExpr->refersToBitField())
243 return StmtError(Diag(InputExpr->getLocStart(),
244 diag::err_asm_bitfield_in_memory_constraint)
245 << 0
246 << Info.getConstraintStr()
247 << InputExpr->getSourceRange());
248
249 // Only allow void types for memory constraints.
250 if (Info.allowsMemory() && !Info.allowsRegister()) {
251 if (CheckAsmLValue(InputExpr, *this))
252 return StmtError(Diag(InputExpr->getLocStart(),
253 diag::err_asm_invalid_lvalue_in_input)
254 << Info.getConstraintStr()
255 << InputExpr->getSourceRange());
256 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
257 if (!InputExpr->isValueDependent()) {
258 llvm::APSInt Result;
259 if (!InputExpr->EvaluateAsInt(Result, Context))
260 return StmtError(
261 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
262 << Info.getConstraintStr() << InputExpr->getSourceRange());
263 if (Result.slt(Info.getImmConstantMin()) ||
264 Result.sgt(Info.getImmConstantMax()))
265 return StmtError(Diag(InputExpr->getLocStart(),
266 diag::err_invalid_asm_value_for_constraint)
267 << Result.toString(10) << Info.getConstraintStr()
268 << InputExpr->getSourceRange());
269 }
270
271 } else {
272 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
273 if (Result.isInvalid())
274 return StmtError();
275
276 Exprs[i] = Result.get();
277 }
278
279 if (Info.allowsRegister()) {
280 if (InputExpr->getType()->isVoidType()) {
281 return StmtError(Diag(InputExpr->getLocStart(),
282 diag::err_asm_invalid_type_in_input)
283 << InputExpr->getType() << Info.getConstraintStr()
284 << InputExpr->getSourceRange());
285 }
286 }
287
288 InputConstraintInfos.push_back(Info);
289
290 const Type *Ty = Exprs[i]->getType().getTypePtr();
291 if (Ty->isDependentType())
292 continue;
293
294 if (!Ty->isVoidType() || !Info.allowsMemory())
295 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
296 diag::err_dereference_incomplete_type))
297 return StmtError();
298
299 unsigned Size = Context.getTypeSize(Ty);
300 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
301 Size))
302 return StmtError(Diag(InputExpr->getLocStart(),
303 diag::err_asm_invalid_input_size)
304 << Info.getConstraintStr());
305 }
306
307 // Check that the clobbers are valid.
308 for (unsigned i = 0; i != NumClobbers; i++) {
309 StringLiteral *Literal = Clobbers[i];
310 assert(Literal->isAscii());
311
312 StringRef Clobber = Literal->getString();
313
314 if (!Context.getTargetInfo().isValidClobber(Clobber))
315 return StmtError(Diag(Literal->getLocStart(),
316 diag::err_asm_unknown_register_name) << Clobber);
317 }
318
319 GCCAsmStmt *NS =
320 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
321 NumInputs, Names, Constraints, Exprs.data(),
322 AsmString, NumClobbers, Clobbers, RParenLoc);
323 // Validate the asm string, ensuring it makes sense given the operands we
324 // have.
325 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
326 unsigned DiagOffs;
327 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
328 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
329 << AsmString->getSourceRange();
330 return StmtError();
331 }
332
333 // Validate constraints and modifiers.
334 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
335 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
336 if (!Piece.isOperand()) continue;
337
338 // Look for the correct constraint index.
339 unsigned ConstraintIdx = Piece.getOperandNo();
340 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
341
342 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
343 // modifier '+'.
344 if (ConstraintIdx >= NumOperands) {
345 unsigned I = 0, E = NS->getNumOutputs();
346
347 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
348 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
349 ConstraintIdx = I;
350 break;
351 }
352
353 assert(I != E && "Invalid operand number should have been caught in "
354 " AnalyzeAsmString");
355 }
356
357 // Now that we have the right indexes go ahead and check.
358 StringLiteral *Literal = Constraints[ConstraintIdx];
359 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
360 if (Ty->isDependentType() || Ty->isIncompleteType())
361 continue;
362
363 unsigned Size = Context.getTypeSize(Ty);
364 std::string SuggestedModifier;
365 if (!Context.getTargetInfo().validateConstraintModifier(
366 Literal->getString(), Piece.getModifier(), Size,
367 SuggestedModifier)) {
368 Diag(Exprs[ConstraintIdx]->getLocStart(),
369 diag::warn_asm_mismatched_size_modifier);
370
371 if (!SuggestedModifier.empty()) {
372 auto B = Diag(Piece.getRange().getBegin(),
373 diag::note_asm_missing_constraint_modifier)
374 << SuggestedModifier;
375 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
376 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
377 SuggestedModifier));
378 }
379 }
380 }
381
382 // Validate tied input operands for type mismatches.
383 unsigned NumAlternatives = ~0U;
384 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
385 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
386 StringRef ConstraintStr = Info.getConstraintStr();
387 unsigned AltCount = ConstraintStr.count(',') + 1;
388 if (NumAlternatives == ~0U)
389 NumAlternatives = AltCount;
390 else if (NumAlternatives != AltCount)
391 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
392 diag::err_asm_unexpected_constraint_alternatives)
393 << NumAlternatives << AltCount);
394 }
395 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
396 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
397 StringRef ConstraintStr = Info.getConstraintStr();
398 unsigned AltCount = ConstraintStr.count(',') + 1;
399 if (NumAlternatives == ~0U)
400 NumAlternatives = AltCount;
401 else if (NumAlternatives != AltCount)
402 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
403 diag::err_asm_unexpected_constraint_alternatives)
404 << NumAlternatives << AltCount);
405
406 // If this is a tied constraint, verify that the output and input have
407 // either exactly the same type, or that they are int/ptr operands with the
408 // same size (int/long, int*/long, are ok etc).
409 if (!Info.hasTiedOperand()) continue;
410
411 unsigned TiedTo = Info.getTiedOperand();
412 unsigned InputOpNo = i+NumOutputs;
413 Expr *OutputExpr = Exprs[TiedTo];
414 Expr *InputExpr = Exprs[InputOpNo];
415
416 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
417 continue;
418
419 QualType InTy = InputExpr->getType();
420 QualType OutTy = OutputExpr->getType();
421 if (Context.hasSameType(InTy, OutTy))
422 continue; // All types can be tied to themselves.
423
424 // Decide if the input and output are in the same domain (integer/ptr or
425 // floating point.
426 enum AsmDomain {
427 AD_Int, AD_FP, AD_Other
428 } InputDomain, OutputDomain;
429
430 if (InTy->isIntegerType() || InTy->isPointerType())
431 InputDomain = AD_Int;
432 else if (InTy->isRealFloatingType())
433 InputDomain = AD_FP;
434 else
435 InputDomain = AD_Other;
436
437 if (OutTy->isIntegerType() || OutTy->isPointerType())
438 OutputDomain = AD_Int;
439 else if (OutTy->isRealFloatingType())
440 OutputDomain = AD_FP;
441 else
442 OutputDomain = AD_Other;
443
444 // They are ok if they are the same size and in the same domain. This
445 // allows tying things like:
446 // void* to int*
447 // void* to int if they are the same size.
448 // double to long double if they are the same size.
449 //
450 uint64_t OutSize = Context.getTypeSize(OutTy);
451 uint64_t InSize = Context.getTypeSize(InTy);
452 if (OutSize == InSize && InputDomain == OutputDomain &&
453 InputDomain != AD_Other)
454 continue;
455
456 // If the smaller input/output operand is not mentioned in the asm string,
457 // then we can promote the smaller one to a larger input and the asm string
458 // won't notice.
459 bool SmallerValueMentioned = false;
460
461 // If this is a reference to the input and if the input was the smaller
462 // one, then we have to reject this asm.
463 if (isOperandMentioned(InputOpNo, Pieces)) {
464 // This is a use in the asm string of the smaller operand. Since we
465 // codegen this by promoting to a wider value, the asm will get printed
466 // "wrong".
467 SmallerValueMentioned |= InSize < OutSize;
468 }
469 if (isOperandMentioned(TiedTo, Pieces)) {
470 // If this is a reference to the output, and if the output is the larger
471 // value, then it's ok because we'll promote the input to the larger type.
472 SmallerValueMentioned |= OutSize < InSize;
473 }
474
475 // If the smaller value wasn't mentioned in the asm string, and if the
476 // output was a register, just extend the shorter one to the size of the
477 // larger one.
478 if (!SmallerValueMentioned && InputDomain != AD_Other &&
479 OutputConstraintInfos[TiedTo].allowsRegister())
480 continue;
481
482 // Either both of the operands were mentioned or the smaller one was
483 // mentioned. One more special case that we'll allow: if the tied input is
484 // integer, unmentioned, and is a constant, then we'll allow truncating it
485 // down to the size of the destination.
486 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
487 !isOperandMentioned(InputOpNo, Pieces) &&
488 InputExpr->isEvaluatable(Context)) {
489 CastKind castKind =
490 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
491 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
492 Exprs[InputOpNo] = InputExpr;
493 NS->setInputExpr(i, InputExpr);
494 continue;
495 }
496
497 Diag(InputExpr->getLocStart(),
498 diag::err_asm_tying_incompatible_types)
499 << InTy << OutTy << OutputExpr->getSourceRange()
500 << InputExpr->getSourceRange();
501 return StmtError();
502 }
503
504 return NS;
505 }
506
LookupInlineAsmIdentifier(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,llvm::InlineAsmIdentifierInfo & Info,bool IsUnevaluatedContext)507 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
508 SourceLocation TemplateKWLoc,
509 UnqualifiedId &Id,
510 llvm::InlineAsmIdentifierInfo &Info,
511 bool IsUnevaluatedContext) {
512 Info.clear();
513
514 if (IsUnevaluatedContext)
515 PushExpressionEvaluationContext(UnevaluatedAbstract,
516 ReuseLambdaContextDecl);
517
518 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
519 /*trailing lparen*/ false,
520 /*is & operand*/ false,
521 /*CorrectionCandidateCallback=*/nullptr,
522 /*IsInlineAsmIdentifier=*/ true);
523
524 if (IsUnevaluatedContext)
525 PopExpressionEvaluationContext();
526
527 if (!Result.isUsable()) return Result;
528
529 Result = CheckPlaceholderExpr(Result.get());
530 if (!Result.isUsable()) return Result;
531
532 // Referring to parameters is not allowed in naked functions.
533 if (CheckNakedParmReference(Result.get(), *this))
534 return ExprError();
535
536 QualType T = Result.get()->getType();
537
538 // For now, reject dependent types.
539 if (T->isDependentType()) {
540 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
541 return ExprError();
542 }
543
544 // Any sort of function type is fine.
545 if (T->isFunctionType()) {
546 return Result;
547 }
548
549 // Otherwise, it needs to be a complete type.
550 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
551 return ExprError();
552 }
553
554 // Compute the type size (and array length if applicable?).
555 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
556 if (T->isArrayType()) {
557 const ArrayType *ATy = Context.getAsArrayType(T);
558 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
559 Info.Length = Info.Size / Info.Type;
560 }
561
562 // We can work with the expression as long as it's not an r-value.
563 if (!Result.get()->isRValue())
564 Info.IsVarDecl = true;
565
566 return Result;
567 }
568
LookupInlineAsmField(StringRef Base,StringRef Member,unsigned & Offset,SourceLocation AsmLoc)569 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
570 unsigned &Offset, SourceLocation AsmLoc) {
571 Offset = 0;
572 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
573 LookupOrdinaryName);
574
575 if (!LookupName(BaseResult, getCurScope()))
576 return true;
577
578 if (!BaseResult.isSingleResult())
579 return true;
580
581 const RecordType *RT = nullptr;
582 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
583 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
584 RT = VD->getType()->getAs<RecordType>();
585 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
586 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
587 RT = TD->getUnderlyingType()->getAs<RecordType>();
588 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
589 RT = TD->getTypeForDecl()->getAs<RecordType>();
590 if (!RT)
591 return true;
592
593 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
594 return true;
595
596 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
597 LookupMemberName);
598
599 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
600 return true;
601
602 // FIXME: Handle IndirectFieldDecl?
603 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
604 if (!FD)
605 return true;
606
607 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
608 unsigned i = FD->getFieldIndex();
609 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
610 Offset = (unsigned)Result.getQuantity();
611
612 return false;
613 }
614
ActOnMSAsmStmt(SourceLocation AsmLoc,SourceLocation LBraceLoc,ArrayRef<Token> AsmToks,StringRef AsmString,unsigned NumOutputs,unsigned NumInputs,ArrayRef<StringRef> Constraints,ArrayRef<StringRef> Clobbers,ArrayRef<Expr * > Exprs,SourceLocation EndLoc)615 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
616 ArrayRef<Token> AsmToks,
617 StringRef AsmString,
618 unsigned NumOutputs, unsigned NumInputs,
619 ArrayRef<StringRef> Constraints,
620 ArrayRef<StringRef> Clobbers,
621 ArrayRef<Expr*> Exprs,
622 SourceLocation EndLoc) {
623 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
624 getCurFunction()->setHasBranchProtectedScope();
625 MSAsmStmt *NS =
626 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
627 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
628 Constraints, Exprs, AsmString,
629 Clobbers, EndLoc);
630 return NS;
631 }
632
GetOrCreateMSAsmLabel(StringRef ExternalLabelName,SourceLocation Location,bool AlwaysCreate)633 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
634 SourceLocation Location,
635 bool AlwaysCreate) {
636 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
637 Location);
638
639 if (Label->isMSAsmLabel()) {
640 // If we have previously created this label implicitly, mark it as used.
641 Label->markUsed(Context);
642 } else {
643 // Otherwise, insert it, but only resolve it if we have seen the label itself.
644 std::string InternalName;
645 llvm::raw_string_ostream OS(InternalName);
646 // Create an internal name for the label. The name should not be a valid mangled
647 // name, and should be unique. We use a dot to make the name an invalid mangled
648 // name.
649 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
650 Label->setMSAsmLabel(OS.str());
651 }
652 if (AlwaysCreate) {
653 // The label might have been created implicitly from a previously encountered
654 // goto statement. So, for both newly created and looked up labels, we mark
655 // them as resolved.
656 Label->setMSAsmLabelResolved();
657 }
658 // Adjust their location for being able to generate accurate diagnostics.
659 Label->setLocation(Location);
660
661 return Label;
662 }
663