ObjCMT.cpp revision b8941a15b6b5477a81c189614d0129070ac099f1
1//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===// 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#include "Transforms.h" 11#include "clang/ARCMigrate/ARCMTActions.h" 12#include "clang/AST/ASTConsumer.h" 13#include "clang/AST/ASTContext.h" 14#include "clang/AST/NSAPI.h" 15#include "clang/AST/ParentMap.h" 16#include "clang/AST/RecursiveASTVisitor.h" 17#include "clang/Basic/FileManager.h" 18#include "clang/Edit/Commit.h" 19#include "clang/Edit/EditedSource.h" 20#include "clang/Edit/EditsReceiver.h" 21#include "clang/Edit/Rewriters.h" 22#include "clang/Frontend/CompilerInstance.h" 23#include "clang/Frontend/MultiplexConsumer.h" 24#include "clang/Lex/PPConditionalDirectiveRecord.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Rewrite/Core/Rewriter.h" 27#include "clang/Analysis/DomainSpecific/CocoaConventions.h" 28#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h" 29#include "clang/AST/Attr.h" 30#include "llvm/ADT/SmallString.h" 31 32using namespace clang; 33using namespace arcmt; 34using namespace ento::objc_retain; 35 36namespace { 37 38class ObjCMigrateASTConsumer : public ASTConsumer { 39 enum CF_BRIDGING_KIND { 40 CF_BRIDGING_NONE, 41 CF_BRIDGING_ENABLE, 42 CF_BRIDGING_MAY_INCLUDE 43 }; 44 45 void migrateDecl(Decl *D); 46 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D); 47 void migrateProtocolConformance(ASTContext &Ctx, 48 const ObjCImplementationDecl *ImpDecl); 49 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl, 50 const TypedefDecl *TypedefDcl); 51 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl); 52 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl, 53 ObjCMethodDecl *OM); 54 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM); 55 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM); 56 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P); 57 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl, 58 ObjCMethodDecl *OM, 59 ObjCInstanceTypeFamily OIT_Family = OIT_None); 60 61 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl); 62 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE, 63 const FunctionDecl *FuncDecl, bool ResultAnnotated); 64 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE, 65 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated); 66 67 void AnnotateImplicitBridging(ASTContext &Ctx); 68 69 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx, 70 const FunctionDecl *FuncDecl); 71 72 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl); 73 74 void migrateAddMethodAnnotation(ASTContext &Ctx, 75 const ObjCMethodDecl *MethodDecl); 76public: 77 std::string MigrateDir; 78 unsigned ASTMigrateActions; 79 unsigned FileId; 80 OwningPtr<NSAPI> NSAPIObj; 81 OwningPtr<edit::EditedSource> Editor; 82 FileRemapper &Remapper; 83 FileManager &FileMgr; 84 const PPConditionalDirectiveRecord *PPRec; 85 Preprocessor &PP; 86 bool IsOutputFile; 87 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls; 88 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates; 89 90 ObjCMigrateASTConsumer(StringRef migrateDir, 91 unsigned astMigrateActions, 92 FileRemapper &remapper, 93 FileManager &fileMgr, 94 const PPConditionalDirectiveRecord *PPRec, 95 Preprocessor &PP, 96 bool isOutputFile = false) 97 : MigrateDir(migrateDir), 98 ASTMigrateActions(astMigrateActions), 99 FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP), 100 IsOutputFile(isOutputFile) { } 101 102protected: 103 virtual void Initialize(ASTContext &Context) { 104 NSAPIObj.reset(new NSAPI(Context)); 105 Editor.reset(new edit::EditedSource(Context.getSourceManager(), 106 Context.getLangOpts(), 107 PPRec, false)); 108 } 109 110 virtual bool HandleTopLevelDecl(DeclGroupRef DG) { 111 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 112 migrateDecl(*I); 113 return true; 114 } 115 virtual void HandleInterestingDecl(DeclGroupRef DG) { 116 // Ignore decls from the PCH. 117 } 118 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 119 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG); 120 } 121 122 virtual void HandleTranslationUnit(ASTContext &Ctx); 123}; 124 125} 126 127ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction, 128 StringRef migrateDir, 129 unsigned migrateAction) 130 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir), 131 ObjCMigAction(migrateAction), 132 CompInst(0) { 133 if (MigrateDir.empty()) 134 MigrateDir = "."; // user current directory if none is given. 135} 136 137ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, 138 StringRef InFile) { 139 PPConditionalDirectiveRecord * 140 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager()); 141 CompInst->getPreprocessor().addPPCallbacks(PPRec); 142 ASTConsumer * 143 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile); 144 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir, 145 ObjCMigAction, 146 Remapper, 147 CompInst->getFileManager(), 148 PPRec, 149 CompInst->getPreprocessor()); 150 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer }; 151 return new MultiplexConsumer(Consumers); 152} 153 154bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) { 155 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(), 156 /*ignoreIfFilesChanges=*/true); 157 CompInst = &CI; 158 CI.getDiagnostics().setIgnoreAllWarnings(true); 159 return true; 160} 161 162namespace { 163class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> { 164 ObjCMigrateASTConsumer &Consumer; 165 ParentMap &PMap; 166 167public: 168 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap) 169 : Consumer(consumer), PMap(PMap) { } 170 171 bool shouldVisitTemplateInstantiations() const { return false; } 172 bool shouldWalkTypesOfTypeLocs() const { return false; } 173 174 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 175 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) { 176 edit::Commit commit(*Consumer.Editor); 177 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap); 178 Consumer.Editor->commit(commit); 179 } 180 181 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) { 182 edit::Commit commit(*Consumer.Editor); 183 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit); 184 Consumer.Editor->commit(commit); 185 } 186 187 return true; 188 } 189 190 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) { 191 // Do depth first; we want to rewrite the subexpressions first so that if 192 // we have to move expressions we will move them already rewritten. 193 for (Stmt::child_range range = E->children(); range; ++range) 194 if (!TraverseStmt(*range)) 195 return false; 196 197 return WalkUpFromObjCMessageExpr(E); 198 } 199}; 200 201class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> { 202 ObjCMigrateASTConsumer &Consumer; 203 OwningPtr<ParentMap> PMap; 204 205public: 206 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { } 207 208 bool shouldVisitTemplateInstantiations() const { return false; } 209 bool shouldWalkTypesOfTypeLocs() const { return false; } 210 211 bool TraverseStmt(Stmt *S) { 212 PMap.reset(new ParentMap(S)); 213 ObjCMigrator(Consumer, *PMap).TraverseStmt(S); 214 return true; 215 } 216}; 217} 218 219void ObjCMigrateASTConsumer::migrateDecl(Decl *D) { 220 if (!D) 221 return; 222 if (isa<ObjCMethodDecl>(D)) 223 return; // Wait for the ObjC container declaration. 224 225 BodyMigrator(*this).TraverseDecl(D); 226} 227 228static void append_attr(std::string &PropertyString, const char *attr) { 229 PropertyString += ", "; 230 PropertyString += attr; 231} 232 233static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter, 234 const ObjCMethodDecl *Setter, 235 const NSAPI &NS, edit::Commit &commit, 236 unsigned LengthOfPrefix) { 237 ASTContext &Context = NS.getASTContext(); 238 std::string PropertyString = "@property (nonatomic"; 239 std::string PropertyNameString = Getter->getNameAsString(); 240 StringRef PropertyName(PropertyNameString); 241 if (LengthOfPrefix > 0) { 242 PropertyString += ", getter="; 243 PropertyString += PropertyNameString; 244 } 245 // Property with no setter may be suggested as a 'readonly' property. 246 if (!Setter) 247 append_attr(PropertyString, "readonly"); 248 249 // Short circuit properties that contain the name "delegate" or "dataSource", 250 // or have exact name "target" to have unsafe_unretained attribute. 251 if (PropertyName.equals("target") || 252 (PropertyName.find("delegate") != StringRef::npos) || 253 (PropertyName.find("dataSource") != StringRef::npos)) 254 append_attr(PropertyString, "unsafe_unretained"); 255 else if (Setter) { 256 const ParmVarDecl *argDecl = *Setter->param_begin(); 257 QualType ArgType = Context.getCanonicalType(argDecl->getType()); 258 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime(); 259 bool RetainableObject = ArgType->isObjCRetainableType(); 260 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) { 261 if (const ObjCObjectPointerType *ObjPtrTy = 262 ArgType->getAs<ObjCObjectPointerType>()) { 263 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface(); 264 if (IDecl && 265 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying"))) 266 append_attr(PropertyString, "copy"); 267 else 268 append_attr(PropertyString, "retain"); 269 } 270 } else if (propertyLifetime == Qualifiers::OCL_Weak) 271 // TODO. More precise determination of 'weak' attribute requires 272 // looking into setter's implementation for backing weak ivar. 273 append_attr(PropertyString, "weak"); 274 else if (RetainableObject) 275 append_attr(PropertyString, "retain"); 276 } 277 PropertyString += ')'; 278 279 QualType RT = Getter->getResultType(); 280 if (!isa<TypedefType>(RT)) { 281 // strip off any ARC lifetime qualifier. 282 QualType CanResultTy = Context.getCanonicalType(RT); 283 if (CanResultTy.getQualifiers().hasObjCLifetime()) { 284 Qualifiers Qs = CanResultTy.getQualifiers(); 285 Qs.removeObjCLifetime(); 286 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs); 287 } 288 } 289 PropertyString += " "; 290 PropertyString += RT.getAsString(Context.getPrintingPolicy()); 291 char LastChar = PropertyString[PropertyString.size()-1]; 292 if (LastChar != '*') 293 PropertyString += " "; 294 if (LengthOfPrefix > 0) { 295 // property name must strip off "is" and lower case the first character 296 // after that; e.g. isContinuous will become continuous. 297 StringRef PropertyNameStringRef(PropertyNameString); 298 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix); 299 PropertyNameString = PropertyNameStringRef; 300 std::string NewPropertyNameString = PropertyNameString; 301 bool NoLowering = (isUppercase(NewPropertyNameString[0]) && 302 NewPropertyNameString.size() > 1 && 303 isUppercase(NewPropertyNameString[1])); 304 if (!NoLowering) 305 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]); 306 PropertyString += NewPropertyNameString; 307 } 308 else 309 PropertyString += PropertyNameString; 310 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc(); 311 Selector GetterSelector = Getter->getSelector(); 312 313 SourceLocation EndGetterSelectorLoc = 314 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size()); 315 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(), 316 EndGetterSelectorLoc), 317 PropertyString); 318 if (Setter) { 319 SourceLocation EndLoc = Setter->getDeclaratorEndLoc(); 320 // Get location past ';' 321 EndLoc = EndLoc.getLocWithOffset(1); 322 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc)); 323 } 324 return true; 325} 326 327void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx, 328 ObjCContainerDecl *D) { 329 if (D->isDeprecated()) 330 return; 331 332 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end(); 333 M != MEnd; ++M) { 334 ObjCMethodDecl *Method = (*M); 335 if (Method->isDeprecated()) 336 continue; 337 migrateProperty(Ctx, D, Method); 338 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 339 migrateNsReturnsInnerPointer(Ctx, Method); 340 } 341 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(), 342 E = D->prop_end(); P != E; ++P) { 343 ObjCPropertyDecl *Prop = *P; 344 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && 345 !P->isDeprecated()) 346 migratePropertyNsReturnsInnerPointer(Ctx, Prop); 347 } 348} 349 350static bool 351ClassImplementsAllMethodsAndProperties(ASTContext &Ctx, 352 const ObjCImplementationDecl *ImpDecl, 353 const ObjCInterfaceDecl *IDecl, 354 ObjCProtocolDecl *Protocol) { 355 // In auto-synthesis, protocol properties are not synthesized. So, 356 // a conforming protocol must have its required properties declared 357 // in class interface. 358 bool HasAtleastOneRequiredProperty = false; 359 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) 360 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(), 361 E = PDecl->prop_end(); P != E; ++P) { 362 ObjCPropertyDecl *Property = *P; 363 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional) 364 continue; 365 HasAtleastOneRequiredProperty = true; 366 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName()); 367 if (R.size() == 0) { 368 // Relax the rule and look into class's implementation for a synthesize 369 // or dynamic declaration. Class is implementing a property coming from 370 // another protocol. This still makes the target protocol as conforming. 371 if (!ImpDecl->FindPropertyImplDecl( 372 Property->getDeclName().getAsIdentifierInfo())) 373 return false; 374 } 375 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) { 376 if ((ClassProperty->getPropertyAttributes() 377 != Property->getPropertyAttributes()) || 378 !Ctx.hasSameType(ClassProperty->getType(), Property->getType())) 379 return false; 380 } 381 else 382 return false; 383 } 384 385 // At this point, all required properties in this protocol conform to those 386 // declared in the class. 387 // Check that class implements the required methods of the protocol too. 388 bool HasAtleastOneRequiredMethod = false; 389 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) { 390 if (PDecl->meth_begin() == PDecl->meth_end()) 391 return HasAtleastOneRequiredProperty; 392 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(), 393 MEnd = PDecl->meth_end(); M != MEnd; ++M) { 394 ObjCMethodDecl *MD = (*M); 395 if (MD->isImplicit()) 396 continue; 397 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) 398 continue; 399 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName()); 400 if (R.size() == 0) 401 return false; 402 bool match = false; 403 HasAtleastOneRequiredMethod = true; 404 for (unsigned I = 0, N = R.size(); I != N; ++I) 405 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0])) 406 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) { 407 match = true; 408 break; 409 } 410 if (!match) 411 return false; 412 } 413 } 414 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod) 415 return true; 416 return false; 417} 418 419static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl, 420 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols, 421 const NSAPI &NS, edit::Commit &commit) { 422 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols(); 423 std::string ClassString; 424 SourceLocation EndLoc = 425 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation(); 426 427 if (Protocols.empty()) { 428 ClassString = '<'; 429 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) { 430 ClassString += ConformingProtocols[i]->getNameAsString(); 431 if (i != (e-1)) 432 ClassString += ", "; 433 } 434 ClassString += "> "; 435 } 436 else { 437 ClassString = ", "; 438 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) { 439 ClassString += ConformingProtocols[i]->getNameAsString(); 440 if (i != (e-1)) 441 ClassString += ", "; 442 } 443 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1; 444 EndLoc = *PL; 445 } 446 447 commit.insertAfterToken(EndLoc, ClassString); 448 return true; 449} 450 451static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl, 452 const TypedefDecl *TypedefDcl, 453 const NSAPI &NS, edit::Commit &commit, 454 bool IsNSIntegerType, 455 bool NSOptions) { 456 std::string ClassString; 457 if (NSOptions) 458 ClassString = "typedef NS_OPTIONS(NSUInteger, "; 459 else 460 ClassString = 461 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " 462 : "typedef NS_ENUM(NSUInteger, "; 463 464 ClassString += TypedefDcl->getIdentifier()->getName(); 465 ClassString += ')'; 466 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart()); 467 commit.replace(R, ClassString); 468 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd(); 469 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext()); 470 if (!EndOfTypedefLoc.isInvalid()) { 471 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc)); 472 return true; 473 } 474 return false; 475} 476 477static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl, 478 const TypedefDecl *TypedefDcl, 479 const NSAPI &NS, edit::Commit &commit, 480 bool IsNSIntegerType) { 481 std::string ClassString = 482 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, "; 483 ClassString += TypedefDcl->getIdentifier()->getName(); 484 ClassString += ')'; 485 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart()); 486 commit.replace(R, ClassString); 487 SourceLocation TypedefLoc = TypedefDcl->getLocEnd(); 488 commit.remove(SourceRange(TypedefLoc, TypedefLoc)); 489 return true; 490} 491 492static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, 493 const EnumDecl *EnumDcl) { 494 bool PowerOfTwo = true; 495 bool AllHexdecimalEnumerator = true; 496 uint64_t MaxPowerOfTwoVal = 0; 497 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(), 498 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) { 499 EnumConstantDecl *Enumerator = (*EI); 500 const Expr *InitExpr = Enumerator->getInitExpr(); 501 if (!InitExpr) { 502 PowerOfTwo = false; 503 AllHexdecimalEnumerator = false; 504 continue; 505 } 506 InitExpr = InitExpr->IgnoreParenCasts(); 507 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) 508 if (BO->isShiftOp() || BO->isBitwiseOp()) 509 return true; 510 511 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue(); 512 if (PowerOfTwo && EnumVal) { 513 if (!llvm::isPowerOf2_64(EnumVal)) 514 PowerOfTwo = false; 515 else if (EnumVal > MaxPowerOfTwoVal) 516 MaxPowerOfTwoVal = EnumVal; 517 } 518 if (AllHexdecimalEnumerator && EnumVal) { 519 bool FoundHexdecimalEnumerator = false; 520 SourceLocation EndLoc = Enumerator->getLocEnd(); 521 Token Tok; 522 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true)) 523 if (Tok.isLiteral() && Tok.getLength() > 2) { 524 if (const char *StringLit = Tok.getLiteralData()) 525 FoundHexdecimalEnumerator = 526 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x')); 527 } 528 if (!FoundHexdecimalEnumerator) 529 AllHexdecimalEnumerator = false; 530 } 531 } 532 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2)); 533} 534 535void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, 536 const ObjCImplementationDecl *ImpDecl) { 537 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface(); 538 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated()) 539 return; 540 // Find all implicit conforming protocols for this class 541 // and make them explicit. 542 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols; 543 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols); 544 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols; 545 546 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I = 547 ObjCProtocolDecls.begin(), 548 E = ObjCProtocolDecls.end(); I != E; ++I) 549 if (!ExplicitProtocols.count(*I)) 550 PotentialImplicitProtocols.push_back(*I); 551 552 if (PotentialImplicitProtocols.empty()) 553 return; 554 555 // go through list of non-optional methods and properties in each protocol 556 // in the PotentialImplicitProtocols list. If class implements every one of the 557 // methods and properties, then this class conforms to this protocol. 558 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols; 559 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++) 560 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl, 561 PotentialImplicitProtocols[i])) 562 ConformingProtocols.push_back(PotentialImplicitProtocols[i]); 563 564 if (ConformingProtocols.empty()) 565 return; 566 567 // Further reduce number of conforming protocols. If protocol P1 is in the list 568 // protocol P2 (P2<P1>), No need to include P1. 569 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols; 570 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) { 571 bool DropIt = false; 572 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i]; 573 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) { 574 ObjCProtocolDecl *PDecl = ConformingProtocols[i1]; 575 if (PDecl == TargetPDecl) 576 continue; 577 if (PDecl->lookupProtocolNamed( 578 TargetPDecl->getDeclName().getAsIdentifierInfo())) { 579 DropIt = true; 580 break; 581 } 582 } 583 if (!DropIt) 584 MinimalConformingProtocols.push_back(TargetPDecl); 585 } 586 edit::Commit commit(*Editor); 587 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols, 588 *NSAPIObj, commit); 589 Editor->commit(commit); 590} 591 592void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, 593 const EnumDecl *EnumDcl, 594 const TypedefDecl *TypedefDcl) { 595 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() || 596 !TypedefDcl->getIdentifier() || 597 EnumDcl->isDeprecated() || TypedefDcl->isDeprecated()) 598 return; 599 600 QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); 601 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt); 602 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt); 603 604 if (!IsNSIntegerType && !IsNSUIntegerType) { 605 // Also check for typedef enum {...} TD; 606 if (const EnumType *EnumTy = qt->getAs<EnumType>()) { 607 if (EnumTy->getDecl() == EnumDcl) { 608 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); 609 if (NSOptions) { 610 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition()) 611 return; 612 } 613 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition()) 614 return; 615 edit::Commit commit(*Editor); 616 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions); 617 Editor->commit(commit); 618 } 619 } 620 return; 621 } 622 623 // We may still use NS_OPTIONS based on what we find in the enumertor list. 624 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); 625 // NS_ENUM must be available. 626 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition()) 627 return; 628 // NS_OPTIONS must be available. 629 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition()) 630 return; 631 edit::Commit commit(*Editor); 632 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions); 633 Editor->commit(commit); 634} 635 636static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC, 637 ObjCMethodDecl *OM) { 638 SourceRange R; 639 std::string ClassString; 640 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) { 641 TypeLoc TL = TSInfo->getTypeLoc(); 642 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); 643 ClassString = "instancetype"; 644 } 645 else { 646 R = SourceRange(OM->getLocStart(), OM->getLocStart()); 647 ClassString = OM->isInstanceMethod() ? '-' : '+'; 648 ClassString += " (instancetype)"; 649 } 650 edit::Commit commit(*ASTC.Editor); 651 commit.replace(R, ClassString); 652 ASTC.Editor->commit(commit); 653} 654 655void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, 656 ObjCContainerDecl *CDecl, 657 ObjCMethodDecl *OM) { 658 ObjCInstanceTypeFamily OIT_Family = 659 Selector::getInstTypeMethodFamily(OM->getSelector()); 660 661 std::string ClassName; 662 switch (OIT_Family) { 663 case OIT_None: 664 migrateFactoryMethod(Ctx, CDecl, OM); 665 return; 666 case OIT_Array: 667 ClassName = "NSArray"; 668 break; 669 case OIT_Dictionary: 670 ClassName = "NSDictionary"; 671 break; 672 case OIT_Singleton: 673 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton); 674 return; 675 case OIT_Init: 676 if (OM->getResultType()->isObjCIdType()) 677 ReplaceWithInstancetype(*this, OM); 678 return; 679 } 680 if (!OM->getResultType()->isObjCIdType()) 681 return; 682 683 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 684 if (!IDecl) { 685 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) 686 IDecl = CatDecl->getClassInterface(); 687 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl)) 688 IDecl = ImpDecl->getClassInterface(); 689 } 690 if (!IDecl || 691 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) { 692 migrateFactoryMethod(Ctx, CDecl, OM); 693 return; 694 } 695 ReplaceWithInstancetype(*this, OM); 696} 697 698static bool TypeIsInnerPointer(QualType T) { 699 if (!T->isAnyPointerType()) 700 return false; 701 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() || 702 T->isBlockPointerType() || T->isFunctionPointerType() || 703 ento::coreFoundation::isCFObjectRef(T)) 704 return false; 705 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume 706 // is not an innter pointer type. 707 QualType OrigT = T; 708 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) 709 T = TD->getDecl()->getUnderlyingType(); 710 if (OrigT == T || !T->isPointerType()) 711 return true; 712 const PointerType* PT = T->getAs<PointerType>(); 713 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType(); 714 if (UPointeeT->isRecordType()) { 715 const RecordType *RecordTy = UPointeeT->getAs<RecordType>(); 716 if (!RecordTy->getDecl()->isCompleteDefinition()) 717 return false; 718 } 719 return true; 720} 721 722static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) { 723 if (Decl1->hasAttrs() != Decl2->hasAttrs()) 724 return false; 725 726 if (!Decl1->hasAttrs()) 727 return true; 728 729 const AttrVec &Attrs1 = Decl1->getAttrs(); 730 const AttrVec &Attrs2 = Decl2->getAttrs(); 731 // This list is very small, so this need not be optimized. 732 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) { 733 bool match = false; 734 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) { 735 // Matching attribute kind only. We are not getting into 736 // details of the attributes. For all practical purposes 737 // this is sufficient. 738 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) { 739 match = true; 740 break; 741 } 742 } 743 if (!match) 744 return false; 745 } 746 return true; 747} 748 749static bool IsValidIdentifier(ASTContext &Ctx, 750 const char *Name) { 751 if (!isIdentifierHead(Name[0])) 752 return false; 753 std::string NameString = Name; 754 NameString[0] = toLowercase(NameString[0]); 755 IdentifierInfo *II = &Ctx.Idents.get(NameString); 756 return II->getTokenID() == tok::identifier; 757} 758 759bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, 760 ObjCContainerDecl *D, 761 ObjCMethodDecl *Method) { 762 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() || 763 Method->param_size() != 0) 764 return false; 765 // Is this method candidate to be a getter? 766 QualType GRT = Method->getResultType(); 767 if (GRT->isVoidType()) 768 return false; 769 770 Selector GetterSelector = Method->getSelector(); 771 ObjCInstanceTypeFamily OIT_Family = 772 Selector::getInstTypeMethodFamily(GetterSelector); 773 774 if (OIT_Family != OIT_None) 775 return false; 776 777 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0); 778 Selector SetterSelector = 779 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 780 PP.getSelectorTable(), 781 getterName); 782 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector); 783 unsigned LengthOfPrefix = 0; 784 if (!SetterMethod) { 785 // try a different naming convention for getter: isXxxxx 786 StringRef getterNameString = getterName->getName(); 787 bool IsPrefix = getterNameString.startswith("is"); 788 // Note that we don't want to change an isXXX method of retainable object 789 // type to property (readonly or otherwise). 790 if (IsPrefix && GRT->isObjCRetainableType()) 791 return false; 792 if (IsPrefix || getterNameString.startswith("get")) { 793 LengthOfPrefix = (IsPrefix ? 2 : 3); 794 const char *CGetterName = getterNameString.data() + LengthOfPrefix; 795 // Make sure that first character after "is" or "get" prefix can 796 // start an identifier. 797 if (!IsValidIdentifier(Ctx, CGetterName)) 798 return false; 799 if (CGetterName[0] && isUppercase(CGetterName[0])) { 800 getterName = &Ctx.Idents.get(CGetterName); 801 SetterSelector = 802 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 803 PP.getSelectorTable(), 804 getterName); 805 SetterMethod = D->getInstanceMethod(SetterSelector); 806 } 807 } 808 } 809 810 if (SetterMethod) { 811 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0) 812 return false; 813 if (SetterMethod->isDeprecated() || 814 !AttributesMatch(Method, SetterMethod)) 815 return false; 816 817 // Is this a valid setter, matching the target getter? 818 QualType SRT = SetterMethod->getResultType(); 819 if (!SRT->isVoidType()) 820 return false; 821 const ParmVarDecl *argDecl = *SetterMethod->param_begin(); 822 QualType ArgType = argDecl->getType(); 823 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT)) 824 return false; 825 edit::Commit commit(*Editor); 826 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit, 827 LengthOfPrefix); 828 Editor->commit(commit); 829 return true; 830 } 831 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) { 832 // Try a non-void method with no argument (and no setter or property of same name 833 // as a 'readonly' property. 834 edit::Commit commit(*Editor); 835 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit, 836 LengthOfPrefix); 837 Editor->commit(commit); 838 return true; 839 } 840 return false; 841} 842 843void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx, 844 ObjCMethodDecl *OM) { 845 if (OM->isImplicit() || 846 !OM->isInstanceMethod() || 847 OM->hasAttr<ObjCReturnsInnerPointerAttr>()) 848 return; 849 850 QualType RT = OM->getResultType(); 851 if (!TypeIsInnerPointer(RT) || 852 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition()) 853 return; 854 855 edit::Commit commit(*Editor); 856 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER"); 857 Editor->commit(commit); 858} 859 860void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, 861 ObjCPropertyDecl *P) { 862 QualType T = P->getType(); 863 864 if (!TypeIsInnerPointer(T) || 865 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition()) 866 return; 867 edit::Commit commit(*Editor); 868 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER "); 869 Editor->commit(commit); 870} 871 872void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx, 873 ObjCContainerDecl *CDecl) { 874 if (CDecl->isDeprecated()) 875 return; 876 877 // migrate methods which can have instancetype as their result type. 878 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(), 879 MEnd = CDecl->meth_end(); 880 M != MEnd; ++M) { 881 ObjCMethodDecl *Method = (*M); 882 if (Method->isDeprecated()) 883 continue; 884 migrateMethodInstanceType(Ctx, CDecl, Method); 885 } 886} 887 888void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, 889 ObjCContainerDecl *CDecl, 890 ObjCMethodDecl *OM, 891 ObjCInstanceTypeFamily OIT_Family) { 892 if (OM->isInstanceMethod() || 893 OM->getResultType() == Ctx.getObjCInstanceType() || 894 !OM->getResultType()->isObjCIdType()) 895 return; 896 897 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class 898 // NSYYYNamE with matching names be at least 3 characters long. 899 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 900 if (!IDecl) { 901 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) 902 IDecl = CatDecl->getClassInterface(); 903 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl)) 904 IDecl = ImpDecl->getClassInterface(); 905 } 906 if (!IDecl) 907 return; 908 909 std::string StringClassName = IDecl->getName(); 910 StringRef LoweredClassName(StringClassName); 911 std::string StringLoweredClassName = LoweredClassName.lower(); 912 LoweredClassName = StringLoweredClassName; 913 914 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0); 915 // Handle method with no name at its first selector slot; e.g. + (id):(int)x. 916 if (!MethodIdName) 917 return; 918 919 std::string MethodName = MethodIdName->getName(); 920 if (OIT_Family == OIT_Singleton) { 921 StringRef STRefMethodName(MethodName); 922 size_t len = 0; 923 if (STRefMethodName.startswith("standard")) 924 len = strlen("standard"); 925 else if (STRefMethodName.startswith("shared")) 926 len = strlen("shared"); 927 else if (STRefMethodName.startswith("default")) 928 len = strlen("default"); 929 else 930 return; 931 MethodName = STRefMethodName.substr(len); 932 } 933 std::string MethodNameSubStr = MethodName.substr(0, 3); 934 StringRef MethodNamePrefix(MethodNameSubStr); 935 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower(); 936 MethodNamePrefix = StringLoweredMethodNamePrefix; 937 size_t Ix = LoweredClassName.rfind(MethodNamePrefix); 938 if (Ix == StringRef::npos) 939 return; 940 std::string ClassNamePostfix = LoweredClassName.substr(Ix); 941 StringRef LoweredMethodName(MethodName); 942 std::string StringLoweredMethodName = LoweredMethodName.lower(); 943 LoweredMethodName = StringLoweredMethodName; 944 if (!LoweredMethodName.startswith(ClassNamePostfix)) 945 return; 946 ReplaceWithInstancetype(*this, OM); 947} 948 949static bool IsVoidStarType(QualType Ty) { 950 if (!Ty->isPointerType()) 951 return false; 952 953 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr())) 954 Ty = TD->getDecl()->getUnderlyingType(); 955 956 // Is the type void*? 957 const PointerType* PT = Ty->getAs<PointerType>(); 958 if (PT->getPointeeType().getUnqualifiedType()->isVoidType()) 959 return true; 960 return IsVoidStarType(PT->getPointeeType()); 961} 962 963/// AuditedType - This routine audits the type AT and returns false if it is one of known 964/// CF object types or of the "void *" variety. It returns true if we don't care about the type 965/// such as a non-pointer or pointers which have no ownership issues (such as "int *"). 966static bool AuditedType (QualType AT) { 967 if (!AT->isAnyPointerType() && !AT->isBlockPointerType()) 968 return true; 969 // FIXME. There isn't much we can say about CF pointer type; or is there? 970 if (ento::coreFoundation::isCFObjectRef(AT) || 971 IsVoidStarType(AT) || 972 // If an ObjC object is type, assuming that it is not a CF function and 973 // that it is an un-audited function. 974 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType()) 975 return false; 976 // All other pointers are assumed audited as harmless. 977 return true; 978} 979 980void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) { 981 if (CFFunctionIBCandidates.empty()) 982 return; 983 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) { 984 CFFunctionIBCandidates.clear(); 985 FileId = 0; 986 return; 987 } 988 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED 989 const Decl *FirstFD = CFFunctionIBCandidates[0]; 990 const Decl *LastFD = 991 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1]; 992 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n"; 993 edit::Commit commit(*Editor); 994 commit.insertBefore(FirstFD->getLocStart(), PragmaString); 995 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n"; 996 SourceLocation EndLoc = LastFD->getLocEnd(); 997 // get location just past end of function location. 998 EndLoc = PP.getLocForEndOfToken(EndLoc); 999 if (isa<FunctionDecl>(LastFD)) { 1000 // For Methods, EndLoc points to the ending semcolon. So, 1001 // not of these extra work is needed. 1002 Token Tok; 1003 // get locaiton of token that comes after end of function. 1004 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true); 1005 if (!Failed) 1006 EndLoc = Tok.getLocation(); 1007 } 1008 commit.insertAfterToken(EndLoc, PragmaString); 1009 Editor->commit(commit); 1010 FileId = 0; 1011 CFFunctionIBCandidates.clear(); 1012} 1013 1014void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) { 1015 if (Decl->isDeprecated()) 1016 return; 1017 1018 if (Decl->hasAttr<CFAuditedTransferAttr>()) { 1019 assert(CFFunctionIBCandidates.empty() && 1020 "Cannot have audited functions/methods inside user " 1021 "provided CF_IMPLICIT_BRIDGING_ENABLE"); 1022 return; 1023 } 1024 1025 // Finction must be annotated first. 1026 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) { 1027 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl); 1028 if (AuditKind == CF_BRIDGING_ENABLE) { 1029 CFFunctionIBCandidates.push_back(Decl); 1030 if (!FileId) 1031 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue(); 1032 } 1033 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) { 1034 if (!CFFunctionIBCandidates.empty()) { 1035 CFFunctionIBCandidates.push_back(Decl); 1036 if (!FileId) 1037 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue(); 1038 } 1039 } 1040 else 1041 AnnotateImplicitBridging(Ctx); 1042 } 1043 else { 1044 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl)); 1045 AnnotateImplicitBridging(Ctx); 1046 } 1047} 1048 1049void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, 1050 const CallEffects &CE, 1051 const FunctionDecl *FuncDecl, 1052 bool ResultAnnotated) { 1053 // Annotate function. 1054 if (!ResultAnnotated) { 1055 RetEffect Ret = CE.getReturnValue(); 1056 const char *AnnotationString = 0; 1057 if (Ret.getObjKind() == RetEffect::CF) { 1058 if (Ret.isOwned() && 1059 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition()) 1060 AnnotationString = " CF_RETURNS_RETAINED"; 1061 else if (Ret.notOwned() && 1062 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition()) 1063 AnnotationString = " CF_RETURNS_NOT_RETAINED"; 1064 } 1065 else if (Ret.getObjKind() == RetEffect::ObjC) { 1066 if (Ret.isOwned() && 1067 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition()) 1068 AnnotationString = " NS_RETURNS_RETAINED"; 1069 } 1070 1071 if (AnnotationString) { 1072 edit::Commit commit(*Editor); 1073 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString); 1074 Editor->commit(commit); 1075 } 1076 } 1077 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1078 unsigned i = 0; 1079 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(), 1080 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) { 1081 const ParmVarDecl *pd = *pi; 1082 ArgEffect AE = AEArgs[i]; 1083 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() && 1084 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) { 1085 edit::Commit commit(*Editor); 1086 commit.insertBefore(pd->getLocation(), "CF_CONSUMED "); 1087 Editor->commit(commit); 1088 } 1089 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() && 1090 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) { 1091 edit::Commit commit(*Editor); 1092 commit.insertBefore(pd->getLocation(), "NS_CONSUMED "); 1093 Editor->commit(commit); 1094 } 1095 } 1096} 1097 1098 1099ObjCMigrateASTConsumer::CF_BRIDGING_KIND 1100 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation( 1101 ASTContext &Ctx, 1102 const FunctionDecl *FuncDecl) { 1103 if (FuncDecl->hasBody()) 1104 return CF_BRIDGING_NONE; 1105 1106 CallEffects CE = CallEffects::getEffect(FuncDecl); 1107 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() || 1108 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() || 1109 FuncDecl->getAttr<NSReturnsRetainedAttr>() || 1110 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() || 1111 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>()); 1112 1113 // Trivial case of when funciton is annotated and has no argument. 1114 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0) 1115 return CF_BRIDGING_NONE; 1116 1117 bool ReturnCFAudited = false; 1118 if (!FuncIsReturnAnnotated) { 1119 RetEffect Ret = CE.getReturnValue(); 1120 if (Ret.getObjKind() == RetEffect::CF && 1121 (Ret.isOwned() || Ret.notOwned())) 1122 ReturnCFAudited = true; 1123 else if (!AuditedType(FuncDecl->getResultType())) 1124 return CF_BRIDGING_NONE; 1125 } 1126 1127 // At this point result type is audited for potential inclusion. 1128 // Now, how about argument types. 1129 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1130 unsigned i = 0; 1131 bool ArgCFAudited = false; 1132 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(), 1133 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) { 1134 const ParmVarDecl *pd = *pi; 1135 ArgEffect AE = AEArgs[i]; 1136 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) { 1137 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>()) 1138 ArgCFAudited = true; 1139 else if (AE == IncRef) 1140 ArgCFAudited = true; 1141 } 1142 else { 1143 QualType AT = pd->getType(); 1144 if (!AuditedType(AT)) { 1145 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated); 1146 return CF_BRIDGING_NONE; 1147 } 1148 } 1149 } 1150 if (ReturnCFAudited || ArgCFAudited) 1151 return CF_BRIDGING_ENABLE; 1152 1153 return CF_BRIDGING_MAY_INCLUDE; 1154} 1155 1156void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx, 1157 ObjCContainerDecl *CDecl) { 1158 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated()) 1159 return; 1160 1161 // migrate methods which can have instancetype as their result type. 1162 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(), 1163 MEnd = CDecl->meth_end(); 1164 M != MEnd; ++M) { 1165 ObjCMethodDecl *Method = (*M); 1166 migrateCFAnnotation(Ctx, Method); 1167 } 1168} 1169 1170void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, 1171 const CallEffects &CE, 1172 const ObjCMethodDecl *MethodDecl, 1173 bool ResultAnnotated) { 1174 // Annotate function. 1175 if (!ResultAnnotated) { 1176 RetEffect Ret = CE.getReturnValue(); 1177 const char *AnnotationString = 0; 1178 if (Ret.getObjKind() == RetEffect::CF) { 1179 if (Ret.isOwned() && 1180 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition()) 1181 AnnotationString = " CF_RETURNS_RETAINED"; 1182 else if (Ret.notOwned() && 1183 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition()) 1184 AnnotationString = " CF_RETURNS_NOT_RETAINED"; 1185 } 1186 else if (Ret.getObjKind() == RetEffect::ObjC) { 1187 ObjCMethodFamily OMF = MethodDecl->getMethodFamily(); 1188 switch (OMF) { 1189 case clang::OMF_alloc: 1190 case clang::OMF_new: 1191 case clang::OMF_copy: 1192 case clang::OMF_init: 1193 case clang::OMF_mutableCopy: 1194 break; 1195 1196 default: 1197 if (Ret.isOwned() && 1198 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition()) 1199 AnnotationString = " NS_RETURNS_RETAINED"; 1200 break; 1201 } 1202 } 1203 1204 if (AnnotationString) { 1205 edit::Commit commit(*Editor); 1206 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString); 1207 Editor->commit(commit); 1208 } 1209 } 1210 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1211 unsigned i = 0; 1212 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(), 1213 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) { 1214 const ParmVarDecl *pd = *pi; 1215 ArgEffect AE = AEArgs[i]; 1216 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() && 1217 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) { 1218 edit::Commit commit(*Editor); 1219 commit.insertBefore(pd->getLocation(), "CF_CONSUMED "); 1220 Editor->commit(commit); 1221 } 1222 } 1223} 1224 1225void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( 1226 ASTContext &Ctx, 1227 const ObjCMethodDecl *MethodDecl) { 1228 if (MethodDecl->hasBody() || MethodDecl->isImplicit()) 1229 return; 1230 1231 CallEffects CE = CallEffects::getEffect(MethodDecl); 1232 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() || 1233 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() || 1234 MethodDecl->getAttr<NSReturnsRetainedAttr>() || 1235 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() || 1236 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>()); 1237 1238 if (CE.getReceiver() == DecRefMsg && 1239 !MethodDecl->getAttr<NSConsumesSelfAttr>() && 1240 MethodDecl->getMethodFamily() != OMF_init && 1241 MethodDecl->getMethodFamily() != OMF_release && 1242 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) { 1243 edit::Commit commit(*Editor); 1244 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF"); 1245 Editor->commit(commit); 1246 } 1247 1248 // Trivial case of when funciton is annotated and has no argument. 1249 if (MethodIsReturnAnnotated && 1250 (MethodDecl->param_begin() == MethodDecl->param_end())) 1251 return; 1252 1253 if (!MethodIsReturnAnnotated) { 1254 RetEffect Ret = CE.getReturnValue(); 1255 if ((Ret.getObjKind() == RetEffect::CF || 1256 Ret.getObjKind() == RetEffect::ObjC) && 1257 (Ret.isOwned() || Ret.notOwned())) { 1258 AddCFAnnotations(Ctx, CE, MethodDecl, false); 1259 return; 1260 } 1261 else if (!AuditedType(MethodDecl->getResultType())) 1262 return; 1263 } 1264 1265 // At this point result type is either annotated or audited. 1266 // Now, how about argument types. 1267 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1268 unsigned i = 0; 1269 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(), 1270 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) { 1271 const ParmVarDecl *pd = *pi; 1272 ArgEffect AE = AEArgs[i]; 1273 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef || 1274 !AuditedType(pd->getType())) { 1275 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated); 1276 return; 1277 } 1278 } 1279 return; 1280} 1281 1282namespace { 1283 1284class RewritesReceiver : public edit::EditsReceiver { 1285 Rewriter &Rewrite; 1286 1287public: 1288 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { } 1289 1290 virtual void insert(SourceLocation loc, StringRef text) { 1291 Rewrite.InsertText(loc, text); 1292 } 1293 virtual void replace(CharSourceRange range, StringRef text) { 1294 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text); 1295 } 1296}; 1297 1298} 1299 1300static bool 1301IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) { 1302 bool Invalid = false; 1303 const SrcMgr::SLocEntry &SEntry = 1304 Ctx.getSourceManager().getSLocEntry(FID, &Invalid); 1305 if (!Invalid && SEntry.isFile()) { 1306 const SrcMgr::FileInfo &FI = SEntry.getFile(); 1307 if (!FI.hasLineDirectives()) { 1308 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem) 1309 return true; 1310 if (FI.getFileCharacteristic() == SrcMgr::C_System) { 1311 // This file is in a system header directory. Continue with commiting change 1312 // only if it is a user specified system directory because user put a 1313 // .system_framework file in the framework directory. 1314 StringRef Directory(file->getDir()->getName()); 1315 size_t Ix = Directory.rfind(".framework"); 1316 if (Ix == StringRef::npos) 1317 return true; 1318 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework")); 1319 PatchToSystemFramework += ".system_framework"; 1320 if (!llvm::sys::fs::exists(PatchToSystemFramework.data())) 1321 return true; 1322 } 1323 } 1324 } 1325 return false; 1326} 1327 1328void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { 1329 1330 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl(); 1331 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) { 1332 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); 1333 D != DEnd; ++D) { 1334 if (unsigned FID = 1335 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue()) 1336 if (FileId && FileId != FID) { 1337 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 1338 AnnotateImplicitBridging(Ctx); 1339 } 1340 1341 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D)) 1342 migrateObjCInterfaceDecl(Ctx, CDecl); 1343 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) 1344 migrateObjCInterfaceDecl(Ctx, CatDecl); 1345 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) 1346 ObjCProtocolDecls.insert(PDecl); 1347 else if (const ObjCImplementationDecl *ImpDecl = 1348 dyn_cast<ObjCImplementationDecl>(*D)) { 1349 if (ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) 1350 migrateProtocolConformance(Ctx, ImpDecl); 1351 } 1352 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) { 1353 DeclContext::decl_iterator N = D; 1354 ++N; 1355 if (N != DEnd) 1356 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N)) { 1357 if (ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros) 1358 migrateNSEnumDecl(Ctx, ED, TD); 1359 } 1360 } 1361 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) { 1362 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 1363 migrateCFAnnotation(Ctx, FD); 1364 } 1365 1366 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) { 1367 // migrate methods which can have instancetype as their result type. 1368 if (ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) 1369 migrateAllMethodInstaceType(Ctx, CDecl); 1370 // annotate methods with CF annotations. 1371 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 1372 migrateARCSafeAnnotation(Ctx, CDecl); 1373 } 1374 } 1375 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 1376 AnnotateImplicitBridging(Ctx); 1377 } 1378 1379 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts()); 1380 RewritesReceiver Rec(rewriter); 1381 Editor->applyRewrites(Rec); 1382 1383 for (Rewriter::buffer_iterator 1384 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) { 1385 FileID FID = I->first; 1386 RewriteBuffer &buf = I->second; 1387 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID); 1388 assert(file); 1389 if (IsReallyASystemHeader(Ctx, file, FID)) 1390 continue; 1391 SmallString<512> newText; 1392 llvm::raw_svector_ostream vecOS(newText); 1393 buf.write(vecOS); 1394 vecOS.flush(); 1395 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy( 1396 StringRef(newText.data(), newText.size()), file->getName()); 1397 SmallString<64> filePath(file->getName()); 1398 FileMgr.FixupRelativePath(filePath); 1399 Remapper.remap(filePath.str(), memBuf); 1400 } 1401 1402 if (IsOutputFile) { 1403 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics()); 1404 } else { 1405 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics()); 1406 } 1407} 1408 1409bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) { 1410 CI.getDiagnostics().setIgnoreAllWarnings(true); 1411 return true; 1412} 1413 1414ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, 1415 StringRef InFile) { 1416 PPConditionalDirectiveRecord * 1417 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager()); 1418 CI.getPreprocessor().addPPCallbacks(PPRec); 1419 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile, 1420 FrontendOptions::ObjCMT_MigrateAll, 1421 Remapper, 1422 CI.getFileManager(), 1423 PPRec, 1424 CI.getPreprocessor(), 1425 /*isOutputFile=*/true); 1426} 1427