1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements stmt-related attribute processing. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/SemaInternal.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Sema/DelayedDiagnostic.h" 17 #include "clang/Sema/Lookup.h" 18 #include "clang/Sema/ScopeInfo.h" 19 #include "llvm/ADT/StringExtras.h" 20 21 using namespace clang; 22 using namespace sema; 23 24 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, 25 SourceRange Range) { 26 FallThroughAttr Attr(A.getRange(), S.Context, 27 A.getAttributeSpellingListIndex()); 28 if (!isa<NullStmt>(St)) { 29 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target) 30 << Attr.getSpelling() << St->getBeginLoc(); 31 if (isa<SwitchCase>(St)) { 32 SourceLocation L = S.getLocForEndOfToken(Range.getEnd()); 33 S.Diag(L, diag::note_fallthrough_insert_semi_fixit) 34 << FixItHint::CreateInsertion(L, ";"); 35 } 36 return nullptr; 37 } 38 auto *FnScope = S.getCurFunction(); 39 if (FnScope->SwitchStack.empty()) { 40 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch); 41 return nullptr; 42 } 43 44 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 45 // about using it as an extension. 46 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() && 47 !A.getScopeName()) 48 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A.getName(); 49 50 FnScope->setHasFallthroughStmt(); 51 return ::new (S.Context) auto(Attr); 52 } 53 54 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, 55 SourceRange Range) { 56 if (A.getNumArgs() < 1) { 57 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1; 58 return nullptr; 59 } 60 61 std::vector<StringRef> DiagnosticIdentifiers; 62 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) { 63 StringRef RuleName; 64 65 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr)) 66 return nullptr; 67 68 // FIXME: Warn if the rule name is unknown. This is tricky because only 69 // clang-tidy knows about available rules. 70 DiagnosticIdentifiers.push_back(RuleName); 71 } 72 73 return ::new (S.Context) SuppressAttr( 74 A.getRange(), S.Context, DiagnosticIdentifiers.data(), 75 DiagnosticIdentifiers.size(), A.getAttributeSpellingListIndex()); 76 } 77 78 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, 79 SourceRange) { 80 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0); 81 IdentifierLoc *OptionLoc = A.getArgAsIdent(1); 82 IdentifierLoc *StateLoc = A.getArgAsIdent(2); 83 Expr *ValueExpr = A.getArgAsExpr(3); 84 85 StringRef PragmaName = 86 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName()) 87 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam", 88 PragmaNameLoc->Ident->getName()) 89 .Default("clang loop"); 90 91 if (St->getStmtClass() != Stmt::DoStmtClass && 92 St->getStmtClass() != Stmt::ForStmtClass && 93 St->getStmtClass() != Stmt::CXXForRangeStmtClass && 94 St->getStmtClass() != Stmt::WhileStmtClass) { 95 std::string Pragma = "#pragma " + std::string(PragmaName); 96 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma; 97 return nullptr; 98 } 99 100 LoopHintAttr::Spelling Spelling = 101 LoopHintAttr::Spelling(A.getAttributeSpellingListIndex()); 102 LoopHintAttr::OptionType Option; 103 LoopHintAttr::LoopHintState State; 104 105 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O, 106 LoopHintAttr::LoopHintState S) { 107 Option = O; 108 State = S; 109 }; 110 111 if (PragmaName == "nounroll") { 112 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable); 113 } else if (PragmaName == "unroll") { 114 // #pragma unroll N 115 if (ValueExpr) 116 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric); 117 else 118 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable); 119 } else if (PragmaName == "nounroll_and_jam") { 120 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable); 121 } else if (PragmaName == "unroll_and_jam") { 122 // #pragma unroll_and_jam N 123 if (ValueExpr) 124 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric); 125 else 126 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable); 127 } else { 128 // #pragma clang loop ... 129 assert(OptionLoc && OptionLoc->Ident && 130 "Attribute must have valid option info."); 131 Option = llvm::StringSwitch<LoopHintAttr::OptionType>( 132 OptionLoc->Ident->getName()) 133 .Case("vectorize", LoopHintAttr::Vectorize) 134 .Case("vectorize_width", LoopHintAttr::VectorizeWidth) 135 .Case("interleave", LoopHintAttr::Interleave) 136 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate) 137 .Case("interleave_count", LoopHintAttr::InterleaveCount) 138 .Case("unroll", LoopHintAttr::Unroll) 139 .Case("unroll_count", LoopHintAttr::UnrollCount) 140 .Case("pipeline", LoopHintAttr::PipelineDisabled) 141 .Case("pipeline_initiation_interval", 142 LoopHintAttr::PipelineInitiationInterval) 143 .Case("distribute", LoopHintAttr::Distribute) 144 .Default(LoopHintAttr::Vectorize); 145 if (Option == LoopHintAttr::VectorizeWidth || 146 Option == LoopHintAttr::InterleaveCount || 147 Option == LoopHintAttr::UnrollCount || 148 Option == LoopHintAttr::PipelineInitiationInterval) { 149 assert(ValueExpr && "Attribute must have a valid value expression."); 150 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 151 return nullptr; 152 State = LoopHintAttr::Numeric; 153 } else if (Option == LoopHintAttr::Vectorize || 154 Option == LoopHintAttr::Interleave || 155 Option == LoopHintAttr::VectorizePredicate || 156 Option == LoopHintAttr::Unroll || 157 Option == LoopHintAttr::Distribute || 158 Option == LoopHintAttr::PipelineDisabled) { 159 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument"); 160 if (StateLoc->Ident->isStr("disable")) 161 State = LoopHintAttr::Disable; 162 else if (StateLoc->Ident->isStr("assume_safety")) 163 State = LoopHintAttr::AssumeSafety; 164 else if (StateLoc->Ident->isStr("full")) 165 State = LoopHintAttr::Full; 166 else if (StateLoc->Ident->isStr("enable")) 167 State = LoopHintAttr::Enable; 168 else 169 llvm_unreachable("bad loop hint argument"); 170 } else 171 llvm_unreachable("bad loop hint"); 172 } 173 174 return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State, 175 ValueExpr, A.getRange()); 176 } 177 178 static void 179 CheckForIncompatibleAttributes(Sema &S, 180 const SmallVectorImpl<const Attr *> &Attrs) { 181 // There are 6 categories of loop hints attributes: vectorize, interleave, 182 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they 183 // come in two variants: a state form and a numeric form. The state form 184 // selectively defaults/enables/disables the transformation for the loop 185 // (for unroll, default indicates full unrolling rather than enabling the 186 // transformation). The numeric form form provides an integer hint (for 187 // example, unroll count) to the transformer. The following array accumulates 188 // the hints encountered while iterating through the attributes to check for 189 // compatibility. 190 struct { 191 const LoopHintAttr *StateAttr; 192 const LoopHintAttr *NumericAttr; 193 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 194 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 195 {nullptr, nullptr}}; 196 197 for (const auto *I : Attrs) { 198 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I); 199 200 // Skip non loop hint attributes 201 if (!LH) 202 continue; 203 204 LoopHintAttr::OptionType Option = LH->getOption(); 205 enum { 206 Vectorize, 207 Interleave, 208 Unroll, 209 UnrollAndJam, 210 Distribute, 211 Pipeline, 212 VectorizePredicate 213 } Category; 214 switch (Option) { 215 case LoopHintAttr::Vectorize: 216 case LoopHintAttr::VectorizeWidth: 217 Category = Vectorize; 218 break; 219 case LoopHintAttr::Interleave: 220 case LoopHintAttr::InterleaveCount: 221 Category = Interleave; 222 break; 223 case LoopHintAttr::Unroll: 224 case LoopHintAttr::UnrollCount: 225 Category = Unroll; 226 break; 227 case LoopHintAttr::UnrollAndJam: 228 case LoopHintAttr::UnrollAndJamCount: 229 Category = UnrollAndJam; 230 break; 231 case LoopHintAttr::Distribute: 232 // Perform the check for duplicated 'distribute' hints. 233 Category = Distribute; 234 break; 235 case LoopHintAttr::PipelineDisabled: 236 case LoopHintAttr::PipelineInitiationInterval: 237 Category = Pipeline; 238 break; 239 case LoopHintAttr::VectorizePredicate: 240 Category = VectorizePredicate; 241 break; 242 }; 243 244 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0])); 245 auto &CategoryState = HintAttrs[Category]; 246 const LoopHintAttr *PrevAttr; 247 if (Option == LoopHintAttr::Vectorize || 248 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll || 249 Option == LoopHintAttr::UnrollAndJam || 250 Option == LoopHintAttr::VectorizePredicate || 251 Option == LoopHintAttr::PipelineDisabled || 252 Option == LoopHintAttr::Distribute) { 253 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable). 254 PrevAttr = CategoryState.StateAttr; 255 CategoryState.StateAttr = LH; 256 } else { 257 // Numeric hint. For example, vectorize_width(8). 258 PrevAttr = CategoryState.NumericAttr; 259 CategoryState.NumericAttr = LH; 260 } 261 262 PrintingPolicy Policy(S.Context.getLangOpts()); 263 SourceLocation OptionLoc = LH->getRange().getBegin(); 264 if (PrevAttr) 265 // Cannot specify same type of attribute twice. 266 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 267 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy) 268 << LH->getDiagnosticName(Policy); 269 270 if (CategoryState.StateAttr && CategoryState.NumericAttr && 271 (Category == Unroll || Category == UnrollAndJam || 272 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) { 273 // Disable hints are not compatible with numeric hints of the same 274 // category. As a special case, numeric unroll hints are also not 275 // compatible with enable or full form of the unroll pragma because these 276 // directives indicate full unrolling. 277 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 278 << /*Duplicate=*/false 279 << CategoryState.StateAttr->getDiagnosticName(Policy) 280 << CategoryState.NumericAttr->getDiagnosticName(Policy); 281 } 282 } 283 } 284 285 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, 286 SourceRange Range) { 287 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's 288 // useful for OpenCL 1.x too and doesn't require HW support. 289 // opencl_unroll_hint can have 0 arguments (compiler 290 // determines unrolling factor) or 1 argument (the unroll factor provided 291 // by the user). 292 293 unsigned NumArgs = A.getNumArgs(); 294 295 if (NumArgs > 1) { 296 S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1; 297 return nullptr; 298 } 299 300 unsigned UnrollFactor = 0; 301 302 if (NumArgs == 1) { 303 Expr *E = A.getArgAsExpr(0); 304 llvm::APSInt ArgVal(32); 305 306 if (!E->isIntegerConstantExpr(ArgVal, S.Context)) { 307 S.Diag(A.getLoc(), diag::err_attribute_argument_type) 308 << A << AANT_ArgumentIntegerConstant << E->getSourceRange(); 309 return nullptr; 310 } 311 312 int Val = ArgVal.getSExtValue(); 313 314 if (Val <= 0) { 315 S.Diag(A.getRange().getBegin(), 316 diag::err_attribute_requires_positive_integer) 317 << A << /* positive */ 0; 318 return nullptr; 319 } 320 UnrollFactor = Val; 321 } 322 323 return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor); 324 } 325 326 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, 327 SourceRange Range) { 328 switch (A.getKind()) { 329 case ParsedAttr::UnknownAttribute: 330 S.Diag(A.getLoc(), A.isDeclspecAttribute() 331 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 332 : (unsigned)diag::warn_unknown_attribute_ignored) 333 << A.getName(); 334 return nullptr; 335 case ParsedAttr::AT_FallThrough: 336 return handleFallThroughAttr(S, St, A, Range); 337 case ParsedAttr::AT_LoopHint: 338 return handleLoopHintAttr(S, St, A, Range); 339 case ParsedAttr::AT_OpenCLUnrollHint: 340 return handleOpenCLUnrollHint(S, St, A, Range); 341 case ParsedAttr::AT_Suppress: 342 return handleSuppressAttr(S, St, A, Range); 343 default: 344 // if we're here, then we parsed a known attribute, but didn't recognize 345 // it as a statement attribute => it is declaration attribute 346 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt) 347 << A.getName() << St->getBeginLoc(); 348 return nullptr; 349 } 350 } 351 352 StmtResult Sema::ProcessStmtAttributes(Stmt *S, 353 const ParsedAttributesView &AttrList, 354 SourceRange Range) { 355 SmallVector<const Attr*, 8> Attrs; 356 for (const ParsedAttr &AL : AttrList) { 357 if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range)) 358 Attrs.push_back(a); 359 } 360 361 CheckForIncompatibleAttributes(*this, Attrs); 362 363 if (Attrs.empty()) 364 return S; 365 366 return ActOnAttributedStmt(Range.getBegin(), Attrs, S); 367 } 368