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/RecordLayout.h"
16 #include "clang/AST/TypeLoc.h"
17 #include "clang/Basic/TargetInfo.h"
18 #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"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 using namespace clang;
27 using 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.
CheckAsmLValue(const Expr * E,Sema & S)36 static 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.
isOperandMentioned(unsigned OpNo,ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces)64 static bool isOperandMentioned(unsigned OpNo,
65                          ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
66   for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
67     const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
68     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 
CheckNakedParmReference(Expr * E,Sema & S)78 static 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 
ActOnGCCAsmStmt(SourceLocation AsmLoc,bool IsSimple,bool IsVolatile,unsigned NumOutputs,unsigned NumInputs,IdentifierInfo ** Names,MultiExprArg constraints,MultiExprArg Exprs,Expr * asmString,MultiExprArg clobbers,SourceLocation RParenLoc)104 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
105                                  bool IsVolatile, unsigned NumOutputs,
106                                  unsigned NumInputs, IdentifierInfo **Names,
107                                  MultiExprArg constraints, MultiExprArg Exprs,
108                                  Expr *asmString, MultiExprArg clobbers,
109                                  SourceLocation RParenLoc) {
110   unsigned NumClobbers = clobbers.size();
111   StringLiteral **Constraints =
112     reinterpret_cast<StringLiteral**>(constraints.data());
113   StringLiteral *AsmString = cast<StringLiteral>(asmString);
114   StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
115 
116   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
117 
118   // The parser verifies that there is a string literal here.
119   assert(AsmString->isAscii());
120 
121   for (unsigned i = 0; i != NumOutputs; i++) {
122     StringLiteral *Literal = Constraints[i];
123     assert(Literal->isAscii());
124 
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 
135     ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
136     if (ER.isInvalid())
137       return StmtError();
138     Exprs[i] = ER.get();
139 
140     // Check that the output exprs are valid lvalues.
141     Expr *OutputExpr = Exprs[i];
142 
143     // Referring to parameters is not allowed in naked functions.
144     if (CheckNakedParmReference(OutputExpr, *this))
145       return StmtError();
146 
147     OutputConstraintInfos.push_back(Info);
148 
149     // If this is dependent, just continue.
150     if (OutputExpr->isTypeDependent())
151       continue;
152 
153     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;
159     case Expr::MLV_ArrayType:
160       // This is OK too.
161       break;
162     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());
186     if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
187                                                     Size))
188       return StmtError(Diag(OutputExpr->getLocStart(),
189                             diag::err_asm_invalid_output_size)
190                        << Info.getConstraintStr());
191   }
192 
193   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
194 
195   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
196     StringLiteral *Literal = Constraints[i];
197     assert(Literal->isAscii());
198 
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 
211     ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
212     if (ER.isInvalid())
213       return StmtError();
214     Exprs[i] = ER.get();
215 
216     Expr *InputExpr = Exprs[i];
217 
218     // Referring to parameters is not allowed in naked functions.
219     if (CheckNakedParmReference(InputExpr, *this))
220       return StmtError();
221 
222     // 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());
229     } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
230       llvm::APSInt Result;
231       if (!InputExpr->EvaluateAsInt(Result, Context))
232         return StmtError(
233             Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
234             << Info.getConstraintStr() << InputExpr->getSourceRange());
235       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 
242     } else {
243       ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
244       if (Result.isInvalid())
245         return StmtError();
246 
247       Exprs[i] = Result.get();
248     }
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 
259     InputConstraintInfos.push_back(Info);
260 
261     const Type *Ty = Exprs[i]->getType().getTypePtr();
262     if (Ty->isDependentType())
263       continue;
264 
265     if (!Ty->isVoidType() || !Info.allowsMemory())
266       if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
267                               diag::err_dereference_incomplete_type))
268         return StmtError();
269 
270     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());
276   }
277 
278   // Check that the clobbers are valid.
279   for (unsigned i = 0; i != NumClobbers; i++) {
280     StringLiteral *Literal = Clobbers[i];
281     assert(Literal->isAscii());
282 
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 
290   GCCAsmStmt *NS =
291     new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
292                              NumInputs, Names, Constraints, Exprs.data(),
293                              AsmString, NumClobbers, Clobbers, RParenLoc);
294   // Validate the asm string, ensuring it makes sense given the operands we
295   // have.
296   SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
297   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 
304   // 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);
345     std::string SuggestedModifier;
346     if (!Context.getTargetInfo().validateConstraintModifier(
347             Literal->getString(), Piece.getModifier(), Size,
348             SuggestedModifier)) {
349       Diag(Exprs[ConstraintIdx]->getLocStart(),
350            diag::warn_asm_mismatched_size_modifier);
351 
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     }
361   }
362 
363   // Validate tied input operands for type mismatches.
364   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   }
376   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
377     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
378     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);
386 
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);
472       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
473       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 
485   return NS;
486 }
487 
LookupInlineAsmIdentifier(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,llvm::InlineAsmIdentifierInfo & Info,bool IsUnevaluatedContext)488 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
489                                            SourceLocation TemplateKWLoc,
490                                            UnqualifiedId &Id,
491                                            llvm::InlineAsmIdentifierInfo &Info,
492                                            bool IsUnevaluatedContext) {
493   Info.clear();
494 
495   if (IsUnevaluatedContext)
496     PushExpressionEvaluationContext(UnevaluatedAbstract,
497                                     ReuseLambdaContextDecl);
498 
499   ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
500                                         /*trailing lparen*/ false,
501                                         /*is & operand*/ false,
502                                         /*CorrectionCandidateCallback=*/nullptr,
503                                         /*IsInlineAsmIdentifier=*/ true);
504 
505   if (IsUnevaluatedContext)
506     PopExpressionEvaluationContext();
507 
508   if (!Result.isUsable()) return Result;
509 
510   Result = CheckPlaceholderExpr(Result.get());
511   if (!Result.isUsable()) return Result;
512 
513   // Referring to parameters is not allowed in naked functions.
514   if (CheckNakedParmReference(Result.get(), *this))
515     return ExprError();
516 
517   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();
523   }
524 
525   // Any sort of function type is fine.
526   if (T->isFunctionType()) {
527     return Result;
528   }
529 
530   // 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())
545     Info.IsVarDecl = true;
546 
547   return Result;
548 }
549 
LookupInlineAsmField(StringRef Base,StringRef Member,unsigned & Offset,SourceLocation AsmLoc)550 bool 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 
562   const RecordType *RT = nullptr;
563   NamedDecl *FoundDecl = BaseResult.getFoundDecl();
564   if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
565     RT = VD->getType()->getAs<RecordType>();
566   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
567     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
568     RT = TD->getUnderlyingType()->getAs<RecordType>();
569   } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
570     RT = TD->getTypeForDecl()->getAs<RecordType>();
571   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 
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)596 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
597                                 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);
605   getCurFunction()->setHasBranchProtectedScope();
606   MSAsmStmt *NS =
607     new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
608                             /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
609                             Constraints, Exprs, AsmString,
610                             Clobbers, EndLoc);
611   return NS;
612 }
613 
GetOrCreateMSAsmLabel(StringRef ExternalLabelName,SourceLocation Location,bool AlwaysCreate)614 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
615                                        SourceLocation Location,
616                                        bool AlwaysCreate) {
617   LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
618                                          Location);
619 
620   if (Label->isMSAsmLabel()) {
621     // If we have previously created this label implicitly, mark it as used.
622     Label->markUsed(Context);
623   } else {
624     // 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 }
644