diff options
Diffstat (limited to 'lib')
268 files changed, 7893 insertions, 6757 deletions
diff --git a/lib/ARCMigrate/ARCMT.cpp b/lib/ARCMigrate/ARCMT.cpp index 74c9974cc8102..3c7b593be6d44 100644 --- a/lib/ARCMigrate/ARCMT.cpp +++ b/lib/ARCMigrate/ARCMT.cpp @@ -226,7 +226,7 @@ static void emitPremigrationErrors(const CapturedDiagList &arcDiags, new DiagnosticsEngine(DiagID, diagOpts, &printer, /*ShouldOwnClient=*/false)); Diags->setSourceManager(&PP.getSourceManager()); - + printer.BeginSourceFile(PP.getLangOpts(), &PP); arcDiags.reportDiagnostics(*Diags); printer.EndSourceFile(); @@ -305,7 +305,7 @@ bool arcmt::checkForManualIssues( // After parsing of source files ended, we want to reuse the // diagnostics objects to emit further diagnostics. - // We call BeginSourceFile because DiagnosticConsumer requires that + // We call BeginSourceFile because DiagnosticConsumer requires that // diagnostics with source range information are emitted only in between // BeginSourceFile() and EndSourceFile(). DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor()); @@ -572,7 +572,7 @@ bool MigrationProcess::applyTransform(TransformFn trans, // After parsing of source files ended, we want to reuse the // diagnostics objects to emit further diagnostics. - // We call BeginSourceFile because DiagnosticConsumer requires that + // We call BeginSourceFile because DiagnosticConsumer requires that // diagnostics with source range information are emitted only in between // BeginSourceFile() and EndSourceFile(). DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor()); diff --git a/lib/ARCMigrate/FileRemapper.cpp b/lib/ARCMigrate/FileRemapper.cpp index 4dedac88f982d..ccc8c9ee30ffe 100644 --- a/lib/ARCMigrate/FileRemapper.cpp +++ b/lib/ARCMigrate/FileRemapper.cpp @@ -67,7 +67,7 @@ bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag, llvm::MemoryBuffer::getFile(infoFile); if (!fileBuf) return report("Error opening file: " + infoFile, Diag); - + SmallVector<StringRef, 64> lines; fileBuf.get()->getBuffer().split(lines, "\n"); @@ -78,7 +78,7 @@ bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag, return report("Invalid file data: '" + lines[idx+1] + "' not a number", Diag); StringRef toFilename = lines[idx+2]; - + const FileEntry *origFE = FileMgr->getFile(fromFilename); if (!origFE) { if (ignoreIfFilesChanged) @@ -152,7 +152,7 @@ bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) { llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); newOut.write(mem->getBufferStart(), mem->getBufferSize()); newOut.close(); - + const FileEntry *newE = FileMgr->getFile(tempPath); remap(origFE, newE); infoOut << newE->getName() << '\n'; diff --git a/lib/ARCMigrate/Internals.h b/lib/ARCMigrate/Internals.h index 4f153b1ad2f4f..1a261c1e31aa3 100644 --- a/lib/ARCMigrate/Internals.h +++ b/lib/ARCMigrate/Internals.h @@ -25,7 +25,7 @@ namespace arcmt { class CapturedDiagList { typedef std::list<StoredDiagnostic> ListTy; ListTy List; - + public: void push_back(const StoredDiagnostic &diag) { List.push_back(diag); } diff --git a/lib/ARCMigrate/ObjCMT.cpp b/lib/ARCMigrate/ObjCMT.cpp index 433e6194a2c26..7e9bc6a5bdc60 100644 --- a/lib/ARCMigrate/ObjCMT.cpp +++ b/lib/ARCMigrate/ObjCMT.cpp @@ -46,7 +46,7 @@ class ObjCMigrateASTConsumer : public ASTConsumer { CF_BRIDGING_ENABLE, CF_BRIDGING_MAY_INCLUDE }; - + void migrateDecl(Decl *D); void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D); void migrateProtocolConformance(ASTContext &Ctx, @@ -63,26 +63,26 @@ class ObjCMigrateASTConsumer : public ASTConsumer { void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl, ObjCMethodDecl *OM, ObjCInstanceTypeFamily OIT_Family = OIT_None); - + void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl); void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE, const FunctionDecl *FuncDecl, bool ResultAnnotated); void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE, const ObjCMethodDecl *MethodDecl, bool ResultAnnotated); - + void AnnotateImplicitBridging(ASTContext &Ctx); - + CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx, const FunctionDecl *FuncDecl); - + void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl); - + void migrateAddMethodAnnotation(ASTContext &Ctx, const ObjCMethodDecl *MethodDecl); void inferDesignatedInitializers(ASTContext &Ctx, const ObjCImplementationDecl *ImplD); - + bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc); public: @@ -225,7 +225,7 @@ namespace { isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) || isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr)); } - + /// - Rewrite message expression for Objective-C setter and getters into /// property-dot syntax. bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg, @@ -239,17 +239,17 @@ namespace { if (const Expr *Receiver = Msg->getInstanceReceiver()) if (Receiver->getType()->isObjCBuiltinType()) return false; - + const ObjCMethodDecl *Method = Msg->getMethodDecl(); if (!Method) return false; if (!Method->isPropertyAccessor()) return false; - + const ObjCPropertyDecl *Prop = Method->findPropertyDecl(); if (!Prop) return false; - + SourceRange MsgRange = Msg->getSourceRange(); bool ReceiverIsSuper = (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); @@ -276,7 +276,7 @@ namespace { PropertyDotString = "."; PropertyDotString += Prop->getName(); commit.replace(SpaceRange, PropertyDotString); - + // remove '[' ']' commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), ""); commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), ""); @@ -465,7 +465,7 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, PropertyString += "(nonatomic"; LParenAdded = true; } - + std::string PropertyNameString = Getter->getNameAsString(); StringRef PropertyName(PropertyNameString); if (LengthOfPrefix > 0) { @@ -480,8 +480,8 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, // Property with no setter may be suggested as a 'readonly' property. if (!Setter) append_attr(PropertyString, "readonly", LParenAdded); - - + + // Short circuit 'delegate' properties that contain the name "delegate" or // "dataSource", or have exact name "target" to have 'assign' attribute. if (PropertyName.equals("target") || @@ -542,7 +542,7 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, } SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc(); Selector GetterSelector = Getter->getSelector(); - + SourceLocation EndGetterSelectorLoc = StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size()); commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(), @@ -572,7 +572,7 @@ void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D) { if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D)) return; - + for (auto *Method : D->methods()) { if (Method->isDeprecated()) continue; @@ -587,7 +587,7 @@ void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx, } if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty)) return; - + for (auto *Prop : D->instance_properties()) { if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && !Prop->isDeprecated()) @@ -628,7 +628,7 @@ ClassImplementsAllMethodsAndProperties(ASTContext &Ctx, else return false; } - + // At this point, all required properties in this protocol conform to those // declared in the class. // Check that class implements the required methods of the protocol too. @@ -666,7 +666,7 @@ static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl, std::string ClassString; SourceLocation EndLoc = IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation(); - + if (Protocols.empty()) { ClassString = '<'; for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) { @@ -686,7 +686,7 @@ static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl, ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1; EndLoc = *PL; } - + commit.insertAfterToken(EndLoc, ClassString); return true; } @@ -717,7 +717,7 @@ static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl, ClassString += NSIntegerName; } ClassString += ", "; - + ClassString += TypedefDcl->getIdentifier()->getName(); ClassString += ')'; SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart()); @@ -731,7 +731,7 @@ static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl, } else return false; - + SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd(); EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc, NS.getASTContext(), /*IsDecl*/true); @@ -763,13 +763,13 @@ static void rewriteToNSMacroDecl(ASTContext &Ctx, QualType DesignatedEnumType = EnumDcl->getIntegerType(); assert(!DesignatedEnumType.isNull() && "rewriteToNSMacroDecl - underlying enum type is null"); - + PrintingPolicy Policy(Ctx.getPrintingPolicy()); std::string TypeString = DesignatedEnumType.getAsString(Policy); std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS("; ClassString += TypeString; ClassString += ", "; - + ClassString += TypedefDcl->getIdentifier()->getName(); ClassString += ") "; SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin(); @@ -781,7 +781,7 @@ static void rewriteToNSMacroDecl(ASTContext &Ctx, SourceLocation StartTypedefLoc = EnumDcl->getLocEnd(); StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1); SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd(); - + commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc)); } @@ -801,7 +801,7 @@ static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) if (BO->isShiftOp() || BO->isBitwiseOp()) return true; - + uint64_t EnumVal = Enumerator->getInitVal().getZExtValue(); if (PowerOfTwo && EnumVal) { if (!llvm::isPowerOf2_64(EnumVal)) @@ -826,7 +826,7 @@ static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2)); } -void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, +void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, const ObjCImplementationDecl *ImpDecl) { const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface(); if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated()) @@ -836,11 +836,11 @@ void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols; Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols); llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols; - + for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls) if (!ExplicitProtocols.count(ProtDecl)) PotentialImplicitProtocols.push_back(ProtDecl); - + if (PotentialImplicitProtocols.empty()) return; @@ -852,10 +852,10 @@ void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl, PotentialImplicitProtocols[i])) ConformingProtocols.push_back(PotentialImplicitProtocols[i]); - + if (ConformingProtocols.empty()) return; - + // Further reduce number of conforming protocols. If protocol P1 is in the list // protocol P2 (P2<P1>), No need to include P1. llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols; @@ -885,7 +885,7 @@ void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed( const TypedefDecl *TypedefDcl) { - + QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); if (NSAPIObj->isObjCNSIntegerType(qt)) NSIntegerTypedefed = TypedefDcl; @@ -919,10 +919,10 @@ bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, } if (TypedefDcl->isDeprecated()) return false; - + QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt); - + if (NSIntegerName.empty()) { // Also check for typedef enum {...} TD; if (const EnumType *EnumTy = qt->getAs<EnumType>()) { @@ -938,7 +938,7 @@ bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, } return false; } - + // We may still use NS_OPTIONS based on what we find in the enumertor list. bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); if (!InsertFoundation(Ctx, TypedefDcl->getLocStart())) @@ -1000,7 +1000,7 @@ void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, ObjCMethodDecl *OM) { ObjCInstanceTypeFamily OIT_Family = Selector::getInstTypeMethodFamily(OM->getSelector()); - + std::string ClassName; switch (OIT_Family) { case OIT_None: @@ -1025,7 +1025,7 @@ void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, } if (!OM->getReturnType()->isObjCIdType()) return; - + ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); if (!IDecl) { if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) @@ -1080,7 +1080,7 @@ static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) { if (!AA1) return true; const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2); - + VersionTuple Introduced1 = AA1->getIntroduced(); VersionTuple Deprecated1 = AA1->getDeprecated(); VersionTuple Obsoleted1 = AA1->getObsoleted(); @@ -1159,14 +1159,14 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, QualType GRT = Method->getReturnType(); if (GRT->isVoidType()) return false; - + Selector GetterSelector = Method->getSelector(); ObjCInstanceTypeFamily OIT_Family = Selector::getInstTypeMethodFamily(GetterSelector); - + if (OIT_Family != OIT_None) return false; - + IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0); Selector SetterSelector = SelectorTable::constructSetterSelector(PP.getIdentifierTable(), @@ -1199,7 +1199,7 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, } } } - + if (SetterMethod) { if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0) return false; @@ -1207,7 +1207,7 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, if (SetterMethod->isDeprecated() || !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch)) return false; - + // Is this a valid setter, matching the target getter? QualType SRT = SetterMethod->getReturnType(); if (!SRT->isVoidType()) @@ -1255,7 +1255,7 @@ void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx, if (!TypeIsInnerPointer(RT) || !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER")) return; - + edit::Commit commit(*Editor); commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER"); Editor->commit(commit); @@ -1277,7 +1277,7 @@ void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl) { if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl)) return; - + // migrate methods which can have instancetype as their result type. for (auto *Method : CDecl->methods()) { if (Method->isDeprecated()) @@ -1294,7 +1294,7 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, OM->getReturnType() == Ctx.getObjCInstanceType() || !OM->getReturnType()->isObjCIdType()) return; - + // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class // NSYYYNamE with matching names be at least 3 characters long. ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); @@ -1306,17 +1306,17 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, } if (!IDecl) return; - + std::string StringClassName = IDecl->getName(); StringRef LoweredClassName(StringClassName); std::string StringLoweredClassName = LoweredClassName.lower(); LoweredClassName = StringLoweredClassName; - + IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0); // Handle method with no name at its first selector slot; e.g. + (id):(int)x. if (!MethodIdName) return; - + std::string MethodName = MethodIdName->getName(); if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) { StringRef STRefMethodName(MethodName); @@ -1353,10 +1353,10 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, static bool IsVoidStarType(QualType Ty) { if (!Ty->isPointerType()) return false; - + while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr())) Ty = TD->getDecl()->getUnderlyingType(); - + // Is the type void*? const PointerType* PT = Ty->getAs<PointerType>(); if (PT->getPointeeType().getUnqualifiedType()->isVoidType()) @@ -1418,14 +1418,14 @@ void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) { void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) { if (Decl->isDeprecated()) return; - + if (Decl->hasAttr<CFAuditedTransferAttr>()) { assert(CFFunctionIBCandidates.empty() && "Cannot have audited functions/methods inside user " "provided CF_IMPLICIT_BRIDGING_ENABLE"); return; } - + // Finction must be annotated first. if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) { CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl); @@ -1469,7 +1469,7 @@ void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED")) AnnotationString = " NS_RETURNS_RETAINED"; } - + if (AnnotationString) { edit::Commit commit(*Editor); commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString); @@ -1503,18 +1503,18 @@ ObjCMigrateASTConsumer::CF_BRIDGING_KIND const FunctionDecl *FuncDecl) { if (FuncDecl->hasBody()) return CF_BRIDGING_NONE; - + CallEffects CE = CallEffects::getEffect(FuncDecl); bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() || FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() || FuncDecl->hasAttr<NSReturnsRetainedAttr>() || FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() || FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>()); - + // Trivial case of when function is annotated and has no argument. if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0) return CF_BRIDGING_NONE; - + bool ReturnCFAudited = false; if (!FuncIsReturnAnnotated) { RetEffect Ret = CE.getReturnValue(); @@ -1524,7 +1524,7 @@ ObjCMigrateASTConsumer::CF_BRIDGING_KIND else if (!AuditedType(FuncDecl->getReturnType())) return CF_BRIDGING_NONE; } - + // At this point result type is audited for potential inclusion. // Now, how about argument types. ArrayRef<ArgEffect> AEArgs = CE.getArgs(); @@ -1550,7 +1550,7 @@ ObjCMigrateASTConsumer::CF_BRIDGING_KIND } if (ReturnCFAudited || ArgCFAudited) return CF_BRIDGING_ENABLE; - + return CF_BRIDGING_MAY_INCLUDE; } @@ -1558,7 +1558,7 @@ void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl) { if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated()) return; - + // migrate methods which can have instancetype as their result type. for (const auto *Method : CDecl->methods()) migrateCFAnnotation(Ctx, Method); @@ -1588,14 +1588,14 @@ void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, case clang::OMF_init: case clang::OMF_mutableCopy: break; - + default: if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED")) AnnotationString = " NS_RETURNS_RETAINED"; break; } } - + if (AnnotationString) { edit::Commit commit(*Editor); commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString); @@ -1622,7 +1622,7 @@ void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( const ObjCMethodDecl *MethodDecl) { if (MethodDecl->hasBody() || MethodDecl->isImplicit()) return; - + CallEffects CE = CallEffects::getEffect(MethodDecl); bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() || MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() || @@ -1639,12 +1639,12 @@ void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF"); Editor->commit(commit); } - + // Trivial case of when function is annotated and has no argument. if (MethodIsReturnAnnotated && (MethodDecl->param_begin() == MethodDecl->param_end())) return; - + if (!MethodIsReturnAnnotated) { RetEffect Ret = CE.getReturnValue(); if ((Ret.getObjKind() == RetEffect::CF || @@ -1655,7 +1655,7 @@ void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( } else if (!AuditedType(MethodDecl->getReturnType())) return; } - + // At this point result type is either annotated or audited. // Now, how about argument types. ArrayRef<ArgEffect> AEArgs = CE.getArgs(); @@ -1811,7 +1811,7 @@ private: OS.write_escaped(Text) << "\",\n"; } }; - + void insert(SourceLocation Loc, StringRef Text) override { EntryWriter Writer(SourceMgr, OS); Writer.writeLoc(Loc); @@ -1835,7 +1835,7 @@ private: } // end anonymous namespace void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { - + TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl(); if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) { for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); @@ -1846,7 +1846,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) AnnotateImplicitBridging(Ctx); } - + if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D)) if (canModify(CDecl)) migrateObjCContainerDecl(Ctx, CDecl); @@ -1911,7 +1911,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { canModify(FD)) migrateCFAnnotation(Ctx, FD); } - + if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) { bool CanModify = canModify(CDecl); // migrate methods which can have instancetype as their result type. @@ -1934,7 +1934,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) AnnotateImplicitBridging(Ctx); } - + if (IsOutputFile) { std::error_code EC; llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None); diff --git a/lib/ARCMigrate/PlistReporter.cpp b/lib/ARCMigrate/PlistReporter.cpp index 2ad1c8591a9e5..9e4cb3f4cd83b 100644 --- a/lib/ARCMigrate/PlistReporter.cpp +++ b/lib/ARCMigrate/PlistReporter.cpp @@ -81,7 +81,7 @@ void arcmt::writeARCDiagsToPlist(const std::string &outPath, for (ArrayRef<StoredDiagnostic>::iterator DI = diags.begin(), DE = diags.end(); DI != DE; ++DI) { - + const StoredDiagnostic &D = *DI; if (D.getLevel() == DiagnosticsEngine::Ignored) diff --git a/lib/ARCMigrate/TransARCAssign.cpp b/lib/ARCMigrate/TransARCAssign.cpp index 80bfd22d6258a..d2b4de4891c31 100644 --- a/lib/ARCMigrate/TransARCAssign.cpp +++ b/lib/ARCMigrate/TransARCAssign.cpp @@ -65,7 +65,7 @@ public: } } } - + return true; } }; diff --git a/lib/ARCMigrate/TransAutoreleasePool.cpp b/lib/ARCMigrate/TransAutoreleasePool.cpp index a8a99fa712a3c..2d35655d186f7 100644 --- a/lib/ARCMigrate/TransAutoreleasePool.cpp +++ b/lib/ARCMigrate/TransAutoreleasePool.cpp @@ -80,7 +80,7 @@ public: Body = body; TraverseStmt(body); } - + ~AutoreleasePoolRewriter() { SmallVector<VarDecl *, 8> VarsToHandle; @@ -174,7 +174,7 @@ public: PoolVarInfo &info = PoolVars[VD]; info.Dcl = DclS; collectRefs(VD, S, info.Refs); - // Does this statement follow the pattern: + // Does this statement follow the pattern: // NSAutoreleasePool * pool = [NSAutoreleasePool new]; if (isPoolCreation(VD->getInit())) { Scopes.push_back(PoolScope()); @@ -188,7 +188,7 @@ public: } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(child)) { if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(bop->getLHS())) { if (VarDecl *VD = dyn_cast<VarDecl>(dref->getDecl())) { - // Does this statement follow the pattern: + // Does this statement follow the pattern: // pool = [NSAutoreleasePool new]; if (isNSAutoreleasePool(VD->getType()) && isPoolCreation(bop->getRHS())) { @@ -311,7 +311,7 @@ private: scope.IsFollowedBySimpleReturnStmt = true; ++SI; // the return will be included in scope, don't check it. } - + for (; SI != SE; ++SI) { nameUsedOutsideScope = !NameReferenceChecker(Pass.Ctx, scope, referenceLoc, @@ -415,7 +415,7 @@ private: IdentifierInfo *PoolII; Selector DrainSel; - + struct PoolVarInfo { DeclStmt *Dcl; ExprSet Refs; diff --git a/lib/ARCMigrate/TransBlockObjCVariable.cpp b/lib/ARCMigrate/TransBlockObjCVariable.cpp index fac6a84c45e58..85bdabb504614 100644 --- a/lib/ARCMigrate/TransBlockObjCVariable.cpp +++ b/lib/ARCMigrate/TransBlockObjCVariable.cpp @@ -43,11 +43,11 @@ class RootBlockObjCVarRewriter : class BlockVarChecker : public RecursiveASTVisitor<BlockVarChecker> { VarDecl *Var; - + typedef RecursiveASTVisitor<BlockVarChecker> base; public: BlockVarChecker(VarDecl *var) : Var(var) { } - + bool TraverseImplicitCastExpr(ImplicitCastExpr *castE) { if (DeclRefExpr * ref = dyn_cast<DeclRefExpr>(castE->getSubExpr())) { @@ -77,7 +77,7 @@ public: bool VisitBlockDecl(BlockDecl *block) { SmallVector<VarDecl *, 4> BlockVars; - + for (const auto &I : block->captures()) { VarDecl *var = I.getVariable(); if (I.isByRef() && diff --git a/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp b/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp index cbc22ed601725..0327b0def1e6b 100644 --- a/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp +++ b/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp @@ -208,7 +208,7 @@ static void cleanupDeallocOrFinalize(MigrationPass &pass) { for (auto *MD : I->instance_methods()) { if (!MD->hasBody()) continue; - + if (MD->getMethodFamily() == OMF_dealloc) { DeallocM = MD; } else if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) { diff --git a/lib/ARCMigrate/TransGCAttrs.cpp b/lib/ARCMigrate/TransGCAttrs.cpp index 4fd21aa6c2699..fb45cd92c1f65 100644 --- a/lib/ARCMigrate/TransGCAttrs.cpp +++ b/lib/ARCMigrate/TransGCAttrs.cpp @@ -48,7 +48,7 @@ public: return true; SaveAndRestore<bool> Save(FullyMigratable, isMigratable(D)); - + if (ObjCPropertyDecl *PropD = dyn_cast<ObjCPropertyDecl>(D)) { lookForAttribute(PropD, PropD->getTypeSourceInfo()); AllProps.push_back(PropD); @@ -107,7 +107,7 @@ public: Kind = MigrationContext::GCAttrOccurrence::Weak; else return false; - + MigrateCtx.AttrSet.insert(RawLoc); MigrateCtx.GCAttrs.push_back(MigrationContext::GCAttrOccurrence()); MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs.back(); @@ -164,7 +164,7 @@ public: for (auto I : D->redecls()) if (!isInMainFile(I->getLocation())) return false; - + return true; } diff --git a/lib/ARCMigrate/TransProperties.cpp b/lib/ARCMigrate/TransProperties.cpp index 1468c21a00931..912f77aeb7893 100644 --- a/lib/ARCMigrate/TransProperties.cpp +++ b/lib/ARCMigrate/TransProperties.cpp @@ -47,7 +47,7 @@ class PropertiesRewriter { MigrationContext &MigrateCtx; MigrationPass &Pass; ObjCImplementationDecl *CurImplD; - + enum PropActionKind { PropAction_None, PropAction_RetainReplacedWithStrong, @@ -118,7 +118,7 @@ public: AtPropDeclsTy::iterator findAtLoc = AtProps.find(rawAtLoc); if (findAtLoc == AtProps.end()) continue; - + PropsTy &props = findAtLoc->second; for (PropsTy::iterator I = props.begin(), E = props.end(); I != E; ++I) { if (I->PropD == propD) { @@ -137,7 +137,7 @@ public: continue; if (hasIvarWithExplicitARCOwnership(props)) continue; - + Transaction Trans(Pass.TA); rewriteProperty(props, atLoc); } @@ -170,7 +170,7 @@ private: void rewriteProperty(PropsTy &props, SourceLocation atLoc) { ObjCPropertyDecl::PropertyAttributeKind propAttrs = getPropertyAttrs(props); - + if (propAttrs & (ObjCPropertyDecl::OBJC_PR_copy | ObjCPropertyDecl::OBJC_PR_unsafe_unretained | ObjCPropertyDecl::OBJC_PR_strong | @@ -215,7 +215,7 @@ private: void rewriteAssign(PropsTy &props, SourceLocation atLoc) const { bool canUseWeak = canApplyWeak(Pass.Ctx, getPropertyType(props), /*AllowOnUnknownClass=*/Pass.isGCMigration()); - const char *toWhich = + const char *toWhich = (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "strong" : (canUseWeak ? "weak" : "unsafe_unretained"); @@ -227,7 +227,7 @@ private: if (isUserDeclared(I->IvarD)) { if (I->IvarD && I->IvarD->getType().getObjCLifetime() != Qualifiers::OCL_Weak) { - const char *toWhich = + const char *toWhich = (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "__strong " : (canUseWeak ? "__weak " : "__unsafe_unretained "); Pass.TA.insert(I->IvarD->getLocation(), toWhich); @@ -327,7 +327,7 @@ private: } } - return false; + return false; } // Returns true if all declarations in the @property have GC __weak. diff --git a/lib/ARCMigrate/TransProtectedScope.cpp b/lib/ARCMigrate/TransProtectedScope.cpp index 0fcbcbedfe04f..1bb4c1f4e4495 100644 --- a/lib/ARCMigrate/TransProtectedScope.cpp +++ b/lib/ARCMigrate/TransProtectedScope.cpp @@ -46,7 +46,7 @@ struct CaseInfo { St_CannotFix, St_Fixed } State; - + CaseInfo() : SC(nullptr), State(St_Unchecked) {} CaseInfo(SwitchCase *S, SourceRange Range) : SC(S), Range(Range), State(St_Unchecked) {} diff --git a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp index ebe289b34df8f..c411044ecde3f 100644 --- a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp +++ b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp @@ -251,7 +251,7 @@ private: while (OuterS && (isa<ParenExpr>(OuterS) || isa<CastExpr>(OuterS) || isa<ExprWithCleanups>(OuterS))); - + if (!OuterS) return std::make_pair(prevStmt, nextStmt); @@ -419,7 +419,7 @@ private: bool isRemovable(Expr *E) const { return Removables.count(E); } - + bool tryRemoving(Expr *E) const { if (isRemovable(E)) { Pass.TA.removeStmt(E); diff --git a/lib/ARCMigrate/TransUnbridgedCasts.cpp b/lib/ARCMigrate/TransUnbridgedCasts.cpp index de52bef4d2060..66167d37ac958 100644 --- a/lib/ARCMigrate/TransUnbridgedCasts.cpp +++ b/lib/ARCMigrate/TransUnbridgedCasts.cpp @@ -97,7 +97,7 @@ public: if (castType->isObjCRetainableType() == castExprType->isObjCRetainableType()) return true; - + bool exprRetainable = castExprType->isObjCIndirectLifetimeType(); bool castRetainable = castType->isObjCIndirectLifetimeType(); if (exprRetainable == castRetainable) return true; @@ -153,7 +153,7 @@ private: // Do not migrate to couple of bridge transfer casts which // cancel each other out. Leave it unchanged so error gets user // attention instead. - if (FD->getName() == "CFRetain" && + if (FD->getName() == "CFRetain" && FD->getNumParams() == 1 && FD->getParent()->isTranslationUnit() && FD->isExternallyVisible()) { diff --git a/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp b/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp index 76ce0ec90db36..220102ec49ce1 100644 --- a/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp +++ b/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp @@ -56,7 +56,7 @@ public: bool BackedBySynthesizeSetter = false; for (llvm::DenseMap<ObjCPropertyDecl*, ObjCPropertyImplDecl*>::iterator - P = SynthesizedProperties.begin(), + P = SynthesizedProperties.begin(), E = SynthesizedProperties.end(); P != E; ++P) { ObjCPropertyDecl *PropDecl = P->first; if (PropDecl->getSetterName() == ME->getSelector()) { @@ -66,11 +66,11 @@ public: } if (!BackedBySynthesizeSetter) return true; - + // Remove the setter message if RHS is null Transaction Trans(TA); Expr *RHS = ME->getArg(0); - bool RHSIsNull = + bool RHSIsNull = RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull); if (RHSIsNull && isRemovable(ME)) @@ -119,10 +119,10 @@ public: ObjCPropertyDecl *PD = PID->getPropertyDecl(); ObjCMethodDecl *setterM = PD->getSetterMethodDecl(); if (!(setterM && setterM->isDefined())) { - ObjCPropertyDecl::PropertyAttributeKind AttrKind = + ObjCPropertyDecl::PropertyAttributeKind AttrKind = PD->getPropertyAttributes(); - if (AttrKind & - (ObjCPropertyDecl::OBJC_PR_retain | + if (AttrKind & + (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy | ObjCPropertyDecl::OBJC_PR_strong)) SynthesizedProperties[PD] = PID; @@ -173,7 +173,7 @@ private: return false; bool IvarBacksPropertySynthesis = false; for (llvm::DenseMap<ObjCPropertyDecl*, ObjCPropertyImplDecl*>::iterator - P = SynthesizedProperties.begin(), + P = SynthesizedProperties.begin(), E = SynthesizedProperties.end(); P != E; ++P) { ObjCPropertyImplDecl *PropImpDecl = P->second; if (PropImpDecl && PropImpDecl->getPropertyIvarDecl() == IVDecl) { diff --git a/lib/ARCMigrate/TransformActions.cpp b/lib/ARCMigrate/TransformActions.cpp index 704be4374d3dc..3f79cc441e854 100644 --- a/lib/ARCMigrate/TransformActions.cpp +++ b/lib/ARCMigrate/TransformActions.cpp @@ -76,7 +76,7 @@ class TransformActionsImpl { End = FullSourceLoc(srcMgr.getExpansionLoc(endLoc), srcMgr); } assert(Begin.isValid() && End.isValid()); - } + } RangeComparison compareWith(const CharRange &RHS) const { if (End.isBeforeInTranslationUnitThan(RHS.Begin)) @@ -94,7 +94,7 @@ class TransformActionsImpl { else return Range_ExtendsEnd; } - + static RangeComparison compare(SourceRange LHS, SourceRange RHS, SourceManager &SrcMgr, Preprocessor &PP) { return CharRange(CharSourceRange::getTokenRange(LHS), SrcMgr, PP) @@ -485,7 +485,7 @@ void TransformActionsImpl::commitReplaceText(SourceLocation loc, SourceLocation afterText = loc.getLocWithOffset(text.size()); addRemoval(CharSourceRange::getCharRange(loc, afterText)); - commitInsert(loc, replacementText); + commitInsert(loc, replacementText); } void TransformActionsImpl::commitIncreaseIndentation(SourceRange range, diff --git a/lib/ARCMigrate/Transforms.cpp b/lib/ARCMigrate/Transforms.cpp index 1f4e6a297fc3a..4a7af28588796 100644 --- a/lib/ARCMigrate/Transforms.cpp +++ b/lib/ARCMigrate/Transforms.cpp @@ -203,7 +203,7 @@ bool trans::isGlobalVar(Expr *E) { return isGlobalVar(condOp->getTrueExpr()) && isGlobalVar(condOp->getFalseExpr()); - return false; + return false; } StringRef trans::getNilString(MigrationPass &Pass) { @@ -240,9 +240,9 @@ class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> { public: RemovablesCollector(ExprSet &removables) : Removables(removables) { } - + bool shouldWalkTypesOfTypeLocs() const { return false; } - + bool TraverseStmtExpr(StmtExpr *E) { CompoundStmt *S = E->getSubStmt(); for (CompoundStmt::body_iterator @@ -253,40 +253,40 @@ public: } return true; } - + bool VisitCompoundStmt(CompoundStmt *S) { for (auto *I : S->body()) mark(I); return true; } - + bool VisitIfStmt(IfStmt *S) { mark(S->getThen()); mark(S->getElse()); return true; } - + bool VisitWhileStmt(WhileStmt *S) { mark(S->getBody()); return true; } - + bool VisitDoStmt(DoStmt *S) { mark(S->getBody()); return true; } - + bool VisitForStmt(ForStmt *S) { mark(S->getInit()); mark(S->getInc()); mark(S->getBody()); return true; } - + private: void mark(Stmt *S) { if (!S) return; - + while (LabelStmt *Label = dyn_cast<LabelStmt>(S)) S = Label->getSubStmt(); S = S->IgnoreImplicit(); @@ -408,12 +408,12 @@ bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr, return false; lexer.LexFromRawLexer(tok); if (tok.isNot(tok::l_paren)) return false; - + Token BeforeTok = tok; Token AfterTok; AfterTok.startToken(); SourceLocation AttrLoc; - + lexer.LexFromRawLexer(tok); if (tok.is(tok::r_paren)) return false; @@ -454,7 +454,7 @@ bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr, return true; } - + return false; } @@ -493,7 +493,7 @@ bool MigrationContext::addPropertyAttribute(StringRef attr, Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") "); return true; } - + lexer.LexFromRawLexer(tok); if (tok.is(tok::r_paren)) { Pass.TA.insert(tok.getLocation(), attr); @@ -520,7 +520,7 @@ static void GCRewriteFinalize(MigrationPass &pass) { DeclContext *DC = Ctx.getTranslationUnitDecl(); Selector FinalizeSel = Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize")); - + typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl> impl_iterator; for (impl_iterator I = impl_iterator(DC->decls_begin()), @@ -528,11 +528,11 @@ static void GCRewriteFinalize(MigrationPass &pass) { for (const auto *MD : I->instance_methods()) { if (!MD->hasBody()) continue; - + if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) { const ObjCMethodDecl *FinalizeM = MD; Transaction Trans(TA); - TA.insert(FinalizeM->getSourceRange().getBegin(), + TA.insert(FinalizeM->getSourceRange().getBegin(), "#if !__has_feature(objc_arc)\n"); CharSourceRange::getTokenRange(FinalizeM->getSourceRange()); const SourceManager &SM = pass.Ctx.getSourceManager(); @@ -540,10 +540,10 @@ static void GCRewriteFinalize(MigrationPass &pass) { bool Invalid; std::string str = "\n#endif\n"; str += Lexer::getSourceText( - CharSourceRange::getTokenRange(FinalizeM->getSourceRange()), + CharSourceRange::getTokenRange(FinalizeM->getSourceRange()), SM, LangOpts, &Invalid); TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str); - + break; } } diff --git a/lib/ARCMigrate/Transforms.h b/lib/ARCMigrate/Transforms.h index 8ea4f79456a8d..bafe9fc52a274 100644 --- a/lib/ARCMigrate/Transforms.h +++ b/lib/ARCMigrate/Transforms.h @@ -103,7 +103,7 @@ public: explicit MigrationContext(MigrationPass &pass) : Pass(pass) {} ~MigrationContext(); - + typedef std::vector<ASTTraverser *>::iterator traverser_iterator; traverser_iterator traversers_begin() { return Traversers.begin(); } traverser_iterator traversers_end() { return Traversers.end(); } diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index 25dc4441aafd7..d50f4493788a0 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -492,11 +492,11 @@ comments::FullComment *ASTContext::getCommentForDecl( if (D->isInvalidDecl()) return nullptr; D = adjustDeclToTemplate(D); - + const Decl *Canonical = D->getCanonicalDecl(); llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = ParsedComments.find(Canonical); - + if (Pos != ParsedComments.end()) { if (Canonical != D) { comments::FullComment *FC = Pos->second; @@ -505,9 +505,9 @@ comments::FullComment *ASTContext::getCommentForDecl( } return Pos->second; } - + const Decl *OriginalDecl; - + const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); if (!RC) { if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { @@ -558,7 +558,7 @@ comments::FullComment *ASTContext::getCommentForDecl( if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { if (!(NonVirtualBase= NonVirtualBase->getDefinition())) continue; - + if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) return cloneFullComment(FC, D); } @@ -580,7 +580,7 @@ comments::FullComment *ASTContext::getCommentForDecl( } return nullptr; } - + // If the RawComment was attached to other redeclaration of this Decl, we // should parse the comment in context of that other Decl. This is important // because comments can contain references to parameter names which can be @@ -593,8 +593,8 @@ comments::FullComment *ASTContext::getCommentForDecl( return FC; } -void -ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, +void +ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, TemplateTemplateParmDecl *Parm) { ID.AddInteger(Parm->getDepth()); ID.AddInteger(Parm->getPosition()); @@ -602,7 +602,7 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, TemplateParameterList *Params = Parm->getTemplateParameters(); ID.AddInteger(Params->size()); - for (TemplateParameterList::const_iterator P = Params->begin(), + for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { @@ -610,7 +610,7 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, ID.AddBoolean(TTP->isParameterPack()); continue; } - + if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { ID.AddInteger(1); ID.AddBoolean(NTTP->isParameterPack()); @@ -622,11 +622,11 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, QualType T = NTTP->getExpansionType(I); ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); } - } else + } else ID.AddBoolean(false); continue; } - + auto *TTP = cast<TemplateTemplateParmDecl>(*P); ID.AddInteger(2); Profile(ID, TTP); @@ -644,17 +644,17 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); if (Canonical) return Canonical->getParam(); - + // Build a canonical template parameter list. TemplateParameterList *Params = TTP->getTemplateParameters(); SmallVector<NamedDecl *, 4> CanonParams; CanonParams.reserve(Params->size()); - for (TemplateParameterList::const_iterator P = Params->begin(), + for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) CanonParams.push_back( - TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), + TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), TTP->getDepth(), @@ -672,7 +672,7 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( ExpandedTInfos.push_back( getTrivialTypeSourceInfo(ExpandedTypes.back())); } - + Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), @@ -704,9 +704,9 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( Expr *const CanonRequiresClause = nullptr; TemplateTemplateParmDecl *CanonTTP - = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), + = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(), - TTP->getPosition(), + TTP->getPosition(), TTP->isParameterPack(), nullptr, TemplateParameterList::Create(*this, SourceLocation(), @@ -823,7 +823,7 @@ ASTContext::~ASTContext() { if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) R->Destroy(*this); } - + for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), AEnd = DeclAttrs.end(); A != AEnd; ++A) @@ -1001,7 +1001,7 @@ void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { auto It = ModuleInitializers.find(M); - if (It == ModuleInitializers.end()) + if (It == ModuleInitializers.end()) return None; auto *Inits = It->second; @@ -1098,7 +1098,7 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target, ABI.reset(createCXXABI(Target)); AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); - + // C99 6.2.5p19. InitBuiltinType(VoidTy, BuiltinType::Void); @@ -1242,13 +1242,13 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target, InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); } - + // Builtin type for __objc_yes and __objc_no ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? SignedCharTy : BoolTy); - + ObjCConstantStringType = QualType(); - + ObjCSuperType = QualType(); // void * type @@ -1281,7 +1281,7 @@ AttrVec& ASTContext::getDeclAttrs(const Decl *D) { void *Mem = Allocate(sizeof(AttrVec)); Result = new (Mem) AttrVec; } - + return *Result; } @@ -1361,11 +1361,11 @@ void ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { assert((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || - isa<UnresolvedUsingTypenameDecl>(Pattern)) && + isa<UnresolvedUsingTypenameDecl>(Pattern)) && "pattern decl is not a using decl"); assert((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || - isa<UnresolvedUsingTypenameDecl>(Inst)) && + isa<UnresolvedUsingTypenameDecl>(Inst)) && "instantiation did not produce a using decl"); assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); InstantiatedFromUsingDecl[Inst] = Pattern; @@ -1432,7 +1432,7 @@ ASTContext::overridden_methods(const CXXMethodDecl *Method) const { return overridden_method_range(Pos->second.begin(), Pos->second.end()); } -void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, +void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden) { assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); OverriddenMethods[Method].push_back(Overridden); @@ -1466,7 +1466,7 @@ void ASTContext::addedLocalImportDecl(ImportDecl *Import) { LastLocalImport = Import; return; } - + LastLocalImport->NextLocalImport = Import; LastLocalImport = Import; } @@ -1513,7 +1513,7 @@ CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { } } else if (isa<FieldDecl>(D)) - UseAlignAttrOnly = + UseAlignAttrOnly = D->hasAttr<PackedAttr>() || cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); @@ -1881,7 +1881,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: - Width = Target->getPointerWidth(0); + Width = Target->getPointerWidth(0); Align = Target->getPointerAlign(0); break; case BuiltinType::OCLSampler: @@ -2056,6 +2056,27 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { return TypeInfo(Width, Align, AlignIsRequired); } +unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { + UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); + if (I != MemoizedUnadjustedAlign.end()) + return I->second; + + unsigned UnadjustedAlign; + if (const auto *RT = T->getAs<RecordType>()) { + const RecordDecl *RD = RT->getDecl(); + const ASTRecordLayout &Layout = getASTRecordLayout(RD); + UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); + } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { + const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); + UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); + } else { + UnadjustedAlign = getTypeAlign(T); + } + + MemoizedUnadjustedAlign[T] = UnadjustedAlign; + return UnadjustedAlign; +} + unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); // Target ppc64 with QPX: simd default alignment for pointer to double is 32. @@ -2086,7 +2107,7 @@ CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { return getTypeInfoInChars(T).first; } -/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in +/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in /// characters. This method does not work on incomplete types. CharUnits ASTContext::getTypeAlignInChars(QualType T) const { return toCharUnitsFromBits(getTypeAlign(T)); @@ -2095,6 +2116,16 @@ CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { return toCharUnitsFromBits(getTypeAlign(T)); } +/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a +/// type, in characters, before alignment adustments. This method does +/// not work on incomplete types. +CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { + return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); +} +CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { + return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); +} + /// getPreferredTypeAlign - Return the "preferred" alignment of the specified /// type for the current target in bits. This can be different than the ABI /// alignment in cases where it is beneficial for performance to overalign @@ -2172,7 +2203,7 @@ void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, Ivars.push_back(I); } else { auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); - for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; + for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; Iv= Iv->getNextIvar()) Ivars.push_back(Iv); } @@ -2184,11 +2215,11 @@ void ASTContext::CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { // We can use protocol_iterator here instead of - // all_referenced_protocol_iterator since we are walking all categories. + // all_referenced_protocol_iterator since we are walking all categories. for (auto *Proto : OI->all_referenced_protocols()) { CollectInheritedProtocols(Proto, Protocols); } - + // Categories of this Interface. for (const auto *Cat : OI->visible_categories()) CollectInheritedProtocols(Cat, Protocols); @@ -2379,11 +2410,11 @@ bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { } unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { - unsigned count = 0; + unsigned count = 0; // Count ivars declared in class extension. for (const auto *Ext : OI->known_extensions()) count += Ext->ivar_size(); - + // Count ivar defined in this class's implementation. This // includes synthesized ivars. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) @@ -2471,7 +2502,7 @@ const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( /// none exists. Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { assert(VD && "Passed null params"); - assert(VD->hasAttr<BlocksAttr>() && + assert(VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"); llvm::DenseMap<const VarDecl*, Expr*>::iterator I = BlockVarCopyInits.find(VD); @@ -2481,7 +2512,7 @@ Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { /// Set the copy inialization expression of a block var decl. void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { assert(VD && Init && "Passed null params"); - assert(VD->hasAttr<BlocksAttr>() && + assert(VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"); BlockVarCopyInits[VD] = Init; } @@ -2868,9 +2899,9 @@ QualType ASTContext::getBlockPointerType(QualType T) const { /// lvalue reference to the specified type. QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { - assert(getCanonicalType(T) != OverloadTy && + assert(getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"); - + // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; @@ -3159,7 +3190,7 @@ QualType ASTContext::getVariableArrayType(QualType EltTy, // Since we don't unique expressions, it isn't possible to unique VLA's // that have an expression provided for their size. QualType Canon; - + // Be sure to pull qualifiers off the element type. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { SplitQualType canonSplit = getCanonicalType(EltTy).split(); @@ -3167,7 +3198,7 @@ QualType ASTContext::getVariableArrayType(QualType EltTy, IndexTypeQuals, Brackets); Canon = getQualifiedType(Canon, canonSplit.Quals); } - + auto *New = new (*this, TypeAlignment) VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); @@ -3184,7 +3215,7 @@ QualType ASTContext::getDependentSizedArrayType(QualType elementType, ArrayType::ArraySizeModifier ASM, unsigned elementTypeQuals, SourceRange brackets) const { - assert((!numElements || numElements->isTypeDependent() || + assert((!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"); @@ -3417,7 +3448,7 @@ ASTContext::getDependentSizedExtVectorType(QualType vecType, } else { QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, SourceLocation()); - New = new (*this, TypeAlignment) + New = new (*this, TypeAlignment) DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); } } @@ -3426,10 +3457,10 @@ ASTContext::getDependentSizedExtVectorType(QualType vecType, return QualType(New, 0); } -QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, - Expr *AddrSpaceExpr, +QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, + Expr *AddrSpaceExpr, SourceLocation AttrLoc) const { - assert(AddrSpaceExpr->isInstantiationDependent()); + assert(AddrSpaceExpr->isInstantiationDependent()); QualType canonPointeeType = getCanonicalType(PointeeType); @@ -3443,22 +3474,22 @@ QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, if (!canonTy) { canonTy = new (*this, TypeAlignment) - DependentAddressSpaceType(*this, canonPointeeType, + DependentAddressSpaceType(*this, canonPointeeType, QualType(), AddrSpaceExpr, AttrLoc); DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); Types.push_back(canonTy); } - + if (canonPointeeType == PointeeType && canonTy->getAddrSpaceExpr() == AddrSpaceExpr) - return QualType(canonTy, 0); + return QualType(canonTy, 0); auto *sugaredType = new (*this, TypeAlignment) - DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), + DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), AddrSpaceExpr, AttrLoc); Types.push_back(sugaredType); - return QualType(sugaredType, 0); + return QualType(sugaredType, 0); } /// Determine whether \p T is canonical as the result type of a function. @@ -3818,7 +3849,7 @@ QualType ASTContext::getRecordType(const RecordDecl *Decl) const { if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) - return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); + return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); auto *newType = new (*this, TypeAlignment) RecordType(Decl); Decl->TypeForDecl = newType; @@ -3831,7 +3862,7 @@ QualType ASTContext::getEnumType(const EnumDecl *Decl) const { if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) - return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); + return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); auto *newType = new (*this, TypeAlignment) EnumType(Decl); Decl->TypeForDecl = newType; @@ -3882,7 +3913,7 @@ ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, return QualType(SubstParm, 0); } -/// Retrieve a +/// Retrieve a QualType ASTContext::getSubstTemplateTypeParmPackType( const TemplateTypeParmType *Parm, const TemplateArgument &ArgPack) { @@ -3892,14 +3923,14 @@ QualType ASTContext::getSubstTemplateTypeParmPackType( assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); } #endif - + llvm::FoldingSetNodeID ID; SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); void *InsertPos = nullptr; if (SubstTemplateTypeParmPackType *SubstParm = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(SubstParm, 0); - + QualType Canon; if (!Parm->isCanonicalUnqualified()) { Canon = getCanonicalType(QualType(Parm, 0)); @@ -3913,7 +3944,7 @@ QualType ASTContext::getSubstTemplateTypeParmPackType( ArgPack); Types.push_back(SubstParm); SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); - return QualType(SubstParm, 0); + return QualType(SubstParm, 0); } /// Retrieve the template type parameter type for a template @@ -3935,7 +3966,7 @@ QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); - TemplateTypeParmType *TypeCheck + TemplateTypeParmType *TypeCheck = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!TypeCheck && "Template type parameter canonical type broken"); (void)TypeCheck; @@ -3954,7 +3985,7 @@ ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, SourceLocation NameLoc, const TemplateArgumentListInfo &Args, QualType Underlying) const { - assert(!Name.getAsDependentTemplateName() && + assert(!Name.getAsDependentTemplateName() && "No dependent template names here!"); QualType TST = getTemplateSpecializationType(Name, Args, Underlying); @@ -3974,7 +4005,7 @@ QualType ASTContext::getTemplateSpecializationType(TemplateName Template, const TemplateArgumentListInfo &Args, QualType Underlying) const { - assert(!Template.getAsDependentTemplateName() && + assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); SmallVector<TemplateArgument, 4> ArgVec; @@ -3990,7 +4021,7 @@ static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { for (const TemplateArgument &Arg : Args) if (Arg.isPackExpansion()) return true; - + return true; } #endif @@ -3999,13 +4030,13 @@ QualType ASTContext::getTemplateSpecializationType(TemplateName Template, ArrayRef<TemplateArgument> Args, QualType Underlying) const { - assert(!Template.getAsDependentTemplateName() && + assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); // Look through qualified template names. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); - - bool IsTypeAlias = + + bool IsTypeAlias = Template.getAsTemplateDecl() && isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); QualType CanonType; @@ -4037,13 +4068,13 @@ ASTContext::getTemplateSpecializationType(TemplateName Template, QualType ASTContext::getCanonicalTemplateSpecializationType( TemplateName Template, ArrayRef<TemplateArgument> Args) const { - assert(!Template.getAsDependentTemplateName() && + assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); // Look through qualified template names. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); - + // Build the canonical template specialization type. TemplateName CanonTemplate = getCanonicalTemplateName(Template); SmallVector<TemplateArgument, 4> CanonArgs; @@ -4174,7 +4205,7 @@ ASTContext::getDependentTemplateSpecializationType( NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const { - assert((!NNS || NNS->isDependent()) && + assert((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"); llvm::FoldingSetNodeID ID; @@ -4309,7 +4340,7 @@ static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { if (Protocols[0]->getCanonicalDecl() != Protocols[0]) return false; - + for (unsigned i = 1; i != Protocols.size(); ++i) if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || Protocols[i]->getCanonicalDecl() != Protocols[i]) @@ -4534,7 +4565,7 @@ bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *IC) { if (!QT->isObjCQualifiedIdType()) return false; - + if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { // If both the right and left sides have qualifiers. for (auto *Proto : OPT->quals()) { @@ -4578,7 +4609,7 @@ bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, } if (Conforms) return true; - + for (auto *PI : InheritedProtocols) { // If both the right and left sides have qualifiers. bool Adopts = false; @@ -4639,7 +4670,7 @@ QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, // Prefer the definition, if there is one. if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) Decl = Def; - + void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); auto *T = new (Mem) ObjCInterfaceType(Decl); Decl->TypeForDecl = T; @@ -4870,7 +4901,7 @@ CanQualType ASTContext::getSizeType() const { return getFromTargetType(Target->getSizeType()); } -/// Return the unique signed counterpart of the integer type +/// Return the unique signed counterpart of the integer type /// corresponding to size_t. CanQualType ASTContext::getSignedSizeType() const { return getFromTargetType(Target->getSignedSizeType()); @@ -5059,14 +5090,14 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { const auto *T1MPType = T1->getAs<MemberPointerType>(); const auto *T2MPType = T2->getAs<MemberPointerType>(); - if (T1MPType && T2MPType && - hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), + if (T1MPType && T2MPType && + hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), QualType(T2MPType->getClass(), 0))) { T1 = T1MPType->getPointeeType(); T2 = T2MPType->getPointeeType(); return true; } - + if (getLangOpts().ObjC1) { const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); @@ -5076,9 +5107,9 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { return true; } } - + // FIXME: Block pointers, too? - + return false; } @@ -5170,7 +5201,7 @@ TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { TemplateDecl *Template = Name.getAsTemplateDecl(); if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) Template = getCanonicalTemplateTemplateParmDecl(TTP); - + // The canonical template name is the canonical template declaration. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); } @@ -5245,7 +5276,7 @@ ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { case TemplateArgument::Pack: { if (Arg.pack_size() == 0) return Arg; - + auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; unsigned Idx = 0; for (TemplateArgument::pack_iterator A = Arg.pack_begin(), @@ -5289,7 +5320,7 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); - + // If we have some kind of dependent-named type (e.g., "typename T::type"), // break it apart into its prefix and identifier, then reconsititute those // as the canonical nested-name-specifier. This is required to canonicalize @@ -5298,7 +5329,7 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { // typedef typename T::type T1; // typedef typename T1::type T2; if (const auto *DNT = T->getAs<DependentNameType>()) - return NestedNameSpecifier::Create(*this, DNT->getQualifier(), + return NestedNameSpecifier::Create(*this, DNT->getQualifier(), const_cast<IdentifierInfo *>(DNT->getIdentifier())); // Otherwise, just canonicalize the type, and force it to be a TypeSpec. @@ -5930,24 +5961,24 @@ bool ASTContext::BlockRequiresCopying(QualType Ty, if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { const Expr *copyExpr = getBlockVarCopyInits(D); if (!copyExpr && record->hasTrivialDestructor()) return false; - + return true; } - + // The block needs copy/destroy helpers if Ty is non-trivial to destructively // move or destroy. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) return true; if (!Ty->isObjCRetainableType()) return false; - + Qualifiers qs = Ty.getQualifiers(); - + // If we have lifetime, that dominates. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { switch (lifetime) { case Qualifiers::OCL_None: llvm_unreachable("impossible"); - + // These are just bits as far as the runtime is concerned. case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: @@ -5971,7 +6002,7 @@ bool ASTContext::getByrefLifetime(QualType Ty, if (!getLangOpts().ObjC1 || getLangOpts().getGC() != LangOptions::NonGC) return false; - + HasByrefExtendedLayout = false; if (Ty->isRecordType()) { HasByrefExtendedLayout = true; @@ -6009,7 +6040,7 @@ static bool isTypeTypedefedAsBOOL(QualType T) { CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { if (!type->isIncompleteArrayType() && type->isIncompleteType()) return CharUnits::Zero(); - + CharUnits sz = getTypeSizeInChars(type); // Make all integer and enum types at least as large as an int @@ -6085,11 +6116,11 @@ std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { S += charUnitsToString(ParmOffset); // Block pointer and offset. S += "@?0"; - + // Argument types. ParmOffset = PtrSize; for (auto PVDecl : Decl->parameters()) { - QualType PType = PVDecl->getOriginalType(); + QualType PType = PVDecl->getOriginalType(); if (const auto *AT = dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of @@ -6122,8 +6153,8 @@ ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; - - assert(sz.isPositive() && + + assert(sz.isPositive() && "getObjCEncodingForFunctionDecl - Incomplete param type"); ParmOffset += sz; } @@ -6145,12 +6176,12 @@ ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } - + return S; } /// getObjCEncodingForMethodParameter - Return the encoded type for a single -/// method parameter or return type. If Extended, include class names and +/// method parameter or return type. If Extended, include class names and /// block object types. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string& S, @@ -6160,9 +6191,9 @@ void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, // Encode parameter type. getObjCEncodingForTypeImpl(T, S, true, true, nullptr, true /*OutermostType*/, - false /*EncodingProperty*/, - false /*StructField*/, - Extended /*EncodeBlockParameters*/, + false /*EncodingProperty*/, + false /*StructField*/, + Extended /*EncodeBlockParameters*/, Extended /*EncodeClassNames*/); } @@ -6188,8 +6219,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; - - assert(sz.isPositive() && + + assert(sz.isPositive() && "getObjCEncodingForMethodDecl - Incomplete param type"); ParmOffset += sz; } @@ -6211,12 +6242,12 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, PType = PVDecl->getType(); } else if (PType->isFunctionType()) PType = PVDecl->getType(); - getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), + getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), PType, S, Extended); S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } - + return S; } @@ -6457,11 +6488,11 @@ static char getObjCEncodingForPrimitiveKind(const ASTContext *C, static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { EnumDecl *Enum = ET->getDecl(); - + // The encoding of an non-fixed enum type is always 'i', regardless of size. if (!Enum->isFixed()) return 'i'; - + // The encoding of a fixed enum type matches its fixed underlying type. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); return getObjCEncodingForPrimitiveKind(C, BT->getKind()); @@ -6709,7 +6740,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += "@?"; // Unlike a pointer-to-function, which is "^?". if (EncodeBlockParameters) { const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); - + S += '<'; // Block return type getObjCEncodingForTypeImpl( @@ -6747,7 +6778,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, // TODO: Double check to make sure this intentionally falls through. LLVM_FALLTHROUGH; } - + case Type::ObjCInterface: { // Ignore protocol qualifiers when mangling at this level. // @encode(class_name) @@ -6837,7 +6868,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, } S += '@'; - if (OPT->getInterfaceDecl() && + if (OPT->getInterfaceDecl() && (FD || EncodingProperty || EncodeClassNames)) { S += '"'; S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); @@ -6862,7 +6893,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, if (NotEncodedT) *NotEncodedT = T; return; - + // We could see an undeduced auto type here during error recovery. // Just ignore it. case Type::Auto: @@ -6910,7 +6941,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, } } } - + unsigned i = 0; for (auto *Field : RDecl->fields()) { uint64_t offs = layout.getFieldOffset(i); @@ -6971,7 +7002,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, #ifndef NDEBUG assert(CurOffs <= CurLayObj->first); if (CurOffs < CurLayObj->first) { - uint64_t padding = CurLayObj->first - CurOffs; + uint64_t padding = CurLayObj->first - CurOffs; // FIXME: There doesn't seem to be a way to indicate in the encoding that // packing/alignment of members is different that normal, in which case // the encoding will be out-of-sync with the real layout. @@ -7071,15 +7102,15 @@ TypedefDecl *ASTContext::getObjCClassDecl() const { ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { if (!ObjCProtocolClassDecl) { - ObjCProtocolClassDecl - = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), + ObjCProtocolClassDecl + = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), &Idents.get("Protocol"), /*typeParamList=*/nullptr, /*PrevDecl=*/nullptr, - SourceLocation(), true); + SourceLocation(), true); } - + return ObjCProtocolClassDecl; } @@ -7485,7 +7516,7 @@ ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const { assert(NNS && "Missing nested-name-specifier in qualified template name"); - + // FIXME: Canonicalization? llvm::FoldingSetNodeID ID; QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); @@ -7540,22 +7571,22 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, /// Retrieve the template name that represents a dependent /// template name such as \c MetaFun::template operator+. -TemplateName +TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, OverloadedOperatorKind Operator) const { assert((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"); - + llvm::FoldingSetNodeID ID; DependentTemplateName::Profile(ID, NNS, Operator); void *InsertPos = nullptr; DependentTemplateName *QTN = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); - + if (QTN) return TemplateName(QTN); - + NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); if (CanonNNS == NNS) { QTN = new (*this, alignof(DependentTemplateName)) @@ -7570,12 +7601,12 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, assert(!CheckQTN && "Dependent template name canonicalization broken"); (void)CheckQTN; } - + DependentTemplateNames.InsertNode(QTN, InsertPos); return TemplateName(QTN); } -TemplateName +TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, TemplateName replacement) const { llvm::FoldingSetNodeID ID; @@ -7584,7 +7615,7 @@ ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, void *insertPos = nullptr; SubstTemplateTemplateParmStorage *subst = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); - + if (!subst) { subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); SubstTemplateTemplateParms.InsertNode(subst, insertPos); @@ -7593,7 +7624,7 @@ ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, return TemplateName(subst); } -TemplateName +TemplateName ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, const TemplateArgument &ArgPack) const { auto &Self = const_cast<ASTContext &>(*this); @@ -7603,9 +7634,9 @@ ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, void *InsertPos = nullptr; SubstTemplateTemplateParmPackStorage *Subst = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); - + if (!Subst) { - Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, + Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, ArgPack.pack_size(), ArgPack.pack_begin()); SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); @@ -7725,12 +7756,12 @@ ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and /// Class<pr1, ...>. -bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, +bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, QualType rhs) { const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>(); const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); - + for (auto *lhsProto : lhsQID->quals()) { bool match = false; for (auto *rhsProto : rhsOPT->quals()) { @@ -7835,7 +7866,7 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, if (!match) return false; } - + // Static class's protocols, or its super class or category protocols // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { @@ -7897,12 +7928,12 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, QualType(RHSOPT,0), false)); } - + if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), QualType(RHSOPT,0))); } - + // If we have 2 user-defined types, fall into that path. if (LHS->getInterface() && RHS->getInterface()) { return finish(canAssignObjCInterfaces(LHS, RHS)); @@ -7912,7 +7943,7 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, } /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written -/// for providing type-safety for objective-c pointers used to pass/return +/// for providing type-safety for objective-c pointers used to pass/return /// arguments in block literals. When passed as arguments, passing 'A*' where /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is /// not OK. For the return type, the opposite is not OK. @@ -7941,17 +7972,17 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer( if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) return true; - + if (LHSOPT->isObjCBuiltinType()) { return finish(RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType()); } - + if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), QualType(RHSOPT,0), false)); - + const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); if (LHS && RHS) { // We have 2 user-defined types. @@ -7979,13 +8010,13 @@ static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, /// the given common base. /// It is used to build composite qualifier list of the composite type of /// the conditional expression involving two objective-c pointer objects. -static +static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { - + const ObjCObjectType* LHS = LHSOPT->getObjectType(); const ObjCObjectType* RHS = RHSOPT->getObjectType(); assert(LHS->getInterface() && "LHS must have an interface base"); @@ -8254,7 +8285,7 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, // If there is no protocols associated with RHS, it is not a match. if (SuperClassInheritedProtocols.empty()) return false; - + for (const auto *LHSProto : LHS->quals()) { bool SuperImplementsProtocol = false; for (auto *SuperClassProto : SuperClassInheritedProtocols) @@ -8367,7 +8398,7 @@ QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); } -QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, +QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, bool OfBlockPointer, bool Unqualified) { const auto *lbase = lhs->getAs<FunctionType>(); @@ -8392,7 +8423,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, Unqualified); if (retType.isNull()) return {}; - + if (Unqualified) retType = retType.getUnqualifiedType(); @@ -8402,7 +8433,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, LRetType = LRetType.getUnqualifiedType(); RRetType = RRetType.getUnqualifiedType(); } - + if (getCanonicalType(retType) != LRetType) allLTypes = false; if (getCanonicalType(retType) != RRetType) @@ -8491,7 +8522,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, if (getCanonicalType(paramType) != getCanonicalType(rParamType)) allRTypes = false; } - + if (allLTypes) return lhs; if (allRTypes) return rhs; @@ -8566,7 +8597,7 @@ static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, return {}; } -QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, +QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType) { // C++ [expr]: If an expression initially has the type "reference to T", the @@ -8581,7 +8612,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHS = LHS.getUnqualifiedType(); RHS = RHS.getUnqualifiedType(); } - + QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS); @@ -8663,7 +8694,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, if (RHS->isObjCIdType() && LHS->isBlockPointerType()) return RHS; } - + return {}; } @@ -8700,7 +8731,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHSPointee = LHSPointee.getUnqualifiedType(); RHSPointee = RHSPointee.getUnqualifiedType(); } - QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, + QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, Unqualified); if (ResultType.isNull()) return {}; @@ -8752,7 +8783,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHSValue = LHSValue.getUnqualifiedType(); RHSValue = RHSValue.getUnqualifiedType(); } - QualType ResultType = mergeTypes(LHSValue, RHSValue, false, + QualType ResultType = mergeTypes(LHSValue, RHSValue, false, Unqualified); if (ResultType.isNull()) return {}; @@ -8775,7 +8806,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHSElem = LHSElem.getUnqualifiedType(); RHSElem = RHSElem.getUnqualifiedType(); } - + QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); if (ResultType.isNull()) return {}; @@ -8958,7 +8989,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); QualType NewReturnType = cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); - QualType ResReturnType = + QualType ResReturnType = mergeObjCGCQualifiers(NewReturnType, OldReturnType); if (ResReturnType.isNull()) return {}; @@ -8976,7 +9007,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { } return {}; } - + // If the qualifiers are different, the types can still be merged. Qualifiers LQuals = LHSCan.getLocalQualifiers(); Qualifiers RQuals = RHSCan.getLocalQualifiers(); @@ -8985,7 +9016,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || LQuals.getAddressSpace() != RQuals.getAddressSpace()) return {}; - + // Exactly one GC qualifier difference is allowed: __strong is // okay if the other type has no GC qualifier but is an Objective // C object pointer (i.e. implicitly strong by default). We fix @@ -8994,17 +9025,17 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); - + if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) return {}; - + if (GC_L == Qualifiers::Strong) return LHS; if (GC_R == Qualifiers::Strong) return RHS; return {}; } - + if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); @@ -9033,7 +9064,7 @@ unsigned ASTContext::getIntWidth(QualType T) const { QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && "Unexpected type"); - + // Turn <4 x signed int> -> <4 x unsigned int> if (const auto *VTy = T->getAs<VectorType>()) return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), @@ -9042,7 +9073,7 @@ QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { // For enums, we return the unsigned version of the base type. if (const auto *ETy = T->getAs<EnumType>()) T = ETy->getDecl()->getIntegerType(); - + const auto *BTy = T->getAs<BuiltinType>(); assert(BTy && "Unexpected signed integer or fixed point type"); switch (BTy->getKind()) { @@ -9114,7 +9145,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, int HowLong = 0; bool Signed = false, Unsigned = false; RequiresICE = false; - + // Read the prefixed modifiers first. bool Done = false; #ifndef NDEBUG @@ -9278,10 +9309,10 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, assert(End != Str && "Missing vector size"); Str = End; - QualType ElementType = DecodeTypeFromStr(Str, Context, Error, + QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require vector ICE"); - + // TODO: No way to make AltiVec vectors in builtins yet. Type = Context.getVectorType(ElementType, NumElements, VectorType::GenericVector); @@ -9289,16 +9320,16 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, } case 'E': { char *End; - + unsigned NumElements = strtoul(Str, &End, 10); assert(End != Str && "Missing vector size"); - + Str = End; - + QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); Type = Context.getExtVectorType(ElementType, NumElements); - break; + break; } case 'X': { QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, @@ -9306,7 +9337,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, assert(!RequiresICE && "Can't require complex ICE"); Type = Context.getComplexType(ElementType); break; - } + } case 'Y': Type = Context.getPointerDiffType(); break; @@ -9376,9 +9407,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, break; } } - + assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && - "Integer constant 'I' type must be an integer"); + "Integer constant 'I' type must be an integer"); return Type; } @@ -9397,9 +9428,9 @@ QualType ASTContext::GetBuiltinType(unsigned Id, RequiresICE, true); if (Error != GE_None) return {}; - + assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); - + while (TypeStr[0] && TypeStr[0] != '.') { QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); if (Error != GE_None) @@ -9409,7 +9440,7 @@ QualType ASTContext::GetBuiltinType(unsigned Id, // caller cares, fill in the bitmask we return. if (RequiresICE && IntegerConstantArgs) *IntegerConstantArgs |= 1 << ArgTypes.size(); - + // Do array -> pointer decay. The builtin should use the decayed type. if (Ty->isArrayType()) Ty = getArrayDecayedType(Ty); @@ -9504,21 +9535,6 @@ static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, return GVA_DiscardableODR; } -static bool isDeclareTargetToDeclaration(const Decl *VD) { - for (const Decl *D : VD->redecls()) { - if (!D->hasAttrs()) - continue; - if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>()) - return Attr->getMapType() == OMPDeclareTargetDeclAttr::MT_To; - } - if (const auto *V = dyn_cast<VarDecl>(VD)) { - if (const VarDecl *TD = V->getTemplateInstantiationPattern()) - return isDeclareTargetToDeclaration(TD); - } - - return false; -} - static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L) { // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx @@ -9535,12 +9551,6 @@ static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, // visible externally so they can be launched from host. if (L == GVA_DiscardableODR || L == GVA_Internal) return GVA_StrongODR; - } else if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice && - isDeclareTargetToDeclaration(D)) { - // Static variables must be visible externally so they can be mapped from - // host. - if (L == GVA_Internal) - return GVA_StrongODR; } return L; } @@ -10006,7 +10016,7 @@ void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { ParameterIndexTable::const_iterator I = ParamIndices.find(D); - assert(I != ParamIndices.end() && + assert(I != ParamIndices.end() && "ParmIndices lacks entry set by ParmVarDecl"); return I->second; } @@ -10240,10 +10250,10 @@ ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, return false; if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) return false; - + if (MethodDecl->param_size() != MethodImpl->param_size()) return false; - + for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), EF = MethodDecl->param_end(); diff --git a/lib/AST/ASTDiagnostic.cpp b/lib/AST/ASTDiagnostic.cpp index c4c0f6e5ebe37..50d2d2999e519 100644 --- a/lib/AST/ASTDiagnostic.cpp +++ b/lib/AST/ASTDiagnostic.cpp @@ -200,7 +200,7 @@ break; \ return QC.apply(Context, QT); } -/// Convert the given type to a string suitable for printing as part of +/// Convert the given type to a string suitable for printing as part of /// a diagnostic. /// /// There are four main criteria when determining whether we should have an @@ -254,7 +254,7 @@ ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty, // and the desugared comparison string. std::string CompareCanS = CompareCanTy.getAsString(Context.getPrintingPolicy()); - + if (CompareCanS == CanS) continue; // No new info from canonical type @@ -327,11 +327,11 @@ void clang::FormatASTNodeDiagnosticArgument( void *Cookie, ArrayRef<intptr_t> QualTypeVals) { ASTContext &Context = *static_cast<ASTContext*>(Cookie); - + size_t OldEnd = Output.size(); llvm::raw_svector_ostream OS(Output); bool NeedQuotes = true; - + switch (Kind) { default: llvm_unreachable("unknown ArgumentKind"); case DiagnosticsEngine::ak_qualtype_pair: { @@ -365,7 +365,7 @@ void clang::FormatASTNodeDiagnosticArgument( case DiagnosticsEngine::ak_qualtype: { assert(Modifier.empty() && Argument.empty() && "Invalid modifier for QualType argument"); - + QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals); NeedQuotes = false; @@ -2040,7 +2040,7 @@ public: /// is successful. static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType, QualType ToType, bool PrintTree, - bool PrintFromType, bool ElideType, + bool PrintFromType, bool ElideType, bool ShowColors, raw_ostream &OS) { if (PrintTree) PrintFromType = true; diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index f46ae58d192d4..8a653ecebae3f 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -1966,7 +1966,7 @@ void ASTDumper::dumpStmt(const Stmt *S) { } void ASTDumper::VisitStmt(const Stmt *Node) { - { + { ColorScope Color(*this, StmtColor); OS << Node->getStmtClassName(); } diff --git a/lib/AST/ASTImporter.cpp b/lib/AST/ASTImporter.cpp index 6668067233e44..b360b39106364 100644 --- a/lib/AST/ASTImporter.cpp +++ b/lib/AST/ASTImporter.cpp @@ -221,8 +221,8 @@ namespace clang { QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); // Importing declarations - bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, - DeclContext *&LexicalDC, DeclarationName &Name, + bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, + DeclContext *&LexicalDC, DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); void ImportDeclarationNameLoc(const DeclarationNameInfo &From, @@ -237,9 +237,9 @@ namespace clang { Designator ImportDesignator(const Designator &D); Optional<LambdaCapture> ImportLambdaCapture(const LambdaCapture &From); - + /// What we should import from the definition. - enum ImportDefinitionKind { + enum ImportDefinitionKind { /// Import the default subset of the definition, which might be /// nothing (if minimal import is set) or might be everything (if minimal /// import is not set). @@ -258,7 +258,7 @@ namespace clang { (IDK == IDK_Default && !Importer.isMinimalImport()); } - bool ImportDefinition(RecordDecl *From, RecordDecl *To, + bool ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind = IDK_Default); bool ImportDefinition(VarDecl *From, VarDecl *To, ImportDefinitionKind Kind = IDK_Default); @@ -600,21 +600,21 @@ QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { // context supports ObjC. case BuiltinType::Char_U: - // The context we're importing from has an unsigned 'char'. If we're - // importing into a context with a signed 'char', translate to + // The context we're importing from has an unsigned 'char'. If we're + // importing into a context with a signed 'char', translate to // 'unsigned char' instead. if (Importer.getToContext().getLangOpts().CharIsSigned) return Importer.getToContext().UnsignedCharTy; - + return Importer.getToContext().CharTy; case BuiltinType::Char_S: - // The context we're importing from has an unsigned 'char'. If we're - // importing into a context with a signed 'char', translate to + // The context we're importing from has an unsigned 'char'. If we're + // importing into a context with a signed 'char', translate to // 'unsigned char' instead. if (!Importer.getToContext().getLangOpts().CharIsSigned) return Importer.getToContext().SignedCharTy; - + return Importer.getToContext().CharTy; case BuiltinType::WChar_S: @@ -639,7 +639,7 @@ QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - + return Importer.getToContext().getComplexType(ToElementType); } @@ -647,7 +647,7 @@ QualType ASTNodeImporter::VisitPointerType(const PointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return {}; - + return Importer.getToContext().getPointerType(ToPointeeType); } @@ -656,7 +656,7 @@ QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return {}; - + return Importer.getToContext().getBlockPointerType(ToPointeeType); } @@ -666,7 +666,7 @@ ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten()); if (ToPointeeType.isNull()) return {}; - + return Importer.getToContext().getLValueReferenceType(ToPointeeType); } @@ -676,8 +676,8 @@ ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten()); if (ToPointeeType.isNull()) return {}; - - return Importer.getToContext().getRValueReferenceType(ToPointeeType); + + return Importer.getToContext().getRValueReferenceType(ToPointeeType); } QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { @@ -685,9 +685,9 @@ QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return {}; - + QualType ClassType = Importer.Import(QualType(T->getClass(), 0)); - return Importer.getToContext().getMemberPointerType(ToPointeeType, + return Importer.getToContext().getMemberPointerType(ToPointeeType, ClassType.getTypePtr()); } @@ -695,8 +695,8 @@ QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getConstantArrayType(ToElementType, + + return Importer.getToContext().getConstantArrayType(ToElementType, T->getSize(), T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); @@ -707,8 +707,8 @@ ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getIncompleteArrayType(ToElementType, + + return Importer.getToContext().getIncompleteArrayType(ToElementType, T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); } @@ -721,7 +721,7 @@ QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { Expr *Size = Importer.Import(T->getSizeExpr()); if (!Size) return {}; - + SourceRange Brackets = Importer.Import(T->getBracketsRange()); return Importer.getToContext().getVariableArrayType(ToElementType, Size, T->getSizeModifier(), @@ -751,8 +751,8 @@ QualType ASTNodeImporter::VisitVectorType(const VectorType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getVectorType(ToElementType, + + return Importer.getToContext().getVectorType(ToElementType, T->getNumElements(), T->getVectorKind()); } @@ -761,14 +761,14 @@ QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getExtVectorType(ToElementType, + + return Importer.getToContext().getExtVectorType(ToElementType, T->getNumElements()); } QualType ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { - // FIXME: What happens if we're importing a function without a prototype + // FIXME: What happens if we're importing a function without a prototype // into C++? Should we make it variadic? QualType ToResultType = Importer.Import(T->getReturnType()); if (ToResultType.isNull()) @@ -782,7 +782,7 @@ QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { QualType ToResultType = Importer.Import(T->getReturnType()); if (ToResultType.isNull()) return {}; - + // Import argument types SmallVector<QualType, 4> ArgTypes; for (const auto &A : T->param_types()) { @@ -791,7 +791,7 @@ QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { return {}; ArgTypes.push_back(ArgType); } - + // Import exception types SmallVector<QualType, 4> ExceptionTypes; for (const auto &E : T->exceptions()) { @@ -841,7 +841,7 @@ QualType ASTNodeImporter::VisitParenType(const ParenType *T) { QualType ToInnerType = Importer.Import(T->getInnerType()); if (ToInnerType.isNull()) return {}; - + return Importer.getToContext().getParenType(ToInnerType); } @@ -850,7 +850,7 @@ QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl())); if (!ToDecl) return {}; - + return Importer.getToContext().getTypeDeclType(ToDecl); } @@ -858,7 +858,7 @@ QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { Expr *ToExpr = Importer.Import(T->getUnderlyingExpr()); if (!ToExpr) return {}; - + return Importer.getToContext().getTypeOfExprType(ToExpr); } @@ -866,7 +866,7 @@ QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType()); if (ToUnderlyingType.isNull()) return {}; - + return Importer.getToContext().getTypeOfType(ToUnderlyingType); } @@ -875,7 +875,7 @@ QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { Expr *ToExpr = Importer.Import(T->getUnderlyingExpr()); if (!ToExpr) return {}; - + QualType UnderlyingType = Importer.Import(T->getUnderlyingType()); if (UnderlyingType.isNull()) return {}; @@ -903,7 +903,7 @@ QualType ASTNodeImporter::VisitAutoType(const AutoType *T) { if (ToDeduced.isNull()) return {}; } - + return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(), /*IsDependent*/false); } @@ -1000,20 +1000,20 @@ QualType ASTNodeImporter::VisitTemplateSpecializationType( TemplateName ToTemplate = Importer.Import(T->getTemplateName()); if (ToTemplate.isNull()) return {}; - + SmallVector<TemplateArgument, 2> ToTemplateArgs; if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs)) return {}; - + QualType ToCanonType; if (!QualType(T, 0).isCanonical()) { - QualType FromCanonType + QualType FromCanonType = Importer.getFromContext().getCanonicalType(QualType(T, 0)); ToCanonType =Importer.Import(FromCanonType); if (ToCanonType.isNull()) return {}; } - return Importer.getToContext().getTemplateSpecializationType(ToTemplate, + return Importer.getToContext().getTemplateSpecializationType(ToTemplate, ToTemplateArgs, ToCanonType); } @@ -1136,9 +1136,9 @@ ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { //---------------------------------------------------------------------------- // Import Declarations //---------------------------------------------------------------------------- -bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, - DeclContext *&LexicalDC, - DeclarationName &Name, +bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, + DeclContext *&LexicalDC, + DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. @@ -1163,19 +1163,19 @@ bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, DC = Importer.ImportContext(OrigDC); if (!DC) return true; - + LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return true; } - + // Import the name of this declaration. Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return true; - + // Import the location of this declaration. Loc = Importer.Import(D->getLocation()); ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); @@ -1185,13 +1185,13 @@ bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { if (!FromD) return; - + if (!ToD) { ToD = Importer.Import(FromD); if (!ToD) return; } - + if (auto *FromRecord = dyn_cast<RecordDecl>(FromD)) { if (auto *ToRecord = cast_or_null<RecordDecl>(ToD)) { if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) { @@ -1246,12 +1246,12 @@ ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From, llvm_unreachable("Unknown name kind."); } -void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { +void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { if (Importer.isMinimalImport() && !ForceImport) { Importer.ImportContext(FromDC); return; } - + for (auto *From : FromDC->decls()) Importer.Import(From); } @@ -1260,7 +1260,7 @@ void ASTNodeImporter::ImportImplicitMethods( const CXXRecordDecl *From, CXXRecordDecl *To) { assert(From->isCompleteDefinition() && To->getDefinition() == To && "Import implicit methods to or from non-definition"); - + for (CXXMethodDecl *FromM : From->methods()) if (FromM->isImplicit()) Importer.Import(FromM); @@ -1277,19 +1277,19 @@ static void setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, } } -bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, +bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) ImportDeclContext(From, /*ForceImport=*/true); - + return false; } - + To->startDefinition(); setTypedefNameForAnonDecl(From, To, Importer); - + // Add base classes. if (auto *ToCXX = dyn_cast<CXXRecordDecl>(To)) { auto *FromCXX = cast<CXXRecordDecl>(From); @@ -1374,9 +1374,9 @@ bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, // Ensure that we have a definition for the base. ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()); - + Bases.push_back( - new (Importer.getToContext()) + new (Importer.getToContext()) CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()), Base1.isVirtual(), Base1.isBaseOfClass(), @@ -1387,10 +1387,10 @@ bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, if (!Bases.empty()) ToCXX->setBases(Bases.data(), Bases.size()); } - + if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From, /*ForceImport=*/true); - + To->completeDefinition(); return false; } @@ -1410,14 +1410,14 @@ bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To, return false; } -bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, +bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) ImportDeclContext(From, /*ForceImport=*/true); return false; } - + To->startDefinition(); setTypedefNameForAnonDecl(From, To, Importer); @@ -1425,14 +1425,14 @@ bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From)); if (T.isNull()) return true; - + QualType ToPromotionType = Importer.Import(From->getPromotionType()); if (ToPromotionType.isNull()) return true; if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From, /*ForceImport=*/true); - + // FIXME: we might need to merge the number of positive or negative bits // if the enumerator lists don't match. To->completeDefinition(T, ToPromotionType, @@ -1446,7 +1446,7 @@ TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList( SmallVector<NamedDecl *, 4> ToParams(Params->size()); if (ImportContainerChecked(*Params, ToParams)) return nullptr; - + Expr *ToRequiresClause; if (Expr *const R = Params->getRequiresClause()) { ToRequiresClause = Importer.Import(R); @@ -1464,19 +1464,19 @@ TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList( ToRequiresClause); } -TemplateArgument +TemplateArgument ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { switch (From.getKind()) { case TemplateArgument::Null: return TemplateArgument(); - + case TemplateArgument::Type: { QualType ToType = Importer.Import(From.getAsType()); if (ToType.isNull()) return {}; return TemplateArgument(ToType); } - + case TemplateArgument::Integral: { QualType ToType = Importer.Import(From.getIntegralType()); if (ToType.isNull()) @@ -1503,16 +1503,16 @@ ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { TemplateName ToTemplate = Importer.Import(From.getAsTemplate()); if (ToTemplate.isNull()) return {}; - + return TemplateArgument(ToTemplate); } case TemplateArgument::TemplateExpansion: { - TemplateName ToTemplate + TemplateName ToTemplate = Importer.Import(From.getAsTemplateOrTemplatePattern()); if (ToTemplate.isNull()) return {}; - + return TemplateArgument(ToTemplate, From.getNumTemplateExpansions()); } @@ -1520,7 +1520,7 @@ ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { if (Expr *ToExpr = Importer.Import(From.getAsExpr())) return TemplateArgument(ToExpr); return TemplateArgument(); - + case TemplateArgument::Pack: { SmallVector<TemplateArgument, 2> ToPack; ToPack.reserve(From.pack_size()); @@ -1531,7 +1531,7 @@ ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { llvm::makeArrayRef(ToPack).copy(Importer.getToContext())); } } - + llvm_unreachable("Invalid template argument kind"); } @@ -1566,10 +1566,10 @@ bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs, TemplateArgument To = ImportTemplateArgument(FromArgs[I]); if (To.isNull() && !FromArgs[I].isNull()) return true; - + ToArgs.push_back(To); } - + return false; } @@ -1714,11 +1714,11 @@ Decl *ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { } Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { - TranslationUnitDecl *ToD = + TranslationUnitDecl *ToD = Importer.getToContext().getTranslationUnitDecl(); - + Importer.MapImported(D, ToD); - + return ToD; } @@ -1801,23 +1801,23 @@ Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace)) continue; - + if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) { MergeWithNamespace = FoundNS; ConflictingDecls.clear(); break; } - + ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); } } - + // Create the "to" namespace, if needed. NamespaceDecl *ToNamespace = MergeWithNamespace; if (!ToNamespace) { @@ -1828,7 +1828,7 @@ Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { return ToNamespace; ToNamespace->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToNamespace); - + // If this is an anonymous namespace, register it as the anonymous // namespace within its context. if (!Name) { @@ -1839,9 +1839,9 @@ Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { } } Importer.MapImported(D, ToNamespace); - + ImportDeclContext(D); - + return ToNamespace; } @@ -1918,7 +1918,7 @@ Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; @@ -2076,7 +2076,7 @@ Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { IDNS = Decl::IDNS_Ordinary; } else if (Importer.getToContext().getLangOpts().CPlusPlus) IDNS |= Decl::IDNS_Ordinary; - + // We may already have an enum of the same name; try to find and match it. if (!DC->isFunctionOrMethod() && SearchName) { SmallVector<NamedDecl *, 4> ConflictingDecls; @@ -2085,24 +2085,24 @@ Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(IDNS)) continue; - + Decl *Found = FoundDecl; if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) Found = Tag->getDecl(); } - + if (auto *FoundEnum = dyn_cast<EnumDecl>(Found)) { if (IsStructuralMatch(D, FoundEnum)) return Importer.MapImported(D, FoundEnum); } - + ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); } } @@ -2126,7 +2126,7 @@ Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { if (ToIntegerType.isNull()) return nullptr; D2->setIntegerType(ToIntegerType); - + // Import the definition if (D->isCompleteDefinition() && ImportDefinition(D, D2)) return nullptr; @@ -2189,7 +2189,7 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(IDNS)) continue; - + Decl *Found = FoundDecl; if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) @@ -2237,38 +2237,38 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { } else if (!D->isCompleteDefinition()) { // We have a forward declaration of this type, so adopt that forward // declaration rather than building a new one. - + // If one or both can be completed from external storage then try one // last time to complete and compare them before doing this. - + if (FoundRecord->hasExternalLexicalStorage() && !FoundRecord->isCompleteDefinition()) FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord); if (D->hasExternalLexicalStorage()) D->getASTContext().getExternalSource()->CompleteType(D); - + if (FoundRecord->isCompleteDefinition() && D->isCompleteDefinition() && !IsStructuralMatch(D, FoundRecord)) continue; - + AdoptDecl = FoundRecord; continue; } else if (!SearchName) { continue; } } - + ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty() && SearchName) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); } } - + // Create the record declaration. RecordDecl *D2 = AdoptDecl; SourceLocation StartLoc = Importer.Import(D->getLocStart()); @@ -2392,7 +2392,7 @@ Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { if (T.isNull()) return nullptr; - // Determine whether there are any other declarations with the same name and + // Determine whether there are any other declarations with the same name and // in the same context. if (!LexicalDC->isFunctionOrMethod()) { SmallVector<NamedDecl *, 4> ConflictingDecls; @@ -2410,16 +2410,16 @@ Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; } } - + Expr *Init = Importer.Import(D->getInitExpr()); if (D->getInitExpr() && !Init) return nullptr; @@ -2608,7 +2608,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { // Complain about inconsistent function types. Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent) << Name << D->getType() << FoundFunction->getType(); - Importer.ToDiag(FoundFunction->getLocation(), + Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) << FoundFunction->getType(); } @@ -2619,11 +2619,11 @@ Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; - } + } } DeclarationNameInfo NameInfo(Name, Loc); @@ -2663,7 +2663,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { Parameters.push_back(ToP); } - + TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); if (D->getTypeSourceInfo() && !TInfo) return nullptr; @@ -2851,7 +2851,7 @@ Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { if (ToD) return ToD; - // Determine whether we've already imported this field. + // Determine whether we've already imported this field. SmallVector<NamedDecl *, 2> FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (auto *FoundDecl : FoundDecls) { @@ -2916,7 +2916,7 @@ Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { if (ToD) return ToD; - // Determine whether we've already imported this field. + // Determine whether we've already imported this field. SmallVector<NamedDecl *, 2> FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { @@ -3153,7 +3153,7 @@ Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { << FoundVar->getType(); } } - + ConflictingDecls.push_back(FoundDecl); } @@ -3165,7 +3165,7 @@ Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { if (VarDecl *DDef = D->getDefinition()) { if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) { - Importer.ToDiag(ExistingDef->getLocation(), + Importer.ToDiag(ExistingDef->getLocation(), diag::err_odr_variable_multiple_def) << Name; Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here); @@ -3179,19 +3179,19 @@ Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { } } } - + return MergeWithVar; } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; } } - + // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) @@ -3228,7 +3228,7 @@ Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { // Parameters are created in the translation unit's context, then moved // into the function declaration's context afterward. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); - + // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) @@ -3236,7 +3236,7 @@ Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); - + // Import the parameter's type. QualType T = Importer.Import(D->getType()); if (T.isNull()) @@ -3255,7 +3255,7 @@ Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { // Parameters are created in the translation unit's context, then moved // into the function declaration's context afterward. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); - + // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) @@ -3263,7 +3263,7 @@ Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); - + // Import the parameter's type. QualType T = Importer.Import(D->getType()); if (T.isNull()) @@ -3334,7 +3334,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent) << D->isInstanceMethod() << Name << D->getReturnType() << FoundMethod->getReturnType(); - Importer.ToDiag(FoundMethod->getLocation(), + Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return nullptr; @@ -3345,7 +3345,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent) << D->isInstanceMethod() << Name << D->param_size() << FoundMethod->param_size(); - Importer.ToDiag(FoundMethod->getLocation(), + Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return nullptr; @@ -3372,7 +3372,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { if (D->isVariadic() != FoundMethod->isVariadic()) { Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent) << D->isInstanceMethod() << Name; - Importer.ToDiag(FoundMethod->getLocation(), + Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return nullptr; @@ -3411,7 +3411,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { ToParams.push_back(ToP); } - + // Set the parameters. for (auto *ToParam : ToParams) { ToParam->setOwningFunction(ToMethod); @@ -3494,7 +3494,7 @@ Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { // loops when bringing in their DeclContext. ToCategory->setTypeParamList(ImportObjCTypeParamList( D->getTypeParamList())); - + // Import protocols SmallVector<ObjCProtocolDecl *, 4> Protocols; SmallVector<SourceLocation, 4> ProtocolLocs; @@ -3511,17 +3511,17 @@ Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } - + // FIXME: If we're merging, make sure that the protocol list is the same. ToCategory->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); } else { Importer.MapImported(D, ToCategory); } - + // Import all of the members of this category. ImportDeclContext(D); - + // If we have an implementation, import it as well. if (D->getImplementation()) { auto *Impl = @@ -3532,11 +3532,11 @@ Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { ToCategory->setImplementation(Impl); } - + return ToCategory; } -bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, +bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition()) { @@ -3547,11 +3547,11 @@ bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, // Start the protocol definition To->startDefinition(); - + // Import protocols SmallVector<ObjCProtocolDecl *, 4> Protocols; SmallVector<SourceLocation, 4> ProtocolLocs; - ObjCProtocolDecl::protocol_loc_iterator + ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), FromProtoEnd = From->protocol_end(); @@ -3563,7 +3563,7 @@ bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } - + // FIXME: If we're merging, make sure that the protocol list is the same. To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); @@ -3576,7 +3576,7 @@ bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, } Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { - // If this protocol has a definition in the translation unit we're coming + // If this protocol has a definition in the translation unit we're coming // from, but this particular declaration is not that definition, import the // definition and map to that. ObjCProtocolDecl *Definition = D->getDefinition(); @@ -3604,11 +3604,11 @@ Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) continue; - + if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl))) break; } - + ObjCProtocolDecl *ToProto = MergeWithProtocol; if (!ToProto) { if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC, @@ -3831,7 +3831,7 @@ Decl *ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( return ToUsing; } -bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, +bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition()) { @@ -3842,36 +3842,36 @@ bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, if (!FromSuper) return true; } - - ObjCInterfaceDecl *ToSuper = To->getSuperClass(); + + ObjCInterfaceDecl *ToSuper = To->getSuperClass(); if ((bool)FromSuper != (bool)ToSuper || (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { - Importer.ToDiag(To->getLocation(), + Importer.ToDiag(To->getLocation(), diag::err_odr_objc_superclass_inconsistent) << To->getDeclName(); if (ToSuper) Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) << To->getSuperClass()->getDeclName(); else - Importer.ToDiag(To->getLocation(), + Importer.ToDiag(To->getLocation(), diag::note_odr_objc_missing_superclass); if (From->getSuperClass()) - Importer.FromDiag(From->getSuperClassLoc(), + Importer.FromDiag(From->getSuperClassLoc(), diag::note_odr_objc_superclass) << From->getSuperClass()->getDeclName(); else - Importer.FromDiag(From->getLocation(), - diag::note_odr_objc_missing_superclass); + Importer.FromDiag(From->getLocation(), + diag::note_odr_objc_missing_superclass); } - + if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From); return false; } - + // Start the definition. To->startDefinition(); - + // If this class has a superclass, import it. if (From->getSuperClass()) { TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo()); @@ -3880,13 +3880,13 @@ bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, To->setSuperClass(SuperTInfo); } - + // Import protocols SmallVector<ObjCProtocolDecl *, 4> Protocols; SmallVector<SourceLocation, 4> ProtocolLocs; - ObjCInterfaceDecl::protocol_loc_iterator + ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); - + for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), FromProtoEnd = From->protocol_end(); FromProto != FromProtoEnd; @@ -3897,23 +3897,23 @@ bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } - + // FIXME: If we're merging, make sure that the protocol list is the same. To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); - + // Import categories. When the categories themselves are imported, they'll // hook themselves into this interface. for (auto *Cat : From->known_categories()) Importer.Import(Cat); - + // If we have an @implementation, import it as well. if (From->getImplementation()) { auto *Impl = cast_or_null<ObjCImplementationDecl>( Importer.Import(From->getImplementation())); if (!Impl) return true; - + To->setImplementation(Impl); } @@ -3975,11 +3975,11 @@ Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) continue; - + if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl))) break; } - + // Create an interface declaration, if one does not already exist. ObjCInterfaceDecl *ToIface = MergeWithIface; if (!ToIface) { @@ -3997,7 +3997,7 @@ Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { // loops when bringing in their DeclContext. ToIface->setTypeParamList(ImportObjCTypeParamList( D->getTypeParamListAsWritten())); - + if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface)) return nullptr; @@ -4032,11 +4032,11 @@ Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { ToImpl->setLexicalDeclContext(LexicalDC); } - + LexicalDC->addDeclInternal(ToImpl); Category->setImplementation(ToImpl); } - + Importer.MapImported(D, ToImpl); ImportDeclContext(D); return ToImpl; @@ -4113,7 +4113,7 @@ Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { return nullptr; } } - + // Import all of the members of this @implementation. ImportDeclContext(D); @@ -4235,10 +4235,10 @@ Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { // Check that we have the same kind of property implementation (@synthesize // vs. @dynamic). if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { - Importer.ToDiag(ToImpl->getLocation(), + Importer.ToDiag(ToImpl->getLocation(), diag::err_odr_objc_property_impl_kind_inconsistent) - << Property->getDeclName() - << (ToImpl->getPropertyImplementation() + << Property->getDeclName() + << (ToImpl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); Importer.FromDiag(D->getLocation(), diag::note_odr_objc_property_impl_kind) @@ -4246,25 +4246,25 @@ Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); return nullptr; } - - // For @synthesize, check that we have the same + + // For @synthesize, check that we have the same if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && Ivar != ToImpl->getPropertyIvarDecl()) { - Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), + Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), diag::err_odr_objc_synthesize_ivar_inconsistent) << Property->getDeclName() << ToImpl->getPropertyIvarDecl()->getDeclName() << Ivar->getDeclName(); - Importer.FromDiag(D->getPropertyIvarDeclLoc(), + Importer.FromDiag(D->getPropertyIvarDeclLoc(), diag::note_odr_objc_synthesize_ivar_here) << D->getPropertyIvarDecl()->getDeclName(); return nullptr; } - + // Merge the existing implementation with the new implementation. Importer.MapImported(D, ToImpl); } - + return ToImpl; } @@ -4272,7 +4272,7 @@ Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { // For template arguments, we adopt the translation unit as our declaration // context. This context will be fixed when the actual template declaration // is created. - + // FIXME: Import default argument. TemplateTypeParmDecl *ToD = nullptr; (void)GetImportedOrCreateDecl( @@ -4444,16 +4444,16 @@ Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { return D2; ToTemplated->setDescribedClassTemplate(D2); - + D2->setAccess(D->getAccess()); D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); - + if (FromTemplated->isCompleteDefinition() && !ToTemplated->isCompleteDefinition()) { // FIXME: Import definition! } - + return D2; } @@ -4488,14 +4488,14 @@ Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( if (!LexicalDC) return nullptr; } - + // Import the location of this declaration. SourceLocation StartLoc = Importer.Import(D->getLocStart()); SourceLocation IdLoc = Importer.Import(D->getLocation()); // Import template arguments. SmallVector<TemplateArgument, 2> TemplateArgs; - if (ImportTemplateArguments(D->getTemplateArgs().data(), + if (ImportTemplateArguments(D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) return nullptr; @@ -4507,9 +4507,9 @@ Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( if (D2) { // We already have a class template specialization with these template // arguments. - + // FIXME: Check for specialization vs. instantiation errors. - + if (RecordDecl *FoundDef = D2->getDefinition()) { if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) { // The record types structurally match, or the "from" translation @@ -4557,7 +4557,7 @@ Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( // Add this specialization to the class template. ClassTemplate->AddSpecialization(D2, InsertPos); - + // Import the qualifier, if any. D2->setQualifierInfo(Importer.Import(D->getQualifierLoc())); @@ -5484,7 +5484,7 @@ Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { if (!FoundD) return nullptr; } - + QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; @@ -5497,7 +5497,7 @@ Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { ResInfo = &ToTAInfo; } - DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), + DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), ToD, @@ -5583,7 +5583,7 @@ Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { if (T.isNull()) return nullptr; - return IntegerLiteral::Create(Importer.getToContext(), + return IntegerLiteral::Create(Importer.getToContext(), E->getValue(), T, Importer.Import(E->getLocation())); } @@ -5674,7 +5674,7 @@ Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) { if (!SubExpr) return nullptr; - return new (Importer.getToContext()) + return new (Importer.getToContext()) ParenExpr(Importer.Import(E->getLParen()), Importer.Import(E->getRParen()), SubExpr); @@ -5721,7 +5721,7 @@ Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { Expr * ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { QualType ResultType = Importer.Import(E->getType()); - + if (E->isArgumentType()) { TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo()); if (!TInfo) @@ -5732,7 +5732,7 @@ ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { Importer.Import(E->getOperatorLoc()), Importer.Import(E->getRParenLoc())); } - + Expr *SubExpr = Importer.Import(E->getArgumentExpr()); if (!SubExpr) return nullptr; @@ -5904,7 +5904,7 @@ Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { if (!RHS) return nullptr; - return new (Importer.getToContext()) + return new (Importer.getToContext()) CompoundAssignOperator(LHS, RHS, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(), @@ -6354,11 +6354,11 @@ Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; - + Expr *ToFn = Importer.Import(E->getCallee()); if (!ToFn) return nullptr; - + SmallVector<Expr *, 4> ToArgs(E->getNumArgs()); if (ImportContainerChecked(E->arguments(), ToArgs)) return nullptr; @@ -6372,7 +6372,7 @@ Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; - + return new (Importer.getToContext()) CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit()); } @@ -6381,7 +6381,7 @@ Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; - + return new (Importer.getToContext()) CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation())); } @@ -6646,7 +6646,7 @@ Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) { } return new (Importer.getToContext()) - CallExpr(Importer.getToContext(), ToCallee, + CallExpr(Importer.getToContext(), ToCallee, llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(), Importer.Import(E->getRParenLoc())); } @@ -6838,18 +6838,18 @@ Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc()); SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc()); SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets()); - + if (isa<CXXStaticCastExpr>(E)) { return CXXStaticCastExpr::Create( - Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, + Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); } else if (isa<CXXDynamicCastExpr>(E)) { return CXXDynamicCastExpr::Create( - Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, + Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); } else if (isa<CXXReinterpretCastExpr>(E)) { return CXXReinterpretCastExpr::Create( - Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, + Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); } else { return nullptr; @@ -6943,22 +6943,22 @@ QualType ASTImporter::Import(QualType FromT) { return {}; const Type *fromTy = FromT.getTypePtr(); - - // Check whether we've already imported this type. + + // Check whether we've already imported this type. llvm::DenseMap<const Type *, const Type *>::iterator Pos = ImportedTypes.find(fromTy); if (Pos != ImportedTypes.end()) return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers()); - + // Import the type ASTNodeImporter Importer(*this); QualType ToT = Importer.Visit(fromTy); if (ToT.isNull()) return ToT; - + // Record the imported type. ImportedTypes[fromTy] = ToT.getTypePtr(); - + return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers()); } @@ -6972,7 +6972,7 @@ TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) { if (T.isNull()) return nullptr; - return ToContext.getTrivialTypeSourceInfo(T, + return ToContext.getTrivialTypeSourceInfo(T, Import(FromTSI->getTypeLoc().getLocStart())); } @@ -7027,7 +7027,7 @@ DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { if (!ToDC) return nullptr; - // When we're using a record/enum/Objective-C class/protocol as a context, we + // When we're using a record/enum/Objective-C class/protocol as a context, we // need it to have a definition. if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) { auto *FromRecord = cast<RecordDecl>(FromDC); @@ -7048,7 +7048,7 @@ DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToEnum); - } + } } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) { auto *FromClass = cast<ObjCInterfaceDecl>(FromDC); if (ToClass->getDefinition()) { @@ -7068,9 +7068,9 @@ DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToProto); - } + } } - + return ToDC; } @@ -7085,11 +7085,11 @@ Stmt *ASTImporter::Import(Stmt *FromS) { if (!FromS) return nullptr; - // Check whether we've already imported this declaration. + // Check whether we've already imported this declaration. llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS); if (Pos != ImportedStmts.end()) return Pos->second; - + // Import the type ASTNodeImporter Importer(*this); Stmt *ToS = Importer.Visit(FromS); @@ -7115,14 +7115,14 @@ NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) { return nullptr; case NestedNameSpecifier::Namespace: - if (auto *NS = + if (auto *NS = cast_or_null<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) { return NestedNameSpecifier::Create(ToContext, prefix, NS); } return nullptr; case NestedNameSpecifier::NamespaceAlias: - if (auto *NSAD = + if (auto *NSAD = cast_or_null<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) { return NestedNameSpecifier::Create(ToContext, prefix, NSAD); } @@ -7142,9 +7142,9 @@ NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) { case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = Import(QualType(FromNNS->getAsType(), 0u)); if (!T.isNull()) { - bool bTemplate = FromNNS->getKind() == + bool bTemplate = FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; - return NestedNameSpecifier::Create(ToContext, prefix, + return NestedNameSpecifier::Create(ToContext, prefix, bTemplate, T.getTypePtr()); } } @@ -7231,48 +7231,48 @@ TemplateName ASTImporter::Import(TemplateName From) { if (auto *ToTemplate = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl()))) return TemplateName(ToTemplate); - + return {}; - + case TemplateName::OverloadedTemplate: { OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); UnresolvedSet<2> ToTemplates; for (auto *I : *FromStorage) { - if (auto *To = cast_or_null<NamedDecl>(Import(I))) + if (auto *To = cast_or_null<NamedDecl>(Import(I))) ToTemplates.addDecl(To); else return {}; } - return ToContext.getOverloadedTemplateName(ToTemplates.begin(), + return ToContext.getOverloadedTemplateName(ToTemplates.begin(), ToTemplates.end()); } - + case TemplateName::QualifiedTemplate: { QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); NestedNameSpecifier *Qualifier = Import(QTN->getQualifier()); if (!Qualifier) return {}; - + if (auto *ToTemplate = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl()))) - return ToContext.getQualifiedTemplateName(Qualifier, - QTN->hasTemplateKeyword(), + return ToContext.getQualifiedTemplateName(Qualifier, + QTN->hasTemplateKeyword(), ToTemplate); return {}; } - + case TemplateName::DependentTemplate: { DependentTemplateName *DTN = From.getAsDependentTemplateName(); NestedNameSpecifier *Qualifier = Import(DTN->getQualifier()); if (!Qualifier) return {}; - + if (DTN->isIdentifier()) { - return ToContext.getDependentTemplateName(Qualifier, + return ToContext.getDependentTemplateName(Qualifier, Import(DTN->getIdentifier())); } - + return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator()); } @@ -7287,10 +7287,10 @@ TemplateName ASTImporter::Import(TemplateName From) { TemplateName replacement = Import(subst->getReplacement()); if (replacement.isNull()) return {}; - + return ToContext.getSubstTemplateTemplateParm(param, replacement); } - + case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *SubstPack = From.getAsSubstTemplateTemplateParmPack(); @@ -7299,17 +7299,17 @@ TemplateName ASTImporter::Import(TemplateName From) { Import(SubstPack->getParameterPack())); if (!Param) return {}; - + ASTNodeImporter Importer(*this); - TemplateArgument ArgPack + TemplateArgument ArgPack = Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); if (ArgPack.isNull()) return {}; - + return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack); } } - + llvm_unreachable("Invalid template name kind"); } @@ -7452,26 +7452,26 @@ void ASTImporter::ImportDefinition(Decl *From) { Decl *To = Import(From); if (!To) return; - + if (auto *FromDC = cast<DeclContext>(From)) { ASTNodeImporter Importer(*this); - + if (auto *ToRecord = dyn_cast<RecordDecl>(To)) { if (!ToRecord->getDefinition()) { - Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, + Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, ASTNodeImporter::IDK_Everything); return; - } + } } if (auto *ToEnum = dyn_cast<EnumDecl>(To)) { if (!ToEnum->getDefinition()) { - Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, + Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); return; - } + } } - + if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) { if (!ToIFace->getDefinition()) { Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace, @@ -7487,7 +7487,7 @@ void ASTImporter::ImportDefinition(Decl *From) { return; } } - + Importer.ImportDeclContext(FromDC, true); } } diff --git a/lib/AST/ASTStructuralEquivalence.cpp b/lib/AST/ASTStructuralEquivalence.cpp index 7853ab28810b9..df3c2be9a2e28 100644 --- a/lib/AST/ASTStructuralEquivalence.cpp +++ b/lib/AST/ASTStructuralEquivalence.cpp @@ -505,7 +505,7 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (Proto1->getTypeQuals() != Proto2->getTypeQuals()) return false; - + // Check exceptions, this information is lost in canonical type. const auto *OrigProto1 = cast<FunctionProtoType>(OrigT1.getDesugaredType(Context.FromCtx)); @@ -513,7 +513,7 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, cast<FunctionProtoType>(OrigT2.getDesugaredType(Context.ToCtx)); auto Spec1 = OrigProto1->getExceptionSpecType(); auto Spec2 = OrigProto2->getExceptionSpecType(); - + if (Spec1 != Spec2) return false; if (Spec1 == EST_Dynamic) { diff --git a/lib/AST/CXXInheritance.cpp b/lib/AST/CXXInheritance.cpp index 2825329775edd..a0b22b6a85e0c 100644 --- a/lib/AST/CXXInheritance.cpp +++ b/lib/AST/CXXInheritance.cpp @@ -99,7 +99,7 @@ bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const { if (getCanonicalDecl() == Base->getCanonicalDecl()) return false; - + Paths.setOrigin(const_cast<CXXRecordDecl*>(this)); const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); @@ -120,7 +120,7 @@ bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const { if (getCanonicalDecl() == Base->getCanonicalDecl()) return false; - + Paths.setOrigin(const_cast<CXXRecordDecl*>(this)); const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); @@ -165,7 +165,7 @@ bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches, continue; } - CXXRecordDecl *Base = + CXXRecordDecl *Base = cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition()); if (!Base || (Base->isDependentContext() && @@ -174,7 +174,7 @@ bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches, AllMatches = false; continue; } - + Queue.push_back(Base); if (!BaseMatches(Base)) { if (AllowShortCircuit) return false; @@ -209,12 +209,12 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, // C++ [temp.dep]p3: // In the definition of a class template or a member of a class template, // if a base class of the class template depends on a template-parameter, - // the base class scope is not examined during unqualified name lookup - // either at the point of definition of the class template or member or + // the base class scope is not examined during unqualified name lookup + // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. if (!LookupInDependent && BaseType->isDependentType()) continue; - + // Determine whether we need to visit this base class at all, // updating the count of subobjects appropriately. IsVirtBaseAndNumberNonVirtBases &Subobjects = ClassSubobjects[BaseType]; @@ -261,13 +261,13 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, if (IsFirstStep) ScratchPath.Access = BaseSpec.getAccessSpecifier(); else - ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, + ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, BaseSpec.getAccessSpecifier()); } - + // Track whether there's a path involving this specific base. bool FoundPathThroughBase = false; - + if (BaseMatches(&BaseSpec, ScratchPath)) { // We've found a path that terminates at this base. FoundPath = FoundPathThroughBase = true; @@ -313,15 +313,15 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, // a sub-object A if A is a base class sub-object of B. Any // declarations that are so hidden are eliminated from // consideration. - - // There is a path to a base class that meets the criteria. If we're + + // There is a path to a base class that meets the criteria. If we're // not collecting paths or finding ambiguities, we're done. FoundPath = FoundPathThroughBase = true; if (!isFindingAmbiguities()) return FoundPath; } } - + // Pop this base specifier off the current path (if we're // collecting paths). if (isRecordingPaths()) { @@ -336,7 +336,7 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, // Reset the scratch path access. ScratchPath.Access = AccessToHere; - + return FoundPath; } @@ -352,7 +352,7 @@ bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches, // we're done. if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities()) return true; - + // C++ [class.member.lookup]p6: // When virtual base classes are used, a hidden declaration can be // reached along a path through the sub-object lattice that does @@ -396,7 +396,7 @@ bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches, return true; } -bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, const CXXRecordDecl *BaseRecord) { assert(BaseRecord->getCanonicalDecl() == BaseRecord && @@ -405,7 +405,7 @@ bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, ->getCanonicalDecl() == BaseRecord; } -bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, const CXXRecordDecl *BaseRecord) { assert(BaseRecord->getCanonicalDecl() == BaseRecord && @@ -415,7 +415,7 @@ bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, ->getCanonicalDecl() == BaseRecord; } -bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) { RecordDecl *BaseRecord = @@ -490,12 +490,12 @@ bool CXXRecordDecl::FindOMPReductionMember(const CXXBaseSpecifier *Specifier, } bool CXXRecordDecl:: -FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, +FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) { RecordDecl *BaseRecord = Specifier->getType()->castAs<RecordType>()->getDecl(); - + for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); Path.Decls = Path.Decls.slice(1)) { @@ -504,7 +504,7 @@ FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag)) return true; } - + return false; } @@ -538,20 +538,20 @@ std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName( return Results; } -void OverridingMethods::add(unsigned OverriddenSubobject, +void OverridingMethods::add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding) { SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides = Overrides[OverriddenSubobject]; - if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(), + if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(), Overriding) == SubobjectOverrides.end()) SubobjectOverrides.push_back(Overriding); } void OverridingMethods::add(const OverridingMethods &Other) { for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) { - for (overriding_const_iterator M = I->second.begin(), + for (overriding_const_iterator M = I->second.begin(), MEnd = I->second.end(); - M != MEnd; + M != MEnd; ++M) add(I->first, *M); } @@ -586,7 +586,7 @@ public: } // namespace -void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, +void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, bool VirtualBase, const CXXRecordDecl *InVirtualSubobject, CXXFinalOverriderMap &Overriders) { @@ -633,7 +633,7 @@ void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, // Merge the overriders from this base class into our own set of // overriders. - for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), + for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), OMEnd = BaseOverriders->end(); OM != OMEnd; ++OM) { @@ -656,7 +656,7 @@ void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, if (OverriddenMethods.begin() == OverriddenMethods.end()) { // This is a new virtual function that does not override any // other virtual function. Add it to the map of virtual - // functions for which we are tracking overridders. + // functions for which we are tracking overridders. // C++ [class.virtual]p2: // For convenience we say that any virtual function overrides itself. @@ -711,12 +711,12 @@ void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, FinalOverriderCollector::~FinalOverriderCollector() { for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end(); - VO != VOEnd; + VO != VOEnd; ++VO) delete VO->second; } -void +void CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const { FinalOverriderCollector Collector; Collector.Collect(this, false, nullptr, FinalOverriders); @@ -754,7 +754,7 @@ CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const { } } -static void +static void AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, CXXIndirectPrimaryBaseSet& Bases) { // If the record has a virtual primary base class, add it to our set. @@ -777,7 +777,7 @@ AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, } -void +void CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const { ASTContext &Context = getASTContext(); diff --git a/lib/AST/Comment.cpp b/lib/AST/Comment.cpp index dfa2a1665d40f..0d759e226c427 100644 --- a/lib/AST/Comment.cpp +++ b/lib/AST/Comment.cpp @@ -205,7 +205,7 @@ void DeclInfo::fill() { return; } CurrentDecl = CommentDecl; - + Decl::Kind K = CommentDecl->getKind(); switch (K) { default: diff --git a/lib/AST/CommentLexer.cpp b/lib/AST/CommentLexer.cpp index 6ff4d45a9572e..8d401ff5c7eaa 100644 --- a/lib/AST/CommentLexer.cpp +++ b/lib/AST/CommentLexer.cpp @@ -274,7 +274,7 @@ const char *findCCommentEnd(const char *BufferPtr, const char *BufferEnd) { } llvm_unreachable("buffer end hit before '*/' was seen"); } - + } // end anonymous namespace void Lexer::formTokenWithChars(Token &Result, const char *TokEnd, diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 3b9b85a20af6f..8030dd0c2f41a 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -633,7 +633,7 @@ LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, // equivalent in C99) // The C++ modules TS adds "non-exported" to this list. if (Context.getLangOpts().CPlusPlus && - Var->getType().isConstQualified() && + Var->getType().isConstQualified() && !Var->getType().isVolatileQualified() && !Var->isInline() && !isExportedFromModuleIntefaceUnit(Var)) { @@ -1049,7 +1049,7 @@ bool NamedDecl::isLinkageValid() const { ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { StringRef name = getName(); if (name.empty()) return SFF_None; - + if (name.front() == 'C') if (name == "CFStringCreateWithFormat" || name == "CFStringCreateWithFormatAndArguments" || @@ -1338,7 +1338,7 @@ LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, case Decl::ObjCPropertyImpl: case Decl::ObjCProtocol: return getExternalLinkageFor(D); - + case Decl::CXXRecord: { const auto *Record = cast<CXXRecordDecl>(D); if (Record->isLambda()) { @@ -1348,25 +1348,25 @@ LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, } // This lambda has its linkage/visibility determined: - // - either by the outermost lambda if that lambda has no mangling - // number. + // - either by the outermost lambda if that lambda has no mangling + // number. // - or by the parent of the outer most lambda - // This prevents infinite recursion in settings such as nested lambdas - // used in NSDMI's, for e.g. + // This prevents infinite recursion in settings such as nested lambdas + // used in NSDMI's, for e.g. // struct L { // int t{}; - // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t); + // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t); // }; - const CXXRecordDecl *OuterMostLambda = + const CXXRecordDecl *OuterMostLambda = getOutermostEnclosingLambda(Record); if (!OuterMostLambda->getLambdaManglingNumber()) return getInternalLinkageFor(D); - + return getLVForClosure( OuterMostLambda->getDeclContext()->getRedeclContext(), OuterMostLambda->getLambdaContextDecl(), computation); } - + break; } } @@ -1374,7 +1374,7 @@ LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, // Handle linkage for namespace-scope names. if (D->getDeclContext()->getRedeclContext()->isFileContext()) return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage); - + // C++ [basic.link]p5: // In addition, a member function, static data member, a named // class or enumeration of class scope, or an unnamed class or @@ -1718,7 +1718,7 @@ NamedDecl *NamedDecl::getUnderlyingDeclImpl() { bool NamedDecl::isCXXInstanceMember() const { if (!isCXXClassMember()) return false; - + const NamedDecl *D = this; if (isa<UsingShadowDecl>(D)) D = cast<UsingShadowDecl>(D)->getTargetDecl(); @@ -1938,7 +1938,7 @@ VarDecl::TLSKind VarDecl::getTLSKind() const { SourceRange VarDecl::getSourceRange() const { if (const Expr *Init = getInit()) { SourceLocation InitEnd = Init->getLocEnd(); - // If Init is implicit, ignore its source range and fallback on + // If Init is implicit, ignore its source range and fallback on // DeclaratorDecl::getSourceRange() to handle postfix elements. if (InitEnd.isValid() && InitEnd != getLocation()) return SourceRange(getOuterLocStart(), InitEnd); @@ -2174,11 +2174,11 @@ bool VarDecl::isOutOfLine() const { return false; // If this static data member was instantiated from a static data member of - // a class template, check whether that static data member was defined + // a class template, check whether that static data member was defined // out-of-line. if (VarDecl *VD = getInstantiatedFromStaticDataMember()) return VD->isOutOfLine(); - + return false; } @@ -2891,7 +2891,7 @@ FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); FunTmpl->setPreviousDecl(PrevFunTmpl); } - + if (PrevDecl && PrevDecl->IsInline) IsInline = true; } @@ -3043,7 +3043,7 @@ static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { if (Redecl->isImplicit()) return false; - if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) + if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) return true; // Not an inline definition return false; @@ -3088,7 +3088,7 @@ bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { if (!Prev->isInlineSpecified() || Prev->getStorageClass() != SC_Extern) return false; - } else if (Prev->isInlineSpecified() && + } else if (Prev->isInlineSpecified() && Prev->getStorageClass() != SC_Extern) { return false; } @@ -3100,8 +3100,8 @@ bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { return false; // C99 6.7.4p6: - // [...] If all of the file scope declarations for a function in a - // translation unit include the inline function specifier without extern, + // [...] If all of the file scope declarations for a function in a + // translation unit include the inline function specifier without extern, // then the definition in that translation unit is an inline definition. if (isInlineSpecified() && getStorageClass() != SC_Extern) return false; @@ -3149,12 +3149,9 @@ SourceRange FunctionDecl::getExceptionSpecSourceRange() const { const Attr *FunctionDecl::getUnusedResultAttr() const { QualType RetType = getReturnType(); - if (RetType->isRecordType()) { - if (const auto *Ret = - dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) { - if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>()) - return R; - } + if (const auto *Ret = RetType->getAsRecordDecl()) { + if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>()) + return R; } else if (const auto *ET = RetType->getAs<EnumType>()) { if (const EnumDecl *ED = ET->getDecl()) { if (const auto *R = ED->getAttr<WarnUnusedResultAttr>()) @@ -3177,16 +3174,16 @@ const Attr *FunctionDecl::getUnusedResultAttr() const { /// inline definition becomes externally visible (C99 6.7.4p6). /// /// In GNU89 mode, or if the gnu_inline attribute is attached to the function -/// definition, we use the GNU semantics for inline, which are nearly the -/// opposite of C99 semantics. In particular, "inline" by itself will create -/// an externally visible symbol, but "extern inline" will not create an +/// definition, we use the GNU semantics for inline, which are nearly the +/// opposite of C99 semantics. In particular, "inline" by itself will create +/// an externally visible symbol, but "extern inline" will not create an /// externally visible symbol. bool FunctionDecl::isInlineDefinitionExternallyVisible() const { assert((doesThisDeclarationHaveABody() || willHaveBody()) && "Must be a function definition"); assert(isInlined() && "Function must be inline"); ASTContext &Context = getASTContext(); - + if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { // Note: If you change the logic here, please change // doesDeclarationForceExternallyVisibleDefinition as well. @@ -3196,15 +3193,15 @@ bool FunctionDecl::isInlineDefinitionExternallyVisible() const { // externally visible. if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) return true; - + // If any declaration is 'inline' but not 'extern', then this definition // is externally visible. for (auto Redecl : redecls()) { - if (Redecl->isInlineSpecified() && + if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != SC_Extern) return true; - } - + } + return false; } @@ -3213,17 +3210,17 @@ bool FunctionDecl::isInlineDefinitionExternallyVisible() const { "should not use C inline rules in C++"); // C99 6.7.4p6: - // [...] If all of the file scope declarations for a function in a - // translation unit include the inline function specifier without extern, + // [...] If all of the file scope declarations for a function in a + // translation unit include the inline function specifier without extern, // then the definition in that translation unit is an inline definition. for (auto Redecl : redecls()) { if (RedeclForcesDefC99(Redecl)) return true; } - + // C99 6.7.4p6: - // An inline definition does not provide an external definition for the - // function, and does not forbid an external definition in another + // An inline definition does not provide an external definition for the + // function, and does not forbid an external definition in another // translation unit. return false; } @@ -3273,13 +3270,13 @@ MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>(); } -void +void FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, TemplateSpecializationKind TSK) { - assert(TemplateOrSpecialization.isNull() && + assert(TemplateOrSpecialization.isNull() && "Member function is already a specialization"); - MemberSpecializationInfo *Info + MemberSpecializationInfo *Info = new (C) MemberSpecializationInfo(FD, TSK); TemplateOrSpecialization = Info; } @@ -3296,12 +3293,12 @@ bool FunctionDecl::isImplicitlyInstantiable() const { // If the function is invalid, it can't be implicitly instantiated. if (isInvalidDecl()) return false; - + switch (getTemplateSpecializationKind()) { case TSK_Undeclared: case TSK_ExplicitInstantiationDefinition: return false; - + case TSK_ImplicitInstantiation: return true; @@ -3320,12 +3317,12 @@ bool FunctionDecl::isImplicitlyInstantiable() const { bool HasPattern = false; if (PatternDecl) HasPattern = PatternDecl->hasBody(PatternDecl); - + // C++0x [temp.explicit]p9: // Except for inline functions, other explicit instantiation declarations // have the effect of suppressing the implicit instantiation of the entity - // to which they refer. - if (!HasPattern || !PatternDecl) + // to which they refer. + if (!HasPattern || !PatternDecl) return true; return PatternDecl->isInlined(); @@ -3335,7 +3332,7 @@ bool FunctionDecl::isTemplateInstantiation() const { switch (getTemplateSpecializationKind()) { case TSK_Undeclared: case TSK_ExplicitSpecialization: - return false; + return false; case TSK_ImplicitInstantiation: case TSK_ExplicitInstantiationDeclaration: case TSK_ExplicitInstantiationDefinition: @@ -3343,7 +3340,7 @@ bool FunctionDecl::isTemplateInstantiation() const { } llvm_unreachable("All TSK values handled."); } - + FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { // Handle class scope explicit specialization special case. if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { @@ -3352,13 +3349,13 @@ FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { return nullptr; } - // If this is a generic lambda call operator specialization, its + // If this is a generic lambda call operator specialization, its // instantiation pattern is always its primary template's pattern - // even if its primary template was instantiated from another + // even if its primary template was instantiated from another // member template (which happens with nested generic lambdas). - // Since a lambda's call operator's body is transformed eagerly, - // we don't have to go hunting for a prototype definition template - // (i.e. instantiated-from-member-template) to use as an instantiation + // Since a lambda's call operator's body is transformed eagerly, + // we don't have to go hunting for a prototype definition template + // (i.e. instantiated-from-member-template) to use as an instantiation // pattern. if (isGenericLambdaCallOperatorSpecialization( @@ -3377,7 +3374,7 @@ FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { } return getDefinitionOrSelf(Primary->getTemplatedDecl()); - } + } if (auto *MFD = getInstantiatedFromMemberFunction()) return getDefinitionOrSelf(MFD); @@ -3432,7 +3429,7 @@ FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, TemplateSpecializationKind TSK, const TemplateArgumentListInfo *TemplateArgsAsWritten, SourceLocation PointOfInstantiation) { - assert(TSK != TSK_Undeclared && + assert(TSK != TSK_Undeclared && "Must specify the type of function template specialization"); FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); @@ -3500,7 +3497,7 @@ TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); if (MSInfo) return MSInfo->getTemplateSpecializationKind(); - + return TSK_Undeclared; } @@ -3540,22 +3537,22 @@ SourceLocation FunctionDecl::getPointOfInstantiation() const { else if (MemberSpecializationInfo *MSInfo = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) return MSInfo->getPointOfInstantiation(); - + return SourceLocation(); } bool FunctionDecl::isOutOfLine() const { if (Decl::isOutOfLine()) return true; - - // If this function was instantiated from a member function of a + + // If this function was instantiated from a member function of a // class template, check whether that member function was defined out-of-line. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { const FunctionDecl *Definition; if (FD->hasBody(Definition)) return Definition->isOutOfLine(); } - + // If this function was instantiated from a function template, // check whether that function template was defined out-of-line. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { @@ -3563,7 +3560,7 @@ bool FunctionDecl::isOutOfLine() const { if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) return Definition->isOutOfLine(); } - + return false; } @@ -3576,7 +3573,7 @@ unsigned FunctionDecl::getMemoryFunctionKind() const { if (!FnInfo) return 0; - + // Builtin handling. switch (getBuiltinID()) { case Builtin::BI__builtin_memset: @@ -4525,7 +4522,7 @@ static unsigned getNumModuleIdentifiers(Module *Mod) { return Result; } -ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, +ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef<SourceLocation> IdentifierLocs) : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) { @@ -4535,7 +4532,7 @@ ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, StoredLocs); } -ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, +ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc) : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) { *getTrailingObjects<SourceLocation>() = EndLoc; diff --git a/lib/AST/DeclBase.cpp b/lib/AST/DeclBase.cpp index e3817c0abc38d..700ddd389ddd3 100644 --- a/lib/AST/DeclBase.cpp +++ b/lib/AST/DeclBase.cpp @@ -139,7 +139,7 @@ void Decl::setInvalidDecl(bool Invalid) { if (!isa<ParmVarDecl>(this)) { // Defensive maneuver for ill-formed code: we're likely not to make it to // a point where we set the access specifier, so default it to "public" - // to avoid triggering asserts elsewhere in the front end. + // to avoid triggering asserts elsewhere in the front end. setAccess(AS_public); } @@ -211,7 +211,7 @@ bool Decl::isTemplateParameterPack() const { bool Decl::isParameterPack() const { if (const auto *Parm = dyn_cast<ParmVarDecl>(this)) return Parm->isParameterPack(); - + return isTemplateParameterPack(); } @@ -253,7 +253,7 @@ bool Decl::isTemplated() const { const DeclContext *Decl::getParentFunctionOrMethod() const { for (const DeclContext *DC = getDeclContext(); - DC && !DC->isTranslationUnit() && !DC->isNamespace(); + DC && !DC->isTranslationUnit() && !DC->isNamespace(); DC = DC->getParent()) if (DC->isFunctionOrMethod()) return DC; @@ -419,7 +419,7 @@ void Decl::markUsed(ASTContext &C) { setIsUsed(); } -bool Decl::isReferenced() const { +bool Decl::isReferenced() const { if (Referenced) return true; @@ -428,7 +428,7 @@ bool Decl::isReferenced() const { if (I->Referenced) return true; - return false; + return false; } bool Decl::isExported() const { @@ -530,13 +530,13 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, HintMessage = " - "; HintMessage += A->getMessage(); } - + // Make sure that this declaration has not been marked 'unavailable'. if (A->getUnavailable()) { if (Message) { Message->clear(); llvm::raw_string_ostream Out(*Message); - Out << "not available on " << PrettyPlatformName + Out << "not available on " << PrettyPlatformName << HintMessage; } @@ -544,13 +544,13 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, } // Make sure that this declaration has already been introduced. - if (!A->getIntroduced().empty() && + if (!A->getIntroduced().empty() && EnclosingVersion < A->getIntroduced()) { if (Message) { Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTI(A->getIntroduced()); - Out << "introduced in " << PrettyPlatformName << ' ' + Out << "introduced in " << PrettyPlatformName << ' ' << VTI << HintMessage; } @@ -563,10 +563,10 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTO(A->getObsoleted()); - Out << "obsoleted in " << PrettyPlatformName << ' ' + Out << "obsoleted in " << PrettyPlatformName << ' ' << VTO << HintMessage; } - + return AR_Unavailable; } @@ -579,7 +579,7 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, Out << "first deprecated in " << PrettyPlatformName << ' ' << VTD << HintMessage; } - + return AR_Deprecated; } @@ -1012,7 +1012,7 @@ DeclContext *DeclContext::getLookupParent() { if (getParent()->getRedeclContext()->isFileContext() && getLexicalParent()->getRedeclContext()->isRecord()) return getLexicalParent(); - + return getParent(); } @@ -1047,11 +1047,11 @@ bool DeclContext::isDependentContext() const { if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) { if (Record->getDescribedClassTemplate()) return true; - + if (Record->isDependentLambda()) return true; } - + if (const auto *Function = dyn_cast<FunctionDecl>(this)) { if (Function->getDescribedFunctionTemplate()) return true; @@ -1140,12 +1140,12 @@ DeclContext *DeclContext::getPrimaryContext() { if (auto *Def = cast<ObjCInterfaceDecl>(this)->getDefinition()) return Def; return this; - + case Decl::ObjCProtocol: if (auto *Def = cast<ObjCProtocolDecl>(this)->getDefinition()) return Def; return this; - + case Decl::ObjCCategory: return this; @@ -1180,20 +1180,20 @@ DeclContext *DeclContext::getPrimaryContext() { } } -void +void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){ Contexts.clear(); - + if (DeclKind != Decl::Namespace) { Contexts.push_back(this); return; } - + auto *Self = static_cast<NamespaceDecl *>(this); for (NamespaceDecl *N = Self->getMostRecentDecl(); N; N = N->getPreviousDecl()) Contexts.push_back(N); - + std::reverse(Contexts.begin(), Contexts.end()); } @@ -1253,7 +1253,7 @@ DeclContext::LoadLexicalDeclsFromExternalStorage() const { bool FieldsAlreadyLoaded = false; if (const auto *RD = dyn_cast<RecordDecl>(this)) FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage; - + // Splice the newly-read declarations into the beginning of the list // of declarations. Decl *ExternalFirst, *ExternalLast; @@ -1638,7 +1638,7 @@ void DeclContext::loadLazyLocalLexicalLookups() { void DeclContext::localUncachedLookup(DeclarationName Name, SmallVectorImpl<NamedDecl *> &Results) { Results.clear(); - + // If there's no external storage, just perform a normal lookup and copy // the results. if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) { @@ -1661,7 +1661,7 @@ void DeclContext::localUncachedLookup(DeclarationName Name, } } - // Slow case: grovel through the declarations in our chain looking for + // Slow case: grovel through the declarations in our chain looking for // matches. // FIXME: If we have lazy external declarations, this will not find them! // FIXME: Should we CollectAllContexts and walk them all here? @@ -1892,7 +1892,7 @@ DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, PartialDiagnostic::Storage *DiagStorage = nullptr; if (PDiag.hasStorage()) DiagStorage = new (C) PartialDiagnostic::Storage; - + auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); // TODO: Maybe we shouldn't reverse the order during insertion. diff --git a/lib/AST/DeclCXX.cpp b/lib/AST/DeclCXX.cpp index 076e6376d1578..51e8e14f804aa 100644 --- a/lib/AST/DeclCXX.cpp +++ b/lib/AST/DeclCXX.cpp @@ -203,7 +203,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // The set of seen virtual base types. llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes; - + // The virtual bases of this class. SmallVector<const CXXBaseSpecifier *, 8> VBases; @@ -257,7 +257,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, data().Aggregate = false; // C++ [class.virtual]p1: - // A class that declares or inherits a virtual function is called a + // A class that declares or inherits a virtual function is called a // polymorphic class. if (BaseClassDecl->isPolymorphic()) { data().Polymorphic = true; @@ -277,7 +277,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // Record if this base is the first non-literal field or base. if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C)) data().HasNonLiteralTypeFieldsOrBases = true; - + // Now go through all virtual bases of this base and add them. for (const auto &VBase : BaseClassDecl->vbases()) { // Add this base if it's not already in the list. @@ -421,7 +421,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // has an Objective-C object member. if (BaseClassDecl->hasObjectMember()) setHasObjectMember(true); - + if (BaseClassDecl->hasVolatileMember()) setHasVolatileMember(true); @@ -453,7 +453,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // we know there are no repeated base classes. if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this)) data().IsStandardLayout = false; - + if (VBases.empty()) { data().IsParsingBaseSpecifiers = false; return; @@ -548,7 +548,7 @@ bool CXXRecordDecl::isTriviallyCopyable() const { } void CXXRecordDecl::markedVirtualFunctionPure() { - // C++ [class.abstract]p2: + // C++ [class.abstract]p2: // A class is abstract if it has at least one pure virtual function. data().Abstract = true; } @@ -639,7 +639,7 @@ void CXXRecordDecl::addedMember(Decl *D) { // Ignore friends and invalid declarations. if (D->getFriendObjectKind() || D->isInvalidDecl()) return; - + auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); if (FunTmpl) D = FunTmpl->getTemplatedDecl(); @@ -651,23 +651,23 @@ void CXXRecordDecl::addedMember(Decl *D) { if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying)) DUnderlying = UnderlyingFunTmpl->getTemplatedDecl(); } - + if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isVirtual()) { // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class with [...] no virtual functions. data().Aggregate = false; - + // C++ [class]p4: // A POD-struct is an aggregate class... data().PlainOldData = false; - + // C++14 [meta.unary.prop]p4: // T is a class type [...] with [...] no virtual member functions... data().Empty = false; // C++ [class.virtual]p1: - // A class that declares or inherits a virtual function is called a + // A class that declares or inherits a virtual function is called a // polymorphic class. data().Polymorphic = true; @@ -873,8 +873,8 @@ void CXXRecordDecl::addedMember(Decl *D) { data().IsStandardLayout = false; // C++ [class.bit]p2: - // A declaration for a bit-field that omits the identifier declares an - // unnamed bit-field. Unnamed bit-fields are not members and cannot be + // A declaration for a bit-field that omits the identifier declares an + // unnamed bit-field. Unnamed bit-fields are not members and cannot be // initialized. if (Field->isUnnamedBitfield()) { // C++ [meta.unary.prop]p4: [LWG2358] @@ -886,7 +886,7 @@ void CXXRecordDecl::addedMember(Decl *D) { data().Empty = false; return; } - + // C++11 [class]p7: // A standard-layout class is a class that: // -- either has no non-static data members in the most derived class @@ -898,7 +898,7 @@ void CXXRecordDecl::addedMember(Decl *D) { // An aggregate is an array or a class (clause 9) with [...] no // private or protected non-static data members (clause 11). // - // A POD must be an aggregate. + // A POD must be an aggregate. if (D->getAccess() == AS_private || D->getAccess() == AS_protected) { data().Aggregate = false; data().PlainOldData = false; @@ -938,8 +938,8 @@ void CXXRecordDecl::addedMember(Decl *D) { data().HasVariantMembers = true; // C++0x [class]p9: - // A POD struct is a class that is both a trivial class and a - // standard-layout class, and has no non-static data members of type + // A POD struct is a class that is both a trivial class and a + // standard-layout class, and has no non-static data members of type // non-POD struct, non-POD union (or array of such types). // // Automatic Reference Counting: the presence of a member of Objective-C pointer type @@ -974,7 +974,7 @@ void CXXRecordDecl::addedMember(Decl *D) { } } else if (!T.isCXX98PODType(Context)) data().PlainOldData = false; - + if (T->isReferenceType()) { if (!Field->hasInClassInitializer()) data().HasUninitializedReferenceMember = true; @@ -1235,7 +1235,7 @@ void CXXRecordDecl::addedMember(Decl *D) { // T is a class type [...] with [...] no non-static data members data().Empty = false; } - + // Handle using declarations of conversion functions. if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) { if (Shadow->getDeclName().getNameKind() @@ -1321,40 +1321,40 @@ bool CXXRecordDecl::isCLike() const { return isPOD() && data().HasOnlyCMembers; } - -bool CXXRecordDecl::isGenericLambda() const { + +bool CXXRecordDecl::isGenericLambda() const { if (!isLambda()) return false; return getLambdaData().IsGenericLambda; } CXXMethodDecl* CXXRecordDecl::getLambdaCallOperator() const { if (!isLambda()) return nullptr; - DeclarationName Name = + DeclarationName Name = getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); DeclContext::lookup_result Calls = lookup(Name); assert(!Calls.empty() && "Missing lambda call operator!"); - assert(Calls.size() == 1 && "More than one lambda call operator!"); - + assert(Calls.size() == 1 && "More than one lambda call operator!"); + NamedDecl *CallOp = Calls.front(); if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp)) return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl()); - + return cast<CXXMethodDecl>(CallOp); } CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { if (!isLambda()) return nullptr; - DeclarationName Name = + DeclarationName Name = &getASTContext().Idents.get(getLambdaStaticInvokerName()); DeclContext::lookup_result Invoker = lookup(Name); if (Invoker.empty()) return nullptr; - assert(Invoker.size() == 1 && "More than one static invoker operator!"); + assert(Invoker.size() == 1 && "More than one static invoker operator!"); NamedDecl *InvokerFun = Invoker.front(); if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(InvokerFun)) return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl()); - - return cast<CXXMethodDecl>(InvokerFun); + + return cast<CXXMethodDecl>(InvokerFun); } void CXXRecordDecl::getCaptureFields( @@ -1375,10 +1375,10 @@ void CXXRecordDecl::getCaptureFields( assert(Field == field_end()); } -TemplateParameterList * +TemplateParameterList * CXXRecordDecl::getGenericLambdaTemplateParameterList() const { if (!isLambda()) return nullptr; - CXXMethodDecl *CallOp = getLambdaCallOperator(); + CXXMethodDecl *CallOp = getLambdaCallOperator(); if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) return Tmpl->getTemplateParameters(); return nullptr; @@ -1481,7 +1481,7 @@ static void CollectVisibleConversions(ASTContext &Context, // found. These will be added to the output as long as they don't // appear in the hidden-conversions set. UnresolvedSet<8> VBaseCs; - + // The set of conversions in virtual bases that we've determined to // be hidden. llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs; @@ -1572,13 +1572,13 @@ MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const { return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>(); } -void +void CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK) { - assert(TemplateOrInstantiation.isNull() && + assert(TemplateOrInstantiation.isNull() && "Previous template or instantiation?"); assert(!isa<ClassTemplatePartialSpecializationDecl>(this)); - TemplateOrInstantiation + TemplateOrInstantiation = new (getASTContext()) MemberSpecializationInfo(RD, TSK); } @@ -1593,25 +1593,25 @@ void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) { TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) return Spec->getSpecializationKind(); - + if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) return MSInfo->getTemplateSpecializationKind(); - + return TSK_Undeclared; } -void +void CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) { Spec->setSpecializationKind(TSK); return; } - + if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { MSInfo->setTemplateSpecializationKind(TSK); return; } - + llvm_unreachable("Not a class template or member class specialization"); } @@ -1771,17 +1771,17 @@ void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { getFinalOverriders(MyFinalOverriders); FinalOverriders = &MyFinalOverriders; } - + bool Done = false; - for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), + for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), MEnd = FinalOverriders->end(); M != MEnd && !Done; ++M) { - for (OverridingMethods::iterator SO = M->second.begin(), + for (OverridingMethods::iterator SO = M->second.begin(), SOEnd = M->second.end(); SO != SOEnd && !Done; ++SO) { - assert(SO->second.size() > 0 && + assert(SO->second.size() > 0 && "All virtual functions have overriding virtual functions"); - + // C++ [class.abstract]p4: // A class is abstract if it contains or inherits at least one // pure virtual function for which the final overrider is pure @@ -1794,7 +1794,7 @@ void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { } } } - + // Set access bits correctly on the directly-declared conversions. for (conversion_iterator I = conversion_begin(), E = conversion_end(); I != E; ++I) @@ -1805,14 +1805,14 @@ bool CXXRecordDecl::mayBeAbstract() const { if (data().Abstract || isInvalidDecl() || !data().Polymorphic || isDependentContext()) return false; - + for (const auto &B : bases()) { const auto *BaseDecl = cast<CXXRecordDecl>(B.getType()->getAs<RecordType>()->getDecl()); if (BaseDecl->isAbstract()) return true; } - + return false; } @@ -2006,7 +2006,7 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { return false; // C++ [basic.stc.dynamic.deallocation]p2: - // If a class T has a member deallocation function named operator delete + // If a class T has a member deallocation function named operator delete // with exactly one parameter, then that function is a usual (non-placement) // deallocation function. [...] if (getNumParams() == 1) @@ -2022,8 +2022,8 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { ++UsualParams; // C++ <=14 [basic.stc.dynamic.deallocation]p2: - // [...] If class T does not declare such an operator delete but does - // declare a member deallocation function named operator delete with + // [...] If class T does not declare such an operator delete but does + // declare a member deallocation function named operator delete with // exactly two parameters, the second of which has type std::size_t (18.1), // then this function is a usual deallocation function. // @@ -2048,8 +2048,8 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { // usual deallocation functions. if (Context.getLangOpts().AlignedAllocation) return true; - - // This function is a usual deallocation function if there are no + + // This function is a usual deallocation function if there are no // single-parameter deallocation functions of the same kind. DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName()); for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); @@ -2058,25 +2058,25 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { if (FD->getNumParams() == 1) return false; } - + return true; } bool CXXMethodDecl::isCopyAssignmentOperator() const { // C++0x [class.copy]p17: - // A user-declared copy assignment operator X::operator= is a non-static - // non-template member function of class X with exactly one parameter of + // A user-declared copy assignment operator X::operator= is a non-static + // non-template member function of class X with exactly one parameter of // type X, X&, const X&, volatile X& or const volatile X&. if (/*operator=*/getOverloadedOperator() != OO_Equal || - /*non-static*/ isStatic() || + /*non-static*/ isStatic() || /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() || getNumParams() != 1) return false; - + QualType ParamType = getParamDecl(0)->getType(); if (const auto *Ref = ParamType->getAs<LValueReferenceType>()) ParamType = Ref->getPointeeType(); - + ASTContext &Context = getASTContext(); QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(getParent())); @@ -2151,7 +2151,7 @@ QualType CXXMethodDecl::getThisType(ASTContext &C) const { } bool CXXMethodDecl::hasInlineBody() const { - // If this function is a template instantiation, look at the template from + // If this function is a template instantiation, look at the template from // which it was instantiated. const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); if (!CheckFn) @@ -2203,7 +2203,7 @@ CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, - SourceLocation L, Expr *Init, + SourceLocation L, Expr *Init, SourceLocation R) : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {} @@ -2225,13 +2225,13 @@ const Type *CXXCtorInitializer::getBaseClass() const { SourceLocation CXXCtorInitializer::getSourceLocation() const { if (isInClassMemberInitializer()) return getAnyMember()->getLocation(); - + if (isAnyMemberInitializer()) return getMemberLocation(); if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>()) return TSInfo->getTypeLoc().getLocalSourceRange().getBegin(); - + return {}; } @@ -2318,37 +2318,37 @@ bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const { // or else all other parameters have default arguments (8.3.6). // C++0x [class.copy]p3: // A non-template constructor for class X is a move constructor if its - // first parameter is of type X&&, const X&&, volatile X&&, or - // const volatile X&&, and either there are no other parameters or else + // first parameter is of type X&&, const X&&, volatile X&&, or + // const volatile X&&, and either there are no other parameters or else // all other parameters have default arguments. if ((getNumParams() < 1) || (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) || (getPrimaryTemplate() != nullptr) || (getDescribedFunctionTemplate() != nullptr)) return false; - + const ParmVarDecl *Param = getParamDecl(0); - - // Do we have a reference type? + + // Do we have a reference type? const auto *ParamRefType = Param->getType()->getAs<ReferenceType>(); if (!ParamRefType) return false; - + // Is it a reference to our class type? ASTContext &Context = getASTContext(); - + CanQualType PointeeType = Context.getCanonicalType(ParamRefType->getPointeeType()); - CanQualType ClassTy + CanQualType ClassTy = Context.getCanonicalType(Context.getTagDeclType(getParent())); if (PointeeType.getUnqualifiedType() != ClassTy) return false; - + // FIXME: other qualifiers? - + // We have a copy or move constructor. TypeQuals = PointeeType.getCVRQualifiers(); - return true; + return true; } bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { @@ -2379,14 +2379,14 @@ bool CXXConstructorDecl::isSpecializationCopyingObject() const { ASTContext &Context = getASTContext(); CanQualType ParamType = Context.getCanonicalType(Param->getType()); - + // Is it the same as our class type? - CanQualType ClassTy + CanQualType ClassTy = Context.getCanonicalType(Context.getTagDeclType(getParent())); if (ParamType.getUnqualifiedType() != ClassTy) return false; - - return true; + + return true; } void CXXDestructorDecl::anchor() {} diff --git a/lib/AST/DeclObjC.cpp b/lib/AST/DeclObjC.cpp index 5db0450999975..01fd10429fc1d 100644 --- a/lib/AST/DeclObjC.cpp +++ b/lib/AST/DeclObjC.cpp @@ -51,7 +51,7 @@ void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { memcpy(List, InList, sizeof(void*)*Elts); } -void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, +void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, const SourceLocation *Locs, ASTContext &Ctx) { if (Elts == 0) return; @@ -145,7 +145,7 @@ bool ObjCContainerDecl::HasUserDeclaredSetterMethod( break; } } - + // Also look into protocols, for a user declared instance method. for (const auto *Proto : ID->all_referenced_protocols()) if (Proto->HasUserDeclaredSetterMethod(Property)) @@ -235,7 +235,7 @@ ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration( if (Def->isHidden()) return nullptr; } - + // Search the extensions of a class first; they override what's in // the class itself. if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) { @@ -332,7 +332,7 @@ ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; - + if (data().ExternallyCompleted) LoadExternalDefinition(); @@ -351,7 +351,7 @@ ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const { SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const { if (TypeSourceInfo *superTInfo = getSuperClassTInfo()) return superTInfo->getTypeLoc().getLocStart(); - + return SourceLocation(); } @@ -429,12 +429,12 @@ void ObjCInterfaceDecl::mergeClassExtensionProtocolList( if (data().ExternallyCompleted) LoadExternalDefinition(); - if (data().AllReferencedProtocols.empty() && + if (data().AllReferencedProtocols.empty() && data().ReferencedProtocols.empty()) { data().AllReferencedProtocols.set(ExtList, ExtNum, C); return; } - + // Check for duplicate protocol in class's protocol list. // This is O(n*m). But it is extremely rare and number of protocols in // class or its extension are very few. @@ -446,7 +446,7 @@ void ObjCInterfaceDecl::mergeClassExtensionProtocolList( if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) { protocolExists = true; break; - } + } } // Do we want to warn on a protocol in extension class which // already exist in the class? Probably not. @@ -633,7 +633,7 @@ ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, return I; } } - + ClassDecl = ClassDecl->getSuperClass(); } return nullptr; @@ -673,7 +673,7 @@ ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) { /// the class, its categories, and its super classes (using a linear search). /// When argument category "C" is specified, any implicit method found /// in this category is ignored. -ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, +ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, bool isInstance, bool shallowCategoryLookup, bool followSuper, @@ -693,7 +693,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, // 1. Look through primary class. if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance))) return MethodDecl; - + // 2. Didn't find one yet - now look through categories. for (const auto *Cat : ClassDecl->visible_categories()) if ((MethodDecl = Cat->getMethod(Sel, isInstance))) @@ -704,7 +704,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, for (const auto *I : ClassDecl->protocols()) if ((MethodDecl = I->lookupMethod(Sel, isInstance))) return MethodDecl; - + // 4. Didn't find one yet - now look through categories' protocols if (!shallowCategoryLookup) for (const auto *Cat : ClassDecl->visible_categories()) { @@ -716,8 +716,8 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, if (C != Cat || !MethodDecl->isImplicit()) return MethodDecl; } - - + + if (!followSuper) return nullptr; @@ -742,7 +742,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod( ObjCMethodDecl *Method = nullptr; if (ObjCImplementationDecl *ImpDecl = getImplementation()) - Method = Instance ? ImpDecl->getInstanceMethod(Sel) + Method = Instance ? ImpDecl->getInstanceMethod(Sel) : ImpDecl->getClassMethod(Sel); // Look through local category implementations associated with the class. @@ -990,12 +990,12 @@ ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { if (!isInstanceMethod()) family = OMF_None; break; - + case OMF_initialize: if (isInstanceMethod() || !getReturnType()->isVoidType()) family = OMF_None; break; - + case OMF_performSelector: if (!isInstanceMethod() || !getReturnType()->isObjCIdType()) family = OMF_None; @@ -1021,7 +1021,7 @@ ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { } } break; - + } // Cache the result. @@ -1441,11 +1441,11 @@ ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc), redeclarable_base(C) { setPreviousDecl(PrevDecl); - + // Copy the 'data' pointer over. if (PrevDecl) Data = PrevDecl->Data; - + setImplicit(IsInternal); setTypeParamList(typeParamList); @@ -1459,9 +1459,9 @@ void ObjCInterfaceDecl::LoadExternalDefinition() const { } void ObjCInterfaceDecl::setExternallyCompleted() { - assert(getASTContext().getExternalSource() && + assert(getASTContext().getExternalSource() && "Class can't be externally completed without an external source"); - assert(hasDefinition() && + assert(hasDefinition() && "Forward declarations can't be externally completed"); data().ExternallyCompleted = true; } @@ -1496,7 +1496,7 @@ ObjCImplementationDecl::getObjCRuntimeNameAsString() const { if (ObjCInterfaceDecl *ID = const_cast<ObjCImplementationDecl*>(this)->getClassInterface()) return ID->getObjCRuntimeNameAsString(); - + return getName(); } @@ -1504,11 +1504,11 @@ ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { if (const ObjCInterfaceDecl *Def = getDefinition()) { if (data().ExternallyCompleted) LoadExternalDefinition(); - + return getASTContext().getObjCImplementation( const_cast<ObjCInterfaceDecl*>(Def)); } - + // FIXME: Should make sure no callers ever do this. return nullptr; } @@ -1576,7 +1576,7 @@ ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { // cached and complete! if (!data().IvarListMissingImplementation) return data().IvarList; - + if (ObjCImplementationDecl *ImplDecl = getImplementation()) { data().IvarListMissingImplementation = false; if (!ImplDecl->ivar_empty()) { @@ -1593,7 +1593,7 @@ ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { curIvar->setNextIvar(IV); curIvar = IV; } - + if (!layout.empty()) { // Order synthesized ivars by their size. std::stable_sort(layout.begin(), layout.end()); @@ -1659,7 +1659,7 @@ bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool RHSIsQualifiedID) { if (!hasDefinition()) return false; - + ObjCInterfaceDecl *IDecl = this; // 1st, look up the class. for (auto *PI : IDecl->protocols()){ @@ -1869,7 +1869,7 @@ void ObjCProtocolDecl::allocateDefinitionData() { void ObjCProtocolDecl::startDefinition() { allocateDefinitionData(); - + // Update all of the declarations with a pointer to the definition. for (auto *RD : redecls()) RD->Data = this->Data; @@ -1926,7 +1926,7 @@ ObjCProtocolDecl::getObjCRuntimeNameAsString() const { void ObjCCategoryDecl::anchor() {} ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, - SourceLocation ClassNameLoc, + SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, ObjCTypeParamList *typeParamList, @@ -2008,7 +2008,7 @@ ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, atStartLoc, CategoryNameLoc); } -ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, +ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, SourceLocation(), SourceLocation(), diff --git a/lib/AST/DeclPrinter.cpp b/lib/AST/DeclPrinter.cpp index d3d9c23cca6e8..09e22f19f87a1 100644 --- a/lib/AST/DeclPrinter.cpp +++ b/lib/AST/DeclPrinter.cpp @@ -44,7 +44,7 @@ namespace { /// /// \param Quals The Objective-C declaration qualifiers. /// \param T The type to print. - void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals, + void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals, QualType T); void PrintObjCTypeParams(ObjCTypeParamList *Params); @@ -196,7 +196,7 @@ LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const { const DeclContext *DC = this; while (!DC->isTranslationUnit()) DC = DC->getParent(); - + ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext(); DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), Ctx, 0); Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false); @@ -482,7 +482,7 @@ void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) { if (!Policy.SuppressSpecifiers) { Out << "typedef "; - + if (D->isModulePrivate()) Out << "__module_private__ "; } @@ -641,7 +641,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { } Proto += ")"; - + if (FT) { if (FT->isConst()) Proto += " const"; @@ -666,7 +666,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { Proto += " throw("; if (FT->getExceptionSpecType() == EST_MSAny) Proto += "..."; - else + else for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) { if (I) Proto += ", "; @@ -1141,8 +1141,8 @@ void DeclPrinter::VisitClassTemplatePartialSpecializationDecl( // Objective-C declarations //---------------------------------------------------------------------------- -void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, - Decl::ObjCDeclQualifier Quals, +void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, + Decl::ObjCDeclQualifier Quals, QualType T) { Out << '('; if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In) @@ -1161,7 +1161,7 @@ void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, if (auto nullability = AttributedType::stripOuterNullability(T)) Out << getNullabilitySpelling(*nullability, true) << ' '; } - + Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy); Out << ')'; } @@ -1216,7 +1216,7 @@ void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { if (lastPos != 0) Out << " "; Out << name.substr(lastPos, pos - lastPos) << ':'; - PrintObjCMethodType(OMD->getASTContext(), + PrintObjCMethodType(OMD->getASTContext(), PI->getObjCDeclQualifier(), PI->getType()); Out << *PI; @@ -1228,7 +1228,7 @@ void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { if (OMD->isVariadic()) Out << ", ..."; - + prettyPrintAttributes(OMD); if (OMD->getBody() && !Policy.TerseOutput) { @@ -1248,7 +1248,7 @@ void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) { Out << "@implementation " << I << " : " << *SID; else Out << "@implementation " << I; - + if (OID->ivar_size() > 0) { Out << "{\n"; eolnOut = true; @@ -1290,7 +1290,7 @@ void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { if (auto TypeParams = OID->getTypeParamListAsWritten()) { PrintObjCTypeParams(TypeParams); } - + if (SID) Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy); @@ -1369,7 +1369,7 @@ void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) { Indentation -= Policy.Indentation; Out << "}\n"; } - + VisitDeclContext(PID, false); Out << "@end"; @@ -1448,7 +1448,7 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { Out << (first ? ' ' : ',') << "atomic"; first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nullability) { if (auto nullability = AttributedType::stripOuterNullability(T)) { diff --git a/lib/AST/DeclTemplate.cpp b/lib/AST/DeclTemplate.cpp index 8854f7879ac69..848427e7f9d9e 100644 --- a/lib/AST/DeclTemplate.cpp +++ b/lib/AST/DeclTemplate.cpp @@ -117,7 +117,7 @@ unsigned TemplateParameterList::getMinRequiredArguments() const { unsigned TemplateParameterList::getDepth() const { if (size() == 0) return 0; - + const NamedDecl *FirstParm = getParam(0); if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(FirstParm)) return TTP->getDepth(); @@ -338,13 +338,13 @@ llvm::FoldingSetVector<ClassTemplateSpecializationDecl> & ClassTemplateDecl::getSpecializations() const { LoadLazySpecializations(); return getCommonPtr()->Specializations; -} +} llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> & ClassTemplateDecl::getPartialSpecializations() { LoadLazySpecializations(); return getCommonPtr()->PartialSpecializations; -} +} RedeclarableTemplateDecl::CommonBase * ClassTemplateDecl::newCommon(ASTContext &C) const { @@ -427,11 +427,11 @@ ClassTemplateDecl::getInjectedClassNameSpecialization() { return CommonPtr->InjectedClassNameType; // C++0x [temp.dep.type]p2: - // The template argument list of a primary template is a template argument + // The template argument list of a primary template is a template argument // list in which the nth template argument has the value of the nth template - // parameter of the class template. If the nth template parameter is a - // template parameter pack (14.5.3), the nth template argument is a pack - // expansion (14.5.3) whose pattern is the name of the template parameter + // parameter of the class template. If the nth template parameter is a + // template parameter pack (14.5.3), the nth template argument is a pack + // expansion (14.5.3) whose pattern is the name of the template parameter // pack. ASTContext &Context = getASTContext(); TemplateParameterList *Params = getTemplateParameters(); diff --git a/lib/AST/DeclarationName.cpp b/lib/AST/DeclarationName.cpp index 31bae93c3cb56..9866d92f61eb4 100644 --- a/lib/AST/DeclarationName.cpp +++ b/lib/AST/DeclarationName.cpp @@ -114,14 +114,14 @@ static int compareInt(unsigned A, unsigned B) { int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) { if (LHS.getNameKind() != RHS.getNameKind()) return (LHS.getNameKind() < RHS.getNameKind() ? -1 : 1); - + switch (LHS.getNameKind()) { case DeclarationName::Identifier: { IdentifierInfo *LII = LHS.getAsIdentifierInfo(); IdentifierInfo *RII = RHS.getAsIdentifierInfo(); if (!LII) return RII ? -1 : 0; if (!RII) return 1; - + return LII->getName().compare(RII->getName()); } @@ -148,7 +148,7 @@ int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) { return compareInt(LN, RN); } - + case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: @@ -171,7 +171,7 @@ int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) { case DeclarationName::CXXLiteralOperatorName: return LHS.getCXXLiteralIdentifier()->getName().compare( RHS.getCXXLiteralIdentifier()->getName()); - + case DeclarationName::CXXUsingDirective: return 0; } @@ -565,7 +565,7 @@ DeclarationNameTable::getCXXLiteralOperatorName(IdentifierInfo *II) { if (CXXLiteralOperatorIdName *Name = LiteralNames->FindNodeOrInsertPos(ID, InsertPos)) return DeclarationName (Name); - + CXXLiteralOperatorIdName *LiteralName = new (Ctx) CXXLiteralOperatorIdName; LiteralName->ExtraKindOrNumArgs = DeclarationNameExtra::CXXLiteralOperator; LiteralName->ID = II; @@ -636,13 +636,13 @@ bool DeclarationNameInfo::isInstantiationDependent() const { case DeclarationName::CXXUsingDirective: case DeclarationName::CXXDeductionGuideName: return false; - + case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: if (TypeSourceInfo *TInfo = LocInfo.NamedType.TInfo) return TInfo->getType()->isInstantiationDependentType(); - + return Name.getCXXNameType()->isInstantiationDependentType(); } llvm_unreachable("All name kinds handled."); @@ -689,7 +689,7 @@ void DeclarationNameInfo::printName(raw_ostream &OS) const { llvm_unreachable("Unexpected declaration name kind"); } -SourceLocation DeclarationNameInfo::getEndLoc() const { +SourceLocation DeclarationNameInfo::getEndLocPrivate() const { switch (Name.getNameKind()) { case DeclarationName::Identifier: case DeclarationName::CXXDeductionGuideName: diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp index 193efa4e097d9..7556c76c38bda 100644 --- a/lib/AST/Expr.cpp +++ b/lib/AST/Expr.cpp @@ -137,9 +137,9 @@ bool Expr::isKnownToHaveBooleanValue() const { // If this value has _Bool type, it is obvious 0/1. if (E->getType()->isBooleanType()) return true; - // If this is a non-scalar-integer type, we don't care enough to try. + // If this is a non-scalar-integer type, we don't care enough to try. if (!E->getType()->isIntegralOrEnumerationType()) return false; - + if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { switch (UO->getOpcode()) { case UO_Plus: @@ -150,12 +150,12 @@ bool Expr::isKnownToHaveBooleanValue() const { return false; } } - + // Only look through implicit casts. If the user writes // '(int) (a && b)' treat it as an arbitrary int. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) return CE->getSubExpr()->isKnownToHaveBooleanValue(); - + if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { switch (BO->getOpcode()) { default: return false; @@ -168,24 +168,24 @@ bool Expr::isKnownToHaveBooleanValue() const { case BO_LAnd: // AND operator. case BO_LOr: // Logical OR operator. return true; - + case BO_And: // Bitwise AND operator. case BO_Xor: // Bitwise XOR operator. case BO_Or: // Bitwise OR operator. // Handle things like (x==2)|(y==12). return BO->getLHS()->isKnownToHaveBooleanValue() && BO->getRHS()->isKnownToHaveBooleanValue(); - + case BO_Comma: case BO_Assign: return BO->getRHS()->isKnownToHaveBooleanValue(); } } - + if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) return CO->getTrueExpr()->isKnownToHaveBooleanValue() && CO->getFalseExpr()->isKnownToHaveBooleanValue(); - + return false; } @@ -230,7 +230,7 @@ SourceLocation Expr::getExprLoc() const { // Primary Expressions. //===----------------------------------------------------------------------===// -/// Compute the type-, value-, and instantiation-dependence of a +/// Compute the type-, value-, and instantiation-dependence of a /// declaration reference /// based on the declaration being referenced. static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, @@ -259,9 +259,9 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, } else if (T->isInstantiationDependentType()) { InstantiationDependent = true; } - + // (TD) - a conversion-function-id that specifies a dependent type - if (D->getDeclName().getNameKind() + if (D->getDeclName().getNameKind() == DeclarationName::CXXConversionFunctionName) { QualType T = D->getDeclName().getCXXNameType(); if (T->isDependentType()) { @@ -270,18 +270,18 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, InstantiationDependent = true; return; } - + if (T->isInstantiationDependentType()) InstantiationDependent = true; } - + // (VD) - the name of a non-type template parameter, if (isa<NonTypeTemplateParmDecl>(D)) { ValueDependent = true; InstantiationDependent = true; return; } - + // (VD) - a constant with integral or enumeration type and is // initialized with an expression that is value-dependent. // (VD) - a constant with literal type and is initialized with an @@ -302,10 +302,10 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, } } - // (VD) - FIXME: Missing from the standard: - // - a member function or a static data member of the current + // (VD) - FIXME: Missing from the standard: + // - a member function or a static data member of the current // instantiation - if (Var->isStaticDataMember() && + if (Var->isStaticDataMember() && Var->getDeclContext()->isDependentContext()) { ValueDependent = true; InstantiationDependent = true; @@ -313,12 +313,12 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, if (TInfo->getType()->isIncompleteArrayType()) TypeDependent = true; } - + return; } - - // (VD) - FIXME: Missing from the standard: - // - a member function or a static data member of the current + + // (VD) - FIXME: Missing from the standard: + // - a member function or a static data member of the current // instantiation if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) { ValueDependent = true; @@ -625,7 +625,7 @@ std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { llvm::raw_string_ostream TOut(TemplateParams); for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend(); I != E; ++I) { - const TemplateParameterList *Params + const TemplateParameterList *Params = (*I)->getSpecializedTemplate()->getTemplateParameters(); const TemplateArgumentList &Args = (*I)->getTemplateArgs(); assert(Params->size() == Args.size()); @@ -638,10 +638,10 @@ std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { } } - FunctionTemplateSpecializationInfo *FSI + FunctionTemplateSpecializationInfo *FSI = FD->getTemplateSpecializationInfo(); if (FSI && !FSI->isExplicitSpecialization()) { - const TemplateParameterList* Params + const TemplateParameterList* Params = FSI->getTemplate()->getTemplateParameters(); const TemplateArgumentList* Args = FSI->TemplateArguments; assert(Params->size() == Args->size()); @@ -942,7 +942,7 @@ void StringLiteral::outputString(raw_ostream &OS) const { // Convert UTF-16 surrogate pairs back to codepoints before rendering. // Leave invalid surrogates alone; we'll use \x for those. - if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && + if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && Char <= 0xdbff) { uint32_t Trail = getCodeUnit(I + 1); if (Trail >= 0xdc00 && Trail <= 0xdfff) { @@ -1025,7 +1025,7 @@ void StringLiteral::setString(const ASTContext &C, StringRef Str, // code unit size and endianness for the type of string. this->Kind = Kind; this->IsPascal = IsPascal; - + CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind); assert((Str.size()%CharByteWidth == 0) && "size of data must be multiple of CharByteWidth"); @@ -1092,7 +1092,7 @@ StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, while (1) { assert(TokNo < getNumConcatenated() && "Invalid byte number!"); SourceLocation StrTokLoc = getStrTokenLoc(TokNo); - + // Get the spelling of the string so that we can get the data that makes up // the string literal, not the identifier for the macro it is potentially // expanded through. @@ -1112,17 +1112,17 @@ StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, } const char *StrData = Buffer.data()+LocInfo.second; - + // Create a lexer starting at the beginning of this token. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features, Buffer.begin(), StrData, Buffer.end()); Token TheTok; TheLexer.LexFromRawLexer(TheTok); - + // Use the StringLiteralParser to compute the length of the string in bytes. StringLiteralParser SLP(TheTok, SM, Features, Target); unsigned TokNumBytes = SLP.GetStringLength(); - + // If the byte is in this token, return the location of the byte. if (ByteNo < TokNumBytes || (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) { @@ -1258,12 +1258,12 @@ Decl *CallExpr::getCalleeDecl() { Decl *Expr::getReferencedDeclOfCallee() { Expr *CEE = IgnoreParenImpCasts(); - + while (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) { CEE = NTTP->getReplacement()->IgnoreParenCasts(); } - + // If we're calling a dereference, look at the pointer instead. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) { if (BO->isPtrMemOp()) @@ -1379,7 +1379,7 @@ SourceLocation CallExpr::getLocEnd() const { OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, - TypeSourceInfo *tsi, + TypeSourceInfo *tsi, ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, SourceLocation RParenLoc) { @@ -1402,17 +1402,17 @@ OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type, ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, SourceLocation RParenLoc) : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary, - /*TypeDependent=*/false, + /*TypeDependent=*/false, /*ValueDependent=*/tsi->getType()->isDependentType(), tsi->getType()->isInstantiationDependentType(), tsi->getType()->containsUnexpandedParameterPack()), - OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), + OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), NumComps(comps.size()), NumExprs(exprs.size()) { for (unsigned i = 0; i != comps.size(); ++i) { setComponent(i, comps[i]); } - + for (unsigned i = 0; i != exprs.size(); ++i) { if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent()) ExprBits.ValueDependent = true; @@ -1427,7 +1427,7 @@ IdentifierInfo *OffsetOfNode::getFieldName() const { assert(getKind() == Field || getKind() == Identifier); if (getKind() == Field) return getField()->getIdentifier(); - + return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); } @@ -1497,11 +1497,11 @@ MemberExpr *MemberExpr::Create( E->setValueDependent(true); E->setTypeDependent(true); E->setInstantiationDependent(true); - } - else if (QualifierLoc && - QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) + } + else if (QualifierLoc && + QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) E->setInstantiationDependent(true); - + E->HasQualifierOrFoundDecl = true; MemberExprNameQualifier *NQ = @@ -1582,9 +1582,9 @@ bool CastExpr::CastConsistency() const { // Otherwise, we should only have block and ObjC pointer casts // here if they stay within the type kind. if (!getType()->isPointerType()) { - assert(getType()->isObjCObjectPointerType() == + assert(getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()); - assert(getType()->isBlockPointerType() == + assert(getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()); } goto CheckNoBasePath; @@ -1708,11 +1708,11 @@ Expr *CastExpr::getSubExprAsWritten() { if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr)) SubExpr = MCE->getImplicitObjectArgument(); } - + // If the subexpression we're left with is an implicit cast, look // through that, too. - } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); - + } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); + return const_cast<Expr*>(SubExpr); } @@ -1734,6 +1734,21 @@ NamedDecl *CastExpr::getConversionFunction() const { return nullptr; } +CastExpr::BasePathSizeTy *CastExpr::BasePathSize() { + assert(!path_empty()); + switch (getStmtClass()) { +#define ABSTRACT_STMT(x) +#define CASTEXPR(Type, Base) \ + case Stmt::Type##Class: \ + return static_cast<Type *>(this) \ + ->getTrailingObjects<CastExpr::BasePathSizeTy>(); +#define STMT(Type, Base) +#include "clang/AST/StmtNodes.inc" + default: + llvm_unreachable("non-cast expressions not possible here"); + } +} + CXXBaseSpecifier **CastExpr::path_buffer() { switch (getStmtClass()) { #define ABSTRACT_STMT(x) @@ -1772,7 +1787,9 @@ ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, const CXXCastPath *BasePath, ExprValueKind VK) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); ImplicitCastExpr *E = new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK); if (PathSize) @@ -1783,7 +1800,9 @@ ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize); } @@ -1794,7 +1813,9 @@ CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); CStyleCastExpr *E = new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R); if (PathSize) @@ -1805,7 +1826,9 @@ CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize); } @@ -1933,7 +1956,7 @@ InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc, if (initExprs[I]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; } - + InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end()); } @@ -2023,12 +2046,12 @@ SourceLocation InitListExpr::getLocStart() const { if (Beg.isInvalid()) { // Find the first non-null initializer. for (InitExprsTy::const_iterator I = InitExprs.begin(), - E = InitExprs.end(); + E = InitExprs.end(); I != E; ++I) { if (Stmt *S = *I) { Beg = S->getLocStart(); break; - } + } } } return Beg; @@ -2079,7 +2102,7 @@ Stmt *BlockExpr::getBody() { /// be warned about if the result is unused. If so, fill in Loc and Ranges /// with location to warn on and the source range[s] to report with the /// warning. -bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, +bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const { // Don't warn if the expr is type dependent. The type could end up @@ -2436,7 +2459,7 @@ bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); case DeclRefExprClass: { const Decl *D = cast<DeclRefExpr>(E)->getDecl(); - + if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (VD->hasGlobalStorage()) return true; @@ -2526,7 +2549,7 @@ Expr *Expr::IgnoreParenCasts() { E = P->getSubExpr(); continue; } - if (MaterializeTemporaryExpr *Materialize + if (MaterializeTemporaryExpr *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) { E = Materialize->GetTemporaryExpr(); continue; @@ -2535,7 +2558,7 @@ Expr *Expr::IgnoreParenCasts() { = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { E = NTTP->getReplacement(); continue; - } + } return E; } } @@ -2574,7 +2597,7 @@ Expr *Expr::IgnoreParenLValueCasts() { E = P->getSubExpr(); continue; } - } else if (MaterializeTemporaryExpr *Materialize + } else if (MaterializeTemporaryExpr *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) { E = Materialize->GetTemporaryExpr(); continue; @@ -2613,7 +2636,7 @@ Expr *Expr::IgnoreParenImpCasts() { E = P->getSubExpr(); continue; } - if (MaterializeTemporaryExpr *Materialize + if (MaterializeTemporaryExpr *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) { E = Materialize->GetTemporaryExpr(); continue; @@ -2668,7 +2691,7 @@ Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { E = NTTP->getReplacement(); continue; } - + return E; } } @@ -2680,7 +2703,7 @@ bool Expr::isDefaultArgument() const { while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) E = ICE->getSubExprAsWritten(); - + return isa<CXXDefaultArgExpr>(E); } @@ -2756,43 +2779,43 @@ bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { bool Expr::isImplicitCXXThis() const { const Expr *E = this; - + // Strip away parentheses and casts we don't care about. while (true) { if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) { E = Paren->getSubExpr(); continue; } - + if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { if (ICE->getCastKind() == CK_NoOp || ICE->getCastKind() == CK_LValueToRValue || - ICE->getCastKind() == CK_DerivedToBase || + ICE->getCastKind() == CK_DerivedToBase || ICE->getCastKind() == CK_UncheckedDerivedToBase) { E = ICE->getSubExpr(); continue; } } - + if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) { if (UnOp->getOpcode() == UO_Extension) { E = UnOp->getSubExpr(); continue; } } - + if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) { E = M->GetTemporaryExpr(); continue; } - + break; } - + if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E)) return This->isImplicit(); - + return false; } @@ -2978,7 +3001,7 @@ bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const { if (!FD || (FD->getBuiltinID() != Builtin::BI__assume && FD->getBuiltinID() != Builtin::BI__builtin_assume)) return false; - + const Expr* Arg = getArg(0); bool ArgVal; return !Arg->isValueDependent() && @@ -3289,11 +3312,11 @@ namespace { typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited; bool NonTrivial; - + public: explicit NonTrivialCallFinder(const ASTContext &Context) : Inherited(Context), NonTrivial(false) { } - + bool hasNonTrivialCall() const { return NonTrivial; } void VisitCallExpr(const CallExpr *E) { @@ -3305,7 +3328,7 @@ namespace { return; } } - + NonTrivial = true; } @@ -3315,7 +3338,7 @@ namespace { Inherited::VisitStmt(E); return; } - + NonTrivial = true; } @@ -3324,7 +3347,7 @@ namespace { Inherited::VisitStmt(E); return; } - + NonTrivial = true; } }; @@ -3333,10 +3356,10 @@ namespace { bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const { NonTrivialCallFinder Finder(Ctx); Finder.Visit(this); - return Finder.hasNonTrivialCall(); + return Finder.hasNonTrivialCall(); } -/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null +/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null /// pointer constant or not, as well as the specific kind of constant detected. /// Null pointer constants can be integer constant expressions with the /// value zero, casts of zero to void*, nullptr (C++0X), or __null @@ -3354,7 +3377,7 @@ Expr::isNullPointerConstant(ASTContext &Ctx, return NPCK_ZeroExpression; else return NPCK_NotNull; - + case NPC_ValueDependentIsNotNull: return NPCK_NotNull; } @@ -3410,7 +3433,7 @@ Expr::isNullPointerConstant(ASTContext &Ctx, } else if (isa<GNUNullExpr>(this)) { // The GNU __null extension is always a null pointer constant. return NPCK_GNUNull; - } else if (const MaterializeTemporaryExpr *M + } else if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(this)) { return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC); } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) { @@ -3431,7 +3454,7 @@ Expr::isNullPointerConstant(ASTContext &Ctx, return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); } // This expression must be an integer type. - if (!getType()->isIntegerType() || + if (!getType()->isIntegerType() || (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType())) return NPCK_NotNull; @@ -3549,7 +3572,7 @@ FieldDecl *Expr::getSourceBitField() { bool Expr::refersToVectorElement() const { // FIXME: Why do we not just look at the ObjectKind here? const Expr *E = this->IgnoreParens(); - + while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { if (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp) @@ -3557,7 +3580,7 @@ bool Expr::refersToVectorElement() const { else break; } - + if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) return ASE->getBase()->getType()->isVectorType(); @@ -3652,7 +3675,7 @@ void ExtVectorElementExpr::getEncodedElementAccess( ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, SourceLocation BLoc, - SourceLocation RP) + SourceLocation RP) : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary, Type->isDependentType(), Type->isDependentType(), Type->isInstantiationDependentType(), @@ -3791,11 +3814,11 @@ DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty, End->isTypeDependent() || End->isValueDependent()) { ExprBits.TypeDependent = ExprBits.ValueDependent = true; ExprBits.InstantiationDependent = true; - } else if (Start->isInstantiationDependent() || + } else if (Start->isInstantiationDependent() || End->isInstantiationDependent()) { ExprBits.InstantiationDependent = true; } - + // Propagate unexpanded parameter packs. if (Start->containsUnexpandedParameterPack() || End->containsUnexpandedParameterPack()) diff --git a/lib/AST/ExprCXX.cpp b/lib/AST/ExprCXX.cpp index 3a204c244f683..93d68ec8e0b28 100644 --- a/lib/AST/ExprCXX.cpp +++ b/lib/AST/ExprCXX.cpp @@ -120,7 +120,7 @@ CXXNewExpr::CXXNewExpr(const ASTContext &C, bool globalNew, if (Array) { if (arraySize->isInstantiationDependent()) ExprBits.InstantiationDependent = true; - + if (arraySize->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; @@ -210,8 +210,8 @@ PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info) CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context, Expr *Base, bool isArrow, SourceLocation OperatorLoc, - NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, - SourceLocation ColonColonLoc, SourceLocation TildeLoc, + NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, + SourceLocation ColonColonLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType) : Expr(CXXPseudoDestructorExprClass, Context.BoundMemberTy, @@ -230,10 +230,10 @@ CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context, ->isInstantiationDependentType())), // ContainsUnexpandedParameterPack (Base->containsUnexpandedParameterPack() || - (QualifierLoc && + (QualifierLoc && QualifierLoc.getNestedNameSpecifier() ->containsUnexpandedParameterPack()) || - (ScopeType && + (ScopeType && ScopeType->getType()->containsUnexpandedParameterPack()) || (DestroyedType.getTypeSourceInfo() && DestroyedType.getTypeSourceInfo()->getType() @@ -246,7 +246,7 @@ CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context, QualType CXXPseudoDestructorExpr::getDestroyedType() const { if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo()) return TInfo->getType(); - + return QualType(); } @@ -300,7 +300,7 @@ OverloadExpr::OverloadExpr(StmtClass K, const ASTContext &C, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, - UnresolvedSetIterator Begin, + UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent, @@ -393,13 +393,13 @@ DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(QualType T, : Expr(DependentScopeDeclRefExprClass, T, VK_LValue, OK_Ordinary, true, true, (NameInfo.isInstantiationDependent() || - (QualifierLoc && + (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())), (NameInfo.containsUnexpandedParameterPack() || - (QualifierLoc && + (QualifierLoc && QualifierLoc.getNestedNameSpecifier() ->containsUnexpandedParameterPack()))), - QualifierLoc(QualifierLoc), NameInfo(NameInfo), + QualifierLoc(QualifierLoc), NameInfo(NameInfo), HasTemplateKWAndArgsInfo(Args != nullptr || TemplateKWLoc.isValid()) { if (Args) { @@ -555,11 +555,13 @@ CXXStaticCastExpr *CXXStaticCastExpr::Create(const ASTContext &C, QualType T, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, - SourceLocation L, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); @@ -571,7 +573,9 @@ CXXStaticCastExpr *CXXStaticCastExpr::Create(const ASTContext &C, QualType T, CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize); } @@ -580,11 +584,13 @@ CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, - SourceLocation L, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); @@ -596,7 +602,9 @@ CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T, CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize); } @@ -637,11 +645,13 @@ CXXReinterpretCastExpr * CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, - TypeSourceInfo *WrittenTy, SourceLocation L, + TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); @@ -653,14 +663,16 @@ CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T, CXXReinterpretCastExpr * CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize); } CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, Expr *Op, TypeSourceInfo *WrittenTy, - SourceLocation L, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets); @@ -676,7 +688,9 @@ CXXFunctionalCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, const CXXCastPath *BasePath, SourceLocation L, SourceLocation R) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, L, R); if (PathSize) @@ -687,7 +701,9 @@ CXXFunctionalCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, CXXFunctionalCastExpr * CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXFunctionalCastExpr(EmptyShell(), PathSize); } @@ -829,7 +845,7 @@ CXXConstructExpr::CXXConstructExpr(const ASTContext &C, StmtClass SC, ZeroInitialization(ZeroInitialization), ConstructKind(ConstructKind) { if (NumArgs) { this->Args = new (C) Stmt*[Args.size()]; - + for (unsigned i = 0; i != Args.size(); ++i) { assert(Args[i] && "NULL argument in CXXConstructExpr"); @@ -839,7 +855,7 @@ CXXConstructExpr::CXXConstructExpr(const ASTContext &C, StmtClass SC, ExprBits.InstantiationDependent = true; if (Args[i]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; - + this->Args[i] = Args[i]; } } @@ -852,7 +868,7 @@ LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit, unsigned Bits = 0; if (Implicit) Bits |= Capture_Implicit; - + switch (Kind) { case LCK_StarThis: Bits |= Capture_ByCopy; @@ -901,9 +917,9 @@ LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange, assert(CaptureInits.size() == Captures.size() && "Wrong number of arguments"); CXXRecordDecl *Class = getLambdaClass(); CXXRecordDecl::LambdaDefinitionData &Data = Class->getLambdaData(); - + // FIXME: Propagate "has unexpanded parameter pack" bit. - + // Copy captures. const ASTContext &Context = Class->getASTContext(); Data.NumCaptures = NumCaptures; @@ -914,15 +930,15 @@ LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange, for (unsigned I = 0, N = Captures.size(); I != N; ++I) { if (Captures[I].isExplicit()) ++Data.NumExplicitCaptures; - + *ToCapture++ = Captures[I]; } - + // Copy initialization expressions for the non-static data members. Stmt **Stored = getStoredStmts(); for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I) *Stored++ = CaptureInits[I]; - + // Copy the body of the lambda. *Stored++ = getCallOperator()->getBody(); } @@ -1001,7 +1017,7 @@ CXXRecordDecl *LambdaExpr::getLambdaClass() const { CXXMethodDecl *LambdaExpr::getCallOperator() const { CXXRecordDecl *Record = getLambdaClass(); - return Record->getLambdaCallOperator(); + return Record->getLambdaCallOperator(); } TemplateParameterList *LambdaExpr::getTemplateParameterList() const { @@ -1188,7 +1204,7 @@ CXXDependentScopeMemberExpr::CreateEmpty(const ASTContext &C, bool CXXDependentScopeMemberExpr::isImplicitAccess() const { if (!Base) return true; - + return cast<Expr>(Base)->isImplicitCXXThis(); } @@ -1218,7 +1234,7 @@ UnresolvedMemberExpr::UnresolvedMemberExpr(const ASTContext &C, SourceLocation TemplateKWLoc, const DeclarationNameInfo &MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, - UnresolvedSetIterator Begin, + UnresolvedSetIterator Begin, UnresolvedSetIterator End) : OverloadExpr( UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc, @@ -1241,7 +1257,7 @@ UnresolvedMemberExpr::UnresolvedMemberExpr(const ASTContext &C, bool UnresolvedMemberExpr::isImplicitAccess() const { if (!Base) return true; - + return cast<Expr>(Base)->isImplicitCXXThis(); } @@ -1300,11 +1316,11 @@ CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() const { assert(PT && "base of arrow member access is not pointer"); BaseType = PT->getPointeeType(); } - + Record = BaseType->getAsCXXRecordDecl(); assert(Record && "base of member expression does not name record"); } - + return Record; } @@ -1328,7 +1344,7 @@ SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context, } SubstNonTypeTemplateParmPackExpr:: -SubstNonTypeTemplateParmPackExpr(QualType T, +SubstNonTypeTemplateParmPackExpr(QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param, SourceLocation NameLoc, @@ -1411,13 +1427,13 @@ TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind, setInstantiationDependent(true); if (Args[I]->getType()->containsUnexpandedParameterPack()) setContainsUnexpandedParameterPack(true); - + ToArgs[I] = Args[I]; } } TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T, - SourceLocation Loc, + SourceLocation Loc, TypeTrait Kind, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc, diff --git a/lib/AST/ExprClassification.cpp b/lib/AST/ExprClassification.cpp index c5b3b361a0a59..e50dd9c79d11e 100644 --- a/lib/AST/ExprClassification.cpp +++ b/lib/AST/ExprClassification.cpp @@ -345,9 +345,9 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { return ClassifyUnnamed(Ctx, cast<ExplicitCastExpr>(E)->getTypeAsWritten()); case Expr::CXXUnresolvedConstructExprClass: - return ClassifyUnnamed(Ctx, + return ClassifyUnnamed(Ctx, cast<CXXUnresolvedConstructExpr>(E)->getTypeAsWritten()); - + case Expr::BinaryConditionalOperatorClass: { if (!Lang.CPlusPlus) return Cl::CL_PRValue; const auto *co = cast<BinaryConditionalOperator>(E); @@ -370,7 +370,7 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind; } return Cl::CL_PRValue; - + // Some C++ expressions are always class temporaries. case Expr::CXXConstructExprClass: case Expr::CXXInheritedCtorInitExprClass: @@ -400,7 +400,7 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { case Expr::MaterializeTemporaryExprClass: return cast<MaterializeTemporaryExpr>(E)->isBoundToLvalueReference() - ? Cl::CL_LValue + ? Cl::CL_LValue : Cl::CL_XValue; case Expr::InitListExprClass: @@ -546,7 +546,7 @@ static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) { if (E->getOpcode() == BO_PtrMemD) return (E->getType()->isFunctionType() || E->hasPlaceholderType(BuiltinType::BoundMember)) - ? Cl::CL_MemberFunction + ? Cl::CL_MemberFunction : ClassifyInternal(Ctx, E->getLHS()); // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its @@ -554,7 +554,7 @@ static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) { if (E->getOpcode() == BO_PtrMemI) return (E->getType()->isFunctionType() || E->hasPlaceholderType(BuiltinType::BoundMember)) - ? Cl::CL_MemberFunction + ? Cl::CL_MemberFunction : Cl::CL_LValue; // All other binary operations are prvalues. diff --git a/lib/AST/ExprConstant.cpp b/lib/AST/ExprConstant.cpp index e69914f25da2b..44cf75dbd25b2 100644 --- a/lib/AST/ExprConstant.cpp +++ b/lib/AST/ExprConstant.cpp @@ -319,6 +319,25 @@ namespace { return false; } + /// Get the range of valid index adjustments in the form + /// {maximum value that can be subtracted from this pointer, + /// maximum value that can be added to this pointer} + std::pair<uint64_t, uint64_t> validIndexAdjustments() { + if (Invalid || isMostDerivedAnUnsizedArray()) + return {0, 0}; + + // [expr.add]p4: For the purposes of these operators, a pointer to a + // nonarray object behaves the same as a pointer to the first element of + // an array of length one with the type of the object as its element type. + bool IsArray = MostDerivedPathLength == Entries.size() && + MostDerivedIsArrayElement; + uint64_t ArrayIndex = + IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; + uint64_t ArraySize = + IsArray ? getMostDerivedArraySize() : (uint64_t)1; + return {ArrayIndex, ArraySize - ArrayIndex}; + } + /// Check that this refers to a valid subobject. bool isValidSubobject() const { if (Invalid) @@ -329,6 +348,13 @@ namespace { /// relevant diagnostic and set the designator as invalid. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); + /// Get the type of the designated object. + QualType getType(ASTContext &Ctx) const { + return MostDerivedPathLength == Entries.size() + ? MostDerivedType + : Ctx.getRecordType(getAsBaseClass(Entries.back())); + } + /// Update this designator to refer to the first element within this array. void addArrayUnchecked(const ConstantArrayType *CAT) { PathEntry Entry; @@ -572,7 +598,7 @@ namespace { // FIXME: Force the precision of the source value down so we don't // print digits which are usually useless (we don't really care here if // we truncate a digit by accident in edge cases). Ideally, - // APFloat::toString would automatically print the shortest + // APFloat::toString would automatically print the shortest // representation which rounds to the correct value, but it's a bit // tricky to implement. unsigned precision = @@ -826,7 +852,7 @@ namespace { private: OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, unsigned ExtraNotes, bool IsCCEDiag) { - + if (EvalStatus.Diag) { // If we have a prior diagnostic, it will be noting that the expression // isn't a constant expression. This diagnostic is more important, @@ -880,7 +906,7 @@ namespace { unsigned ExtraNotes = 0) { return Diag(Loc, DiagId, ExtraNotes, false); } - + OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes = 0) { @@ -1706,6 +1732,54 @@ static bool IsGlobalLValue(APValue::LValueBase B) { } } +static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { + return LVal.Base.dyn_cast<const ValueDecl*>(); +} + +static bool IsLiteralLValue(const LValue &Value) { + if (Value.getLValueCallIndex()) + return false; + const Expr *E = Value.Base.dyn_cast<const Expr*>(); + return E && !isa<MaterializeTemporaryExpr>(E); +} + +static bool IsWeakLValue(const LValue &Value) { + const ValueDecl *Decl = GetLValueBaseDecl(Value); + return Decl && Decl->isWeak(); +} + +static bool isZeroSized(const LValue &Value) { + const ValueDecl *Decl = GetLValueBaseDecl(Value); + if (Decl && isa<VarDecl>(Decl)) { + QualType Ty = Decl->getType(); + if (Ty->isArrayType()) + return Ty->isIncompleteType() || + Decl->getASTContext().getTypeSize(Ty) == 0; + } + return false; +} + +static bool HasSameBase(const LValue &A, const LValue &B) { + if (!A.getLValueBase()) + return !B.getLValueBase(); + if (!B.getLValueBase()) + return false; + + if (A.getLValueBase().getOpaqueValue() != + B.getLValueBase().getOpaqueValue()) { + const Decl *ADecl = GetLValueBaseDecl(A); + if (!ADecl) + return false; + const Decl *BDecl = GetLValueBaseDecl(B); + if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) + return false; + } + + return IsGlobalLValue(A.getLValueBase()) || + (A.getLValueCallIndex() == B.getLValueCallIndex() && + A.getLValueVersion() == B.getLValueVersion()); +} + static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { assert(Base && "no location for a null lvalue"); const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); @@ -1917,33 +1991,6 @@ CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, return true; } -static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { - return LVal.Base.dyn_cast<const ValueDecl*>(); -} - -static bool IsLiteralLValue(const LValue &Value) { - if (Value.getLValueCallIndex()) - return false; - const Expr *E = Value.Base.dyn_cast<const Expr*>(); - return E && !isa<MaterializeTemporaryExpr>(E); -} - -static bool IsWeakLValue(const LValue &Value) { - const ValueDecl *Decl = GetLValueBaseDecl(Value); - return Decl && Decl->isWeak(); -} - -static bool isZeroSized(const LValue &Value) { - const ValueDecl *Decl = GetLValueBaseDecl(Value); - if (Decl && isa<VarDecl>(Decl)) { - QualType Ty = Decl->getType(); - if (Ty->isArrayType()) - return Ty->isIncompleteType() || - Decl->getASTContext().getTypeSize(Ty) == 0; - } - return false; -} - static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { // A null base expression indicates a null pointer. These are always // evaluatable, and they are false unless the offset is zero. @@ -4286,13 +4333,13 @@ static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, if (Info.getLangOpts().CPlusPlus11) { const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; - + // If this function is not constexpr because it is an inherited // non-constexpr constructor, diagnose that directly. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); if (CD && CD->isInheritingConstructor()) { auto *Inherited = CD->getInheritedConstructor().getConstructor(); - if (!Inherited->isConstexpr()) + if (!Inherited->isConstexpr()) DiagDecl = CD = Inherited; } @@ -4853,7 +4900,7 @@ public: return false; This = &ThisVal; Args = Args.slice(1); - } else if (MD && MD->isLambdaStaticInvoker()) { + } else if (MD && MD->isLambdaStaticInvoker()) { // Map the static invoker for the lambda back to the call operator. // Conveniently, we don't have to slice out the 'this' argument (as is // being done for the non-static case), since a static member function @@ -4888,7 +4935,7 @@ public: FD = LambdaCallOp; } - + } else return Error(E); @@ -5732,7 +5779,7 @@ public: // Update 'Result' to refer to the data member/field of the closure object // that represents the '*this' capture. if (!HandleLValueMember(Info, E, Result, - Info.CurrentCall->LambdaThisCaptureField)) + Info.CurrentCall->LambdaThisCaptureField)) return false; // If we captured '*this' by reference, replace the field with its referent. if (Info.CurrentCall->LambdaThisCaptureField->getType() @@ -6117,6 +6164,130 @@ bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, return ZeroInitialization(E); } + case Builtin::BImemcpy: + case Builtin::BImemmove: + case Builtin::BIwmemcpy: + case Builtin::BIwmemmove: + if (Info.getLangOpts().CPlusPlus11) + Info.CCEDiag(E, diag::note_constexpr_invalid_function) + << /*isConstexpr*/0 << /*isConstructor*/0 + << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); + else + Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); + LLVM_FALLTHROUGH; + case Builtin::BI__builtin_memcpy: + case Builtin::BI__builtin_memmove: + case Builtin::BI__builtin_wmemcpy: + case Builtin::BI__builtin_wmemmove: { + bool WChar = BuiltinOp == Builtin::BIwmemcpy || + BuiltinOp == Builtin::BIwmemmove || + BuiltinOp == Builtin::BI__builtin_wmemcpy || + BuiltinOp == Builtin::BI__builtin_wmemmove; + bool Move = BuiltinOp == Builtin::BImemmove || + BuiltinOp == Builtin::BIwmemmove || + BuiltinOp == Builtin::BI__builtin_memmove || + BuiltinOp == Builtin::BI__builtin_wmemmove; + + // The result of mem* is the first argument. + if (!Visit(E->getArg(0))) + return false; + LValue Dest = Result; + + LValue Src; + if (!EvaluatePointer(E->getArg(1), Src, Info)) + return false; + + APSInt N; + if (!EvaluateInteger(E->getArg(2), N, Info)) + return false; + assert(!N.isSigned() && "memcpy and friends take an unsigned size"); + + // If the size is zero, we treat this as always being a valid no-op. + // (Even if one of the src and dest pointers is null.) + if (!N) + return true; + + // We require that Src and Dest are both pointers to arrays of + // trivially-copyable type. (For the wide version, the designator will be + // invalid if the designated object is not a wchar_t.) + QualType T = Dest.Designator.getType(Info.Ctx); + QualType SrcT = Src.Designator.getType(Info.Ctx); + if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { + Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; + return false; + } + if (!T.isTriviallyCopyableType(Info.Ctx)) { + Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; + return false; + } + + // Figure out how many T's we're copying. + uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); + if (!WChar) { + uint64_t Remainder; + llvm::APInt OrigN = N; + llvm::APInt::udivrem(OrigN, TSize, N, Remainder); + if (Remainder) { + Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) + << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) + << (unsigned)TSize; + return false; + } + } + + // Check that the copying will remain within the arrays, just so that we + // can give a more meaningful diagnostic. This implicitly also checks that + // N fits into 64 bits. + uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; + uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; + if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { + Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) + << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T + << N.toString(10, /*Signed*/false); + return false; + } + uint64_t NElems = N.getZExtValue(); + uint64_t NBytes = NElems * TSize; + + // Check for overlap. + int Direction = 1; + if (HasSameBase(Src, Dest)) { + uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); + uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); + if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { + // Dest is inside the source region. + if (!Move) { + Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; + return false; + } + // For memmove and friends, copy backwards. + if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || + !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) + return false; + Direction = -1; + } else if (!Move && SrcOffset >= DestOffset && + SrcOffset - DestOffset < NBytes) { + // Src is inside the destination region for memcpy: invalid. + Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; + return false; + } + } + + while (true) { + APValue Val; + if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || + !handleAssignment(Info, E, Dest, T, Val)) + return false; + // Do not iterate past the last element; if we're copying backwards, that + // might take us off the start of the array. + if (--NElems == 0) + return true; + if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || + !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) + return false; + } + } + default: return visitNonBuiltinCallExpr(E); } @@ -6583,7 +6754,7 @@ bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { if (ClosureClass->isInvalidDecl()) return false; if (Info.checkingPotentialConstantExpression()) return true; - + const size_t NumFields = std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); @@ -6602,7 +6773,7 @@ bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { assert(CaptureInitIt != E->capture_init_end()); // Get the initializer for this field Expr *const CurFieldInit = *CaptureInitIt++; - + // If there is no initializer, either this is a VLA or an error has // occurred. if (!CurFieldInit) @@ -6802,18 +6973,18 @@ VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { // The number of initializers can be less than the number of // vector elements. For OpenCL, this can be due to nested vector - // initialization. For GCC compatibility, missing trailing elements + // initialization. For GCC compatibility, missing trailing elements // should be initialized with zeroes. unsigned CountInits = 0, CountElts = 0; while (CountElts < NumElements) { // Handle nested vector initialization. - if (CountInits < NumInits + if (CountInits < NumInits && E->getInit(CountInits)->getType()->isVectorType()) { APValue v; if (!EvaluateVector(E->getInit(CountInits), v, Info)) return Error(E); unsigned vlen = v.getVectorLength(); - for (unsigned j = 0; j < vlen; j++) + for (unsigned j = 0; j < vlen; j++) Elements.push_back(v.getVectorElt(j)); CountElts += vlen; } else if (EltTy->isIntegerType()) { @@ -7108,7 +7279,7 @@ public: } bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { - assert(E->getType()->isIntegralOrEnumerationType() && + assert(E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result."); assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result."); @@ -7198,7 +7369,7 @@ public: } return Success(Info.ArrayInitIndex, E); } - + // Note, GNU defines __null as an integer, not a pointer. bool VisitGNUNullExpr(const GNUNullExpr *E) { return ZeroInitialization(E); @@ -8357,27 +8528,6 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, } } -static bool HasSameBase(const LValue &A, const LValue &B) { - if (!A.getLValueBase()) - return !B.getLValueBase(); - if (!B.getLValueBase()) - return false; - - if (A.getLValueBase().getOpaqueValue() != - B.getLValueBase().getOpaqueValue()) { - const Decl *ADecl = GetLValueBaseDecl(A); - if (!ADecl) - return false; - const Decl *BDecl = GetLValueBaseDecl(B); - if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) - return false; - } - - return IsGlobalLValue(A.getLValueBase()) || - (A.getLValueCallIndex() == B.getLValueCallIndex() && - A.getLValueVersion() == B.getLValueVersion()); -} - /// Determine whether this is a pointer past the end of the complete /// object referred to by the lvalue. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, @@ -8585,12 +8735,12 @@ bool DataRecursiveIntBinOpEvaluator:: Result = RHSResult.Val; return true; } - + if (E->isLogicalOp()) { bool lhsResult, rhsResult; bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); - + if (LHSIsOK) { if (RHSIsOK) { if (E->getOpcode() == BO_LOr) @@ -8606,26 +8756,26 @@ bool DataRecursiveIntBinOpEvaluator:: return Success(rhsResult, E, Result); } } - + return false; } - + assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()); - + if (LHSResult.Failed || RHSResult.Failed) return false; - + const APValue &LHSVal = LHSResult.Val; const APValue &RHSVal = RHSResult.Val; - + // Handle cases like (unsigned long)&a + 4. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { Result = LHSVal; addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); return true; } - + // Handle cases like 4 + (unsigned long)&a if (E->getOpcode() == BO_Add && RHSVal.isLValue() && LHSVal.isInt()) { @@ -8633,7 +8783,7 @@ bool DataRecursiveIntBinOpEvaluator:: addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); return true; } - + if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { // Handle (intptr_t)&&A - (intptr_t)&&B. if (!LHSVal.getLValueOffset().isZero() || @@ -8672,7 +8822,7 @@ bool DataRecursiveIntBinOpEvaluator:: void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { Job &job = Queue.back(); - + switch (job.Kind) { case Job::AnyExprKind: { if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { @@ -8682,12 +8832,12 @@ void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { return; } } - + EvaluateExpr(job.E, Result); Queue.pop_back(); return; } - + case Job::BinOpKind: { const BinaryOperator *Bop = cast<BinaryOperator>(job.E); bool SuppressRHSDiags = false; @@ -8702,7 +8852,7 @@ void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { enqueue(Bop->getRHS()); return; } - + case Job::BinOpVisitedLHSKind: { const BinaryOperator *Bop = cast<BinaryOperator>(job.E); EvalResult RHS; @@ -8712,7 +8862,7 @@ void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { return; } } - + llvm_unreachable("Invalid Job::Kind!"); } @@ -9299,7 +9449,7 @@ bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { const RecordType *BaseRT = CurrentType->getAs<RecordType>(); if (!BaseRT) return Error(OOE); - + // Add the offset to the base. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); break; @@ -10531,7 +10681,7 @@ static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, IsConst = false; return true; } - + // FIXME: Evaluating values of large array and record types can cause // performance problems. Only do so in C++11 for now. if (Exp->isRValue() && (Exp->getType()->isArrayType() || @@ -10553,7 +10703,7 @@ bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { bool IsConst; if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) return IsConst; - + EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); return ::EvaluateAsRValue(Info, this, Result.Val); } diff --git a/lib/AST/ExternalASTSource.cpp b/lib/AST/ExternalASTSource.cpp index 198ba9d4fbdba..40829c2e249dd 100644 --- a/lib/AST/ExternalASTSource.cpp +++ b/lib/AST/ExternalASTSource.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file provides the default implementation of the ExternalASTSource +// This file provides the default implementation of the ExternalASTSource // interface, which enables construction of AST nodes from some external // source. // diff --git a/lib/AST/ItaniumCXXABI.cpp b/lib/AST/ItaniumCXXABI.cpp index a75ae14f90155..64580edf004b6 100644 --- a/lib/AST/ItaniumCXXABI.cpp +++ b/lib/AST/ItaniumCXXABI.cpp @@ -190,7 +190,7 @@ public: return false; const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - CharUnits PointerSize = + CharUnits PointerSize = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); return Layout.getNonVirtualSize() == PointerSize; } diff --git a/lib/AST/ItaniumMangle.cpp b/lib/AST/ItaniumMangle.cpp index 3b99a3d9afda1..2dc04f2f3d869 100644 --- a/lib/AST/ItaniumMangle.cpp +++ b/lib/AST/ItaniumMangle.cpp @@ -46,10 +46,10 @@ namespace { /// Retrieve the declaration context that should be used when mangling the given /// declaration. static const DeclContext *getEffectiveDeclContext(const Decl *D) { - // The ABI assumes that lambda closure types that occur within + // The ABI assumes that lambda closure types that occur within // default arguments live in the context of the function. However, due to // the way in which Clang parses and creates function declarations, this is - // not the case: the lambda closure type ends up living in the context + // not the case: the lambda closure type ends up living in the context // where the function itself resides, because the function declaration itself // had not yet been created. Fix the context here. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { @@ -65,7 +65,7 @@ static const DeclContext *getEffectiveDeclContext(const Decl *D) { = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) return ContextParam->getDeclContext(); } - + const DeclContext *DC = D->getDeclContext(); if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) { return getEffectiveDeclContext(cast<Decl>(DC)); @@ -441,7 +441,7 @@ public: void mangleName(const NamedDecl *ND); void mangleType(QualType T); void mangleNameOrStandardSubstitution(const NamedDecl *ND); - + private: bool mangleSubstitution(const NamedDecl *ND); @@ -786,7 +786,7 @@ static bool isStd(const NamespaceDecl *NS) { if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS)) ->isTranslationUnit()) return false; - + const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); return II && II->isStr("std"); } @@ -998,7 +998,7 @@ void CXXNameMangler::mangleUnscopedTemplateName( // ::= <substitution> if (TemplateDecl *TD = Template.getAsTemplateDecl()) return mangleUnscopedTemplateName(TD, AdditionalAbiTags); - + if (mangleSubstitution(Template)) return; @@ -1100,7 +1100,7 @@ void CXXNameMangler::manglePrefix(QualType type) { if (const auto *TST = type->getAs<TemplateSpecializationType>()) { if (!mangleSubstitution(QualType(TST, 0))) { mangleTemplatePrefix(TST->getTemplateName()); - + // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? @@ -1372,7 +1372,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, // safety, just handle all ObjC containers here. if (isa<ObjCContainerDecl>(ND)) break; - + // We must have an anonymous struct. const TagDecl *TD = cast<TagDecl>(ND); if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { @@ -1389,7 +1389,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, } // <unnamed-type-name> ::= <closure-type-name> - // + // // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { @@ -1515,9 +1515,9 @@ void CXXNameMangler::mangleNestedName(const NamedDecl *ND, const DeclContext *DC, const AbiTagList *AdditionalAbiTags, bool NoFunction) { - // <nested-name> + // <nested-name> // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E - // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> + // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> // <template-args> E Out << 'N'; @@ -1530,7 +1530,7 @@ void CXXNameMangler::mangleNestedName(const NamedDecl *ND, mangleQualifiers(MethodQuals); mangleRefQualifier(Method->getRefQualifier()); } - + // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { @@ -1561,7 +1561,7 @@ void CXXNameMangler::mangleLocalName(const Decl *D, const AbiTagList *AdditionalAbiTags) { // <local-name> := Z <function encoding> E <entity name> [<discriminator>] // := Z <function encoding> E s [<discriminator>] - // <local-name> := Z <function encoding> E d [ <parameter number> ] + // <local-name> := Z <function encoding> E d [ <parameter number> ] // _ <entity name> // <discriminator> := _ <non-negative number> assert(isa<NamedDecl>(D) || isa<BlockDecl>(D)); @@ -1591,9 +1591,9 @@ void CXXNameMangler::mangleLocalName(const Decl *D, // be a bug that is fixed in trunk. if (RD) { - // The parameter number is omitted for the last parameter, 0 for the - // second-to-last parameter, 1 for the third-to-last parameter, etc. The - // <entity name> will of course contain a <closure-type-name>: Its + // The parameter number is omitted for the last parameter, 0 for the + // second-to-last parameter, 1 for the third-to-last parameter, etc. The + // <entity name> will of course contain a <closure-type-name>: Its // numbering will be local to the particular argument in which it appears // -- other default arguments do not affect its encoding. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD); @@ -1610,7 +1610,7 @@ void CXXNameMangler::mangleLocalName(const Decl *D, } } } - + // Mangle the name relative to the closest enclosing function. // equality ok because RD derived from ND above if (D == RD) { @@ -1699,8 +1699,8 @@ void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { } void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { - // If the context of a closure type is an initializer for a class member - // (static or nonstatic), it is encoded in a qualified name with a final + // If the context of a closure type is an initializer for a class member + // (static or nonstatic), it is encoded in a qualified name with a final // <prefix> of the form: // // <data-member-prefix> := <member source-name> M @@ -1730,9 +1730,9 @@ void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { mangleBareFunctionType(Proto, /*MangleReturnType=*/false, Lambda->getLambdaStaticInvoker()); Out << "E"; - - // The number is omitted for the first closure type with a given - // <lambda-sig> in a given context; it is n-2 for the nth closure type + + // The number is omitted for the first closure type with a given + // <lambda-sig> in a given context; it is n-2 for the nth closure type // (in lexical order) with that same <lambda-sig> and context. // // The AST keeps track of the number for us. @@ -1740,7 +1740,7 @@ void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { assert(Number > 0 && "Lambda should be mangled as an unnamed class"); if (Number > 1) mangleNumber(Number - 2); - Out << '_'; + Out << '_'; } void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { @@ -1795,10 +1795,10 @@ void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { assert(!isLocalContainerContext(DC)); - const NamedDecl *ND = cast<NamedDecl>(DC); + const NamedDecl *ND = cast<NamedDecl>(DC); if (mangleSubstitution(ND)) return; - + // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { @@ -2286,19 +2286,19 @@ void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSp switch (Quals.getObjCLifetime()) { case Qualifiers::OCL_None: break; - + case Qualifiers::OCL_Weak: // Do nothing as we already handled this case above. break; - + case Qualifiers::OCL_Strong: mangleVendorQualifier("__strong"); break; - + case Qualifiers::OCL_Autoreleasing: mangleVendorQualifier("__autoreleasing"); break; - + case Qualifiers::OCL_ExplicitNone: // The __unsafe_unretained qualifier is *not* mangled, so that // __unsafe_unretained types in ARC produce the same manglings as the @@ -2329,11 +2329,11 @@ void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { switch (RefQualifier) { case RQ_None: break; - + case RQ_LValue: Out << 'R'; break; - + case RQ_RValue: Out << 'O'; break; @@ -2364,15 +2364,15 @@ static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, void CXXNameMangler::mangleType(QualType T) { // If our type is instantiation-dependent but not dependent, we mangle - // it as it was written in the source, removing any top-level sugar. + // it as it was written in the source, removing any top-level sugar. // Otherwise, use the canonical type. // - // FIXME: This is an approximation of the instantiation-dependent name + // FIXME: This is an approximation of the instantiation-dependent name // mangling rules, since we should really be using the type as written and // augmented via semantic analysis (i.e., with implicit conversions and - // default template arguments) for any instantiation-dependent type. + // default template arguments) for any instantiation-dependent type. // Unfortunately, that requires several changes to our AST: - // - Instantiation-dependent TemplateSpecializationTypes will need to be + // - Instantiation-dependent TemplateSpecializationTypes will need to be // uniqued, so that we can handle substitutions properly // - Default template arguments will need to be represented in the // TemplateSpecializationType, since they need to be mangled even though @@ -2402,16 +2402,16 @@ void CXXNameMangler::mangleType(QualType T) { do { // Don't desugar through template specialization types that aren't // type aliases. We need to mangle the template arguments as written. - if (const TemplateSpecializationType *TST + if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) if (!TST->isTypeAlias()) break; - QualType Desugared + QualType Desugared = T.getSingleStepDesugaredType(Context.getASTContext()); if (Desugared == T) break; - + T = Desugared; } while (true); } @@ -2435,7 +2435,7 @@ void CXXNameMangler::mangleType(QualType T) { } if (quals || ty->isDependentAddressSpaceType()) { - if (const DependentAddressSpaceType *DAST = + if (const DependentAddressSpaceType *DAST = dyn_cast<DependentAddressSpaceType>(ty)) { SplitQualType splitDAST = DAST->getPointeeType().split(); mangleQualifiers(splitDAST.Quals, DAST); @@ -2899,7 +2899,7 @@ void CXXNameMangler::mangleType(const MemberPointerType *T) { QualType PointeeType = T->getPointeeType(); if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { mangleType(FPT); - + // Itanium C++ ABI 5.1.8: // // The type of a non-static member function is considered to be different, @@ -2907,8 +2907,8 @@ void CXXNameMangler::mangleType(const MemberPointerType *T) { // static member function whose type appears similar. The types of two // non-static member functions are considered to be different, for the // purposes of substitution, if the functions are members of different - // classes. In other words, for the purposes of substitution, the class of - // which the function is a member is considered part of the type of + // classes. In other words, for the purposes of substitution, the class of + // which the function is a member is considered part of the type of // function. // Given that we already substitute member function pointers as a @@ -3225,9 +3225,9 @@ void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { } else { if (mangleSubstitution(QualType(T, 0))) return; - + mangleTemplatePrefix(T->getTemplateName()); - + // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? @@ -3283,7 +3283,7 @@ void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? - mangleTemplateArgs(T->getArgs(), T->getNumArgs()); + mangleTemplateArgs(T->getArgs(), T->getNumArgs()); Out << 'E'; } @@ -3328,7 +3328,7 @@ void CXXNameMangler::mangleType(const UnaryTransformType *T) { // mangle it as the underlying type since they are equivalent. if (T->isDependentType()) { Out << 'U'; - + switch (T->getUTTKind()) { case UnaryTransformType::EnumUnderlyingType: Out << "3eut"; @@ -3498,7 +3498,7 @@ void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { // ::= L <mangled-name> E # external name // ::= fpT # 'this' expression QualType ImplicitlyConvertedToType; - + recurse: switch (E->getStmtClass()) { case Expr::NoStmtClass: @@ -3861,24 +3861,24 @@ recurse: case Expr::UnaryExprOrTypeTraitExprClass: { const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); - + if (!SAE->isInstantiationDependent()) { // Itanium C++ ABI: - // If the operand of a sizeof or alignof operator is not - // instantiation-dependent it is encoded as an integer literal + // If the operand of a sizeof or alignof operator is not + // instantiation-dependent it is encoded as an integer literal // reflecting the result of the operator. // - // If the result of the operator is implicitly converted to a known - // integer type, that type is used for the literal; otherwise, the type + // If the result of the operator is implicitly converted to a known + // integer type, that type is used for the literal; otherwise, the type // of std::size_t or std::ptrdiff_t is used. - QualType T = (ImplicitlyConvertedToType.isNull() || + QualType T = (ImplicitlyConvertedToType.isNull() || !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() : ImplicitlyConvertedToType; llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); mangleIntegerLiteral(T, V); break; } - + switch(SAE->getKind()) { case UETT_SizeOf: Out << 's'; @@ -3994,16 +3994,16 @@ recurse: E = cast<ImplicitCastExpr>(E)->getSubExpr(); goto recurse; } - + case Expr::ObjCBridgedCastExprClass: { - // Mangle ownership casts as a vendor extended operator __bridge, + // Mangle ownership casts as a vendor extended operator __bridge, // __bridge_transfer, or __bridge_retain. StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); Out << "v1U" << Kind.size() << Kind; } // Fall through to mangle the cast itself. LLVM_FALLTHROUGH; - + case Expr::CStyleCastExprClass: mangleCastExpression(E, "cv"); break; @@ -4143,7 +4143,7 @@ recurse: Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); Out << 'E'; break; - + case Expr::CXXBoolLiteralExprClass: Out << "Lb"; Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); @@ -4198,12 +4198,12 @@ recurse: Out << "LDnE"; break; } - + case Expr::PackExpansionExprClass: Out << "sp"; mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); break; - + case Expr::SizeOfPackExprClass: { auto *SPE = cast<SizeOfPackExpr>(E); if (SPE->isPartiallySubstituted()) { @@ -4430,11 +4430,11 @@ void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { // ::= J <template-arg>* E # argument pack if (!A.isInstantiationDependent() || A.isDependent()) A = Context.getASTContext().getCanonicalTemplateArgument(A); - + switch (A.getKind()) { case TemplateArgument::Null: llvm_unreachable("Cannot mangle NULL template argument"); - + case TemplateArgument::Type: mangleType(A.getAsType()); break; @@ -4461,7 +4461,7 @@ void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { break; } } - + Out << 'X'; mangleExpression(E); Out << 'E'; @@ -4578,7 +4578,7 @@ bool CXXNameMangler::mangleSubstitution(QualType T) { bool CXXNameMangler::mangleSubstitution(TemplateName Template) { if (TemplateDecl *TD = Template.getAsTemplateDecl()) return mangleSubstitution(TD); - + Template = Context.getASTContext().getCanonicalTemplateName(Template); return mangleSubstitution( reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); @@ -4743,7 +4743,7 @@ void CXXNameMangler::addSubstitution(QualType T) { void CXXNameMangler::addSubstitution(TemplateName Template) { if (TemplateDecl *TD = Template.getAsTemplateDecl()) return addSubstitution(TD); - + Template = Context.getASTContext().getCanonicalTemplateName(Template); addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); } @@ -4865,14 +4865,14 @@ void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, // # base is the nominal target function of thunk // # first call-offset is 'this' adjustment // # second call-offset is result adjustment - + assert(!isa<CXXDestructorDecl>(MD) && "Use mangleCXXDtor for destructor decls!"); CXXNameMangler Mangler(*this, Out); Mangler.getStream() << "_ZT"; if (!Thunk.Return.isEmpty()) Mangler.getStream() << 'c'; - + // Mangle the 'this' pointer adjustment. Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.Virtual.Itanium.VCallOffsetOffset); @@ -4894,7 +4894,7 @@ void ItaniumMangleContextImpl::mangleCXXDtorThunk( Mangler.getStream() << "_ZT"; // Mangle the 'this' pointer adjustment. - Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, + Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); Mangler.mangleFunctionEncoding(DD); diff --git a/lib/AST/Mangle.cpp b/lib/AST/Mangle.cpp index 56a2500274a72..b0e5146e81943 100644 --- a/lib/AST/Mangle.cpp +++ b/lib/AST/Mangle.cpp @@ -44,7 +44,7 @@ static void mangleFunctionBlock(MangleContext &Context, if (discriminator == 0) Out << "__" << Outer << "_block_invoke"; else - Out << "__" << Outer << "_block_invoke_" << discriminator+1; + Out << "__" << Outer << "_block_invoke_" << discriminator+1; } void MangleContext::anchor() { } diff --git a/lib/AST/MicrosoftMangle.cpp b/lib/AST/MicrosoftMangle.cpp index e45f9f7902e24..5db51b5cb3841 100644 --- a/lib/AST/MicrosoftMangle.cpp +++ b/lib/AST/MicrosoftMangle.cpp @@ -760,7 +760,7 @@ void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, // type [ -> template-parameters] // \-> namespace[s] // What we do is we create a new mangler, mangle the same type (without - // a namespace suffix) to a string using the extra mangler and then use + // a namespace suffix) to a string using the extra mangler and then use // the mangled type name as a key to check the mangling of different types // for aliasing. @@ -1373,13 +1373,14 @@ void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD, case TemplateArgument::Declaration: { const NamedDecl *ND = TA.getAsDecl(); if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) { - mangleMemberDataPointer( - cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentNonInjectedDecl(), - cast<ValueDecl>(ND)); + mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext()) + ->getMostRecentNonInjectedDecl(), + cast<ValueDecl>(ND)); } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); if (MD && MD->isInstance()) { - mangleMemberFunctionPointer(MD->getParent()->getMostRecentNonInjectedDecl(), MD); + mangleMemberFunctionPointer( + MD->getParent()->getMostRecentNonInjectedDecl(), MD); } else { Out << "$1?"; mangleName(FD); @@ -2285,7 +2286,8 @@ void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) { // If you add a call to this, consider updating isArtificialTagType() too. void MicrosoftCXXNameMangler::mangleArtificalTagType( - TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) { + TagTypeKind TK, StringRef UnqualifiedName, + ArrayRef<StringRef> NestedNames) { // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @ mangleTagTypeKind(TK); @@ -2372,8 +2374,8 @@ void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) { // <type> ::= <pointer-to-member-type> // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> // <class name> <type> -void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals, - SourceRange Range) { +void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, + Qualifiers Quals, SourceRange Range) { QualType PointeeType = T->getPointeeType(); manglePointerCVQualifiers(Quals); manglePointerExtQualifiers(Quals, PointeeType); diff --git a/lib/AST/NSAPI.cpp b/lib/AST/NSAPI.cpp index 536bf2c378fae..94ad87b6e337d 100644 --- a/lib/AST/NSAPI.cpp +++ b/lib/AST/NSAPI.cpp @@ -432,7 +432,7 @@ NSAPI::getNSNumberFactoryMethodKind(QualType T) const { return NSAPI::NSNumberWithDouble; case BuiltinType::Bool: return NSAPI::NSNumberWithBool; - + case BuiltinType::Void: case BuiltinType::WChar_U: case BuiltinType::WChar_S: @@ -491,7 +491,7 @@ NSAPI::getNSNumberFactoryMethodKind(QualType T) const { case BuiltinType::OMPArraySection: break; } - + return None; } @@ -511,7 +511,7 @@ bool NSAPI::isObjCNSUIntegerType(QualType T) const { StringRef NSAPI::GetNSIntegralKind(QualType T) const { if (!Ctx.getLangOpts().ObjC1 || T.isNull()) return StringRef(); - + while (const TypedefType *TDT = T->getAs<TypedefType>()) { StringRef NSIntegralResust = llvm::StringSwitch<StringRef>( diff --git a/lib/AST/NestedNameSpecifier.cpp b/lib/AST/NestedNameSpecifier.cpp index 503d0eb65e1eb..a514d57b6b6bc 100644 --- a/lib/AST/NestedNameSpecifier.cpp +++ b/lib/AST/NestedNameSpecifier.cpp @@ -85,7 +85,7 @@ NestedNameSpecifier::Create(const ASTContext &Context, NestedNameSpecifier * NestedNameSpecifier::Create(const ASTContext &Context, - NestedNameSpecifier *Prefix, + NestedNameSpecifier *Prefix, NamespaceAliasDecl *Alias) { assert(Alias && "Namespace alias cannot be NULL"); assert((!Prefix || @@ -234,7 +234,7 @@ bool NestedNameSpecifier::isInstantiationDependent() const { case Identifier: // Identifier specifiers always represent dependent types return true; - + case Namespace: case NamespaceAlias: case Global: @@ -284,7 +284,7 @@ NestedNameSpecifier::print(raw_ostream &OS, case Namespace: if (getAsNamespace()->isAnonymousNamespace()) return; - + OS << getAsNamespace()->getName(); break; @@ -348,7 +348,7 @@ LLVM_DUMP_METHOD void NestedNameSpecifier::dump() const { print(llvm::errs(), PrintingPolicy(LO)); } -unsigned +unsigned NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) { assert(Qualifier && "Expected a non-NULL qualifier"); @@ -379,7 +379,7 @@ NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) { return Length; } -unsigned +unsigned NestedNameSpecifierLoc::getDataLength(NestedNameSpecifier *Qualifier) { unsigned Length = 0; for (; Qualifier; Qualifier = Qualifier->getPrefix()) @@ -394,7 +394,7 @@ static SourceLocation LoadSourceLocation(void *Data, unsigned Offset) { memcpy(&Raw, static_cast<char *>(Data) + Offset, sizeof(unsigned)); return SourceLocation::getFromRawEncoding(Raw); } - + /// Load a (possibly unaligned) pointer from a given address and /// offset. static void *LoadPointer(void *Data, unsigned Offset) { @@ -406,19 +406,19 @@ static void *LoadPointer(void *Data, unsigned Offset) { SourceRange NestedNameSpecifierLoc::getSourceRange() const { if (!Qualifier) return SourceRange(); - + NestedNameSpecifierLoc First = *this; while (NestedNameSpecifierLoc Prefix = First.getPrefix()) First = Prefix; - - return SourceRange(First.getLocalSourceRange().getBegin(), + + return SourceRange(First.getLocalSourceRange().getBegin(), getLocalSourceRange().getEnd()); } SourceRange NestedNameSpecifierLoc::getLocalSourceRange() const { if (!Qualifier) return SourceRange(); - + unsigned Offset = getDataLength(Qualifier->getPrefix()); switch (Qualifier->getKind()) { case NestedNameSpecifier::Global: @@ -478,7 +478,7 @@ static void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize, memcpy(Buffer + BufferSize, Start, End - Start); BufferSize += End-Start; } - + /// Save a source location to the given buffer. static void SaveSourceLocation(SourceLocation Loc, char *&Buffer, unsigned &BufferSize, unsigned &BufferCapacity) { @@ -487,7 +487,7 @@ static void SaveSourceLocation(SourceLocation Loc, char *&Buffer, reinterpret_cast<char *>(&Raw) + sizeof(unsigned), Buffer, BufferSize, BufferCapacity); } - + /// Save a pointer to the given buffer. static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize, unsigned &BufferCapacity) { @@ -497,18 +497,18 @@ static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize, } NestedNameSpecifierLocBuilder:: -NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other) +NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other) : Representation(Other.Representation) { if (!Other.Buffer) return; - + if (Other.BufferCapacity == 0) { // Shallow copy is okay. Buffer = Other.Buffer; BufferSize = Other.BufferSize; return; } - + // Deep copy Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize, BufferCapacity); @@ -518,72 +518,72 @@ NestedNameSpecifierLocBuilder & NestedNameSpecifierLocBuilder:: operator=(const NestedNameSpecifierLocBuilder &Other) { Representation = Other.Representation; - + if (Buffer && Other.Buffer && BufferCapacity >= Other.BufferSize) { // Re-use our storage. BufferSize = Other.BufferSize; memcpy(Buffer, Other.Buffer, BufferSize); return *this; } - + // Free our storage, if we have any. if (BufferCapacity) { free(Buffer); BufferCapacity = 0; } - + if (!Other.Buffer) { // Empty. Buffer = nullptr; BufferSize = 0; return *this; } - + if (Other.BufferCapacity == 0) { // Shallow copy is okay. Buffer = Other.Buffer; BufferSize = Other.BufferSize; return *this; } - + // Deep copy. Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize, BufferCapacity); return *this; } -void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, - SourceLocation TemplateKWLoc, - TypeLoc TL, +void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, + SourceLocation TemplateKWLoc, + TypeLoc TL, SourceLocation ColonColonLoc) { - Representation = NestedNameSpecifier::Create(Context, Representation, - TemplateKWLoc.isValid(), + Representation = NestedNameSpecifier::Create(Context, Representation, + TemplateKWLoc.isValid(), TL.getTypePtr()); - + // Push source-location info into the buffer. SavePointer(TL.getOpaqueData(), Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, +void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, IdentifierInfo *Identifier, - SourceLocation IdentifierLoc, + SourceLocation IdentifierLoc, SourceLocation ColonColonLoc) { - Representation = NestedNameSpecifier::Create(Context, Representation, + Representation = NestedNameSpecifier::Create(Context, Representation, Identifier); - + // Push source-location info into the buffer. SaveSourceLocation(IdentifierLoc, Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, +void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, NamespaceDecl *Namespace, - SourceLocation NamespaceLoc, + SourceLocation NamespaceLoc, SourceLocation ColonColonLoc) { - Representation = NestedNameSpecifier::Create(Context, Representation, + Representation = NestedNameSpecifier::Create(Context, Representation, Namespace); - + // Push source-location info into the buffer. SaveSourceLocation(NamespaceLoc, Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); @@ -591,20 +591,20 @@ void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, NamespaceAliasDecl *Alias, - SourceLocation AliasLoc, + SourceLocation AliasLoc, SourceLocation ColonColonLoc) { Representation = NestedNameSpecifier::Create(Context, Representation, Alias); - + // Push source-location info into the buffer. SaveSourceLocation(AliasLoc, Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context, +void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc) { assert(!Representation && "Already have a nested-name-specifier!?"); Representation = NestedNameSpecifier::GlobalSpecifier(Context); - + // Push source-location info into the buffer. SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } @@ -620,12 +620,12 @@ void NestedNameSpecifierLocBuilder::MakeSuper(ASTContext &Context, SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context, - NestedNameSpecifier *Qualifier, +void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context, + NestedNameSpecifier *Qualifier, SourceRange R) { Representation = Qualifier; - - // Construct bogus (but well-formed) source information for the + + // Construct bogus (but well-formed) source information for the // nested-name-specifier. BufferSize = 0; SmallVector<NestedNameSpecifier *, 4> Stack; @@ -639,24 +639,24 @@ void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context, case NestedNameSpecifier::NamespaceAlias: SaveSourceLocation(R.getBegin(), Buffer, BufferSize, BufferCapacity); break; - + case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(QualType(NNS->getAsType(), 0), R.getBegin()); - SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize, + SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize, BufferCapacity); break; } - + case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: break; } - + // Save the location of the '::'. - SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(), + SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(), Buffer, BufferSize, BufferCapacity); } } @@ -670,8 +670,8 @@ void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) { BufferSize = 0; return; } - - // Rather than copying the data (which is wasteful), "adopt" the + + // Rather than copying the data (which is wasteful), "adopt" the // pointer (which points into the ASTContext) but set the capacity to zero to // indicate that we don't own it. Representation = Other.getNestedNameSpecifier(); @@ -680,16 +680,16 @@ void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) { BufferCapacity = 0; } -NestedNameSpecifierLoc +NestedNameSpecifierLoc NestedNameSpecifierLocBuilder::getWithLocInContext(ASTContext &Context) const { if (!Representation) return NestedNameSpecifierLoc(); - + // If we adopted our data pointer from elsewhere in the AST context, there's // no need to copy the memory. if (BufferCapacity == 0) return NestedNameSpecifierLoc(Representation, Buffer); - + // FIXME: After copying the source-location information, should we free // our (temporary) buffer and adopt the ASTContext-allocated memory? // Doing so would optimize repeated calls to getWithLocInContext(). diff --git a/lib/AST/ParentMap.cpp b/lib/AST/ParentMap.cpp index bc57b20790d95..af2a480dc23f1 100644 --- a/lib/AST/ParentMap.cpp +++ b/lib/AST/ParentMap.cpp @@ -137,7 +137,7 @@ Stmt *ParentMap::getParentIgnoreParenCasts(Stmt *S) const { } while (S && (isa<ParenExpr>(S) || isa<CastExpr>(S))); - return S; + return S; } Stmt *ParentMap::getParentIgnoreParenImpCasts(Stmt *S) const { diff --git a/lib/AST/RecordLayout.cpp b/lib/AST/RecordLayout.cpp index 37fe029f53bd3..9db23d50d0af2 100644 --- a/lib/AST/RecordLayout.cpp +++ b/lib/AST/RecordLayout.cpp @@ -30,10 +30,12 @@ void ASTRecordLayout::Destroy(ASTContext &Ctx) { ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment, + CharUnits unadjustedAlignment, CharUnits requiredAlignment, CharUnits datasize, ArrayRef<uint64_t> fieldoffsets) : Size(size), DataSize(datasize), Alignment(alignment), + UnadjustedAlignment(unadjustedAlignment), RequiredAlignment(requiredAlignment) { FieldOffsets.append(Ctx, fieldoffsets.begin(), fieldoffsets.end()); } @@ -41,6 +43,7 @@ ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, CharUnits size, // Constructor for C++ records. ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment, + CharUnits unadjustedAlignment, CharUnits requiredAlignment, bool hasOwnVFPtr, bool hasExtendableVFPtr, CharUnits vbptroffset, @@ -57,6 +60,7 @@ ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, const BaseOffsetsMapTy& BaseOffsets, const VBaseOffsetsMapTy& VBaseOffsets) : Size(size), DataSize(datasize), Alignment(alignment), + UnadjustedAlignment(unadjustedAlignment), RequiredAlignment(requiredAlignment), CXXInfo(new (Ctx) CXXRecordLayoutInfo) { FieldOffsets.append(Ctx, fieldoffsets.begin(), fieldoffsets.end()); @@ -87,5 +91,5 @@ ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, "Primary base must be at offset 0!"); } } -#endif +#endif } diff --git a/lib/AST/RecordLayoutBuilder.cpp b/lib/AST/RecordLayoutBuilder.cpp index b4b09c7cecd75..6f71d5b83e62e 100644 --- a/lib/AST/RecordLayoutBuilder.cpp +++ b/lib/AST/RecordLayoutBuilder.cpp @@ -105,7 +105,7 @@ struct ExternalLayout { class EmptySubobjectMap { const ASTContext &Context; uint64_t CharWidth; - + /// Class - The class whose empty entries we're keeping track of. const CXXRecordDecl *Class; @@ -113,35 +113,35 @@ class EmptySubobjectMap { typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy; typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy; EmptyClassOffsetsMapTy EmptyClassOffsets; - + /// MaxEmptyClassOffset - The highest offset known to contain an empty /// base subobject. CharUnits MaxEmptyClassOffset; - + /// ComputeEmptySubobjectSizes - Compute the size of the largest base or /// member subobject that is empty. void ComputeEmptySubobjectSizes(); - + void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset); - + void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, CharUnits Offset, bool PlacingEmptyBase); - - void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, + + void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset); void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset); - + /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty /// subobjects beyond the given offset. bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const { return Offset <= MaxEmptyClassOffset; } - CharUnits + CharUnits getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const { uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); - assert(FieldOffset % CharWidth == 0 && + assert(FieldOffset % CharWidth == 0 && "Field offset not at char boundary!"); return Context.toCharUnitsFromBits(FieldOffset); @@ -154,7 +154,7 @@ protected: bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, CharUnits Offset); - bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, + bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset) const; bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, @@ -228,7 +228,7 @@ void EmptySubobjectMap::ComputeEmptySubobjectSizes() { } bool -EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, +EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset) const { // We only need to check empty bases. if (!RD->isEmpty()) @@ -245,8 +245,8 @@ EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, // There is already an empty class of the same type at this offset. return false; } - -void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, + +void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset) { // We only care about empty bases. if (!RD->isEmpty()) @@ -257,9 +257,9 @@ void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, ClassVectorTy &Classes = EmptyClassOffsets[Offset]; if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end()) return; - + Classes.push_back(RD); - + // Update the empty class offset. if (Offset > MaxEmptyClassOffset) MaxEmptyClassOffset = Offset; @@ -296,10 +296,10 @@ EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, return false; } } - + // Traverse all member variables. unsigned FieldNo = 0; - for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), + for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { if (I->isBitField()) continue; @@ -312,15 +312,15 @@ EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, return true; } -void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, +void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, CharUnits Offset, bool PlacingEmptyBase) { if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) { // We know that the only empty subobjects that can conflict with empty // subobject of non-empty bases, are empty bases that can be placed at - // offset zero. Because of this, we only need to keep track of empty base + // offset zero. Because of this, we only need to keep track of empty base // subobjects with offsets less than the size of the largest empty - // subobject for our class. + // subobject for our class. return; } @@ -338,7 +338,7 @@ void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, if (Info->PrimaryVirtualBaseInfo) { BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; - + if (Info == PrimaryVirtualBaseInfo->Derived) UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset, PlacingEmptyBase); @@ -346,7 +346,7 @@ void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, // Traverse all member variables. unsigned FieldNo = 0; - for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), + for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { if (I->isBitField()) continue; @@ -373,7 +373,7 @@ bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, } bool -EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, +EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset) const { // We don't have to keep looking past the maximum offset that's known to @@ -383,7 +383,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, if (!CanPlaceSubobjectAtOffset(RD, Offset)) return false; - + const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); // Traverse all non-virtual bases. @@ -408,7 +408,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, return false; } } - + // Traverse all member variables. unsigned FieldNo = 0; for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); @@ -417,7 +417,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, continue; CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); - + if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset)) return false; } @@ -432,7 +432,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, // contain an empty class. if (!AnyEmptySubobjectsBeyondOffset(Offset)) return true; - + QualType T = FD->getType(); if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset); @@ -454,7 +454,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, // contain an empty class. if (!AnyEmptySubobjectsBeyondOffset(ElementOffset)) return true; - + if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset)) return false; @@ -466,23 +466,23 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, } bool -EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, +EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset) { if (!CanPlaceFieldSubobjectAtOffset(FD, Offset)) return false; - + // We are able to place the member variable at this offset. // Make sure to update the empty base subobject map. UpdateEmptyFieldSubobjects(FD, Offset); return true; } -void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, +void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset) { // We know that the only empty subobjects that can conflict with empty // field subobjects are subobjects of empty bases that can be placed at offset - // zero. Because of this, we only need to keep track of empty field + // zero. Because of this, we only need to keep track of empty field // subobjects with offsets less than the size of the largest empty // subobject for our class. if (Offset >= SizeOfLargestEmptySubobject) @@ -512,7 +512,7 @@ void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset); } } - + // Traverse all member variables. unsigned FieldNo = 0; for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); @@ -525,7 +525,7 @@ void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, UpdateEmptyFieldSubobjects(*I, FieldOffset); } } - + void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset) { QualType T = FD->getType(); @@ -543,13 +543,13 @@ void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - + uint64_t NumElements = Context.getConstantArrayElementCount(AT); CharUnits ElementOffset = Offset; - + for (uint64_t I = 0; I != NumElements; ++I) { // We know that the only empty subobjects that can conflict with empty - // field subobjects are subobjects of empty bases that can be placed at + // field subobjects are subobjects of empty bases that can be placed at // offset zero. Because of this, we only need to keep track of empty field // subobjects with offsets less than the size of the largest empty // subobject for our class. @@ -582,23 +582,26 @@ protected: /// The alignment if attribute packed is not used. CharUnits UnpackedAlignment; + /// \brief The maximum of the alignments of top-level members. + CharUnits UnadjustedAlignment; + SmallVector<uint64_t, 16> FieldOffsets; /// Whether the external AST source has provided a layout for this /// record. unsigned UseExternalLayout : 1; - /// Whether we need to infer alignment, even when we have an + /// Whether we need to infer alignment, even when we have an /// externally-provided layout. unsigned InferAlignment : 1; - + /// Packed - Whether the record is packed or not. unsigned Packed : 1; unsigned IsUnion : 1; unsigned IsMac68kAlign : 1; - + unsigned IsMsStruct : 1; /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield, @@ -662,6 +665,7 @@ protected: EmptySubobjectMap *EmptySubobjects) : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()), + UnadjustedAlignment(CharUnits::One()), UseExternalLayout(false), InferAlignment(false), Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false), UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0), @@ -687,14 +691,14 @@ protected: /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects. llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator; - + typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *> BaseSubobjectInfoMapTy; /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases /// of the class we're laying out to their base subobject info. BaseSubobjectInfoMapTy VirtualBaseInfo; - + /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the /// class we're laying out to their base subobject info. BaseSubobjectInfoMapTy NonVirtualBaseInfo; @@ -705,7 +709,7 @@ protected: /// ComputeBaseSubobjectInfo - Compute the base subobject information for a /// single class and all of its base classes. - BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, + BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived); @@ -754,18 +758,18 @@ protected: /// /// \param Field The field whose offset is being queried. /// \param ComputedOffset The offset that we've computed for this field. - uint64_t updateExternalFieldOffset(const FieldDecl *Field, + uint64_t updateExternalFieldOffset(const FieldDecl *Field, uint64_t ComputedOffset); - + void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset, unsigned UnpackedAlign, bool isPacked, const FieldDecl *D); DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); - CharUnits getSize() const { + CharUnits getSize() const { assert(Size % Context.getCharWidth() == 0); - return Context.toCharUnitsFromBits(Size); + return Context.toCharUnitsFromBits(Size); } uint64_t getSizeInBits() const { return Size; } @@ -774,9 +778,9 @@ protected: CharUnits getAligment() const { return Alignment; } - CharUnits getDataSize() const { + CharUnits getDataSize() const { assert(DataSize % Context.getCharWidth() == 0); - return Context.toCharUnitsFromBits(DataSize); + return Context.toCharUnitsFromBits(DataSize); } uint64_t getDataSizeInBits() const { return DataSize; } @@ -867,7 +871,7 @@ void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) { BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) { BaseSubobjectInfo *Info; - + if (IsVirtual) { // Check if we already have info about this virtual base. BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD]; @@ -882,7 +886,7 @@ BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( } else { Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; } - + Info->Class = RD; Info->IsVirtual = IsVirtual; Info->Derived = nullptr; @@ -898,10 +902,10 @@ BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( // This base does have a primary virtual base. PrimaryVirtualBase = Layout.getPrimaryBase(); assert(PrimaryVirtualBase && "Didn't have a primary virtual base!"); - + // Now check if we have base subobject info about this primary base. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); - + if (PrimaryVirtualBaseInfo) { if (PrimaryVirtualBaseInfo->Derived) { // We did have info about this primary base, and it turns out that it @@ -925,19 +929,19 @@ BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info)); } - + if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) { // Traversing the bases must have created the base info for our primary // virtual base. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); assert(PrimaryVirtualBaseInfo && "Did not create a primary virtual base!"); - + // Claim the primary virtual base as our primary virtual base. Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; PrimaryVirtualBaseInfo->Derived = Info; } - + return Info; } @@ -990,7 +994,7 @@ void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( // Compute base subobject info. ComputeBaseSubobjectInfo(RD); - + // If we have a primary base class, lay it out. if (PrimaryBase) { if (PrimaryBaseIsVirtual) { @@ -1008,9 +1012,9 @@ void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( LayoutVirtualBase(PrimaryBaseInfo); } else { - BaseSubobjectInfo *PrimaryBaseInfo = + BaseSubobjectInfo *PrimaryBaseInfo = NonVirtualBaseInfo.lookup(PrimaryBase); - assert(PrimaryBaseInfo && + assert(PrimaryBaseInfo && "Did not find base info for non-virtual primary base!"); LayoutNonVirtualBase(PrimaryBaseInfo); @@ -1020,9 +1024,9 @@ void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( // primary base, add it in now. } else if (RD->isDynamicClass()) { assert(DataSize == 0 && "Vtable pointer must be at offset zero!"); - CharUnits PtrWidth = + CharUnits PtrWidth = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); - CharUnits PtrAlign = + CharUnits PtrAlign = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); EnsureVTablePointerAlignment(PtrAlign); HasOwnVFPtr = true; @@ -1070,14 +1074,14 @@ void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets( // This base isn't interesting, it has no virtual bases. if (!Info->Class->getNumVBases()) return; - + // First, check if we have a virtual primary base to add offsets for. if (Info->PrimaryVirtualBaseInfo) { - assert(Info->PrimaryVirtualBaseInfo->IsVirtual && + assert(Info->PrimaryVirtualBaseInfo->IsVirtual && "Primary virtual base is not virtual!"); if (Info->PrimaryVirtualBaseInfo->Derived == Info) { // Add the offset. - assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && + assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && "primary vbase offset already exists!"); VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class, ASTRecordLayout::VBaseInfo(Offset, false))); @@ -1147,13 +1151,13 @@ void ItaniumRecordLayoutBuilder::LayoutVirtualBases( void ItaniumRecordLayoutBuilder::LayoutVirtualBase( const BaseSubobjectInfo *Base) { assert(!Base->Derived && "Trying to lay out a primary virtual base!"); - + // Layout the base. CharUnits Offset = LayoutBase(Base); // Add its base class offset. assert(!VBases.count(Base->Class) && "vbase offset already exists!"); - VBases.insert(std::make_pair(Base->Class, + VBases.insert(std::make_pair(Base->Class, ASTRecordLayout::VBaseInfo(Offset, false))); AddPrimaryVirtualBaseOffsets(Base, Offset); @@ -1163,9 +1167,9 @@ CharUnits ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class); - + CharUnits Offset; - + // Query the external layout to see if it provides an offset. bool HasExternalLayout = false; if (UseExternalLayout) { @@ -1174,7 +1178,7 @@ ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { else HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset); } - + // Clang <= 6 incorrectly applied the 'packed' attribute to base classes. // Per GCC's documentation, it only applies to non-static data members. CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment(); @@ -1220,7 +1224,7 @@ ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { InferAlignment = false; } } - + if (!Base->Class->isEmpty()) { // Update the data size. setDataSize(Offset + Layout.getNonVirtualSize()); @@ -1241,7 +1245,7 @@ void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) { IsMsStruct = RD->isMsStruct(Context); } - Packed = D->hasAttr<PackedAttr>(); + Packed = D->hasAttr<PackedAttr>(); // Honor the default struct packing maximum alignment flag. if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) { @@ -1263,7 +1267,7 @@ void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) { if (unsigned MaxAlign = D->getMaxAlignment()) UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign)); } - + // If there is an external AST source, ask it for the various offsets. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) if (ExternalASTSource *Source = Context.getExternalSource()) { @@ -1417,7 +1421,7 @@ void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize, setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize)); FieldOffset = 0; } else { - // The bitfield is allocated starting at the next offset aligned + // The bitfield is allocated starting at the next offset aligned // appropriately for T', with length n bits. FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign)); @@ -1609,7 +1613,7 @@ void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { bool AllowPadding = MaxFieldAlignment.isZero(); // Compute the real offset. - if (FieldSize == 0 || + if (FieldSize == 0 || (AllowPadding && (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) { FieldOffset = llvm::alignTo(FieldOffset, FieldAlign); @@ -1707,7 +1711,9 @@ void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { setSize(std::max(getSizeInBits(), getDataSizeInBits())); // Remember max struct/class alignment. - UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), + UnadjustedAlignment = + std::max(UnadjustedAlignment, Context.toCharUnitsFromBits(FieldAlign)); + UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), Context.toCharUnitsFromBits(UnpackedFieldAlign)); } @@ -1725,7 +1731,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, LastBitfieldTypeSize = 0; bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); - CharUnits FieldOffset = + CharUnits FieldOffset = IsUnion ? CharUnits::Zero() : getDataSize(); CharUnits FieldSize; CharUnits FieldAlign; @@ -1740,12 +1746,12 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, FieldAlign = Context.getTypeAlignInChars(ATy->getElementType()); } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) { unsigned AS = Context.getTargetAddressSpace(RT->getPointeeType()); - FieldSize = + FieldSize = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS)); - FieldAlign = + FieldAlign = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS)); } else { - std::pair<CharUnits, CharUnits> FieldInfo = + std::pair<CharUnits, CharUnits> FieldInfo = Context.getTypeInfoInChars(D->getType()); FieldSize = FieldInfo.first; FieldAlign = FieldInfo.second; @@ -1753,7 +1759,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, if (IsMsStruct) { // If MS bitfield layout is required, figure out what type is being // laid out and align the field to the width of that type. - + // Resolve all typedefs down to their base type and round up the field // alignment if necessary. QualType T = Context.getBaseElementType(D->getType()); @@ -1799,7 +1805,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, if (FieldPacked) FieldAlign = CharUnits::One(); - CharUnits MaxAlignmentInChars = + CharUnits MaxAlignmentInChars = Context.toCharUnitsFromBits(D->getMaxAlignment()); FieldAlign = std::max(FieldAlign, MaxAlignmentInChars); UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars); @@ -1817,12 +1823,12 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, if (UseExternalLayout) { FieldOffset = Context.toCharUnitsFromBits( updateExternalFieldOffset(D, Context.toBits(FieldOffset))); - + if (!IsUnion && EmptySubobjects) { // Record the fact that we're placing a field at this offset. bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset); (void)Allowed; - assert(Allowed && "Externally-placed field cannot be placed here"); + assert(Allowed && "Externally-placed field cannot be placed here"); } } else { if (!IsUnion && EmptySubobjects) { @@ -1833,12 +1839,12 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, } } } - + // Place this field at the current location. FieldOffsets.push_back(Context.toBits(FieldOffset)); if (!UseExternalLayout) - CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, + CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, Context.toBits(UnpackedFieldOffset), Context.toBits(UnpackedFieldAlign), FieldPacked, D); @@ -1862,6 +1868,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, setSize(std::max(getSizeInBits(), getDataSizeInBits())); // Remember max struct/class alignment. + UnadjustedAlignment = std::max(UnadjustedAlignment, FieldAlign); UpdateAlignment(FieldAlign, UnpackedFieldAlign); } @@ -1959,7 +1966,7 @@ ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, Alignment = CharUnits::One(); InferAlignment = false; } - + // Use the externally-supplied field offset. return ExternalFieldOffset; } @@ -1990,7 +1997,7 @@ void ItaniumRecordLayoutBuilder::CheckFieldPadding( // be done by clients of the AST, such as codegen. if (D->getLocation().isInvalid()) return; - + unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); // Warn if padding was introduced to the struct/class. @@ -2445,7 +2452,9 @@ void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) { auto RoundingAlignment = Alignment; if (!MaxFieldAlignment.isZero()) RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment); - NonVirtualSize = Size = Size.alignTo(RoundingAlignment); + if (!UseExternalLayout) + Size = Size.alignTo(RoundingAlignment); + NonVirtualSize = Size; RequiredAlignment = std::max( RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment())); layoutVirtualBases(RD); @@ -2646,21 +2655,16 @@ void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) { LastFieldIsNonZeroWidthBitfield = false; ElementInfo Info = getAdjustedElementInfo(FD); Alignment = std::max(Alignment, Info.Alignment); - if (IsUnion) { - placeFieldAtOffset(CharUnits::Zero()); - Size = std::max(Size, Info.Size); - } else { - CharUnits FieldOffset; - if (UseExternalLayout) { - FieldOffset = - Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD)); - assert(FieldOffset >= Size && "field offset already allocated"); - } else { - FieldOffset = Size.alignTo(Info.Alignment); - } - placeFieldAtOffset(FieldOffset); - Size = FieldOffset + Info.Size; - } + CharUnits FieldOffset; + if (UseExternalLayout) + FieldOffset = + Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD)); + else if (IsUnion) + FieldOffset = CharUnits::Zero(); + else + FieldOffset = Size.alignTo(Info.Alignment); + placeFieldAtOffset(FieldOffset); + Size = std::max(Size, FieldOffset + Info.Size); } void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) { @@ -2685,18 +2689,17 @@ void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) { } LastFieldIsNonZeroWidthBitfield = true; CurrentBitfieldSize = Info.Size; - if (IsUnion) { - placeFieldAtOffset(CharUnits::Zero()); - Size = std::max(Size, Info.Size); - // TODO: Add a Sema warning that MS ignores bitfield alignment in unions. - } else if (UseExternalLayout) { + if (UseExternalLayout) { auto FieldBitOffset = External.getExternalFieldOffset(FD); placeFieldAtBitOffset(FieldBitOffset); auto NewSize = Context.toCharUnitsFromBits( llvm::alignTo(FieldBitOffset + Width, Context.getCharWidth())); - assert(NewSize >= Size && "bit field offset already allocated"); - Size = NewSize; + Size = std::max(Size, NewSize); Alignment = std::max(Alignment, Info.Alignment); + } else if (IsUnion) { + placeFieldAtOffset(CharUnits::Zero()); + Size = std::max(Size, Info.Size); + // TODO: Add a Sema warning that MS ignores bitfield alignment in unions. } else { // Allocate a new block of memory and place the bitfield in it. CharUnits FieldOffset = Size.alignTo(Info.Alignment); @@ -2969,7 +2972,7 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { if (D->hasExternalLexicalStorage() && !D->getDefinition()) getExternalSource()->CompleteType(const_cast<RecordDecl*>(D)); - + D = D->getDefinition(); assert(D && "Cannot get layout of forward declarations!"); assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!"); @@ -2988,7 +2991,8 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { Builder.cxxLayout(RD); NewEntry = new (*this) ASTRecordLayout( - *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment, + *this, Builder.Size, Builder.Alignment, Builder.Alignment, + Builder.RequiredAlignment, Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase, Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets, Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(), @@ -2998,7 +3002,8 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { } else { Builder.layout(D); NewEntry = new (*this) ASTRecordLayout( - *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment, + *this, Builder.Size, Builder.Alignment, Builder.Alignment, + Builder.RequiredAlignment, Builder.Size, Builder.FieldOffsets); } } else { @@ -3019,7 +3024,7 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { CharUnits NonVirtualSize = skipTailPadding ? DataSize : Builder.NonVirtualSize; NewEntry = new (*this) ASTRecordLayout( - *this, Builder.getSize(), Builder.Alignment, + *this, Builder.getSize(), Builder.Alignment, Builder.UnadjustedAlignment, /*RequiredAlignment : used by MS-ABI)*/ Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(), CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets, @@ -3032,7 +3037,7 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { Builder.Layout(D); NewEntry = new (*this) ASTRecordLayout( - *this, Builder.getSize(), Builder.Alignment, + *this, Builder.getSize(), Builder.Alignment, Builder.UnadjustedAlignment, /*RequiredAlignment : used by MS-ABI)*/ Builder.Alignment, Builder.getSize(), Builder.FieldOffsets); } @@ -3186,6 +3191,7 @@ ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, const ASTRecordLayout *NewEntry = new (*this) ASTRecordLayout(*this, Builder.getSize(), Builder.Alignment, + Builder.UnadjustedAlignment, /*RequiredAlignment : used by MS-ABI)*/ Builder.Alignment, Builder.getDataSize(), @@ -3215,7 +3221,7 @@ static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset, BufferOS << Begin << '-' << (Begin + Width - 1); } } - + OS << llvm::right_justify(Buffer, 10) << " | "; OS.indent(IndentLevel * 2); } @@ -3323,7 +3329,7 @@ static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD, // Dump virtual bases. if (CXXRD && IncludeVirtualBases) { - const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps = + const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps = Layout.getVBaseOffsetsMap(); for (const CXXBaseSpecifier &Base : CXXRD->vbases()) { diff --git a/lib/AST/StmtOpenMP.cpp b/lib/AST/StmtOpenMP.cpp index 87bf5aaaa585d..1258af7a2d37e 100644 --- a/lib/AST/StmtOpenMP.cpp +++ b/lib/AST/StmtOpenMP.cpp @@ -1222,9 +1222,9 @@ OMPTargetParallelForSimdDirective *OMPTargetParallelForSimdDirective::Create( alignof(OMPClause *)); void *Mem = C.Allocate( Size + sizeof(OMPClause *) * Clauses.size() + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_parallel_for_simd)); - OMPTargetParallelForSimdDirective *Dir = + OMPTargetParallelForSimdDirective *Dir = new (Mem) OMPTargetParallelForSimdDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size()); Dir->setClauses(Clauses); @@ -1262,20 +1262,20 @@ OMPTargetParallelForSimdDirective::CreateEmpty(const ASTContext &C, alignof(OMPClause *)); void *Mem = C.Allocate( Size + sizeof(OMPClause *) * NumClauses + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_parallel_for_simd)); return new (Mem) OMPTargetParallelForSimdDirective(CollapsedNum, NumClauses); } OMPTargetSimdDirective * -OMPTargetSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc, +OMPTargetSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs) { unsigned Size = llvm::alignTo(sizeof(OMPTargetSimdDirective), alignof(OMPClause *)); void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_simd)); OMPTargetSimdDirective *Dir = new (Mem) OMPTargetSimdDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size()); @@ -1303,7 +1303,7 @@ OMPTargetSimdDirective::CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned Size = llvm::alignTo(sizeof(OMPTargetSimdDirective), alignof(OMPClause *)); void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_simd)); return new (Mem) OMPTargetSimdDirective(CollapsedNum, NumClauses); } diff --git a/lib/AST/StmtPrinter.cpp b/lib/AST/StmtPrinter.cpp index dad57de8940bb..cbf26c0360582 100644 --- a/lib/AST/StmtPrinter.cpp +++ b/lib/AST/StmtPrinter.cpp @@ -366,13 +366,13 @@ void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) { OS << "__if_exists ("; else OS << "__if_not_exists ("; - + if (NestedNameSpecifier *Qualifier = Node->getQualifierLoc().getNestedNameSpecifier()) Qualifier->print(OS, Policy); - + OS << Node->getNameInfo() << ") "; - + PrintRawCompoundStmt(Node->getSubStmt()); } @@ -990,7 +990,7 @@ void OMPClausePrinter::VisitOMPMapClause(OMPMapClause *Node) { OS << "map("; if (Node->getMapType() != OMPC_MAP_unknown) { if (Node->getMapTypeModifier() != OMPC_MAP_unknown) { - OS << getOpenMPSimpleClauseTypeName(OMPC_map, + OS << getOpenMPSimpleClauseTypeName(OMPC_map, Node->getMapTypeModifier()); OS << ','; } @@ -1645,12 +1645,12 @@ void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) { IdentifierInfo *Id = ON.getFieldName(); if (!Id) continue; - + if (PrintedSomething) OS << "."; else PrintedSomething = true; - OS << Id->getName(); + OS << Id->getName(); } OS << ")"; } @@ -2672,7 +2672,7 @@ void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) { if (I > 0) OS << ", "; - + ObjCDictionaryElement Element = E->getKeyValueElement(I); Visit(Element.Key); OS << " : "; @@ -2781,7 +2781,7 @@ void StmtPrinter::VisitBlockExpr(BlockExpr *Node) { OS << "{ }"; } -void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) { +void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) { PrintExpr(Node->getSourceExpr()); } diff --git a/lib/AST/StmtProfile.cpp b/lib/AST/StmtProfile.cpp index 791ec569cc419..15653c4fd838c 100644 --- a/lib/AST/StmtProfile.cpp +++ b/lib/AST/StmtProfile.cpp @@ -1277,25 +1277,24 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_Arrow: case OO_Call: case OO_Conditional: - case OO_Coawait: case NUM_OVERLOADED_OPERATORS: llvm_unreachable("Invalid operator call kind"); - + case OO_Plus: if (S->getNumArgs() == 1) { UnaryOp = UO_Plus; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_Add; return Stmt::BinaryOperatorClass; - + case OO_Minus: if (S->getNumArgs() == 1) { UnaryOp = UO_Minus; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_Sub; return Stmt::BinaryOperatorClass; @@ -1304,14 +1303,14 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, UnaryOp = UO_Deref; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_Mul; return Stmt::BinaryOperatorClass; case OO_Slash: BinaryOp = BO_Div; return Stmt::BinaryOperatorClass; - + case OO_Percent: BinaryOp = BO_Rem; return Stmt::BinaryOperatorClass; @@ -1325,10 +1324,10 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, UnaryOp = UO_AddrOf; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_And; return Stmt::BinaryOperatorClass; - + case OO_Pipe: BinaryOp = BO_Or; return Stmt::BinaryOperatorClass; @@ -1352,7 +1351,7 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_Greater: BinaryOp = BO_GT; return Stmt::BinaryOperatorClass; - + case OO_PlusEqual: BinaryOp = BO_AddAssign; return Stmt::CompoundAssignOperatorClass; @@ -1376,19 +1375,19 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_CaretEqual: BinaryOp = BO_XorAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_AmpEqual: BinaryOp = BO_AndAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_PipeEqual: BinaryOp = BO_OrAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_LessLess: BinaryOp = BO_Shl; return Stmt::BinaryOperatorClass; - + case OO_GreaterGreater: BinaryOp = BO_Shr; return Stmt::BinaryOperatorClass; @@ -1396,7 +1395,7 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_LessLessEqual: BinaryOp = BO_ShlAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_GreaterGreaterEqual: BinaryOp = BO_ShrAssign; return Stmt::CompoundAssignOperatorClass; @@ -1404,15 +1403,15 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_EqualEqual: BinaryOp = BO_EQ; return Stmt::BinaryOperatorClass; - + case OO_ExclaimEqual: BinaryOp = BO_NE; return Stmt::BinaryOperatorClass; - + case OO_LessEqual: BinaryOp = BO_LE; return Stmt::BinaryOperatorClass; - + case OO_GreaterEqual: BinaryOp = BO_GE; return Stmt::BinaryOperatorClass; @@ -1420,17 +1419,17 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_Spaceship: // FIXME: Update this once we support <=> expressions. llvm_unreachable("<=> expressions not supported yet"); - + case OO_AmpAmp: BinaryOp = BO_LAnd; return Stmt::BinaryOperatorClass; - + case OO_PipePipe: BinaryOp = BO_LOr; return Stmt::BinaryOperatorClass; case OO_PlusPlus: - UnaryOp = S->getNumArgs() == 1? UO_PreInc + UnaryOp = S->getNumArgs() == 1? UO_PreInc : UO_PostInc; return Stmt::UnaryOperatorClass; @@ -1446,11 +1445,15 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_ArrowStar: BinaryOp = BO_PtrMemI; return Stmt::BinaryOperatorClass; - + case OO_Subscript: return Stmt::ArraySubscriptExprClass; + + case OO_Coawait: + UnaryOp = UO_Coawait; + return Stmt::UnaryOperatorClass; } - + llvm_unreachable("Invalid overloaded operator expression"); } @@ -1482,7 +1485,7 @@ void StmtProfiler::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *S) { Visit(S->getArg(I)); if (SC == Stmt::UnaryOperatorClass) ID.AddInteger(UnaryOp); - else if (SC == Stmt::BinaryOperatorClass || + else if (SC == Stmt::BinaryOperatorClass || SC == Stmt::CompoundAssignOperatorClass) ID.AddInteger(BinaryOp); else @@ -1843,7 +1846,7 @@ void StmtProfiler::VisitCoyieldExpr(const CoyieldExpr *S) { } void StmtProfiler::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { - VisitExpr(E); + VisitExpr(E); } void StmtProfiler::VisitTypoExpr(const TypoExpr *E) { @@ -1962,7 +1965,7 @@ void StmtProfiler::VisitTemplateArgument(const TemplateArgument &Arg) { case TemplateArgument::TemplateExpansion: VisitTemplateName(Arg.getAsTemplateOrTemplatePattern()); break; - + case TemplateArgument::Declaration: VisitDecl(Arg.getAsDecl()); break; diff --git a/lib/AST/TemplateBase.cpp b/lib/AST/TemplateBase.cpp index 394e9f38bcfdb..a78927d229b9f 100644 --- a/lib/AST/TemplateBase.cpp +++ b/lib/AST/TemplateBase.cpp @@ -157,16 +157,16 @@ bool TemplateArgument::isInstantiationDependent() const { switch (getKind()) { case Null: llvm_unreachable("Should not have a NULL template argument"); - + case Type: return getAsType()->isInstantiationDependentType(); - + case Template: return getAsTemplate().isInstantiationDependent(); - + case TemplateExpansion: return true; - + case Declaration: if (DeclContext *DC = dyn_cast<DeclContext>(getAsDecl())) return DC->isDependentContext(); @@ -174,14 +174,14 @@ bool TemplateArgument::isInstantiationDependent() const { case NullPtr: return false; - + case Integral: // Never dependent return false; - + case Expression: return getAsExpr()->isInstantiationDependent(); - + case Pack: for (const auto &P : pack_elements()) if (P.isInstantiationDependent()) @@ -197,17 +197,17 @@ bool TemplateArgument::isPackExpansion() const { case Null: case Declaration: case Integral: - case Pack: + case Pack: case Template: case NullPtr: return false; - + case TemplateExpansion: return true; - + case Type: return isa<PackExpansionType>(getAsType()); - + case Expression: return isa<PackExpansionExpr>(getAsExpr()); } @@ -233,7 +233,7 @@ bool TemplateArgument::containsUnexpandedParameterPack() const { if (getAsTemplate().containsUnexpandedParameterPack()) return true; break; - + case Expression: if (getAsExpr()->containsUnexpandedParameterPack()) return true; @@ -254,8 +254,8 @@ Optional<unsigned> TemplateArgument::getNumTemplateExpansions() const { assert(getKind() == TemplateExpansion); if (TemplateArg.NumExpansions) return TemplateArg.NumExpansions - 1; - - return None; + + return None; } QualType TemplateArgument::getNonTypeTemplateArgumentType() const { @@ -319,7 +319,7 @@ void TemplateArgument::Profile(llvm::FoldingSetNodeID &ID, } break; } - + case Integral: getAsIntegral().Profile(ID); getIntegralType().Profile(ID); @@ -342,7 +342,7 @@ bool TemplateArgument::structurallyEquals(const TemplateArgument &Other) const { switch (getKind()) { case Null: case Type: - case Expression: + case Expression: case Template: case TemplateExpansion: case NullPtr: @@ -368,14 +368,14 @@ bool TemplateArgument::structurallyEquals(const TemplateArgument &Other) const { TemplateArgument TemplateArgument::getPackExpansionPattern() const { assert(isPackExpansion()); - + switch (getKind()) { case Type: return getAsType()->getAs<PackExpansionType>()->getPattern(); - + case Expression: return cast<PackExpansionExpr>(getAsExpr())->getPattern(); - + case TemplateExpansion: return TemplateArgument(getAsTemplateOrTemplatePattern()); @@ -391,20 +391,20 @@ TemplateArgument TemplateArgument::getPackExpansionPattern() const { llvm_unreachable("Invalid TemplateArgument Kind!"); } -void TemplateArgument::print(const PrintingPolicy &Policy, +void TemplateArgument::print(const PrintingPolicy &Policy, raw_ostream &Out) const { switch (getKind()) { case Null: Out << "(no value)"; break; - + case Type: { PrintingPolicy SubPolicy(Policy); SubPolicy.SuppressStrongLifetime = true; getAsType().print(Out, SubPolicy); break; } - + case Declaration: { NamedDecl *ND = getAsDecl(); Out << '&'; @@ -429,15 +429,15 @@ void TemplateArgument::print(const PrintingPolicy &Policy, getAsTemplateOrTemplatePattern().print(Out, Policy); Out << "..."; break; - + case Integral: printIntegral(*this, Out, Policy); break; - + case Expression: getAsExpr()->printPretty(Out, nullptr, Policy); break; - + case Pack: Out << "<"; bool First = true; @@ -446,11 +446,11 @@ void TemplateArgument::print(const PrintingPolicy &Policy, First = false; else Out << ", "; - + P.print(Policy, Out); } Out << ">"; - break; + break; } } @@ -486,13 +486,13 @@ SourceRange TemplateArgumentLoc::getSourceRange() const { case TemplateArgument::Template: if (getTemplateQualifierLoc()) - return SourceRange(getTemplateQualifierLoc().getBeginLoc(), + return SourceRange(getTemplateQualifierLoc().getBeginLoc(), getTemplateNameLoc()); return SourceRange(getTemplateNameLoc()); case TemplateArgument::TemplateExpansion: if (getTemplateQualifierLoc()) - return SourceRange(getTemplateQualifierLoc().getBeginLoc(), + return SourceRange(getTemplateQualifierLoc().getBeginLoc(), getTemplateEllipsisLoc()); return SourceRange(getTemplateNameLoc(), getTemplateEllipsisLoc()); @@ -514,19 +514,19 @@ const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, // This is bad, but not as bad as crashing because of argument // count mismatches. return DB << "(null template argument)"; - + case TemplateArgument::Type: return DB << Arg.getAsType(); - + case TemplateArgument::Declaration: return DB << Arg.getAsDecl(); case TemplateArgument::NullPtr: return DB << "nullptr"; - + case TemplateArgument::Integral: return DB << Arg.getAsIntegral().toString(10); - + case TemplateArgument::Template: return DB << Arg.getAsTemplate(); @@ -545,7 +545,7 @@ const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, Arg.getAsExpr()->printPretty(OS, nullptr, Policy); return DB << OS.str(); } - + case TemplateArgument::Pack: { // FIXME: We're guessing at LangOptions! SmallString<32> Str; diff --git a/lib/AST/TemplateName.cpp b/lib/AST/TemplateName.cpp index 548468ed17cdc..0a7a6bc3c6a7a 100644 --- a/lib/AST/TemplateName.cpp +++ b/lib/AST/TemplateName.cpp @@ -31,7 +31,7 @@ using namespace clang; -TemplateArgument +TemplateArgument SubstTemplateTemplateParmPackStorage::getArgumentPack() const { return TemplateArgument(llvm::makeArrayRef(Arguments, size())); } @@ -40,7 +40,7 @@ void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parameter, Replacement); } -void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID, +void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID, TemplateTemplateParmDecl *parameter, TemplateName replacement) { ID.AddPointer(parameter); @@ -52,7 +52,7 @@ void SubstTemplateTemplateParmPackStorage::Profile(llvm::FoldingSetNodeID &ID, Profile(ID, Context, Parameter, getArgumentPack()); } -void SubstTemplateTemplateParmPackStorage::Profile(llvm::FoldingSetNodeID &ID, +void SubstTemplateTemplateParmPackStorage::Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, TemplateTemplateParmDecl *Parameter, const TemplateArgument &ArgPack) { @@ -180,7 +180,7 @@ bool TemplateName::isInstantiationDependent() const { if (QTN->getQualifier()->isInstantiationDependent()) return true; } - + return isDependent(); } @@ -191,7 +191,7 @@ bool TemplateName::containsUnexpandedParameterPack() const { } if (TemplateDecl *Template = getAsTemplateDecl()) { - if (TemplateTemplateParmDecl *TTP + if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) return TTP->isParameterPack(); @@ -199,7 +199,7 @@ bool TemplateName::containsUnexpandedParameterPack() const { } if (DependentTemplateName *DTN = getAsDependentTemplateName()) - return DTN->getQualifier() && + return DTN->getQualifier() && DTN->getQualifier()->containsUnexpandedParameterPack(); return getAsSubstTemplateTemplateParmPack() != nullptr; @@ -220,7 +220,7 @@ TemplateName::print(raw_ostream &OS, const PrintingPolicy &Policy, if (!SuppressNNS && DTN->getQualifier()) DTN->getQualifier()->print(OS, Policy); OS << "template "; - + if (DTN->isIdentifier()) OS << DTN->getIdentifier()->getName(); else diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp index fad8c0d1c6b27..f79a59712a410 100644 --- a/lib/AST/Type.cpp +++ b/lib/AST/Type.cpp @@ -138,14 +138,14 @@ unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context, SizeExtended.getBitWidth()) * 2); llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); - TotalSize *= SizeExtended; + TotalSize *= SizeExtended; return TotalSize.getActiveBits(); } unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { unsigned Bits = Context.getTypeSize(Context.getSizeType()); - + // Limit the number of bits in size_t so that maximal bit size fits 64 bit // integer (see PR8256). We can do this as currently there is no hardware // that supports full 64-bit virtual space. @@ -155,7 +155,7 @@ unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { return Bits; } -DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, +DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, Expr *e, ArraySizeModifier sm, unsigned tq, @@ -201,8 +201,8 @@ void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID, DependentSizedExtVectorType::DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, - QualType can, - Expr *SizeExpr, + QualType can, + Expr *SizeExpr, SourceLocation loc) : Type(DependentSizedExtVector, can, /*Dependent=*/true, /*InstantiationDependent=*/true, @@ -249,7 +249,7 @@ VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements, : Type(tc, canonType, vecType->isDependentType(), vecType->isInstantiationDependentType(), vecType->isVariablyModifiedType(), - vecType->containsUnexpandedParameterPack()), + vecType->containsUnexpandedParameterPack()), ElementType(vecType) { VectorTypeBits.VecKind = vecKind; VectorTypeBits.NumElements = nElements; @@ -629,9 +629,9 @@ ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, ArrayRef<QualType> typeArgs, ArrayRef<ObjCProtocolDecl *> protocols, bool isKindOf) - : Type(ObjCObject, Canonical, Base->isDependentType(), - Base->isInstantiationDependentType(), - Base->isVariablyModifiedType(), + : Type(ObjCObject, Canonical, Base->isDependentType(), + Base->isInstantiationDependentType(), + Base->isVariablyModifiedType(), Base->containsUnexpandedParameterPack()), BaseType(Base) { ObjCObjectTypeBits.IsKindOf = isKindOf; @@ -657,7 +657,7 @@ ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, initialize(protocols); } -bool ObjCObjectType::isSpecialized() const { +bool ObjCObjectType::isSpecialized() const { // If we have type arguments written here, the type is specialized. if (ObjCObjectTypeBits.NumTypeArgs > 0) return true; @@ -744,7 +744,7 @@ namespace { /// Visitor used by simpleTransform() to perform the transformation. template<typename F> -struct SimpleTransformVisitor +struct SimpleTransformVisitor : public TypeVisitor<SimpleTransformVisitor<F>, QualType> { ASTContext &Ctx; F &&TheFunc; @@ -769,7 +769,7 @@ public: TRIVIAL_TYPE_CLASS(Builtin) - QualType VisitComplexType(const ComplexType *T) { + QualType VisitComplexType(const ComplexType *T) { QualType elementType = recurse(T->getElementType()); if (elementType.isNull()) return {}; @@ -807,7 +807,7 @@ public: if (pointeeType.isNull()) return {}; - if (pointeeType.getAsOpaquePtr() + if (pointeeType.getAsOpaquePtr() == T->getPointeeTypeAsWritten().getAsOpaquePtr()) return QualType(T, 0); @@ -819,7 +819,7 @@ public: if (pointeeType.isNull()) return {}; - if (pointeeType.getAsOpaquePtr() + if (pointeeType.getAsOpaquePtr() == T->getPointeeTypeAsWritten().getAsOpaquePtr()) return QualType(T, 0); @@ -834,7 +834,7 @@ public: if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getMemberPointerType(pointeeType, T->getClass()); + return Ctx.getMemberPointerType(pointeeType, T->getClass()); } QualType VisitConstantArrayType(const ConstantArrayType *T) { @@ -876,7 +876,7 @@ public: T->getIndexTypeCVRQualifiers()); } - QualType VisitVectorType(const VectorType *T) { + QualType VisitVectorType(const VectorType *T) { QualType elementType = recurse(T->getElementType()); if (elementType.isNull()) return {}; @@ -884,11 +884,11 @@ public: if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getVectorType(elementType, T->getNumElements(), + return Ctx.getVectorType(elementType, T->getNumElements(), T->getVectorKind()); } - QualType VisitExtVectorType(const ExtVectorType *T) { + QualType VisitExtVectorType(const ExtVectorType *T) { QualType elementType = recurse(T->getElementType()); if (elementType.isNull()) return {}; @@ -899,7 +899,7 @@ public: return Ctx.getExtVectorType(elementType, T->getNumElements()); } - QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { + QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { QualType returnType = recurse(T->getReturnType()); if (returnType.isNull()) return {}; @@ -910,7 +910,7 @@ public: return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo()); } - QualType VisitFunctionProtoType(const FunctionProtoType *T) { + QualType VisitFunctionProtoType(const FunctionProtoType *T) { QualType returnType = recurse(T->getReturnType()); if (returnType.isNull()) return {}; @@ -938,7 +938,7 @@ public: QualType newExceptionType = recurse(exceptionType); if (newExceptionType.isNull()) return {}; - + if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr()) exceptionChanged = true; @@ -958,7 +958,7 @@ public: return Ctx.getFunctionType(returnType, paramTypes, info); } - QualType VisitParenType(const ParenType *T) { + QualType VisitParenType(const ParenType *T) { QualType innerType = recurse(T->getInnerType()); if (innerType.isNull()) return {}; @@ -972,7 +972,7 @@ public: TRIVIAL_TYPE_CLASS(Typedef) TRIVIAL_TYPE_CLASS(ObjCTypeParam) - QualType VisitAdjustedType(const AdjustedType *T) { + QualType VisitAdjustedType(const AdjustedType *T) { QualType originalType = recurse(T->getOriginalType()); if (originalType.isNull()) return {}; @@ -981,20 +981,20 @@ public: if (adjustedType.isNull()) return {}; - if (originalType.getAsOpaquePtr() + if (originalType.getAsOpaquePtr() == T->getOriginalType().getAsOpaquePtr() && adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr()) return QualType(T, 0); return Ctx.getAdjustedType(originalType, adjustedType); } - - QualType VisitDecayedType(const DecayedType *T) { + + QualType VisitDecayedType(const DecayedType *T) { QualType originalType = recurse(T->getOriginalType()); if (originalType.isNull()) return {}; - if (originalType.getAsOpaquePtr() + if (originalType.getAsOpaquePtr() == T->getOriginalType().getAsOpaquePtr()) return QualType(T, 0); @@ -1011,7 +1011,7 @@ public: // FIXME: Non-trivial to implement, but important for C++ TRIVIAL_TYPE_CLASS(Elaborated) - QualType VisitAttributedType(const AttributedType *T) { + QualType VisitAttributedType(const AttributedType *T) { QualType modifiedType = recurse(T->getModifiedType()); if (modifiedType.isNull()) return {}; @@ -1020,13 +1020,13 @@ public: if (equivalentType.isNull()) return {}; - if (modifiedType.getAsOpaquePtr() + if (modifiedType.getAsOpaquePtr() == T->getModifiedType().getAsOpaquePtr() && - equivalentType.getAsOpaquePtr() + equivalentType.getAsOpaquePtr() == T->getEquivalentType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getAttributedType(T->getAttrKind(), modifiedType, + return Ctx.getAttributedType(T->getAttrKind(), modifiedType, equivalentType); } @@ -1035,7 +1035,7 @@ public: if (replacementType.isNull()) return {}; - if (replacementType.getAsOpaquePtr() + if (replacementType.getAsOpaquePtr() == T->getReplacementType().getAsOpaquePtr()) return QualType(T, 0); @@ -1054,7 +1054,7 @@ public: if (deducedType.isNull()) return {}; - if (deducedType.getAsOpaquePtr() + if (deducedType.getAsOpaquePtr() == T->getDeducedType().getAsOpaquePtr()) return QualType(T, 0); @@ -1088,7 +1088,7 @@ public: !typeArgChanged) return QualType(T, 0); - return Ctx.getObjCObjectType(baseType, typeArgs, + return Ctx.getObjCObjectType(baseType, typeArgs, llvm::makeArrayRef(T->qual_begin(), T->getNumProtocols()), T->isKindOfTypeAsWritten()); @@ -1101,7 +1101,7 @@ public: if (pointeeType.isNull()) return {}; - if (pointeeType.getAsOpaquePtr() + if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) return QualType(T, 0); @@ -1113,7 +1113,7 @@ public: if (valueType.isNull()) return {}; - if (valueType.getAsOpaquePtr() + if (valueType.getAsOpaquePtr() == T->getValueType().getAsOpaquePtr()) return QualType(T, 0); @@ -1628,6 +1628,10 @@ CXXRecordDecl *Type::getAsCXXRecordDecl() const { return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl()); } +RecordDecl *Type::getAsRecordDecl() const { + return dyn_cast_or_null<RecordDecl>(getAsTagDecl()); +} + TagDecl *Type::getAsTagDecl() const { if (const auto *TT = getAs<TagType>()) return TT->getDecl(); @@ -1739,10 +1743,10 @@ bool Type::hasIntegerRepresentation() const { /// Determine whether this type is an integral type. /// -/// This routine determines whether the given type is an integral type per +/// This routine determines whether the given type is an integral type per /// C++ [basic.fundamental]p7. Although the C standard does not define the /// term "integral type", it has a similar term "integer type", and in C++ -/// the two terms are equivalent. However, C's "integer type" includes +/// the two terms are equivalent. However, C's "integer type" includes /// enumeration types, while C++'s "integer type" does not. The \c ASTContext /// parameter is used to determine whether we should be following the C or /// C++ rules when determining whether this type is an integral/integer type. @@ -1751,7 +1755,7 @@ bool Type::hasIntegerRepresentation() const { /// type", use this routine. /// /// For cases where C permits "an integer type" and C++ permits "an integral -/// or enumeration type", use \c isIntegralOrEnumerationType() instead. +/// or enumeration type", use \c isIntegralOrEnumerationType() instead. /// /// \param Ctx The context in which this type occurs. /// @@ -1862,12 +1866,12 @@ bool Type::isSignedIntegerOrEnumerationType() const { return BT->getKind() >= BuiltinType::Char_S && BT->getKind() <= BuiltinType::Int128; } - + if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { if (ET->getDecl()->isComplete()) return ET->getDecl()->getIntegerType()->isSignedIntegerType(); } - + return false; } @@ -1902,12 +1906,12 @@ bool Type::isUnsignedIntegerOrEnumerationType() const { return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::UInt128; } - + if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { if (ET->getDecl()->isComplete()) return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); } - + return false; } @@ -2111,16 +2115,16 @@ bool QualType::isCXX98PODType(const ASTContext &Context) const { // are PODs according to the standard. if (isNull()) return false; - + if ((*this)->isIncompleteArrayType()) return Context.getBaseElementType(*this).isCXX98PODType(Context); - + if ((*this)->isIncompleteType()) return false; if (hasNonTrivialObjCLifetime()) return false; - + QualType CanonicalType = getTypePtr()->CanonicalType; switch (CanonicalType->getTypeClass()) { // Everything not explicitly mentioned is not POD. @@ -2129,7 +2133,7 @@ bool QualType::isCXX98PODType(const ASTContext &Context) const { case Type::ConstantArray: // IncompleteArray is handled above. return Context.getBaseElementType(*this).isCXX98PODType(Context); - + case Type::ObjCObjectPointer: case Type::BlockPointer: case Type::Builtin: @@ -2159,27 +2163,27 @@ bool QualType::isTrivialType(const ASTContext &Context) const { // are PODs according to the standard. if (isNull()) return false; - + if ((*this)->isArrayType()) return Context.getBaseElementType(*this).isTrivialType(Context); - + // Return false for incomplete types after skipping any incomplete array // types which are expressly allowed by the standard and thus our API. if ((*this)->isIncompleteType()) return false; - + if (hasNonTrivialObjCLifetime()) return false; - + QualType CanonicalType = getTypePtr()->CanonicalType; if (CanonicalType->isDependentType()) return false; - + // C++0x [basic.types]p9: // Scalar types, trivial class types, arrays of such types, and // cv-qualified versions of these types are collectively called trivial // types. - + // As an extension, Clang treats vector types as Scalar types. if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) return true; @@ -2193,10 +2197,10 @@ bool QualType::isTrivialType(const ASTContext &Context) const { !ClassDecl->hasNonTrivialDefaultConstructor() && ClassDecl->isTriviallyCopyable(); } - + return true; } - + // No other types can match. return false; } @@ -2221,7 +2225,7 @@ bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { // which are expressly allowed by the standard and thus our API. if (CanonicalType->isIncompleteType()) return false; - + // As an extension, Clang treats vector types as Scalar types. if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) return true; @@ -2477,10 +2481,10 @@ bool Type::isPromotableIntegerType() const { if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() || ET->getDecl()->isScoped()) return false; - + return true; } - + return false; } @@ -2531,7 +2535,7 @@ TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { case TST_union: return TTK_Union; case TST_enum: return TTK_Enum; } - + llvm_unreachable("Type specifier is not a tag type kind."); } @@ -2647,7 +2651,7 @@ const char *Type::getTypeClassName() const { #define TYPE(Derived, Base) case Derived: return #Derived; #include "clang/AST/TypeNodes.def" } - + llvm_unreachable("Invalid type class."); } @@ -2800,16 +2804,16 @@ StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { QualType QualType::getNonLValueExprType(const ASTContext &Context) const { if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) return RefType->getPointeeType(); - + // C++0x [basic.lval]: - // Class prvalues can have cv-qualified types; non-class prvalues always + // Class prvalues can have cv-qualified types; non-class prvalues always // have cv-unqualified types. // // See also C99 6.3.2.1p2. if (!Context.getLangOpts().CPlusPlus || (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) return getUnqualifiedType(); - + return *this; } @@ -2993,7 +2997,7 @@ bool FunctionProtoType::isTemplateVariadic() const { for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) return true; - + return false; } @@ -3005,7 +3009,7 @@ void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, // Note that valid type pointers are never ambiguous with anything else. // // The encoding grammar begins: - // type type* bool int bool + // type type* bool int bool // If that final bool is true, then there is a section for the EH spec: // bool type* // This is followed by an optional "consumed argument" section of the @@ -3013,7 +3017,7 @@ void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, // bool* // Finally, we have the ext info and trailing return type flag: // int bool - // + // // There is no ambiguity between the consumed arguments and an empty EH // spec because of the leading 'bool' which unambiguously indicates // whether the following bool is the EH spec or part of the arguments. @@ -3074,7 +3078,7 @@ bool TypeOfExprType::isSugared() const { QualType TypeOfExprType::desugar() const { if (isSugared()) return getUnderlyingExpr()->getType(); - + return QualType(this, 0); } @@ -3098,7 +3102,7 @@ bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } QualType DecltypeType::desugar() const { if (isSugared()) return getUnderlyingType(); - + return QualType(this, 0); } @@ -3174,6 +3178,7 @@ bool AttributedType::isQualifier() const { case AttributedType::attr_nonnull: case AttributedType::attr_nullable: case AttributedType::attr_null_unspecified: + case AttributedType::attr_lifetimebound: return true; // These aren't qualifiers; they rewrite the modified type to be a @@ -3243,6 +3248,7 @@ bool AttributedType::isCallingConv() const { case attr_null_unspecified: case attr_objc_kindof: case attr_nocf_check: + case attr_lifetimebound: return false; case attr_pcs: @@ -3274,7 +3280,7 @@ IdentifierInfo *TemplateTypeParmType::getIdentifier() const { } SubstTemplateTypeParmPackType:: -SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, +SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, QualType Canon, const TemplateArgument &ArgPack) : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), @@ -3331,7 +3337,7 @@ TemplateSpecializationType(TemplateName T, false, T.containsUnexpandedParameterPack()), Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) { - assert(!T.getAsDependentTemplateName() && + assert(!T.getAsDependentTemplateName() && "Use DependentTemplateSpecializationType for dependent template-name"); assert((T.getKind() == TemplateName::Template || T.getKind() == TemplateName::SubstTemplateTemplateParm || @@ -3546,7 +3552,7 @@ static CachedProperties computeCachedProperties(const Type *T) { } // C++ [basic.link]p8: - // - it is a compound type (3.9.2) other than a class or enumeration, + // - it is a compound type (3.9.2) other than a class or enumeration, // compounded exclusively from types that have linkage; or case Type::Complex: return Cache::get(cast<ComplexType>(T)->getElementType()); @@ -3716,14 +3722,14 @@ Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const QualType desugared = type.getSingleStepDesugaredType(context); if (desugared.getTypePtr() == type.getTypePtr()) return None; - + type = desugared; } while (true); } bool Type::canHaveNullability(bool ResultIfUnknown) const { QualType type = getCanonicalTypeInternal(); - + switch (type->getTypeClass()) { // We'll only see canonical types here. #define NON_CANONICAL_TYPE(Class, Parent) \ @@ -3957,7 +3963,7 @@ bool Type::isObjCLifetimeType() const { } /// Determine whether the given type T is a "bridgable" Objective-C type, -/// which is either an Objective-C object pointer type or an +/// which is either an Objective-C object pointer type or an bool Type::isObjCARCBridgableType() const { return isObjCObjectPointerType() || isBlockPointerType(); } @@ -3967,7 +3973,7 @@ bool Type::isCARCBridgableType() const { const auto *Pointer = getAs<PointerType>(); if (!Pointer) return false; - + QualType Pointee = Pointer->getPointeeType(); return Pointee->isVoidType() || Pointee->isRecordType(); } @@ -3980,7 +3986,7 @@ bool Type::hasSizedVLAType() const { if (const auto *ref = getAs<ReferenceType>()) return ref->getPointeeType()->hasSizedVLAType(); if (const ArrayType *arr = getAsArrayTypeUnsafe()) { - if (isa<VariableArrayType>(arr) && + if (isa<VariableArrayType>(arr) && cast<VariableArrayType>(arr)->getSizeExpr()) return true; diff --git a/lib/AST/TypeLoc.cpp b/lib/AST/TypeLoc.cpp index 6fa76e14a590c..e4fd6f106e33b 100644 --- a/lib/AST/TypeLoc.cpp +++ b/lib/AST/TypeLoc.cpp @@ -127,7 +127,7 @@ TypeLoc TypeLoc::getNextTypeLocImpl(TypeLoc TL) { /// Initializes a type location, and all of its children /// recursively, as if the entire tree had been written in the /// given location. -void TypeLoc::initializeImpl(ASTContext &Context, TypeLoc TL, +void TypeLoc::initializeImpl(ASTContext &Context, TypeLoc TL, SourceLocation Loc) { while (true) { switch (TL.getTypeLocClass()) { @@ -370,7 +370,7 @@ TypeSpecifierType BuiltinTypeLoc::getWrittenTypeSpec() const { case BuiltinType::SatULongFract: llvm_unreachable("Builtin type needs extra local data!"); // Fall through, if the impossible happens. - + case BuiltinType::NullPtr: case BuiltinType::Overload: case BuiltinType::Dependent: @@ -446,13 +446,13 @@ void ObjCTypeParamTypeLoc::initializeLocal(ASTContext &Context, setProtocolLoc(i, Loc); } -void ObjCObjectTypeLoc::initializeLocal(ASTContext &Context, +void ObjCObjectTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) { setHasBaseTypeAsWritten(true); setTypeArgsLAngleLoc(Loc); setTypeArgsRAngleLoc(Loc); for (unsigned i = 0, e = getNumTypeArgs(); i != e; ++i) { - setTypeArgTInfo(i, + setTypeArgTInfo(i, Context.getTrivialTypeSourceInfo( getTypePtr()->getTypeArgsAsWritten()[i], Loc)); } @@ -479,7 +479,7 @@ void UnaryTransformTypeLoc::initializeLocal(ASTContext &Context, Context.getTrivialTypeSourceInfo(getTypePtr()->getBaseType(), Loc)); } -void ElaboratedTypeLoc::initializeLocal(ASTContext &Context, +void ElaboratedTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) { setElaboratedKeywordLoc(Loc); NestedNameSpecifierLocBuilder Builder; @@ -487,7 +487,7 @@ void ElaboratedTypeLoc::initializeLocal(ASTContext &Context, setQualifierLoc(Builder.getWithLocInContext(Context)); } -void DependentNameTypeLoc::initializeLocal(ASTContext &Context, +void DependentNameTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) { setElaboratedKeywordLoc(Loc); NestedNameSpecifierLocBuilder Builder; @@ -516,14 +516,14 @@ DependentTemplateSpecializationTypeLoc::initializeLocal(ASTContext &Context, getArgInfos(), Loc); } -void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context, +void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context, unsigned NumArgs, const TemplateArgument *Args, TemplateArgumentLocInfo *ArgInfos, SourceLocation Loc) { for (unsigned i = 0, e = NumArgs; i != e; ++i) { switch (Args[i].getKind()) { - case TemplateArgument::Null: + case TemplateArgument::Null: llvm_unreachable("Impossible TemplateArgument"); case TemplateArgument::Integral: @@ -535,10 +535,10 @@ void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context, case TemplateArgument::Expression: ArgInfos[i] = TemplateArgumentLocInfo(Args[i].getAsExpr()); break; - + case TemplateArgument::Type: ArgInfos[i] = TemplateArgumentLocInfo( - Context.getTrivialTypeSourceInfo(Args[i].getAsType(), + Context.getTrivialTypeSourceInfo(Args[i].getAsType(), Loc)); break; diff --git a/lib/AST/TypePrinter.cpp b/lib/AST/TypePrinter.cpp index c5e2244e26c52..e032c312aa12f 100644 --- a/lib/AST/TypePrinter.cpp +++ b/lib/AST/TypePrinter.cpp @@ -52,14 +52,14 @@ namespace { class IncludeStrongLifetimeRAII { PrintingPolicy &Policy; bool Old; - + public: - explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) + explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) : Policy(Policy), Old(Policy.SuppressStrongLifetime) { if (!Policy.SuppressLifetimeQualifiers) Policy.SuppressStrongLifetime = false; } - + ~IncludeStrongLifetimeRAII() { Policy.SuppressStrongLifetime = Old; } @@ -68,13 +68,13 @@ namespace { class ParamPolicyRAII { PrintingPolicy &Policy; bool Old; - + public: - explicit ParamPolicyRAII(PrintingPolicy &Policy) + explicit ParamPolicyRAII(PrintingPolicy &Policy) : Policy(Policy), Old(Policy.SuppressSpecifiers) { Policy.SuppressSpecifiers = false; } - + ~ParamPolicyRAII() { Policy.SuppressSpecifiers = Old; } @@ -84,7 +84,7 @@ namespace { PrintingPolicy &Policy; bool SuppressTagKeyword; bool SuppressScope; - + public: explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) { SuppressTagKeyword = Policy.SuppressTagKeyword; @@ -92,13 +92,13 @@ namespace { Policy.SuppressTagKeyword = true; Policy.SuppressScope = true; } - + ~ElaboratedTypePolicyRAII() { Policy.SuppressTagKeyword = SuppressTagKeyword; Policy.SuppressScope = SuppressScope; } }; - + class TypePrinter { PrintingPolicy Policy; unsigned Indentation; @@ -193,7 +193,7 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, TC = AT->desugar()->getTypeClass(); if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) TC = Subst->getReplacementType()->getTypeClass(); - + switch (TC) { case Type::Auto: case Type::Builtin: @@ -221,19 +221,19 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, case Type::Pipe: CanPrefixQualifiers = true; break; - + case Type::ObjCObjectPointer: CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() || T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType(); break; - + case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: case Type::DependentSizedArray: NeedARCStrongQualifier = true; LLVM_FALLTHROUGH; - + case Type::Adjusted: case Type::Decayed: case Type::Pointer: @@ -444,8 +444,8 @@ void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T, printAfter(Inner, OS); } -void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, - raw_ostream &OS) { +void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getPointeeType(), OS); @@ -461,8 +461,8 @@ void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, OS << "::*"; } -void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, - raw_ostream &OS) { +void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); // Handle things like 'int (Cls::*A)[4];' correctly. @@ -472,14 +472,14 @@ void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, printAfter(T->getPointeeType(), OS); } -void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, +void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getElementType(), OS); } -void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, +void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, raw_ostream &OS) { OS << '['; if (T->getIndexTypeQualifiers().hasQualifiers()) { @@ -495,27 +495,27 @@ void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, printAfter(T->getElementType(), OS); } -void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, +void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getElementType(), OS); } -void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, +void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, raw_ostream &OS) { OS << "[]"; printAfter(T->getElementType(), OS); } -void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, +void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getElementType(), OS); } -void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, +void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, raw_ostream &OS) { OS << '['; if (T->getIndexTypeQualifiers().hasQualifiers()) { @@ -555,7 +555,7 @@ void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) { } void TypePrinter::printDependentSizedArrayBefore( - const DependentSizedArrayType *T, + const DependentSizedArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); @@ -563,7 +563,7 @@ void TypePrinter::printDependentSizedArrayBefore( } void TypePrinter::printDependentSizedArrayAfter( - const DependentSizedArrayType *T, + const DependentSizedArrayType *T, raw_ostream &OS) { OS << '['; if (T->getSizeExpr()) @@ -587,22 +587,22 @@ void TypePrinter::printDependentAddressSpaceAfter( } void TypePrinter::printDependentSizedExtVectorBefore( - const DependentSizedExtVectorType *T, - raw_ostream &OS) { + const DependentSizedExtVectorType *T, + raw_ostream &OS) { printBefore(T->getElementType(), OS); } void TypePrinter::printDependentSizedExtVectorAfter( - const DependentSizedExtVectorType *T, - raw_ostream &OS) { + const DependentSizedExtVectorType *T, + raw_ostream &OS) { OS << " __attribute__((ext_vector_type("; if (T->getSizeExpr()) T->getSizeExpr()->printPretty(OS, nullptr, Policy); - OS << ")))"; + OS << ")))"; printAfter(T->getElementType(), OS); } -void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { +void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { switch (T->getVectorKind()) { case VectorType::AltiVecPixel: OS << "__vector __pixel "; @@ -632,7 +632,7 @@ void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { << T->getNumElements() << " * sizeof("; print(T->getElementType(), OS, StringRef()); - OS << ")))) "; + OS << ")))) "; printBefore(T->getElementType(), OS); break; } @@ -692,19 +692,19 @@ void TypePrinter::printDependentVectorAfter( } void TypePrinter::printExtVectorBefore(const ExtVectorType *T, - raw_ostream &OS) { + raw_ostream &OS) { printBefore(T->getElementType(), OS); } -void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { +void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { printAfter(T->getElementType(), OS); OS << " __attribute__((ext_vector_type("; OS << T->getNumElements(); OS << ")))"; } -void -FunctionProtoType::printExceptionSpecification(raw_ostream &OS, +void +FunctionProtoType::printExceptionSpecification(raw_ostream &OS, const PrintingPolicy &Policy) const { if (hasDynamicExceptionSpec()) { @@ -715,7 +715,7 @@ FunctionProtoType::printExceptionSpecification(raw_ostream &OS, for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) { if (I) OS << ", "; - + OS << getExceptionType(I).stream(Policy); } OS << ')'; @@ -732,7 +732,7 @@ FunctionProtoType::printExceptionSpecification(raw_ostream &OS, } } -void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, +void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, raw_ostream &OS) { if (T->hasTrailingReturn()) { OS << "auto "; @@ -761,8 +761,8 @@ StringRef clang::getParameterABISpelling(ParameterABI ABI) { llvm_unreachable("bad parameter ABI kind"); } -void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, - raw_ostream &OS) { +void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, + raw_ostream &OS) { // If needed for precedence reasons, wrap the inner part in grouping parens. if (!HasEmptyPlaceHolder) OS << ')'; @@ -785,7 +785,7 @@ void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, print(T->getParamType(i), OS, StringRef()); } } - + if (T->isVariadic()) { if (T->getNumParams()) OS << ", "; @@ -794,7 +794,7 @@ void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, // Do not emit int() if we have a proto, emit 'int(void)'. OS << "void"; } - + OS << ')'; FunctionType::ExtInfo Info = T->getExtInfo(); @@ -902,8 +902,8 @@ void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info, OS << " __attribute__((nocf_check))"; } -void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, - raw_ostream &OS) { +void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, + raw_ostream &OS) { // If needed for precedence reasons, wrap the inner part in grouping parens. SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); printBefore(T->getReturnType(), OS); @@ -911,13 +911,13 @@ void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, OS << '('; } -void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, +void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, raw_ostream &OS) { // If needed for precedence reasons, wrap the inner part in grouping parens. if (!HasEmptyPlaceHolder) OS << ')'; SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); - + OS << "()"; printFunctionAfter(T->getExtInfo(), OS); printAfter(T->getReturnType(), OS); @@ -944,7 +944,7 @@ void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T, void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T, raw_ostream &OS) {} -void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { +void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { printTypeSpec(T->getDecl(), OS); } @@ -961,7 +961,7 @@ void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T, void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T, raw_ostream &OS) {} -void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { +void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { OS << "typeof("; print(T->getUnderlyingType(), OS, StringRef()); OS << ')'; @@ -970,7 +970,7 @@ void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {} -void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { +void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { OS << "decltype("; if (T->getUnderlyingExpr()) T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); @@ -1008,7 +1008,7 @@ void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T, printAfter(T->getBaseType(), OS); } -void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { +void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { // If the type has been deduced, do not print 'auto'. if (!T->getDeducedType().isNull()) { printBefore(T->getDeducedType(), OS); @@ -1022,7 +1022,7 @@ void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { } } -void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { +void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { // If the type has been deduced, do not print 'auto'. if (!T->getDeducedType().isNull()) printAfter(T->getDeducedType(), OS); @@ -1079,7 +1079,7 @@ void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) { AppendScope(DC->getParent(), OS); if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) { - if (Policy.SuppressUnwrittenScope && + if (Policy.SuppressUnwrittenScope && (NS->isAnonymousNamespace() || NS->isInline())) return; if (NS->getIdentifier()) @@ -1143,7 +1143,7 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { } else { OS << "anonymous"; } - + if (Policy.AnonymousTagLocations) { // Suppress the redundant tag keyword if we just printed one. // We don't have to worry about ElaboratedTypes here because you can't @@ -1188,14 +1188,14 @@ void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) { void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {} -void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { +void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { printTag(T->getDecl(), OS); } void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {} -void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, - raw_ostream &OS) { +void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, + raw_ostream &OS) { if (IdentifierInfo *Id = T->getIdentifier()) OS << Id->getName(); else @@ -1203,40 +1203,40 @@ void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, spaceBeforePlaceHolder(OS); } -void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, +void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, raw_ostream &OS) {} void TypePrinter::printSubstTemplateTypeParmBefore( - const SubstTemplateTypeParmType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printBefore(T->getReplacementType(), OS); } void TypePrinter::printSubstTemplateTypeParmAfter( - const SubstTemplateTypeParmType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printAfter(T->getReplacementType(), OS); } void TypePrinter::printSubstTemplateTypeParmPackBefore( - const SubstTemplateTypeParmPackType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmPackType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printTemplateTypeParmBefore(T->getReplacedParameter(), OS); } void TypePrinter::printSubstTemplateTypeParmPackAfter( - const SubstTemplateTypeParmPackType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmPackType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printTemplateTypeParmAfter(T->getReplacedParameter(), OS); } void TypePrinter::printTemplateSpecializationBefore( - const TemplateSpecializationType *T, - raw_ostream &OS) { + const TemplateSpecializationType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); T->getTemplateName().print(OS, Policy); @@ -1245,7 +1245,7 @@ void TypePrinter::printTemplateSpecializationBefore( } void TypePrinter::printTemplateSpecializationAfter( - const TemplateSpecializationType *T, + const TemplateSpecializationType *T, raw_ostream &OS) {} void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T, @@ -1279,7 +1279,7 @@ void TypePrinter::printElaboratedBefore(const ElaboratedType *T, if (Qualifier) Qualifier->print(OS, Policy); } - + ElaboratedTypePolicyRAII PolicyRAII(Policy); printBefore(T->getNamedType(), OS); } @@ -1309,13 +1309,13 @@ void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) { } void TypePrinter::printDependentNameBefore(const DependentNameType *T, - raw_ostream &OS) { + raw_ostream &OS) { OS << TypeWithKeyword::getKeywordName(T->getKeyword()); if (T->getKeyword() != ETK_None) OS << " "; - + T->getQualifier()->print(OS, Policy); - + OS << T->getIdentifier()->getName(); spaceBeforePlaceHolder(OS); } @@ -1324,7 +1324,7 @@ void TypePrinter::printDependentNameAfter(const DependentNameType *T, raw_ostream &OS) {} void TypePrinter::printDependentTemplateSpecializationBefore( - const DependentTemplateSpecializationType *T, raw_ostream &OS) { + const DependentTemplateSpecializationType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); OS << TypeWithKeyword::getKeywordName(T->getKeyword()); @@ -1341,12 +1341,12 @@ void TypePrinter::printDependentTemplateSpecializationBefore( void TypePrinter::printDependentTemplateSpecializationAfter( const DependentTemplateSpecializationType *T, raw_ostream &OS) {} -void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, +void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, raw_ostream &OS) { printBefore(T->getPattern(), OS); } -void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, +void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, raw_ostream &OS) { printAfter(T->getPattern(), OS); OS << "..."; @@ -1443,9 +1443,27 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, return; } + if (T->getAttrKind() == AttributedType::attr_lifetimebound) { + OS << " [[clang::lifetimebound]]"; + return; + } + OS << " __attribute__(("; switch (T->getAttrKind()) { - default: llvm_unreachable("This attribute should have been handled already"); + case AttributedType::attr_lifetimebound: + case AttributedType::attr_nonnull: + case AttributedType::attr_nullable: + case AttributedType::attr_null_unspecified: + case AttributedType::attr_objc_gc: + case AttributedType::attr_objc_inert_unsafe_unretained: + case AttributedType::attr_objc_kindof: + case AttributedType::attr_objc_ownership: + case AttributedType::attr_ptr32: + case AttributedType::attr_ptr64: + case AttributedType::attr_sptr: + case AttributedType::attr_uptr: + llvm_unreachable("This attribute should have been handled already"); + case AttributedType::attr_address_space: OS << "address_space("; // FIXME: printing the raw LangAS value is wrong. This should probably @@ -1489,36 +1507,6 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, break; } - case AttributedType::attr_objc_gc: { - OS << "objc_gc("; - - QualType tmp = T->getEquivalentType(); - while (tmp.getObjCGCAttr() == Qualifiers::GCNone) { - QualType next = tmp->getPointeeType(); - if (next == tmp) break; - tmp = next; - } - - if (tmp.isObjCGCWeak()) - OS << "weak"; - else - OS << "strong"; - OS << ')'; - break; - } - - case AttributedType::attr_objc_ownership: - OS << "objc_ownership("; - switch (T->getEquivalentType().getObjCLifetime()) { - case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); - case Qualifiers::OCL_ExplicitNone: OS << "none"; break; - case Qualifiers::OCL_Strong: OS << "strong"; break; - case Qualifiers::OCL_Weak: OS << "weak"; break; - case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break; - } - OS << ')'; - break; - case AttributedType::attr_ns_returns_retained: OS << "ns_returns_retained"; break; @@ -1561,13 +1549,13 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, OS << "))"; } -void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, - raw_ostream &OS) { +void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, + raw_ostream &OS) { OS << T->getDecl()->getName(); spaceBeforePlaceHolder(OS); } -void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, +void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, raw_ostream &OS) {} void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T, @@ -1640,7 +1628,7 @@ void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T, return printAfter(T->getBaseType(), OS); } -void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, +void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, raw_ostream &OS) { printBefore(T->getPointeeType(), OS); @@ -1653,7 +1641,7 @@ void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, } } -void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, +void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, raw_ostream &OS) {} static @@ -1832,11 +1820,11 @@ void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy, switch (lifetime) { case Qualifiers::OCL_None: llvm_unreachable("none but true"); case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break; - case Qualifiers::OCL_Strong: + case Qualifiers::OCL_Strong: if (!Policy.SuppressStrongLifetime) - OS << "__strong"; + OS << "__strong"; break; - + case Qualifiers::OCL_Weak: OS << "__weak"; break; case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break; } diff --git a/lib/AST/VTTBuilder.cpp b/lib/AST/VTTBuilder.cpp index b946f10105f42..a3f3dbdfb4f93 100644 --- a/lib/AST/VTTBuilder.cpp +++ b/lib/AST/VTTBuilder.cpp @@ -32,11 +32,11 @@ using namespace clang; VTTBuilder::VTTBuilder(ASTContext &Ctx, const CXXRecordDecl *MostDerivedClass, bool GenerateDefinition) - : Ctx(Ctx), MostDerivedClass(MostDerivedClass), + : Ctx(Ctx), MostDerivedClass(MostDerivedClass), MostDerivedClassLayout(Ctx.getASTRecordLayout(MostDerivedClass)), GenerateDefinition(GenerateDefinition) { // Lay out this VTT. - LayoutVTT(BaseSubobject(MostDerivedClass, CharUnits::Zero()), + LayoutVTT(BaseSubobject(MostDerivedClass, CharUnits::Zero()), /*BaseIsVirtual=*/false); } @@ -69,22 +69,22 @@ void VTTBuilder::LayoutSecondaryVTTs(BaseSubobject Base) { cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD); - CharUnits BaseOffset = Base.getBaseOffset() + + CharUnits BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); - + // Layout the VTT for this base. LayoutVTT(BaseSubobject(BaseDecl, BaseOffset), /*BaseIsVirtual=*/false); } } void -VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, +VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, bool BaseIsMorallyVirtual, uint64_t VTableIndex, const CXXRecordDecl *VTableClass, VisitedVirtualBasesSetTy &VBases) { const CXXRecordDecl *RD = Base.getBase(); - + // We're not interested in bases that don't have virtual bases, and not // morally virtual bases. if (!RD->getNumVBases() && !BaseIsMorallyVirtual) @@ -96,14 +96,14 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, // Itanium C++ ABI 2.6.2: // Secondary virtual pointers are present for all bases with either - // virtual bases or virtual function declarations overridden along a + // virtual bases or virtual function declarations overridden along a // virtual path. // // If the base class is not dynamic, we don't want to add it, nor any // of its base classes. if (!BaseDecl->isDynamicClass()) continue; - + bool BaseDeclIsMorallyVirtual = BaseIsMorallyVirtual; bool BaseDeclIsNonVirtualPrimaryBase = false; CharUnits BaseOffset; @@ -111,15 +111,15 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, // Ignore virtual bases that we've already visited. if (!VBases.insert(BaseDecl).second) continue; - + BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); BaseDeclIsMorallyVirtual = true; } else { const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD); - - BaseOffset = Base.getBaseOffset() + + + BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); - + if (!Layout.isPrimaryBaseVirtual() && Layout.getPrimaryBase() == BaseDecl) BaseDeclIsNonVirtualPrimaryBase = true; @@ -133,19 +133,19 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, if (!BaseDeclIsNonVirtualPrimaryBase && (BaseDecl->getNumVBases() || BaseDeclIsMorallyVirtual)) { // Add the vtable pointer. - AddVTablePointer(BaseSubobject(BaseDecl, BaseOffset), VTableIndex, + AddVTablePointer(BaseSubobject(BaseDecl, BaseOffset), VTableIndex, VTableClass); } // And lay out the secondary virtual pointers for the base class. LayoutSecondaryVirtualPointers(BaseSubobject(BaseDecl, BaseOffset), - BaseDeclIsMorallyVirtual, VTableIndex, + BaseDeclIsMorallyVirtual, VTableIndex, VTableClass, VBases); } } -void -VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, +void +VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, uint64_t VTableIndex) { VisitedVirtualBasesSetTy VBases; LayoutSecondaryVirtualPointers(Base, /*BaseIsMorallyVirtual=*/false, @@ -155,21 +155,21 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, void VTTBuilder::LayoutVirtualVTTs(const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) { for (const auto &I : RD->bases()) { - const CXXRecordDecl *BaseDecl = + const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); - + // Check if this is a virtual base. if (I.isVirtual()) { // Check if we've seen this base before. if (!VBases.insert(BaseDecl).second) continue; - - CharUnits BaseOffset = + + CharUnits BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); - + LayoutVTT(BaseSubobject(BaseDecl, BaseOffset), /*BaseIsVirtual=*/true); } - + // We only need to layout virtual VTTs for this base if it actually has // virtual bases. if (BaseDecl->getNumVBases()) @@ -181,7 +181,7 @@ void VTTBuilder::LayoutVTT(BaseSubobject Base, bool BaseIsVirtual) { const CXXRecordDecl *RD = Base.getBase(); // Itanium C++ ABI 2.6.2: - // An array of virtual table addresses, called the VTT, is declared for + // An array of virtual table addresses, called the VTT, is declared for // each class type that has indirect or direct virtual base classes. if (RD->getNumVBases() == 0) return; @@ -201,10 +201,10 @@ void VTTBuilder::LayoutVTT(BaseSubobject Base, bool BaseIsVirtual) { // Add the secondary VTTs. LayoutSecondaryVTTs(Base); - + // Add the secondary virtual pointers. LayoutSecondaryVirtualPointers(Base, VTableIndex); - + // If this is the primary VTT, we want to lay out virtual VTTs as well. if (IsPrimaryVTT) { VisitedVirtualBasesSetTy VBases; diff --git a/lib/AST/VTableBuilder.cpp b/lib/AST/VTableBuilder.cpp index 0a3da024f1477..dfc5774ab4988 100644 --- a/lib/AST/VTableBuilder.cpp +++ b/lib/AST/VTableBuilder.cpp @@ -35,14 +35,14 @@ namespace { struct BaseOffset { /// DerivedClass - The derived class. const CXXRecordDecl *DerivedClass; - + /// VirtualBase - If the path from the derived class to the base class /// involves virtual base classes, this holds the declaration of the last /// virtual base in this path (i.e. closest to the base class). const CXXRecordDecl *VirtualBase; /// NonVirtualOffset - The offset from the derived class to the base class. - /// (Or the offset from the virtual base class to the base class, if the + /// (Or the offset from the virtual base class to the base class, if the /// path from the derived class to the base class involves a virtual base /// class. CharUnits NonVirtualOffset; @@ -51,7 +51,7 @@ struct BaseOffset { NonVirtualOffset(CharUnits::Zero()) { } BaseOffset(const CXXRecordDecl *DerivedClass, const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset) - : DerivedClass(DerivedClass), VirtualBase(VirtualBase), + : DerivedClass(DerivedClass), VirtualBase(VirtualBase), NonVirtualOffset(NonVirtualOffset) { } bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; } @@ -81,19 +81,19 @@ private: /// MostDerivedClass - The most derived class for which the final overriders /// are stored. const CXXRecordDecl *MostDerivedClass; - - /// MostDerivedClassOffset - If we're building final overriders for a + + /// MostDerivedClassOffset - If we're building final overriders for a /// construction vtable, this holds the offset from the layout class to the /// most derived class. const CharUnits MostDerivedClassOffset; - /// LayoutClass - The class we're using for layout information. Will be + /// LayoutClass - The class we're using for layout information. Will be /// different than the most derived class if the final overriders are for a - /// construction vtable. - const CXXRecordDecl *LayoutClass; + /// construction vtable. + const CXXRecordDecl *LayoutClass; ASTContext &Context; - + /// MostDerivedClassLayout - the AST record layout of the most derived class. const ASTRecordLayout &MostDerivedClassLayout; @@ -103,19 +103,19 @@ private: typedef llvm::DenseMap<MethodBaseOffsetPairTy, OverriderInfo> OverridersMapTy; - - /// OverridersMap - The final overriders for all virtual member functions of + + /// OverridersMap - The final overriders for all virtual member functions of /// all the base subobjects of the most derived class. OverridersMapTy OverridersMap; - + /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented /// as a record decl and a subobject number) and its offsets in the most /// derived class as well as the layout class. - typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>, + typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>, CharUnits> SubobjectOffsetMapTy; typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy; - + /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the /// given base. void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, @@ -125,40 +125,40 @@ private: SubobjectCountMapTy &SubobjectCounts); typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; - + /// dump - dump the final overriders for a base subobject, and all its direct /// and indirect base subobjects. void dump(raw_ostream &Out, BaseSubobject Base, VisitedVirtualBasesSetTy& VisitedVirtualBases); - + public: FinalOverriders(const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset, const CXXRecordDecl *LayoutClass); /// getOverrider - Get the final overrider for the given method declaration in - /// the subobject with the given base offset. - OverriderInfo getOverrider(const CXXMethodDecl *MD, + /// the subobject with the given base offset. + OverriderInfo getOverrider(const CXXMethodDecl *MD, CharUnits BaseOffset) const { - assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) && + assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) && "Did not find overrider!"); - + return OverridersMap.lookup(std::make_pair(MD, BaseOffset)); } - + /// dump - dump the final overriders. void dump() { VisitedVirtualBasesSetTy VisitedVirtualBases; - dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()), + dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()), VisitedVirtualBases); } - + }; FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset, const CXXRecordDecl *LayoutClass) - : MostDerivedClass(MostDerivedClass), + : MostDerivedClass(MostDerivedClass), MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) { @@ -167,10 +167,10 @@ FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, SubobjectOffsetMapTy SubobjectOffsets; SubobjectOffsetMapTy SubobjectLayoutClassOffsets; SubobjectCountMapTy SubobjectCounts; - ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()), + ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()), /*IsVirtual=*/false, - MostDerivedClassOffset, - SubobjectOffsets, SubobjectLayoutClassOffsets, + MostDerivedClassOffset, + SubobjectOffsets, SubobjectLayoutClassOffsets, SubobjectCounts); // Get the final overriders. @@ -183,10 +183,10 @@ FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, for (const auto &M : Methods) { unsigned SubobjectNumber = M.first; - assert(SubobjectOffsets.count(std::make_pair(MD->getParent(), + assert(SubobjectOffsets.count(std::make_pair(MD->getParent(), SubobjectNumber)) && "Did not find subobject offset!"); - + CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(), SubobjectNumber)]; @@ -198,12 +198,12 @@ FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, std::make_pair(OverriderRD, Method.Subobject)) && "Did not find subobject offset!"); CharUnits OverriderOffset = - SubobjectLayoutClassOffsets[std::make_pair(OverriderRD, + SubobjectLayoutClassOffsets[std::make_pair(OverriderRD, Method.Subobject)]; OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)]; assert(!Overrider.Method && "Overrider should not exist yet!"); - + Overrider.Offset = OverriderOffset; Overrider.Method = Method.Method; Overrider.VirtualBase = Method.InVirtualSubobject; @@ -235,11 +235,11 @@ static BaseOffset ComputeBaseOffset(const ASTContext &Context, break; } } - + // Now compute the non-virtual offset. for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) { const CXXBasePathElement &Element = Path[I]; - + // Check the base class offset. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class); @@ -247,12 +247,12 @@ static BaseOffset ComputeBaseOffset(const ASTContext &Context, NonVirtualOffset += Layout.getBaseClassOffset(Base); } - + // FIXME: This should probably use CharUnits or something. Maybe we should - // even change the base offsets in ASTRecordLayout to be specified in + // even change the base offsets in ASTRecordLayout to be specified in // CharUnits. return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset); - + } static BaseOffset ComputeBaseOffset(const ASTContext &Context, @@ -268,67 +268,67 @@ static BaseOffset ComputeBaseOffset(const ASTContext &Context, } static BaseOffset -ComputeReturnAdjustmentBaseOffset(ASTContext &Context, +ComputeReturnAdjustmentBaseOffset(ASTContext &Context, const CXXMethodDecl *DerivedMD, const CXXMethodDecl *BaseMD) { const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>(); const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>(); - + // Canonicalize the return types. CanQualType CanDerivedReturnType = Context.getCanonicalType(DerivedFT->getReturnType()); CanQualType CanBaseReturnType = Context.getCanonicalType(BaseFT->getReturnType()); - assert(CanDerivedReturnType->getTypeClass() == - CanBaseReturnType->getTypeClass() && + assert(CanDerivedReturnType->getTypeClass() == + CanBaseReturnType->getTypeClass() && "Types must have same type class!"); - + if (CanDerivedReturnType == CanBaseReturnType) { // No adjustment needed. return BaseOffset(); } - + if (isa<ReferenceType>(CanDerivedReturnType)) { - CanDerivedReturnType = + CanDerivedReturnType = CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType(); - CanBaseReturnType = + CanBaseReturnType = CanBaseReturnType->getAs<ReferenceType>()->getPointeeType(); } else if (isa<PointerType>(CanDerivedReturnType)) { - CanDerivedReturnType = + CanDerivedReturnType = CanDerivedReturnType->getAs<PointerType>()->getPointeeType(); - CanBaseReturnType = + CanBaseReturnType = CanBaseReturnType->getAs<PointerType>()->getPointeeType(); } else { llvm_unreachable("Unexpected return type!"); } - + // We need to compare unqualified types here; consider // const T *Base::foo(); // T *Derived::foo(); - if (CanDerivedReturnType.getUnqualifiedType() == + if (CanDerivedReturnType.getUnqualifiedType() == CanBaseReturnType.getUnqualifiedType()) { // No adjustment needed. return BaseOffset(); } - - const CXXRecordDecl *DerivedRD = + + const CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl()); - - const CXXRecordDecl *BaseRD = + + const CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl()); return ComputeBaseOffset(Context, BaseRD, DerivedRD); } -void +void FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, CharUnits OffsetInLayoutClass, SubobjectOffsetMapTy &SubobjectOffsets, SubobjectOffsetMapTy &SubobjectLayoutClassOffsets, SubobjectCountMapTy &SubobjectCounts) { const CXXRecordDecl *RD = Base.getBase(); - + unsigned SubobjectNumber = 0; if (!IsVirtual) SubobjectNumber = ++SubobjectCounts[RD]; @@ -336,13 +336,13 @@ FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, // Set up the subobject to offset mapping. assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber)) && "Subobject offset already exists!"); - assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber)) + assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber)) && "Subobject offset already exists!"); SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset(); SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] = OffsetInLayoutClass; - + // Traverse our bases. for (const auto &B : RD->bases()) { const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); @@ -358,19 +358,19 @@ FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, Context.getASTRecordLayout(LayoutClass); BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); - BaseOffsetInLayoutClass = + BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl); } else { const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); CharUnits Offset = Layout.getBaseClassOffset(BaseDecl); - + BaseOffset = Base.getBaseOffset() + Offset; BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset; } - ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), - B.isVirtual(), BaseOffsetInLayoutClass, - SubobjectOffsets, SubobjectLayoutClassOffsets, + ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), + B.isVirtual(), BaseOffsetInLayoutClass, + SubobjectOffsets, SubobjectLayoutClassOffsets, SubobjectCounts); } } @@ -382,7 +382,7 @@ void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base, for (const auto &B : RD->bases()) { const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); - + // Ignore bases that don't have any virtual member functions. if (!BaseDecl->isPolymorphic()) continue; @@ -393,7 +393,7 @@ void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base, // We've visited this base before. continue; } - + BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); } else { BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset(); @@ -431,19 +431,19 @@ void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base, Offset.VirtualBase->printQualifiedName(Out); Out << " vbase, "; } - + Out << Offset.NonVirtualOffset.getQuantity() << " nv]"; } - + Out << "\n"; - } + } } /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable. struct VCallOffsetMap { - + typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy; - + /// Offsets - Keeps track of methods and their offsets. // FIXME: This should be a real map and not a vector. SmallVector<MethodAndOffsetPairTy, 16> Offsets; @@ -458,11 +458,11 @@ public: /// add was successful, or false if there was already a member function with /// the same signature in the map. bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset); - + /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the /// vtable address point) for the given virtual member function. CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD); - + // empty - Return whether the offset map is empty or not. bool empty() const { return Offsets.empty(); } }; @@ -489,13 +489,13 @@ bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS, const CXXMethodDecl *RHS) { assert(LHS->isVirtual() && "LHS must be virtual!"); assert(RHS->isVirtual() && "LHS must be virtual!"); - + // A destructor can share a vcall offset with another destructor. if (isa<CXXDestructorDecl>(LHS)) return isa<CXXDestructorDecl>(RHS); // FIXME: We need to check more things here. - + // The methods must have the same name. DeclarationName LHSName = LHS->getDeclName(); DeclarationName RHSName = RHS->getDeclName(); @@ -506,14 +506,14 @@ bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS, return HasSameVirtualSignature(LHS, RHS); } -bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, +bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset) { // Check if we can reuse an offset. for (const auto &OffsetPair : Offsets) { if (MethodsCanShareVCallOffset(OffsetPair.first, MD)) return false; } - + // Add the offset. Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset)); return true; @@ -525,36 +525,36 @@ CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) { if (MethodsCanShareVCallOffset(OffsetPair.first, MD)) return OffsetPair.second; } - + llvm_unreachable("Should always find a vcall offset offset!"); } /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets. class VCallAndVBaseOffsetBuilder { public: - typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> + typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> VBaseOffsetOffsetsMapTy; private: /// MostDerivedClass - The most derived class for which we're building vcall /// and vbase offsets. const CXXRecordDecl *MostDerivedClass; - - /// LayoutClass - The class we're using for layout information. Will be + + /// LayoutClass - The class we're using for layout information. Will be /// different than the most derived class if we're building a construction /// vtable. const CXXRecordDecl *LayoutClass; - + /// Context - The ASTContext which we will use for layout information. ASTContext &Context; /// Components - vcall and vbase offset components typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy; VTableComponentVectorTy Components; - + /// VisitedVirtualBases - Visited virtual bases. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; - + /// VCallOffsets - Keeps track of vcall offsets. VCallOffsetMap VCallOffsets; @@ -562,7 +562,7 @@ private: /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets, /// relative to the address point. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets; - + /// FinalOverriders - The final overriders of the most derived class. /// (Can be null when we're not building a vtable of the most derived class). const FinalOverriders *Overriders; @@ -571,48 +571,48 @@ private: /// given base subobject. void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual, CharUnits RealBaseOffset); - + /// AddVCallOffsets - Add vcall offsets for the given base subobject. void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset); - + /// AddVBaseOffsets - Add vbase offsets for the given class. - void AddVBaseOffsets(const CXXRecordDecl *Base, + void AddVBaseOffsets(const CXXRecordDecl *Base, CharUnits OffsetInLayoutClass); - + /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in /// chars, relative to the vtable address point. CharUnits getCurrentOffsetOffset() const; - + public: VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass, const CXXRecordDecl *LayoutClass, const FinalOverriders *Overriders, BaseSubobject Base, bool BaseIsVirtual, CharUnits OffsetInLayoutClass) - : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), + : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), Overriders(Overriders) { - + // Add vcall and vbase offsets. AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass); } - + /// Methods for iterating over the components. typedef VTableComponentVectorTy::const_reverse_iterator const_iterator; const_iterator components_begin() const { return Components.rbegin(); } const_iterator components_end() const { return Components.rend(); } - + const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; } const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const { return VBaseOffsetOffsets; } }; - -void + +void VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual, CharUnits RealBaseOffset) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase()); - + // Itanium C++ ABI 2.5.2: // ..in classes sharing a virtual table with a primary base class, the vcall // and vbase offsets added by the derived class all come before the vcall @@ -626,16 +626,16 @@ VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual(); CharUnits PrimaryBaseOffset; - + // Get the base offset of the primary base. if (PrimaryBaseIsVirtual) { assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() && "Primary vbase should have a zero offset!"); - + const ASTRecordLayout &MostDerivedClassLayout = Context.getASTRecordLayout(MostDerivedClass); - - PrimaryBaseOffset = + + PrimaryBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase); } else { assert(Layout.getBaseClassOffset(PrimaryBase).isZero() && @@ -657,19 +657,19 @@ VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, } CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const { - // OffsetIndex is the index of this vcall or vbase offset, relative to the + // OffsetIndex is the index of this vcall or vbase offset, relative to the // vtable address point. (We subtract 3 to account for the information just // above the address point, the RTTI info, the offset to top, and the // vcall offset itself). int64_t OffsetIndex = -(int64_t)(3 + Components.size()); - - CharUnits PointerWidth = + + CharUnits PointerWidth = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); CharUnits OffsetOffset = PointerWidth * OffsetIndex; return OffsetOffset; } -void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, +void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset) { const CXXRecordDecl *RD = Base.getBase(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); @@ -687,7 +687,7 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()), VBaseOffset); } - + // Add the vcall offsets. for (const auto *MD : RD->methods()) { if (!MD->isVirtual()) @@ -695,7 +695,7 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, MD = MD->getCanonicalDecl(); CharUnits OffsetOffset = getCurrentOffsetOffset(); - + // Don't add a vcall offset if we already have one for this member function // signature. if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset)) @@ -705,20 +705,20 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, if (Overriders) { // Get the final overrider. - FinalOverriders::OverriderInfo Overrider = + FinalOverriders::OverriderInfo Overrider = Overriders->getOverrider(MD, Base.getBaseOffset()); - - /// The vcall offset is the offset from the virtual base to the object + + /// The vcall offset is the offset from the virtual base to the object /// where the function was overridden. Offset = Overrider.Offset - VBaseOffset; } - + Components.push_back( VTableComponent::MakeVCallOffset(Offset)); } // And iterate over all non-virtual bases (ignoring the primary base). - for (const auto &B : RD->bases()) { + for (const auto &B : RD->bases()) { if (B.isVirtual()) continue; @@ -727,18 +727,18 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, continue; // Get the base offset of this base. - CharUnits BaseOffset = Base.getBaseOffset() + + CharUnits BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); - - AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), + + AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset); } } -void +void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass) { - const ASTRecordLayout &LayoutClassLayout = + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); // Add vbase offsets. @@ -747,7 +747,7 @@ VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, // Check if this is a virtual base that we haven't visited before. if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) { - CharUnits Offset = + CharUnits Offset = LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass; // Add the vbase offset offset. @@ -770,12 +770,12 @@ VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, /// ItaniumVTableBuilder - Class for building vtable layout information. class ItaniumVTableBuilder { public: - /// PrimaryBasesSetVectorTy - A set vector of direct and indirect + /// PrimaryBasesSetVectorTy - A set vector of direct and indirect /// primary bases. - typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> + typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> PrimaryBasesSetVectorTy; - - typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> + + typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> VBaseOffsetOffsetsMapTy; typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy; @@ -785,7 +785,7 @@ public: private: /// VTables - Global vtable information. ItaniumVTableContext &VTables; - + /// MostDerivedClass - The most derived class for which we're building this /// vtable. const CXXRecordDecl *MostDerivedClass; @@ -793,19 +793,19 @@ private: /// MostDerivedClassOffset - If we're building a construction vtable, this /// holds the offset from the layout class to the most derived class. const CharUnits MostDerivedClassOffset; - - /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual + + /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual /// base. (This only makes sense when building a construction vtable). bool MostDerivedClassIsVirtual; - - /// LayoutClass - The class we're using for layout information. Will be + + /// LayoutClass - The class we're using for layout information. Will be /// different than the most derived class if we're building a construction /// vtable. const CXXRecordDecl *LayoutClass; - + /// Context - The ASTContext which we will use for layout information. ASTContext &Context; - + /// FinalOverriders - The final overriders of the most derived class. const FinalOverriders Overriders; @@ -828,29 +828,29 @@ private: struct MethodInfo { /// BaseOffset - The base offset of this method. const CharUnits BaseOffset; - + /// BaseOffsetInLayoutClass - The base offset in the layout class of this /// method. const CharUnits BaseOffsetInLayoutClass; - + /// VTableIndex - The index in the vtable that this method has. /// (For destructors, this is the index of the complete destructor). const uint64_t VTableIndex; - - MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass, + + MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass, uint64_t VTableIndex) - : BaseOffset(BaseOffset), + : BaseOffset(BaseOffset), BaseOffsetInLayoutClass(BaseOffsetInLayoutClass), VTableIndex(VTableIndex) { } - - MethodInfo() - : BaseOffset(CharUnits::Zero()), - BaseOffsetInLayoutClass(CharUnits::Zero()), + + MethodInfo() + : BaseOffset(CharUnits::Zero()), + BaseOffsetInLayoutClass(CharUnits::Zero()), VTableIndex(0) { } }; - + typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy; - + /// MethodInfoMap - The information for all methods in the vtable we're /// currently building. MethodInfoMapTy MethodInfoMap; @@ -860,25 +860,25 @@ private: MethodVTableIndicesTy MethodVTableIndices; typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy; - - /// VTableThunks - The thunks by vtable index in the vtable currently being + + /// VTableThunks - The thunks by vtable index in the vtable currently being /// built. VTableThunksMapTy VTableThunks; typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy; typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy; - + /// Thunks - A map that contains all the thunks needed for all methods in the /// most derived class for which the vtable is currently being built. ThunksMapTy Thunks; - + /// AddThunk - Add a thunk for the given method. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk); - + /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the /// part of the vtable we're currently building. void ComputeThisAdjustments(); - + typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; /// PrimaryVirtualBases - All known virtual bases who are a primary base of @@ -888,7 +888,7 @@ private: /// ComputeReturnAdjustment - Compute the return adjustment given a return /// adjustment base offset. ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset); - + /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting /// the 'this' pointer from the base subobject to the derived subobject. BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base, @@ -897,8 +897,8 @@ private: /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the /// given virtual member function, its offset in the layout class and its /// final overrider. - ThisAdjustment - ComputeThisAdjustment(const CXXMethodDecl *MD, + ThisAdjustment + ComputeThisAdjustment(const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass, FinalOverriders::OverriderInfo Overrider); @@ -907,7 +907,7 @@ private: void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment); /// IsOverriderUsed - Returns whether the overrider will ever be used in this - /// part of the vtable. + /// part of the vtable. /// /// Itanium C++ ABI 2.5.2: /// @@ -921,16 +921,16 @@ private: /// adjustment is required and no thunk is generated. However, inside D /// objects, A is no longer a primary base of C, so if we allowed calls to /// C::f() to use the copy of A's vtable in the C subobject, we would need - /// to adjust this from C* to B::A*, which would require a third-party - /// thunk. Since we require that a call to C::f() first convert to A*, - /// C-in-D's copy of A's vtable is never referenced, so this is not + /// to adjust this from C* to B::A*, which would require a third-party + /// thunk. Since we require that a call to C::f() first convert to A*, + /// C-in-D's copy of A's vtable is never referenced, so this is not /// necessary. bool IsOverriderUsed(const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass, const CXXRecordDecl *FirstBaseInPrimaryBaseChain, CharUnits FirstBaseOffsetInLayoutClass) const; - + /// AddMethods - Add the methods of this base subobject and all its /// primary bases to the vtable components vector. void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass, @@ -949,12 +949,12 @@ private: /// or a direct or indirect base of a virtual base. /// /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual - /// in the layout class. + /// in the layout class. void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual, bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass); - + /// LayoutSecondaryVTables - Layout the secondary vtables for the given base /// subobject. /// @@ -965,18 +965,18 @@ private: /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this /// class hierarchy. - void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, + void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass, VisitedVirtualBasesSetTy &VBases); /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the /// given base (excluding any primary bases). - void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, + void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases); /// isBuildingConstructionVTable - Return whether this vtable builder is /// building a construction vtable. - bool isBuildingConstructorVTable() const { + bool isBuildingConstructorVTable() const { return MostDerivedClass != LayoutClass; } @@ -1055,16 +1055,16 @@ public: void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) { - assert(!isBuildingConstructorVTable() && + assert(!isBuildingConstructorVTable() && "Can't add thunks for construction vtable"); SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD]; // Check if we have this thunk already. - if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != + if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != ThunksVector.end()) return; - + ThunksVector.push_back(Thunk); } @@ -1107,18 +1107,18 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { // Ignore adjustments for unused function pointers. uint64_t VTableIndex = MethodInfo.VTableIndex; - if (Components[VTableIndex].getKind() == + if (Components[VTableIndex].getKind() == VTableComponent::CK_UnusedFunctionPointer) continue; - + // Get the final overrider for this method. FinalOverriders::OverriderInfo Overrider = Overriders.getOverrider(MD, MethodInfo.BaseOffset); - + // Check if we need an adjustment at all. if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) { // When a return thunk is needed by a derived class that overrides a - // virtual base, gcc uses a virtual 'this' adjustment as well. + // virtual base, gcc uses a virtual 'this' adjustment as well. // While the thunk itself might be needed by vtables in subclasses or // in construction vtables, there doesn't seem to be a reason for using // the thunk in this vtable. Still, we do so to match gcc. @@ -1143,7 +1143,7 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { /// Clear the method info map. MethodInfoMap.clear(); - + if (isBuildingConstructorVTable()) { // We don't need to store thunk information for construction vtables. return; @@ -1153,7 +1153,7 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { const VTableComponent &Component = Components[TI.first]; const ThunkInfo &Thunk = TI.second; const CXXMethodDecl *MD; - + switch (Component.getKind()) { default: llvm_unreachable("Unexpected vtable component kind!"); @@ -1176,7 +1176,7 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { ReturnAdjustment ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) { ReturnAdjustment Adjustment; - + if (!Offset.isEmpty()) { if (Offset.VirtualBase) { // Get the virtual base offset offset. @@ -1193,7 +1193,7 @@ ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) { Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity(); } - + return Adjustment; } @@ -1201,7 +1201,7 @@ BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset( BaseSubobject Base, BaseSubobject Derived) const { const CXXRecordDecl *BaseRD = Base.getBase(); const CXXRecordDecl *DerivedRD = Derived.getBase(); - + CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/true); @@ -1214,32 +1214,32 @@ BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset( BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path); CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset; - + if (Offset.VirtualBase) { // If we have a virtual base class, the non-virtual offset is relative // to the virtual base class offset. const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); - - /// Get the virtual base offset, relative to the most derived class + + /// Get the virtual base offset, relative to the most derived class /// layout. - OffsetToBaseSubobject += + OffsetToBaseSubobject += LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase); } else { - // Otherwise, the non-virtual offset is relative to the derived class + // Otherwise, the non-virtual offset is relative to the derived class // offset. OffsetToBaseSubobject += Derived.getBaseOffset(); } - + // Check if this path gives us the right base subobject. if (OffsetToBaseSubobject == Base.getBaseOffset()) { // Since we're going from the base class _to_ the derived class, we'll // invert the non-virtual offset here. Offset.NonVirtualOffset = -Offset.NonVirtualOffset; return Offset; - } + } } - + return BaseOffset(); } @@ -1249,13 +1249,13 @@ ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment( // Ignore adjustments for pure virtual member functions. if (Overrider.Method->isPure()) return ThisAdjustment(); - - BaseSubobject OverriddenBaseSubobject(MD->getParent(), + + BaseSubobject OverriddenBaseSubobject(MD->getParent(), BaseOffsetInLayoutClass); - + BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(), Overrider.Offset); - + // Compute the adjustment offset. BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject, OverriderBaseSubobject); @@ -1263,7 +1263,7 @@ ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment( return ThisAdjustment(); ThisAdjustment Adjustment; - + if (Offset.VirtualBase) { // Get the vcall offset map for this virtual base. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase]; @@ -1278,24 +1278,24 @@ ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment( /*BaseIsVirtual=*/true, /*OffsetInLayoutClass=*/ CharUnits::Zero()); - + VCallOffsets = Builder.getVCallOffsets(); } - + Adjustment.Virtual.Itanium.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD).getQuantity(); } // Set the non-virtual part of the adjustment. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity(); - + return Adjustment; } void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment) { if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { - assert(ReturnAdjustment.isEmpty() && + assert(ReturnAdjustment.isEmpty() && "Destructor can't have return adjustment!"); // Add both the complete destructor and the deleting destructor. @@ -1312,7 +1312,7 @@ void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD, } /// OverridesIndirectMethodInBase - Return whether the given member function -/// overrides any methods in the set of given bases. +/// overrides any methods in the set of given bases. /// Unlike OverridesMethodInBase, this checks "overriders of overriders". /// For example, if we have: /// @@ -1320,7 +1320,7 @@ void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD, /// struct B : A { virtual void f(); } /// struct C : B { virtual void f(); } /// -/// OverridesIndirectMethodInBase will return true if given C::f as the method +/// OverridesIndirectMethodInBase will return true if given C::f as the method /// and { A } as the set of bases. static bool OverridesIndirectMethodInBases( const CXXMethodDecl *MD, @@ -1333,7 +1333,7 @@ static bool OverridesIndirectMethodInBases( if (OverridesIndirectMethodInBases(OverriddenMD, Bases)) return true; } - + return false; } @@ -1347,9 +1347,9 @@ bool ItaniumVTableBuilder::IsOverriderUsed( return true; // We know now that Base (or a direct or indirect base of it) is a primary - // base in part of the class hierarchy, but not a primary base in the most + // base in part of the class hierarchy, but not a primary base in the most // derived class. - + // If the overrider is the first base in the primary base chain, we know // that the overrider will be used. if (Overrider->getParent() == FirstBaseInPrimaryBaseChain) @@ -1365,10 +1365,10 @@ bool ItaniumVTableBuilder::IsOverriderUsed( while (true) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); - + if (!PrimaryBase) break; - + if (Layout.isPrimaryBaseVirtual()) { assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() && "Primary base should always be at offset 0!"); @@ -1387,13 +1387,13 @@ bool ItaniumVTableBuilder::IsOverriderUsed( assert(Layout.getBaseClassOffset(PrimaryBase).isZero() && "Primary base should always be at offset 0!"); } - + if (!PrimaryBases.insert(PrimaryBase)) llvm_unreachable("Found a duplicate primary base!"); RD = PrimaryBase; } - + // If the final overrider is an override of one of the primary bases, // then we know that it will be used. return OverridesIndirectMethodInBases(Overrider, PrimaryBases); @@ -1446,13 +1446,13 @@ void ItaniumVTableBuilder::AddMethods( if (Layout.isPrimaryBaseVirtual()) { assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() && "Primary vbase should have a zero offset!"); - + const ASTRecordLayout &MostDerivedClassLayout = Context.getASTRecordLayout(MostDerivedClass); - - PrimaryBaseOffset = + + PrimaryBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase); - + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); @@ -1467,9 +1467,9 @@ void ItaniumVTableBuilder::AddMethods( } AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset), - PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, + PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, FirstBaseOffsetInLayoutClass, PrimaryBases); - + if (!PrimaryBases.insert(PrimaryBase)) llvm_unreachable("Found a duplicate primary base!"); } @@ -1486,31 +1486,31 @@ void ItaniumVTableBuilder::AddMethods( MD = MD->getCanonicalDecl(); // Get the final overrider. - FinalOverriders::OverriderInfo Overrider = + FinalOverriders::OverriderInfo Overrider = Overriders.getOverrider(MD, Base.getBaseOffset()); // Check if this virtual member function overrides a method in a primary // base. If this is the case, and the return type doesn't require adjustment // then we can just use the member function from the primary base. - if (const CXXMethodDecl *OverriddenMD = + if (const CXXMethodDecl *OverriddenMD = FindNearestOverriddenMethod(MD, PrimaryBases)) { - if (ComputeReturnAdjustmentBaseOffset(Context, MD, + if (ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD).isEmpty()) { // Replace the method info of the overridden method with our own // method. - assert(MethodInfoMap.count(OverriddenMD) && + assert(MethodInfoMap.count(OverriddenMD) && "Did not find the overridden method!"); MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD]; - + MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass, OverriddenMethodInfo.VTableIndex); assert(!MethodInfoMap.count(MD) && "Should not have method info for this method yet!"); - + MethodInfoMap.insert(std::make_pair(MD, MethodInfo)); MethodInfoMap.erase(OverriddenMD); - + // If the overridden method exists in a virtual base class or a direct // or indirect base class of a virtual base class, we need to emit a // thunk if we ever have a class hierarchy where the base class is not @@ -1529,11 +1529,11 @@ void ItaniumVTableBuilder::AddMethods( // the final overrider. BaseOffset ReturnAdjustmentOffset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD); - ReturnAdjustment ReturnAdjustment = + ReturnAdjustment ReturnAdjustment = ComputeReturnAdjustment(ReturnAdjustmentOffset); // This is a virtual thunk for the most derived class, add it. - AddThunk(Overrider.Method, + AddThunk(Overrider.Method, ThunkInfo(ThisAdjustment, ReturnAdjustment)); } } @@ -1577,7 +1577,7 @@ void ItaniumVTableBuilder::AddMethods( // Check if this overrider is going to be used. const CXXMethodDecl *OverriderMD = Overrider.Method; if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass, - FirstBaseInPrimaryBaseChain, + FirstBaseInPrimaryBaseChain, FirstBaseOffsetInLayoutClass)) { Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD)); continue; @@ -1587,13 +1587,13 @@ void ItaniumVTableBuilder::AddMethods( // We don't want to do this for pure virtual member functions. BaseOffset ReturnAdjustmentOffset; if (!OverriderMD->isPure()) { - ReturnAdjustmentOffset = + ReturnAdjustmentOffset = ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD); } - ReturnAdjustment ReturnAdjustment = + ReturnAdjustment ReturnAdjustment = ComputeReturnAdjustment(ReturnAdjustmentOffset); - + AddMethod(Overrider.Method, ReturnAdjustment); } } @@ -1604,14 +1604,14 @@ void ItaniumVTableBuilder::LayoutVTable() { /*BaseIsMorallyVirtual=*/false, MostDerivedClassIsVirtual, MostDerivedClassOffset); - + VisitedVirtualBasesSetTy VBases; - + // Determine the primary virtual bases. - DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset, + DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset, VBases); VBases.clear(); - + LayoutVTablesForVirtualBases(MostDerivedClass, VBases); // -fapple-kext adds an extra entry at end of vtbl. @@ -1630,14 +1630,14 @@ void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables( // Add vcall and vbase offsets for this vtable. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders, - Base, BaseIsVirtualInLayoutClass, + Base, BaseIsVirtualInLayoutClass, OffsetInLayoutClass); Components.append(Builder.components_begin(), Builder.components_end()); - + // Check if we need to add these vcall offsets. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) { VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()]; - + if (VCallOffsets.empty()) VCallOffsets = Builder.getVCallOffsets(); } @@ -1659,7 +1659,7 @@ void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables( // Now go through all virtual member functions and add them. PrimaryBasesSetVectorTy PrimaryBases; AddMethods(Base, OffsetInLayoutClass, - Base.getBase(), OffsetInLayoutClass, + Base.getBase(), OffsetInLayoutClass, PrimaryBases); const CXXRecordDecl *RD = Base.getBase(); @@ -1692,10 +1692,10 @@ void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables( const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); - + if (!PrimaryBase) break; - + if (Layout.isPrimaryBaseVirtual()) { // Check if this virtual primary base is a primary base in the layout // class. If it's not, we don't want to add it. @@ -1721,19 +1721,19 @@ ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual, CharUnits OffsetInLayoutClass) { // Itanium C++ ABI 2.5.2: - // Following the primary virtual table of a derived class are secondary + // Following the primary virtual table of a derived class are secondary // virtual tables for each of its proper base classes, except any primary // base(s) with which it shares its primary virtual table. const CXXRecordDecl *RD = Base.getBase(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); - + for (const auto &B : RD->bases()) { // Ignore virtual bases, we'll emit them later. if (B.isVirtual()) continue; - + const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); // Ignore bases that don't have a vtable. @@ -1753,11 +1753,11 @@ ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base, // Get the base offset of this base. CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl); CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset; - - CharUnits BaseOffsetInLayoutClass = + + CharUnits BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset; - - // Don't emit a secondary vtable for a primary base. We might however want + + // Don't emit a secondary vtable for a primary base. We might however want // to emit secondary vtables for other bases of this base. if (BaseDecl == PrimaryBase) { LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset), @@ -1778,7 +1778,7 @@ void ItaniumVTableBuilder::DeterminePrimaryVirtualBases( const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass, VisitedVirtualBasesSetTy &VBases) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - + // Check if this base has a primary base. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) { @@ -1794,13 +1794,13 @@ void ItaniumVTableBuilder::DeterminePrimaryVirtualBases( CharUnits PrimaryBaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(PrimaryBase); - - // We know that the base is not a primary base in the layout class if + + // We know that the base is not a primary base in the layout class if // the base offsets are different. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass) IsPrimaryVirtualBase = false; } - + if (IsPrimaryVirtualBase) PrimaryVirtualBases.insert(PrimaryBase); } @@ -1811,18 +1811,18 @@ void ItaniumVTableBuilder::DeterminePrimaryVirtualBases( const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); CharUnits BaseOffsetInLayoutClass; - + if (B.isVirtual()) { if (!VBases.insert(BaseDecl).second) continue; - + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); - BaseOffsetInLayoutClass = + BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl); } else { - BaseOffsetInLayoutClass = + BaseOffsetInLayoutClass = OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl); } @@ -1846,12 +1846,12 @@ void ItaniumVTableBuilder::LayoutVTablesForVirtualBases( VBases.insert(BaseDecl).second) { const ASTRecordLayout &MostDerivedClassLayout = Context.getASTRecordLayout(MostDerivedClass); - CharUnits BaseOffset = + CharUnits BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); - + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); - CharUnits BaseOffsetInLayoutClass = + CharUnits BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl); LayoutPrimaryAndSecondaryVTables( @@ -1860,7 +1860,7 @@ void ItaniumVTableBuilder::LayoutVTablesForVirtualBases( /*BaseIsVirtualInLayoutClass=*/true, BaseOffsetInLayoutClass); } - + // We only need to check the base for virtual base vtables if it actually // has virtual bases. if (BaseDecl->getNumVBases()) @@ -1897,7 +1897,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { AddressPointsByIndex.insert(std::make_pair(Index, Base)); } - + for (unsigned I = 0, E = Components.size(); I != E; ++I) { uint64_t Index = I; @@ -1910,7 +1910,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { case VTableComponent::CK_VCallOffset: Out << "vcall_offset (" - << Component.getVCallOffset().getQuantity() + << Component.getVCallOffset().getQuantity() << ")"; break; @@ -1925,17 +1925,17 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { << Component.getOffsetToTop().getQuantity() << ")"; break; - + case VTableComponent::CK_RTTI: Component.getRTTIDecl()->printQualifiedName(Out); Out << " RTTI"; break; - + case VTableComponent::CK_FunctionPointer: { const CXXMethodDecl *MD = Component.getFunctionDecl(); - std::string Str = - PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, + std::string Str = + PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, MD); Out << Str; if (MD->isPure()) @@ -1950,7 +1950,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.Return.isEmpty()) { Out << "\n [return adjustment: "; Out << Thunk.Return.NonVirtual << " non-virtual"; - + if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) { Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset; Out << " vbase offset offset"; @@ -1963,26 +1963,26 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.This.isEmpty()) { Out << "\n [this adjustment: "; Out << Thunk.This.NonVirtual << " non-virtual"; - + if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) { Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset; Out << " vcall offset offset"; } Out << ']'; - } + } } break; } - case VTableComponent::CK_CompleteDtorPointer: + case VTableComponent::CK_CompleteDtorPointer: case VTableComponent::CK_DeletingDtorPointer: { - bool IsComplete = + bool IsComplete = Component.getKind() == VTableComponent::CK_CompleteDtorPointer; - + const CXXDestructorDecl *DD = Component.getDestructorDecl(); - + DD->printQualifiedName(Out); if (IsComplete) Out << "() [complete]"; @@ -1998,15 +1998,15 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.This.isEmpty()) { Out << "\n [this adjustment: "; Out << Thunk.This.NonVirtual << " non-virtual"; - + if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) { Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset; Out << " vcall offset offset"; } - + Out << ']'; - } - } + } + } break; } @@ -2014,8 +2014,8 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { case VTableComponent::CK_UnusedFunctionPointer: { const CXXMethodDecl *MD = Component.getUnusedFunctionDecl(); - std::string Str = - PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, + std::string Str = + PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, MD); Out << "[unused] " << Str; if (MD->isPure()) @@ -2025,14 +2025,14 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { } Out << '\n'; - + // Dump the next address point. uint64_t NextIndex = Index + 1; if (AddressPointsByIndex.count(NextIndex)) { if (AddressPointsByIndex.count(NextIndex) == 1) { - const BaseSubobject &Base = + const BaseSubobject &Base = AddressPointsByIndex.find(NextIndex)->second; - + Out << " -- ("; Base.getBase()->printQualifiedName(Out); Out << ", " << Base.getBaseOffset().getQuantity(); @@ -2040,7 +2040,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { } else { CharUnits BaseOffset = AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset(); - + // We store the class names in a set to get a stable order. std::set<std::string> ClassNames; for (const auto &I : @@ -2060,10 +2060,10 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { } Out << '\n'; - + if (isBuildingConstructorVTable()) return; - + if (MostDerivedClass->getNumVBases()) { // We store the virtual base class names and their offsets in a map to get // a stable order. @@ -2074,7 +2074,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { CharUnits OffsetOffset = I.second; ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset)); } - + Out << "Virtual base offset offsets for '"; MostDerivedClass->printQualifiedName(Out); Out << "' ("; @@ -2086,17 +2086,17 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { Out << "\n"; } - + if (!Thunks.empty()) { // We store the method names in a map to get a stable order. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls; for (const auto &I : Thunks) { const CXXMethodDecl *MD = I.first; - std::string MethodName = + std::string MethodName = PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, MD); - + MethodNamesAndDecls.insert(std::make_pair(MethodName, MD)); } @@ -2113,12 +2113,12 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size(); Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n"; - + for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) { const ThunkInfo &Thunk = ThunksVector[I]; Out << llvm::format("%4d | ", I); - + // If this function pointer has a return pointer adjustment, dump it. if (!Thunk.Return.isEmpty()) { Out << "return adjustment: " << Thunk.Return.NonVirtual; @@ -2136,16 +2136,16 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.This.isEmpty()) { Out << "this adjustment: "; Out << Thunk.This.NonVirtual << " non-virtual"; - + if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) { Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset; Out << " vcall offset offset"; } } - + Out << '\n'; } - + Out << '\n'; } } @@ -2227,7 +2227,7 @@ uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) { MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD); if (I != MethodVTableIndices.end()) return I->second; - + const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent(); computeVTableRelatedInformation(RD); @@ -2241,8 +2241,8 @@ CharUnits ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase) { ClassPairTy ClassPair(RD, VBase); - - VirtualBaseClassOffsetOffsetsMapTy::iterator I = + + VirtualBaseClassOffsetOffsetsMapTy::iterator I = VirtualBaseClassOffsetOffsets.find(ClassPair); if (I != VirtualBaseClassOffsetOffsets.end()) return I->second; @@ -2258,10 +2258,10 @@ ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second)); } - + I = VirtualBaseClassOffsetOffsets.find(ClassPair); assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!"); - + return I->second; } @@ -2298,10 +2298,10 @@ ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) { // the rest of the vtable related information. if (!RD->getNumVBases()) return; - + const CXXRecordDecl *VBase = RD->vbases_begin()->getType()->getAsCXXRecordDecl(); - + if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase))) return; diff --git a/lib/Analysis/AnalysisDeclContext.cpp b/lib/Analysis/AnalysisDeclContext.cpp index 486fffbe12996..9557f68452ff0 100644 --- a/lib/Analysis/AnalysisDeclContext.cpp +++ b/lib/Analysis/AnalysisDeclContext.cpp @@ -56,13 +56,13 @@ using ManagedAnalysisMap = llvm::DenseMap<const void *, ManagedAnalysis *>; AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *d, const CFG::BuildOptions &buildOptions) - : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) { + : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) { cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; } AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *d) - : Manager(Mgr), D(d) { + : Manager(Mgr), D(d) { cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; } @@ -154,7 +154,7 @@ const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const { const VarDecl *VD = I.getVariable(); if (isSelfDecl(VD)) return dyn_cast<ImplicitParamDecl>(VD); - } + } } auto *CXXMethod = dyn_cast<CXXMethodDecl>(D); @@ -191,7 +191,7 @@ AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) { assert(forcedBlkExprs); if (const auto *e = dyn_cast<Expr>(stmt)) stmt = e->IgnoreParens(); - CFG::BuildOptions::ForcedBlkExprs::const_iterator itr = + CFG::BuildOptions::ForcedBlkExprs::const_iterator itr = forcedBlkExprs->find(stmt); assert(itr != forcedBlkExprs->end()); return itr->second; @@ -251,7 +251,7 @@ CFG *AnalysisDeclContext::getUnoptimizedCFG() { CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { if (cfgStmtMap) return cfgStmtMap.get(); - + if (CFG *c = getCFG()) { cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap())); return cfgStmtMap.get(); @@ -263,7 +263,7 @@ CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() { if (CFA) return CFA.get(); - + if (CFG *c = getCFG()) { CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c)); return CFA.get(); @@ -346,7 +346,7 @@ bool AnalysisDeclContext::isInStdNamespace(const Decl *D) { LocationContextManager &AnalysisDeclContext::getLocationContextManager() { assert(Manager && "Cannot create LocationContexts without an AnalysisDeclContextManager!"); - return Manager->getLocationContextManager(); + return Manager->getLocationContextManager(); } //===----------------------------------------------------------------------===// @@ -562,9 +562,9 @@ public: IgnoredContexts.insert(BR->getBlockDecl()); Visit(BR->getBlockDecl()->getBody()); } - + void VisitPseudoObjectExpr(PseudoObjectExpr *PE) { - for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(), + for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(), et = PE->semantics_end(); it != et; ++it) { Expr *Semantic = *it; if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) diff --git a/lib/Analysis/BodyFarm.cpp b/lib/Analysis/BodyFarm.cpp index b9fb15b2db25e..ac8fcdc912a02 100644 --- a/lib/Analysis/BodyFarm.cpp +++ b/lib/Analysis/BodyFarm.cpp @@ -50,33 +50,33 @@ namespace { class ASTMaker { public: ASTMaker(ASTContext &C) : C(C) {} - + /// Create a new BinaryOperator representing a simple assignment. BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty); - + /// Create a new BinaryOperator representing a comparison. BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS, BinaryOperator::Opcode Op); - + /// Create a new compound stmt using the provided statements. CompoundStmt *makeCompound(ArrayRef<Stmt*>); - + /// Create a new DeclRefExpr for the referenced variable. DeclRefExpr *makeDeclRefExpr(const VarDecl *D, bool RefersToEnclosingVariableOrCapture = false); - + /// Create a new UnaryOperator representing a dereference. UnaryOperator *makeDereference(const Expr *Arg, QualType Ty); - + /// Create an implicit cast for an integer conversion. Expr *makeIntegralCast(const Expr *Arg, QualType Ty); - + /// Create an implicit cast to a builtin boolean type. ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg); - + /// Create an implicit cast for lvalue-to-rvaluate conversions. ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty); - + /// Make RValue out of variable declaration, creating a temporary /// DeclRefExpr in the process. ImplicitCastExpr * @@ -92,10 +92,10 @@ public: /// Create an Objective-C ivar reference. ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar); - + /// Create a Return statement. ReturnStmt *makeReturn(const Expr *RetVal); - + /// Create an integer literal expression of the given type. IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty); @@ -342,7 +342,7 @@ static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) { // Nullable pointer, non-null iff function is a CXXRecordDecl. CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl(); QualType FlagType = Flag->getType().getNonReferenceType(); - auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl()); + auto *FlagRecordDecl = FlagType->getAsRecordDecl(); if (!FlagRecordDecl) { LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: " @@ -506,9 +506,9 @@ static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) { // block(); // } // } - + ASTMaker M(C); - + // (1) Create the call. CallExpr *CE = new (C) CallExpr( /*ASTContext=*/C, @@ -532,11 +532,11 @@ static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) { PredicateTy), M.makeIntegralCast(DoneValue, PredicateTy), PredicateTy); - + // (3) Create the compound statement. Stmt *Stmts[] = { B, CE }; CompoundStmt *CS = M.makeCompound(Stmts); - + // (4) Create the 'if' condition. ImplicitCastExpr *LValToRval = M.makeLvalueToRvalue( @@ -576,7 +576,7 @@ static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) { // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) { // block(); // } - // + // ASTMaker M(C); DeclRefExpr *DR = M.makeDeclRefExpr(PV); ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty); @@ -612,16 +612,16 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) const ParmVarDecl *NewValue = D->getParamDecl(1); QualType NewValueTy = NewValue->getType(); - + assert(OldValueTy == NewValueTy); - + const ParmVarDecl *TheValue = D->getParamDecl(2); QualType TheValueTy = TheValue->getType(); const PointerType *PT = TheValueTy->getAs<PointerType>(); if (!PT) return nullptr; QualType PointeeTy = PT->getPointeeType(); - + ASTMaker M(C); // Construct the comparison. Expr *Comparison = @@ -643,29 +643,29 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) PointeeTy), M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy), NewValueTy); - + Expr *BoolVal = M.makeObjCBool(true); Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal) : M.makeIntegralCast(BoolVal, ResultTy); Stmts[1] = M.makeReturn(RetVal); CompoundStmt *Body = M.makeCompound(Stmts); - + // Construct the else clause. BoolVal = M.makeObjCBool(false); RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal) : M.makeIntegralCast(BoolVal, ResultTy); Stmt *Else = M.makeReturn(RetVal); - + /// Construct the If. Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr, Comparison, Body, SourceLocation(), Else); - return If; + return If; } Stmt *BodyFarm::getBody(const FunctionDecl *D) { D = D->getCanonicalDecl(); - + Optional<Stmt *> &Val = Bodies[D]; if (Val.hasValue()) return Val.getValue(); @@ -692,7 +692,7 @@ Stmt *BodyFarm::getBody(const FunctionDecl *D) { .Case("dispatch_once", create_dispatch_once) .Default(nullptr); } - + if (FF) { Val = FF(C, D); } else if (Injector) { Val = Injector->getBody(D); } return Val.getValue(); diff --git a/lib/Analysis/CFG.cpp b/lib/Analysis/CFG.cpp index 8a3ab15458dd7..97829de7ace33 100644 --- a/lib/Analysis/CFG.cpp +++ b/lib/Analysis/CFG.cpp @@ -145,7 +145,7 @@ static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) { namespace { class CFGBuilder; - + /// The CFG builder uses a recursive algorithm to build the CFG. When /// we process an expression, sometimes we know that we must add the /// subexpressions as block-level expressions. For example: @@ -279,7 +279,7 @@ public: private: BumpVectorContext ctx; - + /// Automatic variables in order of declaration. AutomaticVarsTy Vars; @@ -366,7 +366,7 @@ class TryResult { public: TryResult() = default; TryResult(bool b) : X(b ? 1 : 0) {} - + bool isTrue() const { return X == 1; } bool isFalse() const { return X == 0; } bool isKnown() const { return X >= 0; } @@ -492,11 +492,11 @@ class CFGBuilder { bool badCFG = false; const CFG::BuildOptions &BuildOpts; - + // State to track for building switch statements. bool switchExclusivelyCovered = false; Expr::EvalResult *switchCond = nullptr; - + CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr; const Stmt *lastLookup = nullptr; @@ -516,7 +516,7 @@ public: std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement); bool alwaysAdd(const Stmt *stmt); - + private: // Visitors to walk an AST and construct the CFG. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); @@ -569,6 +569,7 @@ private: CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); + CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc); CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); CFGBlock *VisitReturnStmt(ReturnStmt *R); CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S); @@ -683,6 +684,25 @@ private: void findConstructionContexts(const ConstructionContextLayer *Layer, Stmt *Child); + // Scan all arguments of a call expression for a construction context. + // These sorts of call expressions don't have a common superclass, + // hence strict duck-typing. + template <typename CallLikeExpr, + typename = typename std::enable_if< + std::is_same<CallLikeExpr, CallExpr>::value || + std::is_same<CallLikeExpr, CXXConstructExpr>::value || + std::is_same<CallLikeExpr, ObjCMessageExpr>::value>> + void findConstructionContextsForArguments(CallLikeExpr *E) { + for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { + Expr *Arg = E->getArg(i); + if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue()) + findConstructionContexts( + ConstructionContextLayer::create(cfg->getBumpVectorContext(), + ConstructionContextItem(E, i)), + Arg); + } + } + // Unset the construction context after consuming it. This is done immediately // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so // there's no need to do this manually in every Visit... function. @@ -721,6 +741,19 @@ private: void addLocalScopeAndDtors(Stmt *S); + const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) { + if (!BuildOpts.AddRichCXXConstructors) + return nullptr; + + const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E); + if (!Layer) + return nullptr; + + cleanupConstructionContext(E); + return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(), + Layer); + } + // Interface to CFGBlock - adding CFGElements. void appendStmt(CFGBlock *B, const Stmt *S) { @@ -733,16 +766,10 @@ private: } void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) { - if (BuildOpts.AddRichCXXConstructors) { - if (const ConstructionContextLayer *Layer = - ConstructionContextMap.lookup(CE)) { - cleanupConstructionContext(CE); - if (const auto *CC = ConstructionContext::createFromLayers( - cfg->getBumpVectorContext(), Layer)) { - B->appendConstructor(CE, CC, cfg->getBumpVectorContext()); - return; - } - } + if (const ConstructionContext *CC = + retrieveAndCleanupConstructionContext(CE)) { + B->appendConstructor(CE, CC, cfg->getBumpVectorContext()); + return; } // No valid construction context found. Fall back to statement. @@ -753,18 +780,10 @@ private: if (alwaysAdd(CE) && cachedEntry) cachedEntry->second = B; - if (BuildOpts.AddRichCXXConstructors) { - if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(CE, *Context)) { - if (const ConstructionContextLayer *Layer = - ConstructionContextMap.lookup(CE)) { - cleanupConstructionContext(CE); - if (const auto *CC = ConstructionContext::createFromLayers( - cfg->getBumpVectorContext(), Layer)) { - B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext()); - return; - } - } - } + if (const ConstructionContext *CC = + retrieveAndCleanupConstructionContext(CE)) { + B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext()); + return; } // No valid construction context found. Fall back to statement. @@ -787,6 +806,20 @@ private: B->appendMemberDtor(FD, cfg->getBumpVectorContext()); } + void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) { + if (alwaysAdd(ME) && cachedEntry) + cachedEntry->second = B; + + if (const ConstructionContext *CC = + retrieveAndCleanupConstructionContext(ME)) { + B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext()); + return; + } + + B->appendStmt(const_cast<ObjCMessageExpr *>(ME), + cfg->getBumpVectorContext()); + } + void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); } @@ -1067,7 +1100,7 @@ private: bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { if (!BuildOpts.PruneTriviallyFalseEdges) return false; - return !S->isTypeDependent() && + return !S->isTypeDependent() && !S->isValueDependent() && S->EvaluateAsRValue(outResult, *Context); } @@ -1183,18 +1216,18 @@ inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, bool CFGBuilder::alwaysAdd(const Stmt *stmt) { bool shouldAdd = BuildOpts.alwaysAdd(stmt); - + if (!BuildOpts.forcedBlkExprs) return shouldAdd; - if (lastLookup == stmt) { + if (lastLookup == stmt) { if (cachedEntry) { assert(cachedEntry->first == stmt); return true; } return shouldAdd; } - + lastLookup = stmt; // Perform the lookup! @@ -1215,7 +1248,7 @@ bool CFGBuilder::alwaysAdd(const Stmt *stmt) { cachedEntry = &*itr; return true; } - + // FIXME: Add support for dependent-sized array types in C++? // Does it even make sense to build a CFG for an uninstantiated template? static const VariableArrayType *FindVA(const Type *t) { @@ -1232,6 +1265,8 @@ static const VariableArrayType *FindVA(const Type *t) { void CFGBuilder::consumeConstructionContext( const ConstructionContextLayer *Layer, Expr *E) { + assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || + isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!"); if (const ConstructionContextLayer *PreviouslyStoredLayer = ConstructionContextMap.lookup(E)) { (void)PreviouslyStoredLayer; @@ -1252,8 +1287,8 @@ void CFGBuilder::findConstructionContexts( if (!Child) return; - auto withExtraLayer = [this, Layer](Stmt *S) { - return ConstructionContextLayer::create(cfg->getBumpVectorContext(), S, + auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) { + return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item, Layer); }; @@ -1275,10 +1310,11 @@ void CFGBuilder::findConstructionContexts( case Stmt::CallExprClass: case Stmt::CXXMemberCallExprClass: case Stmt::CXXOperatorCallExprClass: - case Stmt::UserDefinedLiteralClass: { - auto *CE = cast<CallExpr>(Child); - if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(CE, *Context)) - consumeConstructionContext(Layer, CE); + case Stmt::UserDefinedLiteralClass: + case Stmt::ObjCMessageExprClass: { + auto *E = cast<Expr>(Child); + if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E)) + consumeConstructionContext(Layer, E); break; } case Stmt::ExprWithCleanupsClass: { @@ -1313,18 +1349,17 @@ void CFGBuilder::findConstructionContexts( // it indicates the beginning of a temporary object construction context, // so it shouldn't be found in the middle. However, if it is the beginning // of an elidable copy or move construction context, we need to include it. - if (const auto *CE = - dyn_cast_or_null<CXXConstructExpr>(Layer->getTriggerStmt())) { - if (CE->isElidable()) { - auto *MTE = cast<MaterializeTemporaryExpr>(Child); - findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr()); - } + if (Layer->getItem().getKind() == + ConstructionContextItem::ElidableConstructorKind) { + auto *MTE = cast<MaterializeTemporaryExpr>(Child); + findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr()); } break; } case Stmt::ConditionalOperatorClass: { auto *CO = cast<ConditionalOperator>(Child); - if (!dyn_cast_or_null<MaterializeTemporaryExpr>(Layer->getTriggerStmt())) { + if (Layer->getItem().getKind() != + ConstructionContextItem::MaterializationKind) { // If the object returned by the conditional operator is not going to be a // temporary object that needs to be immediately materialized, then // it must be C++17 with its mandatory copy elision. Do not yet promise @@ -1427,7 +1462,7 @@ std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { // If there is no target block that contains label, then we are looking // at an incomplete AST. Handle this by not registering a successor. if (LI == LabelMap.end()) continue; - + addSuccessor(B, LI->second.block); } @@ -1513,7 +1548,7 @@ CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { return Block; } -/// Retrieve the type of the temporary object whose lifetime was +/// Retrieve the type of the temporary object whose lifetime was /// extended by a local reference with the given initializer. static QualType getReferenceInitTemporaryType(const Expr *Init, bool *FoundMTE = nullptr) { @@ -1766,7 +1801,7 @@ LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { } /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement -/// that should create implicit scope (e.g. if/else substatements). +/// that should create implicit scope (e.g. if/else substatements). void CFGBuilder::addLocalScopeForStmt(Stmt *S) { if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && !BuildOpts.AddScopes) @@ -2101,6 +2136,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { case Stmt::ObjCForCollectionStmtClass: return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); + case Stmt::ObjCMessageExprClass: + return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc); + case Stmt::OpaqueValueExprClass: return Block; @@ -2383,12 +2421,7 @@ CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { if (!boundType.isNull()) calleeType = boundType; } - // FIXME: Once actually implemented, this construction context layer should - // include the number of the argument as well. - for (auto Arg: C->arguments()) { - findConstructionContexts( - ConstructionContextLayer::create(cfg->getBumpVectorContext(), C), Arg); - } + findConstructionContextsForArguments(C); // If this is a call to a no-return function, this stops the block here. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); @@ -2574,7 +2607,7 @@ CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, // At least one of this or the above will be run. return addStmt(BCO->getCommon()); } - + return addStmt(condExpr); } @@ -2583,7 +2616,7 @@ CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { // CFG entirely. if (isa<LabelDecl>(*DS->decl_begin())) return Block; - + // This case also handles static_asserts. if (DS->isSingleDecl()) return VisitDeclSubExpr(DS); @@ -3032,7 +3065,7 @@ CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { } return LastBlock; } - + CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { // Goto is a control-flow statement. Thus we stop processing the current // block and create a new one. @@ -3146,7 +3179,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { else if (badCFG) return nullptr; } - + // Because of short-circuit evaluation, the condition of the loop can span // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that // evaluate the condition. @@ -3188,8 +3221,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { const DeclStmt *DS = F->getConditionVariableDeclStmt(); assert(DS->isSingleDecl()); findConstructionContexts( - ConstructionContextLayer::create(cfg->getBumpVectorContext(), - const_cast<DeclStmt *>(DS)), + ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS), Init); appendStmt(Block, DS); EntryConditionBlock = addStmt(Init); @@ -3214,7 +3246,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { // Link up the loop-back block to the entry condition block. addSuccessor(TransitionBlock, EntryConditionBlock); - + // The condition block is the implicit successor for any code above the loop. Succ = EntryConditionBlock; @@ -3334,7 +3366,7 @@ CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { CFGBlock *LoopBackBlock = nullptr; Succ = LoopBackBlock = createBlock(); LoopBackBlock->setLoopTarget(S); - + BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); ContinueJumpTarget = JumpTarget(Succ, ScopePos); @@ -3401,7 +3433,7 @@ CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { // Add the PseudoObject as the last thing. appendStmt(Block, E); - CFGBlock *lastBlock = Block; + CFGBlock *lastBlock = Block; // Before that, evaluate all of the semantics in order. In // CFG-land, that means appending them in reverse order. @@ -3580,6 +3612,16 @@ CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { return VisitStmt(S, AddStmtChoice::AlwaysAdd); } +CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME, + AddStmtChoice asc) { + findConstructionContextsForArguments(ME); + + autoCreateBlock(); + appendObjCMessage(Block, ME); + + return VisitChildren(ME); +} + CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { // If we were in the middle of a block we stop processing that block. if (badCFG) @@ -3734,7 +3776,7 @@ CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, // VLA types have expressions that must be evaluated. CFGBlock *lastBlock = Block; - + if (E->isArgumentType()) { for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) @@ -3863,7 +3905,7 @@ CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { return LastBlock; } - + static bool shouldAddCase(bool &switchExclusivelyCovered, const Expr::EvalResult *switchCond, const CaseStmt *CS, @@ -3878,7 +3920,7 @@ static bool shouldAddCase(bool &switchExclusivelyCovered, // Evaluate the LHS of the case value. const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); const llvm::APSInt &condInt = switchCond->Val.getInt(); - + if (condInt == lhsInt) { addCase = true; switchExclusivelyCovered = true; @@ -3897,7 +3939,7 @@ static bool shouldAddCase(bool &switchExclusivelyCovered, else addCase = true; } - return addCase; + return addCase; } CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { @@ -4069,7 +4111,7 @@ CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { CFGBlock *CatchBlock = Block; if (!CatchBlock) CatchBlock = createBlock(); - + // CXXCatchStmt is more than just a label. They have semantic meaning // as well, as they implicitly "initialize" the catch variable. Add // it to the CFG as a CFGElement so that the control-flow of these @@ -4244,6 +4286,11 @@ CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc) { + // If the constructor takes objects as arguments by value, we need to properly + // construct these objects. Construction contexts we find here aren't for the + // constructor C, they're for its arguments only. + findConstructionContextsForArguments(C); + autoCreateBlock(); appendConstructor(Block, C); @@ -4624,7 +4671,7 @@ CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { const RecordType *recordType = ty->getAs<RecordType>(); const CXXRecordDecl *classDecl = cast<CXXRecordDecl>(recordType->getDecl()); - return classDecl->getDestructor(); + return classDecl->getDestructor(); } case CFGElement::DeleteDtor: { const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr(); @@ -4722,7 +4769,7 @@ public: for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { unsigned j = 1; for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; - BI != BEnd; ++BI, ++j ) { + BI != BEnd; ++BI, ++j ) { if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { const Stmt *stmt= SE->getStmt(); std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); @@ -4961,7 +5008,7 @@ static void print_construction_context(raw_ostream &OS, OS << ", "; const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC); print_initializer(OS, Helper, SICC->getCXXCtorInitializer()); - break; + return; } case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: { OS << ", "; @@ -5012,6 +5059,17 @@ static void print_construction_context(raw_ostream &OS, Stmts.push_back(TOCC->getConstructorAfterElision()); break; } + case ConstructionContext::ArgumentKind: { + const auto *ACC = cast<ArgumentConstructionContext>(CC); + if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) { + OS << ", "; + Helper.handledStmt(const_cast<Stmt *>(BTE), OS); + } + OS << ", "; + Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS); + OS << "+" << ACC->getIndex(); + return; + } } for (auto I: Stmts) if (I) { @@ -5151,7 +5209,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, // Print the header. if (ShowColors) OS.changeColor(raw_ostream::YELLOW, true); - + OS << "\n [B" << B.getBlockID(); if (&B == &cfg->getEntry()) @@ -5164,7 +5222,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, OS << " (NORETURN)]\n"; else OS << "]\n"; - + if (ShowColors) OS.resetColor(); @@ -5235,7 +5293,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP); TPrinter.print(B.getTerminator()); OS << '\n'; - + if (ShowColors) OS.resetColor(); } @@ -5254,7 +5312,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, if (ShowColors) OS.changeColor(Color); - + for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); I != E; ++I, ++i) { if (i % 10 == 8) @@ -5271,7 +5329,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, if (!Reachable) OS << "(Unreachable)"; } - + if (ShowColors) OS.resetColor(); diff --git a/lib/Analysis/CFGReachabilityAnalysis.cpp b/lib/Analysis/CFGReachabilityAnalysis.cpp index 6f557e092fd7f..cdad5b57aee8a 100644 --- a/lib/Analysis/CFGReachabilityAnalysis.cpp +++ b/lib/Analysis/CFGReachabilityAnalysis.cpp @@ -27,13 +27,13 @@ CFGReverseBlockReachabilityAnalysis::CFGReverseBlockReachabilityAnalysis( bool CFGReverseBlockReachabilityAnalysis::isReachable(const CFGBlock *Src, const CFGBlock *Dst) { const unsigned DstBlockID = Dst->getBlockID(); - + // If we haven't analyzed the destination node, run the analysis now if (!analyzed[DstBlockID]) { mapReachability(Dst); analyzed[DstBlockID] = true; } - + // Return the cached result return reachable[DstBlockID][Src->getBlockID()]; } @@ -43,10 +43,10 @@ bool CFGReverseBlockReachabilityAnalysis::isReachable(const CFGBlock *Src, void CFGReverseBlockReachabilityAnalysis::mapReachability(const CFGBlock *Dst) { SmallVector<const CFGBlock *, 11> worklist; llvm::BitVector visited(analyzed.size()); - + ReachableSet &DstReachability = reachable[Dst->getBlockID()]; DstReachability.resize(analyzed.size(), false); - + // Start searching from the destination node, since we commonly will perform // multiple queries relating to a destination node. worklist.push_back(Dst); @@ -58,7 +58,7 @@ void CFGReverseBlockReachabilityAnalysis::mapReachability(const CFGBlock *Dst) { if (visited[block->getBlockID()]) continue; visited[block->getBlockID()] = true; - + // Update reachability information for this node -> Dst if (!firstRun) { // Don't insert Dst -> Dst unless it was a predecessor of itself @@ -66,9 +66,9 @@ void CFGReverseBlockReachabilityAnalysis::mapReachability(const CFGBlock *Dst) { } else firstRun = false; - + // Add the predecessors to the worklist. - for (CFGBlock::const_pred_iterator i = block->pred_begin(), + for (CFGBlock::const_pred_iterator i = block->pred_begin(), e = block->pred_end(); i != e; ++i) { if (*i) worklist.push_back(*i); diff --git a/lib/Analysis/CFGStmtMap.cpp b/lib/Analysis/CFGStmtMap.cpp index 19b80191f7a77..3eed0d52f848a 100644 --- a/lib/Analysis/CFGStmtMap.cpp +++ b/lib/Analysis/CFGStmtMap.cpp @@ -24,7 +24,7 @@ static SMap *AsMap(void *m) { return (SMap*) m; } CFGStmtMap::~CFGStmtMap() { delete AsMap(M); } -CFGBlock *CFGStmtMap::getBlock(Stmt *S) { +CFGBlock *CFGStmtMap::getBlock(Stmt *S) { SMap *SM = AsMap(M); Stmt *X = S; @@ -53,17 +53,17 @@ static void Accumulate(SMap &SM, CFGBlock *B) { Optional<CFGStmt> CS = CE.getAs<CFGStmt>(); if (!CS) continue; - + CFGBlock *&Entry = SM[CS->getStmt()]; // If 'Entry' is already initialized (e.g., a terminator was already), // skip. if (Entry) continue; - + Entry = B; - + } - + // Look at the label of the block. if (Stmt *Label = B->getLabel()) SM[Label] = B; @@ -82,7 +82,7 @@ CFGStmtMap *CFGStmtMap::Build(CFG *C, ParentMap *PM) { SMap *SM = new SMap(); // Walk all blocks, accumulating the block-level expressions, labels, - // and terminators. + // and terminators. for (CFG::iterator I = C->begin(), E = C->end(); I != E; ++I) Accumulate(*SM, *I); diff --git a/lib/Analysis/CallGraph.cpp b/lib/Analysis/CallGraph.cpp index fb6d7e87a9a31..bac00680ffda3 100644 --- a/lib/Analysis/CallGraph.cpp +++ b/lib/Analysis/CallGraph.cpp @@ -84,7 +84,7 @@ public: void VisitObjCMessageExpr(ObjCMessageExpr *ME) { if (ObjCInterfaceDecl *IDecl = ME->getReceiverInterface()) { Selector Sel = ME->getSelector(); - + // Find the callee definition within the same translation unit. Decl *D = nullptr; if (ME->isInstanceMessage()) diff --git a/lib/Analysis/CocoaConventions.cpp b/lib/Analysis/CocoaConventions.cpp index 4d57623e21611..b2d416c171a10 100644 --- a/lib/Analysis/CocoaConventions.cpp +++ b/lib/Analysis/CocoaConventions.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements cocoa naming convention analysis. +// This file implements cocoa naming convention analysis. // //===----------------------------------------------------------------------===// @@ -34,15 +34,15 @@ bool cocoa::isRefType(QualType RetTy, StringRef Prefix, return false; RetTy = TD->getDecl()->getUnderlyingType(); } - + if (Name.empty()) return false; - + // Is the type void*? const PointerType* PT = RetTy->getAs<PointerType>(); if (!(PT->getPointeeType().getUnqualifiedType()->isVoidType())) return false; - + // Does the name start with the prefix? return Name.startswith(Prefix); } @@ -66,32 +66,32 @@ bool coreFoundation::isCFObjectRef(QualType T) { bool cocoa::isCocoaObjectRef(QualType Ty) { if (!Ty->isObjCObjectPointerType()) return false; - + const ObjCObjectPointerType *PT = Ty->getAs<ObjCObjectPointerType>(); - + // Can be true for objects with the 'NSObject' attribute. if (!PT) return true; - + // We assume that id<..>, id, Class, and Class<..> all represent tracked // objects. if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() || PT->isObjCClassType() || PT->isObjCQualifiedClassType()) return true; - + // Does the interface subclass NSObject? // FIXME: We can memoize here if this gets too expensive. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); - + // Assume that anything declared with a forward declaration and no // @interface subclasses NSObject. if (!ID->hasDefinition()) return true; - + for ( ; ID ; ID = ID->getSuperClass()) if (ID->getIdentifier()->getName() == "NSObject") return true; - + return false; } @@ -101,11 +101,11 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { const IdentifierInfo *ident = fn->getIdentifier(); if (!ident) return false; StringRef functionName = ident->getName(); - + StringRef::iterator it = functionName.begin(); StringRef::iterator start = it; StringRef::iterator endI = functionName.end(); - + while (true) { // Scan for the start of 'create' or 'copy'. for ( ; it != endI ; ++it) { @@ -124,7 +124,7 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { // Did we hit the end of the string? If so, we didn't find a match. if (it == endI) return false; - + // Scan for *lowercase* 'reate' or 'opy', followed by no lowercase // character. StringRef suffix = functionName.substr(it - start); @@ -137,10 +137,10 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { // Keep scanning. continue; } - + if (it == endI || !isLowercase(*it)) return true; - + // If we matched a lowercase character, it isn't the end of the // word. Keep scanning. } diff --git a/lib/Analysis/ConstructionContext.cpp b/lib/Analysis/ConstructionContext.cpp index ed1e632432172..8169d4a93a6d9 100644 --- a/lib/Analysis/ConstructionContext.cpp +++ b/lib/Analysis/ConstructionContext.cpp @@ -15,15 +15,17 @@ //===----------------------------------------------------------------------===// #include "clang/Analysis/ConstructionContext.h" +#include "clang/AST/ExprObjC.h" using namespace clang; const ConstructionContextLayer * -ConstructionContextLayer::create(BumpVectorContext &C, TriggerTy Trigger, +ConstructionContextLayer::create(BumpVectorContext &C, + const ConstructionContextItem &Item, const ConstructionContextLayer *Parent) { ConstructionContextLayer *CC = C.getAllocator().Allocate<ConstructionContextLayer>(); - return new (CC) ConstructionContextLayer(Trigger, Parent); + return new (CC) ConstructionContextLayer(Item, Parent); } bool ConstructionContextLayer::isStrictlyMoreSpecificThan( @@ -32,7 +34,7 @@ bool ConstructionContextLayer::isStrictlyMoreSpecificThan( while (true) { if (!Other) return Self; - if (!Self || !Self->isSameLayer(Other)) + if (!Self || !(Self->Item == Other->Item)) return false; Self = Self->getParent(); Other = Other->getParent(); @@ -40,145 +42,176 @@ bool ConstructionContextLayer::isStrictlyMoreSpecificThan( llvm_unreachable("The above loop can only be terminated via return!"); } +const ConstructionContext * +ConstructionContext::createMaterializedTemporaryFromLayers( + BumpVectorContext &C, const MaterializeTemporaryExpr *MTE, + const CXXBindTemporaryExpr *BTE, + const ConstructionContextLayer *ParentLayer) { + assert(MTE); + + // If the object requires destruction and is not lifetime-extended, + // then it must have a BTE within its MTE, otherwise it shouldn't. + // FIXME: This should be an assertion. + if (!BTE && !(MTE->getType().getCanonicalType()->getAsCXXRecordDecl() + ->hasTrivialDestructor() || + MTE->getStorageDuration() != SD_FullExpression)) { + return nullptr; + } + + // If the temporary is lifetime-extended, don't save the BTE, + // because we don't need a temporary destructor, but an automatic + // destructor. + if (MTE->getStorageDuration() != SD_FullExpression) { + BTE = nullptr; + } + + // Handle pre-C++17 copy and move elision. + const CXXConstructExpr *ElidedCE = nullptr; + const ConstructionContext *ElidedCC = nullptr; + if (ParentLayer) { + const ConstructionContextItem &ElidedItem = ParentLayer->getItem(); + assert(ElidedItem.getKind() == + ConstructionContextItem::ElidableConstructorKind); + ElidedCE = cast<CXXConstructExpr>(ElidedItem.getStmt()); + assert(ElidedCE->isElidable()); + // We're creating a construction context that might have already + // been created elsewhere. Maybe we should unique our construction + // contexts. That's what we often do, but in this case it's unlikely + // to bring any benefits. + ElidedCC = createFromLayers(C, ParentLayer->getParent()); + if (!ElidedCC) { + // We may fail to create the elided construction context. + // In this case, skip copy elision entirely. + return create<SimpleTemporaryObjectConstructionContext>(C, BTE, MTE); + } + return create<ElidedTemporaryObjectConstructionContext>( + C, BTE, MTE, ElidedCE, ElidedCC); + } + + // This is a normal temporary. + assert(!ParentLayer); + return create<SimpleTemporaryObjectConstructionContext>(C, BTE, MTE); +} + +const ConstructionContext *ConstructionContext::createBoundTemporaryFromLayers( + BumpVectorContext &C, const CXXBindTemporaryExpr *BTE, + const ConstructionContextLayer *ParentLayer) { + if (!ParentLayer) { + // A temporary object that doesn't require materialization. + // In particular, it shouldn't require copy elision, because + // copy/move constructors take a reference, which requires + // materialization to obtain the glvalue. + return create<SimpleTemporaryObjectConstructionContext>(C, BTE, + /*MTE=*/nullptr); + } + + const ConstructionContextItem &ParentItem = ParentLayer->getItem(); + switch (ParentItem.getKind()) { + case ConstructionContextItem::VariableKind: { + const auto *DS = cast<DeclStmt>(ParentItem.getStmt()); + assert(!cast<VarDecl>(DS->getSingleDecl())->getType().getCanonicalType() + ->getAsCXXRecordDecl()->hasTrivialDestructor()); + return create<CXX17ElidedCopyVariableConstructionContext>(C, DS, BTE); + } + case ConstructionContextItem::NewAllocatorKind: { + llvm_unreachable("This context does not accept a bound temporary!"); + } + case ConstructionContextItem::ReturnKind: { + assert(ParentLayer->isLast()); + const auto *RS = cast<ReturnStmt>(ParentItem.getStmt()); + assert(!RS->getRetValue()->getType().getCanonicalType() + ->getAsCXXRecordDecl()->hasTrivialDestructor()); + return create<CXX17ElidedCopyReturnedValueConstructionContext>(C, RS, + BTE); + } + + case ConstructionContextItem::MaterializationKind: { + // No assert. We may have an elidable copy on the grandparent layer. + const auto *MTE = cast<MaterializeTemporaryExpr>(ParentItem.getStmt()); + return createMaterializedTemporaryFromLayers(C, MTE, BTE, + ParentLayer->getParent()); + } + case ConstructionContextItem::TemporaryDestructorKind: { + llvm_unreachable("Duplicate CXXBindTemporaryExpr in the AST!"); + } + case ConstructionContextItem::ElidedDestructorKind: { + llvm_unreachable("Elided destructor items are not produced by the CFG!"); + } + case ConstructionContextItem::ElidableConstructorKind: { + llvm_unreachable("Materialization is necessary to put temporary into a " + "copy or move constructor!"); + } + case ConstructionContextItem::ArgumentKind: { + assert(ParentLayer->isLast()); + const auto *E = cast<Expr>(ParentItem.getStmt()); + assert(isa<CallExpr>(E) || isa<CXXConstructExpr>(E) || + isa<ObjCMessageExpr>(E)); + return create<ArgumentConstructionContext>(C, E, ParentItem.getIndex(), + BTE); + } + case ConstructionContextItem::InitializerKind: { + assert(ParentLayer->isLast()); + const auto *I = ParentItem.getCXXCtorInitializer(); + assert(!I->getAnyMember()->getType().getCanonicalType() + ->getAsCXXRecordDecl()->hasTrivialDestructor()); + return create<CXX17ElidedCopyConstructorInitializerConstructionContext>( + C, I, BTE); + } + } // switch (ParentItem.getKind()) + + llvm_unreachable("Unexpected construction context with destructor!"); +} + const ConstructionContext *ConstructionContext::createFromLayers( BumpVectorContext &C, const ConstructionContextLayer *TopLayer) { // Before this point all we've had was a stockpile of arbitrary layers. // Now validate that it is shaped as one of the finite amount of expected // patterns. - if (const Stmt *S = TopLayer->getTriggerStmt()) { - if (const auto *DS = dyn_cast<DeclStmt>(S)) { - assert(TopLayer->isLast()); - return create<SimpleVariableConstructionContext>(C, DS); - } - if (const auto *NE = dyn_cast<CXXNewExpr>(S)) { - assert(TopLayer->isLast()); - return create<NewAllocatedObjectConstructionContext>(C, NE); - } - if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(S)) { - const MaterializeTemporaryExpr *MTE = nullptr; - assert(BTE->getType().getCanonicalType() - ->getAsCXXRecordDecl()->hasNonTrivialDestructor()); - // For temporaries with destructors, there may or may not be - // lifetime extension on the parent layer. - if (const ConstructionContextLayer *ParentLayer = TopLayer->getParent()) { - // C++17 *requires* elision of the constructor at the return site - // and at variable/member initialization site, while previous standards - // were allowing an optional elidable constructor. - // This is the C++17 copy-elided construction into a ctor initializer. - if (const CXXCtorInitializer *I = ParentLayer->getTriggerInit()) { - return create< - CXX17ElidedCopyConstructorInitializerConstructionContext>(C, - I, BTE); - } - assert(ParentLayer->getTriggerStmt() && - "Non-statement-based layers have been handled above!"); - // This is the normal, non-C++17 case: a temporary object which has - // both destruction and materialization info attached to it in the AST. - if ((MTE = dyn_cast<MaterializeTemporaryExpr>( - ParentLayer->getTriggerStmt()))) { - if (MTE->getStorageDuration() != SD_FullExpression) { - // If the temporary is lifetime-extended, don't save the BTE, - // because we don't need a temporary destructor, but an automatic - // destructor. - BTE = nullptr; - } - - // Handle pre-C++17 copy and move elision. - const CXXConstructExpr *ElidedCE = nullptr; - const ConstructionContext *ElidedCC = nullptr; - if (const ConstructionContextLayer *ElidedLayer = - ParentLayer->getParent()) { - ElidedCE = cast<CXXConstructExpr>(ElidedLayer->getTriggerStmt()); - assert(ElidedCE->isElidable()); - // We're creating a construction context that might have already - // been created elsewhere. Maybe we should unique our construction - // contexts. That's what we often do, but in this case it's unlikely - // to bring any benefits. - ElidedCC = createFromLayers(C, ElidedLayer->getParent()); - if (!ElidedCC) { - // We may fail to create the elided construction context. - // In this case, skip copy elision entirely. - return create<SimpleTemporaryObjectConstructionContext>(C, BTE, - MTE); - } else { - return create<ElidedTemporaryObjectConstructionContext>( - C, BTE, MTE, ElidedCE, ElidedCC); - } - } - assert(ParentLayer->isLast()); - return create<SimpleTemporaryObjectConstructionContext>(C, BTE, MTE); - } - assert(ParentLayer->isLast()); - - // This is a constructor into a function argument. Not implemented yet. - if (isa<CallExpr>(ParentLayer->getTriggerStmt())) - return nullptr; - // This is C++17 copy-elided construction into return statement. - if (auto *RS = dyn_cast<ReturnStmt>(ParentLayer->getTriggerStmt())) { - assert(!RS->getRetValue()->getType().getCanonicalType() - ->getAsCXXRecordDecl()->hasTrivialDestructor()); - return create<CXX17ElidedCopyReturnedValueConstructionContext>(C, - RS, BTE); - } - // This is C++17 copy-elided construction into a simple variable. - if (auto *DS = dyn_cast<DeclStmt>(ParentLayer->getTriggerStmt())) { - assert(!cast<VarDecl>(DS->getSingleDecl())->getType() - .getCanonicalType()->getAsCXXRecordDecl() - ->hasTrivialDestructor()); - return create<CXX17ElidedCopyVariableConstructionContext>(C, DS, BTE); - } - llvm_unreachable("Unexpected construction context with destructor!"); - } - // A temporary object that doesn't require materialization. - // In particular, it shouldn't require copy elision, because - // copy/move constructors take a reference, which requires - // materialization to obtain the glvalue. - return create<SimpleTemporaryObjectConstructionContext>(C, BTE, - /*MTE=*/nullptr); - } - if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(S)) { - // If the object requires destruction and is not lifetime-extended, - // then it must have a BTE within its MTE. - // FIXME: This should be an assertion. - if (!(MTE->getType().getCanonicalType() - ->getAsCXXRecordDecl()->hasTrivialDestructor() || - MTE->getStorageDuration() != SD_FullExpression)) - return nullptr; - - // Handle pre-C++17 copy and move elision. - const CXXConstructExpr *ElidedCE = nullptr; - const ConstructionContext *ElidedCC = nullptr; - if (const ConstructionContextLayer *ElidedLayer = TopLayer->getParent()) { - ElidedCE = cast<CXXConstructExpr>(ElidedLayer->getTriggerStmt()); - assert(ElidedCE->isElidable()); - // We're creating a construction context that might have already - // been created elsewhere. Maybe we should unique our construction - // contexts. That's what we often do, but in this case it's unlikely - // to bring any benefits. - ElidedCC = createFromLayers(C, ElidedLayer->getParent()); - if (!ElidedCC) { - // We may fail to create the elided construction context. - // In this case, skip copy elision entirely. - return create<SimpleTemporaryObjectConstructionContext>(C, nullptr, - MTE); - } - return create<ElidedTemporaryObjectConstructionContext>( - C, nullptr, MTE, ElidedCE, ElidedCC); - } - assert(TopLayer->isLast()); - return create<SimpleTemporaryObjectConstructionContext>(C, nullptr, MTE); - } - if (const auto *RS = dyn_cast<ReturnStmt>(S)) { - assert(TopLayer->isLast()); - return create<SimpleReturnedValueConstructionContext>(C, RS); - } - // This is a constructor into a function argument. Not implemented yet. - if (isa<CallExpr>(TopLayer->getTriggerStmt())) - return nullptr; - llvm_unreachable("Unexpected construction context with statement!"); - } else if (const CXXCtorInitializer *I = TopLayer->getTriggerInit()) { + const ConstructionContextItem &TopItem = TopLayer->getItem(); + switch (TopItem.getKind()) { + case ConstructionContextItem::VariableKind: { + assert(TopLayer->isLast()); + const auto *DS = cast<DeclStmt>(TopItem.getStmt()); + return create<SimpleVariableConstructionContext>(C, DS); + } + case ConstructionContextItem::NewAllocatorKind: { + assert(TopLayer->isLast()); + const auto *NE = cast<CXXNewExpr>(TopItem.getStmt()); + return create<NewAllocatedObjectConstructionContext>(C, NE); + } + case ConstructionContextItem::ReturnKind: { assert(TopLayer->isLast()); + const auto *RS = cast<ReturnStmt>(TopItem.getStmt()); + return create<SimpleReturnedValueConstructionContext>(C, RS); + } + case ConstructionContextItem::MaterializationKind: { + const auto *MTE = cast<MaterializeTemporaryExpr>(TopItem.getStmt()); + return createMaterializedTemporaryFromLayers(C, MTE, /*BTE=*/nullptr, + TopLayer->getParent()); + } + case ConstructionContextItem::TemporaryDestructorKind: { + const auto *BTE = cast<CXXBindTemporaryExpr>(TopItem.getStmt()); + assert(BTE->getType().getCanonicalType()->getAsCXXRecordDecl() + ->hasNonTrivialDestructor()); + return createBoundTemporaryFromLayers(C, BTE, TopLayer->getParent()); + } + case ConstructionContextItem::ElidedDestructorKind: { + llvm_unreachable("Elided destructor items are not produced by the CFG!"); + } + case ConstructionContextItem::ElidableConstructorKind: { + llvm_unreachable("The argument needs to be materialized first!"); + } + case ConstructionContextItem::InitializerKind: { + assert(TopLayer->isLast()); + const CXXCtorInitializer *I = TopItem.getCXXCtorInitializer(); return create<SimpleConstructorInitializerConstructionContext>(C, I); } + case ConstructionContextItem::ArgumentKind: { + assert(TopLayer->isLast()); + const auto *E = cast<Expr>(TopItem.getStmt()); + return create<ArgumentConstructionContext>(C, E, TopItem.getIndex(), + /*BTE=*/nullptr); + } + } // switch (TopItem.getKind()) llvm_unreachable("Unexpected construction context!"); } diff --git a/lib/Analysis/Consumed.cpp b/lib/Analysis/Consumed.cpp index a46386e2d13d9..bc81a71b3d91e 100644 --- a/lib/Analysis/Consumed.cpp +++ b/lib/Analysis/Consumed.cpp @@ -40,7 +40,7 @@ // TODO: Adjust states of args to constructors in the same way that arguments to // function calls are handled. // TODO: Use information from tests in for- and while-loop conditional. -// TODO: Add notes about the actual and expected state for +// TODO: Add notes about the actual and expected state for // TODO: Correctly identify unreachable blocks when chaining boolean operators. // TODO: Adjust the parser and AttributesList class to support lists of // identifiers. @@ -124,30 +124,30 @@ static bool isCallableInState(const CallableWhenAttr *CWAttr, case CallableWhenAttr::Unknown: MappedAttrState = CS_Unknown; break; - + case CallableWhenAttr::Unconsumed: MappedAttrState = CS_Unconsumed; break; - + case CallableWhenAttr::Consumed: MappedAttrState = CS_Consumed; break; } - + if (MappedAttrState == State) return true; } - + return false; } static bool isConsumableType(const QualType &QT) { if (QT->isPointerType() || QT->isReferenceType()) return false; - + if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl()) return RD->hasAttr<ConsumableAttr>(); - + return false; } @@ -250,13 +250,13 @@ static StringRef stateToString(ConsumedState State) { switch (State) { case consumed::CS_None: return "none"; - + case consumed::CS_Unknown: return "unknown"; - + case consumed::CS_Unconsumed: return "unconsumed"; - + case consumed::CS_Consumed: return "consumed"; } @@ -307,7 +307,7 @@ class PropagationInfo { VarTestResult LTest; VarTestResult RTest; }; - + union { ConsumedState State; VarTestResult VarTest; @@ -315,7 +315,7 @@ class PropagationInfo { const CXXBindTemporaryExpr *Tmp; BinTestTy BinTest; }; - + public: PropagationInfo() = default; PropagationInfo(const VarTestResult &VarTest) @@ -326,7 +326,7 @@ public: VarTest.Var = Var; VarTest.TestsFor = TestsFor; } - + PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp, const VarTestResult <est, const VarTestResult &RTest) : InfoType(IT_BinTest) { @@ -335,7 +335,7 @@ public: BinTest.LTest = LTest; BinTest.RTest = RTest; } - + PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp, const VarDecl *LVar, ConsumedState LTestsFor, const VarDecl *RVar, ConsumedState RTestsFor) @@ -347,46 +347,46 @@ public: BinTest.RTest.Var = RVar; BinTest.RTest.TestsFor = RTestsFor; } - + PropagationInfo(ConsumedState State) : InfoType(IT_State), State(State) {} PropagationInfo(const VarDecl *Var) : InfoType(IT_Var), Var(Var) {} PropagationInfo(const CXXBindTemporaryExpr *Tmp) : InfoType(IT_Tmp), Tmp(Tmp) {} - + const ConsumedState &getState() const { assert(InfoType == IT_State); return State; } - + const VarTestResult &getVarTest() const { assert(InfoType == IT_VarTest); return VarTest; } - + const VarTestResult &getLTest() const { assert(InfoType == IT_BinTest); return BinTest.LTest; } - + const VarTestResult &getRTest() const { assert(InfoType == IT_BinTest); return BinTest.RTest; } - + const VarDecl *getVar() const { assert(InfoType == IT_Var); return Var; } - + const CXXBindTemporaryExpr *getTmp() const { assert(InfoType == IT_Tmp); return Tmp; } - + ConsumedState getAsState(const ConsumedStateMap *StateMap) const { assert(isVar() || isTmp() || isState()); - + if (isVar()) return StateMap->getState(Var); else if (isTmp()) @@ -396,39 +396,39 @@ public: else return CS_None; } - + EffectiveOp testEffectiveOp() const { assert(InfoType == IT_BinTest); return BinTest.EOp; } - + const BinaryOperator * testSourceNode() const { assert(InfoType == IT_BinTest); return BinTest.Source; } - + bool isValid() const { return InfoType != IT_None; } bool isState() const { return InfoType == IT_State; } bool isVarTest() const { return InfoType == IT_VarTest; } bool isBinTest() const { return InfoType == IT_BinTest; } bool isVar() const { return InfoType == IT_Var; } bool isTmp() const { return InfoType == IT_Tmp; } - + bool isTest() const { return InfoType == IT_VarTest || InfoType == IT_BinTest; } - + bool isPointerToValue() const { return InfoType == IT_Var || InfoType == IT_Tmp; } - + PropagationInfo invertTest() const { assert(InfoType == IT_VarTest || InfoType == IT_BinTest); - + if (InfoType == IT_VarTest) { return PropagationInfo(VarTest.Var, invertConsumedUnconsumed(VarTest.TestsFor)); - + } else if (InfoType == IT_BinTest) { return PropagationInfo(BinTest.Source, BinTest.EOp == EO_And ? EO_Or : EO_And, @@ -447,7 +447,7 @@ static void setStateForVarOrTmp(ConsumedStateMap *StateMap, const PropagationInfo &PInfo, ConsumedState State) { assert(PInfo.isVar() || PInfo.isTmp()); - + if (PInfo.isVar()) StateMap->setState(PInfo.getVar(), State); else @@ -462,7 +462,7 @@ class ConsumedStmtVisitor : public ConstStmtVisitor<ConsumedStmtVisitor> { using PairType= std::pair<const Stmt *, PropagationInfo>; using InfoEntry = MapType::iterator; using ConstInfoEntry = MapType::const_iterator; - + AnalysisDeclContext &AC; ConsumedAnalyzer &Analyzer; ConsumedStateMap *StateMap; @@ -498,7 +498,7 @@ public: SourceLocation BlameLoc); bool handleCall(const CallExpr *Call, const Expr *ObjArg, const FunctionDecl *FunD); - + void VisitBinaryOperator(const BinaryOperator *BinOp); void VisitCallExpr(const CallExpr *Call); void VisitCastExpr(const CastExpr *Cast); @@ -518,16 +518,16 @@ public: ConsumedStmtVisitor(AnalysisDeclContext &AC, ConsumedAnalyzer &Analyzer, ConsumedStateMap *StateMap) : AC(AC), Analyzer(Analyzer), StateMap(StateMap) {} - + PropagationInfo getInfo(const Expr *StmtNode) const { ConstInfoEntry Entry = findInfo(StmtNode); - + if (Entry != PropagationMap.end()) return Entry->second; else return {}; } - + void reset(ConsumedStateMap *NewStateMap) { StateMap = NewStateMap; } @@ -696,7 +696,7 @@ void ConsumedStmtVisitor::propagateReturnType(const Expr *Call, ReturnState = mapReturnTypestateAttrState(RTA); else ReturnState = mapConsumableAttrState(RetType); - + PropagationMap.insert(PairType(Call, PropagationInfo(ReturnState))); } } @@ -707,16 +707,16 @@ void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) { case BO_LOr : { InfoEntry LEntry = findInfo(BinOp->getLHS()), REntry = findInfo(BinOp->getRHS()); - + VarTestResult LTest, RTest; - + if (LEntry != PropagationMap.end() && LEntry->second.isVarTest()) { LTest = LEntry->second.getVarTest(); } else { LTest.Var = nullptr; LTest.TestsFor = CS_None; } - + if (REntry != PropagationMap.end() && REntry->second.isVarTest()) { RTest = REntry->second.getVarTest(); } else { @@ -729,12 +729,12 @@ void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) { static_cast<EffectiveOp>(BinOp->getOpcode() == BO_LOr), LTest, RTest))); break; } - + case BO_PtrMemD: case BO_PtrMemI: forwardInfo(BinOp->getLHS(), BinOp); break; - + default: break; } @@ -762,9 +762,9 @@ void ConsumedStmtVisitor::VisitCastExpr(const CastExpr *Cast) { void ConsumedStmtVisitor::VisitCXXBindTemporaryExpr( const CXXBindTemporaryExpr *Temp) { - + InfoEntry Entry = findInfo(Temp->getSubExpr()); - + if (Entry != PropagationMap.end() && !Entry->second.isTest()) { StateMap->setState(Temp, Entry->second.getAsState(StateMap)); PropagationMap.insert(PairType(Temp, PropagationInfo(Temp))); @@ -776,13 +776,13 @@ void ConsumedStmtVisitor::VisitCXXConstructExpr(const CXXConstructExpr *Call) { ASTContext &CurrContext = AC.getASTContext(); QualType ThisType = Constructor->getThisType(CurrContext)->getPointeeType(); - + if (!isConsumableType(ThisType)) return; - + // FIXME: What should happen if someone annotates the move constructor? if (ReturnTypestateAttr *RTA = Constructor->getAttr<ReturnTypestateAttr>()) { - // TODO: Adjust state of args appropriately. + // TODO: Adjust state of args appropriately. ConsumedState RetState = mapReturnTypestateAttrState(RTA); PropagationMap.insert(PairType(Call, PropagationInfo(RetState))); } else if (Constructor->isDefaultConstructor()) { @@ -840,10 +840,10 @@ void ConsumedStmtVisitor::VisitDeclRefExpr(const DeclRefExpr *DeclRef) { } void ConsumedStmtVisitor::VisitDeclStmt(const DeclStmt *DeclS) { - for (const auto *DI : DeclS->decls()) + for (const auto *DI : DeclS->decls()) if (isa<VarDecl>(DI)) VisitVarDecl(cast<VarDecl>(DI)); - + if (DeclS->isSingleDecl()) if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl())) PropagationMap.insert(PairType(DeclS, PropagationInfo(Var))); @@ -861,38 +861,38 @@ void ConsumedStmtVisitor::VisitMemberExpr(const MemberExpr *MExpr) { void ConsumedStmtVisitor::VisitParmVarDecl(const ParmVarDecl *Param) { QualType ParamType = Param->getType(); ConsumedState ParamState = consumed::CS_None; - + if (const ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>()) - ParamState = mapParamTypestateAttrState(PTA); + ParamState = mapParamTypestateAttrState(PTA); else if (isConsumableType(ParamType)) - ParamState = mapConsumableAttrState(ParamType); + ParamState = mapConsumableAttrState(ParamType); else if (isRValueRef(ParamType) && isConsumableType(ParamType->getPointeeType())) - ParamState = mapConsumableAttrState(ParamType->getPointeeType()); + ParamState = mapConsumableAttrState(ParamType->getPointeeType()); else if (ParamType->isReferenceType() && isConsumableType(ParamType->getPointeeType())) ParamState = consumed::CS_Unknown; - + if (ParamState != CS_None) StateMap->setState(Param, ParamState); } void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) { ConsumedState ExpectedState = Analyzer.getExpectedReturnState(); - + if (ExpectedState != CS_None) { InfoEntry Entry = findInfo(Ret->getRetValue()); - + if (Entry != PropagationMap.end()) { ConsumedState RetState = Entry->second.getAsState(StateMap); - + if (RetState != ExpectedState) Analyzer.WarningsHandler.warnReturnTypestateMismatch( Ret->getReturnLoc(), stateToString(ExpectedState), stateToString(RetState)); } } - + StateMap->checkParamsForReturnTypestate(Ret->getLocStart(), Analyzer.WarningsHandler); } @@ -900,17 +900,17 @@ void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) { void ConsumedStmtVisitor::VisitUnaryOperator(const UnaryOperator *UOp) { InfoEntry Entry = findInfo(UOp->getSubExpr()); if (Entry == PropagationMap.end()) return; - + switch (UOp->getOpcode()) { case UO_AddrOf: PropagationMap.insert(PairType(UOp, Entry->second)); break; - + case UO_LNot: if (Entry->second.isTest()) PropagationMap.insert(PairType(UOp, Entry->second.invertTest())); break; - + default: break; } @@ -924,7 +924,7 @@ void ConsumedStmtVisitor::VisitVarDecl(const VarDecl *Var) { if (VIT != PropagationMap.end()) { PropagationInfo PInfo = VIT->second; ConsumedState St = PInfo.getAsState(StateMap); - + if (St != consumed::CS_None) { StateMap->setState(Var, St); return; @@ -940,7 +940,7 @@ static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test, ConsumedStateMap *ThenStates, ConsumedStateMap *ElseStates) { ConsumedState VarState = ThenStates->getState(Test.Var); - + if (VarState == CS_Unknown) { ThenStates->setState(Test.Var, Test.TestsFor); ElseStates->setState(Test.Var, invertConsumedUnconsumed(Test.TestsFor)); @@ -956,10 +956,10 @@ static void splitVarStateForIfBinOp(const PropagationInfo &PInfo, ConsumedStateMap *ElseStates) { const VarTestResult <est = PInfo.getLTest(), &RTest = PInfo.getRTest(); - + ConsumedState LState = LTest.Var ? ThenStates->getState(LTest.Var) : CS_None, RState = RTest.Var ? ThenStates->getState(RTest.Var) : CS_None; - + if (LTest.Var) { if (PInfo.testEffectiveOp() == EO_And) { if (LState == CS_Unknown) { @@ -987,7 +987,7 @@ static void splitVarStateForIfBinOp(const PropagationInfo &PInfo, } } } - + if (RTest.Var) { if (PInfo.testEffectiveOp() == EO_And) { if (RState == CS_Unknown) @@ -1008,7 +1008,7 @@ bool ConsumedBlockInfo::allBackEdgesVisited(const CFGBlock *CurrBlock, const CFGBlock *TargetBlock) { assert(CurrBlock && "Block pointer must not be NULL"); assert(TargetBlock && "TargetBlock pointer must not be NULL"); - + unsigned int CurrBlockOrder = VisitOrder[CurrBlock->getBlockID()]; for (CFGBlock::const_pred_iterator PI = TargetBlock->pred_begin(), PE = TargetBlock->pred_end(); PI != PE; ++PI) { @@ -1069,7 +1069,7 @@ ConsumedBlockInfo::getInfo(const CFGBlock *Block) { bool ConsumedBlockInfo::isBackEdge(const CFGBlock *From, const CFGBlock *To) { assert(From && "From block must not be NULL"); assert(To && "From block must not be NULL"); - + return VisitOrder[From->getBlockID()] > VisitOrder[To->getBlockID()]; } @@ -1080,7 +1080,7 @@ bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) { // edge. if (Block->pred_size() < 2) return false; - + unsigned int BlockVisitOrder = VisitOrder[Block->getBlockID()]; for (CFGBlock::const_pred_iterator PI = Block->pred_begin(), PE = Block->pred_end(); PI != PE; ++PI) { @@ -1092,16 +1092,16 @@ bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) { void ConsumedStateMap::checkParamsForReturnTypestate(SourceLocation BlameLoc, ConsumedWarningsHandlerBase &WarningsHandler) const { - + for (const auto &DM : VarMap) { if (isa<ParmVarDecl>(DM.first)) { const auto *Param = cast<ParmVarDecl>(DM.first); const ReturnTypestateAttr *RTA = Param->getAttr<ReturnTypestateAttr>(); - + if (!RTA) continue; - - ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA); + + ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA); if (DM.second != ExpectedState) WarningsHandler.warnParamReturnTypestateMismatch(BlameLoc, Param->getNameAsString(), stateToString(ExpectedState), @@ -1116,20 +1116,20 @@ void ConsumedStateMap::clearTemporaries() { ConsumedState ConsumedStateMap::getState(const VarDecl *Var) const { VarMapType::const_iterator Entry = VarMap.find(Var); - + if (Entry != VarMap.end()) return Entry->second; - + return CS_None; } ConsumedState ConsumedStateMap::getState(const CXXBindTemporaryExpr *Tmp) const { TmpMapType::const_iterator Entry = TmpMap.find(Tmp); - + if (Entry != TmpMap.end()) return Entry->second; - + return CS_None; } @@ -1143,10 +1143,10 @@ void ConsumedStateMap::intersect(const ConsumedStateMap &Other) { for (const auto &DM : Other.VarMap) { LocalState = this->getState(DM.first); - + if (LocalState == CS_None) continue; - + if (LocalState != DM.second) VarMap[DM.first] = CS_Unknown; } @@ -1155,16 +1155,16 @@ void ConsumedStateMap::intersect(const ConsumedStateMap &Other) { void ConsumedStateMap::intersectAtLoopHead(const CFGBlock *LoopHead, const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates, ConsumedWarningsHandlerBase &WarningsHandler) { - + ConsumedState LocalState; SourceLocation BlameLoc = getLastStmtLoc(LoopBack); - - for (const auto &DM : LoopBackStates->VarMap) { + + for (const auto &DM : LoopBackStates->VarMap) { LocalState = this->getState(DM.first); - + if (LocalState == CS_None) continue; - + if (LocalState != DM.second) { VarMap[DM.first] = CS_Unknown; WarningsHandler.warnLoopStateMismatch(BlameLoc, @@ -1195,7 +1195,7 @@ void ConsumedStateMap::remove(const CXXBindTemporaryExpr *Tmp) { bool ConsumedStateMap::operator!=(const ConsumedStateMap *Other) const { for (const auto &DM : Other->VarMap) if (this->getState(DM.first) != DM.second) - return true; + return true; return false; } @@ -1235,15 +1235,15 @@ bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, std::unique_ptr<ConsumedStateMap> FalseStates( new ConsumedStateMap(*CurrStates)); PropagationInfo PInfo; - + if (const auto *IfNode = dyn_cast_or_null<IfStmt>(CurrBlock->getTerminator().getStmt())) { const Expr *Cond = IfNode->getCond(); - + PInfo = Visitor.getInfo(Cond); if (!PInfo.isValid() && isa<BinaryOperator>(Cond)) PInfo = Visitor.getInfo(cast<BinaryOperator>(Cond)->getRHS()); - + if (PInfo.isVarTest()) { CurrStates->setSource(Cond); FalseStates->setSource(Cond); @@ -1262,26 +1262,26 @@ bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, if (!PInfo.isVarTest()) { if ((BinOp = dyn_cast_or_null<BinaryOperator>(BinOp->getLHS()))) { PInfo = Visitor.getInfo(BinOp->getRHS()); - + if (!PInfo.isVarTest()) return false; } else { return false; } } - + CurrStates->setSource(BinOp); FalseStates->setSource(BinOp); - + const VarTestResult &Test = PInfo.getVarTest(); ConsumedState VarState = CurrStates->getState(Test.Var); - + if (BinOp->getOpcode() == BO_LAnd) { if (VarState == CS_Unknown) CurrStates->setState(Test.Var, Test.TestsFor); else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) CurrStates->markUnreachable(); - + } else if (BinOp->getOpcode() == BO_LOr) { if (VarState == CS_Unknown) FalseStates->setState(Test.Var, @@ -1292,9 +1292,9 @@ bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, } else { return false; } - + CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(); - + if (*SI) BlockInfo.addInfo(*SI, std::move(CurrStates)); else @@ -1310,7 +1310,7 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { const auto *D = dyn_cast_or_null<FunctionDecl>(AC.getDecl()); if (!D) return; - + CFG *CFGraph = AC.getCFG(); if (!CFGraph) return; @@ -1319,7 +1319,7 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>(); // AC.getCFG()->viewCFG(LangOptions()); - + BlockInfo = ConsumedBlockInfo(CFGraph->getNumBlockIDs(), SortedGraph); CurrStates = llvm::make_unique<ConsumedStateMap>(); @@ -1328,12 +1328,12 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { // Add all trackable parameters to the state map. for (const auto *PI : D->parameters()) Visitor.VisitParmVarDecl(PI); - + // Visit all of the function's basic blocks. for (const auto *CurrBlock : *SortedGraph) { if (!CurrStates) CurrStates = BlockInfo.getInfo(CurrBlock); - + if (!CurrStates) { continue; } else if (!CurrStates->isReachable()) { @@ -1349,34 +1349,34 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { case CFGElement::Statement: Visitor.Visit(B.castAs<CFGStmt>().getStmt()); break; - + case CFGElement::TemporaryDtor: { const CFGTemporaryDtor &DTor = B.castAs<CFGTemporaryDtor>(); const CXXBindTemporaryExpr *BTE = DTor.getBindTemporaryExpr(); - + Visitor.checkCallability(PropagationInfo(BTE), DTor.getDestructorDecl(AC.getASTContext()), BTE->getExprLoc()); CurrStates->remove(BTE); break; } - + case CFGElement::AutomaticObjectDtor: { const CFGAutomaticObjDtor &DTor = B.castAs<CFGAutomaticObjDtor>(); SourceLocation Loc = DTor.getTriggerStmt()->getLocEnd(); const VarDecl *Var = DTor.getVarDecl(); - + Visitor.checkCallability(PropagationInfo(Var), DTor.getDestructorDecl(AC.getASTContext()), Loc); break; } - + default: break; } } - + // TODO: Handle other forms of branching with precision, including while- // and for-loops. (Deferred) if (!splitState(CurrBlock, Visitor)) { @@ -1406,13 +1406,13 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { CurrStates = nullptr; } } - + if (CurrBlock == &AC.getCFG()->getExit() && D->getCallResultType()->isVoidType()) CurrStates->checkParamsForReturnTypestate(D->getLocation(), WarningsHandler); } // End of block iterator. - + // Delete the last existing state map. CurrStates = nullptr; diff --git a/lib/Analysis/FormatString.cpp b/lib/Analysis/FormatString.cpp index c62e537e92dd9..f37e4affae3fc 100644 --- a/lib/Analysis/FormatString.cpp +++ b/lib/Analysis/FormatString.cpp @@ -407,7 +407,7 @@ ArgType::matchesType(ASTContext &C, QualType argTy) const { case WIntTy: { - QualType PromoArg = + QualType PromoArg = argTy->isPromotableIntegerType() ? C.getPromotedIntegerType(argTy) : argTy; @@ -623,7 +623,7 @@ const char *ConversionSpecifier::toString() const { Optional<ConversionSpecifier> ConversionSpecifier::getStandardSpecifier() const { ConversionSpecifier::Kind NewKind; - + switch (getKind()) { default: return None; @@ -672,7 +672,7 @@ bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const { switch (LM.getKind()) { case LengthModifier::None: return true; - + // Handle most integer flags case LengthModifier::AsShort: if (Target.getTriple().isOSMSVCRT()) { @@ -712,7 +712,7 @@ bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const { default: return false; } - + // Handle 'l' flag case LengthModifier::AsLong: // or AsWideChar switch (CS.getKind()) { @@ -745,7 +745,7 @@ bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const { default: return false; } - + case LengthModifier::AsLongDouble: switch (CS.getKind()) { case ConversionSpecifier::aArg: diff --git a/lib/Analysis/FormatStringParsing.h b/lib/Analysis/FormatStringParsing.h index 17fd2f6aefb8a..a63140b366cd1 100644 --- a/lib/Analysis/FormatStringParsing.h +++ b/lib/Analysis/FormatStringParsing.h @@ -23,7 +23,7 @@ public: }; namespace analyze_format_string { - + OptionalAmount ParseAmount(const char *&Beg, const char *E); OptionalAmount ParseNonPositionAmount(const char *&Beg, const char *E, unsigned &argIndex); @@ -31,12 +31,12 @@ OptionalAmount ParseNonPositionAmount(const char *&Beg, const char *E, OptionalAmount ParsePositionAmount(FormatStringHandler &H, const char *Start, const char *&Beg, const char *E, PositionContext p); - + bool ParseFieldWidth(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E, unsigned *argIndex); - + bool ParseArgPosition(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E); @@ -62,7 +62,7 @@ public: SpecifierResult(const char *start, const T &fs) : FS(fs), Start(start), Stop(false) {} - + const char *getStart() const { return Start; } bool shouldStop() const { return Stop; } bool hasValue() const { return Start != nullptr; } @@ -72,7 +72,7 @@ public: } const T &getValue() { return FS; } }; - + } // end analyze_format_string namespace } // end clang namespace diff --git a/lib/Analysis/LiveVariables.cpp b/lib/Analysis/LiveVariables.cpp index b8ea1e960095a..05bc1a5d102ca 100644 --- a/lib/Analysis/LiveVariables.cpp +++ b/lib/Analysis/LiveVariables.cpp @@ -39,7 +39,7 @@ public: : enqueuedBlocks(cfg.getNumBlockIDs()), POV(Ctx.getAnalysis<PostOrderCFGView>()), worklist(POV->getComparator()) {} - + void enqueueBlock(const CFGBlock *block); void enqueuePredecessors(const CFGBlock *block); @@ -73,7 +73,7 @@ const CFGBlock *DataflowWorklist::dequeue() { namespace { class LiveVariablesImpl { -public: +public: AnalysisDeclContext &analysisContext; llvm::ImmutableSet<const Stmt *>::Factory SSetFact; llvm::ImmutableSet<const VarDecl *>::Factory DSetFact; @@ -83,7 +83,7 @@ public: llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness; llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment; const bool killAtAssign; - + LiveVariables::LivenessValues merge(LiveVariables::LivenessValues valsA, LiveVariables::LivenessValues valsB); @@ -130,7 +130,7 @@ namespace { SET mergeSets(SET A, SET B) { if (A.isEmpty()) return B; - + for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) { A = A.add(*it); } @@ -142,17 +142,17 @@ void LiveVariables::Observer::anchor() { } LiveVariables::LivenessValues LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA, - LiveVariables::LivenessValues valsB) { - + LiveVariables::LivenessValues valsB) { + llvm::ImmutableSetRef<const Stmt *> SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()), SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()); - - + + llvm::ImmutableSetRef<const VarDecl *> DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()), DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()); - + llvm::ImmutableSetRef<const BindingDecl *> BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()), BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()); @@ -160,12 +160,12 @@ LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA, SSetRefA = mergeSets(SSetRefA, SSetRefB); DSetRefA = mergeSets(DSetRefA, DSetRefB); BSetRefA = mergeSets(BSetRefA, BSetRefB); - + // asImmutableSet() canonicalizes the tree, allowing us to do an easy // comparison afterwards. return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(), DSetRefA.asImmutableSet(), - BSetRefA.asImmutableSet()); + BSetRefA.asImmutableSet()); } bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const { @@ -211,7 +211,7 @@ public: void VisitBinaryOperator(BinaryOperator *BO); void VisitBlockExpr(BlockExpr *BE); - void VisitDeclRefExpr(DeclRefExpr *DR); + void VisitDeclRefExpr(DeclRefExpr *DR); void VisitDeclStmt(DeclStmt *DS); void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS); void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE); @@ -226,7 +226,7 @@ static const VariableArrayType *FindVA(QualType Ty) { if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT)) if (VAT->getSizeExpr()) return VAT; - + ty = VT->getElementType().getTypePtr(); } @@ -236,7 +236,7 @@ static const VariableArrayType *FindVA(QualType Ty) { static const Stmt *LookThroughStmt(const Stmt *S) { while (S) { if (const Expr *Ex = dyn_cast<Expr>(S)) - S = Ex->IgnoreParens(); + S = Ex->IgnoreParens(); if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) { S = EWC->getSubExpr(); continue; @@ -259,15 +259,15 @@ static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set, void TransferFunctions::Visit(Stmt *S) { if (observer) observer->observeStmt(S, currentBlock, val); - + StmtVisitor<TransferFunctions>::Visit(S); - + if (isa<Expr>(S)) { val.liveStmts = LV.SSetFact.remove(val.liveStmts, S); } // Mark all children expressions live. - + switch (S->getStmtClass()) { default: break; @@ -344,7 +344,7 @@ void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) { if (B->isAssignmentOp()) { if (!LV.killAtAssign) return; - + // Assigning to a variable? Expr *LHS = B->getLHS()->IgnoreParens(); @@ -414,7 +414,7 @@ void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) { else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) { VD = cast<VarDecl>(DR->getDecl()); } - + if (VD) { val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); if (observer && DR) @@ -444,12 +444,12 @@ void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) { // since a ++/-- acts as both a kill and a "use". if (!observer) return; - + switch (UO->getOpcode()) { default: return; case UO_PostInc: - case UO_PostDec: + case UO_PostDec: case UO_PreInc: case UO_PreDec: break; @@ -470,11 +470,11 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, LiveVariables::Observer *obs) { TransferFunctions TF(*this, val, obs, block); - + // Visit the terminator (if any). if (const Stmt *term = block->getTerminator()) TF.Visit(const_cast<Stmt*>(term)); - + // Apply the transfer function for all Stmts in the block. for (CFGBlock::const_reverse_iterator it = block->rbegin(), ei = block->rend(); it != ei; ++it) { @@ -488,7 +488,7 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, if (!elem.getAs<CFGStmt>()) continue; - + const Stmt *S = elem.castAs<CFGStmt>().getStmt(); TF.Visit(const_cast<Stmt*>(S)); stmtsToLiveness[S] = val; @@ -499,10 +499,10 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) { const CFG *cfg = getImpl(impl).analysisContext.getCFG(); for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) - getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs); + getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs); } -LiveVariables::LiveVariables(void *im) : impl(im) {} +LiveVariables::LiveVariables(void *im) : impl(im) {} LiveVariables::~LiveVariables() { delete (LiveVariablesImpl*) impl; @@ -533,7 +533,7 @@ LiveVariables::computeLiveness(AnalysisDeclContext &AC, for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) { const CFGBlock *block = *it; worklist.enqueueBlock(block); - + // FIXME: Scan for DeclRefExprs using in the LHS of an assignment. // We need to do this because we lack context in the reverse analysis // to determine if a DeclRefExpr appears in such a context, and thus @@ -554,35 +554,35 @@ LiveVariables::computeLiveness(AnalysisDeclContext &AC, } } } - + while (const CFGBlock *block = worklist.dequeue()) { // Determine if the block's end value has changed. If not, we // have nothing left to do for this block. LivenessValues &prevVal = LV->blocksEndToLiveness[block]; - + // Merge the values of all successor blocks. LivenessValues val; for (CFGBlock::const_succ_iterator it = block->succ_begin(), ei = block->succ_end(); it != ei; ++it) { - if (const CFGBlock *succ = *it) { + if (const CFGBlock *succ = *it) { val = LV->merge(val, LV->blocksBeginToLiveness[succ]); } } - + if (!everAnalyzedBlock[block->getBlockID()]) everAnalyzedBlock[block->getBlockID()] = true; else if (prevVal.equals(val)) continue; prevVal = val; - + // Update the dataflow value for the start of this block. LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val); - + // Enqueue the value to the predecessors. worklist.enqueuePredecessors(block); } - + return new LiveVariables(LV); } @@ -595,7 +595,7 @@ void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end(); it != ei; ++it) { - vec.push_back(it->first); + vec.push_back(it->first); } llvm::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) { return A->getBlockID() < B->getBlockID(); @@ -607,14 +607,14 @@ void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { it = vec.begin(), ei = vec.end(); it != ei; ++it) { llvm::errs() << "\n[ B" << (*it)->getBlockID() << " (live variables at block exit) ]\n"; - + LiveVariables::LivenessValues vals = blocksEndToLiveness[*it]; declVec.clear(); - + for (llvm::ImmutableSet<const VarDecl *>::iterator si = vals.liveDecls.begin(), se = vals.liveDecls.end(); si != se; ++si) { - declVec.push_back(*si); + declVec.push_back(*si); } llvm::sort(declVec.begin(), declVec.end(), @@ -630,7 +630,7 @@ void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { llvm::errs() << ">\n"; } } - llvm::errs() << "\n"; + llvm::errs() << "\n"; } const void *LiveVariables::getTag() { static int x; return &x; } diff --git a/lib/Analysis/ObjCNoReturn.cpp b/lib/Analysis/ObjCNoReturn.cpp index 52d844bf9dd88..f27568c0c3227 100644 --- a/lib/Analysis/ObjCNoReturn.cpp +++ b/lib/Analysis/ObjCNoReturn.cpp @@ -32,13 +32,13 @@ ObjCNoReturn::ObjCNoReturn(ASTContext &C) { // Generate selectors. SmallVector<IdentifierInfo*, 3> II; - + // raise:format: II.push_back(&C.Idents.get("raise")); II.push_back(&C.Idents.get("format")); NSExceptionInstanceRaiseSelectors[0] = C.Selectors.getSelector(II.size(), &II[0]); - + // raise:format:arguments: II.push_back(&C.Idents.get("arguments")); NSExceptionInstanceRaiseSelectors[1] = @@ -48,7 +48,7 @@ ObjCNoReturn::ObjCNoReturn(ASTContext &C) bool ObjCNoReturn::isImplicitNoReturn(const ObjCMessageExpr *ME) { Selector S = ME->getSelector(); - + if (ME->isInstanceMessage()) { // Check for the "raise" message. return S == RaiseSel; @@ -62,6 +62,6 @@ bool ObjCNoReturn::isImplicitNoReturn(const ObjCMessageExpr *ME) { } } } - + return false; } diff --git a/lib/Analysis/PostOrderCFGView.cpp b/lib/Analysis/PostOrderCFGView.cpp index 124424bf25679..d5d0bafe664cd 100644 --- a/lib/Analysis/PostOrderCFGView.cpp +++ b/lib/Analysis/PostOrderCFGView.cpp @@ -22,11 +22,11 @@ void PostOrderCFGView::anchor() {} PostOrderCFGView::PostOrderCFGView(const CFG *cfg) { Blocks.reserve(cfg->getNumBlockIDs()); CFGBlockSet BSet(cfg); - + for (po_iterator I = po_iterator::begin(cfg, BSet), E = po_iterator::end(cfg, BSet); I != E; ++I) { BlockOrder[*I] = Blocks.size() + 1; - Blocks.push_back(*I); + Blocks.push_back(*I); } } @@ -43,7 +43,7 @@ bool PostOrderCFGView::BlockOrderCompare::operator()(const CFGBlock *b1, const CFGBlock *b2) const { PostOrderCFGView::BlockOrderTy::const_iterator b1It = POV.BlockOrder.find(b1); PostOrderCFGView::BlockOrderTy::const_iterator b2It = POV.BlockOrder.find(b2); - + unsigned b1V = (b1It == POV.BlockOrder.end()) ? 0 : b1It->second; unsigned b2V = (b2It == POV.BlockOrder.end()) ? 0 : b2It->second; return b1V > b2V; diff --git a/lib/Analysis/PrintfFormatString.cpp b/lib/Analysis/PrintfFormatString.cpp index 00591ab2b048b..dcb15c5e37584 100644 --- a/lib/Analysis/PrintfFormatString.cpp +++ b/lib/Analysis/PrintfFormatString.cpp @@ -348,7 +348,7 @@ static PrintfSpecifierResult ParsePrintfSpecifier(FormatStringHandler &H, if (Target.getTriple().isOSMSVCRT()) k = ConversionSpecifier::ZArg; } - + // Check to see if we used the Objective-C modifier flags with // a conversion specifier other than '@'. if (k != ConversionSpecifier::ObjCObjArg && @@ -416,9 +416,9 @@ bool clang::analyze_format_string::ParseFormatStringHasSArg(const char *I, const char *E, const LangOptions &LO, const TargetInfo &Target) { - + unsigned argIndex = 0; - + // Keep looking for a %s format specifier until we have exhausted the string. FormatStringHandler H; while (I != E) { diff --git a/lib/Analysis/ProgramPoint.cpp b/lib/Analysis/ProgramPoint.cpp index 26b59bb71de21..d9833659d7b3f 100644 --- a/lib/Analysis/ProgramPoint.cpp +++ b/lib/Analysis/ProgramPoint.cpp @@ -43,7 +43,7 @@ ProgramPoint ProgramPoint::getProgramPoint(const Stmt *S, ProgramPoint::Kind K, } } -SimpleProgramPointTag::SimpleProgramPointTag(StringRef MsgProvider, +SimpleProgramPointTag::SimpleProgramPointTag(StringRef MsgProvider, StringRef Msg) : Desc((MsgProvider + " : " + Msg).str()) {} diff --git a/lib/Analysis/ReachableCode.cpp b/lib/Analysis/ReachableCode.cpp index f644d503dc490..ed26a94f3d60b 100644 --- a/lib/Analysis/ReachableCode.cpp +++ b/lib/Analysis/ReachableCode.cpp @@ -201,7 +201,7 @@ static bool isConfigurationValue(const Stmt *S, // Special case looking for the sigil '()' around an integer literal. if (const ParenExpr *PE = dyn_cast<ParenExpr>(S)) if (!PE->getLocStart().isMacroID()) - return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal, + return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal, IncludeIntegers, true); if (const Expr *Ex = dyn_cast<Expr>(S)) @@ -310,19 +310,19 @@ static unsigned scanFromBlock(const CFGBlock *Start, Preprocessor *PP, bool IncludeSometimesUnreachableEdges) { unsigned count = 0; - + // Prep work queue SmallVector<const CFGBlock*, 32> WL; - + // The entry block may have already been marked reachable // by the caller. if (!Reachable[Start->getBlockID()]) { ++count; Reachable[Start->getBlockID()] = true; } - + WL.push_back(Start); - + // Find the reachable blocks from 'Start'. while (!WL.empty()) { const CFGBlock *item = WL.pop_back_val(); @@ -337,7 +337,7 @@ static unsigned scanFromBlock(const CFGBlock *Start, if (!IncludeSometimesUnreachableEdges) TreatAllSuccessorsAsReachable = false; - for (CFGBlock::const_succ_iterator I = item->succ_begin(), + for (CFGBlock::const_succ_iterator I = item->succ_begin(), E = item->succ_end(); I != E; ++I) { const CFGBlock *B = *I; if (!B) do { @@ -644,7 +644,7 @@ void DeadCodeScan::reportDeadCode(const CFGBlock *B, Loc, SourceRange(), SourceRange(Loc, Loc), R2); return; } - + // Check if the dead block has a predecessor whose branch has // a configuration value that *could* be modified to // silence the warning. @@ -690,7 +690,7 @@ void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable); if (numReachable == cfg->getNumBlockIDs()) return; - + // If there aren't explicit EH edges, we should include the 'try' dispatch // blocks as roots. if (!AC.getCFGBuildOptions().AddEHEdges) { @@ -703,16 +703,16 @@ void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, } // There are some unreachable blocks. We need to find the root blocks that - // contain code that should be considered unreachable. + // contain code that should be considered unreachable. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { const CFGBlock *block = *I; // A block may have been marked reachable during this loop. if (reachable[block->getBlockID()]) continue; - + DeadCodeScan DS(reachable, PP, AC.getASTContext()); numReachable += DS.scanBackwards(block, CB); - + if (numReachable == cfg->getNumBlockIDs()) return; } diff --git a/lib/Analysis/ScanfFormatString.cpp b/lib/Analysis/ScanfFormatString.cpp index 8398a4b82d5a3..a9af0cdfdacd9 100644 --- a/lib/Analysis/ScanfFormatString.cpp +++ b/lib/Analysis/ScanfFormatString.cpp @@ -41,7 +41,7 @@ static bool ParseScanList(FormatStringHandler &H, H.HandleIncompleteScanList(start, I); return true; } - + // Special case: ']' is the first character. if (*I == ']') { if (++I == E) { @@ -65,7 +65,7 @@ static bool ParseScanList(FormatStringHandler &H, H.HandleIncompleteScanList(start, I - 1); return true; } - } + } CS.setEndScanList(I); return false; @@ -98,17 +98,17 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, break; } } - + // No format specifier found? if (!Start) return false; - + if (I == E) { // No more characters left? H.HandleIncompleteSpecifier(Start, E - Start); return true; } - + ScanfSpecifier FS; if (ParseArgPosition(H, FS, Start, I, E)) return true; @@ -118,7 +118,7 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, H.HandleIncompleteSpecifier(Start, E - Start); return true; } - + // Look for '*' flag if it is present. if (*I == '*') { FS.setSuppressAssignment(I); @@ -127,7 +127,7 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, return true; } } - + // Look for the field width (if any). Unlike printf, this is either // a fixed integer or isn't present. const OptionalAmount &Amt = clang::analyze_format_string::ParseAmount(I, E); @@ -141,20 +141,20 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, return true; } } - + // Look for the length modifier. if (ParseLengthModifier(FS, I, E, LO, /*scanf=*/true) && I == E) { // No more characters left? H.HandleIncompleteSpecifier(Start, E - Start); return true; } - + // Detect spurious null characters, which are likely errors. if (*I == '\0') { H.HandleNullChar(I); return true; } - + // Finally, look for the conversion specifier. const char *conversionPosition = I++; ScanfConversionSpecifier::Kind k = ScanfConversionSpecifier::InvalidSpecifier; @@ -207,7 +207,7 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, if (CS.consumesDataArgument() && !FS.getSuppressAssignment() && !FS.usesPositionalArg()) FS.setArgIndex(argIndex++); - + // FIXME: '%' and '*' doesn't make sense. Issue a warning. // FIXME: 'ConsumedSoFar' and '*' doesn't make sense. @@ -537,9 +537,9 @@ bool clang::analyze_format_string::ParseScanfString(FormatStringHandler &H, const char *E, const LangOptions &LO, const TargetInfo &Target) { - + unsigned argIndex = 0; - + // Keep looking for a format specifier until we have exhausted the string. while (I != E) { const ScanfSpecifierResult &FSR = ParseScanfSpecifier(H, I, E, argIndex, diff --git a/lib/Analysis/UninitializedValues.cpp b/lib/Analysis/UninitializedValues.cpp index 63353292349b3..31c88a109565a 100644 --- a/lib/Analysis/UninitializedValues.cpp +++ b/lib/Analysis/UninitializedValues.cpp @@ -62,13 +62,13 @@ class DeclToIndex { public: DeclToIndex() = default; - + /// Compute the actual mapping from declarations to bits. void computeMap(const DeclContext &dc); - + /// Return the number of declarations in the map. unsigned size() const { return map.size(); } - + /// Returns the bit vector index for a given declaration. Optional<unsigned> getValueIndex(const VarDecl *d) const; }; @@ -126,8 +126,8 @@ public: CFGBlockValues(const CFG &cfg); unsigned getNumEntries() const { return declToIndex.size(); } - - void computeSetOfDeclarations(const DeclContext &dc); + + void computeSetOfDeclarations(const DeclContext &dc); ValueVector &getValueVector(const CFGBlock *block) { return vals[block->getBlockID()]; @@ -136,13 +136,13 @@ public: void setAllScratchValues(Value V); void mergeIntoScratch(ValueVector const &source, bool isFirst); bool updateValueVectorWithScratch(const CFGBlock *block); - + bool hasNoDeclarations() const { return declToIndex.size() == 0; } void resetScratch(); - + ValueVector::reference operator[](const VarDecl *vd); Value getValue(const CFGBlock *block, const CFGBlock *dstBlock, @@ -151,7 +151,7 @@ public: assert(idx.hasValue()); return getValueVector(block)[idx.getValue()]; } -}; +}; } // namespace @@ -235,7 +235,7 @@ public: ++PO_I; } } - + void enqueueSuccessors(const CFGBlock *block); const CFGBlock *dequeue(); }; @@ -614,7 +614,7 @@ public: const CFGBlock *Pred = *I; if (!Pred) continue; - + Value AtPredExit = vals.getValue(Pred, B, vd); if (AtPredExit == Initialized) // This block initializes the variable. @@ -923,7 +923,7 @@ void clang::runUninitializedVariablesAnalysis( classification, wasAnalyzed, PBH); ++stats.NumBlockVisits; if (changed || !previouslyVisited[block->getBlockID()]) - worklist.enqueueSuccessors(block); + worklist.enqueueSuccessors(block); previouslyVisited[block->getBlockID()] = true; } diff --git a/lib/Basic/Diagnostic.cpp b/lib/Basic/Diagnostic.cpp index 519e835e32a25..f1ebd9d38b9e5 100644 --- a/lib/Basic/Diagnostic.cpp +++ b/lib/Basic/Diagnostic.cpp @@ -116,12 +116,12 @@ void DiagnosticsEngine::Reset() { UncompilableErrorOccurred = false; FatalErrorOccurred = false; UnrecoverableErrorOccurred = false; - + NumWarnings = 0; NumErrors = 0; TrapNumErrorsOccurred = 0; TrapNumUnrecoverableErrorsOccurred = 0; - + CurDiagID = std::numeric_limits<unsigned>::max(); LastDiagLevel = DiagnosticIDs::Ignored; DelayedDiagID = 0; @@ -759,7 +759,7 @@ FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { return; } - StringRef Diag = + StringRef Diag = getDiags()->getDiagnosticIDs()->getDescription(getID()); FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); @@ -880,7 +880,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd, continue; } } - + switch (Kind) { // ---- STRINGS ---- case DiagnosticsEngine::ak_std_string: { @@ -1056,7 +1056,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd, break; } } - + // Remember this argument info for subsequent formatting operations. Turn // std::strings into a null terminated string to make it be the same case as // all the other ones. @@ -1077,7 +1077,7 @@ StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, StringRef Message) : ID(ID), Level(Level), Message(Message) {} -StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, +StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info) : ID(Info.getID()), Level(Level) { assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && diff --git a/lib/Basic/DiagnosticIDs.cpp b/lib/Basic/DiagnosticIDs.cpp index 697de68a5afb1..8f2c3d06a5046 100644 --- a/lib/Basic/DiagnosticIDs.cpp +++ b/lib/Basic/DiagnosticIDs.cpp @@ -685,7 +685,7 @@ bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const { ++Diag.NumErrors; } - // If we've emitted a lot of errors, emit a fatal error instead of it to + // If we've emitted a lot of errors, emit a fatal error instead of it to // stop a flood of bogus errors. if (Diag.ErrorLimit && Diag.NumErrors > Diag.ErrorLimit && DiagLevel == DiagnosticIDs::Error) { diff --git a/lib/Basic/FileManager.cpp b/lib/Basic/FileManager.cpp index 7e2d01c4981d8..d339b972ae8ea 100644 --- a/lib/Basic/FileManager.cpp +++ b/lib/Basic/FileManager.cpp @@ -71,7 +71,7 @@ void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, StatCache = std::move(statCache); return; } - + FileSystemStatCache *LastCache = StatCache.get(); while (LastCache->getNextStatCache()) LastCache = LastCache->getNextStatCache(); @@ -82,18 +82,18 @@ void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, void FileManager::removeStatCache(FileSystemStatCache *statCache) { if (!statCache) return; - + if (StatCache.get() == statCache) { // This is the first stat cache. StatCache = StatCache->takeNextStatCache(); return; } - + // Find the stat cache in the list. FileSystemStatCache *PrevCache = StatCache.get(); while (PrevCache && PrevCache->getNextStatCache() != statCache) PrevCache = PrevCache->getNextStatCache(); - + assert(PrevCache && "Stat cache not found for removal"); PrevCache->setNextStatCache(statCache->takeNextStatCache()); } @@ -247,7 +247,7 @@ const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, return nullptr; } - + // FIXME: Use the directory info to prune this, before doing the stat syscall. // FIXME: This will reduce the # syscalls. @@ -394,7 +394,7 @@ FileManager::getVirtualFile(StringRef Filename, off_t Size, bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { StringRef pathRef(path.data(), path.size()); - if (FileSystemOpts.WorkingDir.empty() + if (FileSystemOpts.WorkingDir.empty() || llvm::sys::path::is_absolute(pathRef)) return false; @@ -505,14 +505,14 @@ void FileManager::GetUniqueIDMapping( SmallVectorImpl<const FileEntry *> &UIDToFiles) const { UIDToFiles.clear(); UIDToFiles.resize(NextFileUID); - + // Map file entries for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); FE != FEEnd; ++FE) if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); - + // Map virtual file entries for (const auto &VFE : VirtualFileEntries) if (VFE && VFE.get() != NON_EXISTENT_FILE) diff --git a/lib/Basic/FileSystemStatCache.cpp b/lib/Basic/FileSystemStatCache.cpp index ebee32670e0a5..f5856cb6542a8 100644 --- a/lib/Basic/FileSystemStatCache.cpp +++ b/lib/Basic/FileSystemStatCache.cpp @@ -95,17 +95,17 @@ bool FileSystemStatCache::get(StringRef Path, FileData &Data, bool isFile, // If the path doesn't exist, return failure. if (R == CacheMissing) return true; - + // If the path exists, make sure that its "directoryness" matches the clients // demands. if (Data.IsDirectory != isForDir) { // If not, close the file if opened. if (F) *F = nullptr; - + return true; } - + return false; } @@ -120,7 +120,7 @@ MemorizeStatCalls::getStat(StringRef Path, FileData &Data, bool isFile, // entries). if (Result == CacheMissing) return Result; - + // Cache file 'stat' results and directories with absolutely paths. if (!Data.IsDirectory || llvm::sys::path::is_absolute(Path)) StatCalls[Path] = Data; diff --git a/lib/Basic/IdentifierTable.cpp b/lib/Basic/IdentifierTable.cpp index 2fef481ae2c59..7ec3cb7dd65b6 100644 --- a/lib/Basic/IdentifierTable.cpp +++ b/lib/Basic/IdentifierTable.cpp @@ -319,7 +319,7 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { CASE( 6, 'i', 'n', ifndef); CASE( 6, 'i', 'p', import); CASE( 6, 'p', 'a', pragma); - + CASE( 7, 'd', 'f', defined); CASE( 7, 'i', 'c', include); CASE( 7, 'w', 'r', warning); @@ -328,7 +328,7 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { CASE(12, 'i', 'c', include_next); CASE(14, '_', 'p', __public_macro); - + CASE(15, '_', 'p', __private_macro); CASE(16, '_', 'i', __include_macros); @@ -566,9 +566,9 @@ ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OIT_None; - + StringRef name = first->getName(); - + if (name.empty()) return OIT_None; switch (name.front()) { case 'a': @@ -593,22 +593,22 @@ ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return SFF_None; - + StringRef name = first->getName(); - + switch (name.front()) { case 'a': if (name == "appendFormat") return SFF_NSString; break; - + case 'i': if (name == "initWithFormat") return SFF_NSString; break; - + case 'l': if (name == "localizedStringWithFormat") return SFF_NSString; break; - + case 's': if (name == "stringByAppendingFormat" || name == "stringWithFormat") return SFF_NSString; diff --git a/lib/Basic/Module.cpp b/lib/Basic/Module.cpp index 2714b98120c06..1a0c190590589 100644 --- a/lib/Basic/Module.cpp +++ b/lib/Basic/Module.cpp @@ -58,7 +58,7 @@ Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, if (Parent->ModuleMapIsPrivate) ModuleMapIsPrivate = true; IsMissingRequirement = Parent->IsMissingRequirement; - + Parent->SubModuleIndex[Name] = Parent->SubModules.size(); Parent->SubModules.push_back(this); } @@ -134,10 +134,10 @@ bool Module::isSubModuleOf(const Module *Other) const { do { if (This == Other) return true; - + This = This->Parent; } while (This); - + return false; } @@ -145,7 +145,7 @@ const Module *Module::getTopLevelModule() const { const Module *Result = this; while (Result->Parent) Result = Result->Parent; - + return Result; } @@ -181,16 +181,16 @@ static void printModuleId(raw_ostream &OS, const Container &C) { std::string Module::getFullModuleName(bool AllowStringLiterals) const { SmallVector<StringRef, 2> Names; - + // Build up the set of module names (from innermost to outermost). for (const Module *M = this; M; M = M->Parent) Names.push_back(M->Name); - + std::string Result; llvm::raw_string_ostream Out(Result); printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals); - Out.flush(); + Out.flush(); return Result; } @@ -207,7 +207,7 @@ bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const { Module::DirectoryName Module::getUmbrellaDir() const { if (Header U = getUmbrellaHeader()) return {"", U.Entry->getDir()}; - + return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()}; } @@ -388,7 +388,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { } OS << " {\n"; - + if (!Requirements.empty()) { OS.indent(Indent + 2); OS << "requires "; @@ -401,7 +401,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { } OS << "\n"; } - + if (Header H = getUmbrellaHeader()) { OS.indent(Indent + 2); OS << "umbrella header \""; @@ -411,7 +411,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent + 2); OS << "umbrella \""; OS.write_escaped(D.NameAsWritten); - OS << "\"\n"; + OS << "\"\n"; } if (!ConfigMacros.empty() || ConfigMacrosExhaustive) { @@ -468,7 +468,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent + 2); OS << "export_as" << ExportAsModule << "\n"; } - + for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end(); MI != MIEnd; ++MI) // Print inferred subframework modules so that we don't need to re-infer @@ -477,7 +477,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { // those header files anyway. if (!(*MI)->IsInferred || (*MI)->IsFramework) (*MI)->print(OS, Indent + 2); - + for (unsigned I = 0, N = Exports.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "export "; @@ -554,7 +554,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent + 2); OS << "}\n"; } - + OS.indent(Indent); OS << "}\n"; } diff --git a/lib/Basic/ObjCRuntime.cpp b/lib/Basic/ObjCRuntime.cpp index 8fa0afbe03f2f..311bd067261ad 100644 --- a/lib/Basic/ObjCRuntime.cpp +++ b/lib/Basic/ObjCRuntime.cpp @@ -27,7 +27,7 @@ std::string ObjCRuntime::getAsString() const { llvm::raw_string_ostream Out(Result); Out << *this; } - return Result; + return Result; } raw_ostream &clang::operator<<(raw_ostream &out, const ObjCRuntime &value) { diff --git a/lib/Basic/SourceLocation.cpp b/lib/Basic/SourceLocation.cpp index fef1f44fc8a50..eb916ec76fdcf 100644 --- a/lib/Basic/SourceLocation.cpp +++ b/lib/Basic/SourceLocation.cpp @@ -49,7 +49,7 @@ void SourceLocation::print(raw_ostream &OS, const SourceManager &SM)const{ if (isFileID()) { PresumedLoc PLoc = SM.getPresumedLoc(*this); - + if (PLoc.isInvalid()) { OS << "<invalid>"; return; diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp index ae76817826e11..efa6ad2493b20 100644 --- a/lib/Basic/SourceManager.cpp +++ b/lib/Basic/SourceManager.cpp @@ -105,9 +105,9 @@ llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, if (Buffer.getPointer() || !ContentsEntry) { if (Invalid) *Invalid = isBufferInvalid(); - + return Buffer.getPointer(); - } + } bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile; auto BufferOrError = @@ -141,7 +141,7 @@ llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, << ContentsEntry->getName() << BufferOrError.getError().message(); Buffer.setInt(Buffer.getInt() | InvalidFlag); - + if (Invalid) *Invalid = true; return Buffer.getPointer(); } @@ -187,10 +187,10 @@ llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, << InvalidBOM << ContentsEntry->getName(); Buffer.setInt(Buffer.getInt() | InvalidFlag); } - + if (Invalid) *Invalid = isBufferInvalid(); - + return Buffer.getPointer(); } @@ -672,7 +672,7 @@ StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { bool MyInvalid = false; const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid); if (!SLoc.isFile() || MyInvalid) { - if (Invalid) + if (Invalid) *Invalid = true; return "<<<<<INVALID SOURCE LOCATION>>>>>"; } @@ -684,7 +684,7 @@ StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { if (MyInvalid) return "<<<<<INVALID SOURCE LOCATION>>>>>"; - + return Buf->getBuffer(); } @@ -770,7 +770,7 @@ FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const { unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset(); if (Invalid) return FileID::get(0); - + ++NumProbes; // If the offset of the midpoint is too large, chop the high side of the @@ -1104,7 +1104,7 @@ const char *SourceManager::getCharacterData(SourceLocation SL, if (CharDataInvalid || !Entry.isFile()) { if (Invalid) *Invalid = true; - + return "<<<<INVALID BUFFER>>>>"; } llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer( @@ -1289,7 +1289,7 @@ FoundSpecialChar: /// for the position indicated. This requires building and caching a table of /// line offsets for the MemoryBuffer, so this is not cheap: use only when /// about to emit a diagnostic. -unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, +unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, bool *Invalid) const { if (FID.isInvalid()) { if (Invalid) @@ -1308,10 +1308,10 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, *Invalid = true; return 1; } - + Content = const_cast<ContentCache*>(Entry.getFile().getContentCache()); } - + // If this is the first use of line information for this buffer, compute the /// SourceLineCache for it on demand. if (!Content->SourceLineCache) { @@ -1383,7 +1383,7 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, return LineNo; } -unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, +unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); @@ -1418,7 +1418,7 @@ SourceManager::getFileCharacteristic(SourceLocation Loc) const { const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !SEntry.isFile()) return C_User; - + const SrcMgr::FileInfo &FI = SEntry.getFile(); // If there are no #line directives in this file, just return the whole-file @@ -1466,7 +1466,7 @@ PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !Entry.isFile()) return PresumedLoc(); - + const SrcMgr::FileInfo &FI = Entry.getFile(); const SrcMgr::ContentCache *C = FI.getContentCache(); @@ -1485,7 +1485,7 @@ PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid); if (Invalid) return PresumedLoc(); - + SourceLocation IncludeLoc = FI.getIncludeLoc(); // If we have #line directives in this file, update and overwrite the physical @@ -1621,7 +1621,7 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid); if (Invalid) return FileID(); - + if (MainSLoc.isFile()) { const ContentCache *MainContentCache = MainSLoc.getFile().getContentCache(); @@ -1658,8 +1658,8 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid); if (Invalid) return FileID(); - - if (SLoc.isFile() && + + if (SLoc.isFile() && SLoc.getFile().getContentCache() && SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { FirstFID = FileID::get(I); @@ -1670,7 +1670,7 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { if (FirstFID.isInvalid()) { for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) { const SLocEntry &SLoc = getLoadedSLocEntry(I); - if (SLoc.isFile() && + if (SLoc.isFile() && SLoc.getFile().getContentCache() && SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { FirstFID = FileID::get(-int(I) - 2); @@ -1681,7 +1681,7 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { } // If we haven't found what we want yet, try again, but this time stat() - // each of the files in case the files have changed since we originally + // each of the files in case the files have changed since we originally // parsed the file. if (FirstFID.isInvalid() && (SourceFileName || @@ -1694,13 +1694,13 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid); if (Invalid) return FileID(); - - if (SLoc.isFile()) { - const ContentCache *FileContentCache + + if (SLoc.isFile()) { + const ContentCache *FileContentCache = SLoc.getFile().getContentCache(); const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry : nullptr; - if (Entry && + if (Entry && *SourceFileName == llvm::sys::path::filename(Entry->getName())) { if (Optional<llvm::sys::fs::UniqueID> EntryUID = getActualFileUID(Entry)) { @@ -1712,9 +1712,9 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { } } } - } + } } - + (void) SourceFile; return FirstFID; } @@ -1948,7 +1948,7 @@ SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const { assert(!MacroArgsCache->empty()); MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset); --I; - + unsigned MacroArgBeginOffs = I->first; SourceLocation MacroArgExpandedLoc = I->second; if (MacroArgExpandedLoc.isValid()) @@ -2151,7 +2151,7 @@ void SourceManager::PrintStats() const { << " loaded SLocEntries allocated, " << MaxLoadedOffset - CurrentLoadedOffset << "B of Sloc address space used.\n"; - + unsigned NumLineNumsComputed = 0; unsigned NumFileBytesMapped = 0; for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ @@ -2231,7 +2231,7 @@ ExternalSLocEntrySource::~ExternalSLocEntrySource() = default; SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { size_t malloc_bytes = 0; size_t mmap_bytes = 0; - + for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped()) switch (MemBufferInfos[i]->getMemoryBufferKind()) { @@ -2242,7 +2242,7 @@ SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { malloc_bytes += sized_mapped; break; } - + return MemoryBufferSizes(malloc_bytes, mmap_bytes); } @@ -2252,7 +2252,7 @@ size_t SourceManager::getDataStructureSizes() const { + llvm::capacity_in_bytes(LoadedSLocEntryTable) + llvm::capacity_in_bytes(SLocEntryLoaded) + llvm::capacity_in_bytes(FileInfos); - + if (OverriddenFilesInfo) size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles); diff --git a/lib/Basic/Targets/ARM.cpp b/lib/Basic/Targets/ARM.cpp index efed9b096d563..19fcc5abea97e 100644 --- a/lib/Basic/Targets/ARM.cpp +++ b/lib/Basic/Targets/ARM.cpp @@ -185,6 +185,10 @@ StringRef ARMTargetInfo::getCPUAttr() const { return "8_1A"; case llvm::ARM::ArchKind::ARMV8_2A: return "8_2A"; + case llvm::ARM::ArchKind::ARMV8_3A: + return "8_3A"; + case llvm::ARM::ArchKind::ARMV8_4A: + return "8_4A"; case llvm::ARM::ArchKind::ARMV8MBaseline: return "8M_BASE"; case llvm::ARM::ArchKind::ARMV8MMainline: diff --git a/lib/Basic/Targets/X86.cpp b/lib/Basic/Targets/X86.cpp index 7ae0696ce7e7b..e295cff9d5d2c 100644 --- a/lib/Basic/Targets/X86.cpp +++ b/lib/Basic/Targets/X86.cpp @@ -1757,7 +1757,7 @@ void X86TargetInfo::fillValidCPUList(SmallVectorImpl<StringRef> &Values) const { #define PROC(ENUM, STRING, IS64BIT) \ if (IS64BIT || getTriple().getArch() == llvm::Triple::x86) \ Values.emplace_back(STRING); - // Go through CPUKind checking to ensure that the alias is de-aliased and + // Go through CPUKind checking to ensure that the alias is de-aliased and // 64 bit-ness is checked. #define PROC_ALIAS(ENUM, ALIAS) \ if (checkCPUKind(getCPUKind(ALIAS))) \ diff --git a/lib/Basic/Targets/X86.h b/lib/Basic/Targets/X86.h index b6cb27977b69e..019bc8d51a634 100644 --- a/lib/Basic/Targets/X86.h +++ b/lib/Basic/Targets/X86.h @@ -132,7 +132,7 @@ public: : TargetInfo(Triple) { LongDoubleFormat = &llvm::APFloat::x87DoubleExtended(); } - + unsigned getFloatEvalMethod() const override { // X87 evaluates with 80 bits "long double" precision. return SSELevel == NoSSE ? 2 : 0; @@ -238,7 +238,7 @@ public: void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override; - + static void setSSELevel(llvm::StringMap<bool> &Features, X86SSEEnum Level, bool Enabled); @@ -577,7 +577,7 @@ public: IntPtrType = SignedLong; PtrDiffType = SignedLong; } - + void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { X86_32TargetInfo::getTargetDefines(Opts, Builder); @@ -664,7 +664,7 @@ public: bool hasInt128Type() const override { return true; } unsigned getUnwindWordWidth() const override { return 64; } - + unsigned getRegisterWidth() const override { return 64; } bool validateGlobalRegisterVariable(StringRef RegName, unsigned RegSize, diff --git a/lib/Basic/Warnings.cpp b/lib/Basic/Warnings.cpp index 6306ceabc638a..a999c45a0c3e8 100644 --- a/lib/Basic/Warnings.cpp +++ b/lib/Basic/Warnings.cpp @@ -51,7 +51,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.setElideType(Opts.ElideType); Diags.setPrintTemplateTree(Opts.ShowTemplateTree); Diags.setShowColors(Opts.ShowColors); - + // Handle -ferror-limit if (Opts.ErrorLimit) Diags.setErrorLimit(Opts.ErrorLimit); @@ -75,7 +75,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.getDiagnosticIDs(); // We parse the warning options twice. The first pass sets diagnostic state, // while the second pass reports warnings/errors. This has the effect that - // we follow the more canonical "last option wins" paradigm when there are + // we follow the more canonical "last option wins" paradigm when there are // conflicting options. for (unsigned Report = 0, ReportEnd = 2; Report != ReportEnd; ++Report) { bool SetDiagnostic = (Report == 0); @@ -114,7 +114,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.setSuppressSystemWarnings(!isPositive); continue; } - + // -Weverything is a special case as well. It implicitly enables all // warnings, including ones not explicitly in a warning group. if (Opt == "everything") { @@ -128,8 +128,8 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } continue; } - - // -Werror/-Wno-error is a special case, not controlled by the option + + // -Werror/-Wno-error is a special case, not controlled by the option // table. It also has the "specifier" form of -Werror=foo and -Werror-foo. if (Opt.startswith("error")) { StringRef Specifier; @@ -142,13 +142,13 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } Specifier = Opt.substr(6); } - + if (Specifier.empty()) { if (SetDiagnostic) Diags.setWarningsAsErrors(isPositive); continue; } - + if (SetDiagnostic) { // Set the warning as error flag for this specifier. Diags.setDiagnosticGroupWarningAsError(Specifier, isPositive); @@ -157,7 +157,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } continue; } - + // -Wfatal-errors is yet another special case. if (Opt.startswith("fatal-errors")) { StringRef Specifier; @@ -176,7 +176,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.setErrorsAsFatal(isPositive); continue; } - + if (SetDiagnostic) { // Set the error as fatal flag for this specifier. Diags.setDiagnosticGroupErrorAsFatal(Specifier, isPositive); @@ -185,7 +185,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } continue; } - + if (Report) { if (DiagIDs->getDiagnosticsInGroup(Flavor, Opt, _Diags)) EmitUnknownDiagWarning(Diags, Flavor, isPositive ? "-W" : "-Wno-", diff --git a/lib/CodeGen/CGBlocks.cpp b/lib/CodeGen/CGBlocks.cpp index 617856a7b43ed..8269b5b229a28 100644 --- a/lib/CodeGen/CGBlocks.cpp +++ b/lib/CodeGen/CGBlocks.cpp @@ -85,7 +85,7 @@ static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy)); llvm::PointerType *i8p = nullptr; if (CGM.getLangOpts().OpenCL) - i8p = + i8p = llvm::Type::getInt8PtrTy( CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant)); else @@ -117,7 +117,7 @@ static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr()); elements.add(llvm::ConstantExpr::getBitCast( CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p)); - + // GC layout. if (C.getLangOpts().ObjC1) { if (CGM.getLangOpts().getGC() != LangOptions::NonGC) @@ -381,7 +381,7 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, else if (C.getLangOpts().ObjC1 && CGM.getLangOpts().getGC() == LangOptions::NonGC) info.HasCapturedVariableLayout = true; - + // Collect the layout chunks. SmallVector<BlockLayoutChunk, 16> layout; layout.reserve(block->capturesCXXThis() + @@ -487,12 +487,12 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, QualType VT = getCaptureFieldType(*CGF, CI); CharUnits size = C.getTypeSizeInChars(VT); CharUnits align = C.getDeclAlign(variable); - + maxFieldAlign = std::max(maxFieldAlign, align); llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(VT); - + layout.push_back( BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT)); } @@ -509,11 +509,11 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, // to get reproducible results. There should probably be an // llvm::array_pod_stable_sort. std::stable_sort(layout.begin(), layout.end()); - + // Needed for blocks layout info. info.BlockHeaderForcedGapOffset = info.BlockSize; info.BlockHeaderForcedGapSize = CharUnits::Zero(); - + CharUnits &blockSize = info.BlockSize; info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign); @@ -564,7 +564,7 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, } assert(endAlign == getLowBit(blockSize)); - + // At this point, we just have to add padding if the end align still // isn't aligned right. if (endAlign < maxFieldAlign) { @@ -685,7 +685,7 @@ static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) { CleanupKind cleanupKind = InactiveNormalCleanup; bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind); - if (useArrayEHCleanup) + if (useArrayEHCleanup) cleanupKind = InactiveNormalAndEHCleanup; CGF.pushDestroy(cleanupKind, addr, VT, @@ -1315,7 +1315,7 @@ CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, CurGD = GD; CurEHLocation = blockInfo.getBlockExpr()->getLocEnd(); - + BlockInfo = &blockInfo; // Arrange for local static and local extern declarations to appear @@ -1977,7 +1977,7 @@ public: // variable. llvm::Value *value = CGF.Builder.CreateLoad(srcField); - + llvm::Value *null = llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType())); @@ -2149,7 +2149,7 @@ generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo, "src-object"); generator.emitCopy(CGF, destField, srcField); - } + } CGF.FinishFunction(); @@ -2321,7 +2321,7 @@ CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType, BlockFieldFlags flags; if (type->isBlockPointerType()) { flags |= BLOCK_FIELD_IS_BLOCK; - } else if (CGM.getContext().isObjCNSObjectType(type) || + } else if (CGM.getContext().isObjCNSObjectType(type) || type->isObjCObjectPointerType()) { flags |= BLOCK_FIELD_IS_OBJECT; } else { @@ -2380,24 +2380,24 @@ const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) { llvm::StructType *byrefType = llvm::StructType::create(getLLVMContext(), "struct.__block_byref_" + D->getNameAsString()); - + QualType Ty = D->getType(); CharUnits size; SmallVector<llvm::Type *, 8> types; - + // void *__isa; types.push_back(Int8PtrTy); size += getPointerSize(); - + // void *__forwarding; types.push_back(llvm::PointerType::getUnqual(byrefType)); size += getPointerSize(); - + // int32_t __flags; types.push_back(Int32Ty); size += CharUnits::fromQuantity(4); - + // int32_t __size; types.push_back(Int32Ty); size += CharUnits::fromQuantity(4); @@ -2408,7 +2408,7 @@ const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) { /// void *__copy_helper; types.push_back(Int8PtrTy); size += getPointerSize(); - + /// void *__destroy_helper; types.push_back(Int8PtrTy); size += getPointerSize(); diff --git a/lib/CodeGen/CGBlocks.h b/lib/CodeGen/CGBlocks.h index 5a8e960ffcc13..5abf82b3f6e11 100644 --- a/lib/CodeGen/CGBlocks.h +++ b/lib/CodeGen/CGBlocks.h @@ -70,7 +70,7 @@ public: BlockFlags() : flags(0) {} BlockFlags(BlockLiteralFlags flag) : flags(flag) {} BlockFlags(BlockByrefFlags flag) : flags(flag) {} - + uint32_t getBitMask() const { return flags; } bool empty() const { return flags == 0; } @@ -208,7 +208,7 @@ public: Capture v; v.Data = reinterpret_cast<uintptr_t>(value); return v; - } + } }; /// CanBeGlobal - True if the block can be global, i.e. it has @@ -226,13 +226,13 @@ public: /// UsesStret : True if the block uses an stret return. Mutable /// because it gets set later in the block-creation process. mutable bool UsesStret : 1; - + /// HasCapturedVariableLayout : True if block has captured variables /// and their layout meta-data has been generated. bool HasCapturedVariableLayout : 1; /// The mapping of allocated indexes within the block. - llvm::DenseMap<const VarDecl*, Capture> Captures; + llvm::DenseMap<const VarDecl*, Capture> Captures; Address LocalAddress; llvm::StructType *StructureType; @@ -241,7 +241,7 @@ public: CharUnits BlockSize; CharUnits BlockAlign; CharUnits CXXThisOffset; - + // Offset of the gap caused by block header having a smaller // alignment than the alignment of the block descriptor. This // is the gap offset before the first capturued field. diff --git a/lib/CodeGen/CGBuilder.h b/lib/CodeGen/CGBuilder.h index d2e5eb256d3ba..654ef72060b74 100644 --- a/lib/CodeGen/CGBuilder.h +++ b/lib/CodeGen/CGBuilder.h @@ -116,7 +116,7 @@ public: CharUnits Align, bool IsVolatile = false) { return CreateAlignedStore(Val, Addr, Align.getQuantity(), IsVolatile); } - + // FIXME: these "default-aligned" APIs should be removed, // but I don't feel like fixing all the builtin code right now. llvm::StoreInst *CreateDefaultAlignedStore(llvm::Value *Val, diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp index 0892e84a044ce..e99121c46d9b6 100644 --- a/lib/CodeGen/CGBuiltin.cpp +++ b/lib/CodeGen/CGBuiltin.cpp @@ -8848,7 +8848,7 @@ static Value *EmitX86Ternlog(CodeGenFunction &CGF, bool ZeroMask, return EmitX86Select(CGF, Ops[4], Ternlog, PassThru); } -static Value *EmitX86SExtMask(CodeGenFunction &CGF, Value *Op, +static Value *EmitX86SExtMask(CodeGenFunction &CGF, Value *Op, llvm::Type *DstTy) { unsigned NumberOfElements = DstTy->getVectorNumElements(); Value *Mask = getMaskVecValue(CGF, Op, NumberOfElements); @@ -9970,7 +9970,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, Value *A = Builder.CreateExtractElement(Ops[0], (uint64_t)0); Function *F = CGM.getIntrinsic(Intrinsic::sqrt, A->getType()); A = Builder.CreateCall(F, {A}); - return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0); + return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0); } case X86::BI__builtin_ia32_sqrtsd_round_mask: case X86::BI__builtin_ia32_sqrtss_round_mask: { @@ -10282,7 +10282,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, return EmitX86MaskedCompareResult(*this, Cmp, NumElts, Ops[3]); } default: - return getVectorFCmpIR(Pred); + return getVectorFCmpIR(Pred); } } diff --git a/lib/CodeGen/CGCXX.cpp b/lib/CodeGen/CGCXX.cpp index 475f17b77d92e..d5945be43458e 100644 --- a/lib/CodeGen/CGCXX.cpp +++ b/lib/CodeGen/CGCXX.cpp @@ -284,12 +284,12 @@ static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF, /// indirect call to virtual functions. It makes the call through indexing /// into the vtable. CGCallee -CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, +CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty) { assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) && "BuildAppleKextVirtualCall - bad Qual kind"); - + const Type *QTy = Qual->getAsType(); QualType T = QualType(QTy, 0); const RecordType *RT = T->getAs<RecordType>(); diff --git a/lib/CodeGen/CGCXXABI.cpp b/lib/CodeGen/CGCXXABI.cpp index 0611749acf17a..3b1b47cdfe07e 100644 --- a/lib/CodeGen/CGCXXABI.cpp +++ b/lib/CodeGen/CGCXXABI.cpp @@ -51,9 +51,9 @@ CGCallee CGCXXABI::EmitLoadOfMemberFunctionPointer( ErrorUnsupportedABI(CGF, "calls through member pointers"); ThisPtrForCall = This.getPointer(); - const FunctionProtoType *FPT = + const FunctionProtoType *FPT = MPT->getPointeeType()->getAs<FunctionProtoType>(); - const CXXRecordDecl *RD = + const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); diff --git a/lib/CodeGen/CGCall.cpp b/lib/CodeGen/CGCall.cpp index f066ce168588c..fa51dc30c58b9 100644 --- a/lib/CodeGen/CGCall.cpp +++ b/lib/CodeGen/CGCall.cpp @@ -789,7 +789,7 @@ CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType, bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; assert(erased && "Not in set?"); - + return *FI; } @@ -1344,7 +1344,7 @@ static void CreateCoercedStore(llvm::Value *Src, } static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, - const ABIArgInfo &info) { + const ABIArgInfo &info) { if (unsigned offset = info.getDirectOffset()) { addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, @@ -1675,7 +1675,7 @@ llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { if (!isFuncTypeConvertible(FPT)) return llvm::StructType::get(getLLVMContext()); - + const CGFunctionInfo *Info; if (isa<CXXDestructorDecl>(MD)) Info = @@ -2683,7 +2683,7 @@ static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, llvm::Value *retainedValue = retainCall->getArgOperand(0); llvm::LoadInst *load = dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); - if (!load || load->isAtomic() || load->isVolatile() || + if (!load || load->isAtomic() || load->isVolatile() || load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) return nullptr; @@ -3139,7 +3139,7 @@ static void emitWriteback(CodeGenFunction &CGF, // Cast it back, in case we're writing an id to a Foo* or something. value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), "icr.writeback-cast"); - + // Perform the writeback. // If we have a "to use" value, it's something we need to emit a use @@ -3245,7 +3245,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, // isn't null, so we need to register a dominating point so that the cleanups // system will make valid IR. CodeGenFunction::ConditionalEvaluation condEval(CGF); - + // Zero-initialize it if we're not doing a copy-initialization. bool shouldCopy = CRE->shouldCopy(); if (!shouldCopy) { @@ -3269,7 +3269,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); - finalArgument = CGF.Builder.CreateSelect(isNull, + finalArgument = CGF.Builder.CreateSelect(isNull, llvm::ConstantPointerNull::get(destType), temp.getPointer(), "icr.argument"); @@ -3309,7 +3309,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, valueToUse = src; } } - + // Finish the control flow if we needed it. if (shouldCopy && !provablyNonNull) { llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); @@ -3360,7 +3360,7 @@ void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr; unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; - // Prefer the nonnull attribute if it's present. + // Prefer the nonnull attribute if it's present. const NonNullAttr *NNAttr = nullptr; if (SanOpts.has(SanitizerKind::NonnullAttribute)) NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo); @@ -3713,7 +3713,7 @@ void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, getBundlesForFunclet(callee); if (getInvokeDest()) { - llvm::InvokeInst *invoke = + llvm::InvokeInst *invoke = Builder.CreateInvoke(callee, getUnreachableBlock(), getInvokeDest(), diff --git a/lib/CodeGen/CGCall.h b/lib/CodeGen/CGCall.h index 8adbe76fa6c33..99a36e4e12f11 100644 --- a/lib/CodeGen/CGCall.h +++ b/lib/CodeGen/CGCall.h @@ -356,7 +356,7 @@ public: class FunctionArgList : public SmallVector<const VarDecl*, 16> { }; - /// ReturnValueSlot - Contains the address where the return value of a + /// ReturnValueSlot - Contains the address where the return value of a /// function can be stored, and whether the address is volatile or not. class ReturnValueSlot { llvm::PointerIntPair<llvm::Value *, 2, unsigned int> Value; @@ -381,7 +381,7 @@ public: Address getValue() const { return Address(Value.getPointer(), Alignment); } bool isUnused() const { return Value.getInt() & IS_UNUSED; } }; - + } // end namespace CodeGen } // end namespace clang diff --git a/lib/CodeGen/CGClass.cpp b/lib/CodeGen/CGClass.cpp index 0b9311f7771c3..ec4eb000a3b9c 100644 --- a/lib/CodeGen/CGClass.cpp +++ b/lib/CodeGen/CGClass.cpp @@ -655,7 +655,7 @@ static void EmitMemberInitializer(CodeGenFunction &CGF, // the constructor. QualType::DestructionKind dtorKind = FieldType.isDestructedType(); if (CGF.needsEHCleanup(dtorKind)) - CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); + CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); return; } } @@ -685,7 +685,10 @@ void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS, AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - overlapForFieldInit(Field)); + overlapForFieldInit(Field), + AggValueSlot::IsNotZeroed, + // Checks are made by the code that calls constructor. + AggValueSlot::IsSanitizerChecked); EmitAggExpr(Init, Slot); break; } @@ -887,7 +890,7 @@ namespace { SanitizerSet OldSanOpts; }; } // end anonymous namespace - + namespace { class FieldMemcpyizer { public: @@ -1869,12 +1872,14 @@ void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, /// zero-initialized before it is constructed void CodeGenFunction::EmitCXXAggrConstructorCall( const CXXConstructorDecl *ctor, const ArrayType *arrayType, - Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) { + Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked, + bool zeroInitialize) { QualType elementType; llvm::Value *numElements = emitArrayLength(arrayType, elementType, arrayBegin); - EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize); + EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, + NewPointerIsChecked, zeroInitialize); } /// EmitCXXAggrConstructorCall - Emit a loop to call a particular @@ -1890,6 +1895,7 @@ void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, llvm::Value *numElements, Address arrayBase, const CXXConstructExpr *E, + bool NewPointerIsChecked, bool zeroInitialize) { // It's legal for numElements to be zero. This can happen both // dynamically, because x can be zero in 'new A[x]', and statically, @@ -1931,7 +1937,7 @@ void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, // The alignment of the base, adjusted by the size of a single element, // provides a conservative estimate of the alignment of every element. // (This assumes we never start tracking offsetted alignments.) - // + // // Note that these are complete objects and so we don't need to // use the non-virtual size or alignment. QualType type = getContext().getTypeDeclType(ctor->getParent()); @@ -1966,7 +1972,7 @@ void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false, /*Delegating=*/false, curAddr, E, - AggValueSlot::DoesNotOverlap); + AggValueSlot::DoesNotOverlap, NewPointerIsChecked); } // Go to the next element. @@ -2002,7 +2008,8 @@ void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, bool ForVirtualBase, bool Delegating, Address This, const CXXConstructExpr *E, - AggValueSlot::Overlap_t Overlap) { + AggValueSlot::Overlap_t Overlap, + bool NewPointerIsChecked) { CallArgList Args; // Push the this ptr. @@ -2031,7 +2038,7 @@ void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, /*ParamsToSkip*/ 0, Order); EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args, - Overlap, E->getExprLoc()); + Overlap, E->getExprLoc(), NewPointerIsChecked); } static bool canEmitDelegateCallArgs(CodeGenFunction &CGF, @@ -2065,14 +2072,13 @@ void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, Address This, CallArgList &Args, AggValueSlot::Overlap_t Overlap, - SourceLocation Loc) { + SourceLocation Loc, + bool NewPointerIsChecked) { const CXXRecordDecl *ClassDecl = D->getParent(); - // C++11 [class.mfct.non-static]p2: - // If a non-static member function of a class X is called for an object that - // is not of type X, or of a type derived from X, the behavior is undefined. - EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, - This.getPointer(), getContext().getRecordType(ClassDecl)); + if (!NewPointerIsChecked) + EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(), + getContext().getRecordType(ClassDecl), CharUnits::Zero()); if (D->isTrivial() && D->isDefaultConstructor()) { assert(Args.size() == 1 && "trivial default ctor with args"); @@ -2181,7 +2187,7 @@ void CodeGenFunction::EmitInheritedCXXConstructorCall( EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false, This, Args, AggValueSlot::MayOverlap, - E->getLocation()); + E->getLocation(), /*NewPointerIsChecked*/true); } void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall( @@ -2277,8 +2283,10 @@ CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(), /*ParamsToSkip*/ 1); - EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args, - AggValueSlot::MayOverlap, E->getExprLoc()); + EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false, + /*Delegating*/false, This, Args, + AggValueSlot::MayOverlap, E->getExprLoc(), + /*NewPointerIsChecked*/false); } void @@ -2314,7 +2322,8 @@ CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false, /*Delegating=*/true, This, DelegateArgs, - AggValueSlot::MayOverlap, Loc); + AggValueSlot::MayOverlap, Loc, + /*NewPointerIsChecked=*/true); } namespace { @@ -2346,7 +2355,10 @@ CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - AggValueSlot::MayOverlap); + AggValueSlot::MayOverlap, + AggValueSlot::IsNotZeroed, + // Checks are made by the code that calls constructor. + AggValueSlot::IsSanitizerChecked); EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); diff --git a/lib/CodeGen/CGCleanup.cpp b/lib/CodeGen/CGCleanup.cpp index cfd230997ed0c..0a766d1762002 100644 --- a/lib/CodeGen/CGCleanup.cpp +++ b/lib/CodeGen/CGCleanup.cpp @@ -319,7 +319,7 @@ static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name, auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst); load->setAlignment(addr.getAlignment().getQuantity()); return load; -} +} /// All the branch fixups on the EH stack have propagated out past the /// outermost normal cleanup; resolve them all by adding cases to the @@ -621,7 +621,7 @@ static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, ++i; use.set(unreachableBB); - + // The only uses should be fixup switches. llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser()); if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) { @@ -640,7 +640,7 @@ static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, condition->eraseFromParent(); } } - + assert(entry->use_empty()); delete entry; } @@ -659,7 +659,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { Address NormalActiveFlag = Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : Address::invalid(); - Address EHActiveFlag = + Address EHActiveFlag = Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : Address::invalid(); @@ -708,7 +708,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { // cleanup, rewrite it so that it leads to the appropriate place. if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) { llvm::BasicBlock *prebranchDest; - + // If the prebranch is semantically branching through the next // cleanup, just forward it to the next block, leaving the // insertion point in the prebranched block. @@ -922,7 +922,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { } // V. Set up the fallthrough edge out. - + // Case 1: a fallthrough source exists but doesn't branch to the // cleanup because the cleanup is inactive. if (!HasFallthrough && FallthroughSource) { @@ -1025,11 +1025,11 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const { assert(Dest.getScopeDepth().encloses(EHStack.stable_begin()) && "stale jump destination"); - + // Calculate the innermost active normal cleanup. EHScopeStack::stable_iterator TopCleanup = EHStack.getInnermostActiveNormalCleanup(); - + // If we're not in an active normal cleanup scope, or if the // destination scope is within the innermost active normal cleanup // scope, we don't need to worry about fixups. @@ -1119,7 +1119,7 @@ void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) { break; } } - + Builder.ClearInsertionPoint(); } diff --git a/lib/CodeGen/CGCleanup.h b/lib/CodeGen/CGCleanup.h index 93be3e6c1502a..15d6f46dcb56a 100644 --- a/lib/CodeGen/CGCleanup.h +++ b/lib/CodeGen/CGCleanup.h @@ -509,7 +509,7 @@ class EHScopeStack::iterator { public: iterator() : Ptr(nullptr) {} - EHScope *get() const { + EHScope *get() const { return reinterpret_cast<EHScope*>(Ptr); } diff --git a/lib/CodeGen/CGDebugInfo.cpp b/lib/CodeGen/CGDebugInfo.cpp index 097a1e0430479..5be6fb3e4245b 100644 --- a/lib/CodeGen/CGDebugInfo.cpp +++ b/lib/CodeGen/CGDebugInfo.cpp @@ -971,22 +971,27 @@ llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, auto *DescTy = DBuilder.createPointerType(EltTy, Size); FieldOffset = 0; - FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); - EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); - FType = CGM.getContext().IntTy; - EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); - EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); - FType = CGM.getContext().getPointerType(Ty->getPointeeType()); - EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); - - FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); - FieldSize = CGM.getContext().getTypeSize(Ty); - FieldAlign = CGM.getContext().getTypeAlign(Ty); - EltTys.push_back(DBuilder.createMemberType( - Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset, - llvm::DINode::FlagZero, DescTy)); + if (CGM.getLangOpts().OpenCL) { + FType = CGM.getContext().IntTy; + EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); + EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset)); + } else { + FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); + EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); + FType = CGM.getContext().IntTy; + EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); + EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); + FType = CGM.getContext().getPointerType(Ty->getPointeeType()); + EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); + FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); + FieldSize = CGM.getContext().getTypeSize(Ty); + FieldAlign = CGM.getContext().getTypeAlign(Ty); + EltTys.push_back(DBuilder.createMemberType( + Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset, + llvm::DINode::FlagZero, DescTy)); + FieldOffset += FieldSize; + } - FieldOffset += FieldSize; Elements = DBuilder.getOrCreateArray(EltTys); // The __block_literal_generic structs are marked with a special @@ -3847,26 +3852,35 @@ void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, CGM.getDataLayout().getStructLayout(block.StructureType); SmallVector<llvm::Metadata *, 16> fields; - fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public, - blockLayout->getElementOffsetInBits(0), - tunit, tunit)); - fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public, - blockLayout->getElementOffsetInBits(1), - tunit, tunit)); - fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public, - blockLayout->getElementOffsetInBits(2), - tunit, tunit)); - auto *FnTy = block.getBlockExpr()->getFunctionType(); - auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); - fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public, - blockLayout->getElementOffsetInBits(3), - tunit, tunit)); - fields.push_back(createFieldType( - "__descriptor", - C.getPointerType(block.NeedsCopyDispose - ? C.getBlockDescriptorExtendedType() - : C.getBlockDescriptorType()), - loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); + if (CGM.getLangOpts().OpenCL) { + fields.push_back(createFieldType("__size", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(0), + tunit, tunit)); + fields.push_back(createFieldType("__align", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(1), + tunit, tunit)); + } else { + fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public, + blockLayout->getElementOffsetInBits(0), + tunit, tunit)); + fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(1), + tunit, tunit)); + fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(2), + tunit, tunit)); + auto *FnTy = block.getBlockExpr()->getFunctionType(); + auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); + fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public, + blockLayout->getElementOffsetInBits(3), + tunit, tunit)); + fields.push_back(createFieldType( + "__descriptor", + C.getPointerType(block.NeedsCopyDispose + ? C.getBlockDescriptorExtendedType() + : C.getBlockDescriptorType()), + loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); + } // We want to sort the captures by offset, not because DWARF // requires this, but because we're paranoid about debuggers. diff --git a/lib/CodeGen/CGDeclCXX.cpp b/lib/CodeGen/CGDeclCXX.cpp index 5e237d7e0b69c..510863f68eff0 100644 --- a/lib/CodeGen/CGDeclCXX.cpp +++ b/lib/CodeGen/CGDeclCXX.cpp @@ -27,9 +27,9 @@ using namespace CodeGen; static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress DeclPtr) { assert(D.hasGlobalStorage() && "VarDecl must have global storage!"); - assert(!D.getType()->isReferenceType() && + assert(!D.getType()->isReferenceType() && "Should not call EmitDeclInit on a reference!"); - + QualType type = D.getType(); LValue lv = CGF.MakeAddrLValue(DeclPtr, type); @@ -67,7 +67,7 @@ static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D, CodeGenModule &CGM = CGF.CGM; // FIXME: __attribute__((cleanup)) ? - + QualType type = D.getType(); QualType::DestructionKind dtorKind = type.isDestructedType(); @@ -219,7 +219,7 @@ llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD, CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn, FI, FunctionArgList()); llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr); - + // Make sure the call and the callee agree on calling convention. if (llvm::Function *dtorFn = dyn_cast<llvm::Function>(dtor->stripPointerCasts())) @@ -488,7 +488,7 @@ CodeGenModule::EmitCXXGlobalInitFunc() { // Create our global initialization function. if (!PrioritizedCXXGlobalInits.empty()) { SmallVector<llvm::Function *, 8> LocalCXXGlobalInits; - llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), + llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), PrioritizedCXXGlobalInits.end()); // Iterate over "chunks" of ctors with same priority and emit each chunk // into separate function. Note - everything is sorted first by priority, @@ -684,8 +684,8 @@ llvm::Function *CodeGenFunction::generateDestroyHelper( StartFunction(VD, getContext().VoidTy, fn, FI, args); emitDestroy(addr, type, destroyer, useEHCleanupForArray); - + FinishFunction(); - + return fn; } diff --git a/lib/CodeGen/CGException.cpp b/lib/CodeGen/CGException.cpp index c9820c2425543..a2ff102e1ab4d 100644 --- a/lib/CodeGen/CGException.cpp +++ b/lib/CodeGen/CGException.cpp @@ -335,7 +335,7 @@ void CodeGenModule::SimplifyPersonality() { // Nothing to do if it's unused. if (!Fn || Fn->use_empty()) return; - + // Can't do the optimization if it has non-C++ uses. if (!PersonalityHasOnlyCXXUses(Fn)) return; @@ -443,7 +443,7 @@ void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E, void CodeGenFunction::EmitStartEHSpec(const Decl *D) { if (!CGM.getLangOpts().CXXExceptions) return; - + const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); if (!FD) { // Check if CapturedDecl is nothrow and create terminate scope for it. @@ -520,7 +520,7 @@ static void emitFilterDispatchBlock(CodeGenFunction &CGF, void CodeGenFunction::EmitEndEHSpec(const Decl *D) { if (!CGM.getLangOpts().CXXExceptions) return; - + const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); if (!FD) { // Check if CapturedDecl is nothrow and pop terminate scope for it. @@ -1345,7 +1345,7 @@ namespace { CGF.PopCleanupBlock(); CGF.Builder.restoreIP(SavedIP); } - + // Now make sure we actually have an insertion point or the // cleanup gods will hate us. CGF.EnsureInsertPoint(); diff --git a/lib/CodeGen/CGExpr.cpp b/lib/CodeGen/CGExpr.cpp index 3097caacb31c3..f168dd02ead1b 100644 --- a/lib/CodeGen/CGExpr.cpp +++ b/lib/CodeGen/CGExpr.cpp @@ -1820,14 +1820,14 @@ Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); QualType EQT = ExprVT->getElementType(); llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); - + Address CastToPointerElement = Builder.CreateElementBitCast(VectorAddress, VectorElementTy, "conv.ptr.element"); - + const llvm::Constant *Elts = LV.getExtVectorElts(); unsigned ix = getAccessedFieldNo(0, Elts); - + Address VectorBasePtrPlusIx = Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, getContext().getTypeSizeInChars(EQT), @@ -3282,7 +3282,7 @@ static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, for (auto idx : indices.drop_back()) assert(isa<llvm::ConstantInt>(idx) && cast<llvm::ConstantInt>(idx)->isZero()); -#endif +#endif // Determine the element size of the statically-sized base. This is // the thing that the indices are expressed in terms of. @@ -3764,7 +3764,7 @@ LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field) { const RecordDecl *rec = field->getParent(); - + unsigned idx = CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); diff --git a/lib/CodeGen/CGExprAgg.cpp b/lib/CodeGen/CGExprAgg.cpp index 2917404783298..62641102861ce 100644 --- a/lib/CodeGen/CGExprAgg.cpp +++ b/lib/CodeGen/CGExprAgg.cpp @@ -650,7 +650,7 @@ AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { EmitAggLoadOfLValue(E); return; } - + AggValueSlot Slot = EnsureSlot(E->getType()); CGF.EmitAggExpr(E->getInitializer(), Slot); } @@ -766,7 +766,7 @@ void AggExprEmitter::VisitCastExpr(CastExpr *E) { AggValueSlot::DoesNotOverlap, AggValueSlot::IsZeroed); } - + CGF.EmitAggExpr(E->getSubExpr(), valueDest); return; } @@ -801,7 +801,7 @@ void AggExprEmitter::VisitCastExpr(CastExpr *E) { "Implicit cast types must be compatible"); Visit(E->getSubExpr()); break; - + case CK_LValueBitCast: llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); @@ -1140,7 +1140,7 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { Dest); return; } - + LValue LHS = CGF.EmitLValue(E->getLHS()); // If we have an atomic type, evaluate into the destination and then @@ -1155,7 +1155,7 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { // Codegen the RHS so that it stores directly into the LHS. AggValueSlot LHSSlot = - AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, + AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()), AggValueSlot::IsAliased, AggValueSlot::MayOverlap); @@ -1163,7 +1163,7 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { if (!LHSSlot.isVolatile() && CGF.hasVolatileMember(E->getLHS()->getType())) LHSSlot.setVolatile(true); - + CGF.EmitAggExpr(E->getRHS(), LHSSlot); // Copy into the destination if the assignment isn't ignored. @@ -1303,13 +1303,13 @@ static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { // '\0' if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) return CL->getValue() == 0; - + // Otherwise, hard case: conservatively return false. return false; } -void +void AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) { QualType type = LV.getType(); // FIXME: Ignore result? @@ -1326,7 +1326,7 @@ AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) { RValue RV = CGF.EmitReferenceBindingToExpr(E); return CGF.EmitStoreThroughLValue(RV, LV); } - + switch (CGF.getEvaluationKind(type)) { case TEK_Complex: CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true); @@ -1357,7 +1357,7 @@ void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) { // copied into it, we don't have to emit any zeros here. if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type)) return; - + if (CGF.hasScalarEvaluationKind(type)) { // For non-aggregates, we can store the appropriate null constant. llvm::Value *null = CGF.CGM.EmitNullConstant(type); @@ -1501,12 +1501,12 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { if (curInitIndex == NumInitElements && Dest.isZeroed() && CGF.getTypes().isZeroInitializable(E->getType())) break; - + LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field); // We never generate write-barries for initialized fields. LV.setNonGC(true); - + if (curInitIndex < NumInitElements) { // Store the initializer into the field. EmitInitializationToLValue(E->getInit(curInitIndex++), LV); @@ -1535,10 +1535,10 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { pushedCleanup = true; } } - + // If the GEP didn't get used because of a dead zero init or something // else, clean it up for -O0 builds and general tidiness. - if (!pushedCleanup && LV.isSimple()) + if (!pushedCleanup && LV.isSimple()) if (llvm::GetElementPtrInst *GEP = dyn_cast<llvm::GetElementPtrInst>(LV.getPointer())) if (GEP->use_empty()) @@ -1677,7 +1677,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { ILE = dyn_cast<InitListExpr>(ILE->getInit(0)); if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType())) return CGF.getContext().getTypeSizeInChars(E->getType()); - + // InitListExprs for structs have to be handled carefully. If there are // reference members, we need to consider the size of the reference, not the // referencee. InitListExprs for unions and arrays can't have references. @@ -1685,7 +1685,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { if (!RT->isUnionType()) { RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); CharUnits NumNonZeroBytes = CharUnits::Zero(); - + unsigned ILEElement = 0; if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD)) while (ILEElement != CXXRD->getNumBases()) @@ -1701,7 +1701,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { continue; const Expr *E = ILE->getInit(ILEElement++); - + // Reference values are always non-null and have the width of a pointer. if (Field->getType()->isReferenceType()) NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits( @@ -1709,12 +1709,12 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { else NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); } - + return NumNonZeroBytes; } } - - + + CharUnits NumNonZeroBytes = CharUnits::Zero(); for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); @@ -1750,14 +1750,14 @@ static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); if (NumNonZeroBytes*4 > Size) return; - + // Okay, it seems like a good idea to use an initial memset, emit the call. llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity()); - Address Loc = Slot.getAddress(); + Address Loc = Slot.getAddress(); Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty); CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false); - + // Tell the AggExprEmitter that the slot is known zero. Slot.setZeroed(); } @@ -1777,7 +1777,7 @@ void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) { // Optimize the slot if possible. CheckAggExprForMemSetUse(Slot, E, *this); - + AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E)); } @@ -1826,7 +1826,7 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, if (getLangOpts().CPlusPlus) { if (const RecordType *RT = Ty->getAs<RecordType>()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); - assert((Record->hasTrivialCopyConstructor() || + assert((Record->hasTrivialCopyConstructor() || Record->hasTrivialCopyAssignment() || Record->hasTrivialMoveConstructor() || Record->hasTrivialMoveAssignment() || @@ -1899,7 +1899,7 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { RecordDecl *Record = RecordTy->getDecl(); if (Record->hasObjectMember()) { - CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, + CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, SizeVal); return; } @@ -1907,7 +1907,7 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, QualType BaseType = getContext().getBaseElementType(Ty); if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { if (RecordTy->getDecl()->hasObjectMember()) { - CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, + CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, SizeVal); return; } diff --git a/lib/CodeGen/CGExprCXX.cpp b/lib/CodeGen/CGExprCXX.cpp index 8955d8a4a83c9..f29ef754c03f4 100644 --- a/lib/CodeGen/CGExprCXX.cpp +++ b/lib/CodeGen/CGExprCXX.cpp @@ -255,7 +255,7 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); - if (isa<CXXConstructorDecl>(MD) && + if (isa<CXXConstructorDecl>(MD) && cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) return RValue::get(nullptr); @@ -337,7 +337,7 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( // We also don't emit a virtual call if the base expression has a record type // because then we know what the type is. bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; - + if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { assert(CE->arg_begin() == CE->arg_end() && "Destructor shouldn't have explicit parameters"); @@ -367,7 +367,7 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( } return RValue::get(nullptr); } - + CGCallee Callee; if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { Callee = CGCallee::forDirect( @@ -416,20 +416,20 @@ CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, cast<BinaryOperator>(E->getCallee()->IgnoreParens()); const Expr *BaseExpr = BO->getLHS(); const Expr *MemFnExpr = BO->getRHS(); - - const MemberPointerType *MPT = + + const MemberPointerType *MPT = MemFnExpr->getType()->castAs<MemberPointerType>(); - const FunctionProtoType *FPT = + const FunctionProtoType *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>(); - const CXXRecordDecl *RD = + const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); // Emit the 'this' pointer. Address This = Address::invalid(); if (BO->getOpcode() == BO_PtrMemI) This = EmitPointerWithAlignment(BaseExpr); - else + else This = EmitLValue(BaseExpr).getAddress(); EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), @@ -443,10 +443,10 @@ CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, CGCallee Callee = CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, ThisPtrForCall, MemFnPtr, MPT); - + CallArgList Args; - QualType ThisType = + QualType ThisType = getContext().getPointerType(getContext().getTagDeclType(RD)); // Push the this ptr. @@ -570,7 +570,7 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest) { assert(!Dest.isIgnored() && "Must have a destination!"); const CXXConstructorDecl *CD = E->getConstructor(); - + // If we require zero initialization before (or instead of) calling the // constructor, as can be the case with a non-user-provided default // constructor, emit the zero initialization now, unless destination is @@ -588,11 +588,11 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, break; } } - + // If this is a call to a trivial default constructor, do nothing. if (CD->isTrivial() && CD->isDefaultConstructor()) return; - + // Elide the constructor if we're constructing from a temporary. // The temporary check is required because Sema sets this on NRVO // returns. @@ -604,15 +604,16 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, return; } } - + if (const ArrayType *arrayType = getContext().getAsArrayType(E->getType())) { - EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E); + EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E, + Dest.isSanitizerChecked()); } else { CXXCtorType Type = Ctor_Complete; bool ForVirtualBase = false; bool Delegating = false; - + switch (E->getConstructionKind()) { case CXXConstructExpr::CK_Delegating: // We should be emitting a constructor; GlobalDecl will assert this @@ -631,10 +632,11 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, case CXXConstructExpr::CK_NonVirtualBase: Type = Ctor_Base; } - + // Call the constructor. EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, - Dest.getAddress(), E, Dest.mayOverlap()); + Dest.getAddress(), E, Dest.mayOverlap(), + Dest.isSanitizerChecked()); } } @@ -642,19 +644,19 @@ void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp) { if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) Exp = E->getSubExpr(); - assert(isa<CXXConstructExpr>(Exp) && + assert(isa<CXXConstructExpr>(Exp) && "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); const CXXConstructorDecl *CD = E->getConstructor(); RunCleanupsScope Scope(*this); - + // If we require zero initialization before (or instead of) calling the // constructor, as can be the case with a non-user-provided default // constructor, emit the zero initialization now. // FIXME. Do I still need this for a copy ctor synthesis? if (E->requiresZeroInitialization()) EmitNullInitialization(Dest, E->getType()); - + assert(!getContext().getAsConstantArrayType(E->getType()) && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); @@ -709,7 +711,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, // size_t. That's just a gloss, though, and it's wrong in one // important way: if the count is negative, it's an error even if // the cookie size would bring the total size >= 0. - bool isSigned + bool isSigned = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); llvm::IntegerType *numElementsType = cast<llvm::IntegerType>(numElements->getType()); @@ -729,7 +731,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, // This will be a size_t. llvm::Value *size; - + // If someone is doing 'new int[42]' there is no need to do a dynamic check. // Don't bloat the -O0 code. if (llvm::ConstantInt *numElementsC = @@ -820,7 +822,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, } else if (isSigned) { if (numElementsWidth < sizeWidth) numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); - + // If there's a non-1 type size multiplier, then we can do the // signedness check at the same time as we do the multiply // because a negative number times anything will cause an @@ -897,7 +899,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, // numElements doesn't need to be scaled. assert(arraySizeMultiplier == 1); } - + // Add in the cookie size if necessary. if (cookieSize != 0) { sizeWithoutCookie = size; @@ -954,7 +956,8 @@ static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - MayOverlap); + MayOverlap, AggValueSlot::IsNotZeroed, + AggValueSlot::IsSanitizerChecked); CGF.EmitAggExpr(Init, Slot); return; } @@ -1024,7 +1027,9 @@ void CodeGenFunction::EmitNewArrayInitializer( AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - AggValueSlot::DoesNotOverlap); + AggValueSlot::DoesNotOverlap, + AggValueSlot::IsNotZeroed, + AggValueSlot::IsSanitizerChecked); EmitAggExpr(ILE->getInit(0), Slot); // Move past these elements. @@ -1154,6 +1159,7 @@ void CodeGenFunction::EmitNewArrayInitializer( NumElements, llvm::ConstantInt::get(NumElements->getType(), InitListElements)); EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, + /*NewPointerIsChecked*/true, CCE->requiresZeroInitialization()); return; } @@ -1230,7 +1236,7 @@ void CodeGenFunction::EmitNewArrayInitializer( CurPtr = Address(CurPtrPhi, ElementAlign); // Store the new Cleanup position for irregular Cleanups. - if (EndOfInit.isValid()) + if (EndOfInit.isValid()) Builder.CreateStore(CurPtr.getPointer(), EndOfInit); // Enter a partial-destruction Cleanup if necessary. @@ -1705,6 +1711,12 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()), result.getAlignment()); + // Emit sanitizer checks for pointer value now, so that in the case of an + // array it was checked only once and not at each constructor call. + EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, + E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(), + result.getPointer(), allocType); + EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, allocSizeWithoutCookie); if (E->isArray()) { @@ -1737,7 +1749,7 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { resultPtr = PHI; } - + return resultPtr; } @@ -1901,13 +1913,13 @@ static void EmitObjectDelete(CodeGenFunction &CGF, case Qualifiers::OCL_Strong: CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); break; - + case Qualifiers::OCL_Weak: CGF.EmitARCDestroyWeak(Ptr); break; } } - + CGF.PopCleanupBlock(); } @@ -2110,9 +2122,9 @@ static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, } llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { - llvm::Type *StdTypeInfoPtrTy = + llvm::Type *StdTypeInfoPtrTy = ConvertType(E->getType())->getPointerTo(); - + if (E->isTypeOperand()) { llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); @@ -2125,7 +2137,7 @@ llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { // representing the type of the most derived object (that is, the dynamic // type) to which the glvalue refers. if (E->isPotentiallyEvaluated()) - return EmitTypeidFromVTable(*this, E->getExprOperand(), + return EmitTypeidFromVTable(*this, E->getExprOperand(), StdTypeInfoPtrTy); QualType OperandTy = E->getExprOperand()->getType(); @@ -2187,7 +2199,7 @@ llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); - // C++ [expr.dynamic.cast]p4: + // C++ [expr.dynamic.cast]p4: // If the value of v is a null pointer value in the pointer case, the result // is the null pointer value of type T. bool ShouldNullCheckSrcValue = @@ -2197,7 +2209,7 @@ llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, llvm::BasicBlock *CastNull = nullptr; llvm::BasicBlock *CastNotNull = nullptr; llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); - + if (ShouldNullCheckSrcValue) { CastNull = createBasicBlock("dynamic_cast.null"); CastNotNull = createBasicBlock("dynamic_cast.notnull"); diff --git a/lib/CodeGen/CGExprConstant.cpp b/lib/CodeGen/CGExprConstant.cpp index cfd0b859233ab..68766479a539c 100644 --- a/lib/CodeGen/CGExprConstant.cpp +++ b/lib/CodeGen/CGExprConstant.cpp @@ -57,7 +57,7 @@ public: private: ConstStructBuilder(ConstantEmitter &emitter) - : CGM(emitter.CGM), Emitter(emitter), Packed(false), + : CGM(emitter.CGM), Emitter(emitter), Packed(false), NextFieldOffsetInChars(CharUnits::Zero()), LLVMStructAlignment(CharUnits::One()) { } @@ -244,11 +244,11 @@ void ConstStructBuilder::AppendBitField(const FieldDecl *Field, assert(AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && "Expected non-empty array padding of undefs"); - + // Remove the padding array. NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements()); Elements.pop_back(); - + // Add the padding back in two chunks. AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1)); AppendPadding(CharUnits::One()); @@ -269,7 +269,7 @@ void ConstStructBuilder::AppendBitField(const FieldDecl *Field, if (CGM.getDataLayout().isBigEndian()) { // We want the high bits. - Tmp = + Tmp = FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth); } else { // We want the low bits. @@ -314,14 +314,14 @@ void ConstStructBuilder::AppendPadding(CharUnits PadSize) { llvm::Constant *C = llvm::UndefValue::get(Ty); Elements.push_back(C); - assert(getAlignment(C) == CharUnits::One() && + assert(getAlignment(C) == CharUnits::One() && "Padding must have 1 byte alignment!"); NextFieldOffsetInChars += getSizeInChars(C); } void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) { - assert(NextFieldOffsetInChars <= RecordSize && + assert(NextFieldOffsetInChars <= RecordSize && "Size mismatch!"); AppendPadding(RecordSize - NextFieldOffsetInChars); @@ -364,7 +364,7 @@ void ConstStructBuilder::ConvertStructToPacked() { LLVMStructAlignment = CharUnits::One(); Packed = true; } - + bool ConstStructBuilder::Build(InitListExpr *ILE) { RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl(); const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); @@ -972,7 +972,7 @@ public: unsigned NumInitElements = Updater->getNumInits(); unsigned NumElements = AType->getNumElements(); - + std::vector<llvm::Constant *> Elts; Elts.reserve(NumElements); @@ -1006,7 +1006,7 @@ public: Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType); else Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType); - + if (!Elts[i]) return nullptr; RewriteType |= (Elts[i]->getType() != ElemType); @@ -1037,17 +1037,17 @@ public: auto C = Visit(E->getBase(), destType); if (!C) return nullptr; return EmitDesignatedInitUpdater(C, E->getUpdater(), destType); - } + } llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) { if (!E->getConstructor()->isTrivial()) return nullptr; // FIXME: We should not have to call getBaseElementType here. - const RecordType *RT = + const RecordType *RT = CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>(); const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); - + // If the class doesn't have a trivial destructor, we can't emit it as a // constant expr. if (!RD->hasTrivialDestructor()) @@ -1482,7 +1482,7 @@ llvm::Constant * ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) { auto nonMemoryDestType = getNonMemoryType(CGM, destType); auto C = tryEmitAbstract(E, nonMemoryDestType); - return (C ? emitForMemory(C, destType) : nullptr); + return (C ? emitForMemory(C, destType) : nullptr); } llvm::Constant * @@ -1490,7 +1490,7 @@ ConstantEmitter::tryEmitAbstractForMemory(const APValue &value, QualType destType) { auto nonMemoryDestType = getNonMemoryType(CGM, destType); auto C = tryEmitAbstract(value, nonMemoryDestType); - return (C ? emitForMemory(C, destType) : nullptr); + return (C ? emitForMemory(C, destType) : nullptr); } llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E, @@ -2064,8 +2064,7 @@ static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, if (record->isUnion()) { if (Field->getIdentifier()) break; - if (const auto *FieldRD = - dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl())) + if (const auto *FieldRD = Field->getType()->getAsRecordDecl()) if (FieldRD->findFirstNamedDataMember()) break; } @@ -2074,7 +2073,7 @@ static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, // Fill in the virtual bases, if we're working with the complete object. if (CXXR && asCompleteObject) { for (const auto &I : CXXR->vbases()) { - const CXXRecordDecl *base = + const CXXRecordDecl *base = cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); // Ignore empty bases. @@ -2096,7 +2095,7 @@ static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, if (!elements[i]) elements[i] = llvm::Constant::getNullValue(structure->getElementType(i)); } - + return llvm::ConstantStruct::get(structure, elements); } @@ -2126,7 +2125,7 @@ llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { if (getTypes().isZeroInitializable(T)) return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); - + if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { llvm::ArrayType *ATy = cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); diff --git a/lib/CodeGen/CGExprScalar.cpp b/lib/CodeGen/CGExprScalar.cpp index 783f74c5026d3..c62588c682722 100644 --- a/lib/CodeGen/CGExprScalar.cpp +++ b/lib/CodeGen/CGExprScalar.cpp @@ -299,13 +299,31 @@ public: Value *Src, QualType SrcType, QualType DstType, llvm::Type *DstTy, SourceLocation Loc); + /// Known implicit conversion check kinds. + /// Keep in sync with the enum of the same name in ubsan_handlers.h + enum ImplicitConversionCheckKind : unsigned char { + ICCK_IntegerTruncation = 0, + }; + + /// Emit a check that an [implicit] truncation of an integer does not + /// discard any bits. It is not UB, so we use the value after truncation. + void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst, + QualType DstType, SourceLocation Loc); + /// Emit a conversion from the specified type to the specified destination /// type, both of which are LLVM scalar types. - Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, - SourceLocation Loc); + struct ScalarConversionOpts { + bool TreatBooleanAsSigned; + bool EmitImplicitIntegerTruncationChecks; - Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, - SourceLocation Loc, bool TreatBooleanAsSigned); + ScalarConversionOpts() + : TreatBooleanAsSigned(false), + EmitImplicitIntegerTruncationChecks(false) {} + }; + Value * + EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, + SourceLocation Loc, + ScalarConversionOpts Opts = ScalarConversionOpts()); /// Emit a conversion from the specified complex type to the specified /// destination type, where the destination type is an LLVM scalar type. @@ -923,18 +941,59 @@ void ScalarExprEmitter::EmitFloatConversionCheck( SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc); } -/// Emit a conversion from the specified type to the specified destination type, -/// both of which are LLVM scalar types. -Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, - QualType DstType, - SourceLocation Loc) { - return EmitScalarConversion(Src, SrcType, DstType, Loc, false); +void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, + Value *Dst, QualType DstType, + SourceLocation Loc) { + if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerTruncation)) + return; + + llvm::Type *SrcTy = Src->getType(); + llvm::Type *DstTy = Dst->getType(); + + // We only care about int->int conversions here. + // We ignore conversions to/from pointer and/or bool. + if (!(SrcType->isIntegerType() && DstType->isIntegerType())) + return; + + assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && + "clang integer type lowered to non-integer llvm type"); + + unsigned SrcBits = SrcTy->getScalarSizeInBits(); + unsigned DstBits = DstTy->getScalarSizeInBits(); + // This must be truncation. Else we do not care. + if (SrcBits <= DstBits) + return; + + assert(!DstType->isBooleanType() && "we should not get here with booleans."); + + CodeGenFunction::SanitizerScope SanScope(&CGF); + + llvm::Value *Check = nullptr; + + // 1. Extend the truncated value back to the same width as the Src. + bool InputSigned = DstType->isSignedIntegerOrEnumerationType(); + Check = Builder.CreateIntCast(Dst, SrcTy, InputSigned, "anyext"); + // 2. Equality-compare with the original source value + Check = Builder.CreateICmpEQ(Check, Src, "truncheck"); + // If the comparison result is 'i1 false', then the truncation was lossy. + + llvm::Constant *StaticArgs[] = { + CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType), + CGF.EmitCheckTypeDescriptor(DstType), + llvm::ConstantInt::get(Builder.getInt8Ty(), ICCK_IntegerTruncation)}; + CGF.EmitCheck(std::make_pair(Check, SanitizerKind::ImplicitIntegerTruncation), + SanitizerHandler::ImplicitConversion, StaticArgs, {Src, Dst}); } +/// Emit a conversion from the specified type to the specified destination type, +/// both of which are LLVM scalar types. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, QualType DstType, SourceLocation Loc, - bool TreatBooleanAsSigned) { + ScalarConversionOpts Opts) { + QualType NoncanonicalSrcType = SrcType; + QualType NoncanonicalDstType = DstType; + SrcType = CGF.getContext().getCanonicalType(SrcType); DstType = CGF.getContext().getCanonicalType(DstType); if (SrcType == DstType) return Src; @@ -1083,7 +1142,7 @@ Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, if (isa<llvm::IntegerType>(SrcTy)) { bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); - if (SrcType->isBooleanType() && TreatBooleanAsSigned) { + if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) { InputSigned = true; } if (isa<llvm::IntegerType>(DstTy)) @@ -1118,6 +1177,10 @@ Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, } } + if (Opts.EmitImplicitIntegerTruncationChecks) + EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res, + NoncanonicalDstType, Loc); + return Res; } @@ -1812,16 +1875,26 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { return Builder.CreateVectorSplat(NumElements, Elt, "splat"); } - case CK_IntegralCast: + case CK_IntegralCast: { + ScalarConversionOpts Opts; + if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerTruncation)) { + if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) + Opts.EmitImplicitIntegerTruncationChecks = !ICE->isPartOfExplicitCast(); + } + return EmitScalarConversion(Visit(E), E->getType(), DestTy, + CE->getExprLoc(), Opts); + } case CK_IntegralToFloating: case CK_FloatingToIntegral: case CK_FloatingCast: return EmitScalarConversion(Visit(E), E->getType(), DestTy, CE->getExprLoc()); - case CK_BooleanToSignedIntegral: + case CK_BooleanToSignedIntegral: { + ScalarConversionOpts Opts; + Opts.TreatBooleanAsSigned = true; return EmitScalarConversion(Visit(E), E->getType(), DestTy, - CE->getExprLoc(), - /*TreatBooleanAsSigned=*/true); + CE->getExprLoc(), Opts); + } case CK_IntegralToBoolean: return EmitIntToBoolConversion(Visit(E)); case CK_PointerToBoolean: @@ -2766,7 +2839,7 @@ static Value *emitPointerArithmetic(CodeGenFunction &CGF, // if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(), op.Opcode, - expr->getLHS(), + expr->getLHS(), expr->getRHS())) return CGF.Builder.CreateIntToPtr(index, pointer->getType()); diff --git a/lib/CodeGen/CGLoopInfo.cpp b/lib/CodeGen/CGLoopInfo.cpp index 28998ce8db446..21e2b8dd8c31b 100644 --- a/lib/CodeGen/CGLoopInfo.cpp +++ b/lib/CodeGen/CGLoopInfo.cpp @@ -155,7 +155,7 @@ void LoopInfoStack::push(BasicBlock *Header, clang::ASTContext &Ctx, unsigned ValueInt = 1; // Translate opencl_unroll_hint attribute argument to // equivalent LoopHintAttr enums. - // OpenCL v2.0 s6.11.5: + // OpenCL v2.0 s6.11.5: // 0 - full unroll (no argument). // 1 - disable unroll. // other positive integer n - unroll by n. diff --git a/lib/CodeGen/CGObjC.cpp b/lib/CodeGen/CGObjC.cpp index 81c1201c0e063..b94bbf2a384f2 100644 --- a/lib/CodeGen/CGObjC.cpp +++ b/lib/CodeGen/CGObjC.cpp @@ -45,7 +45,7 @@ static llvm::Constant *getNullForVariable(Address addr) { /// Emits an instance of NSConstantString representing the object. llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) { - llvm::Constant *C = + llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer(); // FIXME: This bitcast should just be made an invariant on the Runtime. return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); @@ -65,7 +65,7 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { assert(BoxingMethod && "BoxingMethod is null"); assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method"); Selector Sel = BoxingMethod->getSelector(); - + // Generate a reference to the class pointer, which will be the receiver. // Assumes that the method was introduced in the class that should be // messaged (avoids pulling it out of the result type). @@ -76,8 +76,8 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { CallArgList Args; const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin(); QualType ArgQT = ArgDecl->getType().getUnqualifiedType(); - - // ObjCBoxedExpr supports boxing of structs and unions + + // ObjCBoxedExpr supports boxing of structs and unions // via [NSValue valueWithBytes:objCType:] const QualType ValueType(SubExpr->getType().getCanonicalType()); if (ValueType->isObjCBoxableRecordType()) { @@ -92,7 +92,7 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { std::string Str; getContext().getObjCEncodingForType(ValueType, Str); llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer(); - + // Cast type encoding to correct type const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1]; QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType(); @@ -106,7 +106,7 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { RValue result = Runtime.GenerateMessageSend( *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver, Args, ClassDecl, BoxingMethod); - return Builder.CreateBitCast(result.getScalarVal(), + return Builder.CreateBitCast(result.getScalarVal(), ConvertType(E->getType())); } @@ -119,7 +119,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, DLE = cast<ObjCDictionaryLiteral>(E); // Optimize empty collections by referencing constants, when available. - uint64_t NumElements = + uint64_t NumElements = ALE ? ALE->getNumElements() : DLE->getNumElements(); if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) { StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__"; @@ -138,8 +138,8 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()), NumElements); QualType ElementType = Context.getObjCIdType().withConst(); - QualType ElementArrayType - = Context.getConstantArrayType(ElementType, APNumElements, + QualType ElementArrayType + = Context.getConstantArrayType(ElementType, APNumElements, ArrayType::Normal, /*IndexTypeQuals=*/0); // Allocate the temporary array(s). @@ -147,7 +147,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, Address Keys = Address::invalid(); if (DLE) Keys = CreateMemTemp(ElementArrayType, "keys"); - + // In ARC, we may need to do extra work to keep all the keys and // values alive until after the call. SmallVector<llvm::Value *, 16> NeededObjects; @@ -169,7 +169,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, if (TrackNeededObjects) { NeededObjects.push_back(value); } - } else { + } else { // Emit the key and store it to the appropriate array slot. const Expr *Key = DLE->getKeyValueElement(i).Key; LValue KeyLV = MakeAddrLValue( @@ -191,9 +191,9 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, } } } - + // Generate the argument list. - CallArgList Args; + CallArgList Args; ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin(); const ParmVarDecl *argDecl = *PI++; QualType ArgQT = argDecl->getType().getUnqualifiedType(); @@ -205,7 +205,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, } argDecl = *PI; ArgQT = argDecl->getType().getUnqualifiedType(); - llvm::Value *Count = + llvm::Value *Count = llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements); Args.add(RValue::get(Count), ArgQT); @@ -214,7 +214,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, QualType ResultType = E->getType(); const ObjCObjectPointerType *InterfacePointerType = ResultType->getAsObjCInterfacePointerType(); - ObjCInterfaceDecl *Class + ObjCInterfaceDecl *Class = InterfacePointerType->getObjectType()->getInterface(); CGObjCRuntime &Runtime = CGM.getObjCRuntime(); llvm::Value *Receiver = Runtime.GetClass(*this, Class); @@ -232,7 +232,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, EmitARCIntrinsicUse(NeededObjects); } - return Builder.CreateBitCast(result.getScalarVal(), + return Builder.CreateBitCast(result.getScalarVal(), ConvertType(E->getType())); } @@ -557,7 +557,7 @@ void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, if (CGM.getLangOpts().ObjCAutoRefCount && OMD->isInstanceMethod() && OMD->getSelector().isUnarySelector()) { - const IdentifierInfo *ident = + const IdentifierInfo *ident = OMD->getSelector().getIdentifierInfoForSlot(0); if (ident->isStr("dealloc")) EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind()); @@ -580,7 +580,7 @@ void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { /// emitStructGetterCall - Call the runtime function to load a property /// into the return value slot. -static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, +static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, bool isAtomic, bool hasStrong) { ASTContext &Context = CGF.getContext(); @@ -588,7 +588,7 @@ static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0) .getAddress(); - // objc_copyStruct (ReturnValue, &structIvar, + // objc_copyStruct (ReturnValue, &structIvar, // sizeof (Type of Ivar), isAtomic, false); CallArgList args; @@ -844,30 +844,30 @@ static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) { return false; } -/// emitCPPObjectAtomicGetterCall - Call the runtime function to +/// emitCPPObjectAtomicGetterCall - Call the runtime function to /// copy the ivar into the resturn slot. -static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, +static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, llvm::Value *returnAddr, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn) { // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar, // AtomicHelperFn); CallArgList args; - + // The 1st argument is the return Slot. args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy); - + // The 2nd argument is the address of the ivar. - llvm::Value *ivarAddr = - CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), + llvm::Value *ivarAddr = + CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0).getPointer(); ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); - + // Third argument is the helper function. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); - - llvm::Constant *copyCppAtomicObjectFn = + + llvm::Constant *copyCppAtomicObjectFn = CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction(); CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn); CGF.EmitCall( @@ -889,7 +889,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, } else { ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); - emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(), + emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(), ivar, AtomicHelperFn); } return; @@ -899,7 +899,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, QualType propType = prop->getType(); ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl(); - ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); + ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); // Pick an implementation strategy. PropertyImplStrategy strategy(CGM, propImpl); @@ -1039,7 +1039,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, value = Builder.CreateBitCast( value, ConvertType(GetterMethodDecl->getReturnType())); } - + EmitReturnOfRValue(RValue::get(value), propType); return; } @@ -1055,7 +1055,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, /// from the first formal parameter into the given ivar. static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar) { - // objc_copyStruct (&structIvar, &Arg, + // objc_copyStruct (&structIvar, &Arg, // sizeof (struct something), true, false); CallArgList args; @@ -1068,7 +1068,7 @@ static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, // The second argument is the address of the parameter variable. ParmVarDecl *argVar = *OMD->param_begin(); - DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), + DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), VK_LValue, SourceLocation()); llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(); argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); @@ -1093,36 +1093,36 @@ static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, callee, ReturnValueSlot(), args); } -/// emitCPPObjectAtomicSetterCall - Call the runtime function to store -/// the value from the first formal parameter into the given ivar, using +/// emitCPPObjectAtomicSetterCall - Call the runtime function to store +/// the value from the first formal parameter into the given ivar, using /// the Cpp API for atomic Cpp objects with non-trivial copy assignment. -static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, +static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn) { - // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, + // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, // AtomicHelperFn); CallArgList args; - + // The first argument is the address of the ivar. - llvm::Value *ivarAddr = - CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), + llvm::Value *ivarAddr = + CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0).getPointer(); ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); - + // The second argument is the address of the parameter variable. ParmVarDecl *argVar = *OMD->param_begin(); - DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), + DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), VK_LValue, SourceLocation()); llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(); argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); - + // Third argument is the helper function. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); - - llvm::Constant *fn = + + llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction(); CGCallee callee = CGCallee::forDirect(fn); CGF.EmitCall( @@ -1168,7 +1168,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl(); - + // Just use the setter expression if Sema gave us one and it's // non-trivial. if (!hasTrivialSetExpr(propImpl)) { @@ -1221,7 +1221,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, llvm::Constant *setPropertyFn = nullptr; if (UseOptimizedSetter(CGM)) { // 10.8 and iOS 6.0 code and GC is off - setOptimizedPropertyFn = + setOptimizedPropertyFn = CGM.getObjCRuntime() .GetOptimizedPropertySetFunction(strategy.isAtomic(), strategy.isCopy()); @@ -1237,7 +1237,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, return; } } - + // Emit objc_setProperty((id) self, _cmd, offset, arg, // <is-atomic>, <is-copy>). llvm::Value *cmd = @@ -1272,7 +1272,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args), callee, ReturnValueSlot(), args); } - + return; } @@ -1301,7 +1301,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack, argType.getUnqualifiedType(), CK_LValueToRValue, &arg, VK_RValue); - + // The property type can differ from the ivar type in some situations with // Objective-C pointer types, we can always bit cast the RHS in these cases. // The following absurdity is just to ensure well-formed IR. @@ -1435,7 +1435,7 @@ void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, for (const auto *IvarInit : IMP->inits()) { FieldDecl *Field = IvarInit->getAnyMember(); ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); - LValue LV = EmitLValueForIvar(TypeOfSelfObject(), + LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0); EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed, @@ -2015,7 +2015,7 @@ static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) { } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) { llvm::FunctionType *type = llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false); - + marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); // If we're at -O1 and above, we don't want to litter the code @@ -2368,10 +2368,10 @@ llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); Selector AllocSel = getContext().Selectors.getSelector(0, &II); CallArgList Args; - RValue AllocRV = - Runtime.GenerateMessageSend(*this, ReturnValueSlot(), + RValue AllocRV = + Runtime.GenerateMessageSend(*this, ReturnValueSlot(), getContext().getObjCIdType(), - AllocSel, Receiver, Args); + AllocSel, Receiver, Args); // [Receiver init] Receiver = AllocRV.getScalarVal(); @@ -2380,7 +2380,7 @@ llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { RValue InitRV = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), getContext().getObjCIdType(), - InitSel, Receiver, Args); + InitSel, Receiver, Args); return InitRV.getScalarVal(); } @@ -2391,7 +2391,7 @@ void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { Selector DrainSel = getContext().Selectors.getSelector(0, &II); CallArgList Args; CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), - getContext().VoidTy, DrainSel, Arg, Args); + getContext().VoidTy, DrainSel, Arg, Args); } void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, @@ -2471,7 +2471,7 @@ static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, e = e->IgnoreParens(); QualType type = e->getType(); - // If we're loading retained from a __strong xvalue, we can avoid + // If we're loading retained from a __strong xvalue, we can avoid // an extra retain/release pair by zeroing out the source of this // "move" operation. if (e->isXValue() && @@ -2479,14 +2479,14 @@ static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, type.getObjCLifetime() == Qualifiers::OCL_Strong) { // Emit the lvalue. LValue lv = CGF.EmitLValue(e); - + // Load the object pointer. llvm::Value *result = CGF.EmitLoadOfLValue(lv, SourceLocation()).getScalarVal(); - + // Set the source pointer to NULL. CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv); - + return TryEmitResult(result, true); } @@ -3225,7 +3225,7 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"); if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty))) return HelperFn; - + ASTContext &C = getContext(); IdentifierInfo *II = &CGM.getContext().Idents.get("__assign_helper_atomic_property_"); @@ -3241,7 +3241,7 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( QualType SrcTy = Ty; SrcTy.addConst(); SrcTy = C.getPointerType(SrcTy); - + FunctionArgList args; ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr, DestTy, ImplicitParamDecl::Other); @@ -3254,7 +3254,7 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args); llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); - + llvm::Function *Fn = llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, "__assign_helper_atomic_property_", @@ -3263,23 +3263,23 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); StartFunction(FD, C.VoidTy, Fn, FI, args); - + DeclRefExpr DstExpr(&DstDecl, false, DestTy, VK_RValue, SourceLocation()); UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary, SourceLocation(), false); - + DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy, VK_RValue, SourceLocation()); UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary, SourceLocation(), false); - + Expr *Args[2] = { &DST, &SRC }; CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment()); CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(), VK_LValue, SourceLocation(), FPOptions()); - + EmitStmt(&TheCall); FinishFunction(); @@ -3307,8 +3307,8 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"); if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty))) return HelperFn; - - + + ASTContext &C = getContext(); IdentifierInfo *II = &CGM.getContext().Idents.get("__copy_helper_atomic_property_"); @@ -3324,7 +3324,7 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( QualType SrcTy = Ty; SrcTy.addConst(); SrcTy = C.getPointerType(SrcTy); - + FunctionArgList args; ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr, DestTy, ImplicitParamDecl::Other); @@ -3337,7 +3337,7 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args); llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); - + llvm::Function *Fn = llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_", &CGM.getModule()); @@ -3345,16 +3345,16 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); StartFunction(FD, C.VoidTy, Fn, FI, args); - + DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy, VK_RValue, SourceLocation()); - + UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary, SourceLocation(), false); - - CXXConstructExpr *CXXConstExpr = + + CXXConstructExpr *CXXConstExpr = cast<CXXConstructExpr>(PID->getGetterCXXConstructor()); - + SmallVector<Expr*, 4> ConstructorArgs; ConstructorArgs.push_back(&SRC); ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()), @@ -3371,21 +3371,21 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( CXXConstExpr->requiresZeroInitialization(), CXXConstExpr->getConstructionKind(), SourceRange()); - + DeclRefExpr DstExpr(&DstDecl, false, DestTy, VK_RValue, SourceLocation()); - + RValue DV = EmitAnyExpr(&DstExpr); CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType()); - EmitAggExpr(TheCXXConstructExpr, + EmitAggExpr(TheCXXConstructExpr, AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment), Qualifiers(), AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap)); - + FinishFunction(); HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); CGM.setAtomicGetterHelperFnMap(Ty, HelperFn); diff --git a/lib/CodeGen/CGObjCGNU.cpp b/lib/CodeGen/CGObjCGNU.cpp index 6a0554b46b1c7..3e994edc976be 100644 --- a/lib/CodeGen/CGObjCGNU.cpp +++ b/lib/CodeGen/CGObjCGNU.cpp @@ -114,7 +114,7 @@ protected: /// contains the receiver (object) and the expected class. llvm::StructType *ObjCSuperTy; /// struct objc_super*. The type of the argument to the superclass message - /// lookup functions. + /// lookup functions. llvm::PointerType *PtrToObjCSuperTy; /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring /// SEL is included in a header somewhere, in which case it will be whatever @@ -159,7 +159,7 @@ protected: llvm::IntegerType *LongTy; /// LLVM type for C size_t. Used in various runtime data structures. llvm::IntegerType *SizeTy; - /// LLVM type for C intptr_t. + /// LLVM type for C intptr_t. llvm::IntegerType *IntPtrTy; /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions. llvm::IntegerType *PtrDiffTy; @@ -197,7 +197,7 @@ protected: /// Helper function that generates a constant string and returns a pointer to /// the start of the string. The result of this function can be used anywhere - /// where the C code specifies const char*. + /// where the C code specifies const char*. llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") { ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name); return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(), @@ -243,7 +243,7 @@ protected: return MakeConstantString(PD->getNameAsString()); } - /// Push the property attributes into two structure fields. + /// Push the property attributes into two structure fields. void PushPropertyAttributes(ConstantStructBuilder &Fields, const ObjCPropertyDecl *property, bool isSynthesized=true, bool isDynamic=true) { @@ -377,7 +377,7 @@ protected: /// Runtime functions used for memory management in GC mode. Note that clang /// supports code generation for calling these functions, but neither GNU /// runtime actually supports this API properly yet. - LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, + LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, WeakAssignFn, GlobalAssignFn; typedef std::pair<std::string, std::string> ClassAliasPair; @@ -554,7 +554,7 @@ protected: /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 /// bits set to their values, LSB first, while larger ones are stored in a /// structure of this / form: - /// + /// /// struct { int32_t length; int32_t values[length]; }; /// /// The values in the array are stored in host-endian format, with the least @@ -810,7 +810,7 @@ class CGObjCGNUstep : public CGObjCGNU { // Slot_t objc_slot_lookup_super(struct objc_super*, SEL); SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy, PtrToObjCSuperTy, SelectorTy); - // If we're in ObjC++ mode, then we want to make + // If we're in ObjC++ mode, then we want to make if (CGM.getLangOpts().CPlusPlus) { llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); // void *__cxa_begin_catch(void *e) @@ -892,7 +892,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { static constexpr const char *const SelSection = "__objc_selectors"; /// The section for classes. static constexpr const char *const ClsSection = "__objc_classes"; - /// The section for references to classes. + /// The section for references to classes. static constexpr const char *const ClsRefSection = "__objc_class_refs"; /// The section for categories. static constexpr const char *const CatSection = "__objc_cats"; @@ -956,8 +956,8 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { bool isNonASCII = SL->containsNonAscii(); - auto LiteralLength = SL->getLength(); - + auto LiteralLength = SL->getLength(); + if ((CGM.getTarget().getPointerWidth(0) == 64) && (LiteralLength < 9) && !isNonASCII) { // Tiny strings are only used on 64-bit platforms. They store 8 7-bit @@ -1224,7 +1224,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { std::string Name = SymbolForProtocol(ProtocolName); auto *GV = TheModule.getGlobalVariable(Name); if (!GV) { - // Emit a placeholder symbol. + // Emit a placeholder symbol. GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, Name); GV->setAlignment(CGM.getPointerAlign().getQuantity()); @@ -1281,7 +1281,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { return Protocol; EmittedProtocol = true; - + // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; @@ -1680,7 +1680,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { OffsetVar = new llvm::GlobalVariable(TheModule, IntTy, false, llvm::GlobalValue::ExternalLinkage, OffsetValue, OffsetName); - auto ivarVisibility = + auto ivarVisibility = (IVD->getAccessControl() == ObjCIvarDecl::Private || IVD->getAccessControl() == ObjCIvarDecl::Package || classDecl->getVisibility() == HiddenVisibility) ? @@ -1700,14 +1700,14 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { // Bits 0-1 are ownership. // Bit 2 indicates an extended type encoding // Bits 3-8 contain log2(aligment) - ivarBuilder.addInt(Int32Ty, + ivarBuilder.addInt(Int32Ty, (align << 3) | (1<<2) | FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime())); ivarBuilder.finishAndAddTo(ivarArrayBuilder); } ivarArrayBuilder.finishAndAddTo(ivarListBuilder); auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list", - CGM.getPointerAlign(), /*constant*/ false, + CGM.getPointerAlign(), /*constant*/ false, llvm::GlobalValue::PrivateLinkage); classFields.add(ivarList); } @@ -2448,7 +2448,7 @@ CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, // returns. With GCC, this generates a random return value (whatever happens // to be on the stack / in those registers at the time) on most platforms, // and generates an illegal instruction trap on SPARC. With LLVM it corrupts - // the stack. + // the stack. bool isPointerSizedReturn = (ResultType->isAnyPointerType() || ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType()); @@ -2461,7 +2461,7 @@ CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, messageBB = CGF.createBasicBlock("msgSend"); continueBB = CGF.createBasicBlock("continue"); - llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, + llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, llvm::Constant::getNullValue(Receiver->getType())); Builder.CreateCondBr(isNil, continueBB, messageBB); CGF.EmitBlock(messageBB); @@ -2495,7 +2495,7 @@ CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, // If we have non-legacy dispatch specified, we try using the objc_msgSend() // functions. These are not supported on all platforms (or all runtimes on a - // given platform), so we + // given platform), so we switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { case CodeGenOptions::Legacy: imp = LookupIMP(CGF, Receiver, cmd, node, MSI); @@ -2720,7 +2720,7 @@ llvm::Constant *CGObjCGNU::GenerateClassStructure( // Fill in the structure - // isa + // isa Elements.addBitCast(MetaClass, PtrToInt8Ty); // super_class Elements.add(SuperClass); @@ -2869,7 +2869,7 @@ CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) { void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { std::string ProtocolName = PD->getNameAsString(); - + // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; @@ -2977,7 +2977,7 @@ void CGObjCGNU::GenerateProtocolHolderCategory() { /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 /// bits set to their values, LSB first, while larger ones are stored in a /// structure of this / form: -/// +/// /// struct { int32_t length; int32_t values[length]; }; /// /// The values in the array are stored in host-endian format, with the least @@ -3200,7 +3200,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { } // Get the size of instances. - int instanceSize = + int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize().getQuantity(); // Collect information about instance variables. @@ -3291,7 +3291,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { // Collect the same information about synthesized properties, which don't // show up in the instance method lists. for (auto *propertyImpl : OID->property_impls()) - if (propertyImpl->getPropertyImplementation() == + if (propertyImpl->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { ObjCPropertyDecl *property = propertyImpl->getPropertyDecl(); auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { @@ -3718,7 +3718,7 @@ void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF, // interoperate very well with foreign exceptions. // // In Objective-C++ mode, we actually emit something equivalent to the C++ - // exception handler. + // exception handler. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn); } diff --git a/lib/CodeGen/CGObjCMac.cpp b/lib/CodeGen/CGObjCMac.cpp index 0c766575dc218..2b54e7bd67afe 100644 --- a/lib/CodeGen/CGObjCMac.cpp +++ b/lib/CodeGen/CGObjCMac.cpp @@ -57,7 +57,7 @@ private: // should always bitcast before calling them. /// id objc_msgSend (id, SEL, ...) - /// + /// /// The default messenger, used for sends whose ABI is unchanged from /// the all-integer/pointer case. llvm::Constant *getMessageSendFn() const { @@ -184,12 +184,12 @@ public: /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) llvm::PointerType *SelectorPtrTy; - + private: /// ProtocolPtrTy - LLVM type for external protocol handles /// (typeof(Protocol)) llvm::Type *ExternalProtocolPtrTy; - + public: llvm::Type *getExternalProtocolPtrTy() { if (!ExternalProtocolPtrTy) { @@ -200,10 +200,10 @@ public: llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); } - + return ExternalProtocolPtrTy; } - + // SuperCTy - clang type for struct objc_super. QualType SuperCTy; // SuperPtrCTy - clang type for struct objc_super *. @@ -231,7 +231,7 @@ public: llvm::Type *CacheTy; /// CachePtrTy - LLVM type for struct objc_cache *. llvm::PointerType *CachePtrTy; - + llvm::Constant *getGetPropertyFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -269,15 +269,15 @@ public: llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); - // void objc_setProperty_atomic(id self, SEL _cmd, + // void objc_setProperty_atomic(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - // void objc_setProperty_nonatomic(id self, SEL _cmd, + // void objc_setProperty_nonatomic(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - // void objc_setProperty_atomic_copy(id self, SEL _cmd, + // void objc_setProperty_atomic_copy(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, + // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - + SmallVector<CanQualType,4> Params; CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); @@ -297,10 +297,10 @@ public: name = "objc_setProperty_nonatomic_copy"; else name = "objc_setProperty_nonatomic"; - + return CGM.CreateRuntimeFunction(FTy, name); } - + llvm::Constant *getCopyStructFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -316,10 +316,10 @@ public: Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct"); } - + /// This routine declares and returns address of: /// void objc_copyCppObjectAtomic( - /// void *dest, const void *src, + /// void *dest, const void *src, /// void (*copyHelper) (void *dest, const void *source)); llvm::Constant *getCppAtomicObjectFunction() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); @@ -334,7 +334,7 @@ public: Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic"); } - + llvm::Constant *getEnumerationMutationFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -396,7 +396,7 @@ public: llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal"); } - + /// GcAssignIvarFn -- LLVM objc_assign_ivar function. llvm::Constant *getGcAssignIvarFn() { // id objc_assign_ivar(id, id *, ptrdiff_t) @@ -439,7 +439,7 @@ public: llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false); return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow"); } - + /// SyncEnterFn - LLVM object_sync_enter function. llvm::Constant *getSyncEnterFn() { // int objc_sync_enter (id) @@ -550,7 +550,7 @@ public: /// ExceptionDataTy - LLVM type for struct _objc_exception_data. llvm::StructType *ExceptionDataTy; - + /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. llvm::Constant *getExceptionTryEnterFn() { llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; @@ -727,7 +727,7 @@ public: llvm::StructType *EHTypeTy; llvm::Type *EHTypePtrTy; - + ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); }; @@ -760,33 +760,33 @@ public: /// to '\0'. /// I != 0: Currently unused. BLOCK_LAYOUT_OPERATOR = 0, - + /// The next I+1 bytes do not contain a value of object pointer type. /// Note that this can leave the stream unaligned, meaning that /// subsequent word-size instructions do not begin at a multiple of /// the pointer size. BLOCK_LAYOUT_NON_OBJECT_BYTES = 1, - + /// The next I+1 words do not contain a value of object pointer type. /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for /// when the required skip quantity is a multiple of the pointer size. BLOCK_LAYOUT_NON_OBJECT_WORDS = 2, - + /// The next I+1 words are __strong pointers to Objective-C /// objects or blocks. BLOCK_LAYOUT_STRONG = 3, - + /// The next I+1 words are pointers to __block variables. BLOCK_LAYOUT_BYREF = 4, - + /// The next I+1 words are __weak pointers to Objective-C /// objects or blocks. BLOCK_LAYOUT_WEAK = 5, - + /// The next I+1 words are __unsafe_unretained pointers to /// Objective-C objects or blocks. BLOCK_LAYOUT_UNRETAINED = 6 - + /// The next I+1 words are block or object pointers with some /// as-yet-unspecified ownership semantics. If we add more /// flavors of ownership semantics, values will be taken from @@ -795,11 +795,11 @@ public: /// This is included so that older tools can at least continue /// processing the layout past such things. //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10, - + /// All other opcodes are reserved. Halt interpretation and /// treat everything else as opaque. }; - + class RUN_SKIP { public: enum BLOCK_LAYOUT_OPCODE opcode; @@ -809,13 +809,13 @@ public: CharUnits BytePos = CharUnits::Zero(), CharUnits Size = CharUnits::Zero()) : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {} - + // Allow sorting based on byte pos. bool operator<(const RUN_SKIP &b) const { return block_var_bytepos < b.block_var_bytepos; } }; - + protected: llvm::LLVMContext &VMContext; // FIXME! May not be needing this after all. @@ -871,7 +871,7 @@ protected: /// DefinedClasses - List of defined classes. SmallVector<llvm::GlobalValue*, 16> DefinedClasses; - + /// ImplementedClasses - List of @implemented classes. SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses; @@ -952,28 +952,28 @@ protected: bool hasMRCWeakIvars) { return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars); } - + Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout); - + void UpdateRunSkipBlockVars(bool IsByref, Qualifiers::ObjCLifetime LifeTime, CharUnits FieldOffset, CharUnits FieldSize); - + void BuildRCBlockVarRecordLayout(const RecordType *RT, CharUnits BytePos, bool &HasUnion, bool ByrefLayout=false); - + void BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const RecordDecl *RD, ArrayRef<const FieldDecl*> RecFields, CharUnits BytePos, bool &HasUnion, bool ByrefLayout); - + uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout); - + llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout); - + /// GetIvarLayoutName - Returns a unique constant for the given /// ivar layout bitmap. llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, @@ -987,9 +987,9 @@ protected: const ObjCCommonTypesHelper &ObjCTypes, bool IsClassProperty); - /// EmitProtocolMethodTypes - Generate the array of extended method type + /// EmitProtocolMethodTypes - Generate the array of extended method type /// strings. The return value has type Int8PtrPtrTy. - llvm::Constant *EmitProtocolMethodTypes(Twine Name, + llvm::Constant *EmitProtocolMethodTypes(Twine Name, ArrayRef<llvm::Constant*> MethodTypes, const ObjCCommonTypesHelper &ObjCTypes); @@ -1205,7 +1205,7 @@ private: /// for the given class. llvm::Value *EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); - + llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II); @@ -1382,7 +1382,7 @@ private: /// DefinedMetaClasses - List of defined meta-classes. std::vector<llvm::GlobalValue*> DefinedMetaClasses; - + /// isVTableDispatchedSelector - Returns true if SEL is a /// vtable-based selector. bool isVTableDispatchedSelector(Selector Sel); @@ -1453,7 +1453,7 @@ private: bool IsSuper, const CallArgList &CallArgs, const ObjCMethodDecl *Method); - + /// GetClassGlobal - Return the global variable for the Objective-C /// class of the given name. llvm::Constant *GetClassGlobal(StringRef Name, @@ -1467,7 +1467,7 @@ private: /// for the given class reference. llvm::Value *EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); - + llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II, const ObjCInterfaceDecl *ID); @@ -1700,7 +1700,7 @@ struct NullReturnState { // Okay, start emitting the null-receiver block. CGF.EmitBlock(NullBB); - + // Release any consumed arguments we've got. if (Method) { CallArgList::const_iterator I = CallArgs.begin(); @@ -1709,7 +1709,7 @@ struct NullReturnState { const ParmVarDecl *ParamDecl = (*i); if (ParamDecl->hasAttr<NSConsumedAttr>()) { RValue RV = I->getRValue(CGF); - assert(RV.isScalar() && + assert(RV.isScalar() && "NullReturnState::complete - arg not on object"); CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime); } @@ -1839,7 +1839,7 @@ llvm::Constant *CGObjCMac::GetEHType(QualType T) { } if (T->isObjCObjectPointerType()) return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true); - + llvm_unreachable("asking for catch type for ObjC type in fragile runtime"); } @@ -1898,8 +1898,8 @@ llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() { return cast<llvm::Constant>(V); auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass; - std::string str = - StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" + std::string str = + StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" : "OBJC_CLASS_$_" + StringClass; auto GV = GetClassGlobal(str, NotForDefinition); @@ -2162,7 +2162,7 @@ CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, if (RequiresNullCheck) { nullReturn.init(CGF, Arg0); } - + llvm::Instruction *CallSite; Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType); CGCallee Callee = CGCallee::forDirect(Fn); @@ -2202,17 +2202,17 @@ static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT, } llvm_unreachable("bad objc ownership"); } - + // Treat unqualified retainable pointers as strong. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) return Qualifiers::Strong; - + // Walk into C pointer types, but only in GC. if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) { if (const PointerType *PT = FQT->getAs<PointerType>()) return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true); } - + return Qualifiers::GCNone; } @@ -2258,7 +2258,7 @@ namespace { void visitRecord(const RecordType *RT, CharUnits offset); template <class Iterator, class GetOffsetFn> - void visitAggregate(Iterator begin, Iterator end, + void visitAggregate(Iterator begin, Iterator end, CharUnits aggrOffset, const GetOffsetFn &getOffset); @@ -2287,7 +2287,7 @@ namespace { llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { - + llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); if (CGM.getLangOpts().getGC() == LangOptions::NonGC) return nullPtr; @@ -2306,7 +2306,7 @@ llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM, printf("\n block variable layout for block: "); builder.dump(buffer); } - + return C; } @@ -2351,7 +2351,7 @@ void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) { visitRecord(record, fieldOffset); continue; } - + Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type); if (GCAttr == Qualifiers::Strong) { @@ -2374,11 +2374,11 @@ Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT, // If it doesn't, and this is ARC, it has no ownership. if (CGM.getLangOpts().ObjCAutoRefCount) return Qualifiers::OCL_None; - + // In MRC, retainable pointers are owned by non-__block variables. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong; - + return Qualifiers::OCL_None; } @@ -2416,11 +2416,11 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr; CharUnits MaxFieldOffset = CharUnits::Zero(); CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero(); - + if (RecFields.empty()) return; unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); - + for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { const FieldDecl *Field = RecFields[i]; // Note that 'i' here is actually the field index inside RD of Field, @@ -2428,7 +2428,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); CharUnits FieldOffset = CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i)); - + // Skip over unnamed or bitfields if (!Field->getIdentifier() || Field->isBitField()) { LastFieldBitfieldOrUnnamed = Field; @@ -2441,12 +2441,12 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, if (FQT->isRecordType() || FQT->isUnionType()) { if (FQT->isUnionType()) HasUnion = true; - + BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(), BytePos + FieldOffset, HasUnion); continue; } - + if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { const ConstantArrayType *CArray = dyn_cast_or_null<ConstantArrayType>(Array); @@ -2464,7 +2464,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const RecordType *RT = FQT->getAs<RecordType>(); BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset, HasUnion); - + // Replicate layout information for each array element. Note that // one element is already done. uint64_t ElIx = 1; @@ -2494,7 +2494,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, FieldSize); } } - + if (LastFieldBitfieldOrUnnamed) { if (LastFieldBitfieldOrUnnamed->isBitField()) { // Last field was a bitfield. Must update the info. @@ -2521,7 +2521,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, FieldSize); } } - + if (MaxField) UpdateRunSkipBlockVars(false, getBlockCaptureLifetime(MaxField->getType(), ByrefLayout), @@ -2538,7 +2538,7 @@ void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT, llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0)); const llvm::StructLayout *RecLayout = CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty)); - + BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout); } @@ -2580,7 +2580,7 @@ uint64_t CGObjCCommonMac::InlineLayoutInstruction( else return 0; break; - + case 2: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); @@ -2607,7 +2607,7 @@ uint64_t CGObjCCommonMac::InlineLayoutInstruction( else return 0; break; - + case 1: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); @@ -2620,20 +2620,20 @@ uint64_t CGObjCCommonMac::InlineLayoutInstruction( else return 0; break; - + default: return 0; } - + // Cannot inline when any of the word counts is 15. Because this is one less // than the actual work count (so 15 means 16 actual word counts), // and we can only display 0 thru 15 word counts. if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16) return 0; - + unsigned count = (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0); - + if (size == count) { if (strong_word_count) Result = strong_word_count; @@ -2655,12 +2655,12 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; - + // Sort on byte position; captures might not be allocated in order, // and unions can do funny things. llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end()); SmallVector<unsigned char, 16> Layout; - + unsigned size = RunSkipBlockVars.size(); for (unsigned i = 0; i < size; i++) { enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode; @@ -2689,7 +2689,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { size_in_bytes -= residue_in_bytes; opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS; } - + unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes; while (size_in_words >= 16) { // Note that value in imm. is one less that the actual @@ -2710,7 +2710,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { Layout.push_back(inst); } } - + while (!Layout.empty()) { unsigned char inst = Layout.back(); enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); @@ -2719,7 +2719,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { else break; } - + uint64_t Result = InlineLayoutInstruction(Layout); if (Result != 0) { // Block variable layout instruction has been inlined. @@ -2739,13 +2739,13 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { } return llvm::ConstantInt::get(CGM.IntPtrTy, Result); } - + unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0; Layout.push_back(inst); std::string BitMap; for (unsigned i = 0, e = Layout.size(); i != e; i++) BitMap += Layout[i]; - + if (CGM.getLangOpts().ObjCGCBitmapPrint) { if (ComputeByrefLayout) printf("\n Byref variable layout: "); @@ -2798,20 +2798,20 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); - + RunSkipBlockVars.clear(); bool hasUnion = false; - + unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; - + const BlockDecl *blockDecl = blockInfo.getBlockDecl(); - + // Calculate the basic layout of the block structure. const llvm::StructLayout *layout = CGM.getDataLayout().getStructLayout(blockInfo.StructureType); - + // Ignore the optional 'this' capture: C++ objects are not assumed // to be GC'ed. if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero()) @@ -2822,15 +2822,15 @@ llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM, for (const auto &CI : blockDecl->captures()) { const VarDecl *variable = CI.getVariable(); QualType type = variable->getType(); - + const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); - + // Ignore constant captures. if (capture.isConstant()) continue; - + CharUnits fieldOffset = CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex())); - + assert(!type->isArrayType() && "array variable should not be caught"); if (!CI.isByRef()) if (const RecordType *record = type->getAs<RecordType>()) { @@ -2891,7 +2891,7 @@ void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { if (DefinedProtocols.count(PD->getIdentifier())) return GetOrEmitProtocol(PD); - + return GetOrEmitProtocolRef(PD); } @@ -3094,12 +3094,12 @@ CGObjCMac::EmitProtocolList(Twine name, return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); } -static void +static void PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet, SmallVectorImpl<const ObjCPropertyDecl *> &Properties, const ObjCProtocolDecl *Proto, bool IsClassProperty) { - for (const auto *P : Proto->protocols()) + for (const auto *P : Proto->protocols()) PushProtocolProperties(PropertySet, Properties, P, IsClassProperty); for (const auto *PD : Proto->properties()) { @@ -3679,7 +3679,7 @@ llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, auto countSlot = ivarList.addPlaceholder(); auto ivars = ivarList.beginArray(ObjCTypes.IvarTy); - for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); + for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) @@ -3964,7 +3964,7 @@ llvm::Constant *CGObjCMac::GetPropertySetFunction() { return ObjCTypes.getSetPropertyFn(); } -llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, +llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, bool copy) { return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy); } @@ -4959,9 +4959,9 @@ llvm::Constant *CGObjCMac::EmitModuleSymbols() { llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II) { LazySymbols.insert(II); - + llvm::GlobalVariable *&Entry = ClassReferences[II]; - + if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetClassName(II->getName()), @@ -4971,7 +4971,7 @@ llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF, "__OBJC,__cls_refs,literal_pointers,no_dead_strip", CGM.getPointerAlign(), true); } - + return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign()); } @@ -5056,7 +5056,7 @@ void IvarLayoutBuilder::visitRecord(const RecordType *RT, } template <class Iterator, class GetOffsetFn> -void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end, +void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end, CharUnits aggregateOffset, const GetOffsetFn &getOffset) { for (; begin != end; ++begin) { @@ -5317,7 +5317,7 @@ CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD, // MRC weak layout strings follow the ARC style. CharUnits baseOffset; if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { - for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); + for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) ivars.push_back(IVD); @@ -5353,7 +5353,7 @@ CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD, llvm::SmallVector<unsigned char, 4> buffer; llvm::Constant *C = builder.buildBitmap(*this, buffer); - + if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) { printf("\n%s ivar layout for class '%s': ", ForStrongLayout ? "strong" : "weak", @@ -5903,7 +5903,7 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); - + // struct objc_typeinfo { // const void** vtable; // objc_ehtype_vtable + 2 @@ -6033,7 +6033,7 @@ bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) { if (CGM.getLangOpts().getGC() != LangOptions::NonGC) { VTableDispatchMethods.insert(GetNullarySelector("hash")); VTableDispatchMethods.insert(GetUnarySelector("addObject")); - + // "countByEnumeratingWithState:objects:count" IdentifierInfo *KeyIdents[] = { &CGM.getContext().Idents.get("countByEnumeratingWithState"), @@ -6418,12 +6418,12 @@ llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF, void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const char *Prefix = "\01l_OBJC_$_CATEGORY_"; - + llvm::SmallString<64> ExtCatName(Prefix); ExtCatName += Interface->getObjCRuntimeNameAsString(); ExtCatName += "_$_"; ExtCatName += OCD->getNameAsString(); - + ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.CategorynfABITy); values.add(GetClassName(OCD->getIdentifier()->getName())); @@ -6684,7 +6684,7 @@ llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( // FIXME. Consolidate this with similar code in GenerateClass. - for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); + for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) @@ -6785,7 +6785,7 @@ llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; - + auto methodLists = ProtocolMethodLists::get(PD); ConstantInitBuilder builder(CGM); @@ -6824,7 +6824,7 @@ llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( values.add(EmitPropertyList( "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(), nullptr, PD, ObjCTypes, true)); - + if (Entry) { // Already created, fix the linkage and update the initializer. Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); @@ -7058,7 +7058,7 @@ CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility); messageRef->setSection(GetSectionName("__objc_msgrefs", "coalesced")); } - + bool requiresnullCheck = false; if (CGM.getLangOpts().ObjCAutoRefCount && method) for (const auto *ParamDecl : method->parameters()) { @@ -7069,7 +7069,7 @@ CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, break; } } - + Address mref = Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy), CGF.getPointerAlign()); @@ -7153,7 +7153,7 @@ CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { CharUnits Align = CGF.getPointerAlign(); llvm::GlobalVariable *&Entry = ClassReferences[II]; - + if (!Entry) { llvm::Constant *ClassGV; if (ID) { @@ -7243,7 +7243,7 @@ llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF, assert(!isa<llvm::GlobalVariable>(ClassGV) || cast<llvm::GlobalVariable>(ClassGV)->hasExternalWeakLinkage()); } - + return EmitClassRef(CGF, ID); } @@ -7304,7 +7304,7 @@ llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF, Address Addr = EmitSelectorAddr(CGF, Sel); llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr); - LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), + LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), llvm::MDNode::get(VMContext, None)); return LI; } diff --git a/lib/CodeGen/CGObjCRuntime.cpp b/lib/CodeGen/CGObjCRuntime.cpp index 2f886fd82caa7..a43885c0f9a2c 100644 --- a/lib/CodeGen/CGObjCRuntime.cpp +++ b/lib/CodeGen/CGObjCRuntime.cpp @@ -181,7 +181,7 @@ void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, for (unsigned I = 0, E = Handlers.size(); I != E; ++I) Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); } - + // Emit the try body. CGF.EmitStmt(S.getTryBody()); @@ -232,7 +232,7 @@ void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, cleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(Cont); - } + } // Go back to the try-statement fallthrough. CGF.Builder.restoreIP(SavedIP); diff --git a/lib/CodeGen/CGObjCRuntime.h b/lib/CodeGen/CGObjCRuntime.h index a14b44abf413b..ce082a61eb5e4 100644 --- a/lib/CodeGen/CGObjCRuntime.h +++ b/lib/CodeGen/CGObjCRuntime.h @@ -143,7 +143,7 @@ public: /// Generate a constant string object. virtual ConstantAddress GenerateConstantString(const StringLiteral *) = 0; - + /// Generate a category. A category contains a list of methods (and /// accompanying metadata) and a list of protocols. virtual void GenerateCategory(const ObjCCategoryImplDecl *OCD) = 0; @@ -211,7 +211,7 @@ public: virtual llvm::Constant *GetPropertySetFunction() = 0; /// Return the runtime function for optimized setting properties. - virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, + virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, bool copy) = 0; // API for atomic copying of qualified aggregates in getter. @@ -224,17 +224,17 @@ public: /// API for atomic copying of qualified aggregates with non-trivial copy /// assignment (c++) in getter. virtual llvm::Constant *GetCppAtomicObjectGetFunction() = 0; - + /// GetClass - Return a reference to the class for the given /// interface decl. virtual llvm::Value *GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *OID) = 0; - - + + virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { llvm_unreachable("autoreleasepool unsupported in this ABI"); } - + /// EnumerationMutationFunction - Return the function that's called by the /// compiler when a mutation is detected during foreach iteration. virtual llvm::Constant *EnumerationMutationFunction() = 0; diff --git a/lib/CodeGen/CGOpenMPRuntime.cpp b/lib/CodeGen/CGOpenMPRuntime.cpp index 3730b9af12fab..fa850155df4f9 100644 --- a/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/lib/CodeGen/CGOpenMPRuntime.cpp @@ -3750,11 +3750,13 @@ CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() { StringRef T = Device.getTriple(); std::string BeginName = getName({"omp_offloading", "img_start", ""}); auto *ImgBegin = new llvm::GlobalVariable( - M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, + M, CGM.Int8Ty, /*isConstant=*/true, + llvm::GlobalValue::ExternalWeakLinkage, /*Initializer=*/nullptr, Twine(BeginName).concat(T)); std::string EndName = getName({"omp_offloading", "img_end", ""}); auto *ImgEnd = new llvm::GlobalVariable( - M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, + M, CGM.Int8Ty, /*isConstant=*/true, + llvm::GlobalValue::ExternalWeakLinkage, /*Initializer=*/nullptr, Twine(EndName).concat(T)); llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin, @@ -8109,6 +8111,19 @@ void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD, VarName = CGM.getMangledName(VD); VarSize = CGM.getContext().getTypeSizeInChars(VD->getType()); Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false); + // Temp solution to prevent optimizations of the internal variables. + if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) { + std::string RefName = getName({VarName, "ref"}); + if (!CGM.GetGlobalValue(RefName)) { + llvm::Constant *AddrRef = + getOrCreateInternalVariable(Addr->getType(), RefName); + auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef); + GVAddrRef->setConstant(/*Val=*/true); + GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage); + GVAddrRef->setInitializer(Addr); + CGM.addCompilerUsedGlobal(GVAddrRef); + } + } break; case OMPDeclareTargetDeclAttr::MT_Link: Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink; diff --git a/lib/CodeGen/CGRecordLayoutBuilder.cpp b/lib/CodeGen/CGRecordLayoutBuilder.cpp index 4ee6c8e71457a..58aaae692552f 100644 --- a/lib/CodeGen/CGRecordLayoutBuilder.cpp +++ b/lib/CodeGen/CGRecordLayoutBuilder.cpp @@ -166,7 +166,7 @@ struct CGRecordLowering { return Layout.getFieldOffset(FD->getFieldIndex()); } // Layout routines. - void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset, + void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType); /// Lowers an ASTRecordLayout to a llvm type. void lower(bool NonVirtualBaseType); @@ -246,7 +246,7 @@ void CGRecordLowering::lower(bool NVBaseType) { // 1) Store all members (fields and bases) in a list and sort them by offset. // 2) Add a 1-byte capstone member at the Size of the structure. // 3) Clip bitfield storages members if their tail padding is or might be - // used by another field or base. The clipping process uses the capstone + // used by another field or base. The clipping process uses the capstone // by treating it as another object that occurs after the record. // 4) Determine if the llvm-struct requires packing. It's important that this // phase occur after clipping, because clipping changes the llvm type. @@ -313,9 +313,8 @@ void CGRecordLowering::lowerUnion() { if (!SeenNamedMember) { SeenNamedMember = Field->getIdentifier(); if (!SeenNamedMember) - if (const auto *FieldRD = - dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl())) - SeenNamedMember = FieldRD->findFirstNamedDataMember(); + if (const auto *FieldRD = Field->getType()->getAsRecordDecl()) + SeenNamedMember = FieldRD->findFirstNamedDataMember(); if (SeenNamedMember && !isZeroInitializable(Field)) { IsZeroInitializable = IsZeroInitializableAsBase = false; StorageType = FieldType; @@ -437,7 +436,7 @@ CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field, StartBitOffset = getFieldBitOffset(*Field); Tail = StartBitOffset + Field->getBitWidthValue(Context); StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Tail - StartBitOffset, - StartBitOffset); + StartBitOffset); } ++Field; continue; @@ -687,7 +686,7 @@ CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types, uint64_t Offset, uint64_t Size, uint64_t StorageSize, CharUnits StorageOffset) { - // This function is vestigial from CGRecordLayoutBuilder days but is still + // This function is vestigial from CGRecordLayoutBuilder days but is still // used in GCObjCRuntime.cpp. That usage has a "fixme" attached to it that // when addressed will allow for the removal of this function. llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType()); @@ -782,14 +781,14 @@ CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, if (BaseTy) { CharUnits NonVirtualSize = Layout.getNonVirtualSize(); - uint64_t AlignedNonVirtualTypeSizeInBits = + uint64_t AlignedNonVirtualTypeSizeInBits = getContext().toBits(NonVirtualSize); - assert(AlignedNonVirtualTypeSizeInBits == + assert(AlignedNonVirtualTypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(BaseTy) && "Type size mismatch!"); } - + // Verify that the LLVM and AST field offsets agree. llvm::StructType *ST = RL->getLLVMType(); const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST); @@ -807,7 +806,7 @@ CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, "Invalid field offset!"); continue; } - + // Ignore unnamed bit-fields. if (!FD->getDeclName()) continue; @@ -854,7 +853,7 @@ void CGRecordLayout::print(raw_ostream &OS) const { OS << "<CGRecordLayout\n"; OS << " LLVMType:" << *CompleteObjectType << "\n"; if (BaseSubobjectType) - OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n"; + OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n"; OS << " IsZeroInitializable:" << IsZeroInitializable << "\n"; OS << " BitFields:[\n"; diff --git a/lib/CodeGen/CGVTT.cpp b/lib/CodeGen/CGVTT.cpp index 41c8c943f54db..b0a3a0bffa2e6 100644 --- a/lib/CodeGen/CGVTT.cpp +++ b/lib/CodeGen/CGVTT.cpp @@ -30,8 +30,8 @@ GetAddrOfVTTVTable(CodeGenVTables &CGVT, CodeGenModule &CGM, // This is a regular vtable. return CGM.getCXXABI().getAddrOfVTable(MostDerivedClass, CharUnits()); } - - return CGVT.GenerateConstructionVTable(MostDerivedClass, + + return CGVT.GenerateConstructionVTable(MostDerivedClass, VTable.getBaseSubobject(), VTable.isVirtual(), Linkage, @@ -45,7 +45,7 @@ CodeGenVTables::EmitVTTDefinition(llvm::GlobalVariable *VTT, VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/true); llvm::Type *Int8PtrTy = CGM.Int8PtrTy, *Int32Ty = CGM.Int32Ty; - llvm::ArrayType *ArrayType = + llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, Builder.getVTTComponents().size()); SmallVector<llvm::GlobalVariable *, 8> VTables; @@ -117,42 +117,42 @@ llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTT(const CXXRecordDecl *RD) { VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/false); - llvm::ArrayType *ArrayType = + llvm::ArrayType *ArrayType = llvm::ArrayType::get(CGM.Int8PtrTy, Builder.getVTTComponents().size()); llvm::GlobalVariable *GV = - CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, + CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, llvm::GlobalValue::ExternalLinkage); GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); return GV; } -uint64_t CodeGenVTables::getSubVTTIndex(const CXXRecordDecl *RD, +uint64_t CodeGenVTables::getSubVTTIndex(const CXXRecordDecl *RD, BaseSubobject Base) { BaseSubobjectPairTy ClassSubobjectPair(RD, Base); SubVTTIndiciesMapTy::iterator I = SubVTTIndicies.find(ClassSubobjectPair); if (I != SubVTTIndicies.end()) return I->second; - + VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/false); for (llvm::DenseMap<BaseSubobject, uint64_t>::const_iterator I = - Builder.getSubVTTIndicies().begin(), + Builder.getSubVTTIndicies().begin(), E = Builder.getSubVTTIndicies().end(); I != E; ++I) { // Insert all indices. BaseSubobjectPairTy ClassSubobjectPair(RD, I->first); - + SubVTTIndicies.insert(std::make_pair(ClassSubobjectPair, I->second)); } - + I = SubVTTIndicies.find(ClassSubobjectPair); assert(I != SubVTTIndicies.end() && "Did not find index!"); - + return I->second; } -uint64_t +uint64_t CodeGenVTables::getSecondaryVirtualPointerIndex(const CXXRecordDecl *RD, BaseSubobject Base) { SecondaryVirtualPointerIndicesMapTy::iterator I = @@ -164,17 +164,17 @@ CodeGenVTables::getSecondaryVirtualPointerIndex(const CXXRecordDecl *RD, VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/false); // Insert all secondary vpointer indices. - for (llvm::DenseMap<BaseSubobject, uint64_t>::const_iterator I = + for (llvm::DenseMap<BaseSubobject, uint64_t>::const_iterator I = Builder.getSecondaryVirtualPointerIndices().begin(), E = Builder.getSecondaryVirtualPointerIndices().end(); I != E; ++I) { std::pair<const CXXRecordDecl *, BaseSubobject> Pair = std::make_pair(RD, I->first); - + SecondaryVirtualPointerIndices.insert(std::make_pair(Pair, I->second)); } I = SecondaryVirtualPointerIndices.find(std::make_pair(RD, Base)); assert(I != SecondaryVirtualPointerIndices.end() && "Did not find index!"); - + return I->second; } diff --git a/lib/CodeGen/CGVTables.cpp b/lib/CodeGen/CGVTables.cpp index 5a2ec65f7763f..cc334637a8310 100644 --- a/lib/CodeGen/CGVTables.cpp +++ b/lib/CodeGen/CGVTables.cpp @@ -110,7 +110,7 @@ static RValue PerformReturnAdjustment(CodeGenFunction &CGF, return RValue::get(ReturnValue); } -/// This function clones a function's DISubprogram node and enters it into +/// This function clones a function's DISubprogram node and enters it into /// a value map with the intent that the map can be utilized by the cloner /// to short-circuit Metadata node mapping. /// Furthermore, the function resolves any DILocalVariable nodes referenced diff --git a/lib/CodeGen/CGVTables.h b/lib/CodeGen/CGVTables.h index a11474a15ea48..6377659e4cb3d 100644 --- a/lib/CodeGen/CGVTables.h +++ b/lib/CodeGen/CGVTables.h @@ -40,7 +40,7 @@ class CodeGenVTables { typedef std::pair<const CXXRecordDecl *, BaseSubobject> BaseSubobjectPairTy; typedef llvm::DenseMap<BaseSubobjectPairTy, uint64_t> SubVTTIndiciesMapTy; - + /// SubVTTIndicies - Contains indices into the various sub-VTTs. SubVTTIndiciesMapTy SubVTTIndicies; @@ -87,21 +87,21 @@ public: /// getSubVTTIndex - Return the index of the sub-VTT for the base class of the /// given record decl. uint64_t getSubVTTIndex(const CXXRecordDecl *RD, BaseSubobject Base); - + /// getSecondaryVirtualPointerIndex - Return the index in the VTT where the /// virtual pointer for the given subobject is located. uint64_t getSecondaryVirtualPointerIndex(const CXXRecordDecl *RD, BaseSubobject Base); - /// GenerateConstructionVTable - Generate a construction vtable for the given + /// GenerateConstructionVTable - Generate a construction vtable for the given /// base subobject. llvm::GlobalVariable * - GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, - bool BaseIsVirtual, + GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, + bool BaseIsVirtual, llvm::GlobalVariable::LinkageTypes Linkage, VTableAddressPointsMapTy& AddressPoints); - + /// GetAddrOfVTT - Get the address of the VTT for the given record decl. llvm::GlobalVariable *GetAddrOfVTT(const CXXRecordDecl *RD); @@ -112,7 +112,7 @@ public: /// EmitThunks - Emit the associated thunks for the given global decl. void EmitThunks(GlobalDecl GD); - + /// GenerateClassData - Generate all the class data required to be /// generated upon definition of a KeyFunction. This includes the /// vtable, the RTTI data structure (if RTTI is enabled) and the VTT diff --git a/lib/CodeGen/CGValue.h b/lib/CodeGen/CGValue.h index 418bda1f41bb5..0dcbea423ad7d 100644 --- a/lib/CodeGen/CGValue.h +++ b/lib/CodeGen/CGValue.h @@ -197,7 +197,7 @@ class LValue { // objective-c's ivar bool Ivar:1; - + // objective-c's ivar is an array bool ObjIsArray:1; @@ -207,7 +207,7 @@ class LValue { // Lvalue is a global reference of an objective-c object bool GlobalObjCRef : 1; - + // Lvalue is a thread local reference bool ThreadLocalRef : 1; @@ -301,7 +301,7 @@ public: bool isVolatile() const { return Quals.hasVolatile(); } - + Expr *getBaseIvarExp() const { return BaseIvarExp; } void setBaseIvarExp(Expr *V) { BaseIvarExp = V; } @@ -452,7 +452,7 @@ class AggValueSlot { /// slot might require calling an appropriate Objective-C GC /// barrier. The exact interaction here is unnecessarily mysterious. bool ObjCGCFlag : 1; - + /// ZeroedFlag - This is set to true if the memory in the slot is /// known to be zero before the assignment into it. This means that /// zero fields don't need to be set. @@ -472,19 +472,27 @@ class AggValueSlot { /// evaluating an expression which constructs such an object. bool AliasedFlag : 1; - /// This is set to true if the tail padding of this slot might overlap + /// This is set to true if the tail padding of this slot might overlap /// another object that may have already been initialized (and whose /// value must be preserved by this initialization). If so, we may only /// store up to the dsize of the type. Otherwise we can widen stores to /// the size of the type. bool OverlapFlag : 1; + /// If is set to true, sanitizer checks are already generated for this address + /// or not required. For instance, if this address represents an object + /// created in 'new' expression, sanitizer checks for memory is made as a part + /// of 'operator new' emission and object constructor should not generate + /// them. + bool SanitizerCheckedFlag : 1; + public: enum IsAliased_t { IsNotAliased, IsAliased }; enum IsDestructed_t { IsNotDestructed, IsDestructed }; enum IsZeroed_t { IsNotZeroed, IsZeroed }; enum Overlap_t { DoesNotOverlap, MayOverlap }; enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers }; + enum IsSanitizerChecked_t { IsNotSanitizerChecked, IsSanitizerChecked }; /// ignored - Returns an aggregate value slot indicating that the /// aggregate value is being ignored. @@ -509,7 +517,8 @@ public: NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, - IsZeroed_t isZeroed = IsNotZeroed) { + IsZeroed_t isZeroed = IsNotZeroed, + IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) { AggValueSlot AV; if (addr.isValid()) { AV.Addr = addr.getPointer(); @@ -524,6 +533,7 @@ public: AV.ZeroedFlag = isZeroed; AV.AliasedFlag = isAliased; AV.OverlapFlag = mayOverlap; + AV.SanitizerCheckedFlag = isChecked; return AV; } @@ -532,9 +542,10 @@ public: NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, - IsZeroed_t isZeroed = IsNotZeroed) { + IsZeroed_t isZeroed = IsNotZeroed, + IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) { return forAddr(LV.getAddress(), LV.getQuals(), isDestructed, needsGC, - isAliased, mayOverlap, isZeroed); + isAliased, mayOverlap, isZeroed, isChecked); } IsDestructed_t isExternallyDestructed() const { @@ -553,7 +564,7 @@ public: void setVolatile(bool flag) { Quals.setVolatile(flag); } - + Qualifiers::ObjCLifetime getObjCLifetime() const { return Quals.getObjCLifetime(); } @@ -586,6 +597,10 @@ public: return Overlap_t(OverlapFlag); } + bool isSanitizerChecked() const { + return SanitizerCheckedFlag; + } + RValue asRValue() const { if (isIgnored()) { return RValue::getIgnored(); diff --git a/lib/CodeGen/CodeGenAction.cpp b/lib/CodeGen/CodeGenAction.cpp index 7ca55070d4a0f..d499364002f08 100644 --- a/lib/CodeGen/CodeGenAction.cpp +++ b/lib/CodeGen/CodeGenAction.cpp @@ -51,7 +51,7 @@ namespace clang { public: ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon) : CodeGenOpts(CGOpts), BackendCon(BCon) {} - + bool handleDiagnostics(const DiagnosticInfo &DI) override; bool isAnalysisRemarkEnabled(StringRef PassName) const override { diff --git a/lib/CodeGen/CodeGenFunction.h b/lib/CodeGen/CodeGenFunction.h index 79870ed59c966..f9e2842329720 100644 --- a/lib/CodeGen/CodeGenFunction.h +++ b/lib/CodeGen/CodeGenFunction.h @@ -116,6 +116,7 @@ enum TypeEvaluationKind { SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \ SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \ SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \ + SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \ SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \ SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \ SANITIZER_CHECK(MissingReturn, missing_return, 0) \ @@ -2490,13 +2491,15 @@ public: void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, Address This, const CXXConstructExpr *E, - AggValueSlot::Overlap_t Overlap); + AggValueSlot::Overlap_t Overlap, + bool NewPointerIsChecked); void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, Address This, CallArgList &Args, AggValueSlot::Overlap_t Overlap, - SourceLocation Loc); + SourceLocation Loc, + bool NewPointerIsChecked); /// Emit assumption load for all bases. Requires to be be called only on /// most-derived class and not under construction of the object. @@ -2513,12 +2516,14 @@ public: const ArrayType *ArrayTy, Address ArrayPtr, const CXXConstructExpr *E, + bool NewPointerIsChecked, bool ZeroInitialization = false); void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, llvm::Value *NumElements, Address ArrayPtr, const CXXConstructExpr *E, + bool NewPointerIsChecked, bool ZeroInitialization = false); static Destroyer destroyCXXObject; diff --git a/lib/CodeGen/CodeGenModule.cpp b/lib/CodeGen/CodeGenModule.cpp index ecdf78d4b3472..8c5e0df0969b8 100644 --- a/lib/CodeGen/CodeGenModule.cpp +++ b/lib/CodeGen/CodeGenModule.cpp @@ -1431,7 +1431,7 @@ void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs); } } - + if (const auto *CSA = D->getAttr<CodeSegAttr>()) GO->setSection(CSA->getName()); else if (const auto *SA = D->getAttr<SectionAttr>()) @@ -3176,6 +3176,10 @@ LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { return LangAS::cuda_constant; else if (D && D->hasAttr<CUDASharedAttr>()) return LangAS::cuda_shared; + else if (D && D->hasAttr<CUDADeviceAttr>()) + return LangAS::cuda_device; + else if (D && D->getType().isConstQualified()) + return LangAS::cuda_constant; else return LangAS::cuda_device; } diff --git a/lib/CodeGen/CodeGenModule.h b/lib/CodeGen/CodeGenModule.h index ee64ed4f2ae20..91f3d94330f18 100644 --- a/lib/CodeGen/CodeGenModule.h +++ b/lib/CodeGen/CodeGenModule.h @@ -280,14 +280,14 @@ private: llvm::LLVMContext &VMContext; std::unique_ptr<CodeGenTBAA> TBAA; - + mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo; - + // This should not be moved earlier, since its initialization depends on some // of the previous reference members being already initialized and also checks // if TheTargetCodeGenInfo is NULL CodeGenTypes Types; - + /// Holds information about C++ vtables. CodeGenVTables VTables; @@ -415,7 +415,7 @@ private: /// order. Once the decl is emitted, the index is replaced with ~0U to ensure /// that we don't re-emit the initializer. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; - + typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData; struct GlobalInitPriorityCmp { @@ -452,7 +452,7 @@ private: /// The type used to describe the state of a fast enumeration in /// Objective-C's for..in loop. QualType ObjCFastEnumerationStateType; - + /// @} /// Lazily create the Objective-C runtime @@ -576,7 +576,7 @@ public: llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) { return StaticLocalDeclMap[D]; } - void setStaticLocalDeclAddress(const VarDecl *D, + void setStaticLocalDeclAddress(const VarDecl *D, llvm::Constant *C) { StaticLocalDeclMap[D] = C; } @@ -588,7 +588,7 @@ public: llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) { return StaticLocalDeclGuardMap[D]; } - void setStaticLocalDeclGuardAddress(const VarDecl *D, + void setStaticLocalDeclGuardAddress(const VarDecl *D, llvm::GlobalVariable *C) { StaticLocalDeclGuardMap[D] = C; } @@ -649,10 +649,10 @@ public: bool shouldUseTBAA() const { return TBAA != nullptr; } - const TargetCodeGenInfo &getTargetCodeGenInfo(); - + const TargetCodeGenInfo &getTargetCodeGenInfo(); + CodeGenTypes &getTypes() { return Types; } - + CodeGenVTables &getVTables() { return VTables; } ItaniumVTableContext &getItaniumVTableContext() { @@ -852,7 +852,7 @@ public: /// Fetches the global unique block count. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } - + /// Fetches the type of a generic block descriptor. llvm::Type *getBlockDescriptorType(); @@ -871,7 +871,7 @@ public: /// Notes that BE's global block is available via Addr. Asserts that BE /// isn't already emitted. void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr); - + /// Return a pointer to a constant CFString object for the given string. ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal); @@ -1139,7 +1139,7 @@ public: /// Return the store size, in character units, of the given LLVM type. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; - + /// Returns LLVM linkage for a declarator. llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, @@ -1316,7 +1316,7 @@ private: void emitCPUDispatchDefinition(GlobalDecl GD); void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); void EmitObjCIvarInitializations(ObjCImplementationDecl *D); - + // C++ related functions. void EmitDeclContext(const DeclContext *DC); diff --git a/lib/CodeGen/CodeGenTypes.cpp b/lib/CodeGen/CodeGenTypes.cpp index 16ec1dd301aa9..1a1395e6ae747 100644 --- a/lib/CodeGen/CodeGenTypes.cpp +++ b/lib/CodeGen/CodeGenTypes.cpp @@ -54,7 +54,7 @@ void CodeGenTypes::addRecordTypeName(const RecordDecl *RD, SmallString<256> TypeName; llvm::raw_svector_ostream OS(TypeName); OS << RD->getKindName() << '.'; - + // Name the codegen type after the typedef name // if there is no tag type name available if (RD->getIdentifier()) { @@ -100,7 +100,7 @@ llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) { /// isRecordLayoutComplete - Return true if the specified type is already /// completely laid out. bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const { - llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I = + llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I = RecordDeclTypes.find(Ty); return I != RecordDeclTypes.end() && !I->second->isOpaque(); } @@ -113,7 +113,7 @@ isSafeToConvert(QualType T, CodeGenTypes &CGT, /// isSafeToConvert - Return true if it is safe to convert the specified record /// decl to IR and lay it out, false if doing so would cause us to get into a /// recursive compilation mess. -static bool +static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) { // If we have already checked this type (maybe the same type is used by-value @@ -122,14 +122,14 @@ isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, return true; const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr(); - + // If this type is already laid out, converting it is a noop. if (CGT.isRecordLayoutComplete(Key)) return true; - + // If this type is currently being laid out, we can't recursively compile it. if (CGT.isRecordBeingLaidOut(Key)) return false; - + // If this type would require laying out bases that are currently being laid // out, don't do it. This includes virtual base classes which get laid out // when a class is translated, even though they aren't embedded by-value into @@ -140,13 +140,13 @@ isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, CGT, AlreadyChecked)) return false; } - + // If this type would require laying out members that are currently being laid // out, don't do it. for (const auto *I : RD->fields()) if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked)) return false; - + // If there are no problems, lets do it. return true; } @@ -170,7 +170,7 @@ isSafeToConvert(QualType T, CodeGenTypes &CGT, return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked); // Otherwise, there is no concern about transforming this. We only care about - // things that are contained by-value in a structure that can have another + // things that are contained by-value in a structure that can have another // structure as a member. return true; } @@ -182,7 +182,7 @@ isSafeToConvert(QualType T, CodeGenTypes &CGT, static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) { // If no structs are being laid out, we can certainly do this one. if (CGT.noRecordsBeingLaidOut()) return true; - + llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked; return isSafeToConvert(RD, CGT, AlreadyChecked); } @@ -229,7 +229,7 @@ bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) { bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) { if (!isFuncParamTypeConvertible(FT->getReturnType())) return false; - + if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++) if (!isFuncParamTypeConvertible(FPT->getParamType(i))) @@ -259,7 +259,7 @@ void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { DI->completeType(ED); return; } - + // If we completed a RecordDecl that we previously used and converted to an // anonymous type, then go ahead and complete it now. const RecordDecl *RD = cast<RecordDecl>(TD); @@ -388,7 +388,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { // RecordTypes are cached and processed specially. if (const RecordType *RT = dyn_cast<RecordType>(Ty)) return ConvertRecordDeclType(RT->getDecl()); - + // See if type is already cached. llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty); // If type is found in map then use it. Otherwise, convert type T. @@ -494,7 +494,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { // Model std::nullptr_t as i8* ResultType = llvm::Type::getInt8PtrTy(getLLVMContext()); break; - + case BuiltinType::UInt128: case BuiltinType::Int128: ResultType = llvm::IntegerType::get(getLLVMContext(), 128); @@ -510,7 +510,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { case BuiltinType::OCLReserveID: ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty); break; - + case BuiltinType::Dependent: #define BUILTIN_TYPE(Id, SingletonId) #define PLACEHOLDER_TYPE(Id, SingletonId) \ @@ -574,8 +574,8 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { case Type::ConstantArray: { const ConstantArrayType *A = cast<ConstantArrayType>(Ty); llvm::Type *EltTy = ConvertTypeForMem(A->getElementType()); - - // Lower arrays of undefined struct type to arrays of i8 just to have a + + // Lower arrays of undefined struct type to arrays of i8 just to have a // concrete type. if (!EltTy->isSized()) { SkippedLayout = true; @@ -674,9 +674,9 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { break; } } - + assert(ResultType && "Didn't convert a type?"); - + TypeCache[Ty] = ResultType; return ResultType; } @@ -709,7 +709,7 @@ llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { RD = RD->getDefinition(); if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque()) return Ty; - + // If converting this type would cause us to infinitely loop, don't do it! if (!isSafeToConvert(RD, *this)) { DeferredRecords.push_back(RD); @@ -720,12 +720,12 @@ llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { bool InsertResult = RecordsBeingLaidOut.insert(Key).second; (void)InsertResult; assert(InsertResult && "Recursively compiling a struct?"); - + // Force conversion of non-virtual base classes recursively. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { for (const auto &I : CRD->bases()) { if (I.isVirtual()) continue; - + ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl()); } } @@ -737,13 +737,13 @@ llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { // We're done laying out this struct. bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult; assert(EraseResult && "struct not in RecordsBeingLaidOut set?"); - + // If this struct blocked a FunctionType conversion, then recompute whatever // was derived from that. // FIXME: This is hugely overconservative. if (SkippedLayout) TypeCache.clear(); - + // If we're done converting the outer-most record, then convert any deferred // structs as well. if (RecordsBeingLaidOut.empty()) @@ -799,7 +799,7 @@ bool CodeGenTypes::isZeroInitializable(QualType T) { // We have to ask the ABI about member pointers. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) return getCXXABI().isZeroInitializable(MPT); - + // Everything else is okay. return true; } diff --git a/lib/CodeGen/CodeGenTypes.h b/lib/CodeGen/CodeGenTypes.h index fb8d316842909..626869f000219 100644 --- a/lib/CodeGen/CodeGenTypes.h +++ b/lib/CodeGen/CodeGenTypes.h @@ -140,7 +140,7 @@ class CodeGenTypes { /// Contains the LLVM IR type for any converted RecordDecl. llvm::DenseMap<const Type*, llvm::StructType *> RecordDeclTypes; - + /// Hold memoized CGFunctionInfo results. llvm::FoldingSet<CGFunctionInfo> FunctionInfos; @@ -149,15 +149,15 @@ class CodeGenTypes { /// struct A { struct B { int x; } } when processing 'x', the 'A' and 'B' /// types will be in this set. llvm::SmallPtrSet<const Type*, 4> RecordsBeingLaidOut; - + llvm::SmallPtrSet<const CGFunctionInfo*, 4> FunctionsBeingProcessed; - + /// True if we didn't layout a function due to a being inside /// a recursive struct conversion, set this to true. bool SkippedLayout; SmallVector<const RecordDecl *, 8> DeferredRecords; - + /// This map keeps cache of llvm::Types and maps clang::Type to /// corresponding llvm::Type. llvm::DenseMap<const Type *, llvm::Type *> TypeCache; @@ -343,7 +343,7 @@ public: /// optional suffix and name the given LLVM type using it. void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty, StringRef suffix); - + public: // These are internal details of CGT that shouldn't be used externally. /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union. @@ -365,7 +365,7 @@ public: // These are internal details of CGT that shouldn't be used externally. /// IsZeroInitializable - Return whether a record type can be /// zero-initialized (in the C++ sense) with an LLVM zeroinitializer. bool isZeroInitializable(const RecordDecl *RD); - + bool isRecordLayoutComplete(const Type *Ty) const; bool noRecordsBeingLaidOut() const { return RecordsBeingLaidOut.empty(); @@ -373,7 +373,7 @@ public: // These are internal details of CGT that shouldn't be used externally. bool isRecordBeingLaidOut(const Type *Ty) const { return RecordsBeingLaidOut.count(Ty); } - + }; } // end namespace CodeGen diff --git a/lib/CodeGen/ConstantInitBuilder.cpp b/lib/CodeGen/ConstantInitBuilder.cpp index 7f8d809850329..59e66b88fb014 100644 --- a/lib/CodeGen/ConstantInitBuilder.cpp +++ b/lib/CodeGen/ConstantInitBuilder.cpp @@ -166,7 +166,7 @@ void ConstantAggregateBuilderBase::getGEPIndicesTo( if (Parent) { Parent->getGEPIndicesTo(indices, Begin); - // Otherwise, add an index to drill into the first level of pointer. + // Otherwise, add an index to drill into the first level of pointer. } else { assert(indices.empty()); indices.push_back(llvm::ConstantInt::get(Builder.CGM.Int32Ty, 0)); diff --git a/lib/CodeGen/ItaniumCXXABI.cpp b/lib/CodeGen/ItaniumCXXABI.cpp index 16fdd1c16a1d5..00fff144b597b 100644 --- a/lib/CodeGen/ItaniumCXXABI.cpp +++ b/lib/CodeGen/ItaniumCXXABI.cpp @@ -3744,22 +3744,12 @@ static StructorCodegen getCodegenToUse(CodeGenModule &CGM, } llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); - // All discardable structors can be RAUWed, but we don't want to do that in - // unoptimized code, as that makes complete structor symbol disappear - // completely, which degrades debugging experience. - // Symbols with private linkage can be safely aliased, so we special case them - // here. - if (llvm::GlobalValue::isLocalLinkage(Linkage)) - return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW - : StructorCodegen::Alias; + if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) + return StructorCodegen::RAUW; - // Linkonce structors cannot be aliased nor placed in a comdat, so these need - // to be emitted separately. // FIXME: Should we allow available_externally aliases? - if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) || - !llvm::GlobalAlias::isValidLinkage(Linkage)) - return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW - : StructorCodegen::Emit; + if (!llvm::GlobalAlias::isValidLinkage(Linkage)) + return StructorCodegen::RAUW; if (llvm::GlobalValue::isWeakForLinker(Linkage)) { // Only ELF and wasm support COMDATs with arbitrary names (C5/D5). diff --git a/lib/CodeGen/MicrosoftCXXABI.cpp b/lib/CodeGen/MicrosoftCXXABI.cpp index 81ed05059546e..059adb78ca302 100644 --- a/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/lib/CodeGen/MicrosoftCXXABI.cpp @@ -165,7 +165,7 @@ public: llvm::BasicBlock * EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, const CXXRecordDecl *RD) override; - + llvm::BasicBlock * EmitDtorCompleteObjectHandler(CodeGenFunction &CGF); @@ -1123,7 +1123,7 @@ MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) { CGF.EmitBlock(CallVbaseDtorsBB); // CGF will put the base dtor calls in this basic block for us later. - + return SkipVbaseDtorsBB; } @@ -1393,7 +1393,7 @@ Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( Address Result = This; if (ML.VBase) { Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty); - + const CXXRecordDecl *Derived = MD->getParent(); const CXXRecordDecl *VBase = ML.VBase; llvm::Value *VBaseOffset = @@ -1562,21 +1562,21 @@ void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), This, false); } - + llvm::BasicBlock *BaseDtorEndBB = nullptr; if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) { BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF); - } + } CGF.EmitCXXDestructorCall(DD, Callee, This.getPointer(), /*ImplicitParam=*/nullptr, /*ImplicitParamTy=*/QualType(), nullptr, getFromDtorType(Type)); if (BaseDtorEndBB) { - // Complete object handler should continue to be the remaining + // Complete object handler should continue to be the remaining CGF.Builder.CreateBr(BaseDtorEndBB); CGF.EmitBlock(BaseDtorEndBB); - } + } } void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info, diff --git a/lib/CodeGen/SwiftCallingConv.cpp b/lib/CodeGen/SwiftCallingConv.cpp index 3673a5597eacc..b411a501ea81d 100644 --- a/lib/CodeGen/SwiftCallingConv.cpp +++ b/lib/CodeGen/SwiftCallingConv.cpp @@ -163,7 +163,7 @@ void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin, // - virtual bases for (auto &vbaseSpecifier : cxxRecord->vbases()) { auto baseRecord = vbaseSpecifier.getType()->getAsCXXRecordDecl(); - addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord)); + addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord)); } } } @@ -583,7 +583,7 @@ bool SwiftAggLowering::shouldPassIndirectly(bool asReturnValue) const { if (Entries.size() == 1) { return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift( Entries.back().Type, - asReturnValue); + asReturnValue); } SmallVector<llvm::Type*, 8> componentTys; diff --git a/lib/CodeGen/TargetInfo.cpp b/lib/CodeGen/TargetInfo.cpp index fa9b0a27af287..6f6c5f50c2e76 100644 --- a/lib/CodeGen/TargetInfo.cpp +++ b/lib/CodeGen/TargetInfo.cpp @@ -305,7 +305,7 @@ static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), DirectAlign); } else { - Addr = Address(Ptr, SlotSize); + Addr = Address(Ptr, SlotSize); } // Advance the pointer past the argument, then store that back. @@ -369,7 +369,7 @@ static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, } return Addr; - + } static Address emitMergePHI(CodeGenFunction &CGF, @@ -1014,7 +1014,7 @@ class X86_32ABIInfo : public SwiftABIInfo { ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; - /// Updates the number of available free registers, returns + /// Updates the number of available free registers, returns /// true if any registers were allocated. bool updateFreeRegs(QualType Ty, CCState &State) const; @@ -1044,7 +1044,7 @@ public: bool RetSmallStructInRegABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI) : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), - IsRetSmallStructInRegABI(RetSmallStructInRegABI), + IsRetSmallStructInRegABI(RetSmallStructInRegABI), IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), @@ -1057,7 +1057,7 @@ public: // four vector registers for vectors, but those can overlap with the // scalar registers. return occupiesMoreThan(CGT, scalars, /*total*/ 3); - } + } bool isSwiftErrorInRegister() const override { // x86-32 lowering does not support passing swifterror in a register. @@ -1546,7 +1546,7 @@ bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { return true; } -bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, +bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, bool &NeedsPadding) const { // On Windows, aggregates other than HFAs are never passed in registers, and @@ -1589,7 +1589,7 @@ bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { if (getContext().getTypeSize(Ty) > 32) return false; - return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || + return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || Ty->isReferenceType()); } @@ -2185,7 +2185,7 @@ public: bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); - } + } bool isSwiftErrorInRegister() const override { return true; } @@ -3785,7 +3785,7 @@ Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); RegAddr = Tmp; } - + } else if (neededSSE == 1) { RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), CharUnits::fromQuantity(16)); @@ -4180,7 +4180,7 @@ Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, } // Get the address of the saved value by scaling the number of - // registers we've used by the number of + // registers we've used by the number of CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); llvm::Value *RegOffset = Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); @@ -4191,7 +4191,7 @@ Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, // Increase the used-register count. NumRegs = - Builder.CreateAdd(NumRegs, + Builder.CreateAdd(NumRegs, Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); Builder.CreateStore(NumRegs, NumRegsAddr); @@ -4227,7 +4227,7 @@ Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), Align); } - + MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); // Increase the overflow area. @@ -5063,7 +5063,13 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { if (getTarget().isRenderScriptTarget()) { return coerceToIntArray(Ty, getContext(), getVMContext()); } - unsigned Alignment = getContext().getTypeAlign(Ty); + unsigned Alignment; + if (Kind == AArch64ABIInfo::AAPCS) { + Alignment = getContext().getTypeUnadjustedAlign(Ty); + Alignment = Alignment < 128 ? 64 : 128; + } else { + Alignment = getContext().getTypeAlign(Ty); + } Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. @@ -5801,11 +5807,14 @@ ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, // most 8-byte. We realign the indirect argument if type alignment is bigger // than ABI alignment. uint64_t ABIAlign = 4; - uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; + uint64_t TyAlign; if (getABIKind() == ARMABIInfo::AAPCS_VFP || - getABIKind() == ARMABIInfo::AAPCS) + getABIKind() == ARMABIInfo::AAPCS) { + TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); - + } else { + TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); + } if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), @@ -5824,7 +5833,7 @@ ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, unsigned SizeRegs; // FIXME: Try to match the types of the arguments more accurately where // we can. - if (getContext().getTypeAlign(Ty) <= 32) { + if (TyAlign <= 4) { ElemTy = llvm::Type::getInt32Ty(getVMContext()); SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; } else { @@ -6985,8 +6994,14 @@ ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) RetTy = EnumTy->getDecl()->getIntegerType(); - return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) - : ABIArgInfo::getDirect()); + if (RetTy->isPromotableIntegerType()) + return ABIArgInfo::getExtend(RetTy); + + if ((RetTy->isUnsignedIntegerOrEnumerationType() || + RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) + return ABIArgInfo::getSignExtend(RetTy); + + return ABIArgInfo::getDirect(); } void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { diff --git a/lib/Driver/CMakeLists.txt b/lib/Driver/CMakeLists.txt index 471ffe0f1b00e..2b03c9f7001f7 100644 --- a/lib/Driver/CMakeLists.txt +++ b/lib/Driver/CMakeLists.txt @@ -57,6 +57,7 @@ add_clang_library(clangDriver ToolChains/NetBSD.cpp ToolChains/OpenBSD.cpp ToolChains/PS4CPU.cpp + ToolChains/RISCV.cpp ToolChains/Solaris.cpp ToolChains/TCE.cpp ToolChains/WebAssembly.cpp diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index 1dfcacc75ea5b..952a716cb6e61 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -37,6 +37,7 @@ #include "ToolChains/NetBSD.h" #include "ToolChains/OpenBSD.h" #include "ToolChains/PS4CPU.h" +#include "ToolChains/RISCV.h" #include "ToolChains/Solaris.h" #include "ToolChains/TCE.h" #include "ToolChains/WebAssembly.h" @@ -4399,6 +4400,10 @@ const ToolChain &Driver::getToolChain(const ArgList &Args, case llvm::Triple::avr: TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args); break; + case llvm::Triple::riscv32: + case llvm::Triple::riscv64: + TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); + break; default: if (Target.getVendor() == llvm::Triple::Myriad) TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target, diff --git a/lib/Driver/SanitizerArgs.cpp b/lib/Driver/SanitizerArgs.cpp index bdc17d11c92be..5d3e31567ce61 100644 --- a/lib/Driver/SanitizerArgs.cpp +++ b/lib/Driver/SanitizerArgs.cpp @@ -27,22 +27,22 @@ using namespace clang::driver; using namespace llvm::opt; enum : SanitizerMask { - NeedsUbsanRt = Undefined | Integer | Nullability | CFI, + NeedsUbsanRt = Undefined | Integer | ImplicitConversion | Nullability | CFI, NeedsUbsanCxxRt = Vptr | CFI, NotAllowedWithTrap = Vptr, NotAllowedWithMinimalRuntime = Vptr, RequiresPIE = DataFlow | HWAddress | Scudo, NeedsUnwindTables = Address | HWAddress | Thread | Memory | DataFlow, SupportsCoverage = Address | HWAddress | KernelAddress | KernelHWAddress | - Memory | Leak | Undefined | Integer | Nullability | - DataFlow | Fuzzer | FuzzerNoLink, - RecoverableByDefault = Undefined | Integer | Nullability, + Memory | Leak | Undefined | Integer | ImplicitConversion | + Nullability | DataFlow | Fuzzer | FuzzerNoLink, + RecoverableByDefault = Undefined | Integer | ImplicitConversion | Nullability, Unrecoverable = Unreachable | Return, AlwaysRecoverable = KernelAddress | KernelHWAddress, LegacyFsanitizeRecoverMask = Undefined | Integer, NeedsLTO = CFI, TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow | - Nullability | LocalBounds | CFI, + ImplicitConversion | Nullability | LocalBounds | CFI, TrappingDefault = CFI, CFIClasses = CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast, @@ -321,7 +321,7 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, D.Diag(diag::err_drv_argument_not_allowed_with) << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args); } else { - // The vptr sanitizer requires RTTI, but RTTI is disabled (by + // The vptr sanitizer requires RTTI, but RTTI is disabled (by // default). Warn that the vptr sanitizer is being disabled. D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default); } diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp index d62ba1253348f..cf3db34688df8 100644 --- a/lib/Driver/ToolChain.cpp +++ b/lib/Driver/ToolChain.cpp @@ -564,7 +564,7 @@ std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, StringRef Suffix = tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple); bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M; - bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && + bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && getTriple().isOSBinFormatMachO()); // FIXME: this is invalid for WindowsCE if (getTriple().isOSWindows()) @@ -803,8 +803,8 @@ SanitizerMask ToolChain::getSupportedSanitizers() const { using namespace SanitizerKind; SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) | - CFICastStrict | UnsignedIntegerOverflow | Nullability | - LocalBounds; + CFICastStrict | UnsignedIntegerOverflow | + ImplicitConversion | Nullability | LocalBounds; if (getTriple().getArch() == llvm::Triple::x86 || getTriple().getArch() == llvm::Triple::x86_64 || getTriple().getArch() == llvm::Triple::arm || diff --git a/lib/Driver/ToolChains/Arch/RISCV.cpp b/lib/Driver/ToolChains/Arch/RISCV.cpp index 11ce8a1fd7694..1321fedcec512 100644 --- a/lib/Driver/ToolChains/Arch/RISCV.cpp +++ b/lib/Driver/ToolChains/Arch/RISCV.cpp @@ -279,7 +279,7 @@ void riscv::getRISCVTargetFeatures(const Driver &D, const ArgList &Args, if (!getExtensionVersion(D, MArch, std::string(1, Baseline), Exts, Major, Minor)) return; - + // TODO: Use version number when setting target features // and consume the underscore '_' that might follow. diff --git a/lib/Driver/ToolChains/Clang.cpp b/lib/Driver/ToolChains/Clang.cpp index eaff940a1c2bf..8e9c4c6aecb87 100644 --- a/lib/Driver/ToolChains/Clang.cpp +++ b/lib/Driver/ToolChains/Clang.cpp @@ -919,34 +919,46 @@ static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, } } +static bool checkDebugInfoOption(const Arg *A, const ArgList &Args, + const Driver &D, const ToolChain &TC) { + assert(A && "Expected non-nullptr argument."); + if (TC.supportsDebugInfoOption(A)) + return true; + D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target) + << A->getAsString(Args) << TC.getTripleString(); + return false; +} + static void RenderDebugInfoCompressionArgs(const ArgList &Args, ArgStringList &CmdArgs, - const Driver &D) { + const Driver &D, + const ToolChain &TC) { const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ); if (!A) return; + if (checkDebugInfoOption(A, Args, D, TC)) { + if (A->getOption().getID() == options::OPT_gz) { + if (llvm::zlib::isAvailable()) + CmdArgs.push_back("-compress-debug-sections"); + else + D.Diag(diag::warn_debug_compression_unavailable); + return; + } - if (A->getOption().getID() == options::OPT_gz) { - if (llvm::zlib::isAvailable()) - CmdArgs.push_back("-compress-debug-sections"); - else - D.Diag(diag::warn_debug_compression_unavailable); - return; - } - - StringRef Value = A->getValue(); - if (Value == "none") { - CmdArgs.push_back("-compress-debug-sections=none"); - } else if (Value == "zlib" || Value == "zlib-gnu") { - if (llvm::zlib::isAvailable()) { - CmdArgs.push_back( - Args.MakeArgString("-compress-debug-sections=" + Twine(Value))); + StringRef Value = A->getValue(); + if (Value == "none") { + CmdArgs.push_back("-compress-debug-sections=none"); + } else if (Value == "zlib" || Value == "zlib-gnu") { + if (llvm::zlib::isAvailable()) { + CmdArgs.push_back( + Args.MakeArgString("-compress-debug-sections=" + Twine(Value))); + } else { + D.Diag(diag::warn_debug_compression_unavailable); + } } else { - D.Diag(diag::warn_debug_compression_unavailable); + D.Diag(diag::err_drv_unsupported_option_argument) + << A->getOption().getName() << Value; } - } else { - D.Diag(diag::err_drv_unsupported_option_argument) - << A->getOption().getName() << Value; } } @@ -2867,7 +2879,9 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, codegenoptions::DebugInfoKind &DebugInfoKind, const Arg *&SplitDWARFArg) { if (Args.hasFlag(options::OPT_fdebug_info_for_profiling, - options::OPT_fno_debug_info_for_profiling, false)) + options::OPT_fno_debug_info_for_profiling, false) && + checkDebugInfoOption( + Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC)) CmdArgs.push_back("-fdebug-info-for-profiling"); // The 'g' groups options involve a somewhat intricate sequence of decisions @@ -2890,29 +2904,38 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf); + if (SplitDWARFArg && !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) { + SplitDWARFArg = nullptr; + SplitDWARFInlining = false; + } + if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) { - // If the last option explicitly specified a debug-info level, use it. - if (A->getOption().matches(options::OPT_gN_Group)) { - DebugInfoKind = DebugLevelToInfoKind(*A); - // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses. - // But -gsplit-dwarf is not a g_group option, hence we have to check the - // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later. - // This gets a bit more complicated if you've disabled inline info in the - // skeleton CUs (SplitDWARFInlining) - then there's value in composing - // split-dwarf and line-tables-only, so let those compose naturally in - // that case. - // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that. - if (SplitDWARFArg) { - if (A->getIndex() > SplitDWARFArg->getIndex()) { - if (DebugInfoKind == codegenoptions::NoDebugInfo || - (DebugInfoKind == codegenoptions::DebugLineTablesOnly && - SplitDWARFInlining)) - SplitDWARFArg = nullptr; - } else if (SplitDWARFInlining) - DebugInfoKind = codegenoptions::NoDebugInfo; + if (checkDebugInfoOption(A, Args, D, TC)) { + // If the last option explicitly specified a debug-info level, use it. + if (A->getOption().matches(options::OPT_gN_Group)) { + DebugInfoKind = DebugLevelToInfoKind(*A); + // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses. + // But -gsplit-dwarf is not a g_group option, hence we have to check the + // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later. + // This gets a bit more complicated if you've disabled inline info in + // the skeleton CUs (SplitDWARFInlining) - then there's value in + // composing split-dwarf and line-tables-only, so let those compose + // naturally in that case. And if you just turned off debug info, + // (-gsplit-dwarf -g0) - do that. + if (SplitDWARFArg) { + if (A->getIndex() > SplitDWARFArg->getIndex()) { + if (DebugInfoKind == codegenoptions::NoDebugInfo || + (DebugInfoKind == codegenoptions::DebugLineTablesOnly && + SplitDWARFInlining)) + SplitDWARFArg = nullptr; + } else if (SplitDWARFInlining) + DebugInfoKind = codegenoptions::NoDebugInfo; + } + } else { + // For any other 'g' option, use Limited. + DebugInfoKind = codegenoptions::LimitedDebugInfo; } } else { - // For any other 'g' option, use Limited. DebugInfoKind = codegenoptions::LimitedDebugInfo; } } @@ -2920,39 +2943,50 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, // If a debugger tuning argument appeared, remember it. if (const Arg *A = Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { - if (A->getOption().matches(options::OPT_glldb)) - DebuggerTuning = llvm::DebuggerKind::LLDB; - else if (A->getOption().matches(options::OPT_gsce)) - DebuggerTuning = llvm::DebuggerKind::SCE; - else - DebuggerTuning = llvm::DebuggerKind::GDB; + if (checkDebugInfoOption(A, Args, D, TC)) { + if (A->getOption().matches(options::OPT_glldb)) + DebuggerTuning = llvm::DebuggerKind::LLDB; + else if (A->getOption().matches(options::OPT_gsce)) + DebuggerTuning = llvm::DebuggerKind::SCE; + else + DebuggerTuning = llvm::DebuggerKind::GDB; + } } // If a -gdwarf argument appeared, remember it. if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3, options::OPT_gdwarf_4, options::OPT_gdwarf_5)) - DWARFVersion = DwarfVersionNum(A->getSpelling()); + if (checkDebugInfoOption(A, Args, D, TC)) + DWARFVersion = DwarfVersionNum(A->getSpelling()); // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility // argument parsing. if (EmitCodeView) { - // DWARFVersion remains at 0 if no explicit choice was made. - CmdArgs.push_back("-gcodeview"); - } else if (DWARFVersion == 0 && - DebugInfoKind != codegenoptions::NoDebugInfo) { - DWARFVersion = TC.GetDefaultDwarfVersion(); + if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) { + EmitCodeView = checkDebugInfoOption(A, Args, D, TC); + if (EmitCodeView) { + // DWARFVersion remains at 0 if no explicit choice was made. + CmdArgs.push_back("-gcodeview"); + } + } } + if (!EmitCodeView && DWARFVersion == 0 && + DebugInfoKind != codegenoptions::NoDebugInfo) + DWARFVersion = TC.GetDefaultDwarfVersion(); + // We ignore flag -gstrict-dwarf for now. // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags. Args.ClaimAllArgs(options::OPT_g_flags_Group); - // Column info is included by default for everything except SCE and CodeView. - // Clang doesn't track end columns, just starting columns, which, in theory, - // is fine for CodeView (and PDB). In practice, however, the Microsoft - // debuggers don't handle missing end columns well, so it's better not to - // include any column info. + // Column info is included by default for everything except SCE and + // CodeView. Clang doesn't track end columns, just starting columns, which, + // in theory, is fine for CodeView (and PDB). In practice, however, the + // Microsoft debuggers don't handle missing end columns well, so it's better + // not to include any column info. + if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info)) + (void)checkDebugInfoOption(A, Args, D, TC); if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info, /*Default=*/!EmitCodeView && DebuggerTuning != llvm::DebuggerKind::SCE)) @@ -2960,12 +2994,14 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, // FIXME: Move backend command line options to the module. // If -gline-tables-only is the last option it wins. - if (DebugInfoKind != codegenoptions::DebugLineTablesOnly && - Args.hasArg(options::OPT_gmodules)) { - DebugInfoKind = codegenoptions::LimitedDebugInfo; - CmdArgs.push_back("-dwarf-ext-refs"); - CmdArgs.push_back("-fmodule-format=obj"); - } + if (const Arg *A = Args.getLastArg(options::OPT_gmodules)) + if (checkDebugInfoOption(A, Args, D, TC)) { + if (DebugInfoKind != codegenoptions::DebugLineTablesOnly) { + DebugInfoKind = codegenoptions::LimitedDebugInfo; + CmdArgs.push_back("-dwarf-ext-refs"); + CmdArgs.push_back("-fmodule-format=obj"); + } + } // -gsplit-dwarf should turn on -g and enable the backend dwarf // splitting and extraction. @@ -2989,19 +3025,23 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug, TC.GetDefaultStandaloneDebug()); + if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug)) + (void)checkDebugInfoOption(A, Args, D, TC); if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug) DebugInfoKind = codegenoptions::FullDebugInfo; - if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) { + if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, + false)) { // Source embedding is a vendor extension to DWARF v5. By now we have // checked if a DWARF version was stated explicitly, and have otherwise - // fallen back to the target default, so if this is still not at least 5 we - // emit an error. + // fallen back to the target default, so if this is still not at least 5 + // we emit an error. + const Arg *A = Args.getLastArg(options::OPT_gembed_source); if (DWARFVersion < 5) D.Diag(diag::err_drv_argument_only_allowed_with) - << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args) - << "-gdwarf-5"; - CmdArgs.push_back("-gembed-source"); + << A->getAsString(Args) << "-gdwarf-5"; + else if (checkDebugInfoOption(A, Args, D, TC)) + CmdArgs.push_back("-gembed-source"); } RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion, @@ -3010,31 +3050,41 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, // -fdebug-macro turns on macro debug info generation. if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro, false)) - CmdArgs.push_back("-debug-info-macro"); + if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args, + D, TC)) + CmdArgs.push_back("-debug-info-macro"); // -ggnu-pubnames turns on gnu style pubnames in the backend. if (Args.hasFlag(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames, false)) - CmdArgs.push_back("-ggnu-pubnames"); + if (checkDebugInfoOption(Args.getLastArg(options::OPT_ggnu_pubnames), Args, + D, TC)) + CmdArgs.push_back("-ggnu-pubnames"); // -gdwarf-aranges turns on the emission of the aranges section in the // backend. // Always enabled for SCE tuning. - if (Args.hasArg(options::OPT_gdwarf_aranges) || - DebuggerTuning == llvm::DebuggerKind::SCE) { + bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE; + if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges)) + NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges; + if (NeedAranges) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-generate-arange-section"); } if (Args.hasFlag(options::OPT_fdebug_types_section, options::OPT_fno_debug_types_section, false)) { - if (!T.isOSBinFormatELF()) + if (!T.isOSBinFormatELF()) { D.Diag(diag::err_drv_unsupported_opt_for_target) << Args.getLastArg(options::OPT_fdebug_types_section) ->getAsString(Args) << T.getTriple(); - CmdArgs.push_back("-mllvm"); - CmdArgs.push_back("-generate-type-units"); + } else if (checkDebugInfoOption( + Args.getLastArg(options::OPT_fdebug_types_section), Args, D, + TC)) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-generate-type-units"); + } } // Decide how to render forward declarations of template instantiations. @@ -3042,11 +3092,12 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, if (DebuggerTuning == llvm::DebuggerKind::SCE) CmdArgs.push_back("-debug-forward-template-params"); - // Do we need to explicitly import anonymous namespaces into the parent scope? + // Do we need to explicitly import anonymous namespaces into the parent + // scope? if (DebuggerTuning == llvm::DebuggerKind::SCE) CmdArgs.push_back("-dwarf-explicit-import"); - RenderDebugInfoCompressionArgs(Args, CmdArgs, D); + RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC); } void Clang::ConstructJob(Compilation &C, const JobAction &JA, @@ -5388,7 +5439,7 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, } RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion, llvm::DebuggerKind::Default); - RenderDebugInfoCompressionArgs(Args, CmdArgs, D); + RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain()); // Handle -fPIC et al -- the relocation-model affects the assembler diff --git a/lib/Driver/ToolChains/Cuda.cpp b/lib/Driver/ToolChains/Cuda.cpp index d17c4c39532ad..7fb4ae4ea9cf6 100644 --- a/lib/Driver/ToolChains/Cuda.cpp +++ b/lib/Driver/ToolChains/Cuda.cpp @@ -679,6 +679,18 @@ void CudaToolChain::addClangTargetOptions( } } +bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const { + const Option &O = A->getOption(); + return (O.matches(options::OPT_gN_Group) && + !O.matches(options::OPT_gmodules)) || + O.matches(options::OPT_g_Flag) || + O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) || + O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) || + O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) || + O.matches(options::OPT_gdwarf_5) || + O.matches(options::OPT_gcolumn_info); +} + void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // Check our CUDA version if we're going to include the CUDA headers. diff --git a/lib/Driver/ToolChains/Cuda.h b/lib/Driver/ToolChains/Cuda.h index 99d5a4a628cef..01580cb66920a 100644 --- a/lib/Driver/ToolChains/Cuda.h +++ b/lib/Driver/ToolChains/Cuda.h @@ -158,6 +158,7 @@ public: bool isPIEDefault() const override { return false; } bool isPICDefaultForced() const override { return false; } bool SupportsProfiling() const override { return false; } + bool supportsDebugInfoOption(const llvm::opt::Arg *A) const override; bool IsMathErrnoDefault() const override { return false; } void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, diff --git a/lib/Driver/ToolChains/Darwin.cpp b/lib/Driver/ToolChains/Darwin.cpp index 95ec8d64c2c73..9205dd52de0bb 100644 --- a/lib/Driver/ToolChains/Darwin.cpp +++ b/lib/Driver/ToolChains/Darwin.cpp @@ -916,26 +916,13 @@ unsigned DarwinClang::GetDefaultDwarfVersion() const { return 4; } -SmallString<128> MachO::runtimeLibDir(bool IsEmbedded) const { - SmallString<128> Dir(getDriver().ResourceDir); - llvm::sys::path::append( - Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin"); - return Dir; -} - -std::string Darwin::getFileNameForSanitizerLib(StringRef SanitizerName, - bool Shared) const { - return (Twine("libclang_rt.") + SanitizerName + "_" + - getOSLibraryNameSuffix() + - (Shared ? "_dynamic.dylib" : ".a")).str(); - -} - void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs, StringRef DarwinLibName, RuntimeLinkOptions Opts) const { + SmallString<128> Dir(getDriver().ResourceDir); + llvm::sys::path::append( + Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin"); - SmallString<128> Dir = runtimeLibDir(Opts & RLO_IsEmbedded); SmallString<128> P(Dir); llvm::sys::path::append(P, DarwinLibName); @@ -1055,9 +1042,12 @@ void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args, StringRef Sanitizer, bool Shared) const { auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U)); - std::string SanitizerRelFilename = - getFileNameForSanitizerLib(Sanitizer, Shared); - AddLinkRuntimeLib(Args, CmdArgs, SanitizerRelFilename, RLO); + AddLinkRuntimeLib(Args, CmdArgs, + (Twine("libclang_rt.") + Sanitizer + "_" + + getOSLibraryNameSuffix() + + (Shared ? "_dynamic.dylib" : ".a")) + .str(), + RLO); } ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType( @@ -2295,43 +2285,24 @@ void Darwin::CheckObjCARC() const { SanitizerMask Darwin::getSupportedSanitizers() const { const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; SanitizerMask Res = ToolChain::getSupportedSanitizers(); - - { - using namespace SanitizerKind; - assert(!(Res & (Address | Leak | Fuzzer | FuzzerNoLink | Thread)) && - "Sanitizer is already registered as supported"); - } - - if (sanitizerRuntimeExists("asan")) - Res |= SanitizerKind::Address; - if (sanitizerRuntimeExists("lsan")) - Res |= SanitizerKind::Leak; - if (sanitizerRuntimeExists("fuzzer", /*Shared=*/false)) { - Res |= SanitizerKind::Fuzzer; - Res |= SanitizerKind::FuzzerNoLink; - } + Res |= SanitizerKind::Address; + Res |= SanitizerKind::Leak; + Res |= SanitizerKind::Fuzzer; + Res |= SanitizerKind::FuzzerNoLink; Res |= SanitizerKind::Function; - if (isTargetMacOS() && !isMacosxVersionLT(10, 9)) - Res |= SanitizerKind::Vptr; - if (isTargetMacOS()) + if (isTargetMacOS()) { + if (!isMacosxVersionLT(10, 9)) + Res |= SanitizerKind::Vptr; Res |= SanitizerKind::SafeStack; - - if (sanitizerRuntimeExists("tsan") && IsX86_64 && - (isTargetMacOS() || isTargetIOSSimulator() || isTargetTvOSSimulator())) - Res |= SanitizerKind::Thread; - + if (IsX86_64) + Res |= SanitizerKind::Thread; + } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) { + if (IsX86_64) + Res |= SanitizerKind::Thread; + } return Res; } void Darwin::printVerboseInfo(raw_ostream &OS) const { CudaInstallation.print(OS); } - -bool Darwin::sanitizerRuntimeExists(StringRef SanitizerName, - bool Shared) const { - std::string RelName = getFileNameForSanitizerLib(SanitizerName, Shared); - SmallString<128> Dir = runtimeLibDir(); - SmallString<128> AbsName(Dir); - llvm::sys::path::append(AbsName, RelName); - return getVFS().exists(AbsName); -} diff --git a/lib/Driver/ToolChains/Darwin.h b/lib/Driver/ToolChains/Darwin.h index eee6e966718b5..87d553bd7e0b2 100644 --- a/lib/Driver/ToolChains/Darwin.h +++ b/lib/Driver/ToolChains/Darwin.h @@ -130,9 +130,6 @@ protected: Tool *buildLinker() const override; Tool *getTool(Action::ActionClass AC) const override; - /// \return Directory to find the runtime library in. - SmallString<128> runtimeLibDir(bool IsEmbedded=false) const; - private: mutable std::unique_ptr<tools::darwin::Lipo> Lipo; mutable std::unique_ptr<tools::darwin::Dsymutil> Dsymutil; @@ -254,6 +251,7 @@ public: GetExceptionModel(const llvm::opt::ArgList &Args) const override { return llvm::ExceptionHandling::None; } + /// } }; @@ -422,11 +420,6 @@ protected: StringRef getPlatformFamily() const; StringRef getOSLibraryNameSuffix() const; - /// \return Relative path to the filename for the library - /// containing the sanitizer {@code SanitizerName}. - std::string getFileNameForSanitizerLib(StringRef SanitizerName, - bool Shared = true) const; - public: static StringRef getSDKName(StringRef isysroot); @@ -480,12 +473,6 @@ public: SanitizerMask getSupportedSanitizers() const override; void printVerboseInfo(raw_ostream &OS) const override; - -private: - /// \return Whether the runtime corresponding to the given - /// sanitizer exists in the toolchain. - bool sanitizerRuntimeExists(StringRef SanitizerName, - bool Shared = true) const; }; /// DarwinClang - The Darwin toolchain used by Clang. diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp index 2c83598f3d779..3755673250b2d 100644 --- a/lib/Driver/ToolChains/Gnu.cpp +++ b/lib/Driver/ToolChains/Gnu.cpp @@ -1877,7 +1877,8 @@ void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes( static const char *const RISCV32LibDirs[] = {"/lib", "/lib32"}; static const char *const RISCVTriples[] = {"riscv32-unknown-linux-gnu", - "riscv64-unknown-linux-gnu"}; + "riscv64-unknown-linux-gnu", + "riscv32-unknown-elf"}; static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"}; static const char *const SPARCv8Triples[] = {"sparc-linux-gnu", @@ -2188,7 +2189,8 @@ void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple( // this on Freescale triples, though, since some systems put a *lot* of // files in that location, not just GCC installation data. {CandidateTriple.str(), "..", - TargetTriple.getVendor() == llvm::Triple::Freescale}, + TargetTriple.getVendor() == llvm::Triple::Freescale || + TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}, // Natively multiarch systems sometimes put the GCC triple-specific // directory within their multiarch lib directory, resulting in the diff --git a/lib/Driver/ToolChains/Linux.cpp b/lib/Driver/ToolChains/Linux.cpp index d27f994d32abd..f8f36239180cf 100644 --- a/lib/Driver/ToolChains/Linux.cpp +++ b/lib/Driver/ToolChains/Linux.cpp @@ -376,7 +376,14 @@ Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) } addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths); - addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths); + // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot + // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle + // this here. + if (Triple.getVendor() == llvm::Triple::OpenEmbedded && + Triple.isArch64Bit()) + addPathIfExists(D, SysRoot + "/usr/" + OSLibDir, Paths); + else + addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths); if (IsRISCV) { StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple); addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths); diff --git a/lib/Driver/ToolChains/RISCV.cpp b/lib/Driver/ToolChains/RISCV.cpp new file mode 100644 index 0000000000000..31996fc588f19 --- /dev/null +++ b/lib/Driver/ToolChains/RISCV.cpp @@ -0,0 +1,117 @@ +//===--- RISCV.cpp - RISCV ToolChain Implementations ------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "RISCV.h" +#include "CommonArgs.h" +#include "InputInfo.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/Options.h" +#include "llvm/Option/ArgList.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/raw_ostream.h" + +using namespace clang::driver; +using namespace clang::driver::toolchains; +using namespace clang::driver::tools; +using namespace clang; +using namespace llvm::opt; + +/// RISCV Toolchain +RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple, + const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + GCCInstallation.init(Triple, Args); + getFilePaths().push_back(D.SysRoot + "/lib"); + if (GCCInstallation.isValid()) { + getFilePaths().push_back(GCCInstallation.getInstallPath().str()); + getProgramPaths().push_back( + (GCCInstallation.getParentLibPath() + "/../bin").str()); + } +} + +Tool *RISCVToolChain::buildLinker() const { + return new tools::RISCV::Linker(*this); +} + +void RISCVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + if (DriverArgs.hasArg(options::OPT_nostdinc)) + return; + + if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) { + SmallString<128> Dir(getDriver().SysRoot); + llvm::sys::path::append(Dir, "include"); + addSystemInclude(DriverArgs, CC1Args, Dir.str()); + } +} + +void RISCVToolChain::addLibStdCxxIncludePaths( + const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const { + StringRef LibDir = GCCInstallation.getParentLibPath(); + const GCCVersion &Version = GCCInstallation.getVersion(); + StringRef TripleStr = GCCInstallation.getTriple().str(); + const Multilib &Multilib = GCCInstallation.getMultilib(); + addLibStdCXXIncludePaths( + LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text, + "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args); +} + +void RISCV::Linker::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const ToolChain &ToolChain = getToolChain(); + const Driver &D = ToolChain.getDriver(); + ArgStringList CmdArgs; + + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); + + std::string Linker = getToolChain().GetProgramPath(getShortName()); + + bool WantCRTs = + !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles); + + if (WantCRTs) { + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o"))); + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o"))); + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + ToolChain.AddFilePathLibArgs(Args, CmdArgs); + Args.AddAllArgs(CmdArgs, + {options::OPT_T_Group, options::OPT_e, options::OPT_s, + options::OPT_t, options::OPT_Z_Flag, options::OPT_r}); + + AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA); + + // TODO: add C++ includes and libs if compiling C++. + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (ToolChain.ShouldLinkCXXStdlib(Args)) + ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("--start-group"); + CmdArgs.push_back("-lc"); + CmdArgs.push_back("-lgloss"); + CmdArgs.push_back("--end-group"); + CmdArgs.push_back("-lgcc"); + } + + if (WantCRTs) + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o"))); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker), + CmdArgs, Inputs)); +} +// RISCV tools end. diff --git a/lib/Driver/ToolChains/RISCV.h b/lib/Driver/ToolChains/RISCV.h new file mode 100644 index 0000000000000..6f59d84020d83 --- /dev/null +++ b/lib/Driver/ToolChains/RISCV.h @@ -0,0 +1,57 @@ +//===--- RISCV.h - RISCV ToolChain Implementations --------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_RISCV_H +#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_RISCV_H + +#include "Gnu.h" +#include "clang/Driver/ToolChain.h" + +namespace clang { +namespace driver { +namespace toolchains { + +class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public Generic_ELF { +public: + RISCVToolChain(const Driver &D, const llvm::Triple &Triple, + const llvm::opt::ArgList &Args); + + bool IsIntegratedAssemblerDefault() const override { return true; } + void + AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const override; + void + addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const override; + +protected: + Tool *buildLinker() const override; +}; + +} // end namespace toolchains + +namespace tools { +namespace RISCV { +class LLVM_LIBRARY_VISIBILITY Linker : public GnuTool { +public: + Linker(const ToolChain &TC) : GnuTool("RISCV::Linker", "ld", TC) {} + bool hasIntegratedCPP() const override { return false; } + bool isLinkJob() const override { return true; } + void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, const InputInfoList &Inputs, + const llvm::opt::ArgList &TCArgs, + const char *LinkingOutput) const override; +}; +} // end namespace RISCV +} // end namespace tools + +} // end namespace driver +} // end namespace clang + +#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_RISCV_H diff --git a/lib/Edit/Commit.cpp b/lib/Edit/Commit.cpp index afc1a131eb258..e72b13cf81983 100644 --- a/lib/Edit/Commit.cpp +++ b/lib/Edit/Commit.cpp @@ -147,7 +147,7 @@ bool Commit::replaceWithInner(CharSourceRange range, } FileOffset OuterEnd = OuterBegin.getWithOffset(OuterLen); - FileOffset InnerEnd = InnerBegin.getWithOffset(InnerLen); + FileOffset InnerEnd = InnerBegin.getWithOffset(InnerLen); if (OuterBegin.getFID() != InnerBegin.getFID() || InnerBegin < OuterBegin || InnerBegin > OuterEnd || @@ -300,7 +300,7 @@ bool Commit::canRemoveRange(CharSourceRange range, range = Lexer::makeFileCharRange(range, SM, LangOpts); if (range.isInvalid()) return false; - + if (range.getBegin().isMacroID() || range.getEnd().isMacroID()) return false; if (SM.isInSystemHeader(range.getBegin()) || diff --git a/lib/Edit/RewriteObjCFoundationAPI.cpp b/lib/Edit/RewriteObjCFoundationAPI.cpp index f89526a71da21..b53a70d87582b 100644 --- a/lib/Edit/RewriteObjCFoundationAPI.cpp +++ b/lib/Edit/RewriteObjCFoundationAPI.cpp @@ -82,7 +82,7 @@ bool edit::rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg, (NS.getNSDictionarySelector( NSAPI::NSDict_dictionaryWithDictionary) == Sel || NS.getNSDictionarySelector(NSAPI::NSDict_initWithDictionary) == Sel))) { - + commit.replaceWithInner(Msg->getSourceRange(), Msg->getArg(0)->getSourceRange()); return true; @@ -726,7 +726,7 @@ static bool getLiteralInfo(SourceRange literalRange, } else break; } - + if (!UpperU.hasValue() && !UpperL.hasValue()) UpperU = UpperL = true; else if (UpperU.hasValue() && !UpperL.hasValue()) @@ -738,7 +738,7 @@ static bool getLiteralInfo(SourceRange literalRange, Info.L = *UpperL ? "L" : "l"; Info.LL = *UpperL ? "LL" : "ll"; Info.F = UpperF ? "F" : "f"; - + Info.Hex = Info.Octal = false; if (text.startswith("0x")) Info.Hex = true; @@ -851,7 +851,7 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, // Try to modify the literal make it the same type as the method call. // -Modify the suffix, and/or // -Change integer to float - + LiteralInfo LitInfo; bool isIntZero = false; if (const IntegerLiteral *IntE = dyn_cast<IntegerLiteral>(literalE)) @@ -862,7 +862,7 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, // Not easy to do int -> float with hex/octal and uncommon anyway. if (!LitIsFloat && CallIsFloating && (LitInfo.Hex || LitInfo.Octal)) return rewriteToNumericBoxedExpression(Msg, NS, commit); - + SourceLocation LitB = LitInfo.WithoutSuffRange.getBegin(); SourceLocation LitE = LitInfo.WithoutSuffRange.getEnd(); @@ -879,7 +879,7 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, } else { if (CallIsUnsigned) commit.insert(LitE, LitInfo.U); - + if (CallIsLong) commit.insert(LitE, LitInfo.L); else if (CallIsLongLong) @@ -997,7 +997,7 @@ static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg, uint64_t FinalTySize = Ctx.getTypeSize(FinalTy); uint64_t OrigTySize = Ctx.getTypeSize(OrigTy); - bool isTruncated = FinalTySize < OrigTySize; + bool isTruncated = FinalTySize < OrigTySize; bool needsCast = false; if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { @@ -1090,7 +1090,7 @@ static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg, } if (needsCast) { - DiagnosticsEngine &Diags = Ctx.getDiagnostics(); + DiagnosticsEngine &Diags = Ctx.getDiagnostics(); // FIXME: Use a custom category name to distinguish migration diagnostics. unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "converting to boxing syntax requires casting %0 to %1"); @@ -1145,7 +1145,7 @@ static bool doRewriteToUTF8StringBoxedExpressionHelper( commit.insertBefore(ArgRange.getBegin(), "@"); else commit.insertWrap("@(", ArgRange, ")"); - + return true; } } diff --git a/lib/Format/BreakableToken.cpp b/lib/Format/BreakableToken.cpp index cc68f70100e36..fc2f891e0857e 100644 --- a/lib/Format/BreakableToken.cpp +++ b/lib/Format/BreakableToken.cpp @@ -235,6 +235,7 @@ BreakableToken::Split BreakableStringLiteral::getSplit( void BreakableStringLiteral::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const { Whitespaces.replaceWhitespaceInToken( Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, @@ -510,8 +511,33 @@ unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, return std::max(0, ContentColumn[LineIndex]); } +const llvm::StringSet<> + BreakableBlockComment::ContentIndentingJavadocAnnotations = { + "@param", "@return", "@returns", "@throws", "@type", "@template", + "@see", "@deprecated", "@define", "@exports", "@mods", "@private", +}; + +unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const { + if (Style.Language != FormatStyle::LK_Java && + Style.Language != FormatStyle::LK_JavaScript) + return 0; + // The content at LineIndex 0 of a comment like: + // /** line 0 */ + // is "* line 0", so we need to skip over the decoration in that case. + StringRef ContentWithNoDecoration = Content[LineIndex]; + if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) { + ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks); + } + StringRef FirstWord = ContentWithNoDecoration.substr( + 0, ContentWithNoDecoration.find_first_of(Blanks)); + if (ContentIndentingJavadocAnnotations.find(FirstWord) != + ContentIndentingJavadocAnnotations.end()) + return Style.ContinuationIndentWidth; + return 0; +} + void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, - Split Split, + Split Split, unsigned ContentIndent, WhitespaceManager &Whitespaces) const { StringRef Text = Content[LineIndex].substr(TailOffset); StringRef Prefix = Decoration; @@ -532,10 +558,14 @@ void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; assert(LocalIndentAtLineBreak >= Prefix.size()); + std::string PrefixWithTrailingIndent = Prefix; + for (unsigned I = 0; I < ContentIndent; ++I) + PrefixWithTrailingIndent += " "; Whitespaces.replaceWhitespaceInToken( - tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix, - InPPDirective, /*Newlines=*/1, - /*Spaces=*/LocalIndentAtLineBreak - Prefix.size()); + tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", + PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1, + /*Spaces=*/LocalIndentAtLineBreak + ContentIndent - + PrefixWithTrailingIndent.size()); } BreakableToken::Split @@ -544,7 +574,16 @@ BreakableBlockComment::getReflowSplit(unsigned LineIndex, if (!mayReflow(LineIndex, CommentPragmasRegex)) return Split(StringRef::npos, 0); + // If we're reflowing into a line with content indent, only reflow the next + // line if its starting whitespace matches the content indent. size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks); + if (LineIndex) { + unsigned PreviousContentIndent = getContentIndent(LineIndex - 1); + if (PreviousContentIndent && Trimmed != StringRef::npos && + Trimmed != PreviousContentIndent) + return Split(StringRef::npos, 0); + } + return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); } @@ -583,7 +622,8 @@ void BreakableBlockComment::adaptStartOfLine( // break length are the same. size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks); if (BreakLength != StringRef::npos) - insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces); + insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0, + Whitespaces); } return; } @@ -754,7 +794,7 @@ unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex, void BreakableLineCommentSection::insertBreak( unsigned LineIndex, unsigned TailOffset, Split Split, - WhitespaceManager &Whitespaces) const { + unsigned ContentIndent, WhitespaceManager &Whitespaces) const { StringRef Text = Content[LineIndex].substr(TailOffset); // Compute the offset of the split relative to the beginning of the token // text. diff --git a/lib/Format/BreakableToken.h b/lib/Format/BreakableToken.h index 0fac8f08c0268..10e1801780214 100644 --- a/lib/Format/BreakableToken.h +++ b/lib/Format/BreakableToken.h @@ -21,6 +21,7 @@ #include "Encoding.h" #include "TokenAnnotator.h" #include "WhitespaceManager.h" +#include "llvm/ADT/StringSet.h" #include "llvm/Support/Regex.h" #include <utility> @@ -135,6 +136,21 @@ public: virtual unsigned getContentStartColumn(unsigned LineIndex, bool Break) const = 0; + /// Returns additional content indent required for the second line after the + /// content at line \p LineIndex is broken. + /// + // (Next lines do not start with `///` since otherwise -Wdocumentation picks + // up the example annotations and generates warnings for them) + // For example, Javadoc @param annotations require and indent of 4 spaces and + // in this example getContentIndex(1) returns 4. + // /** + // * @param loooooooooooooong line + // * continuation + // */ + virtual unsigned getContentIndent(unsigned LineIndex) const { + return 0; + } + /// Returns a range (offset, length) at which to break the line at /// \p LineIndex, if previously broken at \p TailOffset. If possible, do not /// violate \p ColumnLimit, assuming the text starting at \p TailOffset in @@ -146,6 +162,7 @@ public: /// Emits the previously retrieved \p Split via \p Whitespaces. virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const = 0; /// Returns the number of columns needed to format @@ -210,7 +227,7 @@ public: Split SplitAfterLastLine, WhitespaceManager &Whitespaces) const { insertBreak(getLineCount() - 1, TailOffset, SplitAfterLastLine, - Whitespaces); + /*ContentIndent=*/0, Whitespaces); } /// Updates the next token of \p State to the next token after this @@ -245,6 +262,7 @@ public: unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) const override {} @@ -354,7 +372,9 @@ public: unsigned getRemainingLength(unsigned LineIndex, unsigned Offset, unsigned StartColumn) const override; unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override; + unsigned getContentIndent(unsigned LineIndex) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; Split getReflowSplit(unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const override; @@ -368,6 +388,10 @@ public: bool mayReflow(unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const override; + // Contains Javadoc annotations that require additional indent when continued + // on multiple lines. + static const llvm::StringSet<> ContentIndentingJavadocAnnotations; + private: // Rearranges the whitespace between Lines[LineIndex-1] and Lines[LineIndex]. // @@ -423,6 +447,7 @@ public: unsigned StartColumn) const override; unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; Split getReflowSplit(unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const override; diff --git a/lib/Format/ContinuationIndenter.cpp b/lib/Format/ContinuationIndenter.cpp index 90d2a9997111e..7ca588a675b5a 100644 --- a/lib/Format/ContinuationIndenter.cpp +++ b/lib/Format/ContinuationIndenter.cpp @@ -1809,6 +1809,7 @@ ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, if (!DryRun) Token->adaptStartOfLine(0, Whitespaces); + unsigned ContentIndent = 0; unsigned Penalty = 0; LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column " << StartColumn << ".\n"); @@ -1930,11 +1931,28 @@ ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, } } LLVM_DEBUG(llvm::dbgs() << " Breaking...\n"); - ContentStartColumn = - Token->getContentStartColumn(LineIndex, /*Break=*/true); + // Update the ContentIndent only if the current line was not reflown with + // the previous line, since in that case the previous line should still + // determine the ContentIndent. Also never intent the last line. + if (!Reflow) + ContentIndent = Token->getContentIndent(LineIndex); + LLVM_DEBUG(llvm::dbgs() + << " ContentIndent: " << ContentIndent << "\n"); + ContentStartColumn = ContentIndent + Token->getContentStartColumn( + LineIndex, /*Break=*/true); + unsigned NewRemainingTokenColumns = Token->getRemainingLength( LineIndex, TailOffset + Split.first + Split.second, ContentStartColumn); + if (NewRemainingTokenColumns == 0) { + // No content to indent. + ContentIndent = 0; + ContentStartColumn = + Token->getContentStartColumn(LineIndex, /*Break=*/true); + NewRemainingTokenColumns = Token->getRemainingLength( + LineIndex, TailOffset + Split.first + Split.second, + ContentStartColumn); + } // When breaking before a tab character, it may be moved by a few columns, // but will still be expanded to the next tab stop, so we don't save any @@ -1948,7 +1966,8 @@ ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first << ", " << Split.second << "\n"); if (!DryRun) - Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces); + Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent, + Whitespaces); Penalty += NewBreakPenalty; TailOffset += Split.first + Split.second; diff --git a/lib/Format/ContinuationIndenter.h b/lib/Format/ContinuationIndenter.h index 4ff05ba99f1a4..fde89db864b18 100644 --- a/lib/Format/ContinuationIndenter.h +++ b/lib/Format/ContinuationIndenter.h @@ -107,7 +107,7 @@ private: void moveStateToNewBlock(LineState &State); /// Reformats a raw string literal. - /// + /// /// \returns An extra penalty induced by reformatting the token. unsigned reformatRawStringLiteral(const FormatToken &Current, LineState &State, diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index 59d34308c0a9c..9a2da69e89b1f 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -777,9 +777,11 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { { "EqualsProto", "EquivToProto", + "PARSE_PARTIAL_TEXT_PROTO", "PARSE_TEST_PROTO", "PARSE_TEXT_PROTO", "ParseTextOrDie", + "ParseTextProtoOrDie", }, /*CanonicalDelimiter=*/"", /*BasedOnStyle=*/"google", @@ -808,10 +810,9 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.BreakBeforeTernaryOperators = false; - // taze:, triple slash directives (`/// <...`), @tag followed by { for a lot - // of JSDoc tags, and @see, which is commonly followed by overlong URLs. - GoogleStyle.CommentPragmas = - "(taze:|^/[ \t]*<|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)"; + // taze:, triple slash directives (`/// <...`), @see, which is commonly + // followed by overlong URLs. + GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)"; GoogleStyle.MaxEmptyLinesToKeep = 3; GoogleStyle.NamespaceIndentation = FormatStyle::NI_All; GoogleStyle.SpacesInContainerLiterals = false; diff --git a/lib/Frontend/ASTConsumers.cpp b/lib/Frontend/ASTConsumers.cpp index b67c019baed84..2a8bfef68eb9a 100644 --- a/lib/Frontend/ASTConsumers.cpp +++ b/lib/Frontend/ASTConsumers.cpp @@ -181,7 +181,7 @@ namespace { void ASTViewer::HandleTopLevelSingleDecl(Decl *D) { if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { D->print(llvm::errs()); - + if (Stmt *Body = D->getBody()) { llvm::errs() << '\n'; Body->viewAST(); diff --git a/lib/Frontend/ASTMerge.cpp b/lib/Frontend/ASTMerge.cpp index 6ec0e2a98c1b1..2434113ab0dbb 100644 --- a/lib/Frontend/ASTMerge.cpp +++ b/lib/Frontend/ASTMerge.cpp @@ -51,9 +51,9 @@ void ASTMergeAction::ExecuteAction() { if (!Unit) continue; - ASTImporter Importer(CI.getASTContext(), + ASTImporter Importer(CI.getASTContext(), CI.getFileManager(), - Unit->getASTContext(), + Unit->getASTContext(), Unit->getFileManager(), /*MinimalImport=*/false); @@ -64,9 +64,9 @@ void ASTMergeAction::ExecuteAction() { if (IdentifierInfo *II = ND->getIdentifier()) if (II->isStr("__va_list_tag") || II->isStr("__builtin_va_list")) continue; - + Decl *ToD = Importer.Import(D); - + if (ToD) { DeclGroupRef DGR(ToD); CI.getASTConsumer().HandleTopLevelDecl(DGR); @@ -88,7 +88,7 @@ ASTMergeAction::ASTMergeAction(std::unique_ptr<FrontendAction> adaptedAction, assert(AdaptedAction && "ASTMergeAction needs an action to adapt"); } -ASTMergeAction::~ASTMergeAction() { +ASTMergeAction::~ASTMergeAction() { } bool ASTMergeAction::usesPreprocessorOnly() const { diff --git a/lib/Frontend/ChainedIncludesSource.cpp b/lib/Frontend/ChainedIncludesSource.cpp index 534c7587f48d8..4e8eb32121dc6 100644 --- a/lib/Frontend/ChainedIncludesSource.cpp +++ b/lib/Frontend/ChainedIncludesSource.cpp @@ -126,7 +126,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( bool firstInclude = (i == 0); std::unique_ptr<CompilerInvocation> CInvok; CInvok.reset(new CompilerInvocation(CI.getInvocation())); - + CInvok->getPreprocessorOpts().ChainedIncludes.clear(); CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear(); CInvok->getPreprocessorOpts().ImplicitPTHInclude.clear(); @@ -134,7 +134,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( CInvok->getPreprocessorOpts().Includes.clear(); CInvok->getPreprocessorOpts().MacroIncludes.clear(); CInvok->getPreprocessorOpts().Macros.clear(); - + CInvok->getFrontendOpts().Inputs.clear(); FrontendInputFile InputFile(includes[i], IK); CInvok->getFrontendOpts().Inputs.push_back(InputFile); @@ -193,7 +193,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( Clang->setModuleManager(Reader); Clang->getASTContext().setExternalSource(Reader); } - + if (!Clang->InitializeSourceManager(InputFile)) return nullptr; diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp index 155ead4ac8e85..ecb09da3c1ef4 100644 --- a/lib/Frontend/CompilerInstance.cpp +++ b/lib/Frontend/CompilerInstance.cpp @@ -292,7 +292,7 @@ CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, if (!Opts->DiagnosticSerializationFile.empty()) SetupSerializedDiagnostics(Opts, *Diags, Opts->DiagnosticSerializationFile); - + // Configure our handling of diagnostics. ProcessWarningOptions(*Diags, *Opts); @@ -935,7 +935,7 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) { // Adjust target options based on codegen options. getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts()); - // rewriter project will change target built-in bool type from its default. + // rewriter project will change target built-in bool type from its default. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) getTarget().noSignedCharForObjCBool(); @@ -1026,7 +1026,7 @@ static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts) { return LangOpts.CPlusPlus ? InputKind::CXX : InputKind::C; } -/// Compile a module file for the given module, using the options +/// Compile a module file for the given module, using the options /// provided by the importing compiler instance. Returns true if the module /// was built without errors. static bool @@ -1042,7 +1042,7 @@ compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation()); PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); - + // For any options that aren't intended to affect how a module is built, // reset them to their default values. Invocation->getLangOpts()->resetNonModularOptions(); @@ -1092,11 +1092,11 @@ compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, // Don't free the remapped file buffers; they are owned by our caller. PPOpts.RetainRemappedFileBuffers = true; - + Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; assert(ImportingInstance.getInvocation().getModuleHash() == Invocation->getModuleHash() && "Module hash mismatch!"); - + // Construct a compiler instance that will be used to actually create the // module. Since we're sharing a PCMCache, // CompilerInstance::CompilerInstance is responsible for finalizing the @@ -1172,7 +1172,7 @@ static const FileEntry *getPublicModuleMap(const FileEntry *File, return FileMgr.getFile(PublicFilename); } -/// Compile a module file for the given module, using the options +/// Compile a module file for the given module, using the options /// provided by the importing compiler instance. Returns true if the module /// was built without errors. static bool compileModuleImpl(CompilerInstance &ImportingInstance, @@ -1183,7 +1183,7 @@ static bool compileModuleImpl(CompilerInstance &ImportingInstance, InputKind::ModuleMap); // Get or create the module map that we'll use to build this module. - ModuleMap &ModMap + ModuleMap &ModMap = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); bool Result; if (const FileEntry *ModuleMapFile = @@ -1327,7 +1327,7 @@ static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, Module *Mod, SourceLocation ImportLoc) { IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); SourceManager &SourceMgr = PP.getSourceManager(); - + // If this identifier has never had a macro definition, then it could // not have changed. if (!Id->hadMacroDefinition()) @@ -1651,7 +1651,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, = KnownModules.find(Path[0].first); if (Known != KnownModules.end()) { // Retrieve the cached top-level module. - Module = Known->second; + Module = Known->second; } else if (ModuleName == getLangOpts().CurrentModule) { // This is the module we're building. Module = PP->getHeaderSearchInfo().lookupModule( @@ -1851,7 +1851,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, // Cache the result of this top-level module lookup for later. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; } - + // If we never found the module, fail. if (!Module) return ModuleLoadResult(); @@ -1897,13 +1897,13 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, } } } - + if (!Sub) { // Attempt to perform typo correction to find a module name that works. SmallVector<StringRef, 2> Best; unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); - - for (clang::Module::submodule_iterator J = Module->submodule_begin(), + + for (clang::Module::submodule_iterator J = Module->submodule_begin(), JEnd = Module->submodule_end(); J != JEnd; ++J) { unsigned ED = Name.edit_distance((*J)->Name, @@ -1914,20 +1914,20 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, Best.clear(); BestEditDistance = ED; } - + Best.push_back((*J)->Name); } } - + // If there was a clear winner, user it. if (Best.size() == 1) { - getDiagnostics().Report(Path[I].second, + getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest) << Path[I].first << Module->getFullModuleName() << Best[0] << SourceRange(Path[0].second, Path[I-1].second) << FixItHint::CreateReplacement(SourceRange(Path[I].second), Best[0]); - + Sub = Module->findSubmodule(Best[0]); } } @@ -1940,7 +1940,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, << SourceRange(Path[0].second, Path[I-1].second); break; } - + Module = Sub; } } diff --git a/lib/Frontend/DependencyFile.cpp b/lib/Frontend/DependencyFile.cpp index f89722eeb9edc..e6e07190e1ffb 100644 --- a/lib/Frontend/DependencyFile.cpp +++ b/lib/Frontend/DependencyFile.cpp @@ -318,7 +318,7 @@ void DFGImpl::InclusionDirective(SourceLocation HashLoc, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, - const Module *Imported, + const Module *Imported, SrcMgr::CharacteristicKind FileType) { if (!File) { if (AddMissingHeaderDeps) diff --git a/lib/Frontend/DependencyGraph.cpp b/lib/Frontend/DependencyGraph.cpp index 660f664447ab1..c6c9ac2ea2fa5 100644 --- a/lib/Frontend/DependencyGraph.cpp +++ b/lib/Frontend/DependencyGraph.cpp @@ -33,9 +33,9 @@ class DependencyGraphCallback : public PPCallbacks { llvm::SetVector<const FileEntry *> AllFiles; typedef llvm::DenseMap<const FileEntry *, SmallVector<const FileEntry *, 2> > DependencyMap; - + DependencyMap Dependencies; - + private: raw_ostream &writeNodeReference(raw_ostream &OS, const FileEntry *Node); @@ -56,7 +56,7 @@ public: void EndOfMainFile() override { OutputGraphFile(); } - + }; } @@ -75,11 +75,11 @@ void DependencyGraphCallback::InclusionDirective( const FileEntry *File, StringRef SearchPath, StringRef RelativePath, - const Module *Imported, + const Module *Imported, SrcMgr::CharacteristicKind FileType) { if (!File) return; - + SourceManager &SM = PP->getSourceManager(); const FileEntry *FromFile = SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(HashLoc))); @@ -87,7 +87,7 @@ void DependencyGraphCallback::InclusionDirective( return; Dependencies[FromFile].push_back(File); - + AllFiles.insert(File); AllFiles.insert(FromFile); } @@ -109,7 +109,7 @@ void DependencyGraphCallback::OutputGraphFile() { } OS << "digraph \"dependencies\" {\n"; - + // Write the nodes for (unsigned I = 0, N = AllFiles.size(); I != N; ++I) { // Write the node itself. @@ -119,15 +119,15 @@ void DependencyGraphCallback::OutputGraphFile() { StringRef FileName = AllFiles[I]->getName(); if (FileName.startswith(SysRoot)) FileName = FileName.substr(SysRoot.size()); - + OS << DOT::EscapeString(FileName) << "\"];\n"; } // Write the edges - for (DependencyMap::iterator F = Dependencies.begin(), + for (DependencyMap::iterator F = Dependencies.begin(), FEnd = Dependencies.end(); - F != FEnd; ++F) { + F != FEnd; ++F) { for (unsigned I = 0, N = F->second.size(); I != N; ++I) { OS.indent(2); writeNodeReference(OS, F->first); diff --git a/lib/Frontend/DiagnosticRenderer.cpp b/lib/Frontend/DiagnosticRenderer.cpp index fb0a92d1f8c69..757ceec7ec9d0 100644 --- a/lib/Frontend/DiagnosticRenderer.cpp +++ b/lib/Frontend/DiagnosticRenderer.cpp @@ -172,9 +172,9 @@ void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc, // Skip redundant include stacks altogether. if (LastIncludeLoc == IncludeLoc) return; - + LastIncludeLoc = IncludeLoc; - + if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note) return; @@ -199,7 +199,7 @@ void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) { return; // If this source location was imported from a module, print the module - // import stack rather than the + // import stack rather than the // FIXME: We want submodule granularity here. std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc(); if (!Imported.second.empty()) { diff --git a/lib/Frontend/FrontendAction.cpp b/lib/Frontend/FrontendAction.cpp index a5929424e52a9..74550c410396c 100644 --- a/lib/Frontend/FrontendAction.cpp +++ b/lib/Frontend/FrontendAction.cpp @@ -288,7 +288,7 @@ static void addHeaderInclude(StringRef HeaderName, Includes += "}\n"; } -/// Collect the set of header includes needed to construct the given +/// Collect the set of header includes needed to construct the given /// module and update the TopHeaders file set of the module. /// /// \param Module The module we're collecting includes from. @@ -345,7 +345,7 @@ static std::error_code collectModuleHeaderIncludes( vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; Dir != End && !EC; Dir.increment(EC)) { - // Check whether this entry has an extension typically associated with + // Check whether this entry has an extension typically associated with // headers. if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName())) .Cases(".h", ".H", ".hh", ".hpp", true) @@ -358,7 +358,7 @@ static std::error_code collectModuleHeaderIncludes( if (!Header) continue; - // If this header is marked 'unavailable' in this module, don't include + // If this header is marked 'unavailable' in this module, don't include // it. if (ModMap.isHeaderUnavailableInModule(Header, Module)) continue; @@ -431,7 +431,7 @@ static Module *prepareToBuildModule(CompilerInstance &CI, CI.getDiagnostics().Report(diag::err_missing_module_name); // FIXME: Eventually, we could consider asking whether there was just - // a single module described in the module map, and use that as a + // a single module described in the module map, and use that as a // default. Then it would be fairly trivial to just "compile" a module // map with a single module (the common case). return nullptr; diff --git a/lib/Frontend/FrontendActions.cpp b/lib/Frontend/FrontendActions.cpp index 9344e673c7ac8..8a8354c7d4c90 100644 --- a/lib/Frontend/FrontendActions.cpp +++ b/lib/Frontend/FrontendActions.cpp @@ -377,7 +377,7 @@ private: if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) { llvm::raw_string_ostream OS(Entry.Name); NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); - const PresumedLoc DefLoc = + const PresumedLoc DefLoc = TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation()); if(!DefLoc.isInvalid()) Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" + @@ -709,13 +709,13 @@ void PrintPreprocessedAction::ExecuteAction() { // the input format has inconsistent line endings. // // This should be a relatively fast operation since most files won't have - // all of their source code on a single line. However, that is still a + // all of their source code on a single line. However, that is still a // concern, so if we scan for too long, we'll just assume the file should // be opened in binary mode. bool BinaryMode = true; bool InvalidFile = false; const SourceManager& SM = CI.getSourceManager(); - const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), + const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), &InvalidFile); if (!InvalidFile) { const char *cur = Buffer->getBufferStart(); @@ -723,7 +723,7 @@ void PrintPreprocessedAction::ExecuteAction() { const char *next = (cur != end) ? cur + 1 : end; // Limit ourselves to only scanning 256 characters into the source - // file. This is mostly a sanity check in case the file has no + // file. This is mostly a sanity check in case the file has no // newlines whatsoever. if (end - cur > 256) end = cur + 256; @@ -774,7 +774,7 @@ void PrintPreambleAction::ExecuteAction() { case InputKind::CUDA: case InputKind::HIP: break; - + case InputKind::Unknown: case InputKind::Asm: case InputKind::LLVM_IR: diff --git a/lib/Frontend/LayoutOverrideSource.cpp b/lib/Frontend/LayoutOverrideSource.cpp index 93e07eb81f729..b31fbd087ba78 100644 --- a/lib/Frontend/LayoutOverrideSource.cpp +++ b/lib/Frontend/LayoutOverrideSource.cpp @@ -23,7 +23,7 @@ static std::string parseName(StringRef S) { unsigned Offset = 1; while (Offset < S.size() && isIdentifierBody(S[Offset])) ++Offset; - + return S.substr(0, Offset).str(); } @@ -31,33 +31,33 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { std::ifstream Input(Filename.str().c_str()); if (!Input.is_open()) return; - + // Parse the output of -fdump-record-layouts. std::string CurrentType; Layout CurrentLayout; bool ExpectingType = false; - + while (Input.good()) { std::string Line; getline(Input, Line); - + StringRef LineStr(Line); - // Determine whether the following line will start a + // Determine whether the following line will start a if (LineStr.find("*** Dumping AST Record Layout") != StringRef::npos) { // Flush the last type/layout, if there is one. if (!CurrentType.empty()) Layouts[CurrentType] = CurrentLayout; CurrentLayout = Layout(); - + ExpectingType = true; continue; } - + // If we're expecting a type, grab it. if (ExpectingType) { ExpectingType = false; - + StringRef::size_type Pos; if ((Pos = LineStr.find("struct ")) != StringRef::npos) LineStr = LineStr.substr(Pos + strlen("struct ")); @@ -67,19 +67,19 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { LineStr = LineStr.substr(Pos + strlen("union ")); else continue; - + // Find the name of the type. CurrentType = parseName(LineStr); CurrentLayout = Layout(); continue; } - + // Check for the size of the type. StringRef::size_type Pos = LineStr.find(" Size:"); if (Pos != StringRef::npos) { // Skip past the " Size:" prefix. LineStr = LineStr.substr(Pos + strlen(" Size:")); - + unsigned long long Size = 0; (void)LineStr.getAsInteger(10, Size); CurrentLayout.Size = Size; @@ -91,13 +91,13 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { if (Pos != StringRef::npos) { // Skip past the "Alignment:" prefix. LineStr = LineStr.substr(Pos + strlen("Alignment:")); - + unsigned long long Alignment = 0; (void)LineStr.getAsInteger(10, Alignment); CurrentLayout.Align = Alignment; continue; } - + // Check for the size/alignment of the type. Pos = LineStr.find("sizeof="); if (Pos != StringRef::npos) { @@ -113,16 +113,16 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { if (Pos != StringRef::npos) { /* Skip past the align= prefix. */ LineStr = LineStr.substr(Pos + strlen("align=")); - + // Parse alignment. unsigned long long Alignment = 0; (void)LineStr.getAsInteger(10, Alignment); CurrentLayout.Align = Alignment; } - + continue; } - + // Check for the field offsets of the type. Pos = LineStr.find("FieldOffsets: ["); if (Pos == StringRef::npos) @@ -134,55 +134,55 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { unsigned Idx = 1; while (Idx < LineStr.size() && isDigit(LineStr[Idx])) ++Idx; - + unsigned long long Offset = 0; (void)LineStr.substr(0, Idx).getAsInteger(10, Offset); - + CurrentLayout.FieldOffsets.push_back(Offset); - + // Skip over this offset, the following comma, and any spaces. LineStr = LineStr.substr(Idx + 1); while (!LineStr.empty() && isWhitespace(LineStr[0])) LineStr = LineStr.substr(1); } } - + // Flush the last type/layout, if there is one. if (!CurrentType.empty()) Layouts[CurrentType] = CurrentLayout; } -bool +bool LayoutOverrideSource::layoutRecordType(const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets, - llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets) + llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets) { // We can't override unnamed declarations. if (!Record->getIdentifier()) return false; - + // Check whether we have a layout for this record. llvm::StringMap<Layout>::iterator Known = Layouts.find(Record->getName()); if (Known == Layouts.end()) return false; - + // Provide field layouts. unsigned NumFields = 0; - for (RecordDecl::field_iterator F = Record->field_begin(), + for (RecordDecl::field_iterator F = Record->field_begin(), FEnd = Record->field_end(); F != FEnd; ++F, ++NumFields) { if (NumFields >= Known->second.FieldOffsets.size()) continue; - + FieldOffsets[*F] = Known->second.FieldOffsets[NumFields]; } - + // Wrong number of fields. if (NumFields != Known->second.FieldOffsets.size()) return false; - + Size = Known->second.Size; Alignment = Known->second.Align; return true; @@ -190,7 +190,7 @@ LayoutOverrideSource::layoutRecordType(const RecordDecl *Record, LLVM_DUMP_METHOD void LayoutOverrideSource::dump() { raw_ostream &OS = llvm::errs(); - for (llvm::StringMap<Layout>::iterator L = Layouts.begin(), + for (llvm::StringMap<Layout>::iterator L = Layouts.begin(), LEnd = Layouts.end(); L != LEnd; ++L) { OS << "Type: blah " << L->first() << '\n'; diff --git a/lib/Frontend/MultiplexConsumer.cpp b/lib/Frontend/MultiplexConsumer.cpp index df36c88ec38ef..c6e18d9cae21f 100644 --- a/lib/Frontend/MultiplexConsumer.cpp +++ b/lib/Frontend/MultiplexConsumer.cpp @@ -107,7 +107,7 @@ public: void DeclarationMarkedOpenMPDeclareTarget(const Decl *D, const Attr *Attr) override; void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override; - void AddedAttributeToRecord(const Attr *Attr, + void AddedAttributeToRecord(const Attr *Attr, const RecordDecl *Record) override; private: @@ -219,9 +219,9 @@ void MultiplexASTMutationListener::RedefinedHiddenDefinition(const NamedDecl *D, for (auto *L : Listeners) L->RedefinedHiddenDefinition(D, M); } - + void MultiplexASTMutationListener::AddedAttributeToRecord( - const Attr *Attr, + const Attr *Attr, const RecordDecl *Record) { for (auto *L : Listeners) L->AddedAttributeToRecord(Attr, Record); diff --git a/lib/Frontend/PrintPreprocessedOutput.cpp b/lib/Frontend/PrintPreprocessedOutput.cpp index 1b35b32656e73..69cd072ea57f4 100644 --- a/lib/Frontend/PrintPreprocessedOutput.cpp +++ b/lib/Frontend/PrintPreprocessedOutput.cpp @@ -160,7 +160,7 @@ public: } bool MoveToLine(unsigned LineNo); - bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok, + bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok, const Token &Tok) { return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok); } @@ -248,7 +248,7 @@ PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) { ++CurLine; return true; } - + return false; } @@ -262,11 +262,11 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, // Unless we are exiting a #include, make sure to skip ahead to the line the // #include directive was at. SourceManager &SourceMgr = SM; - + PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc); if (UserLoc.isInvalid()) return; - + unsigned NewLine = UserLoc.getLine(); if (Reason == PPCallbacks::EnterFile) { @@ -281,7 +281,7 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, // off by one. We can do better by simply incrementing NewLine here. NewLine += 1; } - + CurLine = NewLine; CurFilename.clear(); @@ -292,7 +292,7 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false); return; } - + if (!Initialized) { WriteLineInfo(CurLine); Initialized = true; diff --git a/lib/Frontend/Rewrite/FixItRewriter.cpp b/lib/Frontend/Rewrite/FixItRewriter.cpp index 64785e3012368..1c2efe63aa199 100644 --- a/lib/Frontend/Rewrite/FixItRewriter.cpp +++ b/lib/Frontend/Rewrite/FixItRewriter.cpp @@ -184,7 +184,7 @@ void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, } return; } - + if (!Editor.commit(commit)) { ++NumFailures; Diag(Info.getLocation(), diag::note_fixit_failed); diff --git a/lib/Frontend/Rewrite/FrontendActions.cpp b/lib/Frontend/Rewrite/FrontendActions.cpp index 4d587048f62d7..fa17b3e7cb3f5 100644 --- a/lib/Frontend/Rewrite/FrontendActions.cpp +++ b/lib/Frontend/Rewrite/FrontendActions.cpp @@ -131,9 +131,9 @@ bool FixItRecompile::BeginInvocation(CompilerInstance &CI) { FixItRewriter Rewriter(CI.getDiagnostics(), CI.getSourceManager(), CI.getLangOpts(), FixItOpts.get()); FixAction->Execute(); - + err = Rewriter.WriteFixedFiles(&RewrittenFiles); - + FixAction->EndSourceFile(); CI.setSourceManager(nullptr); CI.setFileManager(nullptr); diff --git a/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/lib/Frontend/Rewrite/RewriteModernObjC.cpp index 52b979c85f15b..36382e1438d52 100644 --- a/lib/Frontend/Rewrite/RewriteModernObjC.cpp +++ b/lib/Frontend/Rewrite/RewriteModernObjC.cpp @@ -39,12 +39,12 @@ using llvm::utostr; namespace { class RewriteModernObjC : public ASTConsumer { protected: - + enum { BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), block, ... */ BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ - BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the + BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the __block variable */ BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy helpers */ @@ -52,7 +52,7 @@ namespace { support routines */ BLOCK_BYREF_CURRENT_MAX = 256 }; - + enum { BLOCK_NEEDS_FREE = (1 << 24), BLOCK_HAS_COPY_DISPOSE = (1 << 25), @@ -61,7 +61,7 @@ namespace { BLOCK_IS_GLOBAL = (1 << 28), BLOCK_HAS_DESCRIPTOR = (1 << 29) }; - + Rewriter Rewrite; DiagnosticsEngine &Diags; const LangOptions &LangOpts; @@ -75,7 +75,7 @@ namespace { std::string InFileName; std::unique_ptr<raw_ostream> OutFile; std::string Preamble; - + TypeDecl *ProtocolTypeDecl; VarDecl *GlobalVarDecl; Expr *GlobalConstructionExp; @@ -88,13 +88,13 @@ namespace { // ObjC foreach break/continue generation support. int BcLabelCount; - + unsigned TryFinallyContainsReturnDiag; // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; - + FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; @@ -118,22 +118,22 @@ namespace { SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen; /// DefinedNonLazyClasses - List of defined "non-lazy" classes. SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses; - + /// DefinedNonLazyCategories - List of defined "non-lazy" categories. SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories; - + SmallVector<Stmt *, 32> Stmts; SmallVector<int, 8> ObjCBcLabelNo; // Remember all the @protocol(<expr>) expressions. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; - + llvm::DenseSet<uint64_t> CopyDestroyCache; // Block expressions. SmallVector<BlockExpr *, 32> Blocks; SmallVector<int, 32> InnerDeclRefsCount; SmallVector<DeclRefExpr *, 32> InnerDeclRefs; - + SmallVector<DeclRefExpr *, 32> BlockDeclRefs; // Block related declarations. @@ -144,11 +144,11 @@ namespace { llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; - + llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; - llvm::DenseMap<ObjCInterfaceDecl *, + llvm::DenseMap<ObjCInterfaceDecl *, llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars; - + // ivar bitfield grouping containers llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups; llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber; @@ -156,7 +156,7 @@ namespace { // of the struct where the bitfield belongs. llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType; SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen; - + // This maps an original source AST to it's rewritten form. This allows // us to avoid rewriting the same node twice (which is very uncommon). // This is needed to support some of the exotic property rewriting. @@ -167,12 +167,12 @@ namespace { bool SilenceRewriteMacroWarning; bool GenerateLineInfo; bool objc_impl_method; - + bool DisableReplaceStmt; class DisableReplaceStmtScope { RewriteModernObjC &R; bool SavedValue; - + public: DisableReplaceStmtScope(RewriteModernObjC &R) : R(R), SavedValue(R.DisableReplaceStmt) { @@ -237,7 +237,7 @@ namespace { } } } - + void HandleTopLevelSingleDecl(Decl *D); void HandleDeclInMainFile(Decl *D); RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, @@ -314,7 +314,7 @@ namespace { std::string &LineString); void RewriteForwardClassDecl(DeclGroupRef D); void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); - void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, + void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString); void RewriteImplementations(); void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -341,9 +341,9 @@ namespace { void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); void RewriteTypeOfDecl(VarDecl *VD); void RewriteObjCQualifiedInterfaceTypes(Expr *E); - + std::string getIvarAccessString(ObjCIvarDecl *D); - + // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); @@ -367,7 +367,7 @@ namespace { Stmt *RewriteContinueStmt(ContinueStmt *S); void RewriteCastExpr(CStyleCastExpr *CE); void RewriteImplicitCastObjCExpr(CastExpr *IE); - + // Computes ivar bitfield group no. unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV); // Names field decl. for ivar bitfield group. @@ -381,28 +381,28 @@ namespace { QualType SynthesizeBitfieldGroupStructType( ObjCIvarDecl *IV, SmallVectorImpl<ObjCIvarDecl *> &IVars); - + // Block rewriting. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); - + // Block specific rewrite rules. void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl); Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); - + void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); - + void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result); bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition); - void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, + void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result); - + bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result); - + void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, std::string &Result); @@ -414,9 +414,9 @@ namespace { ArrayRef<Expr *> Args, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); - + Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType returnType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method); @@ -424,7 +424,7 @@ namespace { Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); - + void SynthCountByEnumWithState(std::string &buf); void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); @@ -436,7 +436,7 @@ namespace { void SynthGetSuperClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperConstructorFunctionDecl(); - + // Rewriting metadata template<typename MethodIterator> void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, @@ -450,27 +450,27 @@ namespace { void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result); void RewriteClassSetupInitHook(std::string &Result); - + void RewriteMetaDataIntoBuffer(std::string &Result); void WriteImageInfo(std::string &Result); void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, std::string &Result); void RewriteCategorySetupInitHook(std::string &Result); - + // Rewriting ivar void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result); Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV); - + std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag); - std::string SynthesizeBlockImpl(BlockExpr *CE, + std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc); - std::string SynthesizeBlockDescriptor(std::string DescTag, + std::string SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef funcName, unsigned hasCopy); @@ -512,18 +512,18 @@ namespace { } return false; } - + bool convertObjCTypeToCStyleType(QualType &T); - + bool needToScanForQualifiers(QualType T); QualType getSuperStructType(); QualType getConstantStringStructType(); QualType convertFunctionTypeOfBlocks(const FunctionType *FT); - + void convertToUnqualifiedObjCType(QualType &T) { if (T->isObjCQualifiedIdType()) { bool isConst = T.isConstQualified(); - T = isConst ? Context->getObjCIdType().withConst() + T = isConst ? Context->getObjCIdType().withConst() : Context->getObjCIdType(); } else if (T->isObjCQualifiedClassType()) @@ -538,7 +538,7 @@ namespace { } } } - + // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) @@ -562,7 +562,7 @@ namespace { bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); - + void QuoteDoublequotes(std::string &From, std::string &To) { for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') @@ -589,7 +589,7 @@ namespace { return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr, TInfo, SourceLocation(), SourceLocation()); } - + bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const { IdentifierInfo* II = &Context->Idents.get("load"); Selector LoadSel = Context->Selectors.getSelector(0, &II); @@ -653,7 +653,7 @@ RewriteModernObjC::RewriteModernObjC(std::string inFile, // may break including some headers. GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "rewriting block literal declared in global scope is not implemented"); - + TryFinallyContainsReturnDiag = Diags.getCustomDiagID( DiagnosticsEngine::Warning, "rewriter doesn't support user-specified control flow semantics " @@ -756,7 +756,7 @@ void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardClassDecl(DG); @@ -781,14 +781,14 @@ void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardProtocolDecl(DG); continue; } } - + HandleTopLevelSingleDecl(*DI); ++DI; } @@ -836,28 +836,28 @@ static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl, Result += IvarDecl->getName(); } -std::string +std::string RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface(); - + // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(ClassDecl, D, IvarOffsetName); - + std::string S = "(*("; QualType IvarT = D->getType(); if (D->isBitField()) IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); - + if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl(); RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * - ObjCContainerDecl *CDecl = + ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) @@ -868,7 +868,7 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), @@ -893,7 +893,7 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { std::string TypeString(castT.getAsString(Context->getPrintingPolicy())); S += TypeString; S += ")"; - + // ((char *)self + IVAR_OFFSET_SYMBOL_NAME) S += "((char *)self + "; S += IvarOffsetName; @@ -913,7 +913,7 @@ static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, bool getter) { return getter ? !IMP->getInstanceMethod(PD->getGetterName()) : !IMP->getInstanceMethod(PD->getSetterName()); - + } void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -922,7 +922,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, static bool objcGetPropertyDefined = false; static bool objcSetPropertyDefined = false; SourceLocation startGetterSetterLoc; - + if (PID->getLocStart().isValid()) { SourceLocation startLoc = PID->getLocStart(); InsertText(startLoc, "// "); @@ -946,7 +946,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, unsigned Attributes = PD->getPropertyAttributes(); if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) { bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && - (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy)); std::string Getr; if (GenGetProperty && !objcGetPropertyDefined) { @@ -955,7 +955,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr = "\nextern \"C\" __declspec(dllimport) " "id objc_getProperty(id, SEL, long, bool);\n"; } - RewriteObjCMethodDecl(OID->getContainingInterface(), + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. @@ -969,7 +969,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += " _TYPE"; if (FPRetType) { Getr += ")"; // close the precedence "scope" for "*". - + // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ Getr += "("; @@ -999,14 +999,14 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += "; }"; InsertText(startGetterSetterLoc, Getr); } - - if (PD->isReadOnly() || + + if (PD->isReadOnly() || !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)) return; // Generate the 'setter' function. std::string Setr; - bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy); if (GenSetProperty && !objcSetPropertyDefined) { objcSetPropertyDefined = true; @@ -1015,7 +1015,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; } - RewriteObjCMethodDecl(OID->getContainingInterface(), + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. @@ -1063,9 +1063,9 @@ void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl const std::string &typedefString) { SourceLocation startLoc = ClassDecl->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - const char *semiPtr = strchr(startBuf, ';'); + const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. - ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); + ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); } void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) { @@ -1139,24 +1139,24 @@ void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { else { ReplaceText(LocStart, 0, "// "); } - + for (auto *I : CatDecl->instance_properties()) RewriteProperty(I); - + for (auto *I : CatDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : CatDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(CatDecl->getAtEndRange().getBegin(), + ReplaceText(CatDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation LocStart = PDecl->getLocStart(); assert(PDecl->isThisDeclarationADefinition()); - + // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); @@ -1166,7 +1166,7 @@ void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { RewriteMethodDeclaration(I); for (auto *I : PDecl->instance_properties()) RewriteProperty(I); - + // Lastly, comment out the @end. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); ReplaceText(LocEnd, strlen("@end"), "/* @end */\n"); @@ -1196,7 +1196,7 @@ void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { ReplaceText(LocStart, 0, "// "); } -void +void RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { SourceLocation LocStart = DG[0]->getLocStart(); if (LocStart.isInvalid()) @@ -1390,11 +1390,11 @@ void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { // we haven't seen a forward decl - generate a typedef. RewriteOneForwardClassDecl(ClassDecl, ResultStr); RewriteIvarOffsetSymbols(ClassDecl, ResultStr); - + RewriteObjCInternalStruct(ClassDecl, ResultStr); // Mark this typedef as having been written into its c++ equivalent. ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl()); - + for (auto *I : ClassDecl->instance_properties()) RewriteProperty(I); for (auto *I : ClassDecl->instance_methods()) @@ -1403,7 +1403,7 @@ void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), + ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } } @@ -1431,7 +1431,7 @@ Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseud Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); } - + unsigned numArgs = OldMsg->getNumArgs(); for (unsigned i = 0; i < numArgs; i++) { Expr *Arg = OldMsg->getArg(i); @@ -1869,11 +1869,11 @@ Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) SourceLocation SynchLoc = S->getAtSynchronizedLoc(); ConvertSourceLocationToLineDirective(SynchLoc, buf); buf += "{ id _rethrow = 0; id _sync_obj = (id)"; - + const char *lparenBuf = startBuf; while (*lparenBuf != '(') lparenBuf++; ReplaceText(startLoc, lparenBuf-startBuf+1, buf); - + buf = "; objc_sync_enter(_sync_obj);\n"; buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}"; buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}"; @@ -1887,16 +1887,16 @@ Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc); while (*RParenExprLocBuf != ')') RParenExprLocBuf--; RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf); - + SourceLocation LBranceLoc = S->getSynchBody()->getLocStart(); const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc); assert (*LBraceLocBuf == '{'); ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf); - + SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd(); assert((*SM->getCharacterData(startRBraceLoc) == '}') && "bogus @synchronized block"); - + buf = "} catch (id e) {_rethrow = e;}\n"; Write_RethrowObject(buf); buf += "}\n"; @@ -1923,7 +1923,7 @@ void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { SourceLocation startLoc = S->getAtLoc(); ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */"); - ReplaceText(S->getSubStmt()->getLocStart(), 1, + ReplaceText(S->getSubStmt()->getLocStart(), 1, "{ __AtAutoreleasePool __autoreleasepool; "); return nullptr; @@ -1935,7 +1935,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { std::string buf; SourceLocation TryLocation = S->getAtTryLoc(); ConvertSourceLocationToLineDirective(TryLocation, buf); - + if (finalStmt) { if (noCatch) buf += "{ id volatile _rethrow = 0;\n"; @@ -1953,11 +1953,11 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { else // @try -> try ReplaceText(startLoc, 1, ""); - + for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) { ObjCAtCatchStmt *Catch = S->getCatchStmt(I); VarDecl *catchDecl = Catch->getCatchParamDecl(); - + startLoc = Catch->getLocStart(); bool AtRemoved = false; if (catchDecl) { @@ -1968,12 +1968,12 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { if (IDecl) { std::string Result; ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result); - + startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @catch location"); SourceLocation rParenLoc = Catch->getRParenLoc(); const char *rParenBuf = SM->getCharacterData(rParenLoc); - + // _objc_exc_Foo *_e as argument to catch. Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString(); Result += " *_"; Result += catchDecl->getNameAsString(); @@ -1986,7 +1986,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { Result += " *"; Result += catchDecl->getNameAsString(); Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)"; Result += "_"; Result += catchDecl->getNameAsString(); - + Result += "; "; SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart(); ReplaceText(lBraceLoc, 1, Result); @@ -1997,12 +1997,12 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { if (!AtRemoved) // @catch -> catch ReplaceText(startLoc, 1, ""); - + } if (finalStmt) { buf.clear(); SourceLocation FinallyLoc = finalStmt->getLocStart(); - + if (noCatch) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; @@ -2012,7 +2012,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; } - + SourceLocation startFinalLoc = finalStmt->getLocStart(); ReplaceText(startFinalLoc, 8, buf); Stmt *body = finalStmt->getFinallyBody(); @@ -2020,7 +2020,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf.clear(); Write_RethrowObject(buf); ReplaceText(startFinalBodyLoc, 1, buf); - + SourceLocation endFinalBodyLoc = body->getLocEnd(); ReplaceText(endFinalBodyLoc, 1, "}\n}"); // Now check for any return/continue/go statements within the @try. @@ -2102,7 +2102,7 @@ RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, // Now, we cast the reference to a pointer to the objc_msgSend type. QualType pToFunc = Context->getPointerType(msgSendType); - ImplicitCastExpr *ICE = + ImplicitCastExpr *ICE = ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, DRE, nullptr, VK_RValue); @@ -2525,7 +2525,7 @@ void RewriteModernObjC::SynthGetClassFunctionDecl() { // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); void RewriteModernObjC::SynthGetSuperClassFunctionDecl() { - IdentifierInfo *getSuperClassIdent = + IdentifierInfo *getSuperClassIdent = &Context->Idents.get("class_getSuperclass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getObjCClassType()); @@ -2602,13 +2602,13 @@ Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) { unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - - Expr *FlagExp = IntegerLiteral::Create(*Context, - llvm::APInt(IntSize, Exp->getValue()), + + Expr *FlagExp = IntegerLiteral::Create(*Context, + llvm::APInt(IntSize, Exp->getValue()), Context->IntTy, Exp->getLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy, CK_BitCast, FlagExp); - ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), + ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), cast); ReplaceStmt(Exp, PE); return PE; @@ -2623,25 +2623,25 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); - + FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getLocStart(); SourceLocation EndLoc = Exp->getLocEnd(); - + // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 4> MsgExprs; SmallVector<Expr*, 4> ClsExprs; - + // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument. ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod(); ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface(); - + IdentifierInfo *clsName = BoxingClass->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); - + // Create a call to sel_registerName("<BoxingMethod>:"), etc. // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; @@ -2650,7 +2650,7 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); - + // User provided sub-expression is the 3rd, and last, argument. Expr *subExpr = Exp->getSubExpr(); if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) { @@ -2662,35 +2662,35 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr); } MsgExprs.push_back(subExpr); - + SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto PI : BoxingMethod->parameters()) ArgTypes.push_back(PI->getType()); - + QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - + CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); - + // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); @@ -2707,24 +2707,24 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); - + FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getLocStart(); SourceLocation EndLoc = Exp->getLocEnd(); - + // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSArrayFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSArrayFName("__NSContainer_literal"); FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName); - DeclRefExpr *NSArrayDRE = + DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation()); SmallVector<Expr*, 16> InitExprs; unsigned NumElements = Exp->getNumElements(); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), @@ -2732,7 +2732,7 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { InitExprs.push_back(count); for (unsigned i = 0; i < NumElements; i++) InitExprs.push_back(Exp->getElement(i)); - Expr *NSArrayCallExpr = + Expr *NSArrayCallExpr = new (Context) CallExpr(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue, SourceLocation()); @@ -2746,27 +2746,27 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD, SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); - CStyleCastExpr * ArrayLiteralObjects = - NoTypeInfoCStyleCastExpr(Context, + CStyleCastExpr * ArrayLiteralObjects = + NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, ArrayLiteralME); - + // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); - + // Create a call to objc_getClass("NSArray"). It will be th 1st argument. - ObjCInterfaceDecl *Class = + ObjCInterfaceDecl *Class = expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface(); - + IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); - + // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; @@ -2776,44 +2776,44 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); - + // (const id [])objects MsgExprs.push_back(ArrayLiteralObjects); - + // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); - + SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : ArrayMethod->parameters()) ArgTypes.push_back(PI->getType()); - + QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - + CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); - + // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); @@ -2830,26 +2830,26 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); - + FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getLocStart(); SourceLocation EndLoc = Exp->getLocEnd(); - + // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSDictFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSDictFName("__NSContainer_literal"); FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName); - DeclRefExpr *NSDictDRE = + DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue, SourceLocation()); - + SmallVector<Expr*, 16> KeyExprs; SmallVector<Expr*, 16> ValueExprs; - + unsigned NumElements = Exp->getNumElements(); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), @@ -2861,9 +2861,9 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral KeyExprs.push_back(Element.Key); ValueExprs.push_back(Element.Value); } - + // (const id [])objects - Expr *NSValueCallExpr = + Expr *NSValueCallExpr = new (Context) CallExpr(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue, SourceLocation()); @@ -2877,13 +2877,13 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD, SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); - CStyleCastExpr * DictValueObjects = - NoTypeInfoCStyleCastExpr(Context, + CStyleCastExpr * DictValueObjects = + NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralValueME); // (const id <NSCopying> [])keys - Expr *NSKeyCallExpr = + Expr *NSKeyCallExpr = new (Context) CallExpr(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation()); @@ -2891,27 +2891,27 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD, SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); - CStyleCastExpr * DictKeyObjects = - NoTypeInfoCStyleCastExpr(Context, + CStyleCastExpr * DictKeyObjects = + NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralKeyME); - + // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); - + // Create a call to objc_getClass("NSArray"). It will be th 1st argument. - ObjCInterfaceDecl *Class = + ObjCInterfaceDecl *Class = expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface(); - + IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); - + // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; @@ -2920,19 +2920,19 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); - + // (const id [])objects MsgExprs.push_back(DictValueObjects); - + // (const id <NSCopying> [])keys MsgExprs.push_back(DictKeyObjects); - + // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); - + SmallVector<QualType, 8> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); @@ -2945,29 +2945,29 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral } ArgTypes.push_back(T); } - + QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - + CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); - + // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); @@ -2975,8 +2975,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral return CE; } -// struct __rw_objc_super { -// struct objc_object *object; struct objc_object *superClass; +// struct __rw_objc_super { +// struct objc_object *object; struct objc_object *superClass; // }; QualType RewriteModernObjC::getSuperStructType() { if (!SuperStructDecl) { @@ -3057,9 +3057,9 @@ static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R, } void RewriteModernObjC::RewriteLineDirective(const Decl *D) { - + SourceLocation Location = D->getLocation(); - + if (Location.isFileID() && GenerateLineInfo) { std::string LineString("\n#line "); PresumedLoc PLoc = SM->getPresumedLoc(Location); @@ -3069,7 +3069,7 @@ void RewriteModernObjC::RewriteLineDirective(const Decl *D) { if (isa<ObjCMethodDecl>(D)) LineString += "\""; else LineString += "\"\n"; - + Location = D->getLocStart(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isExternC() && !FD->isMain()) { @@ -3091,11 +3091,11 @@ void RewriteModernObjC::RewriteLineDirective(const Decl *D) { /// msgSendType - function type of objc_msgSend_stret(...) /// returnType - Result type of the method being synthesized. /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type. -/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, +/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, /// starting with receiver. /// Method - Method being rewritten. Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType returnType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { @@ -3104,11 +3104,11 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla Method ? Method->isVariadic() : false); castType = Context->getPointerType(castType); - + // build type for containing the objc_msgSend_stret object. static unsigned stretCount=0; std::string name = "__Stret"; name += utostr(stretCount); - std::string str = + std::string str = "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n"; str += "namespace {\n"; str += "struct "; str += name; @@ -3127,13 +3127,13 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla Context->getPrintingPolicy()); str += ", "; str += ArgName; } - + str += ") {\n"; str += "\t unsigned size = sizeof("; str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n"; - + str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n"; - + str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { @@ -3144,11 +3144,11 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla str += ", arg"; str += utostr(i); } str+= ");\n"; - + str += "\t else if (receiver == 0)\n"; str += "\t memset((void*)&s, 0, sizeof(s));\n"; str += "\t else\n"; - + str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend_stret)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { @@ -3159,7 +3159,7 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla str += ", arg"; str += utostr(i); } str += ");\n"; - + str += "\t}\n"; str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy()); str += " s;\n"; @@ -3174,7 +3174,7 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla InsertText(FunLocStart, str); ++stretCount; - + // AST for __Stretn(receiver, args).s; IdentifierInfo *ID = &Context->Idents.get(name); FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), @@ -3266,7 +3266,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using class_getSuperclass(). @@ -3350,7 +3350,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, Context->getObjCIdType(), VK_RValue, SourceLocation())) ); // set the 'receiver'. - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); @@ -3361,7 +3361,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( @@ -3446,7 +3446,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, (void)convertBlockPointerToFunctionPointer(type); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK; - if (SubExpr->getType()->isIntegralType(*Context) && + if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) { CK = CK_IntegralToBoolean; } else if (type->isObjCObjectPointerType()) { @@ -3591,7 +3591,7 @@ QualType RewriteModernObjC::getProtocolType() { /// The forward references (and metadata) are generated in /// RewriteModernObjC::HandleTranslationUnit(). Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { - std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + + std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + Exp->getProtocol()->getNameAsString(); IdentifierInfo *ID = &Context->Idents.get(Name); VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), @@ -3608,9 +3608,9 @@ Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { return castExpr; } -/// IsTagDefinedInsideClass - This routine checks that a named tagged type -/// is defined inside an objective-c class. If so, it returns true. -bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, +/// IsTagDefinedInsideClass - This routine checks that a named tagged type +/// is defined inside an objective-c class. If so, it returns true. +bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition) { if (!IDecl) @@ -3638,13 +3638,13 @@ bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer. /// It handles elaborated types, as well as enum types in the process. -bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, +bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, std::string &Result) { if (isa<TypedefType>(Type)) { Result += "\t"; return false; } - + if (Type->isArrayType()) { QualType ElemTy = Context->getBaseElementType(Type); return RewriteObjCFieldDeclType(ElemTy, Result); @@ -3658,7 +3658,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += "\n\tunion "; else assert(false && "class not allowed as an ivar type"); - + Result += RD->getName(); if (GlobalDefinedTags.count(RD)) { // struct/union is defined globally, use it. @@ -3668,7 +3668,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += " {\n"; for (auto *FD : RD->fields()) RewriteObjCFieldDecl(FD, Result); - Result += "\t} "; + Result += "\t} "; return true; } } @@ -3682,7 +3682,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += " "; return true; } - + Result += " {\n"; for (const auto *EC : ED->enumerators()) { Result += "\t"; Result += EC->getName(); Result += " = "; @@ -3690,11 +3690,11 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += Val.toString(10); Result += ",\n"; } - Result += "\t} "; + Result += "\t} "; return true; } } - + Result += "\t"; convertObjCTypeToCStyleType(Type); return false; @@ -3703,12 +3703,12 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer. /// It handles elaborated types, as well as enum types in the process. -void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, +void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); std::string Name = fieldDecl->getNameAsString(); - - bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); + + bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); if (!EleboratedType) Type.getAsStringInternal(Name, Context->getPrintingPolicy()); Result += Name; @@ -3727,20 +3727,20 @@ void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, AT = Context->getAsArrayType(AT->getElementType()); } while (AT); } - + Result += ";\n"; } /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined /// named aggregate types into the input buffer. -void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, +void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); if (isa<TypedefType>(Type)) return; if (Type->isArrayType()) Type = Context->getBaseElementType(Type); - ObjCContainerDecl *IDecl = + ObjCContainerDecl *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext()); TagDecl *TD = nullptr; @@ -3750,11 +3750,11 @@ void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDec else if (Type->isEnumeralType()) { TD = Type->getAs<EnumType>()->getDecl(); } - + if (TD) { if (GlobalDefinedTags.count(TD)) return; - + bool IsNamedDefinition = false; if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) { RewriteObjCFieldDeclType(Type, Result); @@ -3775,7 +3775,7 @@ unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) { for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); - + for (unsigned i = 0, e = IVars.size(); i < e; i++) if (IVars[i]->isBitField()) { IvarGroupNumber[IVars[i++]] = ++GroupNo; @@ -3816,7 +3816,7 @@ QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl * std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo); if (GroupRecordType.count(tuple)) return GroupRecordType[tuple]; - + SmallVector<ObjCIvarDecl *, 8> IVars; for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { @@ -3840,7 +3840,7 @@ QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl * } QualType RetQT = GroupRecordType[tuple]; assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL"); - + return RetQT; } @@ -3895,13 +3895,13 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); - + SourceLocation LocStart = CDecl->getLocStart(); SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); - + const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); - + // If no ivars and no root or if its root, directly or indirectly, // have no ivars (thus not synthesized) then no need to synthesize this class. if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) && @@ -3910,13 +3910,13 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, ReplaceText(LocStart, endBuf-startBuf, Result); return; } - + // Insert named struct/union definitions inside class to // outer scope. This follows semantics of locally defined // struct/unions in objective-c classes. for (unsigned i = 0, e = IVars.size(); i < e; i++) RewriteLocallyDefinedNamedAggregates(IVars[i], Result); - + // Insert named structs which are syntheized to group ivar bitfields // to outer scope as well. for (unsigned i = 0, e = IVars.size(); i < e; i++) @@ -3928,17 +3928,17 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, // skip over ivar bitfields in this group. SKIP_BITFIELDS(i , e, IVars); } - + Result += "\nstruct "; Result += CDecl->getNameAsString(); Result += "_IMPL {\n"; - + if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { Result += "\tstruct "; Result += RCDecl->getNameAsString(); Result += "_IMPL "; Result += RCDecl->getNameAsString(); Result += "_IVARS;\n"; } - + for (unsigned i = 0, e = IVars.size(); i < e; i++) { if (IVars[i]->isBitField()) { ObjCIvarDecl *IV = IVars[i]; @@ -3984,7 +3984,7 @@ void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; Result += "extern \"C\" "; - if (LangOpts.MicrosoftExt && + if (LangOpts.MicrosoftExt && IvarDecl->getAccessControl() != ObjCIvarDecl::Private && IvarDecl->getAccessControl() != ObjCIvarDecl::Package) Result += "__declspec(dllimport) "; @@ -4031,14 +4031,14 @@ void RewriteModernObjC::RewriteImplementations() { } } -void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, +void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def) { - assert(BlockByRefDeclNo.count(VD) && + assert(BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"); if (def) ResultStr += "struct "; - ResultStr += "__Block_byref_" + Name + + ResultStr += "__Block_byref_" + Name + "_" + utostr(BlockByRefDeclNo[VD]) ; } @@ -4057,7 +4057,7 @@ std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, SourceLocation BlockLoc = CE->getExprLoc(); std::string S; ConvertSourceLocationToLineDirective(BlockLoc, S); - + S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" + funcName.str() + "_block_func_" + utostr(i); @@ -4132,7 +4132,7 @@ std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); - S += Name + " = __cself->" + + S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } } @@ -4168,7 +4168,7 @@ std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; - + S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); @@ -4188,7 +4188,7 @@ std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, return S; } -std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, +std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; @@ -4277,7 +4277,7 @@ std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Ta Constructor += ", "; Constructor += Name + "(_" + Name + "->__forwarding)"; } - + Constructor += " {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; @@ -4303,19 +4303,19 @@ std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Ta return S; } -std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, +std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef FunName, unsigned hasCopy) { std::string S = "\nstatic struct " + DescTag; - + S += " {\n size_t reserved;\n"; S += " size_t Block_size;\n"; if (hasCopy) { S += " void (*copy)(struct "; S += ImplTag; S += "*, struct "; S += ImplTag; S += "*);\n"; - + S += " void (*dispose)(struct "; S += ImplTag; S += "*);\n"; } @@ -4343,7 +4343,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, SC += "() {}"; InsertText(FunLocStart, SC); } - + // Insert closures that were part of the function. for (unsigned i = 0, count=0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); @@ -4368,7 +4368,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, // imported objects in the inner blocks not used in the outer // blocks must be copied/disposed in the outer block as well. - if (VD->getType()->isObjCObjectPointerType() || + if (VD->getType()->isObjCObjectPointerType() || VD->getType()->isBlockPointerType()) ImportedBlockDecls.insert(VD); } @@ -4415,7 +4415,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, } if (GlobalConstructionExp) { // extra fancy dance for global literal expression. - + // Always the latest block expression on the block stack. std::string Tag = "__"; Tag += FunName; @@ -4424,7 +4424,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, std::string globalBuf = "static "; globalBuf += Tag; globalBuf += " "; std::string SStr; - + llvm::raw_string_ostream constructorExprBuf(SStr); GlobalConstructionExp->printPretty(constructorExprBuf, nullptr, PrintingPolicy(LangOpts)); @@ -4441,7 +4441,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, } void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { - SourceLocation FunLocStart = + SourceLocation FunLocStart = (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD) : FD->getTypeSpecStartLoc(); StringRef FuncName = FD->getName(); @@ -4528,7 +4528,7 @@ bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) { } } } - + convertToUnqualifiedObjCType(T); return T != oldT; } @@ -4544,7 +4544,7 @@ QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) SmallVector<QualType, 8> ArgTypes; QualType Res = FT->getReturnType(); bool modified = convertObjCTypeToCStyleType(Res); - + if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; @@ -4569,13 +4569,13 @@ Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp CPT = DRE->getType()->getAs<BlockPointerType>(); } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { CPT = MExpr->getType()->getAs<BlockPointerType>(); - } + } else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { return SynthesizeBlockCall(Exp, PRE->getSubExpr()); } - else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) + else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) CPT = IEXPR->getType()->getAs<BlockPointerType>(); - else if (const ConditionalOperator *CEXPR = + else if (const ConditionalOperator *CEXPR = dyn_cast<ConditionalOperator>(BlockExp)) { Expr *LHSExp = CEXPR->getLHS(); Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); @@ -4676,7 +4676,7 @@ Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp // }; //} Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { - // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR + // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR // for each DeclRefExp where BYREFVAR is name of the variable. ValueDecl *VD = DeclRefExp->getDecl(); bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() || @@ -4684,7 +4684,7 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get("__forwarding"), + &Context->Idents.get("__forwarding"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -4694,7 +4694,7 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get(Name), + &Context->Idents.get(Name), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -4703,14 +4703,14 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { DeclRefExp->getType(), VK_LValue, OK_Ordinary); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), - DeclRefExp->getExprLoc(), + ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), + DeclRefExp->getExprLoc(), ME); ReplaceStmt(DeclRefExp, PE); return PE; } -// Rewrites the imported local variable V with external storage +// Rewrites the imported local variable V with external storage // (static, extern, etc.) as *V // Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { @@ -4722,7 +4722,7 @@ Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { VK_LValue, OK_Ordinary, DRE->getLocation(), false); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), + ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Exp); ReplaceStmt(DRE, PE); return PE; @@ -4771,7 +4771,7 @@ void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) { if (CastKind != CK_BlockPointerToObjCPointerCast && CastKind != CK_AnyPointerToBlockPointerCast) return; - + QualType QT = IC->getType(); (void)convertBlockPointerToFunctionPointer(QT); std::string TypeString(QT.getAsString(Context->getPrintingPolicy())); @@ -4851,7 +4851,7 @@ bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { I->getPointeeType()->isObjCQualifiedInterfaceType()) return true; } - + } return false; } @@ -4917,7 +4917,7 @@ void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { } buf += ')'; OrigLength++; - + if (PointerTypeTakesAnyBlockArguments(DeclT) || PointerTypeTakesAnyObjCQualifiedType(DeclT)) { // Replace the '^' with '*' for arguments. @@ -4930,7 +4930,7 @@ void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (*argListBegin == '^') buf += '*'; else if (*argListBegin == '<') { - buf += "/*"; + buf += "/*"; buf += *argListBegin++; OrigLength++; while (*argListBegin != '>') { @@ -4954,19 +4954,19 @@ void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, /// struct Block_byref_id_object *src) { -/// _Block_object_assign (&_dest->object, _src->object, +/// _Block_object_assign (&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_assign(&_dest->object, _src->object, +/// _Block_object_assign(&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } /// And: /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } @@ -4980,14 +4980,14 @@ std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; - + // offset into the object pointer is computed as: // void * + void* + int + int + void* + void * - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - unsigned VoidPtrSize = + unsigned VoidPtrSize = static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); - + unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); S += " _Block_object_assign((char*)dst + "; S += utostr(offset); @@ -4996,7 +4996,7 @@ std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S += "), "; S += utostr(flag); S += ");\n}\n"; - + S += "static void __Block_byref_id_object_dispose_"; S += utostr(flag); S += "(void *src) {\n"; @@ -5021,8 +5021,8 @@ std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, /// }; /// /// It then replaces declaration of ND variable with: -/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, -/// __size=sizeof(struct __Block_byref_ND), +/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, +/// __size=sizeof(struct __Block_byref_ND), /// ND=initializer-if-any}; /// /// @@ -5048,7 +5048,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, ByrefType += " *__forwarding;\n"; ByrefType += " int __flags;\n"; ByrefType += " int __size;\n"; - // Add void *__Block_byref_id_object_copy; + // Add void *__Block_byref_id_object_copy; // void *__Block_byref_id_object_dispose; if needed. QualType Ty = ND->getType(); bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); @@ -5060,7 +5060,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, QualType T = Ty; (void)convertBlockPointerToFunctionPointer(T); T.getAsStringInternal(Name, Context->getPrintingPolicy()); - + ByrefType += " " + Name + ";\n"; ByrefType += "};\n"; // Insert this type in global scope. It is needed by helper function. @@ -5072,7 +5072,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, FunLocStart = CurMethodDef->getLocStart(); } InsertText(FunLocStart, ByrefType); - + if (Ty.isObjCGCWeak()) { flag |= BLOCK_FIELD_IS_WEAK; isa = 1; @@ -5089,9 +5089,9 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, if (!HF.empty()) Preamble += HF; } - - // struct __Block_byref_ND ND = - // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), + + // struct __Block_byref_ND ND = + // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), // initializer-if-any}; bool hasInit = (ND->getInit() != nullptr); // FIXME. rewriter does not support __block c++ objects which @@ -5102,7 +5102,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, if (CXXDecl && CXXDecl->isDefaultConstructor()) hasInit = false; } - + unsigned flags = 0; if (HasCopyAndDispose) flags |= BLOCK_HAS_COPY_DISPOSE; @@ -5125,7 +5125,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, ByrefType += ", __Block_byref_id_object_dispose_"; ByrefType += utostr(flag); } - + if (!firstDecl) { // In multiple __block declarations, and for all but 1st declaration, // find location of the separating comma. This would be start location @@ -5139,7 +5139,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf); startBuf = commaBuf; } - + if (!hasInit) { ByrefType += "};\n"; unsigned nameSize = Name.size(); @@ -5164,11 +5164,11 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, const char separator = lastDecl ? ';' : ','; const char *startInitializerBuf = SM->getCharacterData(startLoc); const char *separatorBuf = strchr(startInitializerBuf, separator); - assert((*separatorBuf == separator) && + assert((*separatorBuf == separator) && "RewriteByRefVar: can't find ';' or ','"); SourceLocation separatorLoc = startLoc.getLocWithOffset(separatorBuf-startInitializerBuf); - + InsertText(separatorLoc, lastDecl ? "}" : "};\n"); } } @@ -5196,7 +5196,7 @@ void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || BlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } @@ -5213,11 +5213,11 @@ FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) { Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) { const BlockDecl *block = Exp->getBlockDecl(); - + Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); - + // Add inner imported variables now used in current block. int countOfInnerDecls = 0; if (!InnerBlockDeclRefs.empty()) { @@ -5243,12 +5243,12 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); } InnerDeclRefsCount.push_back(countOfInnerDecls); - + std::string FuncName; if (CurFunctionDef) @@ -5258,14 +5258,14 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, else if (GlobalVarDecl) FuncName = std::string(GlobalVarDecl->getNameAsString()); - bool GlobalBlockExpr = + bool GlobalBlockExpr = block->getDeclContext()->getRedeclContext()->isFileContext(); - + if (GlobalBlockExpr && !GlobalVarDecl) { Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag); GlobalBlockExpr = false; } - + std::string BlockNumber = utostr(Blocks.size()-1); std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; @@ -5279,13 +5279,13 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, // Simulate a constructor call... std::string Tag; - + if (GlobalBlockExpr) Tag = "__global_"; else Tag = "__"; Tag += FuncName + "_block_impl_" + BlockNumber; - + FD = SynthBlockInitFunctionDecl(Tag); DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue, SourceLocation()); @@ -5310,13 +5310,13 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, Context->VoidPtrTy, VK_LValue, - SourceLocation()), + SourceLocation()), UO_AddrOf, - Context->getPointerType(Context->VoidPtrTy), + Context->getPointerType(Context->VoidPtrTy), VK_RValue, OK_Ordinary, SourceLocation(), false); - InitExprs.push_back(DescRefExpr); - + InitExprs.push_back(DescRefExpr); + // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; @@ -5352,7 +5352,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, OK_Ordinary, SourceLocation(), false); } - + } InitExprs.push_back(Exp); } @@ -5363,14 +5363,14 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); - IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + sizeof("struct")); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); - + FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, SourceLocation()); @@ -5379,7 +5379,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, for (const auto &CI : block->captures()) { const VarDecl *variable = CI.getVariable(); if (variable == ND && CI.isNested()) { - assert (CI.isByRef() && + assert (CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"); isNestedCapturedVar = true; break; @@ -5399,22 +5399,22 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, if (ImportedBlockDecls.size()) { // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), + Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } NewRep = new (Context) CallExpr(*Context, DRE, InitExprs, FType, VK_LValue, SourceLocation()); - + if (GlobalBlockExpr) { assert (!GlobalConstructionExp && "SynthBlockInitExpr - GlobalConstructionExp must be null"); GlobalConstructionExp = NewRep; NewRep = DRE; } - + NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue, OK_Ordinary, SourceLocation(), false); @@ -5423,7 +5423,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, // Put Paren around the call. NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(), NewRep); - + BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByRefDeclsPtrSet.clear(); @@ -5434,7 +5434,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, } bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { - if (const ObjCForCollectionStmt * CS = + if (const ObjCForCollectionStmt * CS = dyn_cast<ObjCForCollectionStmt>(Stmts.back())) return CS->getElement() == DS; return false; @@ -5506,7 +5506,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { RewrittenBlockExprs[BE] = Str; Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); - + //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); return blockTranscribed; @@ -5520,17 +5520,17 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) return RewriteObjCStringLiteral(AtString); - + if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S)) return RewriteObjCBoolLiteralExpr(BoolLitExpr); - + if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S)) return RewriteObjCBoxedExpr(BoxedExpr); - + if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S)) return RewriteObjCArrayLiteralExpr(ArrayLitExpr); - - if (ObjCDictionaryLiteral *DictionaryLitExpr = + + if (ObjCDictionaryLiteral *DictionaryLitExpr = dyn_cast<ObjCDictionaryLiteral>(S)) return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr); @@ -5557,11 +5557,11 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { return RewriteMessageExpr(MessExpr); } - if (ObjCAutoreleasePoolStmt *StmtAutoRelease = + if (ObjCAutoreleasePoolStmt *StmtAutoRelease = dyn_cast<ObjCAutoreleasePoolStmt>(S)) { return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease); } - + if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) return RewriteObjCTryStmt(StmtTry); @@ -5595,7 +5595,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // the context of an ObjCForCollectionStmt. For example: // NSArray *someArray; // for (id <FooProtocol> index in someArray) ; - // This is because RewriteObjCForCollectionStmt() does textual rewriting + // This is because RewriteObjCForCollectionStmt() does textual rewriting // and it depends on the original text locations/positions. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); @@ -5617,7 +5617,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE)); } - else + else RewriteTypeOfDecl(VD); } } @@ -5643,13 +5643,13 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { } // Handle blocks rewriting. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { - ValueDecl *VD = DRE->getDecl(); + ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<BlocksAttr>()) return RewriteBlockDeclRefExpr(DRE); if (HasLocalVariableExternalStorage(VD)) return RewriteLocalVariableExternalStorage(DRE); } - + if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); @@ -5812,7 +5812,7 @@ void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { case Decl::CXXRecord: case Decl::Record: { RecordDecl *RD = cast<RecordDecl>(D); - if (RD->isCompleteDefinition()) + if (RD->isCompleteDefinition()) RewriteRecordBody(RD); break; } @@ -5825,7 +5825,7 @@ void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { /// Write_ProtocolExprReferencedMetadata - This routine writer out the /// protocol reference symbols in the for of: /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA. -static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, +static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, ObjCProtocolDecl *PDecl, std::string &Result) { // Also output .objc_protorefs$B section and its meta-data. @@ -5861,10 +5861,10 @@ void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { } InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false); - + if (ClassImplementation.size() || CategoryImplementation.size()) RewriteImplementations(); - + for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) { ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i]; // Write struct declaration for the class matching its ivar declarations. @@ -5873,7 +5873,7 @@ void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { // private ivars. RewriteInterfaceDecl(CDecl); } - + // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. if (const RewriteBuffer *RewriteBuf = @@ -5903,7 +5903,7 @@ void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { void RewriteModernObjC::Initialize(ASTContext &context) { InitializeCommon(context); - + Preamble += "#ifndef __OBJC2__\n"; Preamble += "#define __OBJC2__\n"; Preamble += "#endif\n"; @@ -5919,7 +5919,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) "; Preamble += ": object(o), superClass(s) {} "; Preamble += "\n};\n"; - + if (LangOpts.MicrosoftExt) { // Define all sections using syntax that makes sense. // These are currently generated. @@ -5933,13 +5933,13 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n"; - + // These need be generated for performance. Currently they are not, // using API calls instead. Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n"; - + } Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; Preamble += "typedef struct objc_object Protocol;\n"; @@ -5948,10 +5948,10 @@ void RewriteModernObjC::Initialize(ASTContext &context) { if (LangOpts.MicrosoftExt) { Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; - } + } else Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; - + Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n"; @@ -6041,7 +6041,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "#define __block\n"; Preamble += "#define __weak\n"; } - + // Declarations required for modern objective-c array and dictionary literals. Preamble += "\n#include <stdarg.h>\n"; Preamble += "struct __NSContainer_literal {\n"; @@ -6058,7 +6058,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "\tdelete[] arr;\n"; Preamble += " }\n"; Preamble += "};\n"; - + // Declaration required for implementation of @autoreleasepool statement. Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n"; Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n"; @@ -6067,7 +6067,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n"; Preamble += " void * atautoreleasepoolobj;\n"; Preamble += "};\n"; - + // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long // as this avoids warning in any 64bit/32bit compilation model. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n"; @@ -6195,20 +6195,20 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re static bool meta_data_declared = false; if (meta_data_declared) return; - + Result += "\nstruct _prop_t {\n"; Result += "\tconst char *name;\n"; Result += "\tconst char *attributes;\n"; Result += "};\n"; - + Result += "\nstruct _protocol_t;\n"; - + Result += "\nstruct _objc_method {\n"; Result += "\tstruct objc_selector * _cmd;\n"; Result += "\tconst char *method_type;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; - + Result += "\nstruct _protocol_t {\n"; Result += "\tvoid * isa; // NULL\n"; Result += "\tconst char *protocol_name;\n"; @@ -6222,7 +6222,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tconst unsigned int flags; // = 0\n"; Result += "\tconst char ** extendedMethodTypes;\n"; Result += "};\n"; - + Result += "\nstruct _ivar_t {\n"; Result += "\tunsigned long int *offset; // pointer to ivar offset location\n"; Result += "\tconst char *name;\n"; @@ -6230,7 +6230,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tunsigned int alignment;\n"; Result += "\tunsigned int size;\n"; Result += "};\n"; - + Result += "\nstruct _class_ro_t {\n"; Result += "\tunsigned int flags;\n"; Result += "\tunsigned int instanceStart;\n"; @@ -6246,7 +6246,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tconst unsigned char *weakIvarLayout;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; - + Result += "\nstruct _class_t {\n"; Result += "\tstruct _class_t *isa;\n"; Result += "\tstruct _class_t *superclass;\n"; @@ -6254,7 +6254,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tvoid *vtable;\n"; Result += "\tstruct _class_ro_t *ro;\n"; Result += "};\n"; - + Result += "\nstruct _category_t {\n"; Result += "\tconst char *name;\n"; Result += "\tstruct _class_t *cls;\n"; @@ -6263,7 +6263,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tconst struct _protocol_list_t *protocols;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; - + Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n"; Result += "#pragma warning(disable:4273)\n"; meta_data_declared = true; @@ -6316,12 +6316,12 @@ static void Write_protocol_list_initializer(ASTContext *Context, std::string &Re Result += "\nstatic "; Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size()); Result += " "; Result += VarName; - Result += ProtocolName; + Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n"; for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) { ObjCProtocolDecl *SuperPD = SuperProtocols[i]; - Result += "\t&"; Result += "_OBJC_PROTOCOL_"; + Result += "\t&"; Result += "_OBJC_PROTOCOL_"; Result += SuperPD->getNameAsString(); if (i == e-1) Result += "\n};\n"; @@ -6341,7 +6341,7 @@ static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, Result += "\nstatic "; Write_method_list_t_TypeDecl(Result, Methods.size()); Result += " "; Result += VarName; - Result += TopLevelDeclName; + Result += TopLevelDeclName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n"; Result += "\t"; Result += utostr(Methods.size()); Result += ",\n"; @@ -6381,7 +6381,7 @@ static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, Result += "\nstatic "; Write__prop_list_t_TypeDecl(Result, Properties.size()); Result += " "; Result += VarName; - Result += ProtocolName; + Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n"; Result += "\t"; Result += utostr(Properties.size()); Result += ",\n"; @@ -6413,16 +6413,16 @@ enum MetaDataDlags { CLS_ROOT = 0x2, OBJC2_CLS_HIDDEN = 0x10, CLS_EXCEPTION = 0x20, - + /// (Obsolete) ARC-specific: this class has a .release_ivars method CLS_HAS_IVAR_RELEASER = 0x40, /// class was compiled with -fobjc-arr CLS_COMPILED_BY_ARC = 0x80 // (1<<7) }; -static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, - unsigned int flags, - const std::string &InstanceStart, +static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, + unsigned int flags, + const std::string &InstanceStart, const std::string &InstanceSize, ArrayRef<ObjCMethodDecl *>baseMethods, ArrayRef<ObjCProtocolDecl *>baseProtocols, @@ -6433,8 +6433,8 @@ static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Resu Result += "\nstatic struct _class_ro_t "; Result += VarName; Result += ClassName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; - Result += "\t"; - Result += llvm::utostr(flags); Result += ", "; + Result += "\t"; + Result += llvm::utostr(flags); Result += ", "; Result += InstanceStart; Result += ", "; Result += InstanceSize; Result += ", \n"; Result += "\t"; @@ -6492,7 +6492,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, const ObjCInterfaceDecl *CDecl, bool metaclass) { bool rootClass = (!CDecl->getSuperClass()); const ObjCInterfaceDecl *RootClass = CDecl; - + if (!rootClass) { // Find the Root class RootClass = CDecl->getSuperClass(); @@ -6509,7 +6509,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; - + Result += "struct _class_t OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; @@ -6524,11 +6524,11 @@ static void Write_class_t(ASTContext *Context, std::string &Result, else Result += "__declspec(dllimport) "; - Result += "struct _class_t "; + Result += "struct _class_t "; Result += VarName; Result += SuperClass->getNameAsString(); Result += ";\n"; - + if (metaclass && RootClass != SuperClass) { Result += "extern \"C\" "; if (RootClass->getImplementation()) @@ -6536,14 +6536,14 @@ static void Write_class_t(ASTContext *Context, std::string &Result, else Result += "__declspec(dllimport) "; - Result += "struct _class_t "; + Result += "struct _class_t "; Result += VarName; Result += RootClass->getNameAsString(); Result += ";\n"; } } - - Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; + + Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n"; Result += "\t"; @@ -6557,7 +6557,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += ",\n\t"; } else { - Result += "0, // &"; Result += VarName; + Result += "0, // &"; Result += VarName; Result += CDecl->getNameAsString(); Result += ",\n\t"; Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); @@ -6565,7 +6565,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, } } else { - Result += "0, // &OBJC_METACLASS_$_"; + Result += "0, // &OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ",\n\t"; if (!rootClass) { @@ -6573,7 +6573,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += CDecl->getSuperClass()->getNameAsString(); Result += ",\n\t"; } - else + else Result += "0,\n\t"; } Result += "0, // (void *)&_objc_empty_cache,\n\t"; @@ -6584,22 +6584,22 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += "&_OBJC_CLASS_RO_$_"; Result += CDecl->getNameAsString(); Result += ",\n};\n"; - + // Add static function to initialize some of the meta-data fields. // avoid doing it twice. if (metaclass) return; - - const ObjCInterfaceDecl *SuperClass = + + const ObjCInterfaceDecl *SuperClass = rootClass ? CDecl : CDecl->getSuperClass(); - + Result += "static void OBJC_CLASS_SETUP_$_"; Result += CDecl->getNameAsString(); Result += "(void ) {\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += RootClass->getNameAsString(); Result += ";\n"; - + Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; if (rootClass) @@ -6608,26 +6608,26 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += "&OBJC_METACLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; - + Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; - + Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; - + if (!rootClass) { Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; Result += "&OBJC_CLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; } - + Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; Result += "}\n"; } -static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, +static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ObjCCategoryDecl *CatDecl, ObjCInterfaceDecl *ClassDecl, @@ -6637,7 +6637,7 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, ArrayRef<ObjCPropertyDecl *> ClassProperties) { StringRef CatName = CatDecl->getName(); StringRef ClassName = ClassDecl->getName(); - // must declare an extern class object in case this class is not implemented + // must declare an extern class object in case this class is not implemented // in this TU. Result += "\n"; Result += "extern \"C\" "; @@ -6645,11 +6645,11 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; - + Result += "struct _class_t "; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ";\n"; - + Result += "\nstatic struct _category_t "; Result += "_OBJC_$_CATEGORY_"; Result += ClassName; Result += "_$_"; Result += CatName; @@ -6659,32 +6659,32 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ",\n"; if (InstanceMethods.size() > 0) { - Result += "\t(const struct _method_list_t *)&"; + Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; - + if (ClassMethods.size() > 0) { - Result += "\t(const struct _method_list_t *)&"; + Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_CLASS_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; - + if (RefedProtocols.size() > 0) { - Result += "\t(const struct _protocol_list_t *)&"; + Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_CATEGORY_PROTOCOLS_$_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; - + if (ClassProperties.size() > 0) { Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; Result += "_$_"; Result += CatName; @@ -6692,16 +6692,16 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, } else Result += "\t0,\n"; - + Result += "};\n"; - + // Add static function to initialize the class pointer in the category structure. Result += "static void OBJC_CATEGORY_SETUP_$_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; Result += "(void ) {\n"; - Result += "\t_OBJC_$_CATEGORY_"; + Result += "\t_OBJC_$_CATEGORY_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; @@ -6716,7 +6716,7 @@ static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj StringRef ProtocolName) { if (Methods.size() == 0) return; - + Result += "\nstatic const char *"; Result += VarName; Result += ProtocolName; Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; @@ -6738,8 +6738,8 @@ static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, ASTContext *Context, - std::string &Result, - ArrayRef<ObjCIvarDecl *> Ivars, + std::string &Result, + ArrayRef<ObjCIvarDecl *> Ivars, ObjCInterfaceDecl *CDecl) { // FIXME. visibilty of offset symbols may have to be set; for Darwin // this is what happens: @@ -6751,17 +6751,17 @@ static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, else Visibility should be: DefaultVisibility; */ - + Result += "\n"; for (unsigned i =0, e = Ivars.size(); i < e; i++) { ObjCIvarDecl *IvarDecl = Ivars[i]; if (Context->getLangOpts().MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; - + if (!Context->getLangOpts().MicrosoftExt || IvarDecl->getAccessControl() == ObjCIvarDecl::Private || IvarDecl->getAccessControl() == ObjCIvarDecl::Package) - Result += "extern \"C\" unsigned long int "; + Result += "extern \"C\" unsigned long int "; else Result += "extern \"C\" __declspec(dllexport) unsigned long int "; if (Ivars[i]->isBitField()) @@ -6799,7 +6799,7 @@ static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, else Ivars.push_back(OriginalIvars[i]); } - + Result += "\nstatic "; Write__ivar_list_t_TypeDecl(Result, Ivars.size()); Result += " "; Result += VarName; @@ -6819,24 +6819,24 @@ static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += ", "; - + Result += "\""; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result); else Result += IvarDecl->getName(); Result += "\", "; - + QualType IVQT = IvarDecl->getType(); if (IvarDecl->isBitField()) IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl); - + std::string IvarTypeString, QuoteIvarTypeString; Context->getObjCEncodingForType(IVQT, IvarTypeString, IvarDecl); RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString); Result += "\""; Result += QuoteIvarTypeString; Result += "\", "; - + // FIXME. this alignment represents the host alignment and need be changed to // represent the target alignment. unsigned Align = Context->getTypeAlign(IVQT)/8; @@ -6854,21 +6854,21 @@ static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, } /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. -void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, +void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, std::string &Result) { - + // Do not synthesize the protocol more than once. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) return; WriteModernMetadataDeclarations(Context, Result); - + if (ObjCProtocolDecl *Def = PDecl->getDefinition()) PDecl = Def; // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. for (auto *I : PDecl->protocols()) RewriteObjCProtocolMetaData(I, Result); - + // Construct method lists. std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods; std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods; @@ -6879,7 +6879,7 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, InstanceMethods.push_back(MD); } } - + for (auto *MD : PDecl->class_methods()) { if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptClassMethods.push_back(MD); @@ -6902,27 +6902,27 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, "_OBJC_PROTOCOL_METHOD_TYPES_", PDecl->getNameAsString()); // Protocol's super protocol list - SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); + SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); Write_protocol_list_initializer(Context, Result, SuperProtocols, "_OBJC_PROTOCOL_REFS_", PDecl->getNameAsString()); - - Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, + + Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_PROTOCOL_INSTANCE_METHODS_", PDecl->getNameAsString(), false); - - Write_method_list_t_initializer(*this, Context, Result, ClassMethods, + + Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_PROTOCOL_CLASS_METHODS_", PDecl->getNameAsString(), false); - Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, + Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_", PDecl->getNameAsString(), false); - - Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, + + Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, "_OBJC_PROTOCOL_OPT_CLASS_METHODS_", PDecl->getNameAsString(), false); - + // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties( PDecl->instance_properties()); @@ -6947,43 +6947,43 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, else Result += "\t0,\n"; if (InstanceMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (ClassMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + if (OptInstanceMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + if (OptClassMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + if (ProtocolProperties.size() > 0) { - Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; + Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n"; Result += "\t0,\n"; - + if (AllMethods.size() > 0) { Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_"; Result += PDecl->getNameAsString(); @@ -6991,14 +6991,14 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, } else Result += "\t0\n};\n"; - + if (LangOpts.MicrosoftExt) Result += "static "; Result += "struct _protocol_t *"; Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString(); Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += ";\n"; - + // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second) llvm_unreachable("protocol already synthesized"); @@ -7019,15 +7019,15 @@ static bool hasObjCExceptionAttribute(ASTContext &Context, void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); - + // Explicitly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) - assert(false && + assert(false && "Legacy implicit interface rewriting not supported in moder abi"); - + WriteModernMetadataDeclarations(Context, Result); SmallVector<ObjCIvarDecl *, 8> IVars; - + for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. @@ -7035,14 +7035,14 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, continue; IVars.push_back(IVD); } - - Write__ivar_list_t_initializer(*this, Context, Result, IVars, + + Write__ivar_list_t_initializer(*this, Context, Result, IVars, "_OBJC_$_INSTANCE_VARIABLES_", CDecl); - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -7062,17 +7062,17 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/)) InstanceMethods.push_back(Setter); } - + Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_INSTANCE_METHODS_", IDecl->getNameAsString(), true); - + SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); - + Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CLASS_METHODS_", IDecl->getNameAsString(), true); - + // Protocols referenced in class declaration? // Protocol's super protocol list std::vector<ObjCProtocolDecl *> RefedProtocols; @@ -7085,12 +7085,12 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(*I, Result); } - - Write_protocol_list_initializer(Context, Result, + + Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CLASS_PROTOCOLS_$_", IDecl->getNameAsString()); - + // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); @@ -7098,22 +7098,22 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, /* Container */IDecl, "_OBJC_$_PROP_LIST_", CDecl->getNameAsString()); - + // Data for initializing _class_ro_t metaclass meta-data uint32_t flags = CLS_META; std::string InstanceSize; std::string InstanceStart; - + bool classIsHidden = CDecl->getVisibility() == HiddenVisibility; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; - + if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; InstanceSize = "sizeof(struct _class_t)"; InstanceStart = InstanceSize; - Write__class_ro_t_initializer(Context, Result, flags, + Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, ClassMethods, nullptr, @@ -7126,14 +7126,14 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, flags = CLS; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; - + if (hasObjCExceptionAttribute(*Context, CDecl)) flags |= CLS_EXCEPTION; if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; - + InstanceSize.clear(); InstanceStart.clear(); if (!ObjCSynthesizedStructs.count(CDecl)) { @@ -7144,15 +7144,15 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, InstanceSize = "sizeof(struct "; InstanceSize += CDecl->getNameAsString(); InstanceSize += "_IMPL)"; - + ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); if (IVD) { RewriteIvarOffsetComputation(IVD, InstanceStart); } - else + else InstanceStart = InstanceSize; } - Write__class_ro_t_initializer(Context, Result, flags, + Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, InstanceMethods, RefedProtocols, @@ -7160,15 +7160,15 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, ClassProperties, "_OBJC_CLASS_RO_$_", CDecl->getNameAsString()); - + Write_class_t(Context, Result, "OBJC_METACLASS_$_", CDecl, /*metaclass*/true); - + Write_class_t(Context, Result, "OBJC_CLASS_$_", CDecl, /*metaclass*/false); - + if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyClasses.push_back(CDecl); } @@ -7192,25 +7192,25 @@ void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) { void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); - + // For each implemented class, write out all its meta data. for (int i = 0; i < ClsDefCount; i++) RewriteObjCClassMetaData(ClassImplementation[i], Result); - + RewriteClassSetupInitHook(Result); - + // For each implemented category, write out all its meta data. for (int i = 0; i < CatDefCount; i++) RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); - + RewriteCategorySetupInitHook(Result); - + if (ClsDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_classlist$B\")) "; Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ ["; Result += llvm::utostr(ClsDefCount); Result += "]"; - Result += + Result += " __attribute__((used, section (\"__DATA, __objc_classlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < ClsDefCount; i++) { @@ -7219,7 +7219,7 @@ void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { Result += ",\n"; } Result += "};\n"; - + if (!DefinedNonLazyClasses.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n"; @@ -7231,34 +7231,34 @@ void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { Result += "};\n"; } } - + if (CatDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_catlist$B\")) "; Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ ["; Result += llvm::utostr(CatDefCount); Result += "]"; - Result += + Result += " __attribute__((used, section (\"__DATA, __objc_catlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < CatDefCount; i++) { Result += "\t&_OBJC_$_CATEGORY_"; - Result += - CategoryImplementation[i]->getClassInterface()->getNameAsString(); + Result += + CategoryImplementation[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += CategoryImplementation[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } - + if (!DefinedNonLazyCategories.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n"; Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t"; for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) { Result += "\t&_OBJC_$_CATEGORY_"; - Result += - DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); + Result += + DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += DefinedNonLazyCategories[i]->getNameAsString(); Result += ",\n"; @@ -7270,7 +7270,7 @@ void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { void RewriteModernObjC::WriteImageInfo(std::string &Result) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n"; - + Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } "; // version 0, ObjCABI is 2 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n"; @@ -7285,14 +7285,14 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, // Find category declaration for this implementation. ObjCCategoryDecl *CDecl = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); - + std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += "_$_"; FullCategoryName += CDecl->getNameAsString(); - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -7310,17 +7310,17 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) InstanceMethods.push_back(Setter); } - + Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_CATEGORY_INSTANCE_METHODS_", FullCategoryName, true); - + SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); - + Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CATEGORY_CLASS_METHODS_", FullCategoryName, true); - + // Protocols referenced in class declaration? // Protocol's super protocol list SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols()); @@ -7328,12 +7328,12 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(I, Result); - - Write_protocol_list_initializer(Context, Result, + + Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CATEGORY_PROTOCOLS_$_", FullCategoryName); - + // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); @@ -7341,7 +7341,7 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, /* Container */IDecl, "_OBJC_$_PROP_LIST_", FullCategoryName); - + Write_category_t(*this, Context, Result, CDecl, ClassDecl, @@ -7349,7 +7349,7 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, ClassMethods, RefedProtocols, ClassProperties); - + // Determine if this category is also "non-lazy". if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyCategories.push_back(CDecl); @@ -7385,7 +7385,7 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, StringRef ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; - + if (!objc_impl_method) { /* struct _objc_method { SEL _cmd; @@ -7398,12 +7398,12 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, Result += "\tchar *method_types;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; - + objc_impl_method = true; } - + // Build _objc_method_list for class's methods if needed - + /* struct { struct _objc_method_list *next_method; int method_count; @@ -7432,7 +7432,7 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, Result += IsInstanceMethod ? "inst" : "cls"; Result += "_meth\")))= "; Result += "{\n\t0, " + utostr(NumMethods) + "\n"; - + Result += "\t,{{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString().c_str(); std::string MethodTypeString; @@ -7459,18 +7459,18 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceRange OldRange = IV->getSourceRange(); Expr *BaseExpr = IV->getBase(); - + // Rewrite the base, but without actually doing replaces. { DisableReplaceStmtScope S(*this); BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); IV->setBase(BaseExpr); } - + ObjCIvarDecl *D = IV->getDecl(); - + Expr *Replacement = IV; - + if (BaseExpr->getType()->isObjCObjectPointerType()) { const ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); @@ -7480,18 +7480,18 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); - + // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(clsDeclared, D, IvarOffsetName); - + ReferencedIvars[clsDeclared].insert(D); - + // cast offset to "char *". - CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, + CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->CharTy), CK_BitCast, BaseExpr); @@ -7502,8 +7502,8 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, Context->UnsignedLongTy, VK_LValue, SourceLocation()); - BinaryOperator *addExpr = - new (Context) BinaryOperator(castExpr, DRE, BO_Add, + BinaryOperator *addExpr = + new (Context) BinaryOperator(castExpr, DRE, BO_Add, Context->getPointerType(Context->CharTy), VK_RValue, OK_Ordinary, SourceLocation(), FPOptions()); // Don't forget the parens to enforce the proper binding. @@ -7519,7 +7519,7 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * - ObjCContainerDecl *CDecl = + ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) @@ -7530,7 +7530,7 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), @@ -7552,20 +7552,20 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { } convertObjCTypeToCStyleType(IvarT); QualType castT = Context->getPointerType(IvarT); - - castExpr = NoTypeInfoCStyleCastExpr(Context, + + castExpr = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, PE); - - + + Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT, VK_LValue, OK_Ordinary, SourceLocation(), false); PE = new (Context) ParenExpr(OldRange.getBegin(), OldRange.getEnd(), Exp); - + if (D->isBitField()) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -7582,9 +7582,9 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { else Replacement = PE; } - + ReplaceStmtWithRange(IV, Replacement, OldRange); - return Replacement; + return Replacement; } #endif // CLANG_ENABLE_OBJC_REWRITER diff --git a/lib/Frontend/Rewrite/RewriteObjC.cpp b/lib/Frontend/Rewrite/RewriteObjC.cpp index 9938f89eb8692..6229351e8f542 100644 --- a/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -42,7 +42,7 @@ namespace { BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), block, ... */ BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ - BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the + BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the __block variable */ BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy helpers */ @@ -50,7 +50,7 @@ namespace { support routines */ BLOCK_BYREF_CURRENT_MAX = 256 }; - + enum { BLOCK_NEEDS_FREE = (1 << 24), BLOCK_HAS_COPY_DISPOSE = (1 << 25), @@ -60,7 +60,7 @@ namespace { BLOCK_HAS_DESCRIPTOR = (1 << 29) }; static const int OBJC_ABI_VERSION = 7; - + Rewriter Rewrite; DiagnosticsEngine &Diags; const LangOptions &LangOpts; @@ -74,7 +74,7 @@ namespace { std::string InFileName; std::unique_ptr<raw_ostream> OutFile; std::string Preamble; - + TypeDecl *ProtocolTypeDecl; VarDecl *GlobalVarDecl; unsigned RewriteFailedDiag; @@ -85,13 +85,13 @@ namespace { // ObjC foreach break/continue generation support. int BcLabelCount; - + unsigned TryFinallyContainsReturnDiag; // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; - + FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; @@ -117,14 +117,14 @@ namespace { SmallVector<int, 8> ObjCBcLabelNo; // Remember all the @protocol(<expr>) expressions. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; - + llvm::DenseSet<uint64_t> CopyDestroyCache; // Block expressions. SmallVector<BlockExpr *, 32> Blocks; SmallVector<int, 32> InnerDeclRefsCount; SmallVector<DeclRefExpr *, 32> InnerDeclRefs; - + SmallVector<DeclRefExpr *, 32> BlockDeclRefs; // Block related declarations. @@ -135,7 +135,7 @@ namespace { llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; - + llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; // This maps an original source AST to it's rewritten form. This allows @@ -147,12 +147,12 @@ namespace { bool IsHeader; bool SilenceRewriteMacroWarning; bool objc_impl_method; - + bool DisableReplaceStmt; class DisableReplaceStmtScope { RewriteObjC &R; bool SavedValue; - + public: DisableReplaceStmtScope(RewriteObjC &R) : R(R), SavedValue(R.DisableReplaceStmt) { @@ -262,7 +262,7 @@ namespace { void RewriteInclude(); void RewriteForwardClassDecl(DeclGroupRef D); void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); - void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, + void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString); void RewriteImplementations(); void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -289,7 +289,7 @@ namespace { void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); void RewriteTypeOfDecl(VarDecl *VD); void RewriteObjCQualifiedInterfaceTypes(Expr *E); - + // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); @@ -309,17 +309,17 @@ namespace { Stmt *RewriteBreakStmt(BreakStmt *S); Stmt *RewriteContinueStmt(ContinueStmt *S); void RewriteCastExpr(CStyleCastExpr *CE); - + // Block rewriting. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); - + // Block specific rewrite rules. void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteByRefVar(VarDecl *VD); Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); - + void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); @@ -339,12 +339,12 @@ namespace { std::string &Result) = 0; virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) = 0; - + // Rewriting ivar access virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0; virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result) = 0; - + // Misc. AST transformation routines. Sometimes they end up calling // rewriting routines on the new ASTs. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, @@ -352,15 +352,15 @@ namespace { SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType msgSendType, - QualType returnType, + QualType msgSendType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method); Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); - + void SynthCountByEnumWithState(std::string &buf); void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); @@ -372,15 +372,15 @@ namespace { void SynthGetSuperClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperConstructorFunctionDecl(); - + std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag); - std::string SynthesizeBlockImpl(BlockExpr *CE, + std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc); - std::string SynthesizeBlockDescriptor(std::string DescTag, + std::string SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef funcName, unsigned hasCopy); @@ -423,13 +423,13 @@ namespace { } return false; } - + bool needToScanForQualifiers(QualType T); QualType getSuperStructType(); QualType getConstantStringStructType(); QualType convertFunctionTypeOfBlocks(const FunctionType *FT); bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); - + void convertToUnqualifiedObjCType(QualType &T) { if (T->isObjCQualifiedIdType()) T = Context->getObjCIdType(); @@ -445,7 +445,7 @@ namespace { } } } - + // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) @@ -468,7 +468,7 @@ namespace { bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); - + void QuoteDoublequotes(std::string &From, std::string &To) { for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') @@ -504,7 +504,7 @@ namespace { /*Pascal=*/false, StrType, SourceLocation()); } }; - + class RewriteObjCFragileABI : public RewriteObjC { public: RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS, @@ -688,7 +688,7 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardClassDecl(DG); @@ -707,14 +707,14 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardProtocolDecl(DG); continue; } } - + HandleTopLevelSingleDecl(*DI); ++DI; } @@ -790,7 +790,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, unsigned Attributes = PD->getPropertyAttributes(); if (!PD->getGetterMethodDecl()->isDefined()) { bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && - (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy)); std::string Getr; if (GenGetProperty && !objcGetPropertyDefined) { @@ -799,7 +799,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr = "\nextern \"C\" __declspec(dllimport) " "id objc_getProperty(id, SEL, long, bool);\n"; } - RewriteObjCMethodDecl(OID->getContainingInterface(), + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. @@ -813,7 +813,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += " _TYPE"; if (FPRetType) { Getr += ")"; // close the precedence "scope" for "*". - + // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ Getr += "("; @@ -843,13 +843,13 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += "; }"; InsertText(onePastSemiLoc, Getr); } - + if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined()) return; // Generate the 'setter' function. std::string Setr; - bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy); if (GenSetProperty && !objcSetPropertyDefined) { objcSetPropertyDefined = true; @@ -857,8 +857,8 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Setr = "\nextern \"C\" __declspec(dllimport) " "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; } - - RewriteObjCMethodDecl(OID->getContainingInterface(), + + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. @@ -903,9 +903,9 @@ void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString) { SourceLocation startLoc = ClassDecl->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - const char *semiPtr = strchr(startBuf, ';'); + const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. - ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); + ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); } void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) { @@ -971,21 +971,21 @@ void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { ReplaceText(LocStart, 0, "// "); for (auto *I : CatDecl->instance_properties()) - RewriteProperty(I); + RewriteProperty(I); for (auto *I : CatDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : CatDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(CatDecl->getAtEndRange().getBegin(), + ReplaceText(CatDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */"); } void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation LocStart = PDecl->getLocStart(); assert(PDecl->isThisDeclarationADefinition()); - + // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); @@ -995,7 +995,7 @@ void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { RewriteMethodDeclaration(I); for (auto *I : PDecl->instance_properties()) RewriteProperty(I); - + // Lastly, comment out the @end. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); ReplaceText(LocEnd, strlen("@end"), "/* @end */"); @@ -1025,7 +1025,7 @@ void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { ReplaceText(LocStart, 0, "// "); } -void +void RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { SourceLocation LocStart = DG[0]->getLocStart(); if (LocStart.isInvalid()) @@ -1220,7 +1220,7 @@ void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), + ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */"); } @@ -1677,7 +1677,7 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { buf += "}\n"; buf += "{ /* implicit finally clause */\n"; buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; - + std::string syncBuf; syncBuf += " objc_sync_exit("; @@ -1695,7 +1695,7 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts)); syncBuf += syncExprBuf.str(); syncBuf += ");"; - + buf += syncBuf; buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n"; buf += "}\n"; @@ -1724,8 +1724,8 @@ void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S) } } -void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) -{ +void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) +{ // Perform a bottom up traversal of all children. for (Stmt *SubStmt : S->children()) if (SubStmt) @@ -1750,7 +1750,7 @@ void RewriteObjC::RewriteTryReturnStmts(Stmt *S) { std::string buf; buf = "{ objc_exception_try_exit(&_stack); return"; - + ReplaceText(startLoc, 6, buf); InsertText(onePastSemiLoc, "}"); } @@ -1774,7 +1774,7 @@ void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { buf = "{ objc_exception_try_exit(&_stack);"; buf += syncExitBuf; buf += " return"; - + ReplaceText(startLoc, 6, buf); InsertText(onePastSemiLoc, "}"); } @@ -1930,7 +1930,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf += " if (_rethrow) objc_exception_throw(_rethrow);\n"; buf += "}"; ReplaceText(lastCurlyLoc, 1, buf); - + // Now check for any return/continue/go statements within the @try. // The implicit finally clause won't called if the @try contains any // jump statements. @@ -2446,7 +2446,7 @@ void RewriteObjC::SynthGetClassFunctionDecl() { // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); void RewriteObjC::SynthGetSuperClassFunctionDecl() { - IdentifierInfo *getSuperClassIdent = + IdentifierInfo *getSuperClassIdent = &Context->Idents.get("class_getSuperclass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getObjCClassType()); @@ -2583,8 +2583,8 @@ QualType RewriteObjC::getConstantStringStructType() { } CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType msgSendType, - QualType returnType, + QualType msgSendType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { @@ -2603,10 +2603,10 @@ CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavo castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *STCE = new (Context) CallExpr( *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation()); @@ -2764,7 +2764,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, Context->getObjCIdType(), VK_RValue, SourceLocation())) ); // set the 'receiver'. - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); @@ -2778,7 +2778,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ClsExprs.push_back(ArgExpr); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( @@ -2863,7 +2863,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, (void)convertBlockPointerToFunctionPointer(type); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK; - if (SubExpr->getType()->isIntegralType(*Context) && + if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) { CK = CK_IntegralToBoolean; } else if (type->isObjCObjectPointerType()) { @@ -2968,9 +2968,9 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, // call to objc_msgSend_stret and hang both varieties on a conditional // expression which dictate which one to envoke depending on size of // method's return type. - - CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, - msgSendType, returnType, + + CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, + msgSendType, returnType, ArgTypes, MsgExprs, Exp->getMethodDecl()); @@ -2990,7 +2990,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, llvm::APInt(IntSize, 8), Context->IntTy, SourceLocation()); - BinaryOperator *lessThanExpr = + BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy, VK_RValue, OK_Ordinary, SourceLocation(), FPOptions()); @@ -3000,7 +3000,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation(), CE, SourceLocation(), STCE, returnType, VK_RValue, OK_Ordinary); - ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), + ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr); } // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. @@ -3232,14 +3232,14 @@ void RewriteObjC::RewriteImplementations() { RewriteImplementationDecl(CategoryImplementation[i]); } -void RewriteObjC::RewriteByRefString(std::string &ResultStr, +void RewriteObjC::RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def) { - assert(BlockByRefDeclNo.count(VD) && + assert(BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"); if (def) ResultStr += "struct "; - ResultStr += "__Block_byref_" + Name + + ResultStr += "__Block_byref_" + Name + "_" + utostr(BlockByRefDeclNo[VD]) ; } @@ -3329,7 +3329,7 @@ std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); - S += Name + " = __cself->" + + S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } } @@ -3365,7 +3365,7 @@ std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; - + S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); @@ -3385,7 +3385,7 @@ std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, return S; } -std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, +std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; @@ -3474,7 +3474,7 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, Constructor += ", "; Constructor += Name + "(_" + Name + "->__forwarding)"; } - + Constructor += " {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; @@ -3500,19 +3500,19 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, return S; } -std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, +std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef FunName, unsigned hasCopy) { std::string S = "\nstatic struct " + DescTag; - + S += " {\n unsigned long reserved;\n"; S += " unsigned long Block_size;\n"; if (hasCopy) { S += " void (*copy)(struct "; S += ImplTag; S += "*, struct "; S += ImplTag; S += "*);\n"; - + S += " void (*dispose)(struct "; S += ImplTag; S += "*);\n"; } @@ -3543,7 +3543,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, SC += "() {}"; InsertText(FunLocStart, SC); } - + // Insert closures that were part of the function. for (unsigned i = 0, count=0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); @@ -3564,7 +3564,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, // imported objects in the inner blocks not used in the outer // blocks must be copied/disposed in the outer block as well. if (VD->hasAttr<BlocksAttr>() || - VD->getType()->isObjCObjectPointerType() || + VD->getType()->isObjCObjectPointerType() || VD->getType()->isBlockPointerType()) ImportedBlockDecls.insert(VD); } @@ -3609,7 +3609,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, SC += "restrict "; InsertText(FunLocStart, SC); } - + Blocks.clear(); InnerDeclRefsCount.clear(); InnerDeclRefs.clear(); @@ -3697,7 +3697,7 @@ QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) { SmallVector<QualType, 8> ArgTypes; QualType Res = FT->getReturnType(); bool HasBlockType = convertBlockPointerToFunctionPointer(Res); - + if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; @@ -3724,13 +3724,13 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { CPT = DRE->getType()->getAs<BlockPointerType>(); } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { CPT = MExpr->getType()->getAs<BlockPointerType>(); - } + } else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { return SynthesizeBlockCall(Exp, PRE->getSubExpr()); } - else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) + else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) CPT = IEXPR->getType()->getAs<BlockPointerType>(); - else if (const ConditionalOperator *CEXPR = + else if (const ConditionalOperator *CEXPR = dyn_cast<ConditionalOperator>(BlockExp)) { Expr *LHSExp = CEXPR->getLHS(); Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); @@ -3831,7 +3831,7 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { // }; //} Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { - // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR + // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR // for each DeclRefExp where BYREFVAR is name of the variable. ValueDecl *VD = DeclRefExp->getDecl(); bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() || @@ -3839,7 +3839,7 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get("__forwarding"), + &Context->Idents.get("__forwarding"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -3849,7 +3849,7 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get(Name), + &Context->Idents.get(Name), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -3858,14 +3858,14 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { DeclRefExp->getType(), VK_LValue, OK_Ordinary); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), - DeclRefExp->getExprLoc(), + ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), + DeclRefExp->getExprLoc(), ME); ReplaceStmt(DeclRefExp, PE); return PE; } -// Rewrites the imported local variable V with external storage +// Rewrites the imported local variable V with external storage // (static, extern, etc.) as *V // Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { @@ -3877,7 +3877,7 @@ Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { VK_LValue, OK_Ordinary, DRE->getLocation(), false); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), + ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Exp); ReplaceStmt(DRE, PE); return PE; @@ -3991,7 +3991,7 @@ bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { I->getPointeeType()->isObjCQualifiedInterfaceType()) return true; } - + } return false; } @@ -4057,7 +4057,7 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { } buf += ')'; OrigLength++; - + if (PointerTypeTakesAnyBlockArguments(DeclT) || PointerTypeTakesAnyObjCQualifiedType(DeclT)) { // Replace the '^' with '*' for arguments. @@ -4070,7 +4070,7 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (*argListBegin == '^') buf += '*'; else if (*argListBegin == '<') { - buf += "/*"; + buf += "/*"; buf += *argListBegin++; OrigLength++; while (*argListBegin != '>') { @@ -4094,19 +4094,19 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, /// struct Block_byref_id_object *src) { -/// _Block_object_assign (&_dest->object, _src->object, +/// _Block_object_assign (&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_assign(&_dest->object, _src->object, +/// _Block_object_assign(&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } /// And: /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } @@ -4120,14 +4120,14 @@ std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; - + // offset into the object pointer is computed as: // void * + void* + int + int + void* + void * - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - unsigned VoidPtrSize = + unsigned VoidPtrSize = static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); - + unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); S += " _Block_object_assign((char*)dst + "; S += utostr(offset); @@ -4136,7 +4136,7 @@ std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S += "), "; S += utostr(flag); S += ");\n}\n"; - + S += "static void __Block_byref_id_object_dispose_"; S += utostr(flag); S += "(void *src) {\n"; @@ -4161,8 +4161,8 @@ std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, /// }; /// /// It then replaces declaration of ND variable with: -/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, -/// __size=sizeof(struct __Block_byref_ND), +/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, +/// __size=sizeof(struct __Block_byref_ND), /// ND=initializer-if-any}; /// /// @@ -4191,7 +4191,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { ByrefType += " *__forwarding;\n"; ByrefType += " int __flags;\n"; ByrefType += " int __size;\n"; - // Add void *__Block_byref_id_object_copy; + // Add void *__Block_byref_id_object_copy; // void *__Block_byref_id_object_dispose; if needed. QualType Ty = ND->getType(); bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); @@ -4203,7 +4203,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { QualType T = Ty; (void)convertBlockPointerToFunctionPointer(T); T.getAsStringInternal(Name, Context->getPrintingPolicy()); - + ByrefType += " " + Name + ";\n"; ByrefType += "};\n"; // Insert this type in global scope. It is needed by helper function. @@ -4219,7 +4219,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { flag |= BLOCK_FIELD_IS_WEAK; isa = 1; } - + if (HasCopyAndDispose) { flag = BLOCK_BYREF_CALLER; QualType Ty = ND->getType(); @@ -4232,9 +4232,9 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { if (!HF.empty()) InsertText(FunLocStart, HF); } - - // struct __Block_byref_ND ND = - // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), + + // struct __Block_byref_ND ND = + // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), // initializer-if-any}; bool hasInit = (ND->getInit() != nullptr); unsigned flags = 0; @@ -4294,13 +4294,13 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { ByrefType += ", "; } ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); - + // Complete the newly synthesized compound expression by inserting a right // curly brace before the end of the declaration. // FIXME: This approach avoids rewriting the initializer expression. It // also assumes there is only one declarator. For example, the following // isn't currently supported by this routine (in general): - // + // // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37; // const char *startInitializerBuf = SM->getCharacterData(startLoc); @@ -4336,7 +4336,7 @@ void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || BlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } @@ -4356,7 +4356,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); - + // Add inner imported variables now used in current block. int countOfInnerDecls = 0; if (!InnerBlockDeclRefs.empty()) { @@ -4382,12 +4382,12 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); } InnerDeclRefsCount.push_back(countOfInnerDecls); - + std::string FuncName; if (CurFunctionDef) @@ -4434,13 +4434,13 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, Context->VoidPtrTy, VK_LValue, - SourceLocation()), + SourceLocation()), UO_AddrOf, - Context->getPointerType(Context->VoidPtrTy), + Context->getPointerType(Context->VoidPtrTy), VK_RValue, OK_Ordinary, SourceLocation(), false); - InitExprs.push_back(DescRefExpr); - + InitExprs.push_back(DescRefExpr); + // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; @@ -4486,14 +4486,14 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); - IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + sizeof("struct")); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); - + FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, SourceLocation()); @@ -4502,7 +4502,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, for (const auto &CI : block->captures()) { const VarDecl *variable = CI.getVariable(); if (variable == ND && CI.isNested()) { - assert (CI.isByRef() && + assert (CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"); isNestedCapturedVar = true; break; @@ -4521,9 +4521,9 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, if (ImportedBlockDecls.size()) { // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), + Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } @@ -4544,7 +4544,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, } bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { - if (const ObjCForCollectionStmt * CS = + if (const ObjCForCollectionStmt * CS = dyn_cast<ObjCForCollectionStmt>(Stmts.back())) return CS->getElement() == DS; return false; @@ -4614,7 +4614,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { RewrittenBlockExprs[BE] = Str; Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); - + //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); return blockTranscribed; @@ -4685,7 +4685,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // the context of an ObjCForCollectionStmt. For example: // NSArray *someArray; // for (id <FooProtocol> index in someArray) ; - // This is because RewriteObjCForCollectionStmt() does textual rewriting + // This is because RewriteObjCForCollectionStmt() does textual rewriting // and it depends on the original text locations/positions. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); @@ -4705,7 +4705,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; RewriteByRefVar(VD); } - else + else RewriteTypeOfDecl(VD); } } @@ -4731,13 +4731,13 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { } // Handle blocks rewriting. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { - ValueDecl *VD = DRE->getDecl(); + ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<BlocksAttr>()) return RewriteBlockDeclRefExpr(DRE); if (HasLocalVariableExternalStorage(VD)) return RewriteLocalVariableExternalStorage(DRE); } - + if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); @@ -4894,7 +4894,7 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { case Decl::CXXRecord: case Decl::Record: { RecordDecl *RD = cast<RecordDecl>(D); - if (RD->isCompleteDefinition()) + if (RD->isCompleteDefinition()) RewriteRecordBody(RD); break; } @@ -4942,7 +4942,7 @@ void RewriteObjC::HandleTranslationUnit(ASTContext &C) { void RewriteObjCFragileABI::Initialize(ASTContext &context) { InitializeCommon(context); - + // declaring objc_selector outside the parameter list removes a silly // scope related warning... if (IsHeader) @@ -5079,7 +5079,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( ObjCProtocolDecl *PDecl, StringRef prefix, StringRef ClassName, std::string &Result) { static bool objc_protocol_methods = false; - + // Output struct protocol_methods holder of method selector and type. if (!objc_protocol_methods && PDecl->hasDefinition()) { /* struct protocol_methods { @@ -5091,16 +5091,16 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( Result += "\tstruct objc_selector *_cmd;\n"; Result += "\tchar *method_types;\n"; Result += "};\n"; - + objc_protocol_methods = true; } // Do not synthesize the protocol more than once. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) return; - + if (ObjCProtocolDecl *Def = PDecl->getDefinition()) PDecl = Def; - + if (PDecl->instmeth_begin() != PDecl->instmeth_end()) { unsigned NumMethods = std::distance(PDecl->instmeth_begin(), PDecl->instmeth_end()); @@ -5117,7 +5117,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( Result += PDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= " "{\n\t" + utostr(NumMethods) + "\n"; - + // Output instance methods declared in this protocol. for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); @@ -5134,7 +5134,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( } Result += "\t }\n};\n"; } - + // Output class methods declared in this protocol. unsigned NumMethods = std::distance(PDecl->classmeth_begin(), PDecl->classmeth_end()); @@ -5154,7 +5154,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( "{\n\t"; Result += utostr(NumMethods); Result += "\n"; - + // Output instance methods declared in this protocol. for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); @@ -5171,7 +5171,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( } Result += "\t }\n};\n"; } - + // Output: /* struct _objc_protocol { // Objective-C 1.0 extensions @@ -5191,10 +5191,10 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( Result += "\tstruct _objc_protocol_method_list *instance_methods;\n"; Result += "\tstruct _objc_protocol_method_list *class_methods;\n"; Result += "};\n"; - + objc_protocol = true; } - + Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= " @@ -5216,7 +5216,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( else Result += "0\n"; Result += "};\n"; - + // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second) llvm_unreachable("protocol already synthesized"); @@ -5227,10 +5227,10 @@ void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData( StringRef prefix, StringRef ClassName, std::string &Result) { if (Protocols.empty()) return; - + for (unsigned i = 0; i != Protocols.size(); i++) RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result); - + // Output the top lovel protocol meta-data for the class. /* struct _objc_protocol_list { struct _objc_protocol_list *next; @@ -5251,11 +5251,11 @@ void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData( "{\n\t0, "; Result += utostr(Protocols.size()); Result += "\n"; - + Result += "\t,{&_OBJC_PROTOCOL_"; Result += Protocols[0]->getNameAsString(); Result += " \n"; - + for (unsigned i = 1; i != Protocols.size(); i++) { Result += "\t ,&_OBJC_PROTOCOL_"; Result += Protocols[i]->getNameAsString(); @@ -5267,14 +5267,14 @@ void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData( void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); - + // Explicitly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) { // FIXME: Implementation of a class with no @interface (legacy) does not // produce correct synthesis as yet. RewriteObjCInternalStruct(CDecl, Result); } - + // Build _objc_ivar_list metadata for classes ivars if needed unsigned NumIvars = !IDecl->ivar_empty() ? IDecl->ivar_size() @@ -5293,10 +5293,10 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe Result += "\tchar *ivar_type;\n"; Result += "\tint ivar_offset;\n"; Result += "};\n"; - + objc_ivar = true; } - + /* struct { int ivar_count; struct _objc_ivar ivar_list[nIvars]; @@ -5312,7 +5312,7 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe "{\n\t"; Result += utostr(NumIvars); Result += "\n"; - + ObjCInterfaceDecl::ivar_iterator IVI, IVE; SmallVector<ObjCIvarDecl *, 8> IVars; if (!IDecl->ivar_empty()) { @@ -5346,13 +5346,13 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe RewriteIvarOffsetComputation(*IVI, Result); Result += "}\n"; } - + Result += "\t }\n};\n"; } - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -5374,15 +5374,15 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe } RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), true, "", IDecl->getName(), Result); - + // Build _objc_method_list for class's class methods if needed RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), false, "", IDecl->getName(), Result); - + // Protocols referenced in class declaration? RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CLASS", CDecl->getName(), Result); - + // Declaration of class/meta-class metadata /* struct _objc_class { struct _objc_class *isa; // or const char *root_class_name when metadata @@ -5417,7 +5417,7 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe Result += "};\n"; objc_class = true; } - + // Meta-class metadata generation. ObjCInterfaceDecl *RootClass = nullptr; ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); @@ -5426,14 +5426,14 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe SuperClass = SuperClass->getSuperClass(); } SuperClass = CDecl->getSuperClass(); - + Result += "\nstatic struct _objc_class _OBJC_METACLASS_"; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= " "{\n\t(struct _objc_class *)\""; Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString()); Result += "\""; - + if (SuperClass) { Result += ", \""; Result += SuperClass->getNameAsString(); @@ -5464,7 +5464,7 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe else Result += "\t,0,0,0,0\n"; Result += "};\n"; - + // class metadata generation. Result += "\nstatic struct _objc_class _OBJC_CLASS_"; Result += CDecl->getNameAsString(); @@ -5522,15 +5522,15 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); - + // For each implemented class, write out all its meta data. for (int i = 0; i < ClsDefCount; i++) RewriteObjCClassMetaData(ClassImplementation[i], Result); - + // For each implemented category, write out all its meta data. for (int i = 0; i < CatDefCount; i++) RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); - + // Write objc_symtab metadata /* struct _objc_symtab @@ -5542,7 +5542,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { void *defs[cls_def_cnt + cat_def_cnt]; }; */ - + Result += "\nstruct _objc_symtab {\n"; Result += "\tlong sel_ref_cnt;\n"; Result += "\tSEL *refs;\n"; @@ -5550,7 +5550,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += "\tshort cat_def_cnt;\n"; Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n"; Result += "};\n\n"; - + Result += "static struct _objc_symtab " "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n"; Result += "\t0, 0, " + utostr(ClsDefCount) @@ -5560,7 +5560,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += ClassImplementation[i]->getNameAsString(); Result += "\n"; } - + for (int i = 0; i < CatDefCount; i++) { Result += "\t,&_OBJC_CATEGORY_"; Result += CategoryImplementation[i]->getClassInterface()->getNameAsString(); @@ -5568,11 +5568,11 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += CategoryImplementation[i]->getNameAsString(); Result += "\n"; } - + Result += "};\n\n"; - + // Write objc_module metadata - + /* struct _objc_module { long version; @@ -5581,7 +5581,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { struct _objc_symtab *symtab; } */ - + Result += "\nstruct _objc_module {\n"; Result += "\tlong version;\n"; Result += "\tlong size;\n"; @@ -5593,7 +5593,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += "\t" + utostr(OBJC_ABI_VERSION) + ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n"; Result += "};\n\n"; - + if (LangOpts.MicrosoftExt) { if (ProtocolExprDecls.size()) { Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n"; @@ -5623,14 +5623,14 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID // Find category declaration for this implementation. ObjCCategoryDecl *CDecl = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); - + std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += '_'; FullCategoryName += IDecl->getNameAsString(); - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -5672,7 +5672,7 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID // @property decl. }; */ - + static bool objc_category = false; if (!objc_category) { Result += "\nstruct _objc_category {\n"; @@ -5693,7 +5693,7 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID Result += "\"\n\t, \""; Result += ClassDecl->getNameAsString(); Result += "\"\n"; - + if (IDecl->instmeth_begin() != IDecl->instmeth_end()) { Result += "\t, (struct _objc_method_list *)" "&_OBJC_CATEGORY_INSTANCE_METHODS_"; @@ -5710,7 +5710,7 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID } else Result += "\t, 0\n"; - + if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) { Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_"; Result += FullCategoryName; @@ -5731,7 +5731,7 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi StringRef ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; - + if (!objc_impl_method) { /* struct _objc_method { SEL _cmd; @@ -5744,12 +5744,12 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi Result += "\tchar *method_types;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; - + objc_impl_method = true; } - + // Build _objc_method_list for class's methods if needed - + /* struct { struct _objc_method_list *next_method; int method_count; @@ -5771,7 +5771,7 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi Result += IsInstanceMethod ? "inst" : "cls"; Result += "_meth\")))= "; Result += "{\n\t0, " + utostr(NumMethods) + "\n"; - + Result += "\t,{{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString(); std::string MethodTypeString = @@ -5798,16 +5798,16 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceRange OldRange = IV->getSourceRange(); Expr *BaseExpr = IV->getBase(); - + // Rewrite the base, but without actually doing replaces. { DisableReplaceStmtScope S(*this); BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); IV->setBase(BaseExpr); } - + ObjCIvarDecl *D = IV->getDecl(); - + Expr *Replacement = IV; if (CurMethodDef) { if (BaseExpr->getType()->isObjCObjectPointerType()) { @@ -5819,7 +5819,7 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); - + // Synthesize an explicit cast to gain access to the ivar. std::string RecName = clsDeclared->getIdentifier()->getName(); RecName += "_IMPL"; @@ -5848,7 +5848,7 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { } } else { // we are outside a method. assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method"); - + // Explicit ivar refs need to have a cast inserted. // FIXME: consider sharing some of this code with the code above. if (BaseExpr->getType()->isObjCObjectPointerType()) { @@ -5859,7 +5859,7 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); - + // Synthesize an explicit cast to gain access to the ivar. std::string RecName = clsDeclared->getIdentifier()->getName(); RecName += "_IMPL"; @@ -5881,9 +5881,9 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { IV->setBase(PE); } } - + ReplaceStmtWithRange(IV, Replacement, OldRange); - return Replacement; + return Replacement; } #endif // CLANG_ENABLE_OBJC_REWRITER diff --git a/lib/Frontend/SerializedDiagnosticPrinter.cpp b/lib/Frontend/SerializedDiagnosticPrinter.cpp index ca60c4812f722..22546ce4c0970 100644 --- a/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ b/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -28,31 +28,31 @@ using namespace clang; using namespace clang::serialized_diags; namespace { - + class AbbreviationMap { llvm::DenseMap<unsigned, unsigned> Abbrevs; public: AbbreviationMap() {} - + void set(unsigned recordID, unsigned abbrevID) { - assert(Abbrevs.find(recordID) == Abbrevs.end() + assert(Abbrevs.find(recordID) == Abbrevs.end() && "Abbreviation already set."); Abbrevs[recordID] = abbrevID; } - + unsigned get(unsigned recordID) { assert(Abbrevs.find(recordID) != Abbrevs.end() && "Abbreviation not set."); return Abbrevs[recordID]; } }; - + typedef SmallVector<uint64_t, 64> RecordData; typedef SmallVectorImpl<uint64_t> RecordDataImpl; typedef ArrayRef<uint64_t> RecordDataRef; class SDiagsWriter; - + class SDiagsRenderer : public DiagnosticNoteRenderer { SDiagsWriter &Writer; public: @@ -172,7 +172,7 @@ private: /// Emit the preamble for the serialized diagnostics. void EmitPreamble(); - + /// Emit the BLOCKINFO block. void EmitBlockInfoBlock(); @@ -197,10 +197,10 @@ private: /// Emit a record for a CharSourceRange. void EmitCharSourceRange(CharSourceRange R, const SourceManager &SM); - + /// Emit the string information for the category. unsigned getEmitCategory(unsigned category = 0); - + /// Emit the string information for diagnostic flags. unsigned getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel, unsigned DiagID = 0); @@ -312,7 +312,7 @@ static void EmitBlockID(unsigned ID, const char *Name, Record.clear(); Record.push_back(ID); Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); - + // Emit the block name if present. if (!Name || Name[0] == 0) return; @@ -370,11 +370,11 @@ void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range, unsigned SDiagsWriter::getEmitFile(const char *FileName){ if (!FileName) return 0; - + unsigned &entry = State->Files[FileName]; if (entry) return entry; - + // Lazily generate the record for the file. entry = State->Files.size(); StringRef Name(FileName); @@ -417,7 +417,7 @@ static void AddSourceLocationAbbrev(llvm::BitCodeAbbrev &Abbrev) { static void AddRangeLocationAbbrev(llvm::BitCodeAbbrev &Abbrev) { AddSourceLocationAbbrev(Abbrev); - AddSourceLocationAbbrev(Abbrev); + AddSourceLocationAbbrev(Abbrev); } void SDiagsWriter::EmitBlockInfoBlock() { @@ -456,12 +456,12 @@ void SDiagsWriter::EmitBlockInfoBlock() { Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Diag level. AddSourceLocationAbbrev(*Abbrev); - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category. + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text. Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit abbreviation for RECORD_CATEGORY. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY)); @@ -476,7 +476,7 @@ void SDiagsWriter::EmitBlockInfoBlock() { AddRangeLocationAbbrev(*Abbrev); Abbrevs.set(RECORD_SOURCE_RANGE, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit the abbreviation for RECORD_DIAG_FLAG. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG)); @@ -485,18 +485,18 @@ void SDiagsWriter::EmitBlockInfoBlock() { Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text. Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit the abbreviation for RECORD_FILENAME. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped file ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Size. - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modification time. + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modification time. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text. Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit the abbreviation for RECORD_FIXIT. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_FIXIT)); @@ -529,7 +529,7 @@ unsigned SDiagsWriter::getEmitCategory(unsigned int category) { RecordData::value_type Record[] = {RECORD_CATEGORY, category, catName.size()}; State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_CATEGORY), Record, catName); - + return category; } @@ -537,7 +537,7 @@ unsigned SDiagsWriter::getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel, unsigned DiagID) { if (DiagLevel == DiagnosticsEngine::Note) return 0; // No flag for notes. - + StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(DiagID); return getEmitDiagnosticFlag(FlagName); } @@ -553,7 +553,7 @@ unsigned SDiagsWriter::getEmitDiagnosticFlag(StringRef FlagName) { if (entry.first == 0) { entry.first = State->DiagFlags.size(); entry.second = FlagName; - + // Lazily emit the string in a separate record. RecordData::value_type Record[] = {RECORD_DIAG_FLAG, entry.first, FlagName.size()}; @@ -630,7 +630,7 @@ void SDiagsWriter::EmitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; AbbreviationMap &Abbrevs = State->Abbrevs; - + // Emit the RECORD_DIAG record. Record.clear(); Record.push_back(RECORD_DIAG); diff --git a/lib/Frontend/TestModuleFileExtension.cpp b/lib/Frontend/TestModuleFileExtension.cpp index 294f7e44cee52..087bdc5435489 100644 --- a/lib/Frontend/TestModuleFileExtension.cpp +++ b/lib/Frontend/TestModuleFileExtension.cpp @@ -91,7 +91,7 @@ llvm::hash_code TestModuleFileExtension::hashExtension( Code = llvm::hash_combine(Code, MinorVersion); Code = llvm::hash_combine(Code, UserInfo); } - + return Code; } diff --git a/lib/Frontend/TextDiagnostic.cpp b/lib/Frontend/TextDiagnostic.cpp index 85cd019005da2..35b99b10f94a4 100644 --- a/lib/Frontend/TextDiagnostic.cpp +++ b/lib/Frontend/TextDiagnostic.cpp @@ -100,7 +100,7 @@ printableTextForNextCharacter(StringRef SourceLine, size_t *i, unsigned TabStop) { assert(i && "i must not be null"); assert(*i<SourceLine.size() && "must point to a valid index"); - + if (SourceLine[*i]=='\t') { assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop && "Invalid -ftabstop value"); @@ -118,7 +118,7 @@ printableTextForNextCharacter(StringRef SourceLine, size_t *i, unsigned char const *begin, *end; begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i)); end = begin + (SourceLine.size() - *i); - + if (llvm::isLegalUTF8Sequence(begin, end)) { llvm::UTF32 c; llvm::UTF32 *cptr = &c; @@ -203,7 +203,7 @@ static void byteToColumn(StringRef SourceLine, unsigned TabStop, out.resize(1u,0); return; } - + out.resize(SourceLine.size()+1, -1); int columns = 0; @@ -255,10 +255,10 @@ namespace { struct SourceColumnMap { SourceColumnMap(StringRef SourceLine, unsigned TabStop) : m_SourceLine(SourceLine) { - + ::byteToColumn(SourceLine, TabStop, m_byteToColumn); ::columnToByte(SourceLine, TabStop, m_columnToByte); - + assert(m_byteToColumn.size()==SourceLine.size()+1); assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size()); assert(m_byteToColumn.size() @@ -309,7 +309,7 @@ struct SourceColumnMap { StringRef getSourceLine() const { return m_SourceLine; } - + private: const std::string m_SourceLine; SmallVector<int,200> m_byteToColumn; @@ -684,7 +684,7 @@ void TextDiagnostic::emitDiagnosticMessage( if (DiagOpts->ShowColors) OS.resetColor(); - + printDiagnosticLevel(OS, Level, DiagOpts->ShowColors, DiagOpts->CLFallbackMode); printDiagnosticMessage(OS, @@ -891,7 +891,7 @@ void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) { OS << "In file included from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; else - OS << "In included file:\n"; + OS << "In included file:\n"; } void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, @@ -1269,15 +1269,15 @@ void TextDiagnostic::emitSnippet(StringRef line) { return; size_t i = 0; - + std::string to_print; bool print_reversed = false; - + while (i<line.size()) { std::pair<SmallString<16>,bool> res = printableTextForNextCharacter(line, &i, DiagOpts->TabStop); bool was_printable = res.second; - + if (DiagOpts->ShowColors && was_printable == print_reversed) { if (print_reversed) OS.reverseColor(); @@ -1286,17 +1286,17 @@ void TextDiagnostic::emitSnippet(StringRef line) { if (DiagOpts->ShowColors) OS.resetColor(); } - + print_reversed = !was_printable; to_print += res.first.str(); } - + if (print_reversed && DiagOpts->ShowColors) OS.reverseColor(); OS << to_print; if (print_reversed && DiagOpts->ShowColors) OS.resetColor(); - + OS << '\n'; } diff --git a/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/lib/FrontendTool/ExecuteCompilerInvocation.cpp index ac2ee50a1e4b5..747fdd2416404 100644 --- a/lib/FrontendTool/ExecuteCompilerInvocation.cpp +++ b/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -139,7 +139,7 @@ CreateFrontendAction(CompilerInstance &CI) { if (FEOpts.FixAndRecompile) { Act = llvm::make_unique<FixItRecompile>(std::move(Act)); } - + #if CLANG_ENABLE_ARCMT if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource && CI.getFrontendOpts().ProgramAction != frontend::GeneratePCH) { @@ -260,4 +260,4 @@ bool ExecuteCompilerInvocation(CompilerInstance *Clang) { return Success; } -} // namespace clang +} // namespace clang diff --git a/lib/Headers/avx512fintrin.h b/lib/Headers/avx512fintrin.h index 81696953b76eb..8dd4a0a40eeaa 100644 --- a/lib/Headers/avx512fintrin.h +++ b/lib/Headers/avx512fintrin.h @@ -319,9 +319,9 @@ _mm512_set1_epi32(int __s) } static __inline __m512i __DEFAULT_FN_ATTRS512 -_mm512_maskz_set1_epi32(__mmask16 __M, int __A) +_mm512_maskz_set1_epi32(__mmask16 __M, int __A) { - return (__m512i)__builtin_ia32_selectd_512(__M, + return (__m512i)__builtin_ia32_selectd_512(__M, (__v16si)_mm512_set1_epi32(__A), (__v16si)_mm512_setzero_si512()); } diff --git a/lib/Headers/avx512vlcdintrin.h b/lib/Headers/avx512vlcdintrin.h index 127c5b132ac77..903a7c25493f3 100644 --- a/lib/Headers/avx512vlcdintrin.h +++ b/lib/Headers/avx512vlcdintrin.h @@ -34,7 +34,7 @@ static __inline__ __m128i __DEFAULT_FN_ATTRS128 _mm_broadcastmb_epi64 (__mmask8 __A) -{ +{ return (__m128i) _mm_set1_epi64x((long long) __A); } diff --git a/lib/Headers/clzerointrin.h b/lib/Headers/clzerointrin.h index 07628acd80054..f4e920839bee2 100644 --- a/lib/Headers/clzerointrin.h +++ b/lib/Headers/clzerointrin.h @@ -45,6 +45,6 @@ _mm_clzero (void * __line) __builtin_ia32_clzero ((void *)__line); } -#undef __DEFAULT_FN_ATTRS +#undef __DEFAULT_FN_ATTRS #endif /* __CLZEROINTRIN_H */ diff --git a/lib/Headers/lwpintrin.h b/lib/Headers/lwpintrin.h index 3455575cced64..0b28d73582954 100644 --- a/lib/Headers/lwpintrin.h +++ b/lib/Headers/lwpintrin.h @@ -84,7 +84,7 @@ __slwpcb (void) (__builtin_ia32_lwpins32((unsigned int) (DATA2), (unsigned int) (DATA1), \ (unsigned int) (FLAGS))) -/// Decrements the LWP programmed value sample event counter. If the result is +/// Decrements the LWP programmed value sample event counter. If the result is /// negative, inserts an event record into the LWP event ring buffer in memory /// and advances the ring buffer pointer. /// @@ -125,7 +125,7 @@ __slwpcb (void) (__builtin_ia32_lwpins64((unsigned long long) (DATA2), (unsigned int) (DATA1), \ (unsigned int) (FLAGS))) -/// Decrements the LWP programmed value sample event counter. If the result is +/// Decrements the LWP programmed value sample event counter. If the result is /// negative, inserts an event record into the LWP event ring buffer in memory /// and advances the ring buffer pointer. /// diff --git a/lib/Headers/opencl-c.h b/lib/Headers/opencl-c.h index e648b0f2f3704..e481c792df719 100644 --- a/lib/Headers/opencl-c.h +++ b/lib/Headers/opencl-c.h @@ -11540,7 +11540,7 @@ half16 __ovld __cnfn select(half16 a, half16 b, ushort16 c); * * vstoren write sizeof (gentypen) bytes given by data to address (p + (offset * n)). * - * The address computed as (p + (offset * n)) must be + * The address computed as (p + (offset * n)) must be * 8-bit aligned if gentype is char, uchar; * 16-bit aligned if gentype is short, ushort, half; * 32-bit aligned if gentype is int, uint, float; @@ -12888,7 +12888,7 @@ void __ovld write_mem_fence(cl_mem_fence_flags flags); cl_mem_fence_flags __ovld get_fence(const void *ptr); cl_mem_fence_flags __ovld get_fence(void *ptr); -/** +/** * Builtin functions to_global, to_local, and to_private need to be declared as Clang builtin functions * and checked in Sema since they should be declared as * addr gentype* to_addr (gentype*); @@ -13773,7 +13773,7 @@ ulong __ovld atomic_fetch_max_explicit(volatile atomic_ulong *object, long opera // add/sub: atomic type argument can be uintptr_t/intptr_t, value type argument can be ptrdiff_t. // or/xor/and/min/max: atomic type argument can be intptr_t/uintptr_t, value type argument can be intptr_t/uintptr_t. -#if defined(cl_khr_int64_base_atomics) && defined(cl_khr_int64_extended_atomics) +#if defined(cl_khr_int64_base_atomics) && defined(cl_khr_int64_extended_atomics) uintptr_t __ovld atomic_fetch_add(volatile atomic_uintptr_t *object, ptrdiff_t operand); uintptr_t __ovld atomic_fetch_add_explicit(volatile atomic_uintptr_t *object, ptrdiff_t operand, memory_order order); uintptr_t __ovld atomic_fetch_add_explicit(volatile atomic_uintptr_t *object, ptrdiff_t operand, memory_order order, memory_scope scope); @@ -14571,7 +14571,7 @@ int printf(__constant const char* st, ...); * only. The filter_mode specified in sampler * must be set to CLK_FILTER_NEAREST; otherwise * the values returned are undefined. - + * The read_image{f|i|ui} calls that take * integer coordinates must use a sampler with * normalized coordinates set to diff --git a/lib/Index/IndexBody.cpp b/lib/Index/IndexBody.cpp index ac34956b24840..786563a44a4d7 100644 --- a/lib/Index/IndexBody.cpp +++ b/lib/Index/IndexBody.cpp @@ -30,7 +30,7 @@ public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } - + bool shouldWalkTypesOfTypeLocs() const { return false; } bool dataTraverseStmtPre(Stmt *S) { @@ -322,7 +322,7 @@ public: } return true; } - + bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); diff --git a/lib/Index/IndexTypeSourceInfo.cpp b/lib/Index/IndexTypeSourceInfo.cpp index 7a7a156478f88..4b6bfbc67eff6 100644 --- a/lib/Index/IndexTypeSourceInfo.cpp +++ b/lib/Index/IndexTypeSourceInfo.cpp @@ -37,7 +37,7 @@ public: Relations.emplace_back((unsigned)SymbolRole::RelationIBTypeOf, Parent); } } - + bool shouldWalkTypesOfTypeLocs() const { return false; } #define TRY_TO(CALL_EXPR) \ @@ -193,7 +193,7 @@ void IndexingContext::indexTypeSourceInfo(TypeSourceInfo *TInfo, bool isIBType) { if (!TInfo || TInfo->getTypeLoc().isNull()) return; - + indexTypeLoc(TInfo->getTypeLoc(), Parent, DC, isBase, isIBType); } diff --git a/lib/Index/IndexingContext.cpp b/lib/Index/IndexingContext.cpp index 80d851b43d732..333f9dc3091bb 100644 --- a/lib/Index/IndexingContext.cpp +++ b/lib/Index/IndexingContext.cpp @@ -75,7 +75,7 @@ bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc, if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D)) return true; - + return handleDeclOccurrence(D, Loc, /*IsRef=*/true, Parent, Roles, Relations, RefE, RefD, DC); } diff --git a/lib/Index/USRGeneration.cpp b/lib/Index/USRGeneration.cpp index e69fa749b45f7..b128b69931a36 100644 --- a/lib/Index/USRGeneration.cpp +++ b/lib/Index/USRGeneration.cpp @@ -62,9 +62,9 @@ class USRGenerator : public ConstDeclVisitor<USRGenerator> { bool IgnoreResults; ASTContext *Context; bool generatedLoc; - + llvm::DenseMap<const Type *, unsigned> TypeSubstitutions; - + public: explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf) : Buf(Buf), @@ -159,7 +159,7 @@ public: void VisitTemplateParameterList(const TemplateParameterList *Params); void VisitTemplateName(TemplateName Name); void VisitTemplateArgument(const TemplateArgument &Arg); - + /// Emit a Decl's name using NamedDecl::printName() and return true if /// the decl had no name. bool EmitDeclName(const NamedDecl *D); @@ -366,7 +366,7 @@ void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) { void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) { VisitDeclContext(D->getDeclContext()); if (!IgnoreResults) - Out << "@NA@" << D->getName(); + Out << "@NA@" << D->getName(); } void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) { @@ -493,7 +493,7 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) { if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) { AlreadyStarted = true; - + switch (D->getTagKind()) { case TTK_Interface: case TTK_Class: @@ -505,18 +505,18 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) { AlreadyStarted = true; - + switch (D->getTagKind()) { case TTK_Interface: case TTK_Class: case TTK_Struct: Out << "@SP"; break; case TTK_Union: Out << "@UP"; break; case TTK_Enum: llvm_unreachable("enum partial specialization"); - } + } VisitTemplateParameterList(PartialSpec->getTemplateParameters()); } } - + if (!AlreadyStarted) { switch (D->getTagKind()) { case TTK_Interface: @@ -526,7 +526,7 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { case TTK_Enum: Out << "@E"; break; } } - + Out << '@'; assert(Buf.size() > 0); const unsigned off = Buf.size() - 1; @@ -551,7 +551,7 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { } } } - + // For a class template specialization, mangle the template arguments. if (const ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) { @@ -640,7 +640,7 @@ void USRGenerator::VisitType(QualType T) { Out << 'P'; T = Expansion->getPattern(); } - + if (const BuiltinType *BT = T->getAs<BuiltinType>()) { unsigned char c = '\0'; switch (BT->getKind()) { @@ -758,7 +758,7 @@ void USRGenerator::VisitType(QualType T) { unsigned Number = TypeSubstitutions.size(); TypeSubstitutions[T.getTypePtr()] = Number; } - + if (const PointerType *PT = T->getAs<PointerType>()) { Out << '*'; T = PT->getPointeeType(); @@ -889,7 +889,7 @@ void USRGenerator::VisitTemplateParameterList( Out << 'T'; continue; } - + if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { if (NTTP->isParameterPack()) Out << 'p'; @@ -897,7 +897,7 @@ void USRGenerator::VisitTemplateParameterList( VisitType(NTTP->getType()); continue; } - + TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); if (TTP->isParameterPack()) Out << 'p'; @@ -913,11 +913,11 @@ void USRGenerator::VisitTemplateName(TemplateName Name) { Out << 't' << TTP->getDepth() << '.' << TTP->getIndex(); return; } - + Visit(Template); return; } - + // FIXME: Visit dependent template names. } @@ -939,21 +939,21 @@ void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) { case TemplateArgument::Template: VisitTemplateName(Arg.getAsTemplateOrTemplatePattern()); break; - + case TemplateArgument::Expression: // FIXME: Visit expressions. break; - + case TemplateArgument::Pack: Out << 'p' << Arg.pack_size(); for (const auto &P : Arg.pack_elements()) VisitTemplateArgument(P); break; - + case TemplateArgument::Type: VisitType(Arg.getAsType()); break; - + case TemplateArgument::Integral: Out << 'V'; VisitType(Arg.getIntegralType()); diff --git a/lib/Lex/HeaderSearch.cpp b/lib/Lex/HeaderSearch.cpp index b1a2ef121288e..fbfa54b2fffd2 100644 --- a/lib/Lex/HeaderSearch.cpp +++ b/lib/Lex/HeaderSearch.cpp @@ -246,9 +246,9 @@ Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, break; } } - + // FIXME: Figure out how header maps and module maps will work together. - + // Only deal with normal search directories. if (!SearchDirs[Idx].isNormalDir()) continue; @@ -263,7 +263,7 @@ Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, if (Module) break; } - + // Search for a module map in a subdirectory with the same name as the // module. SmallString<128> NestedModuleMapDirName; @@ -530,7 +530,7 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup( RelativePath->clear(); RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); } - + // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" unsigned OrigSize = FrameworkName.size(); @@ -709,7 +709,7 @@ const FileEntry *HeaderSearch::LookupFile( if (SuggestedModule) *SuggestedModule = ModuleMap::KnownHeader(); - + // If 'Filename' is absolute, check to see if it exists and no searching. if (llvm::sys::path::is_absolute(Filename)) { CurDir = nullptr; @@ -898,7 +898,7 @@ const FileEntry *HeaderSearch::LookupFile( size_t SlashPos = Filename.find('/'); if (SlashPos != StringRef::npos) { HFI.IndexHeaderMapHeader = 1; - HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), + HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); } } @@ -1079,7 +1079,7 @@ LookupSubframeworkHeader(StringRef Filename, /// Merge the header file info provided by \p OtherHFI into the current /// header file info (\p HFI) -static void mergeHeaderFileInfo(HeaderFileInfo &HFI, +static void mergeHeaderFileInfo(HeaderFileInfo &HFI, const HeaderFileInfo &OtherHFI) { assert(OtherHFI.External && "expected to merge external HFI"); @@ -1101,7 +1101,7 @@ static void mergeHeaderFileInfo(HeaderFileInfo &HFI, if (HFI.Framework.empty()) HFI.Framework = OtherHFI.Framework; } - + /// getFileInfo - Return the HeaderFileInfo structure for the specified /// FileEntry. HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { @@ -1285,14 +1285,14 @@ StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { return FrameworkNames.insert(Framework).first->first(); } -bool HeaderSearch::hasModuleMap(StringRef FileName, +bool HeaderSearch::hasModuleMap(StringRef FileName, const DirectoryEntry *Root, bool IsSystem) { if (!HSOpts->ImplicitModuleMaps) return false; SmallVector<const DirectoryEntry *, 2> FixUpDirectories; - + StringRef DirName = FileName; do { // Get the parent directory name. @@ -1325,7 +1325,7 @@ bool HeaderSearch::hasModuleMap(StringRef FileName, // If we hit the top of our search, we're done. if (Dir == Root) return false; - + // Keep track of all of the directories we checked, so we can mark them as // having module maps if we eventually do find a module map. FixUpDirectories.push_back(Dir); @@ -1385,7 +1385,7 @@ bool HeaderSearch::findUsableModuleForFrameworkHeader( SmallVector<std::string, 4> SubmodulePath; const DirectoryEntry *TopFrameworkDir = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); - + // Determine the name of the top-level framework. StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); @@ -1532,16 +1532,16 @@ Module *HeaderSearch::loadFrameworkModule(StringRef Name, return ModMap.findModule(Name); } -HeaderSearch::LoadModuleMapResult +HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, bool IsFramework) { if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName)) return loadModuleMapFile(Dir, IsSystem, IsFramework); - + return LMM_NoDirectory; } -HeaderSearch::LoadModuleMapResult +HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, bool IsFramework) { auto KnownDir = DirectoryHasModuleMap.find(Dir); @@ -1610,7 +1610,7 @@ void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { } // Populate the list of modules. - for (ModuleMap::module_iterator M = ModMap.module_begin(), + for (ModuleMap::module_iterator M = ModMap.module_begin(), MEnd = ModMap.module_end(); M != MEnd; ++M) { Modules.push_back(M->getValue()); diff --git a/lib/Lex/LiteralSupport.cpp b/lib/Lex/LiteralSupport.cpp index 966dafca27197..3f2af1a74e5a2 100644 --- a/lib/Lex/LiteralSupport.cpp +++ b/lib/Lex/LiteralSupport.cpp @@ -30,7 +30,7 @@ #include <algorithm> #include <cassert> #include <cstddef> -#include <cstdint> +#include <cstdint> #include <cstring> #include <string> @@ -274,7 +274,7 @@ void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) { static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, - FullSourceLoc Loc, DiagnosticsEngine *Diags, + FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features, bool in_char_string_literal = false) { const char *UcnBegin = ThisTokBuf; @@ -1539,7 +1539,7 @@ void StringLiteralParser::init(ArrayRef<Token> StringToks){ // that ThisTokBuf points to a buffer that is big enough for the whole token // and 'spelled' tokens can only shrink. bool StringInvalid = false; - unsigned ThisTokLen = + unsigned ThisTokLen = Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features, &StringInvalid); if (StringInvalid) diff --git a/lib/Lex/MacroArgs.cpp b/lib/Lex/MacroArgs.cpp index 3b6e2dc2411a0..dc2ba3074a8b1 100644 --- a/lib/Lex/MacroArgs.cpp +++ b/lib/Lex/MacroArgs.cpp @@ -29,7 +29,7 @@ MacroArgs *MacroArgs::create(const MacroInfo *MI, "Can't have args for an object-like macro!"); MacroArgs **ResultEnt = nullptr; unsigned ClosestMatch = ~0U; - + // See if we have an entry with a big enough argument list to reuse on the // free list. If so, reuse it. for (MacroArgs **Entry = &PP.MacroArgCache; *Entry; @@ -37,7 +37,7 @@ MacroArgs *MacroArgs::create(const MacroInfo *MI, if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() && (*Entry)->NumUnexpArgTokens < ClosestMatch) { ResultEnt = Entry; - + // If we have an exact match, use it. if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size()) break; @@ -83,7 +83,7 @@ void MacroArgs::destroy(Preprocessor &PP) { // would deallocate the element vectors. for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i) PreExpArgTokens[i].clear(); - + // Add this to the preprocessor's free list. ArgCache = PP.MacroArgCache; PP.MacroArgCache = this; @@ -93,14 +93,14 @@ void MacroArgs::destroy(Preprocessor &PP) { /// its freelist. MacroArgs *MacroArgs::deallocate() { MacroArgs *Next = ArgCache; - + // Run the dtor to deallocate the vectors. this->~MacroArgs(); // Release the memory for the object. static_assert(std::is_trivially_destructible<Token>::value, "assume trivially destructible and forego destructors"); free(this); - + return Next; } @@ -125,7 +125,7 @@ const Token *MacroArgs::getUnexpArgument(unsigned Arg) const { // in memory. const Token *Start = getTrailingObjects<Token>(); const Token *Result = Start; - + // Scan to find Arg. for (; Arg; ++Result) { assert(Result < Start+NumUnexpArgTokens && "Invalid arg #"); @@ -171,7 +171,7 @@ const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg, // If we have already computed this, return it. if (PreExpArgTokens.size() < getNumMacroArguments()) PreExpArgTokens.resize(getNumMacroArguments()); - + std::vector<Token> &Result = PreExpArgTokens[Arg]; if (!Result.empty()) return Result; diff --git a/lib/Lex/ModuleMap.cpp b/lib/Lex/ModuleMap.cpp index f048a73a8ccc2..87749f74734c9 100644 --- a/lib/Lex/ModuleMap.cpp +++ b/lib/Lex/ModuleMap.cpp @@ -103,8 +103,8 @@ ModuleMap::headerKindToRole(Module::HeaderKind Kind) { llvm_unreachable("unknown header kind"); } -Module::ExportDecl -ModuleMap::resolveExport(Module *Mod, +Module::ExportDecl +ModuleMap::resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved, bool Complain) const { // We may have just a wildcard. @@ -112,7 +112,7 @@ ModuleMap::resolveExport(Module *Mod, assert(Unresolved.Wildcard && "Invalid unresolved export"); return Module::ExportDecl(nullptr, true); } - + // Resolve the module-id. Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain); if (!Context) @@ -151,7 +151,7 @@ Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod, return Context; } -/// Append to \p Paths the set of paths needed to get to the +/// Append to \p Paths the set of paths needed to get to the /// subframework in which the given module lives. static void appendSubframeworkPaths(Module *Mod, SmallVectorImpl<char> &Path) { @@ -161,10 +161,10 @@ static void appendSubframeworkPaths(Module *Mod, if (Mod->IsFramework) Paths.push_back(Mod->Name); } - + if (Paths.empty()) return; - + // Add Frameworks/Name.framework for each subframework. for (unsigned I = Paths.size() - 1; I != 0; --I) llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework"); @@ -325,7 +325,7 @@ ModuleMap::~ModuleMap() { } void ModuleMap::setTarget(const TargetInfo &Target) { - assert((!this->Target || this->Target == &Target) && + assert((!this->Target || this->Target == &Target) && "Improper target override"); this->Target = &Target; } @@ -528,7 +528,7 @@ void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule, << RequestingModule->getTopLevelModule()->Name << Filename; } else if (RequestingModule && RequestingModuleIsModuleInterface && LangOpts.isCompilingModule()) { - // Do not diagnose when we are not compiling a module. + // Do not diagnose when we are not compiling a module. diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ? diag::warn_non_modular_include_in_framework_module : diag::warn_non_modular_include_in_module; @@ -732,7 +732,7 @@ ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, if (IsUnavailable(Found)) return true; } - + // Infer a submodule with the same name as this header file. SmallString<32> NameBuf; StringRef Name = sanitizeFilenameAsIdentifier( @@ -745,18 +745,18 @@ ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, return IsUnavailable(Found); } - + SkippedDirs.push_back(Dir); - + // Retrieve our parent path. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; - + // Resolve the parent path to a directory entry. Dir = SourceMgr.getFileManager().getDirectory(DirName); } while (Dir); - + return false; } @@ -774,14 +774,14 @@ Module *ModuleMap::lookupModuleUnqualified(StringRef Name, if (Module *Sub = lookupModuleQualified(Name, Context)) return Sub; } - + return findModule(Name); } Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{ if (!Context) return findModule(Name); - + return Context->findSubmodule(Name); } @@ -892,7 +892,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, // Check whether we've already found this module. if (Module *Mod = lookupModuleQualified(ModuleName, Parent)) return Mod; - + FileManager &FileMgr = SourceMgr.getFileManager(); // If the framework has a parent path from which we're allowed to infer @@ -953,7 +953,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName()); llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h"); const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName); - + // FIXME: If there's no umbrella header, we could probably scan the // framework to load *everything*. But, it's not clear that this is a good // idea. @@ -983,14 +983,14 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, // The "Headers/" component of the name is implied because this is // a framework module. setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h"); - + // export * Result->Exports.push_back(Module::ExportDecl(nullptr, true)); // module * { export * } Result->InferSubmodules = true; Result->InferExportWildcard = true; - + // Look for subframeworks. std::error_code EC; SmallString<128> SubframeworksDirName @@ -1200,11 +1200,11 @@ void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) { LLVM_DUMP_METHOD void ModuleMap::dump() { llvm::errs() << "Modules:"; - for (llvm::StringMap<Module *>::iterator M = Modules.begin(), - MEnd = Modules.end(); + for (llvm::StringMap<Module *>::iterator M = Modules.begin(), + MEnd = Modules.end(); M != MEnd; ++M) M->getValue()->print(llvm::errs(), 2); - + llvm::errs() << "Headers:"; for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); H != HEnd; ++H) { @@ -1299,7 +1299,7 @@ namespace clang { LSquare, RSquare } Kind; - + unsigned Location; unsigned StringLength; union { @@ -1309,16 +1309,16 @@ namespace clang { // If Kind == IntegerLiteral. uint64_t IntegerValue; }; - + void clear() { Kind = EndOfFile; Location = 0; StringLength = 0; StringData = nullptr; } - + bool is(TokenKind K) const { return Kind == K; } - + SourceLocation getLocation() const { return SourceLocation::getFromRawEncoding(Location); } @@ -1326,7 +1326,7 @@ namespace clang { uint64_t getInteger() const { return Kind == IntegerLiteral ? IntegerValue : 0; } - + StringRef getString() const { return Kind == IntegerLiteral ? StringRef() : StringRef(StringData, StringLength); @@ -1356,17 +1356,17 @@ namespace clang { /// Whether this module map is in a system header directory. bool IsSystem; - + /// Whether an error occurred. bool HadError = false; - + /// Stores string data for the various string literals referenced /// during parsing. llvm::BumpPtrAllocator StringData; - + /// The current token. MMToken Tok; - + /// The active module. Module *ActiveModule = nullptr; @@ -1413,7 +1413,7 @@ namespace clang { using Attributes = ModuleMap::Attributes; bool parseOptionalAttributes(Attributes &Attrs); - + public: explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, const TargetInfo *Target, DiagnosticsEngine &Diags, @@ -1475,7 +1475,7 @@ retry: case tok::eof: Tok.Kind = MMToken::EndOfFile; break; - + case tok::l_brace: Tok.Kind = MMToken::LBrace; break; @@ -1483,27 +1483,27 @@ retry: case tok::l_square: Tok.Kind = MMToken::LSquare; break; - + case tok::period: Tok.Kind = MMToken::Period; break; - + case tok::r_brace: Tok.Kind = MMToken::RBrace; break; - + case tok::r_square: Tok.Kind = MMToken::RSquare; break; - + case tok::star: Tok.Kind = MMToken::Star; break; - + case tok::exclaim: Tok.Kind = MMToken::Exclaim; break; - + case tok::string_literal: { if (LToken.hasUDSuffix()) { Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl); @@ -1516,13 +1516,13 @@ retry: StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target); if (StringLiteral.hadError) goto retry; - + // Copy the string literal into our string data allocator. unsigned Length = StringLiteral.GetStringLength(); char *Saved = StringData.Allocate<char>(Length + 1); memcpy(Saved, StringLiteral.GetString().data(), Length); Saved[Length] = 0; - + // Form the token. Tok.Kind = MMToken::StringLiteral; Tok.StringData = Saved; @@ -1548,7 +1548,7 @@ retry: Tok.IntegerValue = Value; break; } - + case tok::comment: goto retry; @@ -1576,7 +1576,7 @@ retry: HadError = true; goto retry; } - + return Result; } @@ -1591,14 +1591,14 @@ void ModuleMapParser::skipUntil(MMToken::TokenKind K) { case MMToken::LBrace: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; - + ++braceDepth; break; case MMToken::LSquare: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; - + ++squareDepth; break; @@ -1621,7 +1621,7 @@ void ModuleMapParser::skipUntil(MMToken::TokenKind K) { return; break; } - + consumeToken(); } while (true); } @@ -1643,13 +1643,13 @@ bool ModuleMapParser::parseModuleId(ModuleId &Id) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name); return true; } - + if (!Tok.is(MMToken::Period)) break; - + consumeToken(); } while (true); - + return false; } @@ -1740,7 +1740,7 @@ void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc, /// /// module-declaration: /// 'extern' 'module' module-id string-literal -/// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] +/// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] /// { module-member* } /// /// module-member: @@ -1778,8 +1778,8 @@ void ModuleMapParser::parseModuleDecl() { if (Tok.is(MMToken::FrameworkKeyword)) { FrameworkLoc = consumeToken(); Framework = true; - } - + } + // Parse 'module' keyword. if (!Tok.is(MMToken::ModuleKeyword)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); @@ -1790,10 +1790,10 @@ void ModuleMapParser::parseModuleDecl() { CurrModuleDeclLoc = consumeToken(); // 'module' keyword // If we have a wildcard for the module name, this is an inferred submodule. - // Parse it. + // Parse it. if (Tok.is(MMToken::Star)) return parseInferredModuleDecl(Framework, Explicit); - + // Parse the module name. ModuleId Id; if (parseModuleId(Id)) { @@ -1805,7 +1805,7 @@ void ModuleMapParser::parseModuleDecl() { if (Id.size() > 1) { Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id) << SourceRange(Id.front().second, Id.back().second); - + HadError = true; return; } @@ -1816,8 +1816,8 @@ void ModuleMapParser::parseModuleDecl() { ExplicitLoc = SourceLocation(); HadError = true; } - - Module *PreviousActiveModule = ActiveModule; + + Module *PreviousActiveModule = ActiveModule; if (Id.size() > 1) { // This module map defines a submodule. Go find the module of which it // is a submodule. @@ -1830,7 +1830,7 @@ void ModuleMapParser::parseModuleDecl() { ActiveModule = Next; continue; } - + if (ActiveModule) { Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) << Id[I].first @@ -1849,10 +1849,10 @@ void ModuleMapParser::parseModuleDecl() { Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile); } } - + StringRef ModuleName = Id.back().first; SourceLocation ModuleNameLoc = Id.back().second; - + // Parse the optional attribute list. Attributes Attrs; if (parseOptionalAttributes(Attrs)) @@ -1864,9 +1864,9 @@ void ModuleMapParser::parseModuleDecl() { << ModuleName; HadError = true; return; - } + } SourceLocation LBraceLoc = consumeToken(); - + // Determine whether this (sub)module has already been defined. Module *ShadowingModule = nullptr; if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { @@ -1890,7 +1890,7 @@ void ModuleMapParser::parseModuleDecl() { else { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); - HadError = true; + HadError = true; } return; } @@ -1986,7 +1986,7 @@ void ModuleMapParser::parseModuleDecl() { case MMToken::UseKeyword: parseUseDecl(); break; - + case MMToken::RequiresKeyword: parseRequiresDecl(); break; @@ -2023,7 +2023,7 @@ void ModuleMapParser::parseModuleDecl() { default: Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member); consumeToken(); - break; + break; } } while (!Done); @@ -2233,7 +2233,7 @@ void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken, // Parse the header name. if (!Tok.is(MMToken::StringLiteral)) { - Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) + Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << "header"; HadError = true; return; @@ -2330,7 +2330,7 @@ static int compareModuleHeaders(const Module::Header *A, void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { // Parse the directory name. if (!Tok.is(MMToken::StringLiteral)) { - Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) + Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << "umbrella"; HadError = true; return; @@ -2338,7 +2338,7 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { std::string DirName = Tok.getString(); SourceLocation DirNameLoc = consumeToken(); - + // Check whether we already have an umbrella. if (ActiveModule->Umbrella) { Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash) @@ -2357,7 +2357,7 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { llvm::sys::path::append(PathName, DirName); Dir = SourceMgr.getFileManager().getDirectory(PathName); } - + if (!Dir) { Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found) << DirName; @@ -2413,38 +2413,38 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { void ModuleMapParser::parseExportDecl() { assert(Tok.is(MMToken::ExportKeyword)); SourceLocation ExportLoc = consumeToken(); - + // Parse the module-id with an optional wildcard at the end. ModuleId ParsedModuleId; bool Wildcard = false; do { // FIXME: Support string-literal module names here. if (Tok.is(MMToken::Identifier)) { - ParsedModuleId.push_back(std::make_pair(Tok.getString(), + ParsedModuleId.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); consumeToken(); - + if (Tok.is(MMToken::Period)) { consumeToken(); continue; - } - + } + break; } - + if(Tok.is(MMToken::Star)) { Wildcard = true; consumeToken(); break; } - + Diags.Report(Tok.getLocation(), diag::err_mmap_module_id); HadError = true; return; } while (true); - - Module::UnresolvedExportDecl Unresolved = { - ExportLoc, ParsedModuleId, Wildcard + + Module::UnresolvedExportDecl Unresolved = { + ExportLoc, ParsedModuleId, Wildcard }; ActiveModule->UnresolvedExports.push_back(Unresolved); } @@ -2468,7 +2468,7 @@ void ModuleMapParser::parseExportAsDecl() { consumeToken(); return; } - + if (!ActiveModule->ExportAsModule.empty()) { if (ActiveModule->ExportAsModule == Tok.getString()) { Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as) @@ -2479,7 +2479,7 @@ void ModuleMapParser::parseExportAsDecl() { << Tok.getString(); } } - + ActiveModule->ExportAsModule = Tok.getString(); Map.addLinkAsDependency(ActiveModule); @@ -2666,7 +2666,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella); Failed = true; } - + // Check for redefinition of an inferred module. if (!Failed && ActiveModule->InferSubmodules) { Diags.Report(StarLoc, diag::err_mmap_inferred_redef); @@ -2721,7 +2721,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard); HadError = true; return; - } + } SourceLocation LBraceLoc = consumeToken(); // Parse the body of the inferred submodule. @@ -2762,10 +2762,10 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { } consumeToken(); - if (Tok.is(MMToken::Star)) + if (Tok.is(MMToken::Star)) ActiveModule->InferExportWildcard = true; else - Diags.Report(Tok.getLocation(), + Diags.Report(Tok.getLocation(), diag::err_mmap_expected_export_wildcard); consumeToken(); break; @@ -2779,10 +2779,10 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) << (ActiveModule != nullptr); consumeToken(); - break; + break; } } while (!Done); - + if (Tok.is(MMToken::RBrace)) consumeToken(); else { @@ -2806,7 +2806,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { /// \returns true if an error occurred, false otherwise. bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) { bool HadError = false; - + while (Tok.is(MMToken::LSquare)) { // Consume the '['. SourceLocation LSquareLoc = consumeToken(); @@ -2876,7 +2876,7 @@ bool ModuleMapParser::parseModuleMapFile() { switch (Tok.Kind) { case MMToken::EndOfFile: return HadError; - + case MMToken::ExplicitKeyword: case MMToken::ExternKeyword: case MMToken::ModuleKeyword: diff --git a/lib/Lex/PPDirectives.cpp b/lib/Lex/PPDirectives.cpp index d8dae73037a89..66a9faa6e60a5 100644 --- a/lib/Lex/PPDirectives.cpp +++ b/lib/Lex/PPDirectives.cpp @@ -2597,13 +2597,13 @@ void Preprocessor::HandleDefineDirective( MacroInfo *const MI = ReadOptionalMacroParameterListAndBody( MacroNameTok, ImmediatelyAfterHeaderGuard); - + if (!MI) return; if (MacroShadowsKeyword && !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) { Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword); - } + } // Check that there is no paste (##) operator at the beginning or end of the // replacement list. unsigned NumTokens = MI->getNumTokens(); @@ -2716,7 +2716,7 @@ void Preprocessor::HandleUndefDirective() { auto *II = MacroNameTok.getIdentifierInfo(); auto MD = getMacroDefinition(II); UndefMacroDirective *Undef = nullptr; - + // If the macro is not defined, this is a noop undef. if (const MacroInfo *MI = MD.getMacroInfo()) { if (!MI->isUsed() && MI->isWarnIfUnused()) diff --git a/lib/Lex/PPExpressions.cpp b/lib/Lex/PPExpressions.cpp index b1ed0e10c6fc7..ac01efad9bf69 100644 --- a/lib/Lex/PPExpressions.cpp +++ b/lib/Lex/PPExpressions.cpp @@ -273,7 +273,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, case tok::numeric_constant: { SmallString<64> IntegerBuffer; bool NumberInvalid = false; - StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, + StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, &NumberInvalid); if (NumberInvalid) return true; // a diagnostic was already reported @@ -832,11 +832,11 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // expression. bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion; DisableMacroExpansion = false; - + // Peek ahead one token. Token Tok; LexNonComment(Tok); - + // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t. unsigned BitWidth = getTargetInfo().getIntMaxTWidth(); @@ -846,7 +846,7 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // Parse error, skip the rest of the macro line. if (Tok.isNot(tok::eod)) DiscardUntilEndOfDirective(); - + // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return {false, DT.IncludedUndefinedIds}; @@ -873,7 +873,7 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // Parse error, skip the rest of the macro line. if (Tok.isNot(tok::eod)) DiscardUntilEndOfDirective(); - + // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return {false, DT.IncludedUndefinedIds}; diff --git a/lib/Lex/PPLexerChange.cpp b/lib/Lex/PPLexerChange.cpp index 352814d715fa9..6631b13b15836 100644 --- a/lib/Lex/PPLexerChange.cpp +++ b/lib/Lex/PPLexerChange.cpp @@ -82,10 +82,10 @@ bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir, return false; } } - + // Get the MemoryBuffer for this FID, if it fails, we fail. bool Invalid = false; - const llvm::MemoryBuffer *InputFile = + const llvm::MemoryBuffer *InputFile = getSourceManager().getBuffer(FID, Loc, &Invalid); if (Invalid) { SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID); @@ -145,7 +145,7 @@ void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, CurLexerSubmodule = nullptr; if (CurLexerKind != CLK_LexAfterModuleImport) CurLexerKind = CLK_PTHLexer; - + // Notify the client, if desired, that we are in a new source file. if (Callbacks) { FileID FID = CurPPLexer->getFileID(); @@ -240,15 +240,15 @@ static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir, if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) { if (CurDir == Dir) { Result = FilePath.substr(Path.size()); - llvm::sys::path::append(Result, + llvm::sys::path::append(Result, llvm::sys::path::filename(File->getName())); return; } } - + Path = llvm::sys::path::parent_path(Path); } - + Result = File->getName(); } @@ -553,7 +553,7 @@ bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { CurPTHLexer->getEOF(Result); CurPTHLexer.reset(); } - + if (!isIncrementalProcessingEnabled()) CurPPLexer = nullptr; diff --git a/lib/Lex/PPMacroExpansion.cpp b/lib/Lex/PPMacroExpansion.cpp index d9992e00f8c0f..346dd947c0289 100644 --- a/lib/Lex/PPMacroExpansion.cpp +++ b/lib/Lex/PPMacroExpansion.cpp @@ -1186,7 +1186,7 @@ static bool EvaluateHasIncludeCommon(Token &Tok, SmallString<128> FilenameBuffer; StringRef Filename; SourceLocation EndLoc; - + switch (Tok.getKind()) { case tok::eod: // If the token kind is EOD, the error has already been diagnosed. @@ -1260,7 +1260,7 @@ static bool EvaluateHasIncludeNext(Token &Tok, // __has_include_next is like __has_include, except that we start // searching after the current found directory. If we can't do this, // issue a diagnostic. - // FIXME: Factor out duplication with + // FIXME: Factor out duplication with // Preprocessor::HandleIncludeNextDirective. const DirectoryLookup *Lookup = PP.GetCurDirLookup(); const FileEntry *LookupFromFile = nullptr; @@ -1510,7 +1510,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { PLoc = SourceMgr.getPresumedLoc(NextLoc); if (PLoc.isInvalid()) break; - + NextLoc = PLoc.getIncludeLoc(); } } diff --git a/lib/Lex/Pragma.cpp b/lib/Lex/Pragma.cpp index 930c5f6b069c8..37c0a23646c59 100644 --- a/lib/Lex/Pragma.cpp +++ b/lib/Lex/Pragma.cpp @@ -64,7 +64,7 @@ PragmaHandler::~PragmaHandler() = default; EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {} -void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, +void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) {} @@ -99,7 +99,7 @@ void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { Handlers.erase(Handler->getName()); } -void PragmaNamespace::HandlePragma(Preprocessor &PP, +void PragmaNamespace::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro @@ -141,7 +141,7 @@ void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc, PragmaHandlers->HandlePragma(*this, Introducer, Tok); // If the pragma handler didn't read the rest of the line, consume it now. - if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) + if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)) DiscardUntilEndOfDirective(); } @@ -468,7 +468,7 @@ void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); if (PLoc.isInvalid()) return; - + unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); // Notify the client, if desired, that we are in a new source file. @@ -601,7 +601,7 @@ void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { // Get the MacroInfo associated with IdentInfo. MacroInfo *MI = getMacroInfo(IdentInfo); - + if (MI) { // Allow the original MacroInfo to be redefined later. MI->setIsAllowRedefinitionsWithoutWarning(true); @@ -653,7 +653,7 @@ void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { } void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { - // We will either get a quoted filename or a bracketed filename, and we + // We will either get a quoted filename or a bracketed filename, and we // have to track which we got. The first filename is the source name, // and the second name is the mapped filename. If the first is quoted, // the second must be as well (cannot mix and match quotes and brackets). @@ -675,7 +675,7 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { StringRef SourceFileName; SmallString<128> FileNameBuffer; - if (SourceFilenameTok.is(tok::string_literal) || + if (SourceFilenameTok.is(tok::string_literal) || SourceFilenameTok.is(tok::angle_string_literal)) { SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); } else if (SourceFilenameTok.is(tok::less)) { @@ -706,7 +706,7 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { } StringRef ReplaceFileName; - if (ReplaceFilenameTok.is(tok::string_literal) || + if (ReplaceFilenameTok.is(tok::string_literal) || ReplaceFilenameTok.is(tok::angle_string_literal)) { ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); } else if (ReplaceFilenameTok.is(tok::less)) { @@ -732,8 +732,8 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { // they're both of the same type (angled vs non-angled) StringRef OriginalSource = SourceFileName; - bool SourceIsAngled = - GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), + bool SourceIsAngled = + GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), SourceFileName); bool ReplaceIsAngled = GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(), @@ -747,7 +747,7 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { DiagID = diag::warn_pragma_include_alias_mismatch_quote; Diag(SourceFilenameTok.getLocation(), DiagID) - << SourceFileName + << SourceFileName << ReplaceFileName; return; @@ -1615,7 +1615,7 @@ struct PragmaPopMacroHandler : public PragmaHandler { } }; -/// PragmaARCCFCodeAuditedHandler - +/// PragmaARCCFCodeAuditedHandler - /// \#pragma clang arc_cf_code_audited begin/end struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} @@ -1790,7 +1790,7 @@ void Preprocessor::RegisterBuiltinPragmas() { ModuleHandler->AddPragma(new PragmaModuleEndHandler()); ModuleHandler->AddPragma(new PragmaModuleBuildHandler()); ModuleHandler->AddPragma(new PragmaModuleLoadHandler()); - + // Add region pragmas. AddPragmaHandler(new PragmaRegionHandler("region")); AddPragmaHandler(new PragmaRegionHandler("endregion")); diff --git a/lib/Lex/PreprocessingRecord.cpp b/lib/Lex/PreprocessingRecord.cpp index b59820003b56a..b37a8cf1ced49 100644 --- a/lib/Lex/PreprocessingRecord.cpp +++ b/lib/Lex/PreprocessingRecord.cpp @@ -67,7 +67,7 @@ PreprocessingRecord::getPreprocessedEntitiesInRange(SourceRange Range) { } std::pair<int, int> Res = getPreprocessedEntitiesInRangeSlow(Range); - + CachedRangeQuery.Range = Range; CachedRangeQuery.Result = Res; @@ -138,28 +138,28 @@ std::pair<int, int> PreprocessingRecord::getPreprocessedEntitiesInRangeSlow(SourceRange Range) { assert(Range.isValid()); assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); - + std::pair<unsigned, unsigned> Local = findLocalPreprocessedEntitiesInRange(Range); - + // Check if range spans local entities. if (!ExternalSource || SourceMgr.isLocalSourceLocation(Range.getBegin())) return std::make_pair(Local.first, Local.second); - + std::pair<unsigned, unsigned> Loaded = ExternalSource->findPreprocessedEntitiesInRange(Range); - + // Check if range spans local entities. if (Loaded.first == Loaded.second) return std::make_pair(Local.first, Local.second); - + unsigned TotalLoaded = LoadedPreprocessedEntities.size(); - + // Check if range spans loaded entities. if (Local.first == Local.second) return std::make_pair(int(Loaded.first)-TotalLoaded, int(Loaded.second)-TotalLoaded); - + // Range spands loaded and local entities. return std::make_pair(int(Loaded.first)-TotalLoaded, Local.second); } @@ -324,7 +324,7 @@ void PreprocessingRecord::SetExternalSource( unsigned PreprocessingRecord::allocateLoadedEntities(unsigned NumEntities) { unsigned Result = LoadedPreprocessedEntities.size(); - LoadedPreprocessedEntities.resize(LoadedPreprocessedEntities.size() + LoadedPreprocessedEntities.resize(LoadedPreprocessedEntities.size() + NumEntities); return Result; } @@ -371,7 +371,7 @@ PreprocessedEntity *PreprocessingRecord::getPreprocessedEntity(PPEntityID PPID){ /// Retrieve the loaded preprocessed entity at the given index. PreprocessedEntity * PreprocessingRecord::getLoadedPreprocessedEntity(unsigned Index) { - assert(Index < LoadedPreprocessedEntities.size() && + assert(Index < LoadedPreprocessedEntities.size() && "Out-of bounds loaded preprocessed entity"); assert(ExternalSource && "No external source to load from"); PreprocessedEntity *&Entity = LoadedPreprocessedEntities[Index]; @@ -471,27 +471,27 @@ void PreprocessingRecord::InclusionDirective( const FileEntry *File, StringRef SearchPath, StringRef RelativePath, - const Module *Imported, + const Module *Imported, SrcMgr::CharacteristicKind FileType) { InclusionDirective::InclusionKind Kind = InclusionDirective::Include; - + switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { - case tok::pp_include: - Kind = InclusionDirective::Include; + case tok::pp_include: + Kind = InclusionDirective::Include; break; - - case tok::pp_import: - Kind = InclusionDirective::Import; + + case tok::pp_import: + Kind = InclusionDirective::Import; break; - - case tok::pp_include_next: - Kind = InclusionDirective::IncludeNext; + + case tok::pp_include_next: + Kind = InclusionDirective::IncludeNext; break; - - case tok::pp___include_macros: + + case tok::pp___include_macros: Kind = InclusionDirective::IncludeMacros; break; - + default: llvm_unreachable("Unknown include directive kind"); } diff --git a/lib/Lex/Preprocessor.cpp b/lib/Lex/Preprocessor.cpp index 0217a2e60ede8..def47b2f1095b 100644 --- a/lib/Lex/Preprocessor.cpp +++ b/lib/Lex/Preprocessor.cpp @@ -95,12 +95,12 @@ Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, TUKind(TUKind), SkipMainFilePreamble(0, true), CurSubmoduleState(&NullSubmoduleState) { OwnsHeaderSearch = OwnsHeaders; - + // Default to discarding comments. KeepComments = false; KeepMacroComments = false; SuppressIncludeNotFoundError = false; - + // Macro expansion is enabled. DisableMacroExpansion = false; MacroExpansionInDirectivesOverride = false; @@ -127,10 +127,10 @@ Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, // Initialize the pragma handlers. RegisterBuiltinPragmas(); - + // Initialize builtin macros like __LINE__ and friends. RegisterBuiltinMacros(); - + if(LangOpts.Borland) { Ident__exception_info = getIdentifierInfo("_exception_info"); Ident___exception_info = getIdentifierInfo("__exception_info"); @@ -379,7 +379,7 @@ void Preprocessor::recomputeCurLexerKind() { CurLexerKind = CLK_PTHLexer; else if (CurTokenLexer) CurLexerKind = CLK_TokenLexer; - else + else CurLexerKind = CLK_CachingLexer; } @@ -772,7 +772,7 @@ bool Preprocessor::HandleIdentifier(Token &Identifier) { if (IsSpecialVariadicMacro) II.setIsPoisoned(CurrentIsPoisoned); } - + // If this identifier was poisoned, and if it was not produced from a macro // expansion, emit an error. if (II.isPoisoned() && CurPPLexer) { @@ -818,7 +818,7 @@ bool Preprocessor::HandleIdentifier(Token &Identifier) { // like "#define TY typeof", "TY(1) x". if (II.isExtensionToken() && !DisableMacroExpansion) Diag(Identifier, diag::ext_token_used); - + // If this is the 'import' contextual keyword following an '@', note // that the next token indicates a module name. // @@ -881,15 +881,15 @@ void Preprocessor::Lex(Token &Result) { void Preprocessor::LexAfterModuleImport(Token &Result) { // Figure out what kind of lexer we actually have. recomputeCurLexerKind(); - + // Lex the next token. Lex(Result); - // The token sequence + // The token sequence // // import identifier (. identifier)* // - // indicates a module import directive. We already saw the 'import' + // indicates a module import directive. We already saw the 'import' // contextual keyword, so now we're looking for the identifiers. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { // We expected to see an identifier here, and we did; continue handling @@ -900,7 +900,7 @@ void Preprocessor::LexAfterModuleImport(Token &Result) { CurLexerKind = CLK_LexAfterModuleImport; return; } - + // If we're expecting a '.' or a ';', and we got a '.', then wait until we // see the next identifier. (We can also see a '[[' that begins an // attribute-specifier-seq here under the C++ Modules TS.) @@ -1056,7 +1056,7 @@ CodeCompletionHandler::~CodeCompletionHandler() = default; void Preprocessor::createPreprocessingRecord() { if (Record) return; - + Record = new PreprocessingRecord(getSourceManager()); addPPCallbacks(std::unique_ptr<PPCallbacks>(Record)); } diff --git a/lib/Lex/TokenLexer.cpp b/lib/Lex/TokenLexer.cpp index 184b1b390287a..608e0dedebb7e 100644 --- a/lib/Lex/TokenLexer.cpp +++ b/lib/Lex/TokenLexer.cpp @@ -248,7 +248,7 @@ void TokenLexer::ExpandFunctionArguments() { ActualArgs->invokedWithVariadicArgument(Macro); VAOptExpansionContext VCtx(PP); - + for (unsigned I = 0, E = NumTokens; I != E; ++I) { const Token &CurTok = Tokens[I]; // We don't want a space for the next token after a paste @@ -268,7 +268,7 @@ void TokenLexer::ExpandFunctionArguments() { ++I; // Skip the l_paren VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(), ResultToks.size()); - + continue; } @@ -336,14 +336,14 @@ void TokenLexer::ExpandFunctionArguments() { } // If we found the stringify operator, get the argument stringified. The - // preprocessor already verified that the following token is a macro + // preprocessor already verified that the following token is a macro // parameter or __VA_OPT__ when the #define was lexed. - + if (CurTok.isOneOf(tok::hash, tok::hashat)) { int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo()); assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) && "Token following # is not an argument or __VA_OPT__!"); - + if (ArgNo == -1) { // Handle the __VA_OPT__ case. VCtx.sawHashOrHashAtBefore(NextTokGetsSpace, @@ -706,7 +706,7 @@ bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream, if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) && TokenStream[CurIdx - 2].is(tok::hashhash)) LHSTok.clearFlag(Token::LeadingSpace); - + SmallString<128> Buffer; const char *ResultTokStrPtr = nullptr; SourceLocation StartLoc = LHSTok.getLocation(); @@ -845,7 +845,7 @@ bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream, // Transfer properties of the LHS over the Result. Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine()); Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace()); - + // Finally, replace LHS with the result, consume the RHS, and iterate. ++CurIdx; LHSTok = Result; @@ -868,7 +868,7 @@ bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream, StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin(); while (SM.getFileID(EndLoc) != MacroFID) EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd(); - + LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc, LHSTok.getLength())); @@ -927,7 +927,7 @@ TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const { assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() && "Not appropriate for token streams"); assert(loc.isValid() && loc.isFileID()); - + SourceManager &SM = PP.getSourceManager(); assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) && "Expected loc to come from the macro definition"); @@ -1019,7 +1019,7 @@ void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc, SourceLocation InstLoc = getExpansionLocForMacroDefLoc(ArgIdSpellLoc); - + while (begin_tokens < end_tokens) { // If there's only one token just create a SLocEntry for it. if (end_tokens - begin_tokens == 1) { diff --git a/lib/Parse/ParseAST.cpp b/lib/Parse/ParseAST.cpp index 696506099e589..e71b5a9d1e6d0 100644 --- a/lib/Parse/ParseAST.cpp +++ b/lib/Parse/ParseAST.cpp @@ -107,7 +107,7 @@ void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer, // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get()); - + ParseAST(*S.get(), PrintStats, SkipFunctionBodies); } @@ -166,7 +166,7 @@ void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) { // Process any TopLevelDecls generated by #pragma weak. for (Decl *D : S.WeakTopLevelDecls()) Consumer->HandleTopLevelDecl(DeclGroupRef(D)); - + Consumer->HandleTranslationUnit(S.getASTContext()); // Finalize the template instantiation observer chain. diff --git a/lib/Parse/ParseCXXInlineMethods.cpp b/lib/Parse/ParseCXXInlineMethods.cpp index 27d48be0e3eb7..5898120cab461 100644 --- a/lib/Parse/ParseCXXInlineMethods.cpp +++ b/lib/Parse/ParseCXXInlineMethods.cpp @@ -590,9 +590,9 @@ void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { if (!Class.LateParsedDeclarations.empty()) { // C++11 [expr.prim.general]p4: - // Otherwise, if a member-declarator declares a non-static data member + // Otherwise, if a member-declarator declares a non-static data member // (9.2) of a class X, the expression this is a prvalue of type "pointer - // to X" within the optional brace-or-equal-initializer. It shall not + // to X" within the optional brace-or-equal-initializer. It shall not // appear elsewhere in the member-declarator. Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, /*TypeQuals=*/(unsigned)0); @@ -601,7 +601,7 @@ void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers(); } } - + if (!AlreadyHasClassScope) Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); @@ -627,7 +627,7 @@ void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) { Actions.ActOnStartCXXInClassMemberInitializer(); - ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, + ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, EqualLoc); Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 4f6bb08bdc64f..6e57c7bbba913 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -757,7 +757,7 @@ void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) { if (!getLangOpts().ObjC1) Diag(AttrNameLoc, diag::ext_nullability) << AttrName; - attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, + attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, ParsedAttr::AS_Keyword); break; } @@ -867,7 +867,7 @@ VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } - + // Warn if separators, be it '.' or '_', do not match. if (AfterMajorSeparator != AfterMinorSeparator) Diag(Tok, diag::warn_expected_consistent_version_separator); @@ -1047,7 +1047,7 @@ void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, continue; } } - + SourceRange VersionRange; VersionTuple Version = ParseVersionTuple(VersionRange); @@ -1259,7 +1259,7 @@ void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, Diag(Tok, diag::err_expected) << tok::l_paren; return; } - + // Parse the related class name. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_objcbridge_related_expected_related_class); @@ -1292,7 +1292,7 @@ void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SkipUntil(tok::r_paren, StopAtSemi); return; } - + // Parse instance method name. Also non-optional but empty string is // permitted. IdentifierLoc *InstanceMethod = nullptr; @@ -1303,14 +1303,14 @@ void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SkipUntil(tok::r_paren, StopAtSemi); return; } - + // Closing ')'. if (T.consumeClose()) return; - + if (endLoc) *endLoc = T.getCloseLocation(); - + // Record this attribute attrs.addNew(&ObjCBridgeRelated, SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()), @@ -2032,7 +2032,7 @@ Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, DeclsInGroup.push_back(FirstDecl); bool ExpectSemi = Context != DeclaratorContext::ForContext; - + // If we don't have a comma, it is either the end of the list (a ';') or an // error, bail out. SourceLocation CommaLoc; @@ -3815,7 +3815,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, PrevSpec, DiagID, Type.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; - + DS.SetRangeEnd(EndLoc); } else { DS.SetTypeSpecError(); @@ -5627,7 +5627,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { } else { AllowConstructorName = (D.getContext() == DeclaratorContext::MemberContext); - AllowDeductionGuide = + AllowDeductionGuide = (D.getContext() == DeclaratorContext::FileContext || D.getContext() == DeclaratorContext::MemberContext); } @@ -6082,13 +6082,13 @@ void Parser::ParseFunctionDeclarator(Declarator &D, LocalEndLoc = RParenLoc; EndLoc = RParenLoc; - // If there are attributes following the identifier list, parse them and + // If there are attributes following the identifier list, parse them and // prohibit them. MaybeParseCXX11Attributes(FnAttrs); ProhibitAttributes(FnAttrs); } else { if (Tok.isNot(tok::r_paren)) - ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, + ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc); else if (RequiresArg) Diag(Tok, diag::err_argument_required_after_attribute); @@ -6391,8 +6391,8 @@ void Parser::ParseParameterDeclarationClause( ParseDeclarationSpecifiers(DS); - // Parse the declarator. This is "PrototypeContext" or - // "LambdaExprParameterContext", because we must accept either + // Parse the declarator. This is "PrototypeContext" or + // "LambdaExprParameterContext", because we must accept either // 'declarator' or 'abstract-declarator' here. Declarator ParmDeclarator( DS, D.getContext() == DeclaratorContext::LambdaExprContext @@ -6484,7 +6484,7 @@ void Parser::ParseParameterDeclarationClause( } ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, - ParmDeclarator.getIdentifierLoc(), + ParmDeclarator.getIdentifierLoc(), Param, std::move(DefArgToks))); } diff --git a/lib/Parse/ParseDeclCXX.cpp b/lib/Parse/ParseDeclCXX.cpp index 7c4c83d032b66..9ba44d07aba86 100644 --- a/lib/Parse/ParseDeclCXX.cpp +++ b/lib/Parse/ParseDeclCXX.cpp @@ -61,7 +61,7 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. ObjCDeclContextSwitch ObjCDC(*this); - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteNamespaceDecl(getCurScope()); cutOffParsing(); @@ -130,8 +130,8 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, return nullptr; } - if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || - getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || + if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || + getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || getCurScope()->getFnParent()) { Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope); SkipUntil(tok::r_brace); @@ -190,7 +190,7 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl, NamespaceLoc, "parsing namespace"); - // Parse the contents of the namespace. This includes parsing recovery on + // Parse the contents of the namespace. This includes parsing recovery on // any improperly nested namespaces. ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0, InlineLoc, attrs, T); @@ -200,8 +200,8 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, DeclEnd = T.getCloseLocation(); Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd); - - return Actions.ConvertDeclToDeclGroup(NamespcDecl, + + return Actions.ConvertDeclToDeclGroup(NamespcDecl, ImplicitUsingDirectiveDecl); } @@ -236,7 +236,7 @@ void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc, getCurScope(), SourceLocation(), NamespaceLoc[index], IdentLoc[index], Ident[index], Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl); - assert(!ImplicitUsingDirectiveDecl && + assert(!ImplicitUsingDirectiveDecl && "nested namespace definition cannot define anonymous namespace"); ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc, @@ -438,7 +438,7 @@ Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context, ParsedAttributesWithRange &attrs) { assert(Tok.is(tok::kw_using) && "Not using token"); ObjCDeclContextSwitch ObjCDC(*this); - + // Eat 'using'. SourceLocation UsingLoc = ConsumeToken(); @@ -896,7 +896,7 @@ Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype) && "Not a decltype specifier"); - + ExprResult Result; SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc; @@ -999,7 +999,7 @@ SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { return EndLoc; } -void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, +void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, SourceLocation StartLoc, SourceLocation EndLoc) { // make sure we have a token we can turn into an annotation token @@ -1050,9 +1050,9 @@ void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) { } /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a -/// class name or decltype-specifier. Note that we only check that the result -/// names a type; semantic analysis will need to verify that the type names a -/// class. The result is either a type or null, depending on whether a type +/// class name or decltype-specifier. Note that we only check that the result +/// names a type; semantic analysis will need to verify that the type names a +/// class. The result is either a type or null, depending on whether a type /// name was found. /// /// base-type-specifier: [C++11 class.derived] @@ -1083,7 +1083,7 @@ TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, BaseLoc = Tok.getLocation(); // Parse decltype-specifier - // tok == kw_decltype is just error recovery, it can only happen when SS + // tok == kw_decltype is just error recovery, it can only happen when SS // isn't empty if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) { if (SS.isNotEmpty()) @@ -1348,8 +1348,8 @@ bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) { void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation StartLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, - AccessSpecifier AS, - bool EnteringContext, DeclSpecContext DSC, + AccessSpecifier AS, + bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes) { DeclSpec::TST TagType; if (TagTokKind == tok::kw_struct) @@ -2061,7 +2061,7 @@ BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { if (BaseType.isInvalid()) return true; - // Parse the optional ellipsis (for a pack expansion). The ellipsis is + // Parse the optional ellipsis (for a pack expansion). The ellipsis is // actually part of the base-specifier-list grammar productions, but we // parse it here for convenience. SourceLocation EllipsisLoc; @@ -2229,7 +2229,7 @@ void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool Parser::isCXX11FinalKeyword() const { VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(); return Specifier == VirtSpecifiers::VS_Final || - Specifier == VirtSpecifiers::VS_GNU_Final || + Specifier == VirtSpecifiers::VS_GNU_Final || Specifier == VirtSpecifiers::VS_Sealed; } @@ -2397,7 +2397,7 @@ void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq( /// override /// final /// [MS] sealed -/// +/// /// pure-specifier: /// '= 0' /// @@ -2648,9 +2648,9 @@ Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, } DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind); - // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains + // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains // to a friend declaration, that declaration shall be a definition. - if (DeclaratorInfo.isFunctionDeclarator() && + if (DeclaratorInfo.isFunctionDeclarator() && DefinitionKind != FDK_Definition && DS.isFriendSpecified()) { // Diagnose attributes that appear before decl specifier: // [[]] friend int foo(); @@ -3142,7 +3142,7 @@ void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok); assert((Specifier == VirtSpecifiers::VS_Final || - Specifier == VirtSpecifiers::VS_GNU_Final || + Specifier == VirtSpecifiers::VS_GNU_Final || Specifier == VirtSpecifiers::VS_Sealed) && "not a class definition"); FinalLoc = ConsumeToken(); @@ -3457,7 +3457,7 @@ MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { TryConsumeToken(tok::ellipsis, EllipsisLoc); return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, - TemplateTypeTy, DS, IdLoc, + TemplateTypeTy, DS, IdLoc, InitList.get(), EllipsisLoc); } else if(Tok.is(tok::l_paren)) { BalancedDelimiterTracker T(*this, tok::l_paren); @@ -3506,7 +3506,7 @@ Parser::tryParseExceptionSpecification(bool Delayed, CachedTokens *&ExceptionSpecTokens) { ExceptionSpecificationType Result = EST_None; ExceptionSpecTokens = nullptr; - + // Handle delayed parsing of exception-specifications. if (Delayed) { if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept)) @@ -3525,11 +3525,11 @@ Parser::tryParseExceptionSpecification(bool Delayed, NoexceptExpr = nullptr; return EST_BasicNoexcept; } - + Diag(Tok, diag::err_expected_lparen_after) << "throw"; return EST_DynamicNone; } - + // Cache the tokens for the exception-specification. ExceptionSpecTokens = new CachedTokens; ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept' @@ -3543,7 +3543,7 @@ Parser::tryParseExceptionSpecification(bool Delayed, return EST_Unparsed; } - + // See if there's a dynamic specification. if (Tok.is(tok::kw_throw)) { Result = ParseDynamicExceptionSpecification(SpecificationRange, @@ -3660,7 +3660,7 @@ ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( if (Tok.is(tok::ellipsis)) { // C++0x [temp.variadic]p5: - // - In a dynamic-exception-specification (15.4); the pattern is a + // - In a dynamic-exception-specification (15.4); the pattern is a // type-id. SourceLocation Ellipsis = ConsumeToken(); Range.setEnd(Ellipsis); @@ -4207,7 +4207,7 @@ void Parser::ParseMicrosoftIfExistsClassDeclaration( IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; - + BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; @@ -4218,13 +4218,13 @@ void Parser::ParseMicrosoftIfExistsClassDeclaration( case IEB_Parse: // Parse the declarations below. break; - + case IEB_Dependent: Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) << Result.IsIfExists; // Fall through to skip. LLVM_FALLTHROUGH; - + case IEB_Skip: Braces.skipToEnd(); return; @@ -4262,6 +4262,6 @@ void Parser::ParseMicrosoftIfExistsClassDeclaration( // Parse all the comma separated declarators. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs); } - + Braces.consumeClose(); } diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 4a0e1c5e34130..2a65eec8a0f63 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -441,7 +441,7 @@ Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { // is okay, to bind exactly as tightly. For example, compile A=B=C=D as // A=(B=(C=D)), where each paren is a level of recursion here. // The function takes ownership of the RHS. - RHS = ParseRHSOfBinaryExpression(RHS, + RHS = ParseRHSOfBinaryExpression(RHS, static_cast<prec::Level>(ThisPrec + !isRightAssoc)); RHSIsInitList = false; @@ -656,14 +656,14 @@ class CastExpressionIdValidator : public CorrectionCandidateCallback { /// /// id-expression: [C++ 5.1] /// unqualified-id -/// qualified-id +/// qualified-id /// /// unqualified-id: [C++ 5.1] /// identifier /// operator-function-id /// conversion-function-id -/// '~' class-name -/// template-id +/// '~' class-name +/// template-id /// /// new-expression: [C++ 5.3.4] /// '::'[opt] 'new' new-placement[opt] new-type-id @@ -729,7 +729,7 @@ class CastExpressionIdValidator : public CorrectionCandidateCallback { /// '__trivially_copyable' /// /// binary-type-trait: -/// [GNU] '__is_base_of' +/// [GNU] '__is_base_of' /// [MS] '__is_convertible_to' /// '__is_convertible' /// '__is_same' @@ -789,6 +789,10 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, // We have parsed the cast-expression and no postfix-expr pieces are // following. return Res; + case FoldExpr: + // We only parsed a fold-expression. There might be postfix-expr pieces + // afterwards; parse them now. + break; } break; @@ -807,7 +811,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, case tok::kw_false: Res = ParseCXXBoolLiteral(); break; - + case tok::kw___objc_yes: case tok::kw___objc_no: return ParseObjCBoolLiteral(); @@ -831,7 +835,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, return ExprError(); assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super)); return ParseCastExpression(isUnaryExpression, isAddressOfOperand); - + case tok::identifier: { // primary-expression: identifier // unqualified-id: identifier // constant: enumeration-constant @@ -953,14 +957,14 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, return ExprError(); } // Allow either an identifier or the keyword 'class' (in C++). - if (Tok.isNot(tok::identifier) && + if (Tok.isNot(tok::identifier) && !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) { Diag(Tok, diag::err_expected_property_name); return ExprError(); } IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); SourceLocation PropertyLoc = ConsumeToken(); - + Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, ILoc, PropertyLoc); break; @@ -969,7 +973,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, // In an Objective-C method, if we have "super" followed by an identifier, // the token sequence is ill-formed. However, if there's a ':' or ']' after // that identifier, this is probably a message send with a missing open - // bracket. Treat it as such. + // bracket. Treat it as such. if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression && getCurScope()->isInObjcMethodScope() && ((Tok.is(tok::identifier) && @@ -979,17 +983,17 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, nullptr); break; } - + // If we have an Objective-C class name followed by an identifier // and either ':' or ']', this is an Objective-C class message // send that's missing the opening '['. Recovery // appropriately. Also take this path if we're performing code // completion after an Objective-C class name. - if (getLangOpts().ObjC1 && - ((Tok.is(tok::identifier) && !InMessageExpression) || + if (getLangOpts().ObjC1 && + ((Tok.is(tok::identifier) && !InMessageExpression) || Tok.is(tok::code_completion))) { const Token& Next = NextToken(); - if (Tok.is(tok::code_completion) || + if (Tok.is(tok::code_completion) || Next.is(tok::colon) || Next.is(tok::r_square)) if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) if (Typ.get()->isObjCObjectOrInterfaceType()) { @@ -1001,24 +1005,24 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, unsigned DiagID; DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ, Actions.getASTContext().getPrintingPolicy()); - + Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext); - TypeResult Ty = Actions.ActOnTypeName(getCurScope(), + TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); if (Ty.isInvalid()) break; - Res = ParseObjCMessageExpressionBody(SourceLocation(), - SourceLocation(), + Res = ParseObjCMessageExpressionBody(SourceLocation(), + SourceLocation(), Ty.get(), nullptr); break; } } - + // Make sure to pass down the right value for isAddressOfOperand. if (isAddressOfOperand && isPostfixExpressionSuffixStart()) isAddressOfOperand = false; - + // Function designators are allowed to be undeclared (C99 6.5.1p2), so we // need to know whether or not this identifier is a function designator or // not. @@ -1175,7 +1179,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, if (getCurScope()->getFnParent() == nullptr) return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); - + Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), Tok.getLocation()); @@ -1380,7 +1384,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, T.consumeClose(); if (!Result.isInvalid()) - Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), + Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Result.get(), T.getCloseLocation()); return Result; } @@ -1389,7 +1393,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, case tok::kw_##Spelling: #include "clang/Basic/TokenKinds.def" return ParseTypeTrait(); - + case tok::kw___array_rank: case tok::kw___array_extent: return ParseArrayTypeTrait(); @@ -1397,7 +1401,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, case tok::kw___is_lvalue_expr: case tok::kw___is_rvalue_expr: return ParseExpressionTrait(); - + case tok::at: { SourceLocation AtLoc = ConsumeToken(); return ParseObjCAtExpression(AtLoc); @@ -1485,16 +1489,16 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { case tok::code_completion: if (InMessageExpression) return LHS; - + Actions.CodeCompletePostfixExpression(getCurScope(), LHS); cutOffParsing(); return ExprError(); - + case tok::identifier: // If we see identifier: after an expression, and we're not already in a // message send, then this is probably a message send with a missing // opening bracket '['. - if (getLangOpts().ObjC1 && !InMessageExpression && + if (getLangOpts().ObjC1 && !InMessageExpression && (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), nullptr, LHS.get()); @@ -1616,8 +1620,8 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { if (!LHS.isInvalid()) { ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), - OpenLoc, - ExecConfigExprs, + OpenLoc, + ExecConfigExprs, CloseLoc); if (ECResult.isInvalid()) LHS = ExprError(); @@ -1631,7 +1635,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { ExprVector ArgExprs; CommaLocsTy CommaLocs; - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteCall(getCurScope(), LHS.get(), None); cutOffParsing(); @@ -1671,7 +1675,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { PT.consumeClose(); LHS = ExprError(); } else { - assert((ArgExprs.size() == 0 || + assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc, @@ -1712,7 +1716,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { if (LHS.isInvalid()) break; - ParseOptionalCXXScopeSpecifier(SS, ObjectType, + ParseOptionalCXXScopeSpecifier(SS, ObjectType, /*EnteringContext=*/false, &MayBePseudoDestructor); if (SS.isNotEmpty()) @@ -1745,7 +1749,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { } if (MayBePseudoDestructor && !LHS.isInvalid()) { - LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, + LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, ObjectType); break; } @@ -1766,24 +1770,24 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { // 'class' as if it were an identifier. // // This hack allows property access to the 'class' method because it is - // such a common method name. For other C++ keywords that are + // such a common method name. For other C++ keywords that are // Objective-C method names, one must use the message send syntax. IdentifierInfo *Id = Tok.getIdentifierInfo(); SourceLocation Loc = ConsumeToken(); Name.setIdentifier(Id, Loc); - } else if (ParseUnqualifiedId(SS, - /*EnteringContext=*/false, + } else if (ParseUnqualifiedId(SS, + /*EnteringContext=*/false, /*AllowDestructorName=*/true, /*AllowConstructorName=*/ - getLangOpts().MicrosoftExt, + getLangOpts().MicrosoftExt, /*AllowDeductionGuide=*/false, ObjectType, &TemplateKWLoc, Name)) { (void)Actions.CorrectDelayedTyposInExpr(LHS); LHS = ExprError(); } - + if (!LHS.isInvalid()) - LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, + LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, OpKind, SS, TemplateKWLoc, Name, CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : nullptr); @@ -1878,7 +1882,7 @@ Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, ParenParseOption ExprType = CastExpr; SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; - Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, + Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, false, CastTy, RParenLoc); CastRange = SourceRange(LParenLoc, RParenLoc); @@ -1892,7 +1896,7 @@ Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { // GNU typeof in C requires the expression to be parenthesized. Not so for // sizeof/alignof or in C++. Therefore, the parenthesized expression is - // the start of a unary-expression, but doesn't include any postfix + // the start of a unary-expression, but doesn't include any postfix // pieces. Parse these now if present. if (!Operand.isInvalid()) Operand = ParsePostfixExpressionSuffix(Operand.get()); @@ -1958,7 +1962,7 @@ ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { } else { Diag(Tok, diag::err_sizeof_parameter_pack); } - + if (!Name) return ExprError(); @@ -1967,7 +1971,7 @@ ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { Sema::ReuseLambdaContextDecl); return Actions.ActOnSizeofParameterPackExpr(getCurScope(), - OpTok.getLocation(), + OpTok.getLocation(), *Name, NameLoc, RParenLoc); } @@ -2202,15 +2206,15 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { TypeResult DestTy = ParseTypeName(); if (DestTy.isInvalid()) return ExprError(); - + // Attempt to consume the r-paren. if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } - - Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc, + + Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc, ConsumeParen()); break; } @@ -2231,15 +2235,15 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { TypeResult DestTy = ParseTypeName(); if (DestTy.isInvalid()) return ExprError(); - + // Attempt to consume the r-paren. if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } - - Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc, + + Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc, ConsumeParen()); break; } @@ -2294,7 +2298,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, CastTy = nullptr; if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteOrdinaryName(getCurScope(), + Actions.CodeCompleteOrdinaryName(getCurScope(), ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression : Sema::PCC_Expression); cutOffParsing(); @@ -2318,7 +2322,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, } BridgeCast = false; } - + // None of these cases should fall through with an invalid Result // unless they've already reported an error. if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { @@ -2372,16 +2376,16 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained"); } - + TypeResult Ty = ParseTypeName(); T.consumeClose(); ColonProtection.restore(); RParenLoc = T.getCloseLocation(); ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false); - + if (Ty.isInvalid() || SubExpr.isInvalid()) return ExprError(); - + return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind, BridgeKeywordLoc, Ty.get(), RParenLoc, SubExpr.get()); @@ -2407,8 +2411,8 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, ParseSpecifierQualifierList(DS); Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext); ParseDeclarator(DeclaratorInfo); - - // If our type is followed by an identifier and either ':' or ']', then + + // If our type is followed by an identifier and either ':' or ']', then // this is probably an Objective-C message send where the leading '[' is // missing. Recover as if that were the case. if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) && @@ -2419,10 +2423,10 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, InMessageExpressionRAIIObject InMessage(*this, false); Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } - Result = ParseObjCMessageExpressionBody(SourceLocation(), - SourceLocation(), + Result = ParseObjCMessageExpressionBody(SourceLocation(), + SourceLocation(), Ty.get(), nullptr); - } else { + } else { // Match the ')'. T.consumeClose(); ColonProtection.restore(); @@ -2499,7 +2503,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, // Reject the cast of super idiom in ObjC. if (Tok.is(tok::identifier) && getLangOpts().ObjC1 && - Tok.getIdentifierInfo() == Ident_super && + Tok.getIdentifierInfo() == Ident_super && getCurScope()->isInObjcMethodScope() && GetLookAheadToken(1).isNot(tok::period)) { Diag(Tok.getLocation(), diag::err_illegal_super_cast) @@ -2514,7 +2518,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, /*isTypeCast=*/IsTypeCast); if (!Result.isInvalid()) { Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, - DeclaratorInfo, CastTy, + DeclaratorInfo, CastTy, RParenLoc, Result.get()); } return Result; @@ -2523,8 +2527,9 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, Diag(Tok, diag::err_expected_lbrace_in_compound_literal); return ExprError(); } - } else if (Tok.is(tok::ellipsis) && + } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) && isFoldOperator(NextToken().getKind())) { + ExprType = FoldExpr; return ParseFoldExpression(ExprResult(), T); } else if (isTypeCast) { // Parse the expression-list. @@ -2536,9 +2541,11 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) { // FIXME: If we ever support comma expressions as operands to // fold-expressions, we'll need to allow multiple ArgExprs here. - if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) && - NextToken().is(tok::ellipsis)) + if (ExprType >= FoldExpr && ArgExprs.size() == 1 && + isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) { + ExprType = FoldExpr; return ParseFoldExpression(ArgExprs[0], T); + } ExprType = SimpleExpr; Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), @@ -2553,10 +2560,13 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, // expressions are parsed correctly. Result = Actions.CorrectDelayedTyposInExpr(Result); } - ExprType = SimpleExpr; - if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) + if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) && + NextToken().is(tok::ellipsis)) { + ExprType = FoldExpr; return ParseFoldExpression(Result, T); + } + ExprType = SimpleExpr; // Don't build a paren expression unless we actually match a ')'. if (!Result.isInvalid() && Tok.is(tok::r_paren)) @@ -2712,7 +2722,7 @@ ExprResult Parser::ParseGenericSelectionExpression() { if (T.getCloseLocation().isInvalid()) return ExprError(); - return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, + return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, T.getCloseLocation(), ControllingExpr.get(), Types, Exprs); @@ -2815,7 +2825,7 @@ bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, Expr = ParseAssignmentExpression(); if (Tok.is(tok::ellipsis)) - Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); + Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); if (Expr.isInvalid()) { SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch); SawError = true; @@ -2882,7 +2892,7 @@ void Parser::ParseBlockId(SourceLocation CaretLoc) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); return cutOffParsing(); } - + // Parse the specifier-qualifier-list piece. DeclSpec DS(AttrFactory); ParseSpecifierQualifierList(DS); diff --git a/lib/Parse/ParseExprCXX.cpp b/lib/Parse/ParseExprCXX.cpp index 26e75999518af..663c397ee0495 100644 --- a/lib/Parse/ParseExprCXX.cpp +++ b/lib/Parse/ParseExprCXX.cpp @@ -306,13 +306,13 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, } // If the next token is not '<', we have a qualified-id that refers - // to a template name, such as T::template apply, but is not a + // to a template name, such as T::template apply, but is not a // template-id. if (Tok.isNot(tok::less)) { TPA.Revert(); break; - } - + } + // Commit to parsing the template-id. TPA.Commit(); TemplateTy Template; @@ -366,7 +366,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, TemplateId->RAngleLoc, CCLoc, EnteringContext)) { - SourceLocation StartLoc + SourceLocation StartLoc = SS.getBeginLoc().isValid()? SS.getBeginLoc() : TemplateId->TemplateNameLoc; SS.SetInvalid(SourceRange(StartLoc, CCLoc)); @@ -480,7 +480,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, UnqualifiedId TemplateName; TemplateName.setIdentifier(&II, Tok.getLocation()); bool MemberOfUnknownSpecialization; - if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, + if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, TemplateName, ObjectType, @@ -500,16 +500,16 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, continue; } - if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && + if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && (IsTypename || IsTemplateArgumentList(1))) { - // We have something like t::getAs<T>, where getAs is a + // We have something like t::getAs<T>, where getAs is a // member of an unknown specialization. However, this will only // parse correctly as a template, so suggest the keyword 'template' // before 'getAs' and treat this as a dependent template name. unsigned DiagID = diag::err_missing_dependent_template_keyword; if (getLangOpts().MicrosoftExt) DiagID = diag::warn_missing_dependent_template_keyword; - + Diag(Tok.getLocation(), DiagID) << II.getName() << FixItHint::CreateInsertion(Tok.getLocation(), "template "); @@ -524,9 +524,9 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, return true; } else - return true; - - continue; + return true; + + continue; } } @@ -719,7 +719,7 @@ ExprResult Parser::TryParseLambdaExpression() { if (Next.is(tok::identifier) && After.is(tok::identifier)) { return ExprEmpty(); } - + // Here, we're stuck: lambda introducers and Objective-C message sends are // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of @@ -776,7 +776,7 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, if (Tok.is(tok::code_completion) && !(getLangOpts().ObjC1 && Intro.Default == LCD_None && !Intro.Captures.empty())) { - Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, + Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/false); cutOffParsing(); break; @@ -793,14 +793,14 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, if (getLangOpts().ObjC1 && first) Actions.CodeCompleteObjCMessageReceiver(getCurScope()); else - Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, + Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/false); cutOffParsing(); break; } first = false; - + // Parse capture. LambdaCaptureKind Kind = LCK_ByCopy; LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit; @@ -811,10 +811,10 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, SourceLocation LocStart = Tok.getLocation(); if (Tok.is(tok::star)) { - Loc = ConsumeToken(); + Loc = ConsumeToken(); if (Tok.is(tok::kw_this)) { - ConsumeToken(); - Kind = LCK_StarThis; + ConsumeToken(); + Kind = LCK_StarThis; } else { return DiagResult(diag::err_expected_star_this_capture); } @@ -827,7 +827,7 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, ConsumeToken(); if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, + Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/true); cutOffParsing(); break; @@ -1090,7 +1090,7 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer( PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, "lambda expression parsing"); - + // FIXME: Call into Actions to add any init-capture declarations to the // scope while parsing the lambda-declarator and compound-statement. @@ -1135,13 +1135,13 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer( // Parse parameter-declaration-clause. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; SourceLocation EllipsisLoc; - + if (Tok.isNot(tok::r_paren)) { Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth); ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc); - // For a generic lambda, each 'auto' within the parameter declaration + // For a generic lambda, each 'auto' within the parameter declaration // clause creates a template type parameter, so increment the depth. - if (Actions.getCurGenericLambda()) + if (Actions.getCurGenericLambda()) ++CurTemplateDepthTracker; } T.consumeClose(); @@ -1161,7 +1161,7 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer( SourceLocation ConstexprLoc; tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc, DeclEndLoc); - + addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS); // Parse exception-specification[opt]. @@ -1376,7 +1376,7 @@ ExprResult Parser::ParseCXXCasts() { Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, LAngleBracketLoc, DeclaratorInfo, RAngleBracketLoc, - T.getOpenLocation(), Result.get(), + T.getOpenLocation(), Result.get(), T.getCloseLocation()); return Result; @@ -1477,7 +1477,7 @@ ExprResult Parser::ParseCXXUuidof() { return ExprError(); Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, - Ty.get().getAsOpaquePtr(), + Ty.get().getAsOpaquePtr(), T.getCloseLocation()); } else { EnterExpressionEvaluationContext Unevaluated( @@ -1507,13 +1507,13 @@ ExprResult Parser::ParseCXXUuidof() { /// postfix-expression . pseudo-destructor-name /// postfix-expression -> pseudo-destructor-name /// -/// pseudo-destructor-name: -/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name -/// ::[opt] nested-name-specifier template simple-template-id :: -/// ~type-name +/// pseudo-destructor-name: +/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name +/// ::[opt] nested-name-specifier template simple-template-id :: +/// ~type-name /// ::[opt] nested-name-specifier[opt] ~type-name -/// -ExprResult +/// +ExprResult Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, @@ -1562,13 +1562,13 @@ Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, Diag(Tok, diag::err_destructor_tilde_identifier); return ExprError(); } - + // Parse the second type. UnqualifiedId SecondTypeName; IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = ConsumeToken(); SecondTypeName.setIdentifier(Name, NameLoc); - + // If there is a '<', the second type name is a template-id. Parse // it as such. if (Tok.is(tok::less) && @@ -1821,7 +1821,7 @@ Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt, MaybeParseGNUAttributes(DeclaratorInfo); // Type-check the declaration itself. - DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), + DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), DeclaratorInfo); if (Dcl.isInvalid()) return Sema::ConditionError(); @@ -1909,10 +1909,10 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { getTypeAnnotation(Tok), Policy); else DS.SetTypeSpecError(); - + DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeAnnotationToken(); - + DS.Finish(Actions, Policy); return; } @@ -2009,7 +2009,7 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { } /// Finish parsing a C++ unqualified-id that is a template-id of -/// some form. +/// some form. /// /// This routine is invoked when a '<' is encountered after an identifier or /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine @@ -2023,10 +2023,10 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { /// \param Name for constructor and destructor names, this is the actual /// identifier that may be a template-name. /// -/// \param NameLoc the location of the class-name in a constructor or +/// \param NameLoc the location of the class-name in a constructor or /// destructor. /// -/// \param EnteringContext whether we're entering the scope of the +/// \param EnteringContext whether we're entering the scope of the /// nested-name-specifier. /// /// \param ObjectType if this unqualified-id occurs within a member access @@ -2035,9 +2035,9 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { /// \param Id as input, describes the template-name or operator-function-id /// that precedes the '<'. If template arguments were parsed successfully, /// will be updated with the template-id. -/// +/// /// \param AssumeTemplateId When true, this routine will assume that the name -/// refers to a template without performing name lookup to verify. +/// refers to a template without performing name lookup to verify. /// /// \returns true if a parse error occurred, false otherwise. bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, @@ -2070,10 +2070,10 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, TemplateKWLoc.isValid(), Id, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); - + if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && ObjectType && IsTemplateArgumentList()) { - // We have something like t->getAs<T>(), where getAs is a + // We have something like t->getAs<T>(), where getAs is a // member of an unknown specialization. However, this will only // parse correctly as a template, so suggest the keyword 'template' // before 'getAs' and treat this as a dependent template name. @@ -2094,22 +2094,22 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext, Template, /*AllowInjectedClassName*/ true); if (TNK == TNK_Non_template) - return true; + return true; } } break; - + case UnqualifiedIdKind::IK_ConstructorName: { UnqualifiedId TemplateName; bool MemberOfUnknownSpecialization; TemplateName.setIdentifier(Name, NameLoc); TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), - TemplateName, ObjectType, + TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); break; } - + case UnqualifiedIdKind::IK_DestructorName: { UnqualifiedId TemplateName; bool MemberOfUnknownSpecialization; @@ -2122,26 +2122,26 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, return true; } else { TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), - TemplateName, ObjectType, + TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); - + if (TNK == TNK_Non_template && !Id.DestructorName.get()) { Diag(NameLoc, diag::err_destructor_template_id) << Name << SS.getRange(); - return true; + return true; } } break; } - + default: return false; } - + if (TNK == TNK_Non_template) return false; - + // Parse the enclosed template argument list. SourceLocation LAngleLoc, RAngleLoc; TemplateArgList TemplateArgs; @@ -2183,12 +2183,12 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, /*IsCtorOrDtorName=*/true); if (Type.isInvalid()) return true; - + if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName) Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); else Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); - + return false; } @@ -2223,7 +2223,7 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, /// \param SS The nested-name-specifier that preceded this unqualified-id. If /// non-empty, then we are parsing the unqualified-id of a qualified-id. /// -/// \param EnteringContext whether we are entering the scope of the +/// \param EnteringContext whether we are entering the scope of the /// nested-name-specifier. /// /// \param ObjectType if this unqualified-id occurs within a member access @@ -2236,10 +2236,10 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result) { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); - + // Consume the 'operator' keyword. SourceLocation KeywordLoc = ConsumeToken(); - + // Determine what kind of operator name we have. unsigned SymbolIdx = 0; SourceLocation SymbolLocations[3]; @@ -2259,7 +2259,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; - + SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = isNew? OO_Array_New : OO_Array_Delete; @@ -2268,7 +2268,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, } break; } - + #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case tok::Token: \ SymbolLocations[SymbolIdx++] = ConsumeToken(); \ @@ -2276,7 +2276,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) #include "clang/Basic/OperatorKinds.def" - + case tok::l_paren: { // Consume the '(' and ')'. BalancedDelimiterTracker T(*this, tok::l_paren); @@ -2284,13 +2284,13 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; - + SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = OO_Call; break; } - + case tok::l_square: { // Consume the '[' and ']'. BalancedDelimiterTracker T(*this, tok::l_square); @@ -2298,25 +2298,25 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; - + SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = OO_Subscript; break; } - + case tok::code_completion: { // Code completion for the operator name. Actions.CodeCompleteOperatorName(getCurScope()); - cutOffParsing(); + cutOffParsing(); // Don't try to parse any further. return true; } - + default: break; } - + if (Op != OO_None) { // We have parsed an operator-function-id. Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); @@ -2409,12 +2409,12 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, // // conversion-declarator: // ptr-operator conversion-declarator[opt] - + // Parse the type-specifier-seq. DeclSpec DS(AttrFactory); if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? return true; - + // Parse the conversion-declarator, which is merely a sequence of // ptr-operators. Declarator D(DS, DeclaratorContext::ConversionIdContext); @@ -2424,11 +2424,11 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); if (Ty.isInvalid()) return true; - + // Note that this is a conversion-function-id. - Result.setConversionFunctionId(KeywordLoc, Ty.get(), + Result.setConversionFunctionId(KeywordLoc, Ty.get(), D.getSourceRange().getEnd()); - return false; + return false; } /// Parse a C++ unqualified-id (or a C identifier), which describes the @@ -2448,7 +2448,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, /// \param SS The nested-name-specifier that preceded this unqualified-id. If /// non-empty, then we are parsing the unqualified-id of a qualified-id. /// -/// \param EnteringContext whether we are entering the scope of the +/// \param EnteringContext whether we are entering the scope of the /// nested-name-specifier. /// /// \param AllowDestructorName whether we allow parsing of a destructor name. @@ -2503,7 +2503,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, } ParsedTemplateTy TemplateName; - if (AllowConstructorName && + if (AllowConstructorName && Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { // We have parsed a constructor name. ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS, @@ -2519,7 +2519,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, Result.setDeductionGuideName(TemplateName, IdLoc); } else { // We have parsed an identifier. - Result.setIdentifier(Id, IdLoc); + Result.setIdentifier(Id, IdLoc); } // If the next token is a '<', we may have a template. @@ -2537,13 +2537,13 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, return false; } - + // unqualified-id: // template-id (already parsed and annotated) if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); - // If the template-name names the current class, then this is a constructor + // If the template-name names the current class, then this is a constructor if (AllowConstructorName && TemplateId->Name && Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { if (SS.isSet()) { @@ -2551,7 +2551,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, // is taken as the constructor name where a constructor can be // declared. Thus, the template arguments are extraneous, so // complain about them and remove them entirely. - Diag(TemplateId->TemplateNameLoc, + Diag(TemplateId->TemplateNameLoc, diag::err_out_of_line_constructor_template_id) << TemplateId->Name << FixItHint::CreateRemoval( @@ -2586,17 +2586,17 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, ConsumeAnnotationToken(); return false; } - + // unqualified-id: // operator-function-id // conversion-function-id if (Tok.is(tok::kw_operator)) { if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) return true; - + // If we have an operator-function-id or a literal-operator-id and the next // token is a '<', we may have a - // + // // template-id: // operator-function-id < template-argument-list[opt] > TemplateTy Template; @@ -2616,14 +2616,14 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, return false; } - - if (getLangOpts().CPlusPlus && + + if (getLangOpts().CPlusPlus && (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { // C++ [expr.unary.op]p10: - // There is an ambiguity in the unary-expression ~X(), where X is a - // class-name. The ambiguity is resolved in favor of treating ~ as a + // There is an ambiguity in the unary-expression ~X(), where X is a + // class-name. The ambiguity is resolved in favor of treating ~ as a // unary complement rather than treating ~X as referring to a destructor. - + // Parse the '~'. SourceLocation TildeLoc = ConsumeToken(); @@ -2637,7 +2637,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, } return true; } - + // Parse the class-name. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_destructor_tilde_identifier); @@ -2688,7 +2688,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, } // Note that this is a destructor name. - ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, + ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, ClassNameLoc, getCurScope(), SS, ObjectType, EnteringContext); @@ -2698,7 +2698,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); return false; } - + Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; return true; @@ -3002,7 +3002,7 @@ static unsigned TypeTraitArity(tok::TokenKind kind) { } } -/// Parse the built-in type-trait pseudo-functions that allow +/// Parse the built-in type-trait pseudo-functions that allow /// implementation of the TR1/C++11 type traits templates. /// /// primary-expression: @@ -3018,7 +3018,7 @@ ExprResult Parser::ParseTypeTrait() { unsigned Arity = TypeTraitArity(Kind); SourceLocation Loc = ConsumeToken(); - + BalancedDelimiterTracker Parens(*this, tok::l_paren); if (Parens.expectAndConsume()) return ExprError(); @@ -3040,7 +3040,7 @@ ExprResult Parser::ParseTypeTrait() { return ExprError(); } } - + // Add this type to the list of arguments. Args.push_back(Ty.get()); } while (TryConsumeToken(tok::comma)); @@ -3266,7 +3266,7 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, ExprType = SimpleExpr; Result = ParseExpression(); if (!Result.isInvalid() && Tok.is(tok::r_paren)) - Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), + Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), Tok.getLocation(), Result.get()); // Match the ')'. diff --git a/lib/Parse/ParseInit.cpp b/lib/Parse/ParseInit.cpp index 90f3561cb9637..0cd550bc6a47d 100644 --- a/lib/Parse/ParseInit.cpp +++ b/lib/Parse/ParseInit.cpp @@ -20,21 +20,21 @@ using namespace clang; -/// MayBeDesignationStart - Return true if the current token might be the start -/// of a designator. If we can tell it is impossible that it is a designator, +/// MayBeDesignationStart - Return true if the current token might be the start +/// of a designator. If we can tell it is impossible that it is a designator, /// return false. bool Parser::MayBeDesignationStart() { switch (Tok.getKind()) { - default: + default: return false; - + case tok::period: // designator: '.' identifier return true; - + case tok::l_square: { // designator: array-designator if (!PP.getLangOpts().CPlusPlus11) return true; - + // C++11 lambda expressions and C99 designators can be ambiguous all the // way through the closing ']' and to the next character. Handle the easy // cases here, and fall back to tentative parsing if those fail. @@ -43,28 +43,28 @@ bool Parser::MayBeDesignationStart() { case tok::r_square: // Definitely starts a lambda expression. return false; - + case tok::amp: case tok::kw_this: case tok::identifier: // We have to do additional analysis, because these could be the // start of a constant expression or a lambda capture list. break; - + default: - // Anything not mentioned above cannot occur following a '[' in a + // Anything not mentioned above cannot occur following a '[' in a // lambda expression. - return true; + return true; } - + // Handle the complicated case below. - break; + break; } case tok::identifier: // designation: identifier ':' return PP.LookAhead(0).is(tok::colon); } - - // Parse up to (at most) the token after the closing ']' to determine + + // Parse up to (at most) the token after the closing ']' to determine // whether this is a C99 designator or a lambda. TentativeParsingAction Tentative(*this); @@ -198,7 +198,7 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { // it will be rejected because a constant-expression cannot begin with a // lambda-expression. InMessageExpressionRAIIObject InMessage(*this, true); - + BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); SourceLocation StartLoc = T.getOpenLocation(); @@ -212,7 +212,7 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) { // Send to 'super'. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && - NextToken().isNot(tok::period) && + NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) { CheckArrayDesignatorSyntax(*this, StartLoc, Desig); return ParseAssignmentExprWithObjCMessageExprStart( @@ -226,13 +226,13 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } - + // If the receiver was a type, we have a class message; parse // the rest of it. if (!IsExpr) { CheckArrayDesignatorSyntax(*this, StartLoc, Desig); - return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, - SourceLocation(), + return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, + SourceLocation(), ParsedType::getFromOpaquePtr(TypeOrExpr), nullptr); } @@ -281,8 +281,8 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { } return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, - SourceLocation(), - ReceiverType, + SourceLocation(), + ReceiverType, nullptr); case Sema::ObjCInstanceMessage: @@ -387,7 +387,7 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { /// ExprResult Parser::ParseBraceInitializer() { InMessageExpressionRAIIObject InMessage(*this, false); - + BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); SourceLocation LBraceLoc = T.getOpenLocation(); @@ -485,7 +485,7 @@ bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return false; - + BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; @@ -496,7 +496,7 @@ bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, case IEB_Parse: // Parse the declarations below. break; - + case IEB_Dependent: Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) << Result.IsIfExists; @@ -520,7 +520,7 @@ bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, if (Tok.is(tok::ellipsis)) SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); - + // If we couldn't parse the subelement, bail out. if (!SubElt.isInvalid()) InitExprs.push_back(SubElt.get()); diff --git a/lib/Parse/ParseObjc.cpp b/lib/Parse/ParseObjc.cpp index 5c5b3cdfcf338..99e5edb9d4a3e 100644 --- a/lib/Parse/ParseObjc.cpp +++ b/lib/Parse/ParseObjc.cpp @@ -247,7 +247,7 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, if (Tok.is(tok::l_paren) && !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. - + BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); @@ -258,7 +258,7 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, cutOffParsing(); return nullptr; } - + // For ObjC2, the category name is optional (not an error). if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); @@ -269,11 +269,11 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, << tok::identifier; // missing category name. return nullptr; } - + T.consumeClose(); if (T.getCloseLocation().isInvalid()) return nullptr; - + // Next, we need to check for any protocol references. assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols"); SmallVector<Decl *, 8> ProtocolRefs; @@ -291,7 +291,7 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, if (Tok.is(tok::l_brace)) ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); - + ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); return CategoryType; @@ -592,14 +592,14 @@ ObjCTypeParamList *Parser::parseObjCTypeParamList() { /// @required /// @optional /// -void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, +void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl) { SmallVector<Decl *, 32> allMethods; SmallVector<DeclGroupPtrTy, 8> allTUVariables; tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; SourceRange AtEnd; - + while (1) { // If this is a method prototype, parse it. if (Tok.isOneOf(tok::minus, tok::plus)) { @@ -618,8 +618,8 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, } if (Tok.is(tok::l_paren)) { Diag(Tok, diag::err_expected_minus_or_plus); - ParseObjCMethodDecl(Tok.getLocation(), - tok::minus, + ParseObjCMethodDecl(Tok.getLocation(), + tok::minus, MethodImplKind, false); continue; } @@ -635,12 +635,12 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, // Code completion within an Objective-C interface. if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteOrdinaryName(getCurScope(), + Actions.CodeCompleteOrdinaryName(getCurScope(), CurParsedObjCImpl? Sema::PCC_ObjCImplementation : Sema::PCC_ObjCInterface); return cutOffParsing(); } - + // If we don't have an @ directive, parse it as a function definition. if (Tok.isNot(tok::at)) { // The code below does not consume '}'s because it is afraid of eating the @@ -685,7 +685,7 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, // Skip until we see an '@' or '}' or ';'. SkipUntil(tok::r_brace, tok::at, StopAtSemi); break; - + case tok::objc_implementation: case tok::objc_interface: Diag(AtLoc, diag::err_objc_missing_end) @@ -694,7 +694,7 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, << (int) Actions.getObjCContainerKind(); ConsumeToken(); break; - + case tok::objc_required: case tok::objc_optional: // This is only valid on protocols. @@ -1021,7 +1021,7 @@ IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { } return nullptr; } - + case tok::identifier: case tok::kw_asm: case tok::kw_auto: @@ -1134,11 +1134,11 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, while (1) { if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteObjCPassingType(getCurScope(), DS, + Actions.CodeCompleteObjCPassingType(getCurScope(), DS, Context == DeclaratorContext::ObjCParameterContext); return cutOffParsing(); } - + if (Tok.isNot(tok::identifier)) return; @@ -1160,17 +1160,17 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; - case objc_nonnull: + case objc_nonnull: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::NonNull; break; - case objc_nullable: + case objc_nullable: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::Nullable; break; - case objc_null_unspecified: + case objc_null_unspecified: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::Unspecified; break; @@ -1222,7 +1222,7 @@ static void takeDeclAttributes(ParsedAttributes &attrs, /// '(' objc-type-qualifiers[opt] type-name ')' /// '(' objc-type-qualifiers[opt] ')' /// -ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, +ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext context, ParsedAttributes *paramAttrs) { assert(context == DeclaratorContext::ObjCParameterContext || @@ -1343,7 +1343,7 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, MaybeParseCXX11Attributes(methodAttrs); if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, + Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, ReturnType); cutOffParsing(); return nullptr; @@ -1409,7 +1409,7 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, // Code completion for the next piece of the selector. if (Tok.is(tok::code_completion)) { KeyIdents.push_back(SelIdent); - Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), + Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), mType == tok::minus, /*AtParameterName=*/true, ReturnType, KeyIdents); @@ -1433,14 +1433,14 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, // Code completion for the next piece of the selector. if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), + Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), mType == tok::minus, /*AtParameterName=*/false, ReturnType, KeyIdents); cutOffParsing(); return nullptr; } - + // Check for another keyword selector. SelIdent = ParseObjCSelectorPiece(selLoc); if (!SelIdent && Tok.isNot(tok::colon)) @@ -1478,7 +1478,7 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, IdentifierInfo *ParmII = ParmDecl.getIdentifier(); Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, - ParmDecl.getIdentifierLoc(), + ParmDecl.getIdentifierLoc(), Param, nullptr)); } @@ -1614,7 +1614,7 @@ void Parser::parseObjCTypeArgsOrProtocolQualifiers( // FIXME: Also include types here. SmallVector<IdentifierLocPair, 4> identifierLocPairs; for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { - identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], + identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], identifierLocs[i])); } @@ -1800,10 +1800,10 @@ void Parser::parseObjCTypeArgsAndProtocolQualifiers( << SourceRange(protocolLAngleLoc, protocolRAngleLoc); SkipUntil(tok::greater, tok::greatergreater, skipFlags); } else { - ParseObjCProtocolReferences(protocols, protocolLocs, + ParseObjCProtocolReferences(protocols, protocolLocs, /*WarnOnDeclarations=*/false, /*ForObjCContainer=*/false, - protocolLAngleLoc, protocolRAngleLoc, + protocolLAngleLoc, protocolRAngleLoc, consumeLastToken); } } @@ -1857,7 +1857,7 @@ void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocatio bool RBraceMissing) { if (!RBraceMissing) T.consumeClose(); - + Actions.ActOnObjCContainerStartDefinition(interfaceDecl); Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); Actions.ActOnObjCContainerFinishDefinition(); @@ -1893,7 +1893,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, SourceLocation atLoc) { assert(Tok.is(tok::l_brace) && "expected {"); SmallVector<Decl *, 32> AllIvarDecls; - + ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); ObjCDeclContextSwitch ObjCDC(*this); @@ -1915,7 +1915,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, Actions.CodeCompleteObjCAtVisibility(getCurScope()); return cutOffParsing(); } - + switch (Tok.getObjCKeywordID()) { case tok::objc_private: case tok::objc_public: @@ -1934,7 +1934,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, HelperActionsForIvarDeclarations(interfaceDecl, atLoc, T, AllIvarDecls, true); return; - + default: Diag(Tok, diag::err_objc_illegal_visibility_spec); continue; @@ -1942,7 +1942,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, } if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteOrdinaryName(getCurScope(), + Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_ObjCInstanceVariableList); return cutOffParsing(); } @@ -1992,7 +1992,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, /// "\@protocol identifier ;" should be resolved as "\@protocol /// identifier-list ;": objc-interface-decl-list may not start with a /// semicolon in the first alternative if objc-protocol-refs are omitted. -Parser::DeclGroupPtrTy +Parser::DeclGroupPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, ParsedAttributes &attrs) { assert(Tok.isObjCAtKeyword(tok::objc_protocol) && @@ -2125,7 +2125,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { cutOffParsing(); return nullptr; } - + if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); categoryLoc = ConsumeToken(); @@ -2145,7 +2145,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { SourceLocation protocolLAngleLoc, protocolRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; - (void)ParseObjCProtocolReferences(protocols, protocolLocs, + (void)ParseObjCProtocolReferences(protocols, protocolLocs, /*warnOnIncompleteProtocols=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, @@ -2169,7 +2169,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { ObjCImpDecl = Actions.ActOnStartClassImplementation( AtLoc, nameId, nameLoc, superClassId, superClassLoc); - + if (Tok.is(tok::l_brace)) // we have ivars ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); else if (Tok.is(tok::less)) { // we have illegal '<' try to recover @@ -2178,7 +2178,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { SourceLocation protocolLAngleLoc, protocolRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; - (void)ParseObjCProtocolReferences(protocols, protocolLocs, + (void)ParseObjCProtocolReferences(protocols, protocolLocs, /*warnOnIncompleteProtocols=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, @@ -2235,16 +2235,16 @@ void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { assert(!Finished); P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin()); for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) - P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], + P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], true/*Methods*/); P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); if (HasCFunction) for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) - P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], + P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], false/*c-functions*/); - + /// Clear and free the cached objc methods. for (LateParsedObjCMethodContainer::iterator I = LateParsedObjCMethods.begin(), @@ -2297,7 +2297,7 @@ Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { cutOffParsing(); return nullptr; } - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_synthesized_property_name); SkipUntil(tok::semi); @@ -2380,7 +2380,7 @@ Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { SkipUntil(tok::semi); return nullptr; } - + IdentifierInfo *propertyId = Tok.getIdentifierInfo(); SourceLocation propertyLoc = ConsumeToken(); // consume property name Actions.ActOnPropertyImplDecl( @@ -2538,14 +2538,14 @@ StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { Diag(Tok, diag::err_expected) << tok::l_brace; if (CatchBody.isInvalid()) CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); - + StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, - RParenLoc, - FirstPart, + RParenLoc, + FirstPart, CatchBody.get()); if (!Catch.isInvalid()) CatchStmts.push_back(Catch.get()); - + } else { Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) << "@catch clause"; @@ -2588,8 +2588,8 @@ StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { Diag(atLoc, diag::err_missing_catch_finally); return StmtError(); } - - return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), + + return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), CatchStmts, FinallyStmt.get()); } @@ -2613,11 +2613,11 @@ Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { BodyScope.Exit(); if (AutoreleasePoolBody.isInvalid()) AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); - return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, + return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, AutoreleasePoolBody.get()); } -/// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them +/// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them /// for later parsing. void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) && @@ -2698,7 +2698,7 @@ Decl *Parser::ParseObjCMethodDefinition() { // Allow the rest of sema to find private method decl implementations. Actions.AddAnyMethodToGlobalPool(MDecl); - assert (CurParsedObjCImpl + assert (CurParsedObjCImpl && "ParseObjCMethodDefinition - Method out of @implementation"); // Consume the tokens and store them for later parsing. StashAwayMethodOrFunctionBodyTokens(MDecl); @@ -2711,13 +2711,13 @@ StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { cutOffParsing(); return StmtError(); } - + if (Tok.isObjCAtKeyword(tok::objc_try)) return ParseObjCTryStmt(AtLoc); - + if (Tok.isObjCAtKeyword(tok::objc_throw)) return ParseObjCThrowStmt(AtLoc); - + if (Tok.isObjCAtKeyword(tok::objc_synchronized)) return ParseObjCSynchronizedStmt(AtLoc); @@ -2739,7 +2739,7 @@ StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { SkipUntil(tok::semi); return StmtError(); } - + // Otherwise, eat the semicolon. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); return Actions.ActOnExprStmt(Res); @@ -2789,7 +2789,7 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { case tok::char_constant: return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); - + case tok::numeric_constant: return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); @@ -2799,19 +2799,19 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { case tok::kw_false: // Objective-C++, etc. case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); - + case tok::l_square: // Objective-C array literal return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); - + case tok::l_brace: // Objective-C dictionary literal return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); - + case tok::l_paren: // Objective-C boxed expression return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); - + default: if (Tok.getIdentifierInfo() == nullptr) return ExprError(Diag(AtLoc, diag::err_unexpected_at)); @@ -2833,14 +2833,14 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { if (GetLookAheadToken(1).is(tok::l_brace) && ExprStatementTokLoc == AtLoc) { char ch = Tok.getIdentifierInfo()->getNameStart()[0]; - str = - ch == 't' ? "try" - : (ch == 'f' ? "finally" + str = + ch == 't' ? "try" + : (ch == 'f' ? "finally" : (ch == 'a' ? "autoreleasepool" : nullptr)); } if (str) { SourceLocation kwLoc = Tok.getLocation(); - return ExprError(Diag(AtLoc, diag::err_unexpected_at) << + return ExprError(Diag(AtLoc, diag::err_unexpected_at) << FixItHint::CreateReplacement(kwLoc, str)); } else @@ -2856,7 +2856,7 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { /// Objective-C++ either as a type or as an expression. Note that this /// routine must not be called to parse a send to 'super', since it /// has no way to return such a result. -/// +/// /// \param IsExpr Whether the receiver was parsed as an expression. /// /// \param TypeOrExpr If the receiver was parsed as an expression (\c @@ -2900,7 +2900,7 @@ bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { // expression (that starts with one of the above) DeclSpec DS(AttrFactory); ParseCXXSimpleTypeSpecifier(DS); - + if (Tok.is(tok::l_paren)) { // If we see an opening parentheses at this point, we are // actually parsing an expression that starts with a @@ -2926,7 +2926,7 @@ bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { TypeOrExpr = Receiver.get(); return false; } - + // We have a class message. Turn the simple-type-specifier or // typename-specifier we parsed into a type and parse the // remainder of the class message. @@ -2953,26 +2953,26 @@ bool Parser::isSimpleObjCMessageExpression() { } bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { - if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || + if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || InMessageExpression) return false; - + ParsedType Type; - if (Tok.is(tok::annot_typename)) + if (Tok.is(tok::annot_typename)) Type = getTypeAnnotation(Tok); else if (Tok.is(tok::identifier)) - Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), + Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope()); else return false; - + if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { const Token &AfterNext = GetLookAheadToken(2); if (AfterNext.isOneOf(tok::colon, tok::r_square)) { if (Tok.is(tok::identifier)) TryAnnotateTypeOrScopeToken(); - + return Tok.is(tok::annot_typename); } } @@ -2998,14 +2998,14 @@ ExprResult Parser::ParseObjCMessageExpression() { cutOffParsing(); return ExprError(); } - + InMessageExpressionRAIIObject InMessage(*this, true); - + if (getLangOpts().CPlusPlus) { // We completely separate the C and C++ cases because C++ requires - // more complicated (read: slower) parsing. - - // Handle send to super. + // more complicated (read: slower) parsing. + + // Handle send to super. // FIXME: This doesn't benefit from the same typo-correction we // get in Objective-C. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && @@ -3025,11 +3025,11 @@ ExprResult Parser::ParseObjCMessageExpression() { return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr, static_cast<Expr *>(TypeOrExpr)); - return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), + return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ParsedType::getFromOpaquePtr(TypeOrExpr), nullptr); } - + if (Tok.is(tok::identifier)) { IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = Tok.getLocation(); @@ -3065,7 +3065,7 @@ ExprResult Parser::ParseObjCMessageExpression() { ReceiverType = NewReceiverType.get(); } - return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), + return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ReceiverType, nullptr); case Sema::ObjCInstanceMessage: @@ -3073,7 +3073,7 @@ ExprResult Parser::ParseObjCMessageExpression() { break; } } - + // Otherwise, an arbitrary expression can be the receiver of a send. ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression()); if (Res.isInvalid()) { @@ -3143,11 +3143,11 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, cutOffParsing(); return ExprError(); } - + // Parse objc-selector SourceLocation Loc; IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); - + SmallVector<IdentifierInfo *, 12> KeyIdents; SmallVector<SourceLocation, 12> KeyLocs; ExprVector KeyExprs; @@ -3167,10 +3167,10 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, } /// Parse the expression after ':' - + if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) - Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, + Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, KeyIdents, /*AtArgumentEpression=*/true); else if (ReceiverType) @@ -3185,14 +3185,14 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, cutOffParsing(); return ExprError(); } - + ExprResult Expr; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); Expr = ParseBraceInitializer(); } else Expr = ParseAssignmentExpression(); - + ExprResult Res(Expr); if (Res.isInvalid()) { // We must manually skip to a ']', otherwise the expression skipper will @@ -3208,7 +3208,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, // Code completion after each argument. if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) - Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, + Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, KeyIdents, /*AtArgumentEpression=*/false); else if (ReceiverType) @@ -3222,7 +3222,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, cutOffParsing(); return ExprError(); } - + // Check for another keyword selector. selIdent = ParseObjCSelectorPiece(Loc); if (!selIdent && Tok.isNot(tok::colon)) @@ -3260,7 +3260,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } - + if (Tok.isNot(tok::r_square)) { Diag(Tok, diag::err_expected) << (Tok.is(tok::identifier) ? tok::colon : tok::r_square); @@ -3270,7 +3270,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } - + SourceLocation RBracLoc = ConsumeBracket(); // consume ']' unsigned nKeys = KeyIdents.size(); @@ -3324,7 +3324,7 @@ ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { /// ; /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' /// ; -ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, +ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue) { SourceLocation EndLoc = ConsumeToken(); // consume the keyword. return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); @@ -3395,15 +3395,15 @@ ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return Res; - } - + } + Res = Actions.CorrectDelayedTyposInExpr(Res.get()); if (Res.isInvalid()) HasInvalidEltExpr = true; // Parse the ellipsis that indicates a pack expansion. if (Tok.is(tok::ellipsis)) - Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); + Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); if (Res.isInvalid()) HasInvalidEltExpr = true; @@ -3447,7 +3447,7 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { SkipUntil(tok::r_brace, StopAtSemi); return ExprError(); } - + ExprResult ValueExpr(ParseAssignmentExpression()); if (ValueExpr.isInvalid()) { // We must manually skip to a '}', otherwise the expression skipper will @@ -3456,7 +3456,7 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { SkipUntil(tok::r_brace, StopAtSemi); return ValueExpr; } - + // Check the key and value for possible typos KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get()); ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get()); @@ -3472,8 +3472,8 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { // We have a valid expression. Collect it in a vector so we can // build the argument list. - ObjCDictionaryElement Element = { - KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None + ObjCDictionaryElement Element = { + KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None }; Elements.push_back(Element); @@ -3485,7 +3485,7 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { if (HasInvalidEltExpr) return ExprError(); - + // Create the ObjCDictionaryLiteral. return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), Elements); @@ -3551,26 +3551,26 @@ ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { SmallVector<IdentifierInfo *, 12> KeyIdents; SourceLocation sLoc; - + BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); bool HasOptionalParen = Tok.is(tok::l_paren); if (HasOptionalParen) ConsumeParen(); - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); cutOffParsing(); return ExprError(); } - + IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); if (!SelIdent && // missing selector name. Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); KeyIdents.push_back(SelIdent); - + unsigned nColons = 0; if (Tok.isNot(tok::r_paren)) { while (1) { @@ -3583,7 +3583,7 @@ ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { if (Tok.is(tok::r_paren)) break; - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); cutOffParsing(); @@ -3611,12 +3611,12 @@ ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { // MCDecl might be null due to error in method or c-function prototype, etc. Decl *MCDecl = LM.D; - bool skip = MCDecl && + bool skip = MCDecl && ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); if (skip) return; - + // Save the current token position. SourceLocation OrigLoc = Tok.getLocation(); @@ -3636,15 +3636,15 @@ void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); - - assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && + + assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && "Inline objective-c method not starting with '{' or 'try' or ':'"); // Enter a scope for the method or c-function body. ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) | Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope); - // Tell the actions module that we have entered a method or c-function definition + // Tell the actions module that we have entered a method or c-function definition // with the specified Declarator for the method/function. if (parseMethod) Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl); diff --git a/lib/Parse/ParsePragma.cpp b/lib/Parse/ParsePragma.cpp index 9a25f9c25c036..07f48e0779dc6 100644 --- a/lib/Parse/ParsePragma.cpp +++ b/lib/Parse/ParsePragma.cpp @@ -1492,7 +1492,7 @@ void Parser::HandlePragmaAttribute() { // #pragma GCC visibility comes in two variants: // 'push' '(' [visibility] ')' // 'pop' -void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, +void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &VisTok) { SourceLocation VisLoc = VisTok.getLocation(); @@ -1552,7 +1552,7 @@ void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, // pack '(' [integer] ')' // pack '(' 'show' ')' // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')' -void PragmaPackHandler::HandlePragma(Preprocessor &PP, +void PragmaPackHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &PackTok) { SourceLocation PackLoc = PackTok.getLocation(); @@ -1663,7 +1663,7 @@ void PragmaPackHandler::HandlePragma(Preprocessor &PP, // #pragma ms_struct on // #pragma ms_struct off -void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, +void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &MSStructTok) { PragmaMSStructKind Kind = PMSST_OFF; @@ -1686,7 +1686,7 @@ void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct); return; } - + if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "ms_struct"; @@ -1817,20 +1817,20 @@ static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok, PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); } -void PragmaAlignHandler::HandlePragma(Preprocessor &PP, +void PragmaAlignHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &AlignTok) { ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false); } -void PragmaOptionsHandler::HandlePragma(Preprocessor &PP, +void PragmaOptionsHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &OptionsTok) { ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true); } // #pragma unused(identifier) -void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, +void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &UnusedTok) { // FIXME: Should we be expanding macros here? My guess is no. @@ -1911,7 +1911,7 @@ void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, // #pragma weak identifier // #pragma weak identifier '=' identifier -void PragmaWeakHandler::HandlePragma(Preprocessor &PP, +void PragmaWeakHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &WeakTok) { SourceLocation WeakLoc = WeakTok.getLocation(); @@ -1970,7 +1970,7 @@ void PragmaWeakHandler::HandlePragma(Preprocessor &PP, } // #pragma redefine_extname identifier identifier -void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, +void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &RedefToken) { SourceLocation RedefLoc = RedefToken.getLocation(); @@ -2015,7 +2015,7 @@ void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, void -PragmaFPContractHandler::HandlePragma(Preprocessor &PP, +PragmaFPContractHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { tok::OnOffSwitch OOS; @@ -2033,8 +2033,8 @@ PragmaFPContractHandler::HandlePragma(Preprocessor &PP, PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); } -void -PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, +void +PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { PP.LexUnexpandedToken(Tok); @@ -2095,7 +2095,7 @@ PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); if (PP.getPPCallbacks()) - PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext, + PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext, StateLoc, State); } @@ -2523,7 +2523,7 @@ void PragmaCommentHandler::HandlePragma(Preprocessor &PP, // #pragma clang optimize off // #pragma clang optimize on -void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, +void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) { Token Tok; @@ -2549,7 +2549,7 @@ void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, return; } PP.Lex(Tok); - + if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument) << PP.getSpelling(Tok); diff --git a/lib/Parse/ParseStmtAsm.cpp b/lib/Parse/ParseStmtAsm.cpp index 290723c29532e..9b96c5150e569 100644 --- a/lib/Parse/ParseStmtAsm.cpp +++ b/lib/Parse/ParseStmtAsm.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements parsing for GCC and Microsoft inline assembly. +// This file implements parsing for GCC and Microsoft inline assembly. // //===----------------------------------------------------------------------===// diff --git a/lib/Parse/ParseTemplate.cpp b/lib/Parse/ParseTemplate.cpp index f7a69c482e17a..063f7ccea320a 100644 --- a/lib/Parse/ParseTemplate.cpp +++ b/lib/Parse/ParseTemplate.cpp @@ -27,7 +27,7 @@ Decl *Parser::ParseDeclarationStartingWithTemplate( DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS) { ObjCDeclContextSwitch ObjCDC(*this); - + if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) { return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(), DeclEnd, AccessAttrs, AS); @@ -360,7 +360,7 @@ bool Parser::ParseTemplateParameterList(const unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams) { while (1) { - + if (NamedDecl *TmpParam = ParseTemplateParameter(Depth, TemplateParams.size())) { TemplateParams.push_back(TmpParam); @@ -403,23 +403,23 @@ bool Parser::isStartOfTemplateTypeParameter() { case tok::greatergreater: case tok::ellipsis: return true; - + case tok::identifier: - // This may be either a type-parameter or an elaborated-type-specifier. + // This may be either a type-parameter or an elaborated-type-specifier. // We have to look further. break; - + default: return false; } - + switch (GetLookAheadToken(2).getKind()) { case tok::equal: case tok::comma: case tok::greater: case tok::greatergreater: return true; - + default: return false; } @@ -464,7 +464,7 @@ bool Parser::isStartOfTemplateTypeParameter() { /// 'class' identifier[opt] '=' type-id /// 'typename' ...[opt] identifier[opt] /// 'typename' identifier[opt] '=' type-id -/// 'template' '<' template-parameter-list '>' +/// 'template' '<' template-parameter-list '>' /// 'class' ...[opt] identifier[opt] /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] /// = id-expression @@ -617,7 +617,7 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_variadic_templates : diag::ext_variadic_templates); - + // Get the identifier, if given. SourceLocation NameLoc; IdentifierInfo *ParamName = nullptr; @@ -652,16 +652,16 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { if (TryConsumeToken(tok::equal, EqualLoc)) { DefaultArg = ParseTemplateTemplateArgument(); if (DefaultArg.isInvalid()) { - Diag(Tok.getLocation(), + Diag(Tok.getLocation(), diag::err_default_template_template_parameter_not_template); SkipUntil(tok::comma, tok::greater, tok::greatergreater, StopAtSemi | StopBeforeMatch); } } - + return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc, - ParamList, EllipsisLoc, - ParamName, NameLoc, Depth, + ParamList, EllipsisLoc, + ParamName, NameLoc, Depth, Position, EqualLoc, DefaultArg); } @@ -714,8 +714,8 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { } // Create the parameter. - return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, - Depth, Position, EqualLoc, + return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, + Depth, Position, EqualLoc, DefaultArg.get()); } @@ -1045,7 +1045,7 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, // Build a template-id annotation token that can be processed // later. Tok.setKind(tok::annot_template_id); - + IdentifierInfo *TemplateII = TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier ? TemplateName.Identifier @@ -1059,7 +1059,7 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create( SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK, LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds); - + Tok.setAnnotationValue(TemplateId); if (TemplateKWLoc.isValid()) Tok.setLocation(TemplateKWLoc); @@ -1135,13 +1135,13 @@ ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { // C++0x [temp.arg.template]p1: // A template-argument for a template template-parameter shall be the name // of a class template or an alias template, expressed as id-expression. - // + // // We parse an id-expression that refers to a class template or alias // template. The grammar we parse is: // // nested-name-specifier[opt] template[opt] identifier ...[opt] // - // followed by a token that terminates a template argument, such as ',', + // followed by a token that terminates a template argument, such as ',', // '>', or (in some cases) '>>'. CXXScopeSpec SS; // nested-name-specifier, if present ParseOptionalCXXScopeSpecifier(SS, nullptr, @@ -1150,10 +1150,10 @@ ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { ParsedTemplateArgument Result; SourceLocation EllipsisLoc; if (SS.isSet() && Tok.is(tok::kw_template)) { - // Parse the optional 'template' keyword following the + // Parse the optional 'template' keyword following the // nested-name-specifier. SourceLocation TemplateKWLoc = ConsumeToken(); - + if (Tok.is(tok::identifier)) { // We appear to have a dependent template name. UnqualifiedId Name; @@ -1191,16 +1191,16 @@ ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization); if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) { // We have an id-expression that refers to a class template or - // (C++0x) alias template. + // (C++0x) alias template. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); } } } - + // If this is a pack expansion, build it as such. if (EllipsisLoc.isValid() && !Result.isInvalid()) Result = Actions.ActOnPackExpansion(Result, EllipsisLoc); - + return Result; } @@ -1230,7 +1230,7 @@ ParsedTemplateArgument Parser::ParseTemplateArgument() { /*Range=*/nullptr, DeclaratorContext::TemplateArgContext); return Actions.ActOnTemplateTypeArgument(TypeArg); } - + // Try to parse a template template argument. { TentativeParsingAction TPA(*this); @@ -1241,35 +1241,35 @@ ParsedTemplateArgument Parser::ParseTemplateArgument() { TPA.Commit(); return TemplateTemplateArgument; } - + // Revert this tentative parse to parse a non-type template argument. TPA.Revert(); } - - // Parse a non-type template argument. + + // Parse a non-type template argument. SourceLocation Loc = Tok.getLocation(); ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast); if (ExprArg.isInvalid() || !ExprArg.get()) return ParsedTemplateArgument(); - return ParsedTemplateArgument(ParsedTemplateArgument::NonType, + return ParsedTemplateArgument(ParsedTemplateArgument::NonType, ExprArg.get(), Loc); } -/// Determine whether the current tokens can only be parsed as a -/// template argument list (starting with the '<') and never as a '<' +/// Determine whether the current tokens can only be parsed as a +/// template argument list (starting with the '<') and never as a '<' /// expression. bool Parser::IsTemplateArgumentList(unsigned Skip) { struct AlwaysRevertAction : TentativeParsingAction { AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { } ~AlwaysRevertAction() { Revert(); } } Tentative(*this); - + while (Skip) { ConsumeAnyToken(); --Skip; } - + // '<' if (!TryConsumeToken(tok::less)) return false; @@ -1277,11 +1277,11 @@ bool Parser::IsTemplateArgumentList(unsigned Skip) { // An empty template argument list. if (Tok.is(tok::greater)) return true; - + // See whether we have declaration specifiers, which indicate a type. while (isCXXDeclarationSpecifier() == TPResult::True) ConsumeAnyToken(); - + // If we have a '>' or a ',' then this is a template argument list. return Tok.isOneOf(tok::greater, tok::comma); } @@ -1294,7 +1294,7 @@ bool Parser::IsTemplateArgumentList(unsigned Skip) { /// template-argument-list ',' template-argument bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { - + ColonProtectionRAIIObject ColonProtection(*this, false); do { @@ -1310,7 +1310,7 @@ Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { // Save this template argument. TemplateArgs.push_back(Arg); - + // If the next token is a comma, consume it and keep reading // arguments. } while (TryConsumeToken(tok::comma)); diff --git a/lib/Parse/ParseTentative.cpp b/lib/Parse/ParseTentative.cpp index 0603d8e75eeac..dfd1f8c3b2e68 100644 --- a/lib/Parse/ParseTentative.cpp +++ b/lib/Parse/ParseTentative.cpp @@ -80,10 +80,10 @@ bool Parser::isCXXDeclarationStatement() { /// (if AllowForRangeDecl specified) /// for ( for-range-declaration : for-range-initializer ) statement /// -/// for-range-declaration: +/// for-range-declaration: /// decl-specifier-seq declarator /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']' -/// +/// /// In any of the above cases there can be a preceding attribute-specifier-seq, /// but the caller is expected to handle that. bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { @@ -132,7 +132,7 @@ bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { // Ok, we have a simple-type-specifier/typename-specifier followed by a '(', // or an identifier which doesn't resolve as anything. We need tentative // parsing... - + { RevertingTentativeParsingAction PA(*this); TPR = TryParseSimpleDeclaration(AllowForRangeDecl); @@ -236,7 +236,7 @@ Parser::TPResult Parser::TryConsumeDeclarationSpecifier() { /// /// (if AllowForRangeDecl specified) /// for ( for-range-declaration : for-range-initializer ) statement -/// for-range-declaration: +/// for-range-declaration: /// attribute-specifier-seqopt type-specifier-seq declarator /// Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) { @@ -964,7 +964,7 @@ Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract, return TPResult::Ambiguous; } -Parser::TPResult +Parser::TPResult Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { switch (Kind) { // Obviously starts an expression. @@ -1026,7 +1026,7 @@ Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { case tok::kw_##Spelling: #include "clang/Basic/TokenKinds.def" return TPResult::True; - + // Obviously starts a type-specifier-seq: case tok::kw_char: case tok::kw_const: @@ -1084,7 +1084,7 @@ Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { default: break; } - + return TPResult::Ambiguous; } @@ -1338,7 +1338,7 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, // Debugger support case tok::kw___unknown_anytype: - + // type-specifier: // simple-type-specifier // class-specifier @@ -1395,7 +1395,7 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, // Borland case tok::kw___pascal: return TPResult::True; - + // AltiVec case tok::kw___vector: return TPResult::True; @@ -1510,24 +1510,24 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, // Tentatively parse the protocol qualifiers. RevertingTentativeParsingAction PA(*this); ConsumeAnyToken(); // The type token - + TPResult TPR = TryParseProtocolQualifiers(); bool isFollowedByParen = Tok.is(tok::l_paren); bool isFollowedByBrace = Tok.is(tok::l_brace); - + if (TPR == TPResult::Error) return TPResult::Error; - + if (isFollowedByParen) return TPResult::Ambiguous; if (getLangOpts().CPlusPlus11 && isFollowedByBrace) return BracedCastResult; - + return TPResult::True; } LLVM_FALLTHROUGH; - + case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char8_t: @@ -1562,7 +1562,7 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, if (isStartOfObjCClassMessageMissingOpenBracket()) return TPResult::False; - + return TPResult::True; // GNU typeof support. @@ -1681,18 +1681,18 @@ Parser::TPResult Parser::TryParseProtocolQualifiers() { if (Tok.isNot(tok::identifier)) return TPResult::Error; ConsumeToken(); - + if (Tok.is(tok::comma)) { ConsumeToken(); continue; } - + if (Tok.is(tok::greater)) { ConsumeToken(); return TPResult::Ambiguous; } } while (false); - + return TPResult::Error; } @@ -1910,7 +1910,7 @@ Parser::TPResult Parser::TryParseFunctionDeclarator() { // ref-qualifier[opt] if (Tok.isOneOf(tok::amp, tok::ampamp)) ConsumeToken(); - + // exception-specification if (Tok.is(tok::kw_throw)) { ConsumeToken(); diff --git a/lib/Parse/Parser.cpp b/lib/Parse/Parser.cpp index 7a0b29cbae866..c3085654f5299 100644 --- a/lib/Parse/Parser.cpp +++ b/lib/Parse/Parser.cpp @@ -41,7 +41,7 @@ public: } // end anonymous namespace IdentifierInfo *Parser::getSEHExceptKeyword() { - // __except is accepted as a (contextual) keyword + // __except is accepted as a (contextual) keyword if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland)) Ident__except = PP.getIdentifierInfo("__except"); @@ -50,7 +50,7 @@ IdentifierInfo *Parser::getSEHExceptKeyword() { Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies) : PP(pp), Actions(actions), Diags(PP.getDiagnostics()), - GreaterThanIsOperator(true), ColonIsSacred(false), + GreaterThanIsOperator(true), ColonIsSacred(false), InMessageExpression(false), TemplateParameterDepth(0), ParsingInObjCContainer(false) { SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies; @@ -161,8 +161,8 @@ bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { handleUnexpectedCodeCompletionToken(); return false; } - - if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && + + if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && NextToken().is(tok::semi)) { Diag(Tok, diag::err_extraneous_token_before_semi) << PP.getSpelling(Tok) @@ -171,7 +171,7 @@ bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { ConsumeToken(); // The ';'. return false; } - + return ExpectAndConsume(tok::semi, DiagID); } @@ -291,7 +291,7 @@ bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) { if (!HasFlagsSet(Flags, StopAtCodeCompletion)) handleUnexpectedCodeCompletionToken(); return false; - + case tok::l_paren: // Recursively skip properly-nested parens. ConsumeParen(); @@ -796,17 +796,17 @@ Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs, return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs); } goto dont_know; - + case tok::kw_inline: if (getLangOpts().CPlusPlus) { tok::TokenKind NextKind = NextToken().getKind(); - + // Inline namespaces. Allowed as an extension even in C++03. if (NextKind == tok::kw_namespace) { SourceLocation DeclEnd; return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs); } - + // Parse (then ignore) 'inline' prior to a template instantiation. This is // a GCC extension that we intentionally do not support. if (NextKind == tok::kw_template) { @@ -867,7 +867,7 @@ bool Parser::isDeclarationAfterDeclarator() { if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) return false; } - + return Tok.is(tok::equal) || // int X()= -> not a function def Tok.is(tok::comma) || // int X(), -> not a function def Tok.is(tok::semi) || // int X(); -> not a function def @@ -883,17 +883,17 @@ bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); if (Tok.is(tok::l_brace)) // int X() {} return true; - + // Handle K&R C argument lists: int X(f) int f; {} if (!getLangOpts().CPlusPlus && - Declarator.getFunctionTypeInfo().isKNRPrototype()) + Declarator.getFunctionTypeInfo().isKNRPrototype()) return isDeclarationSpecifier(); if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { const Token &KW = NextToken(); return KW.is(tok::kw_default) || KW.is(tok::kw_delete); } - + return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) Tok.is(tok::kw_try); // X() try { ... } } @@ -947,7 +947,7 @@ Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, default: llvm_unreachable("we only expect to get the length of the class/struct/union/enum"); } - + }; // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]' SourceLocation CorrectLocationForAttributes = @@ -1072,7 +1072,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, // We should have either an opening brace or, in a C++ constructor, // we may have a colon. - if (Tok.isNot(tok::l_brace) && + if (Tok.isNot(tok::l_brace) && (!getLangOpts().CPlusPlus || (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && Tok.isNot(tok::equal)))) { @@ -1128,10 +1128,10 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, } return DP; } - else if (CurParsedObjCImpl && + else if (CurParsedObjCImpl && !TemplateInfo.TemplateParams && (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || - Tok.is(tok::colon)) && + Tok.is(tok::colon)) && Actions.CurContext->isTranslationUnit()) { ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope); @@ -1171,7 +1171,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, // Break out of the ParsingDeclarator context before we parse the body. D.complete(Res); - + // Break out of the ParsingDeclSpec context, too. This const_cast is // safe because we're always the sole owner. D.getMutableDeclSpec().abort(); @@ -1710,7 +1710,7 @@ bool Parser::TryAnnotateTypeOrScopeToken() { TypeResult Ty; if (Tok.is(tok::identifier)) { // FIXME: check whether the next token is '<', first! - Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, + Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, *Tok.getIdentifierInfo(), Tok.getLocation()); } else if (Tok.is(tok::annot_template_id)) { @@ -1926,14 +1926,14 @@ SourceLocation Parser::handleUnexpectedCodeCompletionToken() { cutOffParsing(); return PrevTokLocation; } - + if (S->getFlags() & Scope::ClassScope) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); cutOffParsing(); return PrevTokLocation; } } - + Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); cutOffParsing(); return PrevTokLocation; @@ -1953,7 +1953,7 @@ void Parser::CodeCompleteMacroName(bool IsDefinition) { Actions.CodeCompletePreprocessorMacroName(IsDefinition); } -void Parser::CodeCompletePreprocessorExpression() { +void Parser::CodeCompletePreprocessorExpression() { Actions.CodeCompletePreprocessorExpression(); } @@ -1976,11 +1976,11 @@ bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { - Diag(Tok, diag::err_expected_lparen_after) + Diag(Tok, diag::err_expected_lparen_after) << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); return true; } - + // Parse nested-name-specifier. if (getLangOpts().CPlusPlus) ParseOptionalCXXScopeSpecifier(Result.SS, nullptr, @@ -2004,7 +2004,7 @@ bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { if (T.consumeClose()) return true; - + // Check if the symbol exists. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, Result.IsIfExists, Result.SS, @@ -2020,7 +2020,7 @@ bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { case Sema::IER_Dependent: Result.Behavior = IEB_Dependent; break; - + case Sema::IER_Error: return true; } @@ -2032,7 +2032,7 @@ void Parser::ParseMicrosoftIfExistsExternalDeclaration() { IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; - + BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; @@ -2043,10 +2043,10 @@ void Parser::ParseMicrosoftIfExistsExternalDeclaration() { case IEB_Parse: // Parse declarations below. break; - + case IEB_Dependent: llvm_unreachable("Cannot have a dependent external declaration"); - + case IEB_Skip: Braces.skipToEnd(); return; @@ -2109,7 +2109,7 @@ Parser::DeclGroupPtrTy Parser::ParseModuleDecl() { /// Parse a module import declaration. This is essentially the same for /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC) /// and the trailing optional attributes (in C++). -/// +/// /// [ObjC] @import declaration: /// '@' 'import' module-name ';' /// [ModTS] module-import-declaration: @@ -2121,7 +2121,7 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc) { bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import); SourceLocation ImportLoc = ConsumeToken(); SourceLocation StartLoc = AtLoc.isInvalid() ? ImportLoc : AtLoc; - + SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; if (ParseModuleName(ImportLoc, Path, /*IsImport*/true)) return nullptr; @@ -2174,12 +2174,12 @@ bool Parser::ParseModuleName( cutOffParsing(); return true; } - + Diag(Tok, diag::err_module_expected_ident) << IsImport; SkipUntil(tok::semi); return true; } - + // Record this part of the module path. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); ConsumeToken(); @@ -2258,7 +2258,7 @@ bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, if (getDepth() < P.getLangOpts().BracketDepth) return false; - + return diagnoseOverflow(); } diff --git a/lib/Rewrite/DeltaTree.cpp b/lib/Rewrite/DeltaTree.cpp index 1dfc26cc918ff..06f3b4fb4a66d 100644 --- a/lib/Rewrite/DeltaTree.cpp +++ b/lib/Rewrite/DeltaTree.cpp @@ -50,7 +50,7 @@ namespace { return Delta; } }; - + /// DeltaTreeNode - The common part of all nodes. /// class DeltaTreeNode { @@ -59,7 +59,7 @@ namespace { DeltaTreeNode *LHS, *RHS; SourceDelta Split; }; - + private: friend class DeltaTreeInteriorNode; diff --git a/lib/Rewrite/HTMLRewrite.cpp b/lib/Rewrite/HTMLRewrite.cpp index d93961f3582ec..12d7a16a2fc81 100644 --- a/lib/Rewrite/HTMLRewrite.cpp +++ b/lib/Rewrite/HTMLRewrite.cpp @@ -49,7 +49,7 @@ void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E, const char *BufferStart = SM.getBufferData(FID, &Invalid).data(); if (Invalid) return; - + HighlightRange(R.getEditBuffer(FID), BOffset, EOffset, BufferStart, StartTag, EndTag); } diff --git a/lib/Rewrite/Rewriter.cpp b/lib/Rewrite/Rewriter.cpp index cb59a161fe689..a5421ec807b75 100644 --- a/lib/Rewrite/Rewriter.cpp +++ b/lib/Rewrite/Rewriter.cpp @@ -88,7 +88,7 @@ void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size, } ++posI; } - + unsigned lineSize = 0; posI = curLineStart; while (posI != end() && isWhitespaceExceptNL(*posI)) { @@ -353,10 +353,10 @@ bool Rewriter::IncreaseIndentation(CharSourceRange range, unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1; unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1; unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1; - + const SrcMgr::ContentCache * Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache(); - + // Find where the lines start. unsigned parentLineOffs = Content->SourceLineCache[parentLineNo]; unsigned startLineOffs = Content->SourceLineCache[startLineNo]; diff --git a/lib/Sema/AnalysisBasedWarnings.cpp b/lib/Sema/AnalysisBasedWarnings.cpp index 82d9df25d934a..ed240f4ed292b 100644 --- a/lib/Sema/AnalysisBasedWarnings.cpp +++ b/lib/Sema/AnalysisBasedWarnings.cpp @@ -90,7 +90,7 @@ namespace { } S.Diag(L, diag) << R1 << R2; - + SourceLocation Open = SilenceableCondVal.getBegin(); if (Open.isValid()) { SourceLocation Close = SilenceableCondVal.getEnd(); @@ -330,7 +330,7 @@ static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc, S.Diag(FD->getLocation(), diag::note_throw_in_dtor) << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec() << FD->getExceptionSpecSourceRange(); - } else + } else S.Diag(FD->getLocation(), diag::note_throw_in_function) << FD->getExceptionSpecSourceRange(); } @@ -525,18 +525,18 @@ struct CheckFallThroughDiagnostics { bool isVirtualMethod = false; if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) isVirtualMethod = Method->isVirtual(); - + // Don't suggest that template instantiations be marked "noreturn" bool isTemplateInstantiation = false; if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) isTemplateInstantiation = Function->isTemplateInstantiation(); - + if (!isVirtualMethod && !isTemplateInstantiation) D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function; else D.diag_NeverFallThroughOrReturn = 0; - + D.funMode = Function; return D; } @@ -1226,7 +1226,7 @@ static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, bool PerFunction) { // Only perform this analysis when using [[]] attributes. There is no good // workflow for this warning when not using C++11. There is no good way to - // silence the warning (no attribute is available) unless we are using + // silence the warning (no attribute is available) unless we are using // [[]] attributes. One could use pragmas to silence the warning, but as a // general solution that is gross and not in the spirit of this warning. // @@ -1492,7 +1492,7 @@ class UninitValsDiagReporter : public UninitVariablesHandler { // order of diagnostics when calling flushDiagnostics(). typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap; UsesMap uses; - + public: UninitValsDiagReporter(Sema &S) : S(S) {} ~UninitValsDiagReporter() override { flushDiagnostics(); } @@ -1508,11 +1508,11 @@ public: const UninitUse &use) override { getUses(vd).getPointer()->push_back(use); } - + void handleSelfInit(const VarDecl *vd) override { getUses(vd).setInt(true); } - + void flushDiagnostics() { for (const auto &P : uses) { const VarDecl *vd = P.first; @@ -1521,7 +1521,7 @@ public: UsesVec *vec = V.getPointer(); bool hasSelfInit = V.getInt(); - // Specially handle the case where we have uses of an uninitialized + // Specially handle the case where we have uses of an uninitialized // variable, but the root cause is an idiomatic self-init. We want // to report the diagnostic at the self-init since that is the root cause. if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec)) @@ -1551,7 +1551,7 @@ public: break; } } - + // Release the uses vector. delete vec; } @@ -1865,10 +1865,10 @@ namespace clang { namespace consumed { namespace { class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase { - + Sema &S; DiagList Warnings; - + public: ConsumedWarningsHandler(Sema &S) : S(S) {} @@ -1889,28 +1889,28 @@ public: Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnParamReturnTypestateMismatch(SourceLocation Loc, StringRef VariableName, StringRef ExpectedState, StringRef ObservedState) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_param_return_typestate_mismatch) << VariableName << ExpectedState << ObservedState); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, StringRef ObservedState) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnReturnTypestateForUnconsumableType(SourceLocation Loc, StringRef TypeName) override { PartialDiagnosticAt Warning(Loc, S.PDiag( @@ -1918,28 +1918,28 @@ public: Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, StringRef ObservedState) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State, SourceLocation Loc) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_use_of_temp_in_invalid_state) << MethodName << State); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnUseInInvalidState(StringRef MethodName, StringRef VariableName, StringRef State, SourceLocation Loc) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) << MethodName << VariableName << State); @@ -2027,7 +2027,7 @@ AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, flushDiagnostics(S, fscope); return; } - + const Stmt *Body = D->getBody(); assert(Body); @@ -2113,7 +2113,7 @@ AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, if (!analyzed) flushDiagnostics(S, fscope); } - + // Warning: check missing 'return' if (P.enableCheckFallThrough) { const CheckFallThroughDiagnostics &CD = diff --git a/lib/Sema/CMakeLists.txt b/lib/Sema/CMakeLists.txt index bad42a2ce252e..3d21d79f2b850 100644 --- a/lib/Sema/CMakeLists.txt +++ b/lib/Sema/CMakeLists.txt @@ -5,6 +5,7 @@ set(LLVM_LINK_COMPONENTS if (MSVC) set_source_files_properties(SemaDeclAttr.cpp PROPERTIES COMPILE_FLAGS /bigobj) set_source_files_properties(SemaExpr.cpp PROPERTIES COMPILE_FLAGS /bigobj) + set_source_files_properties(SemaTemplate.cpp PROPERTIES COMPILE_FLAGS /bigobj) endif() add_clang_library(clangSema diff --git a/lib/Sema/CodeCompleteConsumer.cpp b/lib/Sema/CodeCompleteConsumer.cpp index 9c4d315a692f8..8af54b993932f 100644 --- a/lib/Sema/CodeCompleteConsumer.cpp +++ b/lib/Sema/CodeCompleteConsumer.cpp @@ -49,7 +49,7 @@ bool CodeCompletionContext::wantConstructorResults() const { case CCC_ObjCMessageReceiver: case CCC_ParenthesizedExpression: return true; - + case CCC_TopLevel: case CCC_ObjCInterface: case CCC_ObjCImplementation: @@ -164,7 +164,7 @@ StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) { // Code completion string implementation //===----------------------------------------------------------------------===// -CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) +CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) : Kind(Kind), Text("") { switch (Kind) { case CK_TypedText: @@ -178,7 +178,7 @@ CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) case CK_Optional: llvm_unreachable("Optional strings cannot be created from text"); - + case CK_LeftParen: this->Text = "("; break; @@ -190,11 +190,11 @@ CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) case CK_LeftBracket: this->Text = "["; break; - + case CK_RightBracket: this->Text = "]"; break; - + case CK_LeftBrace: this->Text = "{"; break; @@ -206,11 +206,11 @@ CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) case CK_LeftAngle: this->Text = "<"; break; - + case CK_RightAngle: this->Text = ">"; break; - + case CK_Comma: this->Text = ", "; break; @@ -242,7 +242,7 @@ CodeCompletionString::Chunk::CreateText(const char *Text) { return Chunk(CK_Text, Text); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) { Chunk Result; Result.Kind = CK_Optional; @@ -250,30 +250,30 @@ CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) { return Result; } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) { return Chunk(CK_Placeholder, Placeholder); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateInformative(const char *Informative) { return Chunk(CK_Informative, Informative); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateResultType(const char *ResultType) { return Chunk(CK_ResultType, ResultType); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter( const char *CurrentParameter) { return Chunk(CK_CurrentParameter, CurrentParameter); } -CodeCompletionString::CodeCompletionString(const Chunk *Chunks, +CodeCompletionString::CodeCompletionString(const Chunk *Chunks, unsigned NumChunks, - unsigned Priority, + unsigned Priority, CXAvailabilityKind Availability, const char **Annotations, unsigned NumAnnotations, @@ -281,7 +281,7 @@ CodeCompletionString::CodeCompletionString(const Chunk *Chunks, const char *BriefComment) : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority), Availability(Availability), - ParentName(ParentName), BriefComment(BriefComment) { + ParentName(ParentName), BriefComment(BriefComment) { assert(NumChunks <= 0xffff); assert(NumAnnotations <= 0xffff); @@ -308,17 +308,17 @@ const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const { std::string CodeCompletionString::getAsString() const { std::string Result; llvm::raw_string_ostream OS(Result); - + for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) { switch (C->Kind) { case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break; case CK_Placeholder: OS << "<#" << C->Text << "#>"; break; - - case CK_Informative: + + case CK_Informative: case CK_ResultType: - OS << "[#" << C->Text << "#]"; + OS << "[#" << C->Text << "#]"; break; - + case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break; default: OS << C->Text; break; } @@ -350,7 +350,7 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { const NamedDecl *ND = dyn_cast<NamedDecl>(DC); if (!ND) return {}; - + // Check whether we've already cached the parent name. StringRef &CachedParentName = ParentNames[DC]; if (!CachedParentName.empty()) @@ -368,7 +368,7 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { if (ND->getIdentifier()) Contexts.push_back(DC); } - + DC = DC->getParent(); } @@ -382,11 +382,11 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { else { OS << "::"; } - + const DeclContext *CurDC = Contexts[I-1]; if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC)) CurDC = CatImpl->getCategoryDecl(); - + if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) { const ObjCInterfaceDecl *Interface = Cat->getClassInterface(); if (!Interface) { @@ -395,13 +395,13 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0); return {}; } - + OS << Interface->getName() << '(' << Cat->getName() << ')'; } else { OS << cast<NamedDecl>(CurDC)->getName(); } } - + CachedParentName = AllocatorRef->CopyString(OS.str()); } @@ -413,7 +413,7 @@ CodeCompletionString *CodeCompletionBuilder::TakeString() { sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() + sizeof(const char *) * Annotations.size(), alignof(CodeCompletionString)); - CodeCompletionString *Result + CodeCompletionString *Result = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(), Annotations.size(), @@ -459,14 +459,14 @@ void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK, void CodeCompletionBuilder::addParentContext(const DeclContext *DC) { if (DC->isTranslationUnit()) return; - + if (DC->isFunctionOrMethod()) return; - + const NamedDecl *ND = dyn_cast<NamedDecl>(DC); if (!ND) return; - + ParentName = getCodeCompletionTUInfo().getParentName(DC); } @@ -492,11 +492,11 @@ CodeCompleteConsumer::OverloadCandidate::getFunctionType() const { switch (Kind) { case CK_Function: return Function->getType()->getAs<FunctionType>(); - + case CK_FunctionTemplate: return FunctionTemplate->getTemplatedDecl()->getType() ->getAs<FunctionType>(); - + case CK_FunctionType: return Type; } @@ -526,13 +526,13 @@ bool PrintingCodeCompleteConsumer::isResultFilteredOut(StringRef Filter, llvm_unreachable("Unknown code completion result Kind."); } -void +void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults) { std::stable_sort(Results, Results + NumResults); - + StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter(); // Print the results. @@ -545,7 +545,7 @@ PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, OS << *Results[I].Declaration; if (Results[I].Hidden) OS << " (Hidden)"; - if (CodeCompletionString *CCS + if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(SemaRef, Context, getAllocator(), CCTUInfo, @@ -574,14 +574,14 @@ PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, } OS << '\n'; break; - + case CodeCompletionResult::RK_Keyword: OS << Results[I].Keyword << '\n'; break; - + case CodeCompletionResult::RK_Macro: OS << Results[I].Macro->getName(); - if (CodeCompletionString *CCS + if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(SemaRef, Context, getAllocator(), CCTUInfo, @@ -590,9 +590,9 @@ PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, } OS << '\n'; break; - + case CodeCompletionResult::RK_Pattern: - OS << "Pattern : " + OS << "Pattern : " << Results[I].Pattern->getAsString() << '\n'; break; } @@ -624,7 +624,7 @@ static std::string getOverloadAsString(const CodeCompletionString &CCS) { return OS.str(); } -void +void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates, @@ -655,19 +655,19 @@ void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) { break; } LLVM_FALLTHROUGH; - + case RK_Declaration: { // Set the availability based on attributes. switch (getDeclAvailability(Declaration)) { case AR_Available: case AR_NotYetIntroduced: - Availability = CXAvailability_Available; + Availability = CXAvailability_Available; break; - + case AR_Deprecated: Availability = CXAvailability_Deprecated; break; - + case AR_Unavailable: Availability = CXAvailability_NotAvailable; break; @@ -676,11 +676,11 @@ void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) { if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration)) if (Function->isDeleted()) Availability = CXAvailability_NotAvailable; - + CursorKind = getCursorKindForDecl(Declaration); if (CursorKind == CXCursor_UnexposedDecl) { - // FIXME: Forward declarations of Objective-C classes and protocols - // are not directly exposed, but we want code completion to treat them + // FIXME: Forward declarations of Objective-C classes and protocols + // are not directly exposed, but we want code completion to treat them // like a definition. if (isa<ObjCInterfaceDecl>(Declaration)) CursorKind = CXCursor_ObjCInterfaceDecl; @@ -717,9 +717,9 @@ StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const { // Handle declarations below. break; } - + DeclarationName Name = Declaration->getDeclName(); - + // If the name is a simple identifier (by far the common case), or a // zero-argument selector, just return a reference to that identifier. if (IdentifierInfo *Id = Name.getAsIdentifierInfo()) @@ -728,12 +728,12 @@ StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const { if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0)) return Id->getName(); - + Saved = Name.getAsString(); return Saved; } - -bool clang::operator<(const CodeCompletionResult &X, + +bool clang::operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y) { std::string XSaved, YSaved; StringRef XStr = X.getOrderedName(XSaved); @@ -741,11 +741,11 @@ bool clang::operator<(const CodeCompletionResult &X, int cmp = XStr.compare_lower(YStr); if (cmp) return cmp < 0; - + // If case-insensitive comparison fails, try case-sensitive comparison. cmp = XStr.compare(YStr); if (cmp) return cmp < 0; - + return false; } diff --git a/lib/Sema/DeclSpec.cpp b/lib/Sema/DeclSpec.cpp index ccca5d37ea395..b22eea2b3642a 100644 --- a/lib/Sema/DeclSpec.cpp +++ b/lib/Sema/DeclSpec.cpp @@ -44,7 +44,7 @@ void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) { EndLocation = TemplateId->RAngleLoc; } -void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc, +void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, SourceLocation ColonColonLoc) { Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc); if (Range.getBegin().isInvalid()) @@ -56,23 +56,23 @@ void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc, } void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier, - SourceLocation IdentifierLoc, + SourceLocation IdentifierLoc, SourceLocation ColonColonLoc) { Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc); - + if (Range.getBegin().isInvalid()) Range.setBegin(IdentifierLoc); Range.setEnd(ColonColonLoc); - + assert(Range == Builder.getSourceRange() && "NestedNameSpecifierLoc range computation incorrect"); } void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace, - SourceLocation NamespaceLoc, + SourceLocation NamespaceLoc, SourceLocation ColonColonLoc) { Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc); - + if (Range.getBegin().isInvalid()) Range.setBegin(NamespaceLoc); Range.setEnd(ColonColonLoc); @@ -82,10 +82,10 @@ void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace, } void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias, - SourceLocation AliasLoc, + SourceLocation AliasLoc, SourceLocation ColonColonLoc) { Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc); - + if (Range.getBegin().isInvalid()) Range.setBegin(AliasLoc); Range.setEnd(ColonColonLoc); @@ -94,12 +94,12 @@ void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias, "NestedNameSpecifierLoc range computation incorrect"); } -void CXXScopeSpec::MakeGlobal(ASTContext &Context, +void CXXScopeSpec::MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc) { Builder.MakeGlobal(Context, ColonColonLoc); - + Range = SourceRange(ColonColonLoc); - + assert(Range == Builder.getSourceRange() && "NestedNameSpecifierLoc range computation incorrect"); } @@ -116,7 +116,7 @@ void CXXScopeSpec::MakeSuper(ASTContext &Context, CXXRecordDecl *RD, "NestedNameSpecifierLoc range computation incorrect"); } -void CXXScopeSpec::MakeTrivial(ASTContext &Context, +void CXXScopeSpec::MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R) { Builder.MakeTrivial(Context, Qualifier, R); Range = R; @@ -139,11 +139,11 @@ SourceLocation CXXScopeSpec::getLastQualifierNameLoc() const { return Builder.getTemporary().getLocalBeginLoc(); } -NestedNameSpecifierLoc +NestedNameSpecifierLoc CXXScopeSpec::getWithLocInContext(ASTContext &Context) const { if (!Builder.getRepresentation()) return NestedNameSpecifierLoc(); - + return Builder.getWithLocInContext(Context); } @@ -232,7 +232,7 @@ DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto, I.Fun.DeleteParams = true; } for (unsigned i = 0; i < NumParams; i++) - I.Fun.Params[i] = std::move(Params[i]); + I.Fun.Params[i] = std::move(Params[i]); } // Check what exception specification information we should actually store. @@ -323,7 +323,7 @@ bool Declarator::isDeclarationOfFunction() const { } llvm_unreachable("Invalid type chunk"); } - + switch (DS.getTypeSpecType()) { case TST_atomic: case TST_auto: @@ -369,20 +369,20 @@ bool Declarator::isDeclarationOfFunction() const { if (Expr *E = DS.getRepAsExpr()) return E->getType()->isFunctionType(); return false; - + case TST_underlyingType: case TST_typename: case TST_typeofType: { QualType QT = DS.getRepAsType().get(); if (QT.isNull()) return false; - + if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) QT = LIT->getType(); if (QT.isNull()) return false; - + return QT->isFunctionType(); } } @@ -438,8 +438,8 @@ template <class T> static bool BadSpecifier(T TNew, T TPrev, if (TNew != TPrev) DiagID = diag::err_invalid_decl_spec_combination; else - DiagID = IsExtension ? diag::ext_duplicate_declspec : - diag::warn_duplicate_declspec; + DiagID = IsExtension ? diag::ext_duplicate_declspec : + diag::warn_duplicate_declspec; return true; } @@ -970,7 +970,7 @@ bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, DiagID = diag::ext_duplicate_declspec; return true; } - + ModulePrivateLoc = Loc; return false; } @@ -1300,7 +1300,7 @@ bool DeclSpec::isMissingDeclaratorOk() { StorageClassSpec != DeclSpec::SCS_typedef; } -void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc, +void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc, OverloadedOperatorKind Op, SourceLocation SymbolLocations[3]) { Kind = UnqualifiedIdKind::IK_OperatorFunctionId; @@ -1309,7 +1309,7 @@ void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc, OperatorFunctionId.Operator = Op; for (unsigned I = 0; I != 3; ++I) { OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I].getRawEncoding(); - + if (SymbolLocations[I].isValid()) EndLocation = SymbolLocations[I]; } @@ -1321,7 +1321,7 @@ bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc, FirstLocation = Loc; LastLocation = Loc; LastSpecifier = VS; - + if (Specifiers & VS) { PrevSpec = getSpecifierName(VS); return true; diff --git a/lib/Sema/DelayedDiagnostic.cpp b/lib/Sema/DelayedDiagnostic.cpp index 122b477d55228..a064e492c0989 100644 --- a/lib/Sema/DelayedDiagnostic.cpp +++ b/lib/Sema/DelayedDiagnostic.cpp @@ -59,8 +59,8 @@ DelayedDiagnostic::makeAvailability(AvailabilityResult AR, void DelayedDiagnostic::Destroy() { switch (Kind) { - case Access: - getAccessData().~AccessedEntity(); + case Access: + getAccessData().~AccessedEntity(); break; case Availability: diff --git a/lib/Sema/IdentifierResolver.cpp b/lib/Sema/IdentifierResolver.cpp index dbd52dee1eea5..dba56931d49c3 100644 --- a/lib/Sema/IdentifierResolver.cpp +++ b/lib/Sema/IdentifierResolver.cpp @@ -46,7 +46,7 @@ class IdentifierResolver::IdDeclInfoMap { IdDeclInfoPool(IdDeclInfoPool *Next) : Next(Next) {} }; - + IdDeclInfoPool *CurPool = nullptr; unsigned int CurIndex = POOL_SIZE; @@ -171,9 +171,9 @@ void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) { DeclarationName Name = D->getDeclName(); if (IdentifierInfo *II = Name.getAsIdentifierInfo()) updatingIdentifier(*II); - + void *Ptr = Name.getFETokenInfo<void>(); - + if (!Ptr) { AddDecl(D); return; @@ -196,7 +196,7 @@ void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) { return; } - // General case: insert the declaration at the appropriate point in the + // General case: insert the declaration at the appropriate point in the // list, which already has at least two elements. IdDeclInfo *IDI = toIdDeclInfo(Ptr); if (Pos.isIterator()) { @@ -231,7 +231,7 @@ IdentifierResolver::iterator IdentifierResolver::begin(DeclarationName Name) { if (IdentifierInfo *II = Name.getAsIdentifierInfo()) readingIdentifier(*II); - + void *Ptr = Name.getFETokenInfo<void>(); if (!Ptr) return end(); @@ -258,7 +258,7 @@ enum DeclMatchKind { } // namespace /// Compare two declarations to see whether they are different or, -/// if they are the same, whether the new declaration should replace the +/// if they are the same, whether the new declaration should replace the /// existing declaration. static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) { // If the declarations are identical, ignore the new one. @@ -289,40 +289,40 @@ static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) { for (auto RD : New->redecls()) { if (RD == Existing) return DMK_Replace; - + if (RD->isCanonicalDecl()) break; } - + return DMK_Ignore; } - + return DMK_Different; } bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ if (IdentifierInfo *II = Name.getAsIdentifierInfo()) readingIdentifier(*II); - + void *Ptr = Name.getFETokenInfo<void>(); - + if (!Ptr) { Name.setFETokenInfo(D); return true; } - + IdDeclInfo *IDI; - + if (isDeclPtr(Ptr)) { NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr); - + switch (compareDeclarations(PrevD, D)) { case DMK_Different: break; - + case DMK_Ignore: return false; - + case DMK_Replace: Name.setFETokenInfo(D); return true; @@ -330,7 +330,7 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ Name.setFETokenInfo(nullptr); IDI = &(*IdDeclInfos)[Name]; - + // If the existing declaration is not visible in translation unit scope, // then add the new top-level declaration first. if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { @@ -341,28 +341,28 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ IDI->AddDecl(D); } return true; - } - + } + IDI = toIdDeclInfo(Ptr); // See whether this declaration is identical to any existing declarations. // If not, find the right place to insert it. - for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(), + for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(), IEnd = IDI->decls_end(); I != IEnd; ++I) { - + switch (compareDeclarations(*I, D)) { case DMK_Different: break; - + case DMK_Ignore: return false; - + case DMK_Replace: *I = D; return true; } - + if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) { // We've found a declaration that is not visible from the translation // unit (it's in an inner scope). Insert our declaration here. @@ -370,7 +370,7 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ return true; } } - + // Add the declaration to the end. IDI->AddDecl(D); return true; @@ -378,13 +378,13 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ void IdentifierResolver::readingIdentifier(IdentifierInfo &II) { if (II.isOutOfDate()) - PP.getExternalSource()->updateOutOfDateIdentifier(II); + PP.getExternalSource()->updateOutOfDateIdentifier(II); } void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) { if (II.isOutOfDate()) PP.getExternalSource()->updateOutOfDateIdentifier(II); - + if (II.isFromAST()) II.setFETokenInfoChangedSinceDeserialization(); } diff --git a/lib/Sema/MultiplexExternalSemaSource.cpp b/lib/Sema/MultiplexExternalSemaSource.cpp index 7e61ccbb1068b..50808effe007f 100644 --- a/lib/Sema/MultiplexExternalSemaSource.cpp +++ b/lib/Sema/MultiplexExternalSemaSource.cpp @@ -121,7 +121,7 @@ void MultiplexExternalSemaSource::FindExternalLexicalDecls( Sources[i]->FindExternalLexicalDecls(DC, IsKindWeWant, Result); } -void MultiplexExternalSemaSource::FindFileRegionDecls(FileID File, +void MultiplexExternalSemaSource::FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls){ @@ -179,13 +179,13 @@ bool MultiplexExternalSemaSource::DeclIsFromPCHWithObjectFile(const Decl *D) { } bool MultiplexExternalSemaSource::layoutRecordType(const RecordDecl *Record, - uint64_t &Size, + uint64_t &Size, uint64_t &Alignment, llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets){ for(size_t i = 0; i < Sources.size(); ++i) - if (Sources[i]->layoutRecordType(Record, Size, Alignment, FieldOffsets, + if (Sources[i]->layoutRecordType(Record, Size, Alignment, FieldOffsets, BaseOffsets, VirtualBaseOffsets)) return true; return false; @@ -243,10 +243,10 @@ void MultiplexExternalSemaSource::ReadMismatchingDeleteExpressions( Source->ReadMismatchingDeleteExpressions(Exprs); } -bool MultiplexExternalSemaSource::LookupUnqualified(LookupResult &R, Scope *S){ +bool MultiplexExternalSemaSource::LookupUnqualified(LookupResult &R, Scope *S){ for(size_t i = 0; i < Sources.size(); ++i) Sources[i]->LookupUnqualified(R, S); - + return !R.empty(); } @@ -255,13 +255,13 @@ void MultiplexExternalSemaSource::ReadTentativeDefinitions( for(size_t i = 0; i < Sources.size(); ++i) Sources[i]->ReadTentativeDefinitions(TentativeDefs); } - + void MultiplexExternalSemaSource::ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl*> &Decls) { for(size_t i = 0; i < Sources.size(); ++i) Sources[i]->ReadUnusedFileScopedDecls(Decls); } - + void MultiplexExternalSemaSource::ReadDelegatingConstructors( SmallVectorImpl<CXXConstructorDecl*> &Decls) { for(size_t i = 0; i < Sources.size(); ++i) diff --git a/lib/Sema/Sema.cpp b/lib/Sema/Sema.cpp index d57473c5616f4..49f3decc11517 100644 --- a/lib/Sema/Sema.cpp +++ b/lib/Sema/Sema.cpp @@ -1500,7 +1500,7 @@ LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { return CurLSI; } -// We have a generic lambda if we parsed auto parameters, or we have +// We have a generic lambda if we parsed auto parameters, or we have // an associated template parameter list. LambdaScopeInfo *Sema::getCurGenericLambda() { if (LambdaScopeInfo *LSI = getCurLambda()) { diff --git a/lib/Sema/SemaAccess.cpp b/lib/Sema/SemaAccess.cpp index 9fbae2ca297f5..e06792cae78ba 100644 --- a/lib/Sema/SemaAccess.cpp +++ b/lib/Sema/SemaAccess.cpp @@ -152,8 +152,8 @@ struct AccessTarget : public AccessedEntity { : AccessedEntity(Entity) { initialize(); } - - AccessTarget(ASTContext &Context, + + AccessTarget(ASTContext &Context, MemberNonce _, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, @@ -163,7 +163,7 @@ struct AccessTarget : public AccessedEntity { initialize(); } - AccessTarget(ASTContext &Context, + AccessTarget(ASTContext &Context, BaseNonce _, CXXRecordDecl *BaseClass, CXXRecordDecl *DerivedClass, @@ -777,7 +777,7 @@ static AccessResult HasAccess(Sema &S, // We interpret this as a restriction on [M3]. // In this part of the code, 'C' is just our context class ECRecord. - + // These rules are different if we don't have an instance context. if (!Target.hasInstanceContext()) { // If it's not an instance member, these restrictions don't apply. @@ -1272,8 +1272,8 @@ static void DiagnoseBadAccess(Sema &S, SourceLocation Loc, DiagnoseAccessPath(S, EC, Entity); } -/// MSVC has a bug where if during an using declaration name lookup, -/// the declaration found is unaccessible (private) and that declaration +/// MSVC has a bug where if during an using declaration name lookup, +/// the declaration found is unaccessible (private) and that declaration /// was bring into scope via another using declaration whose target /// declaration is accessible (public) then no error is generated. /// Example: @@ -1290,15 +1290,15 @@ static void DiagnoseBadAccess(Sema &S, SourceLocation Loc, /// using B::f; /// }; /// -/// Here, B::f is private so this should fail in Standard C++, but +/// Here, B::f is private so this should fail in Standard C++, but /// because B::f refers to A::f which is public MSVC accepts it. -static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S, +static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S, SourceLocation AccessLoc, AccessTarget &Entity) { if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) { const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl(); - if (Entity.getTargetDecl()->getAccess() == AS_private && + if (Entity.getTargetDecl()->getAccess() == AS_private && (OrigDecl->getAccess() == AS_public || OrigDecl->getAccess() == AS_protected)) { S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible) @@ -1536,7 +1536,7 @@ Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, Found.getAccess() == AS_public) return AR_accessible; - AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(), + AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(), Found, QualType()); Entity.setDiag(diag::err_access) << E->getSourceRange(); @@ -1691,7 +1691,7 @@ Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc, AccessEntity.setDiag(PD); return CheckAccess(*this, UseLoc, AccessEntity); -} +} /// Checks access to an overloaded operator new or delete. Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc, @@ -1823,7 +1823,7 @@ Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc, BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl()); DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl()); - AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD, + AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD, Path.Access); if (DiagID) Entity.setDiag(DiagID) << Derived << Base; @@ -1893,7 +1893,7 @@ bool Sema::IsSimplyAccessible(NamedDecl *Target, DeclContext *Ctx) { if (ObjCMethodDecl *MD = getCurMethodDecl()) ClassOfMethodDecl = MD->getClassInterface(); else if (FunctionDecl *FD = getCurFunctionDecl()) { - if (ObjCImplDecl *Impl + if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) { if (ObjCImplementationDecl *IMPD = dyn_cast<ObjCImplementationDecl>(Impl)) @@ -1903,21 +1903,21 @@ bool Sema::IsSimplyAccessible(NamedDecl *Target, DeclContext *Ctx) { ClassOfMethodDecl = CatImplClass->getClassInterface(); } } - + // If we're not in an interface, this ivar is inaccessible. if (!ClassOfMethodDecl) return false; - + // If we're inside the same interface that owns the ivar, we're fine. if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface())) return true; - + // If the ivar is private, it's inaccessible. if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private) return false; - + return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl); } - + return true; } diff --git a/lib/Sema/SemaAttr.cpp b/lib/Sema/SemaAttr.cpp index 4f3cf4633c809..1a8a000753062 100644 --- a/lib/Sema/SemaAttr.cpp +++ b/lib/Sema/SemaAttr.cpp @@ -268,7 +268,7 @@ void Sema::DiagnoseUnterminatedPragmaPack() { } } -void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) { +void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) { MSStructPragmaOn = (Kind == PMSST_ON); } @@ -693,7 +693,7 @@ void Sema::AddRangeBasedOptnone(FunctionDecl *FD) { AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation); } -void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, +void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc) { // Don't add a conflicting attribute. No diagnostic is needed. if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>()) diff --git a/lib/Sema/SemaCXXScopeSpec.cpp b/lib/Sema/SemaCXXScopeSpec.cpp index f2fad825c3e78..4e39d0675471e 100644 --- a/lib/Sema/SemaCXXScopeSpec.cpp +++ b/lib/Sema/SemaCXXScopeSpec.cpp @@ -401,18 +401,18 @@ bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, isDependent = isDependentScopeSpecifier(SS); Found.setContextRange(SS.getRange()); } - + if (LookupCtx) { // Perform "qualified" name lookup into the declaration context we // computed, which is either the type of the base of a member access // expression or the declaration context associated with a prior // nested-name-specifier. - + // The declaration context must be complete. if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS, LookupCtx)) return false; - + LookupQualifiedName(Found, LookupCtx); } else if (isDependent) { return false; @@ -420,7 +420,7 @@ bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, LookupName(Found, S); } Found.suppressDiagnostics(); - + return Found.getAsSingle<NamespaceDecl>(); } @@ -739,7 +739,7 @@ bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, = TLB.push<UnresolvedUsingTypeLoc>(T); UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc); } else if (isa<SubstTemplateTypeParmType>(T)) { - SubstTemplateTypeParmTypeLoc TL + SubstTemplateTypeParmTypeLoc TL = TLB.push<SubstTemplateTypeParmTypeLoc>(T); TL.setNameLoc(IdInfo.IdentifierLoc); } else if (isa<SubstTemplateTypeParmPackType>(T)) { @@ -772,11 +772,11 @@ bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, } // In Microsoft mode, if we are within a templated function and we can't - // resolve Identifier, then extend the SS with Identifier. This will have - // the effect of resolving Identifier during template instantiation. + // resolve Identifier, then extend the SS with Identifier. This will have + // the effect of resolving Identifier during template instantiation. // The goal is to be able to resolve a function call whose // nested-name-specifier is located inside a dependent base class. - // Example: + // Example: // // class C { // public: @@ -850,7 +850,7 @@ bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, return true; if (!T->isDependentType() && !T->getAs<TagType>()) { - Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) + Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) << T << getLangOpts().CPlusPlus; return true; } @@ -891,7 +891,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, bool EnteringContext) { if (SS.isInvalid()) return true; - + // Translate the parser's template argument list in our AST format. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); translateTemplateArguments(TemplateArgsIn, TemplateArgs); @@ -905,7 +905,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, DTN->getQualifier(), DTN->getIdentifier(), TemplateArgs); - + // Create source-location information for this type. TypeLocBuilder Builder; DependentTemplateSpecializationTypeLoc SpecTL @@ -918,7 +918,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, SpecTL.setRAngleLoc(RAngleLoc); for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); - + SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T), CCLoc); return false; @@ -937,7 +937,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, return true; } - // We were able to resolve the template name to an actual template. + // We were able to resolve the template name to an actual template. // Build an appropriate nested-name-specifier. QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc, TemplateArgs); @@ -971,7 +971,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, namespace { /// A structure that stores a nested-name-specifier annotation, - /// including both the nested-name-specifier + /// including both the nested-name-specifier struct NestedNameSpecifierAnnotation { NestedNameSpecifier *NNS; }; @@ -991,14 +991,14 @@ void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) { return Annotation; } -void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, +void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, SourceRange AnnotationRange, CXXScopeSpec &SS) { if (!AnnotationPtr) { SS.SetInvalid(AnnotationRange); return; } - + NestedNameSpecifierAnnotation *Annotation = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr); SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1)); @@ -1065,7 +1065,7 @@ bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) { // it is a complete declaration context. if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC)) return true; - + EnterDeclaratorContext(S, DC); // Rebuild the nested name specifier for the new scope. diff --git a/lib/Sema/SemaCast.cpp b/lib/Sema/SemaCast.cpp index b7f4629fbab75..57aac80f5ad2e 100644 --- a/lib/Sema/SemaCast.cpp +++ b/lib/Sema/SemaCast.cpp @@ -205,13 +205,13 @@ static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExp CXXCastPath &BasePath); static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, - QualType DestType, + QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization); static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, - QualType DestType, + QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, @@ -319,7 +319,7 @@ Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, return ExprError(); DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); } - + return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), &Op.BasePath, DestTInfo, @@ -573,11 +573,11 @@ CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, "Destination type is not pointer or pointer to member."); } - QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), + QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), UnwrappedDestType = Self.Context.getCanonicalType(DestType); - // Find the qualifiers. We only care about cvr-qualifiers for the - // purpose of this check, because other qualifiers (address spaces, + // Find the qualifiers. We only care about cvr-qualifiers for the + // purpose of this check, because other qualifiers (address spaces, // Objective-C GC, etc.) are part of the type's identity. QualType PrevUnwrappedSrcType = UnwrappedSrcType; QualType PrevUnwrappedDestType = UnwrappedDestType; @@ -719,7 +719,7 @@ void CastOperation::CheckDynamicCast() { // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to // complete class type, [...]. If T is an lvalue reference type, v shall be - // an lvalue of a complete class type, [...]. If T is an rvalue reference + // an lvalue of a complete class type, [...]. If T is an rvalue reference // type, v shall be an expression having a complete class type, [...] QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); QualType SrcPointee; @@ -788,7 +788,7 @@ void CastOperation::CheckDynamicCast() { if (DestRecord && Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, - OpRange.getBegin(), OpRange, + OpRange.getBegin(), OpRange, &BasePath)) { SrcExpr = ExprError(); return; @@ -950,15 +950,15 @@ void CastOperation::CheckReinterpretCast() { return; unsigned msg = diag::err_bad_cxx_cast_generic; - TryCastResult tcr = - TryReinterpretCast(Self, SrcExpr, DestType, + TryCastResult tcr = + TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg, Kind); if (tcr != TC_Success && msg != 0) { if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { - //FIXME: &f<int>; is overloaded and resolvable - Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) + //FIXME: &f<int>; is overloaded and resolvable + Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) << OverloadExpr::find(SrcExpr.get()).Expression->getName() << DestType << OpRange; Self.NoteAllOverloadCandidates(SrcExpr.get()); @@ -996,8 +996,8 @@ void CastOperation::CheckStaticCast() { Kind = CK_ToVoid; if (claimPlaceholder(BuiltinType::Overload)) { - Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, - false, // Decay Function to ptr + Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, + false, // Decay Function to ptr true, // Complain OpRange, DestType, diag::err_bad_static_cast_overload); if (SrcExpr.isInvalid()) @@ -1025,7 +1025,7 @@ void CastOperation::CheckStaticCast() { if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) - << oe->getName() << DestType << OpRange + << oe->getName() << DestType << OpRange << oe->getQualifierLoc().getSourceRange(); Self.NoteAllOverloadCandidates(SrcExpr.get()); } else { @@ -1048,15 +1048,15 @@ void CastOperation::CheckStaticCast() { /// possible. If @p CStyle, ignore access restrictions on hierarchy casting /// and casting away constness. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, - QualType DestType, + QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath, bool ListInitialization) { // Determine whether we have the semantics of a C-style cast. - bool CStyle + bool CStyle = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); - + // The order the tests is not entirely arbitrary. There is one conversion // that can be handled in two different ways. Given: // struct A {}; @@ -1082,7 +1082,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, if (tcr != TC_NotApplicable) return tcr; - // C++11 [expr.static.cast]p3: + // C++11 [expr.static.cast]p3: // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, @@ -1098,7 +1098,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, return TC_Failed; if (tcr != TC_NotApplicable) return tcr; - + // C++ 5.2.9p6: May apply the reverse of any standard conversion, except // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean // conversions, subject to further restrictions. @@ -1126,7 +1126,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, } } } - + // Reverse integral promotion/conversion. All such conversions are themselves // again integral promotions or conversions and are thus already handled by // p2 (TryDirectInitialization above). @@ -1199,7 +1199,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, } } else if (DestType->isObjCObjectPointerType()) { - // allow both c-style cast and static_cast of objective-c pointers as + // allow both c-style cast and static_cast of objective-c pointers as // they are pervasive. Kind = CK_CPointerToObjCPointerCast; return TC_Success; @@ -1230,7 +1230,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, if (SrcPointer->getPointeeType()->getAs<RecordType>() && DestPointer->getPointeeType()->getAs<RecordType>()) msg = diag::err_bad_cxx_cast_unrelated_class; - + // We tried everything. Everything! Nothing works! :-( return TC_NotApplicable; } @@ -1284,11 +1284,11 @@ TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(), R->getPointeeType(), Paths)) return TC_NotApplicable; - + Self.BuildBasePathArray(Paths, BasePath); } else Kind = CK_NoOp; - + return TC_Success; } @@ -1323,8 +1323,8 @@ TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, // FIXME: If the source is a prvalue, we should issue a warning (because the // cast always has undefined behavior), and for AST consistency, we should // materialize a temporary. - return TryStaticDowncast(Self, - Self.Context.getCanonicalType(SrcExpr->getType()), + return TryStaticDowncast(Self, + Self.Context.getCanonicalType(SrcExpr->getType()), Self.Context.getCanonicalType(DestPointee), CStyle, OpRange, SrcExpr->getType(), DestType, msg, Kind, BasePath); @@ -1355,9 +1355,9 @@ TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, return TC_NotApplicable; } - return TryStaticDowncast(Self, + return TryStaticDowncast(Self, Self.Context.getCanonicalType(SrcPointer->getPointeeType()), - Self.Context.getCanonicalType(DestPointer->getPointeeType()), + Self.Context.getCanonicalType(DestPointer->getPointeeType()), CStyle, OpRange, SrcType, DestType, msg, Kind, BasePath); } @@ -1368,7 +1368,7 @@ TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, bool CStyle, SourceRange OpRange, QualType OrigSrcType, - QualType OrigDestType, unsigned &msg, + QualType OrigDestType, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { // We can only work with complete types. But don't complain if it doesn't work if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || @@ -1434,7 +1434,7 @@ TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, } Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) - << QualType(SrcType).getUnqualifiedType() + << QualType(SrcType).getUnqualifiedType() << QualType(DestType).getUnqualifiedType() << PathDisplayStr << OpRange; msg = 0; @@ -1478,8 +1478,8 @@ TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, /// where B is a base class of D [...]. /// TryCastResult -TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, - QualType DestType, bool CStyle, +TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, + QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { @@ -1499,7 +1499,7 @@ TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, WasOverloadedFunction = true; } } - + const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); if (!SrcMemPtr) { msg = diag::err_bad_static_cast_member_pointer_nonmp; @@ -1569,8 +1569,8 @@ TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, if (WasOverloadedFunction) { // Resolve the address of the overloaded function again, this time // allowing complaints if something goes wrong. - FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), - DestType, + FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), + DestType, true, FoundOverload); if (!Fn) { @@ -1597,7 +1597,7 @@ TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, /// @c static_cast if the declaration "T t(e);" is well-formed [...]. TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, - Sema::CheckedConversionKind CCK, + Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization) { if (DestType->isRecordType()) { @@ -1625,26 +1625,26 @@ TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); // At this point of CheckStaticCast, if the destination is a reference, - // or the expression is an overload expression this has to work. + // or the expression is an overload expression this has to work. // There is no other way that works. // On the other hand, if we're checking a C-style cast, we've still got // the reinterpret_cast way. - bool CStyle + bool CStyle = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) return TC_NotApplicable; - + ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); if (Result.isInvalid()) { msg = 0; return TC_Failed; } - + if (InitSeq.isConstructorInitialization()) Kind = CK_ConstructorConversion; else Kind = CK_NoOp; - + SrcExpr = Result; return TC_Success; } @@ -1976,7 +1976,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, unsigned &msg, CastKind &Kind) { bool IsLValueCast = false; - + DestType = Self.Context.getCanonicalType(DestType); QualType SrcType = SrcExpr.get()->getType(); @@ -2019,7 +2019,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, // FIXME: Use a specific diagnostic for the rest of these cases. case OK_VectorComponent: inappropriate = "vector element"; break; case OK_ObjCProperty: inappropriate = "property expression"; break; - case OK_ObjCSubscript: inappropriate = "container subscripting expression"; + case OK_ObjCSubscript: inappropriate = "container subscripting expression"; break; } if (inappropriate) { @@ -2033,7 +2033,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, // This code does this transformation for the checked types. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); SrcType = Self.Context.getPointerType(SrcType); - + IsLValueCast = true; } @@ -2121,18 +2121,18 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; else msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; - + return TC_Failed; } if (SrcType == DestType) { // C++ 5.2.10p2 has a note that mentions that, subject to all other // restrictions, a cast to the same type is allowed so long as it does not - // cast away constness. In C++98, the intent was not entirely clear here, + // cast away constness. In C++98, the intent was not entirely clear here, // since all other paragraphs explicitly forbid casts to the same type. // C++11 clarifies this case with p2. // - // The only allowed types are: integral, enumeration, pointer, or + // The only allowed types are: integral, enumeration, pointer, or // pointer-to-member types. We also won't restrict Obj-C pointers either. Kind = CK_NoOp; TryCastResult Result = TC_NotApplicable; @@ -2260,7 +2260,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, << OpRange; return SuccessResult; } - + // C++ 5.2.10p7: A pointer to an object can be explicitly converted to // a pointer to an object of different type. // Void pointers are not specified, but supported by every compiler out there. @@ -2296,7 +2296,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, if (claimPlaceholder(BuiltinType::Overload)) { Self.ResolveAndFixSingleFunctionTemplateSpecialization( - SrcExpr, /* Decay Function to ptr */ false, + SrcExpr, /* Decay Function to ptr */ false, /* Complain */ true, DestRange, DestType, diag::err_bad_cstyle_cast_overload); if (SrcExpr.isInvalid()) @@ -2404,7 +2404,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, } } -/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a +/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a /// non-matching type. Such as enum function call to int, int call to /// pointer; etc. Cast to 'void' is an exception. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, @@ -2412,10 +2412,10 @@ static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, if (Self.Diags.isIgnored(diag::warn_bad_function_cast, SrcExpr.get()->getExprLoc())) return; - + if (!isa<CallExpr>(SrcExpr.get())) return; - + QualType SrcType = SrcExpr.get()->getType(); if (DestType.getUnqualifiedType()->isVoidType()) return; @@ -2434,7 +2434,7 @@ static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, return; if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) return; - + Self.Diag(SrcExpr.get()->getExprLoc(), diag::warn_bad_function_cast) << SrcType << DestType << SrcExpr.get()->getSourceRange(); @@ -2641,26 +2641,26 @@ void CastOperation::CheckCStyleCast() { if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); - if (CastPtr->getPointeeType()->isObjCLifetimeType() && + if (CastPtr->getPointeeType()->isObjCLifetimeType() && ExprPtr->getPointeeType()->isObjCLifetimeType() && !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { - Self.Diag(SrcExpr.get()->getLocStart(), + Self.Diag(SrcExpr.get()->getLocStart(), diag::err_typecheck_incompatible_ownership) << SrcType << DestType << Sema::AA_Casting << SrcExpr.get()->getSourceRange(); return; } } - } + } else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { - Self.Diag(SrcExpr.get()->getLocStart(), + Self.Diag(SrcExpr.get()->getLocStart(), diag::err_arc_convesion_of_weak_unavailable) << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } - + DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); DiagnoseBadFunctionCast(Self, SrcExpr, DestType); @@ -2714,7 +2714,7 @@ ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, TypeSourceInfo *CastTypeInfo, SourceLocation RPLoc, Expr *CastExpr) { - CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); + CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp index 8d953b6ef3413..93dbeab5b0344 100644 --- a/lib/Sema/SemaChecking.cpp +++ b/lib/Sema/SemaChecking.cpp @@ -119,7 +119,7 @@ static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { // Highlight all the excess arguments. SourceRange range(call->getArg(desiredArgCount)->getLocStart(), call->getArg(argCount - 1)->getLocEnd()); - + return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) << 0 /*function call*/ << desiredArgCount << argCount << call->getArg(1)->getSourceRange(); @@ -888,18 +888,18 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); if (Error != ASTContext::GE_None) ICEArguments = 0; // Don't diagnose previously diagnosed errors. - + // If any arguments are required to be ICE's, check and diagnose. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { // Skip arguments not required to be ICE's. if ((ICEArguments & (1 << ArgNo)) == 0) continue; - + llvm::APSInt Result; if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) return true; ICEArguments &= ~(1 << ArgNo); } - + switch (BuiltinID) { case Builtin::BI__builtin___CFStringMakeConstantString: assert(TheCall->getNumArgs() == 1 && @@ -3850,7 +3850,7 @@ DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, static bool isNonNullType(ASTContext &ctx, QualType type) { if (auto nullability = type->getNullability(ctx)) return *nullability == NullabilityKind::NonNull; - + return false; } @@ -3893,12 +3893,12 @@ static void CheckNonNullArguments(Sema &S, parms = FD->parameters(); else parms = cast<ObjCMethodDecl>(FDecl)->parameters(); - + unsigned ParamIndex = 0; for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); I != E; ++I, ++ParamIndex) { const ParmVarDecl *PVD = *I; - if (PVD->hasAttr<NonNullAttr>() || + if (PVD->hasAttr<NonNullAttr>() || isNonNullType(S.Context, PVD->getType())) { if (NonNullArgs.empty()) NonNullArgs.resize(Args.size()); @@ -3920,7 +3920,7 @@ static void CheckNonNullArguments(Sema &S, // Dig out the function prototype, if there is one. Proto = type->getAs<FunctionProtoType>(); - } + } } // Fill in non-null argument information from the nullability @@ -3931,17 +3931,17 @@ static void CheckNonNullArguments(Sema &S, if (isNonNullType(S.Context, paramType)) { if (NonNullArgs.empty()) NonNullArgs.resize(Args.size()); - + NonNullArgs.set(Index); } - + ++Index; } } } // Check for non-null arguments. - for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); + for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); ArgIndex != ArgIndexEnd; ++ArgIndex) { if (NonNullArgs[ArgIndex]) CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); @@ -4074,7 +4074,7 @@ bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, return false; } -bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, +bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, ArrayRef<const Expr *> Args) { VariadicCallType CallType = Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; @@ -4577,7 +4577,7 @@ ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), SubExprs, ResultType, Op, TheCall->getRParenLoc()); - + if ((Op == AtomicExpr::AO__c11_atomic_load || Op == AtomicExpr::AO__c11_atomic_store || Op == AtomicExpr::AO__opencl_atomic_load || @@ -4744,52 +4744,52 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { bool WarnAboutSemanticsChange = false; switch (BuiltinID) { default: llvm_unreachable("Unknown overloaded atomic builtin!"); - case Builtin::BI__sync_fetch_and_add: + case Builtin::BI__sync_fetch_and_add: case Builtin::BI__sync_fetch_and_add_1: case Builtin::BI__sync_fetch_and_add_2: case Builtin::BI__sync_fetch_and_add_4: case Builtin::BI__sync_fetch_and_add_8: case Builtin::BI__sync_fetch_and_add_16: - BuiltinIndex = 0; + BuiltinIndex = 0; break; - - case Builtin::BI__sync_fetch_and_sub: + + case Builtin::BI__sync_fetch_and_sub: case Builtin::BI__sync_fetch_and_sub_1: case Builtin::BI__sync_fetch_and_sub_2: case Builtin::BI__sync_fetch_and_sub_4: case Builtin::BI__sync_fetch_and_sub_8: case Builtin::BI__sync_fetch_and_sub_16: - BuiltinIndex = 1; + BuiltinIndex = 1; break; - - case Builtin::BI__sync_fetch_and_or: + + case Builtin::BI__sync_fetch_and_or: case Builtin::BI__sync_fetch_and_or_1: case Builtin::BI__sync_fetch_and_or_2: case Builtin::BI__sync_fetch_and_or_4: case Builtin::BI__sync_fetch_and_or_8: case Builtin::BI__sync_fetch_and_or_16: - BuiltinIndex = 2; + BuiltinIndex = 2; break; - - case Builtin::BI__sync_fetch_and_and: + + case Builtin::BI__sync_fetch_and_and: case Builtin::BI__sync_fetch_and_and_1: case Builtin::BI__sync_fetch_and_and_2: case Builtin::BI__sync_fetch_and_and_4: case Builtin::BI__sync_fetch_and_and_8: case Builtin::BI__sync_fetch_and_and_16: - BuiltinIndex = 3; + BuiltinIndex = 3; break; - case Builtin::BI__sync_fetch_and_xor: + case Builtin::BI__sync_fetch_and_xor: case Builtin::BI__sync_fetch_and_xor_1: case Builtin::BI__sync_fetch_and_xor_2: case Builtin::BI__sync_fetch_and_xor_4: case Builtin::BI__sync_fetch_and_xor_8: case Builtin::BI__sync_fetch_and_xor_16: - BuiltinIndex = 4; + BuiltinIndex = 4; break; - case Builtin::BI__sync_fetch_and_nand: + case Builtin::BI__sync_fetch_and_nand: case Builtin::BI__sync_fetch_and_nand_1: case Builtin::BI__sync_fetch_and_nand_2: case Builtin::BI__sync_fetch_and_nand_4: @@ -4799,43 +4799,43 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { WarnAboutSemanticsChange = true; break; - case Builtin::BI__sync_add_and_fetch: + case Builtin::BI__sync_add_and_fetch: case Builtin::BI__sync_add_and_fetch_1: case Builtin::BI__sync_add_and_fetch_2: case Builtin::BI__sync_add_and_fetch_4: case Builtin::BI__sync_add_and_fetch_8: case Builtin::BI__sync_add_and_fetch_16: - BuiltinIndex = 6; + BuiltinIndex = 6; break; - - case Builtin::BI__sync_sub_and_fetch: + + case Builtin::BI__sync_sub_and_fetch: case Builtin::BI__sync_sub_and_fetch_1: case Builtin::BI__sync_sub_and_fetch_2: case Builtin::BI__sync_sub_and_fetch_4: case Builtin::BI__sync_sub_and_fetch_8: case Builtin::BI__sync_sub_and_fetch_16: - BuiltinIndex = 7; + BuiltinIndex = 7; break; - - case Builtin::BI__sync_and_and_fetch: + + case Builtin::BI__sync_and_and_fetch: case Builtin::BI__sync_and_and_fetch_1: case Builtin::BI__sync_and_and_fetch_2: case Builtin::BI__sync_and_and_fetch_4: case Builtin::BI__sync_and_and_fetch_8: case Builtin::BI__sync_and_and_fetch_16: - BuiltinIndex = 8; + BuiltinIndex = 8; break; - - case Builtin::BI__sync_or_and_fetch: + + case Builtin::BI__sync_or_and_fetch: case Builtin::BI__sync_or_and_fetch_1: case Builtin::BI__sync_or_and_fetch_2: case Builtin::BI__sync_or_and_fetch_4: case Builtin::BI__sync_or_and_fetch_8: case Builtin::BI__sync_or_and_fetch_16: - BuiltinIndex = 9; + BuiltinIndex = 9; break; - - case Builtin::BI__sync_xor_and_fetch: + + case Builtin::BI__sync_xor_and_fetch: case Builtin::BI__sync_xor_and_fetch_1: case Builtin::BI__sync_xor_and_fetch_2: case Builtin::BI__sync_xor_and_fetch_4: @@ -4844,7 +4844,7 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { BuiltinIndex = 10; break; - case Builtin::BI__sync_nand_and_fetch: + case Builtin::BI__sync_nand_and_fetch: case Builtin::BI__sync_nand_and_fetch_1: case Builtin::BI__sync_nand_and_fetch_2: case Builtin::BI__sync_nand_and_fetch_4: @@ -4863,7 +4863,7 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { BuiltinIndex = 12; NumFixed = 2; break; - + case Builtin::BI__sync_bool_compare_and_swap: case Builtin::BI__sync_bool_compare_and_swap_1: case Builtin::BI__sync_bool_compare_and_swap_2: @@ -4874,16 +4874,16 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { NumFixed = 2; ResultType = Context.BoolTy; break; - + case Builtin::BI__sync_lock_test_and_set: case Builtin::BI__sync_lock_test_and_set_1: case Builtin::BI__sync_lock_test_and_set_2: case Builtin::BI__sync_lock_test_and_set_4: case Builtin::BI__sync_lock_test_and_set_8: case Builtin::BI__sync_lock_test_and_set_16: - BuiltinIndex = 14; + BuiltinIndex = 14; break; - + case Builtin::BI__sync_lock_release: case Builtin::BI__sync_lock_release_1: case Builtin::BI__sync_lock_release_2: @@ -4894,14 +4894,14 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { NumFixed = 0; ResultType = Context.VoidTy; break; - - case Builtin::BI__sync_swap: + + case Builtin::BI__sync_swap: case Builtin::BI__sync_swap_1: case Builtin::BI__sync_swap_2: case Builtin::BI__sync_swap_4: case Builtin::BI__sync_swap_8: case Builtin::BI__sync_swap_16: - BuiltinIndex = 16; + BuiltinIndex = 16; break; } @@ -5410,7 +5410,7 @@ bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { } } } - + return false; } @@ -5787,13 +5787,13 @@ bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, Expr *Arg = TheCall->getArg(ArgNum); DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); - + if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; - + if (!Arg->isIntegerConstantExpr(Result, Context)) return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) << FDecl->getDeclName() << Arg->getSourceRange(); - + return false; } @@ -5964,7 +5964,7 @@ bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { // TODO: This is less than ideal. Overload this to take a value. if (SemaBuiltinConstantArg(TheCall, 1, Result)) return true; - + if (Result != 1) return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); @@ -6231,7 +6231,7 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, // cannot contain format specifiers and thus are not a security // liability. return SLCT_UncheckedLiteral; - + case Stmt::DeclRefExprClass: { const DeclRefExpr *DR = cast<DeclRefExpr>(E); @@ -6626,14 +6626,14 @@ protected: void HandlePositionalNonpositionalArgs(SourceLocation Loc, const char *startSpec, unsigned specifierLen); - + SourceRange getFormatStringRange(); CharSourceRange getSpecifierRange(const char *startSpecifier, unsigned specifierLen); SourceLocation getLocationOfByte(const char *x); const Expr *getDataArg(unsigned i) const; - + bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, const analyze_format_string::ConversionSpecifier &CS, const char *startSpecifier, unsigned specifierLen, @@ -7052,7 +7052,7 @@ public: const char *startSpecifier, unsigned specifierLen); bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E); - + void HandleEmptyObjCModifierFlag(const char *startFlag, unsigned flagLen) override; @@ -7061,7 +7061,7 @@ public: void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, const char *flagsEnd, - const char *conversionPosition) + const char *conversionPosition) override; }; @@ -7073,7 +7073,7 @@ bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( unsigned specifierLen) { const analyze_printf::PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); - + return HandleInvalidConversionSpecifier(FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier, specifierLen, @@ -7736,7 +7736,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, CastFix << ")"; SmallVector<FixItHint,4> Hints; - if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) + if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { @@ -7777,7 +7777,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, SpecRange, Hints); } else { // In this case, the expression could be printed using a different - // specifier, but we've decided that the specifier is probably correct + // specifier, but we've decided that the specifier is probably correct // and we should cast instead. Just use the normal warning message. EmitFormatDiagnostic( S.PDiag(diag::warn_format_conversion_argument_type_mismatch) @@ -7852,7 +7852,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, //===--- CHECK: Scanf format string checking ------------------------------===// -namespace { +namespace { class CheckScanfHandler : public CheckFormatHandler { public: @@ -7872,7 +7872,7 @@ public: bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, unsigned specifierLen) override; - + bool HandleInvalidScanfConversionSpecifier( const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, @@ -7908,7 +7908,7 @@ bool CheckScanfHandler::HandleScanfSpecifier( const char *startSpecifier, unsigned specifierLen) { using namespace analyze_scanf; - using namespace analyze_format_string; + using namespace analyze_format_string; const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); @@ -7925,7 +7925,7 @@ bool CheckScanfHandler::HandleScanfSpecifier( return false; } } - + // Check if the field with is non-zero. const OptionalAmount &Amt = FS.getFieldWidth(); if (Amt.getHowSpecified() == OptionalAmount::Constant) { @@ -8981,7 +8981,7 @@ void Sema::CheckMemaccessArguments(const CallExpr *Call, else if (BId == Builtin::BImemcmp) OperationType = 3; } - + DiagRuntimeBehavior( Dest->getExprLoc(), Dest, PDiag(diag::warn_dyn_class_memaccess) @@ -9035,7 +9035,7 @@ static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); - + if (isa<IntegerLiteral>(RHS)) Ex = LHS; else if (isa<IntegerLiteral>(LHS)) @@ -9077,7 +9077,7 @@ void Sema::CheckStrlcpycatArguments(const CallExpr *Call, if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, Call->getLocStart(), Call->getRParenLoc())) return; - + // Look for 'strlcpy(dst, x, sizeof(x))' if (const Expr *Ex = getSizeOfExprArg(SizeArg)) CompareWithSrc = Ex; @@ -9100,16 +9100,16 @@ void Sema::CheckStrlcpycatArguments(const CallExpr *Call, const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); if (!SrcArgDRE) return; - + const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); - if (!CompareWithSrcDRE || + if (!CompareWithSrcDRE || SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) return; - + const Expr *OriginalSizeArg = Call->getArg(2); Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) << OriginalSizeArg->getSourceRange() << FnName; - + // Output a FIXIT hint if the destination is an array (rather than a // pointer to an array). This could be enhanced to handle some // pointers if we know the actual size, like if DstArg is 'array+2' @@ -9123,7 +9123,7 @@ void Sema::CheckStrlcpycatArguments(const CallExpr *Call, OS << "sizeof("; DstArg->printPretty(OS, nullptr, getPrintingPolicy()); OS << ")"; - + Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), OS.str()); @@ -10271,7 +10271,7 @@ static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { } /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. -static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, +static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow = false) { if (pruneControlFlow) { @@ -10876,7 +10876,7 @@ CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, // We also want to warn about it in -Wconversion. // So if -Wconversion is off, use a completely identical diagnostic // in the sign-compare group. - // The conditional-checking code will + // The conditional-checking code will if (ICContext) { DiagID = diag::warn_impcast_integer_sign_conditional; *ICContext = true; @@ -10897,7 +10897,7 @@ CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, Source = S.Context.getCanonicalType(SourceType).getTypePtr(); } } - + if (const EnumType *SourceEnum = Source->getAs<EnumType>()) if (const EnumType *TargetEnum = Target->getAs<EnumType>()) if (SourceEnum->getDecl()->hasNameForLinkage() && @@ -10906,7 +10906,7 @@ CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, if (S.SourceMgr.isInSystemMacro(CC)) return; - return DiagnoseImpCast(S, E, SourceType, T, CC, + return DiagnoseImpCast(S, E, SourceType, T, CC, diag::warn_impcast_different_enum_types); } } @@ -10945,7 +10945,7 @@ static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, // ...then check whether it would have warned about either of the // candidates for a signedness conversion to the condition type. if (E->getType() == T) return; - + Suspicious = false; CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), E->getType(), CC, &Suspicious); @@ -12426,11 +12426,11 @@ namespace { } void VisitBlockExpr(BlockExpr *block) { - // Look inside nested blocks + // Look inside nested blocks if (block->getBlockDecl()->capturesVariable(Variable)) Visit(block->getBlockDecl()->getBody()); } - + void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { if (Capturer) return; if (OVE->getSourceExpr()) @@ -12483,7 +12483,7 @@ static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { } } } - + BlockExpr *block = dyn_cast<BlockExpr>(e); if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) return nullptr; @@ -12736,12 +12736,12 @@ void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { RetainCycleOwner Owner; if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) return; - + // Because we don't have an expression for the variable, we have to set the // location explicitly here. Owner.Loc = Var->getLocation(); Owner.Range = Var->getSourceRange(); - + if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) diagnoseRetainCycle(*this, Capturer, Owner); } @@ -12814,7 +12814,7 @@ void Sema::checkUnsafeExprAssigns(SourceLocation Loc, if (PD) LHSType = PD->getType(); } - + if (LHSType.isNull()) LHSType = LHS->getType(); @@ -12831,14 +12831,14 @@ void Sema::checkUnsafeExprAssigns(SourceLocation Loc, // FIXME. Check for other life times. if (LT != Qualifiers::OCL_None) return; - + if (PRE) { if (PRE->isImplicitProperty()) return; const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); if (!PD) return; - + unsigned Attributes = PD->getPropertyAttributes(); if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { // when 'assign' attribute was not explicitly specified @@ -12848,7 +12848,7 @@ void Sema::checkUnsafeExprAssigns(SourceLocation Loc, if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && LHSType->isObjCRetainableType()) return; - + while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { if (cast->getCastKind() == CK_ARCConsumeObject) { Diag(Loc, diag::warn_arc_retained_property_assign) diff --git a/lib/Sema/SemaCodeComplete.cpp b/lib/Sema/SemaCodeComplete.cpp index 4e571eba17e96..30af826ef6cc0 100644 --- a/lib/Sema/SemaCodeComplete.cpp +++ b/lib/Sema/SemaCodeComplete.cpp @@ -1303,34 +1303,8 @@ namespace { void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override { bool Accessible = true; - if (Ctx) { - DeclContext *AccessingCtx = Ctx; - // If ND comes from a base class, set the naming class back to the - // derived class if the search starts from the derived class (i.e. - // InBaseClass is true). - // - // Example: - // class B { protected: int X; } - // class D : public B { void f(); } - // void D::f() { this->^; } - // The completion after "this->" will have `InBaseClass` set to true and - // `Ctx` set to "B", when looking up in `B`. We need to set the actual - // accessing context (i.e. naming class) to "D" so that access can be - // calculated correctly. - if (InBaseClass && isa<CXXRecordDecl>(Ctx)) { - CXXRecordDecl *RC = nullptr; - // Get the enclosing record. - for (DeclContext *DC = CurContext; !DC->isFileContext(); - DC = DC->getParent()) { - if ((RC = dyn_cast<CXXRecordDecl>(DC))) - break; - } - if (RC) - AccessingCtx = RC; - } - Accessible = Results.getSema().IsSimplyAccessible(ND, AccessingCtx); - } - + if (Ctx) + Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx); ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, false, Accessible, FixIts); Results.AddResult(Result, CurContext, Hiding, InBaseClass); diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp index 55542828f7839..b92d76ad42049 100644 --- a/lib/Sema/SemaDecl.cpp +++ b/lib/Sema/SemaDecl.cpp @@ -3182,7 +3182,7 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, if (OldTypeInfo.getNoCallerSavedRegs() != NewTypeInfo.getNoCallerSavedRegs()) { if (NewTypeInfo.getNoCallerSavedRegs()) { - AnyX86NoCallerSavedRegistersAttr *Attr = + AnyX86NoCallerSavedRegistersAttr *Attr = New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; Diag(OldLocation, diag::note_previous_declaration); @@ -6008,6 +6008,31 @@ static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { << Attr; ND.dropAttr<NotTailCalledAttr>(); } + + // Check the attributes on the function type, if any. + if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { + // Don't declare this variable in the second operand of the for-statement; + // GCC miscompiles that by ending its lifetime before evaluating the + // third operand. See gcc.gnu.org/PR86769. + AttributedTypeLoc ATL; + for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); + (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); + TL = ATL.getModifiedLoc()) { + // The [[lifetimebound]] attribute can be applied to the implicit object + // parameter of a non-static member function (other than a ctor or dtor) + // by applying it to the function type. + if (ATL.getAttrKind() == AttributedType::attr_lifetimebound) { + const auto *MD = dyn_cast<CXXMethodDecl>(FD); + if (!MD || MD->isStatic()) { + S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_no_object_param) + << !MD << ATL.getLocalSourceRange(); + } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { + S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_ctor_dtor) + << isa<CXXDestructorDecl>(MD) << ATL.getLocalSourceRange(); + } + } + } + } } static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, @@ -8049,6 +8074,29 @@ enum OpenCLParamType { RecordKernelParam }; +static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { + // Size dependent types are just typedefs to normal integer types + // (e.g. unsigned long), so we cannot distinguish them from other typedefs to + // integers other than by their names. + StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; + + // Remove typedefs one by one until we reach a typedef + // for a size dependent type. + QualType DesugaredTy = Ty; + do { + ArrayRef<StringRef> Names(SizeTypeNames); + auto Match = + std::find(Names.begin(), Names.end(), DesugaredTy.getAsString()); + if (Names.end() != Match) + return true; + + Ty = DesugaredTy; + DesugaredTy = Ty.getSingleStepDesugaredType(C); + } while (DesugaredTy != Ty); + + return false; +} + static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { if (PT->isPointerType()) { QualType PointeeType = PT->getPointeeType(); @@ -8061,8 +8109,13 @@ static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { return PtrKernelParam; } - // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can - // be used as builtin types. + // OpenCL v1.2 s6.9.k: + // Arguments to kernel functions in a program cannot be declared with the + // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and + // uintptr_t or a struct and/or union that contain fields declared to be one + // of these built-in scalar types. + if (isOpenCLSizeDependentType(S.getASTContext(), PT)) + return InvalidKernelParam; if (PT->isImageType()) return PtrKernelParam; @@ -8079,6 +8132,15 @@ static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { if (PT->isRecordType()) return RecordKernelParam; + // Look into an array argument to check if it has a forbidden type. + if (PT->isArrayType()) { + const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); + // Call ourself to check an underlying type of an array. Since the + // getPointeeOrArrayElementType returns an innermost type which is not an + // array, this recusive call only happens once. + return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); + } + return ValidKernelParam; } @@ -8124,8 +8186,20 @@ static void checkIsValidOpenCLKernelParameter( // of event_t type. // Do not diagnose half type since it is diagnosed as invalid argument // type for any function elsewhere. - if (!PT->isHalfType()) + if (!PT->isHalfType()) { S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; + + // Explain what typedefs are involved. + const TypedefType *Typedef = nullptr; + while ((Typedef = PT->getAs<TypedefType>())) { + SourceLocation Loc = Typedef->getDecl()->getLocation(); + // SourceLocation may be invalid for a built-in type. + if (Loc.isValid()) + S.Diag(Loc, diag::note_entity_declared_at) << PT; + PT = Typedef->desugar(); + } + } + D.setInvalidType(); return; @@ -8146,9 +8220,14 @@ static void checkIsValidOpenCLKernelParameter( SmallVector<const FieldDecl *, 4> HistoryStack; HistoryStack.push_back(nullptr); - const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); - VisitStack.push_back(PD); + // At this point we already handled everything except of a RecordType or + // an ArrayType of a RecordType. + assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); + const RecordType *RecTy = + PT->getPointeeOrArrayElementType()->getAs<RecordType>(); + const RecordDecl *OrigRecDecl = RecTy->getDecl(); + VisitStack.push_back(RecTy->getDecl()); assert(VisitStack.back() && "First decl null?"); do { @@ -8167,7 +8246,15 @@ static void checkIsValidOpenCLKernelParameter( const RecordDecl *RD; if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { HistoryStack.push_back(Field); - RD = Field->getType()->castAs<RecordType>()->getDecl(); + + QualType FieldTy = Field->getType(); + // Other field types (known to be valid or invalid) are handled while we + // walk around RecordDecl::fields(). + assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && + "Unexpected type."); + const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); + + RD = FieldRecTy->castAs<RecordType>()->getDecl(); } else { RD = cast<RecordDecl>(Next); } @@ -8204,8 +8291,8 @@ static void checkIsValidOpenCLKernelParameter( S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; } - S.Diag(PD->getLocation(), diag::note_within_field_of_type) - << PD->getDeclName(); + S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) + << OrigRecDecl->getDeclName(); // We have an error, now let's go back up through history and show where // the offending field came from @@ -10720,7 +10807,7 @@ QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); InitializationKind Kind = InitializationKind::CreateForInit( VDecl->getLocation(), DirectInit, Init); - // FIXME: Initialization should not be taking a mutable list of inits. + // FIXME: Initialization should not be taking a mutable list of inits. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, InitsCopy); @@ -11914,14 +12001,25 @@ void Sema::FinalizeDeclaration(Decl *ThisDecl) { NewAttr->setInherited(true); VD->addAttr(NewAttr); } - // CUDA E.2.9.4: Within the body of a __device__ or __global__ - // function, only __shared__ variables may be declared with - // static storage class. - if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && - CUDADiagIfDeviceCode(VD->getLocation(), - diag::err_device_static_local_var) - << CurrentCUDATarget()) - VD->setInvalidDecl(); + // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ + // function, only __shared__ variables or variables without any device + // memory qualifiers may be declared with static storage class. + // Note: It is unclear how a function-scope non-const static variable + // without device memory qualifier is implemented, therefore only static + // const variable without device memory qualifier is allowed. + [&]() { + if (!getLangOpts().CUDA) + return; + if (VD->hasAttr<CUDASharedAttr>()) + return; + if (VD->getType().isConstQualified() && + !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) + return; + if (CUDADiagIfDeviceCode(VD->getLocation(), + diag::err_device_static_local_var) + << CurrentCUDATarget()) + VD->setInvalidDecl(); + }(); } } @@ -13398,7 +13496,7 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { break; } } - + if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && !FD->hasAttr<ReturnsTwiceAttr>()) FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, diff --git a/lib/Sema/SemaDeclAttr.cpp b/lib/Sema/SemaDeclAttr.cpp index 320eabd5ec2f5..77deed6047f47 100644 --- a/lib/Sema/SemaDeclAttr.cpp +++ b/lib/Sema/SemaDeclAttr.cpp @@ -1051,7 +1051,7 @@ static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) { << AL.getName() << AANT_ArgumentIdentifier; return; } - + D->addAttr(::new (S.Context) ConsumableAttr(AL.getRange(), S.Context, DefaultState, AL.getAttributeSpellingListIndex())); @@ -1061,30 +1061,30 @@ static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, const ParsedAttr &AL) { ASTContext &CurrContext = S.getASTContext(); QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); - + if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { if (!RD->hasAttr<ConsumableAttr>()) { S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD->getNameAsString(); - + return false; } } - + return true; } static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; - + if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) return; - + SmallVector<CallableWhenAttr::ConsumedState, 3> States; for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) { CallableWhenAttr::ConsumedState CallableState; - + StringRef StateString; SourceLocation Loc; if (AL.isArgIdent(ArgIndex)) { @@ -1102,10 +1102,10 @@ static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { << AL.getName() << StateString; return; } - + States.push_back(CallableState); } - + D->addAttr(::new (S.Context) CallableWhenAttr(AL.getRange(), S.Context, States.data(), States.size(), AL.getAttributeSpellingListIndex())); @@ -1113,7 +1113,7 @@ static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ParamTypestateAttr::ConsumedState ParamState; - + if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef StateString = Ident->Ident->getName(); @@ -1129,7 +1129,7 @@ static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. @@ -1141,7 +1141,7 @@ static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // ReturnType.getAsString(); // return; //} - + D->addAttr(::new (S.Context) ParamTypestateAttr(AL.getRange(), S.Context, ParamState, AL.getAttributeSpellingListIndex())); @@ -1149,7 +1149,7 @@ static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ReturnTypestateAttr::ConsumedState ReturnState; - + if (AL.isArgIdent(0)) { IdentifierLoc *IL = AL.getArgAsIdent(0); if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), @@ -1163,7 +1163,7 @@ static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. @@ -1175,9 +1175,9 @@ static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { //} else if (const CXXConstructorDecl *Constructor = // dyn_cast<CXXConstructorDecl>(D)) { // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); - // + // //} else { - // + // // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); //} // @@ -1197,7 +1197,7 @@ static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) return; - + SetTypestateAttr::ConsumedState NewState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); @@ -1212,7 +1212,7 @@ static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + D->addAttr(::new (S.Context) SetTypestateAttr(AL.getRange(), S.Context, NewState, AL.getAttributeSpellingListIndex())); @@ -1221,8 +1221,8 @@ static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) return; - - TestTypestateAttr::ConsumedState TestState; + + TestTypestateAttr::ConsumedState TestState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); @@ -1236,7 +1236,7 @@ static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + D->addAttr(::new (S.Context) TestTypestateAttr(AL.getRange(), S.Context, TestState, AL.getAttributeSpellingListIndex())); @@ -1980,7 +1980,7 @@ static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { return; } } - + D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); @@ -2343,7 +2343,7 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { return; IdentifierLoc *Platform = AL.getArgAsIdent(0); unsigned Index = AL.getAttributeSpellingListIndex(); - + IdentifierInfo *II = Platform->Ident; if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) @@ -2533,7 +2533,7 @@ static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL, << AL.getName() << TypeStr; return; } - + // Complain about attempts to use protected visibility on targets // (like Darwin) that don't support it. if (type == VisibilityAttr::Protected && @@ -2604,7 +2604,7 @@ static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) { // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); // // In this case it follows tradition and suppresses an error in the above - // case. + // case. S.Diag(D->getLocation(), diag::warn_nsobject_attribute); } D->addAttr(::new (S.Context) @@ -2752,14 +2752,14 @@ static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { << AL.getName() << 1; return; } - + // If this is spelled as the standard C++17 attribute, but not in C++17, warn // about using it as an extension. if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() && !AL.getScopeName()) S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL.getName(); - D->addAttr(::new (S.Context) + D->addAttr(::new (S.Context) WarnUnusedResultAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } @@ -2892,7 +2892,7 @@ bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); if (!Error.empty()) { Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error - << 1 /*'section'*/; + << 1 /*'section'*/; return false; } return true; @@ -3191,7 +3191,7 @@ static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); return; } - + if (S.getCurFunctionOrMethodDecl()) { S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); AL.setInvalid(); @@ -3269,10 +3269,10 @@ static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Check for supported formats. FormatAttrKind Kind = getFormatAttrKind(Format); - + if (Kind == IgnoredFormat) return; - + if (Kind == InvalidFormat) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL.getName() << II->getName(); @@ -3454,7 +3454,7 @@ static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (I->getAnnotation() == Str) return; } - + D->addAttr(::new (S.Context) AnnotateAttr(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); @@ -4595,7 +4595,7 @@ static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, << AL.getName() << 1 << AANT_ArgumentIdentifier; return; } - + if (!checkAttributeNumArgs(S, AL, 1)) return; @@ -4819,7 +4819,7 @@ static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { const int EP_ObjCMethod = 1; const int EP_ObjCProperty = 2; - + SourceLocation loc = Attrs.getLoc(); QualType resultType; if (isa<ObjCMethodDecl>(D)) @@ -4887,7 +4887,7 @@ static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { return; } } - + D->addAttr(::new (S.Context) ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident, AL.getAttributeSpellingListIndex())); @@ -4901,7 +4901,7 @@ static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0; return; } - + D->addAttr(::new (S.Context) ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident, AL.getAttributeSpellingListIndex())); @@ -5195,7 +5195,7 @@ static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgExpr(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL.getName() << AANT_ArgumentIntegerConstant; - return; + return; } // FIXME: Check for decl - it should be void ()(void). @@ -6150,6 +6150,9 @@ static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, case ParsedAttr::AT_Restrict: handleRestrictAttr(S, D, AL); break; + case ParsedAttr::AT_LifetimeBound: + handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL); + break; case ParsedAttr::AT_MayAlias: handleSimpleAttribute<MayAliasAttr>(S, D, AL); break; diff --git a/lib/Sema/SemaDeclObjC.cpp b/lib/Sema/SemaDeclObjC.cpp index e1b033ea82820..595cc76cd4a31 100644 --- a/lib/Sema/SemaDeclObjC.cpp +++ b/lib/Sema/SemaDeclObjC.cpp @@ -109,9 +109,33 @@ bool Sema::checkInitMethod(ObjCMethodDecl *method, return true; } -void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, +/// Issue a warning if the parameter of the overridden method is non-escaping +/// but the parameter of the overriding method is not. +static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, + Sema &S) { + if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) { + S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape); + S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape); + return false; + } + + return true; +} + +/// Produce additional diagnostics if a category conforms to a protocol that +/// defines a method taking a non-escaping parameter. +static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, + const ObjCCategoryDecl *CD, + const ObjCProtocolDecl *PD, Sema &S) { + if (!diagnoseNoescape(NewD, OldD, S)) + S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot) + << CD->IsClassExtension() << PD + << cast<ObjCMethodDecl>(NewD->getDeclContext()); +} + +void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden) { - if (Overridden->hasRelatedResultType() && + if (Overridden->hasRelatedResultType() && !NewMethod->hasRelatedResultType()) { // This can only happen when the method follows a naming convention that // implies a related result type, and the original (overridden) method has @@ -119,9 +143,9 @@ void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, // a suitable return type. QualType ResultType = NewMethod->getReturnType(); SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange(); - + // Figure out which class this method is part of, if any. - ObjCInterfaceDecl *CurrentClass + ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); if (!CurrentClass) { DeclContext *DC = NewMethod->getDeclContext(); @@ -133,27 +157,27 @@ void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, = dyn_cast<ObjCCategoryImplDecl>(DC)) CurrentClass = CatImpl->getClassInterface(); } - + if (CurrentClass) { - Diag(NewMethod->getLocation(), + Diag(NewMethod->getLocation(), diag::warn_related_result_type_compatibility_class) << Context.getObjCInterfaceType(CurrentClass) << ResultType << ResultTypeRange; } else { - Diag(NewMethod->getLocation(), + Diag(NewMethod->getLocation(), diag::warn_related_result_type_compatibility_protocol) << ResultType << ResultTypeRange; } - + if (ObjCMethodFamily Family = Overridden->getMethodFamily()) - Diag(Overridden->getLocation(), + Diag(Overridden->getLocation(), diag::note_related_result_type_family) << /*overridden method*/ 0 << Family; else - Diag(Overridden->getLocation(), + Diag(Overridden->getLocation(), diag::note_related_result_type_overridden); } @@ -192,13 +216,7 @@ void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter"; } - // A parameter of the overriding method should be annotated with noescape - // if the corresponding parameter of the overridden method is annotated. - if (oldDecl->hasAttr<NoEscapeAttr>() && !newDecl->hasAttr<NoEscapeAttr>()) { - Diag(newDecl->getLocation(), - diag::warn_overriding_method_missing_noescape); - Diag(oldDecl->getLocation(), diag::note_overridden_marked_noescape); - } + diagnoseNoescape(newDecl, oldDecl, *this); } } @@ -232,7 +250,7 @@ bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { return true; } return false; - + case OMF_init: // If the method doesn't obey the init rules, don't bother annotating it. if (checkInitMethod(method, QualType())) @@ -310,7 +328,7 @@ static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND, /// pool. void Sema::AddAnyMethodToGlobalPool(Decl *D) { ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); - + // If we don't have a valid method decl, simply return. if (!MDecl) return; @@ -325,7 +343,7 @@ void Sema::AddAnyMethodToGlobalPool(Decl *D) { static bool HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { QualType T = Param->getType(); - + if (const PointerType *PT = T->getAs<PointerType>()) { T = PT->getPointeeType(); } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { @@ -333,8 +351,8 @@ HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { } else { return true; } - - // If we have a lifetime qualifier, but it's local, we must have + + // If we have a lifetime qualifier, but it's local, we must have // inferred it. So, it is implicit. return !T.getLocalQualifiers().hasObjCLifetime(); } @@ -344,7 +362,7 @@ HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); - + // If we don't have a valid method decl, simply return. if (!MDecl) return; @@ -359,7 +377,7 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { // Allow all of Sema to see that we are entering a method definition. PushDeclContext(FnBodyScope, MDecl); PushFunctionScope(); - + // Create Decl objects for each parameter, entrring them in the scope for // binding to their use. @@ -380,7 +398,7 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { !HasExplicitOwnershipAttr(*this, Param)) Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << Param->getType(); - + if (Param->getIdentifier()) PushOnScopeChains(Param, FnBodyScope); } @@ -414,13 +432,13 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { // Warn on deprecated methods under -Wdeprecated-implementations, // and prepare for warning on missing super calls. if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { - ObjCMethodDecl *IMD = + ObjCMethodDecl *IMD = IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); - + if (IMD) { - ObjCImplDecl *ImplDeclOfMethodDef = + ObjCImplDecl *ImplDeclOfMethodDef = dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); - ObjCContainerDecl *ContDeclOfMethodDecl = + ObjCContainerDecl *ContDeclOfMethodDecl = dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) @@ -463,12 +481,12 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { } else if (Family == OMF_finalize) { if (Context.getLangOpts().getGC() != LangOptions::NonGC) getCurFunction()->ObjCShouldCallSuper = true; - + } else { const ObjCMethodDecl *SuperMethod = SuperClass->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); - getCurFunction()->ObjCShouldCallSuper = + getCurFunction()->ObjCShouldCallSuper = (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); } } @@ -609,11 +627,11 @@ ActOnSuperClassOfClassInterface(Scope *S, // Handle type arguments on the superclass. TypeSourceInfo *SuperClassTInfo = nullptr; - if (!SuperTypeArgs.empty()) { + if (!SuperTypeArgs.empty()) { TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers( S, SuperLoc, - CreateParsedType(SuperClassType, + CreateParsedType(SuperClassType, nullptr), SuperTypeArgsRange.getBegin(), SuperTypeArgs, @@ -625,12 +643,12 @@ ActOnSuperClassOfClassInterface(Scope *S, if (!fullSuperClassType.isUsable()) return; - SuperClassType = GetTypeFromParser(fullSuperClassType.get(), + SuperClassType = GetTypeFromParser(fullSuperClassType.get(), &SuperClassTInfo); } if (!SuperClassTInfo) { - SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, + SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, SuperLoc); } @@ -834,7 +852,7 @@ static bool checkTypeParamListConsistency(Sema &S, // When the new type parameter is invariant and is not part // of the definition, just propagate the variance. newTypeParam->setVariance(prevTypeParam->getVariance()); - } else if (prevTypeParam->getVariance() + } else if (prevTypeParam->getVariance() == ObjCTypeParamVariance::Invariant && !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) && cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) @@ -993,7 +1011,7 @@ Decl *Sema::ActOnStartClassInterface( if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) { if (typeParamList) { // Both have type parameter lists; check for consistency. - if (checkTypeParamListConsistency(*this, prevTypeParamList, + if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList, TypeParamListContext::Definition)) { typeParamList = nullptr; @@ -1020,7 +1038,7 @@ Decl *Sema::ActOnStartClassInterface( Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType()))); } - typeParamList = ObjCTypeParamList::create(Context, + typeParamList = ObjCTypeParamList::create(Context, SourceLocation(), clonedTypeParams, SourceLocation()); @@ -1045,18 +1063,18 @@ Decl *Sema::ActOnStartClassInterface( AddPragmaAttributes(TUScope, IDecl); PushOnScopeChains(IDecl, TUScope); - // Start the definition of this class. If we're in a redefinition case, there + // Start the definition of this class. If we're in a redefinition case, there // may already be a definition, so we'll end up adding to it. if (!IDecl->hasDefinition()) IDecl->startDefinition(); - + if (SuperName) { // Diagnose availability in the context of the @interface. ContextRAII SavedContext(*this, IDecl); - ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, - ClassName, ClassLoc, - SuperName, SuperLoc, SuperTypeArgs, + ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, + ClassName, ClassLoc, + SuperName, SuperLoc, SuperTypeArgs, SuperTypeArgsRange); } else { // we have a root class. IDecl->setEndOfDefinitionLoc(ClassLoc); @@ -1088,7 +1106,7 @@ void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, LookupOrdinaryName); if (!IDecl) return; - + if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { QualType T = TDecl->getUnderlyingType(); if (T->isObjCObjectType()) @@ -1157,7 +1175,7 @@ bool Sema::CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &Ploc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList) { - + bool res = false; for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), E = PList.end(); I != E; ++I) { @@ -1168,10 +1186,10 @@ bool Sema::CheckForwardProtocolDeclarationForCircularDependency( Diag(PrevLoc, diag::note_previous_definition); res = true; } - + if (!PDecl->hasDefinition()) continue; - + if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, PDecl->getLocation(), PDecl->getReferencedProtocols())) res = true; @@ -1223,7 +1241,7 @@ Decl *Sema::ActOnStartProtocolInterface( PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, ProtocolLoc, AtProtoInterfaceLoc, /*PrevDecl=*/PrevDecl); - + PushOnScopeChains(PDecl, TUScope); PDecl->startDefinition(); } @@ -1253,7 +1271,7 @@ static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, UndefinedProtocol = PDecl; return true; } - + for (auto *PI : PDecl->protocols()) if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { UndefinedProtocol = PI; @@ -1300,7 +1318,7 @@ Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, // case, do it. // FIXME: Recover nicely in the hidden case. ObjCProtocolDecl *UndefinedProtocol; - + if (WarnOnDeclarations && NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first; @@ -1393,7 +1411,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( unsigned numProtocolsResolved = 0; auto resolvedAsProtocols = [&] { assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols"); - + // Determine whether the base type is a parameterized class, in // which case we want to warn about typos such as // "NSArray<NSObject>" (that should be NSArray<NSObject *>). @@ -1416,7 +1434,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( } for (unsigned i = 0, n = protocols.size(); i != n; ++i) { - ObjCProtocolDecl *&proto + ObjCProtocolDecl *&proto = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]); // For an objc container, delay protocol reference checking until after we // can set the objc decl as the availability context, otherwise check now. @@ -1458,7 +1476,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( } } } - + // All of the protocols listed also have type names, and at least // one is an Objective-C class name. Check whether all of the // protocol conformances are declared by the base class itself, in @@ -1533,7 +1551,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( // Local function that forms a reference to the given type or // Objective-C class declaration. - auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) + auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) -> TypeResult { // Form declaration specifiers. They simply refer to the type. DeclSpec DS(attrFactory); @@ -1749,10 +1767,10 @@ Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second, forRedeclarationInCurContext()); ObjCProtocolDecl *PDecl - = ObjCProtocolDecl::Create(Context, CurContext, Ident, + = ObjCProtocolDecl::Create(Context, CurContext, Ident, IdentPair.second, AtProtocolLoc, PrevDecl); - + PushOnScopeChains(PDecl, TUScope); CheckObjCDeclScope(PDecl); @@ -1780,7 +1798,7 @@ Decl *Sema::ActOnStartCategoryInterface( /// Check that class of this category is already completely declared. - if (!IDecl + if (!IDecl || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), diag::err_category_forward_interface, CategoryName == nullptr)) { @@ -1792,7 +1810,7 @@ Decl *Sema::ActOnStartCategoryInterface( IDecl, typeParamList); CDecl->setInvalidDecl(); CurContext->addDecl(CDecl); - + if (!IDecl) Diag(ClassLoc, diag::err_undef_interface) << ClassName; return ActOnObjCContainerStartDefinition(CDecl); @@ -1800,7 +1818,7 @@ Decl *Sema::ActOnStartCategoryInterface( if (!CategoryName && IDecl->getImplementation()) { Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; - Diag(IDecl->getImplementation()->getLocation(), + Diag(IDecl->getImplementation()->getLocation(), diag::note_implementation_declared); } @@ -1853,8 +1871,8 @@ Decl *Sema::ActOnStartCategoryInterface( ProtoLocs, Context); // Protocols in the class extension belong to the class. if (CDecl->IsClassExtension()) - IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, - NumProtoRefs, Context); + IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, + NumProtoRefs, Context); } CheckObjCDeclScope(CDecl); @@ -1915,7 +1933,7 @@ Decl *Sema::ActOnStartCategoryImplementation( CDecl->setInvalidDecl(); } else { CatIDecl->setImplementation(CDecl); - // Warn on implementating category of deprecated class under + // Warn on implementating category of deprecated class under // -Wdeprecated-implementations flag. DiagnoseObjCImplementedDeprecations(*this, CatIDecl, CDecl->getLocation()); @@ -2009,7 +2027,7 @@ Decl *Sema::ActOnStartClassImplementation( } else { IDecl->setEndOfDefinitionLoc(ClassLoc); } - + PushOnScopeChains(IDecl, TUScope); } else { // Mark the interface as being completed, even if it was just as @@ -2036,7 +2054,7 @@ Decl *Sema::ActOnStartClassImplementation( } else { // add it to the list. IDecl->setImplementation(IMPDecl); PushOnScopeChains(IMPDecl, TUScope); - // Warn on implementating deprecated class under + // Warn on implementating deprecated class under // -Wdeprecated-implementations flag. DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation()); } @@ -2090,7 +2108,7 @@ void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, IDecl->makeDeclVisibleInContext(ivars[i]); ImpDecl->addDecl(ivars[i]); } - + return; } // If implementation has empty ivar list, just return. @@ -2103,17 +2121,17 @@ void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); for (unsigned i = 0; i < numIvars; i++) { ObjCIvarDecl* ImplIvar = ivars[i]; - if (const ObjCIvarDecl *ClsIvar = + if (const ObjCIvarDecl *ClsIvar = IDecl->getIvarDecl(ImplIvar->getIdentifier())) { - Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); + Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); Diag(ClsIvar->getLocation(), diag::note_previous_definition); continue; } // Check class extensions (unnamed categories) for duplicate ivars. for (const auto *CDecl : IDecl->visible_extensions()) { - if (const ObjCIvarDecl *ClsExtIvar = + if (const ObjCIvarDecl *ClsExtIvar = CDecl->getIvarDecl(ImplIvar->getIdentifier())) { - Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); + Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); continue; } @@ -2194,8 +2212,8 @@ static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, } /// Determines if type B can be substituted for type A. Returns true if we can -/// guarantee that anything that the user will do to an object of type A can -/// also be done to an object of type B. This is trivially true if the two +/// guarantee that anything that the user will do to an object of type A can +/// also be done to an object of type B. This is trivially true if the two /// types are the same, or if B is a subclass of A. It becomes more complex /// in cases where protocols are involved. /// @@ -2204,12 +2222,12 @@ static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, /// example, if A is a subclass of B, then B* may refer to an instance of A. /// The principle of substitutability means that we may use an instance of A /// anywhere that we may use an instance of B - it will implement all of the -/// ivars of B and all of the methods of B. +/// ivars of B and all of the methods of B. /// -/// This substitutability is important when type checking methods, because +/// This substitutability is important when type checking methods, because /// the implementation may have stricter type definitions than the interface. /// The interface specifies minimum requirements, but the implementation may -/// have more accurate ones. For example, a method may privately accept +/// have more accurate ones. For example, a method may privately accept /// instances of B, but only publish that it accepts instances of A. Any /// object passed to it will be type checked against B, and so will implicitly /// by a valid A*. Similarly, a method may return a subclass of the class that @@ -2225,7 +2243,7 @@ static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, /// advertises, but it may be specified more accurately. This avoids the need /// for explicit down-casting by callers. /// -/// Note: This is a stricter requirement than for assignment. +/// Note: This is a stricter requirement than for assignment. static bool isObjCTypeSubstitutable(ASTContext &Context, const ObjCObjectPointerType *A, const ObjCObjectPointerType *B, @@ -2314,15 +2332,15 @@ static bool CheckMethodOverrideReturn(Sema &S, != 0)); S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration); } - + if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), MethodDecl->getReturnType())) return true; if (!Warn) return false; - unsigned DiagID = - IsOverridingMode ? diag::warn_conflicting_overriding_ret_types + unsigned DiagID = + IsOverridingMode ? diag::warn_conflicting_overriding_ret_types : diag::warn_conflicting_ret_types; // Mismatches between ObjC pointers go into a different warning @@ -2338,8 +2356,8 @@ static bool CheckMethodOverrideReturn(Sema &S, if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) return false; - DiagID = - IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types + DiagID = + IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types : diag::warn_non_covariant_ret_types; } } @@ -2368,21 +2386,21 @@ static bool CheckMethodOverrideParam(Sema &S, IfaceVar->getObjCDeclQualifier())) { if (Warn) { if (IsOverridingMode) - S.Diag(ImplVar->getLocation(), + S.Diag(ImplVar->getLocation(), diag::warn_conflicting_overriding_param_modifiers) << getTypeRange(ImplVar->getTypeSourceInfo()) << MethodImpl->getDeclName(); - else S.Diag(ImplVar->getLocation(), + else S.Diag(ImplVar->getLocation(), diag::warn_conflicting_param_modifiers) << getTypeRange(ImplVar->getTypeSourceInfo()) << MethodImpl->getDeclName(); S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) - << getTypeRange(IfaceVar->getTypeSourceInfo()); + << getTypeRange(IfaceVar->getTypeSourceInfo()); } else return false; } - + QualType ImplTy = ImplVar->getType(); QualType IfaceTy = IfaceVar->getType(); if (Warn && IsOverridingMode && @@ -2405,8 +2423,8 @@ static bool CheckMethodOverrideParam(Sema &S, if (!Warn) return false; - unsigned DiagID = - IsOverridingMode ? diag::warn_conflicting_overriding_param_types + unsigned DiagID = + IsOverridingMode ? diag::warn_conflicting_overriding_param_types : diag::warn_conflicting_param_types; // Mismatches between ObjC pointers go into a different warning @@ -2422,8 +2440,8 @@ static bool CheckMethodOverrideParam(Sema &S, if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) return false; - DiagID = - IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types + DiagID = + IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types : diag::warn_non_contravariant_param_types; } } @@ -2431,8 +2449,8 @@ static bool CheckMethodOverrideParam(Sema &S, S.Diag(ImplVar->getLocation(), DiagID) << getTypeRange(ImplVar->getTypeSourceInfo()) << MethodImpl->getDeclName() << IfaceTy << ImplTy; - S.Diag(IfaceVar->getLocation(), - (IsOverridingMode ? diag::note_previous_declaration + S.Diag(IfaceVar->getLocation(), + (IsOverridingMode ? diag::note_previous_declaration : diag::note_previous_definition)) << getTypeRange(IfaceVar->getTypeSourceInfo()); return false; @@ -2517,8 +2535,8 @@ void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) return; - CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, - IsProtocolMethodDecl, false, + CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, + IsProtocolMethodDecl, false, true); for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), @@ -2530,7 +2548,7 @@ void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, } if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { - Diag(ImpMethodDecl->getLocation(), + Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic); Diag(MethodDecl->getLocation(), diag::note_previous_declaration); } @@ -2539,11 +2557,11 @@ void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl) { - - CheckMethodOverrideReturn(*this, Method, Overridden, - IsProtocolMethodDecl, true, + + CheckMethodOverrideReturn(*this, Method, Overridden, + IsProtocolMethodDecl, true, true); - + for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), IF = Overridden->param_begin(), EM = Method->param_end(), EF = Overridden->param_end(); @@ -2551,9 +2569,9 @@ void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, IsProtocolMethodDecl, true, true); } - + if (Method->isVariadic() != Overridden->isVariadic()) { - Diag(Method->getLocation(), + Diag(Method->getLocation(), diag::warn_conflicting_overriding_variadic); Diag(Overridden->getLocation(), diag::note_previous_declaration); } @@ -2569,20 +2587,20 @@ void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, // to implement it. if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) return; - // don't issue warning when primary class's method is + // don't issue warning when primary class's method is // depecated/unavailable. if (MethodDecl->hasAttr<UnavailableAttr>() || MethodDecl->hasAttr<DeprecatedAttr>()) return; - - bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, + + bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, IsProtocolMethodDecl, false, false); if (match) for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), EF = MethodDecl->param_end(); IM != EM && IF != EF; ++IM, ++IF) { - match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, + match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, IsProtocolMethodDecl, false, false); if (!match) @@ -2593,9 +2611,9 @@ void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, if (match) match = !(MethodDecl->isClassMethod() && MethodDecl->getSelector() == GetNullarySelector("load", Context)); - + if (match) { - Diag(ImpMethodDecl->getLocation(), + Diag(ImpMethodDecl->getLocation(), diag::warn_category_method_impl_match); Diag(MethodDecl->getLocation(), diag::note_method_declared_at) << MethodDecl->getDeclName(); @@ -2644,10 +2662,10 @@ static void CheckProtocolMethodDefs(Sema &S, ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) { ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); - ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() + ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() : dyn_cast<ObjCInterfaceDecl>(CDecl); assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); - + ObjCInterfaceDecl *Super = IDecl->getSuperClass(); ObjCInterfaceDecl *NSIDecl = nullptr; @@ -2696,7 +2714,7 @@ static void CheckProtocolMethodDefs(Sema &S, if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) PDecl = PDecl->getDefinition(); - + // If a method lookup fails locally we still need to look and see if // the method was implemented by a base class or an inherited // protocol. This lookup is slow, but occurs rarely in correct code @@ -2715,10 +2733,10 @@ static void CheckProtocolMethodDefs(Sema &S, nullptr /* category */))) { // If a method is not implemented in the category implementation but // has been declared in its primary class, superclass, - // or in one of their protocols, no need to issue the warning. - // This is because method will be implemented in the primary class + // or in one of their protocols, no need to issue the warning. + // This is because method will be implemented in the primary class // or one of its super class implementation. - + // Ugly, but necessary. Method declared in protocol might have // have been synthesized due to a property declared in the class which // uses the protocol. @@ -2828,7 +2846,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, } } } - + if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { // Also, check for methods declared in protocols inherited by // this protocol. @@ -2837,7 +2855,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, IMPDecl, PI, IncompleteImpl, false, WarnCategoryMethodImpl); } - + if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { // when checking that methods in implementation match their declaration, // i.e. when WarnCategoryMethodImpl is false, check declarations in class @@ -2862,8 +2880,8 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, IMPDecl, PI, IncompleteImpl, false, WarnCategoryMethodImpl); - // FIXME. For now, we are not checking for extact match of methods - // in category implementation and its primary class's super class. + // FIXME. For now, we are not checking for extact match of methods + // in category implementation and its primary class's super class. if (!WarnCategoryMethodImpl && I->getSuperClass()) MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, IMPDecl, @@ -2873,7 +2891,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and -/// warns each time an exact match is found. +/// warns each time an exact match is found. void Sema::CheckCategoryVsClassMethodMatches( ObjCCategoryImplDecl *CatIMPDecl) { // Get category's primary class. @@ -2885,7 +2903,7 @@ void Sema::CheckCategoryVsClassMethodMatches( return; ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); SelectorSet InsMap, ClsMap; - + for (const auto *I : CatIMPDecl->instance_methods()) { Selector Sel = I->getSelector(); // When checking for methods implemented in the category, skip over @@ -2895,7 +2913,7 @@ void Sema::CheckCategoryVsClassMethodMatches( continue; InsMap.insert(Sel); } - + for (const auto *I : CatIMPDecl->class_methods()) { Selector Sel = I->getSelector(); if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) @@ -2904,12 +2922,12 @@ void Sema::CheckCategoryVsClassMethodMatches( } if (InsMap.empty() && ClsMap.empty()) return; - + SelectorSet InsMapSeen, ClsMapSeen; bool IncompleteImpl = false; MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, CatIMPDecl, IDecl, - IncompleteImpl, false, + IncompleteImpl, false, true /*WarnCategoryMethodImpl*/); } @@ -2959,10 +2977,10 @@ void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, IMPDecl, CDecl, IncompleteImpl, true); - + // check all methods implemented in category against those declared // in its primary class. - if (ObjCCategoryImplDecl *CatDecl = + if (ObjCCategoryImplDecl *CatDecl = dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) CheckCategoryVsClassMethodMatches(CatDecl); @@ -2987,7 +3005,7 @@ void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ExplicitImplProtocols); DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, /*SynthesizeProperties=*/false); - } + } } else llvm_unreachable("invalid ObjCContainerDecl type."); } @@ -3002,7 +3020,7 @@ Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, for (unsigned i = 0; i != NumElts; ++i) { // Check for another declaration kind with the same name. NamedDecl *PrevDecl - = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], + = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], LookupOrdinaryName, forRedeclarationInCurContext()); if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { // GCC apparently allows the following idiom: @@ -3029,7 +3047,7 @@ Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, } } } - + // Create a declaration to describe this forward declaration. ObjCInterfaceDecl *PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); @@ -3120,7 +3138,7 @@ static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, // Consider all the kinds of non-dependent canonical types: // - functions and arrays aren't possible as return and parameter types - + // - vector types of equal size can be arbitrarily mixed if (isa<VectorType>(left)) return isa<VectorType>(right); if (isa<VectorType>(right)) return false; @@ -3368,14 +3386,14 @@ void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, if (ExternalSource) ReadMethodPool(Method->getSelector()); - + GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); if (Pos == MethodPool.end()) Pos = MethodPool.insert(std::make_pair(Method->getSelector(), GlobalMethods())).first; Method->setDefined(impl); - + ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; addMethodToGlobalList(&Entry, Method); } @@ -3503,7 +3521,7 @@ ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool instance) { if (ExternalSource) ReadMethodPool(Sel); - + GlobalMethodPool::iterator Pos = MethodPool.find(Sel); if (Pos == MethodPool.end()) return nullptr; @@ -3553,7 +3571,7 @@ void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> & break; } } - + if (issueDiagnostic) { if (issueError) Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; @@ -3561,7 +3579,7 @@ void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> & Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; else Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; - + Diag(Methods[0]->getLocStart(), issueError ? diag::note_possibility : diag::note_using) << Methods[0]->getSourceRange(); @@ -3584,7 +3602,7 @@ ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { (Method->getMethod()->isDefined() || Method->getMethod()->isPropertyAccessor())) return Method->getMethod(); - + for (const ObjCMethodList *Method = &Methods.second; Method; Method = Method->getNext()) if (Method->getMethod() && @@ -3601,7 +3619,7 @@ HelperSelectorsForTypoCorrection( const unsigned MaxEditDistance = 1; unsigned BestEditDistance = MaxEditDistance + 1; std::string MethodName = Method->getSelector().getAsString(); - + unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); if (MinPossibleEditDistance > 0 && Typo.size() / MinPossibleEditDistance < 1) @@ -3676,7 +3694,7 @@ Sema::SelectorsForTypoCorrection(Selector Sel, Methods.push_back(M->getMethod()); } } - + SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; for (unsigned i = 0, e = Methods.size(); i < e; i++) { HelperSelectorsForTypoCorrection(SelectedMethods, @@ -3686,11 +3704,11 @@ Sema::SelectorsForTypoCorrection(Selector Sel, } /// DiagnoseDuplicateIvars - -/// Check for duplicate ivars in the entire class at the start of +/// Check for duplicate ivars in the entire class at the start of /// \@implementation. This becomes necesssary because class extension can /// add ivars to a class in random order which will not be known until /// class's \@implementation is seen. -void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, +void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID) { for (auto *Ivar : ID->ivars()) { if (Ivar->isInvalidDecl()) @@ -3962,7 +3980,7 @@ Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, if (const ObjCPropertyImplDecl *PIDecl = IC->FindPropertyImplDecl(Property->getIdentifier(), Property->getQueryKind())) - if (PIDecl->getPropertyImplementation() + if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) continue; @@ -4089,12 +4107,12 @@ CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. /// -static Sema::ResultTypeCompatibilityKind +static Sema::ResultTypeCompatibilityKind CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, ObjCInterfaceDecl *CurrentClass) { QualType ResultType = Method->getReturnType(); - // If an Objective-C method inherits its related result type, then its + // If an Objective-C method inherits its related result type, then its // declared result type must be compatible with its own class type. The // declared result type is compatible if: if (const ObjCObjectPointerType *ResultObjectType @@ -4103,25 +4121,25 @@ CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, if (ResultObjectType->isObjCIdType() || ResultObjectType->isObjCQualifiedIdType()) return Sema::RTC_Compatible; - + if (CurrentClass) { - if (ObjCInterfaceDecl *ResultClass + if (ObjCInterfaceDecl *ResultClass = ResultObjectType->getInterfaceDecl()) { // - it is the same as the method's class type, or if (declaresSameEntity(CurrentClass, ResultClass)) return Sema::RTC_Compatible; - + // - it is a superclass of the method's class type if (ResultClass->isSuperClassOf(CurrentClass)) return Sema::RTC_Compatible; - } + } } else { // Any Objective-C pointer type might be acceptable for a protocol // method; we just don't know. return Sema::RTC_Unknown; } } - + return Sema::RTC_Incompatible; } @@ -4145,7 +4163,7 @@ public: if (it == S.MethodPool.end()) { if (!S.getExternalSource()) return; S.ReadMethodPool(selector); - + it = S.MethodPool.find(selector); if (it == S.MethodPool.end()) return; @@ -4193,7 +4211,7 @@ private: void searchFrom(ObjCProtocolDecl *protocol) { if (!protocol->hasDefinition()) return; - + // A method in a protocol declaration overrides declarations from // referenced ("parent") protocols. search(protocol->getReferencedProtocols()); @@ -4225,7 +4243,7 @@ private: // A method in a class declaration overrides declarations from if (!iface->hasDefinition()) return; - + // - categories, for (auto *Cat : iface->known_categories()) search(Cat); @@ -4342,11 +4360,11 @@ void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, continue; // Conflicting properties are detected elsewhere. // Check for overriding methods - if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || + if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) CheckConflictingOverridingMethod(ObjCMethod, overridden, isa<ObjCProtocolDecl>(overridden->getDeclContext())); - + if (CurrentClass && overridden->getDeclContext() != CurrentClass && isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && !overridden->isImplicit() /* not meant for properties */) { @@ -4556,17 +4574,17 @@ Decl *Sema::ActOnMethodDeclaration( ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); } - LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, + LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, LookupOrdinaryName, forRedeclarationInCurContext()); LookupName(R, S); if (R.isSingleResult()) { NamedDecl *PrevDecl = R.getFoundDecl(); if (S->isDeclScope(PrevDecl)) { - Diag(ArgInfo[i].NameLoc, - (MethodDefinition ? diag::warn_method_param_redefinition - : diag::warn_method_param_declaration)) + Diag(ArgInfo[i].NameLoc, + (MethodDefinition ? diag::warn_method_param_redefinition + : diag::warn_method_param_declaration)) << ArgInfo[i].Name; - Diag(PrevDecl->getLocation(), + Diag(PrevDecl->getLocation(), diag::note_previous_declaration); } } @@ -4597,7 +4615,7 @@ Decl *Sema::ActOnMethodDeclaration( Params.push_back(Param); } - + for (unsigned i = 0, e = CNumArgs; i != e; ++i) { ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); QualType ArgType = Param->getType(); @@ -4610,7 +4628,7 @@ Decl *Sema::ActOnMethodDeclaration( Param->setDeclContext(ObjCMethod); Params.push_back(Param); } - + ObjCMethod->setMethodParams(Context, Params, SelectorLocs); ObjCMethod->setObjCDeclQualifier( CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); @@ -4643,6 +4661,22 @@ Decl *Sema::ActOnMethodDeclaration( << ObjCMethod->getDeclName(); } } + + // Warn if a method declared in a protocol to which a category or + // extension conforms is non-escaping and the implementation's method is + // escaping. + for (auto *C : IDecl->visible_categories()) + for (auto &P : C->protocols()) + if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(), + ObjCMethod->isInstanceMethod())) { + assert(ObjCMethod->parameters().size() == + IMD->parameters().size() && + "Methods have different number of parameters"); + auto OI = IMD->param_begin(), OE = IMD->param_end(); + auto NI = ObjCMethod->param_begin(); + for (; OI != OE; ++OI, ++NI) + diagnoseNoescape(*NI, *OI, C, P, *this); + } } } else { cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); @@ -4696,12 +4730,12 @@ Decl *Sema::ActOnMethodDeclaration( case OMF_initialize: case OMF_performSelector: break; - + case OMF_alloc: case OMF_new: InferRelatedResultType = ObjCMethod->isClassMethod(); break; - + case OMF_init: case OMF_autorelease: case OMF_retain: @@ -4709,7 +4743,7 @@ Decl *Sema::ActOnMethodDeclaration( InferRelatedResultType = ObjCMethod->isInstanceMethod(); break; } - + if (InferRelatedResultType && !ObjCMethod->getReturnType()->isObjCIndependentClassType()) ObjCMethod->SetRelatedResultType(); @@ -4745,7 +4779,7 @@ bool Sema::CheckObjCDeclScope(Decl *D) { // an objc container, it means the parser missed emitting an error. if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) return false; - + Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); D->setInvalidDecl(); @@ -4800,7 +4834,7 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid) { - // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage + // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage // duration shall not be qualified by an address-space qualifier." // Since all parameters have automatic store duration, they can not have // an address space. @@ -4808,7 +4842,7 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, Diag(IdLoc, diag::err_arg_with_address_space); Invalid = true; } - + // An @catch parameter must be an unqualified object pointer type; // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? if (Invalid) { @@ -4827,11 +4861,11 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, Invalid = true; Diag(IdLoc, diag::err_catch_param_not_objc_type); } - + VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, T, TInfo, SC_None); New->setExceptionVariable(true); - + // In ARC, infer 'retaining' for variables of retainable type. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) Invalid = true; @@ -4843,7 +4877,7 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { const DeclSpec &DS = D.getDeclSpec(); - + // We allow the "register" storage class on exception variables because // GCC did, but we drop it completely. Any other storage class is an error. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { @@ -4863,12 +4897,12 @@ Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { D.getMutableDeclSpec().ClearStorageClassSpecs(); DiagnoseFunctionSpecifiers(D.getDeclSpec()); - + // Check that there are no default arguments inside the type of this // exception object (C++ only). if (getLangOpts().CPlusPlus) CheckExtraCXXDefaultArguments(D); - + TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); QualType ExceptionType = TInfo->getType(); @@ -4877,21 +4911,21 @@ Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { D.getIdentifierLoc(), D.getIdentifier(), D.isInvalidType()); - + // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). if (D.getCXXScopeSpec().isSet()) { Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) << D.getCXXScopeSpec().getRange(); New->setInvalidDecl(); } - + // Add the parameter declaration into this scope. S->AddDecl(New); if (D.getIdentifier()) IdResolver.AddDecl(New); - + ProcessDeclAttributes(S, New, D); - + if (New->hasAttr<BlocksAttr>()) Diag(New->getLocation(), diag::err_block_on_nonlocal); return New; @@ -4901,7 +4935,7 @@ Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { /// initialization. void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars) { - for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; + for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; Iv= Iv->getNextIvar()) { QualType QT = Context.getBaseElementType(Iv->getType()); if (QT->isRecordType()) @@ -4917,11 +4951,11 @@ void Sema::DiagnoseUseOfUnimplementedSelectors() { for (unsigned I = 0, N = Sels.size(); I != N; ++I) ReferencedSelectors[Sels[I].first] = Sels[I].second; } - + // Warning will be issued only when selector table is // generated (which means there is at lease one implementation // in the TU). This is to match gcc's behavior. - if (ReferencedSelectors.empty() || + if (ReferencedSelectors.empty() || !Context.AnyObjCImplementation()) return; for (auto &SelectorAndLocation : ReferencedSelectors) { diff --git a/lib/Sema/SemaExceptionSpec.cpp b/lib/Sema/SemaExceptionSpec.cpp index df5bc9b82b96a..134c76ef28c62 100644 --- a/lib/Sema/SemaExceptionSpec.cpp +++ b/lib/Sema/SemaExceptionSpec.cpp @@ -385,7 +385,7 @@ bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) { OnFirstException = false; else OS << ", "; - + OS << E.getAsString(getPrintingPolicy()); } OS << ")"; diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp index 60abd718e228d..3dc6fb151cb7c 100644 --- a/lib/Sema/SemaExpr.cpp +++ b/lib/Sema/SemaExpr.cpp @@ -248,7 +248,7 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, Diag(Loc, diag::err_deleted_inherited_ctor_use) << Ctor->getParent() << Ctor->getInheritedConstructor().getConstructor()->getParent(); - else + else Diag(Loc, diag::err_deleted_function_use); NoteDeletedFunction(FD); return true; @@ -401,7 +401,7 @@ void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, if (MissingNilLoc.isInvalid()) Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); else - Diag(MissingNilLoc, diag::warn_missing_sentinel) + Diag(MissingNilLoc, diag::warn_missing_sentinel) << int(calleeType) << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); @@ -423,7 +423,7 @@ ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { if (result.isInvalid()) return ExprError(); E = result.get(); } - + QualType Ty = E->getType(); assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); @@ -479,12 +479,12 @@ static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, const ObjCIvarDecl *IV = OIRE->getDecl(); if (!IV) return; - + DeclarationName MemberName = IV->getDeclName(); IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); if (!Member || !Member->isStr("isa")) return; - + const Expr *Base = OIRE->getBase(); QualType BaseType = Base->getType(); if (OIRE->isArrow()) @@ -536,7 +536,7 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { if (result.isInvalid()) return ExprError(); E = result.get(); } - + // C++ [conv.lval]p1: // A glvalue of a non-function, non-array type T can be // converted to a prvalue. @@ -604,8 +604,8 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { (void)isCompleteType(E->getExprLoc(), T); UpdateMarkingForLValueToRValue(E); - - // Loading a __weak object implicitly retains the value, so we need a cleanup to + + // Loading a __weak object implicitly retains the value, so we need a cleanup to // balance that. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) Cleanup.setExprNeedsCleanups(true); @@ -614,14 +614,14 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { nullptr, VK_RValue); // C11 6.3.2.1p2: - // ... if the lvalue has atomic type, the value has the non-atomic version + // ... if the lvalue has atomic type, the value has the non-atomic version // of the type of the lvalue ... if (const AtomicType *Atomic = T->getAs<AtomicType>()) { T = Atomic->getValueType().getUnqualifiedType(); Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), nullptr, VK_RValue); } - + return Res; } @@ -876,7 +876,7 @@ ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, E = ExprRes.get(); } } - + ExprResult ExprRes = DefaultArgumentPromotion(E); if (ExprRes.isInvalid()) return ExprError(); @@ -1011,7 +1011,7 @@ static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, CK_IntegralToFloating); return FloatTy; } - + // Convert both sides to the appropriate complex float. assert(IntTy->isComplexIntegerType()); QualType result = S.Context.getComplexType(FloatTy); @@ -1201,7 +1201,7 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, QualType ComplexType = S.Context.getComplexType(ScalarType); RHS = S.ImpCastExprToType(RHS.get(), ComplexType, CK_IntegralRealToComplex); - + return ComplexType; } @@ -1212,7 +1212,7 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, handleIntegerConversion<doIntegralCast, doComplexIntegralCast> (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); QualType ComplexType = S.Context.getComplexType(ScalarType); - + if (!IsCompAssign) LHS = S.ImpCastExprToType(LHS.get(), ComplexType, CK_IntegralRealToComplex); @@ -2099,7 +2099,7 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); LookupParsedName(R, S, &SS, !IvarLookupFollowUp); - // If the result might be in a dependent base class, this is a dependent + // If the result might be in a dependent base class, this is a dependent // id-expression. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, @@ -2357,7 +2357,7 @@ Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation) { SourceLocation Loc = Lookup.getNameLoc(); ObjCMethodDecl *CurMethod = getCurMethodDecl(); - + // Check for error condition which is already reported. if (!CurMethod) return ExprError(); @@ -2445,7 +2445,7 @@ Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, Diag(Loc, diag::warn_implicitly_retains_self) << FixItHint::CreateInsertion(Loc, "self->"); } - + return Result; } } else if (CurMethod->isInstanceMethod()) { @@ -2918,7 +2918,7 @@ ExprResult Sema::BuildDeclarationNameExpr( if (!CapturedType.isNull()) type = CapturedType; } - + break; } @@ -2934,7 +2934,7 @@ ExprResult Sema::BuildDeclarationNameExpr( diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); break; } - + case Decl::Function: { if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { @@ -2959,7 +2959,7 @@ ExprResult Sema::BuildDeclarationNameExpr( valueKind = VK_LValue; break; } - + // C99 DR 316 says that, if a function type comes from a // function definition (without a prototype), that type is only // used for checking compatibility. Therefore, when referencing @@ -4029,11 +4029,11 @@ ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind) { ExprResult PE = CheckPlaceholderExpr(E); - if (PE.isInvalid()) + if (PE.isInvalid()) return ExprError(); E = PE.get(); - + // Verify that the operand is valid. bool isInvalid = false; if (E->isTypeDependent()) { @@ -4562,7 +4562,7 @@ bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, diag::note_default_argument_declared_here); return true; } - + if (Param->hasUninstantiatedDefaultArg()) { Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); @@ -4664,7 +4664,7 @@ bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, "default argument expression has capturing blocks?"); } - // We already type-checked the argument, so we know it works. + // We already type-checked the argument, so we know it works. // Just mark all of the declarations in this potentially-evaluated expression // as being "referenced". MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), @@ -4861,7 +4861,7 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) Diag(FDecl->getLocStart(), diag::note_callee_decl) << FDecl; - + // This deletes the extra arguments. Call->setNumArgs(Context, NumParams); return true; @@ -4869,7 +4869,7 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, } SmallVector<Expr *, 8> AllArgs; VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); - + Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, Proto, 0, Args, AllArgs, CallType); if (Invalid) @@ -5275,11 +5275,11 @@ tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( // Check if the naming class in which the unresolved members were found is // related (same as or is a base of) to the enclosing class. - + if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) return; - - + + DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); // If the enclosing function is not dependent, then this lambda is // capture ready, so if we can capture this, do so. @@ -5625,7 +5625,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); } - + // If the function we're calling isn't a function prototype, but we have // a function prototype from a prior declaratiom, use that prototype. if (!FDecl->hasPrototype()) @@ -5643,7 +5643,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, PerformCopyInitialization(Entity, SourceLocation(), Arg); if (ArgE.isInvalid()) return true; - + Arg = ArgE.getAs<Expr>(); } else { @@ -5654,7 +5654,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, Arg = ArgE.getAs<Expr>(); } - + if (RequireCompleteType(Arg->getLocStart(), Arg->getType(), diag::err_call_incomplete_argument, Arg)) @@ -5728,7 +5728,7 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, InitializedEntity Entity = InitializedEntity::InitializeCompoundLiteralInit(TInfo); InitializationKind Kind - = InitializationKind::CreateCStyleCast(LParenLoc, + = InitializationKind::CreateCStyleCast(LParenLoc, SourceRange(LParenLoc, RParenLoc), /*InitList=*/true); InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); @@ -6007,11 +6007,11 @@ static bool breakDownVectorType(QualType type, uint64_t &len, assert(eltType->isScalarType()); return true; } - + // We allow lax conversion to and from non-vector types, but only if // they're real types (i.e. non-complex, non-pointer scalar types). if (!type->isRealType()) return false; - + len = 1; eltType = type; return true; @@ -6026,7 +6026,7 @@ static bool breakDownVectorType(QualType type, uint64_t &len, /// vector nor a real type. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { assert(destTy->isVectorType() || srcTy->isVectorType()); - + // Disallow lax conversions between scalars and ExtVectors (these // conversions are allowed for other vector types because common headers // depend on them). Most scalar OP ExtVector cases are handled by the @@ -6039,13 +6039,13 @@ bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { QualType srcEltTy, destEltTy; if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; - + // ASTContext::getTypeSize will return the size rounded up to a // power of 2, so instead of using that, we need to use the raw // element size multiplied by the element count. uint64_t srcEltSize = Context.getTypeSize(srcEltTy); uint64_t destEltSize = Context.getTypeSize(destEltTy); - + return (srcLen * srcEltSize == destLen * destEltSize); } @@ -6053,7 +6053,7 @@ bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { /// known to be a vector type? bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { assert(destTy->isVectorType() || srcTy->isVectorType()); - + if (!Context.getLangOpts().LaxVectorConversions) return false; return areLaxCompatibleVectorTypes(srcTy, destTy); @@ -6211,9 +6211,9 @@ Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, if (getLangOpts().CPlusPlus && !castType->isVoidType() && !getSourceManager().isInSystemMacro(LParenLoc)) Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); - + CheckTollFreeBridgeCast(castType, CastExpr); - + CheckObjCBridgeRelatedCast(castType, CastExpr); DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); @@ -6250,7 +6250,7 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, SmallVector<Expr *, 8> initExprs; const VectorType *VTy = Ty->getAs<VectorType>(); unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); - + // '(...)' form of vector initialization in AltiVec: the number of // initializers must be one or must match the size of the vector. // If a single value is specified in the initializer then it will be @@ -6290,7 +6290,7 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, PrepareScalarCast(Literal, ElemTy)); return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); } - + initExprs.append(exprs, exprs + numExprs); } // FIXME: This means that pretty-printing the final AST will produce curly @@ -6787,7 +6787,7 @@ static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc) { - Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); + Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); if (Cond.isInvalid()) return QualType(); QualType CondTy = Cond.get()->getType(); @@ -7359,7 +7359,7 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, ExprValueKind VK = VK_RValue; ExprObjectKind OK = OK_Ordinary; ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; - QualType result = CheckConditionalOperands(Cond, LHS, RHS, + QualType result = CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) @@ -7431,7 +7431,7 @@ checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { // Treat lifetime mismatches as fatal. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; - + // For GCC/MS compatibility, other qualifier mismatches are treated // as still compatible in C. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; @@ -7778,7 +7778,7 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, // - conversions from 'Class' to the redefinition type if (RHSType->isObjCClassType() && - Context.hasSameType(LHSType, + Context.hasSameType(LHSType, Context.getObjCClassRedefinitionType())) { Kind = CK_BitCast; return Compatible; @@ -7845,10 +7845,10 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, // A* -> B* if (RHSType->isObjCObjectPointerType()) { Kind = CK_BitCast; - Sema::AssignConvertType result = + Sema::AssignConvertType result = checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && - result == Compatible && + result == Compatible && !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) result = IncompatibleObjCWeakRef; return result; @@ -7872,7 +7872,7 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, // - conversions to 'Class' from its redefinition type if (LHSType->isObjCClassType() && - Context.hasSameType(RHSType, + Context.hasSameType(RHSType, Context.getObjCClassRedefinitionType())) { return Compatible; } @@ -7881,7 +7881,7 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, } // Only under strict condition T^ is compatible with an Objective-C pointer. - if (RHSType->isBlockPointerType() && + if (RHSType->isBlockPointerType() && LHSType->isBlockCompatibleObjCPointerType(Context)) { if (ConvertRHS) maybeExtendBlockObject(RHS); @@ -8113,7 +8113,7 @@ Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; } } - + CastKind Kind; Sema::AssignConvertType result = CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); @@ -8249,7 +8249,7 @@ static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, // The conversion to apply to the scalar before splatting it, // if necessary. CastKind scalarCast = CK_NoOp; - + if (vectorEltTy->isIntegralType(S.Context)) { if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || (scalarTy->isIntegerType() && @@ -8709,7 +8709,7 @@ QualType Sema::CheckRemainderOperands( if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) { - if (LHS.get()->getType()->hasIntegerRepresentation() && + if (LHS.get()->getType()->hasIntegerRepresentation() && RHS.get()->getType()->hasIntegerRepresentation()) return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, /*AllowBothBool*/getLangOpts().AltiVec, @@ -9061,7 +9061,7 @@ QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, // In C++ adding zero to a null pointer is defined. llvm::APSInt KnownVal; if (!getLangOpts().CPlusPlus || - (!IExp->isValueDependent() && + (!IExp->isValueDependent() && (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { // Check the conditions to see if this is the 'p = nullptr + n' idiom. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( @@ -9138,7 +9138,7 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, Expr::NPC_ValueDependentIsNotNull)) { // In C++ adding zero to a null pointer is defined. llvm::APSInt KnownVal; - if (!getLangOpts().CPlusPlus || + if (!getLangOpts().CPlusPlus || (!RHS.get()->isValueDependent() && (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); @@ -10416,7 +10416,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, if (isError) return QualType(); } - + if (LHSType->isIntegerType()) LHS = ImpCastExprToType(LHS.get(), RHSType, LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); @@ -10425,7 +10425,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); return computeResultTy(); } - + // Handle block pointers. if (!IsRelational && RHSIsNull && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { @@ -10596,7 +10596,7 @@ inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, // Check vector operands differently. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) return CheckVectorLogicalOperands(LHS, RHS, Loc); - + // Diagnose cases where the user write a logical and/or but probably meant a // bitwise one. We do this when the LHS is a non-bool integer and the RHS // is a constant. @@ -11120,7 +11120,7 @@ QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, << LHSType.getUnqualifiedType(); return QualType(); } - + AssignConvertType ConvTy; if (CompoundType.isNull()) { Expr *RHSCheck = RHS.get(); @@ -11357,7 +11357,7 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, // Otherwise, we just need a complete type. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || checkArithmeticOnObjCPointer(S, OpLoc, Op)) - return QualType(); + return QualType(); } else if (ResType->isAnyComplexType()) { // C99 does not support ++/-- on complex types, we allow as an extension. S.Diag(OpLoc, diag::ext_integer_increment_complex) @@ -11397,7 +11397,7 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, return ResType.getUnqualifiedType(); } } - + /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). /// This routine allows us to typecheck complex/recursive expressions @@ -11557,7 +11557,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { Expr::LValueClassification lval = op->ClassifyLValue(Context); unsigned AddressOfError = AO_No_Error; - if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { + if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { bool sfinae = (bool)isSFINAEContext(); Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary : diag::ext_typecheck_addrof_temporary) @@ -11772,7 +11772,7 @@ static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, // ...except that certain expressions are never l-values in C. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) VK = VK_RValue; - + return Result; } @@ -11910,7 +11910,7 @@ static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, if (SelArg0.startswith("performSelector")) Diag = diag::warn_objc_pointer_masking_performSelector; } - + S.Diag(OpLoc, Diag) << ObjCPointerExpr->getSourceRange(); } @@ -12209,7 +12209,7 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, else if (const ObjCIvarRefExpr *OIRE = dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); - + // Opc is not a compound assignment if CompResultTy is null. if (CompResultTy.isNull()) { if (ConvertHalfVec) @@ -12549,7 +12549,7 @@ ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, return ExprError(); } } - + ExprResult LHS = CheckPlaceholderExpr(LHSExpr); if (LHS.isInvalid()) return ExprError(); LHSExpr = LHS.get(); @@ -12762,7 +12762,7 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << resultType << Input.get()->getSourceRange()); } - + // LNot always has type int. C99 6.5.3.3p5. // In C++, it's bool. C++ 5.3.1p8 resultType = Context.getLogicalOperationType(); @@ -12820,23 +12820,23 @@ bool Sema::isQualifiedMemberAccess(Expr *E) { if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { if (!DRE->getQualifier()) return false; - + ValueDecl *VD = DRE->getDecl(); if (!VD->isCXXClassMember()) return false; - + if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) return true; if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) return Method->isInstance(); - + return false; } - + if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { if (!ULE->getQualifier()) return false; - + for (NamedDecl *D : ULE->decls()) { if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isInstance()) @@ -12846,10 +12846,10 @@ bool Sema::isQualifiedMemberAccess(Expr *E) { break; } } - + return false; } - + return false; } @@ -13031,17 +13031,17 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, QualType ArgTy = TInfo->getType(); bool Dependent = ArgTy->isDependentType(); SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); - + // We must have at least one component that refers to the type, and the first // one is known to be a field designator. Verify that the ArgTy represents // a struct/union/class. if (!Dependent && !ArgTy->isRecordType()) - return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) + return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) << ArgTy << TypeRange); - + // Type must be complete per C99 7.17p3 because a declaring a variable // with an incomplete type would be ill-formed. - if (!Dependent + if (!Dependent && RequireCompleteType(BuiltinLoc, ArgTy, diag::err_offsetof_incomplete_type, TypeRange)) return ExprError(); @@ -13061,7 +13061,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, CurrentType = AT->getElementType(); } else CurrentType = Context.DependentTy; - + ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); if (IdxRval.isInvalid()) return ExprError(); @@ -13080,7 +13080,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, Exprs.push_back(Idx); continue; } - + // Offset of a field. if (CurrentType->isDependentType()) { // We have the offset of a field, but we can't look into the dependent @@ -13089,19 +13089,19 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, CurrentType = Context.DependentTy; continue; } - + // We need to have a complete type to look into. if (RequireCompleteType(OC.LocStart, CurrentType, diag::err_offsetof_incomplete_type)) return ExprError(); - + // Look for the designated field. const RecordType *RC = CurrentType->getAs<RecordType>(); - if (!RC) + if (!RC) return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) << CurrentType); RecordDecl *RD = RC->getDecl(); - + // C++ [lib.support.types]p5: // The macro offsetof accepts a restricted set of type arguments in this // International Standard. type shall be a POD structure or a POD union @@ -13122,7 +13122,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, << CurrentType)) DidWarnAboutNonPOD = true; } - + // Look for the field. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); LookupQualifiedName(R, RD); @@ -13135,9 +13135,9 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, if (!MemberDecl) return ExprError(Diag(BuiltinLoc, diag::err_no_member) - << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, + << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd)); - + // C99 7.17p3: // (If the specified member is a bit-field, the behavior is undefined.) // @@ -13180,9 +13180,9 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, } else Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); - CurrentType = MemberDecl->getType().getNonReferenceType(); + CurrentType = MemberDecl->getType().getNonReferenceType(); } - + return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, Comps, Exprs, RParenLoc); } @@ -13193,7 +13193,7 @@ ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc) { - + TypeSourceInfo *ArgTInfo; QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); if (ArgTy.isNull()) @@ -13298,7 +13298,7 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, T = Context.getFunctionType(Context.DependentTy, None, EPI); Sig = Context.getTrivialTypeSourceInfo(T); } - + // GetTypeForDeclarator always produces a function type for a block // literal signature. Furthermore, it is always a FunctionProtoType // unless the function was written with a typedef. @@ -13376,7 +13376,7 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), /*CheckParameterNames=*/false); } - + // Finally we can process decl attributes. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); @@ -13452,7 +13452,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, FunctionType::ExtInfo Ext = FTy->getExtInfo(); if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); - + // Turn protoless block types into nullary block types. if (isa<FunctionNoProtoType>(FTy)) { FunctionProtoType::ExtProtoInfo EPI; @@ -13500,7 +13500,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, if (getLangOpts().CPlusPlus && RetTy->isRecordType() && !BSI->TheDecl->isDependentContext()) computeNRVO(Body, BSI); - + BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); @@ -13674,7 +13674,7 @@ bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, if (!ID || !ID->getIdentifier()->isStr("NSString")) return false; } - + // Ignore any parens, implicit casts (should only be // array-to-pointer decays), and not-so-opaque values. The last is // important for making this trigger for property assignments. @@ -13907,7 +13907,7 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, PDecl && IFace && !IFace->hasDefinition()) Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) << IFace << PDecl; - + if (SecondType == Context.OverloadTy) NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, FirstType, /*TakingAddress=*/true); @@ -13917,7 +13917,7 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, if (Action == AA_Returning && ConvTy == IncompatiblePointer) EmitRelatedResultTypeNoteForReturn(DstType); - + if (Complained) *Complained = true; return isInvalid; @@ -13931,7 +13931,7 @@ ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; } } Diagnoser; - + return VerifyIntegerConstantExpression(E, Result, Diagnoser); } @@ -13941,16 +13941,16 @@ ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, bool AllowFold) { class IDDiagnoser : public VerifyICEDiagnoser { unsigned DiagID; - + public: IDDiagnoser(unsigned DiagID) : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } - + void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { S.Diag(Loc, DiagID) << SR; } } Diagnoser(DiagID); - + return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); } @@ -14516,19 +14516,19 @@ diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, // capture. } - -static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, + +static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, - QualType &CaptureType, + QualType &CaptureType, QualType &DeclRefType) { // Check whether we've already captured it. if (CSI->CaptureMap.count(Var)) { // If we found a capture, any subcaptures are nested. SubCapturesAreNested = true; - + // Retrieve the capture type for this variable. CaptureType = CSI->getCapture(Var).getCaptureType(); - + // Compute the type of an expression that refers to this variable. DeclRefType = CaptureType.getNonReferenceType(); @@ -14548,8 +14548,8 @@ static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDec // Only block literals, captured statements, and lambda expressions can // capture; other scopes don't work. -static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, - SourceLocation Loc, +static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, + SourceLocation Loc, const bool Diagnose, Sema &S) { if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) return getLambdaAwareParentOfDeclContext(DC); @@ -14560,11 +14560,11 @@ static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl * return nullptr; } -// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture +// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture // certain types of variables (unnamed, variably modified types etc.) // so check for eligibility. -static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, - SourceLocation Loc, +static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, + SourceLocation Loc, const bool Diagnose, Sema &S) { bool IsBlock = isa<BlockScopeInfo>(CSI); @@ -14586,7 +14586,7 @@ static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, if (Var->getType()->isVariablyModifiedType() && IsBlock) { if (Diagnose) { S.Diag(Loc, diag::err_ref_vm_type); - S.Diag(Var->getLocation(), diag::note_previous_decl) + S.Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); } return false; @@ -14631,21 +14631,21 @@ static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, } // Returns true if the capture by block was successful. -static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, - SourceLocation Loc, - const bool BuildAndDiagnose, +static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, + SourceLocation Loc, + const bool BuildAndDiagnose, QualType &CaptureType, - QualType &DeclRefType, + QualType &DeclRefType, const bool Nested, Sema &S) { Expr *CopyExpr = nullptr; bool ByRef = false; - + // Blocks are not allowed to capture arrays. if (CaptureType->isArrayType()) { if (BuildAndDiagnose) { S.Diag(Loc, diag::err_ref_array_type); - S.Diag(Var->getLocation(), diag::note_previous_decl) + S.Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); } return false; @@ -14703,7 +14703,7 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, // Block capture by copy introduces 'const'. CaptureType = CaptureType.getNonReferenceType().withConst(); DeclRefType = CaptureType; - + if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { // The capture logic needs the destructor, so make sure we mark it. @@ -14723,15 +14723,15 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, // the stack requires a const copy constructor. This is not true // of the copy/move done to move a __block variable to the heap. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, - DeclRefType.withConst(), + DeclRefType.withConst(), VK_LValue, Loc); - + ExprResult Result = S.PerformCopyInitialization( InitializedEntity::InitializeBlock(Var->getLocation(), CaptureType, false), Loc, DeclRef); - + // Build a full-expression copy expression if initialization // succeeded and used a non-trivial constructor. Recover from // errors by pretending that the copy isn't necessary. @@ -14747,7 +14747,7 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, // Actually capture the variable. if (BuildAndDiagnose) - BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, + BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), CaptureType, CopyExpr); return true; @@ -14757,11 +14757,11 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, /// Capture the given variable in the captured region. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, - VarDecl *Var, - SourceLocation Loc, - const bool BuildAndDiagnose, + VarDecl *Var, + SourceLocation Loc, + const bool BuildAndDiagnose, QualType &CaptureType, - QualType &DeclRefType, + QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S) { // By default, capture variables by reference. @@ -14799,7 +14799,7 @@ static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, RD->addDecl(Field); if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); - + CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc); Var->setReferenced(true); @@ -14810,14 +14810,14 @@ static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, if (BuildAndDiagnose) RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, SourceLocation(), CaptureType, CopyExpr); - - + + return true; } /// Create a field within the lambda class for the variable /// being captured. -static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, +static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, QualType FieldType, QualType DeclRefType, SourceLocation Loc, bool RefersToCapturedVariable) { @@ -14835,13 +14835,13 @@ static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, /// Capture the given variable in the lambda. static bool captureInLambda(LambdaScopeInfo *LSI, - VarDecl *Var, - SourceLocation Loc, - const bool BuildAndDiagnose, + VarDecl *Var, + SourceLocation Loc, + const bool BuildAndDiagnose, QualType &CaptureType, - QualType &DeclRefType, + QualType &DeclRefType, const bool RefersToCapturedVariable, - const Sema::TryCaptureKind Kind, + const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S) { @@ -14853,7 +14853,7 @@ static bool captureInLambda(LambdaScopeInfo *LSI, } else { ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); } - + // Compute the type of the field that will capture this variable. if (ByRef) { // C++11 [expr.prim.lambda]p15: @@ -14865,7 +14865,7 @@ static bool captureInLambda(LambdaScopeInfo *LSI, // // FIXME: It is not clear whether we want to build an lvalue reference // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears - // to do the former, while EDG does the latter. Core issue 1249 will + // to do the former, while EDG does the latter. Core issue 1249 will // clarify, but for now we follow GCC because it's a more permissive and // easily defensible position. CaptureType = S.Context.getLValueReferenceType(DeclRefType); @@ -14913,26 +14913,26 @@ static bool captureInLambda(LambdaScopeInfo *LSI, if (BuildAndDiagnose) addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, RefersToCapturedVariable); - + // Compute the type of a reference to this captured variable. if (ByRef) DeclRefType = CaptureType.getNonReferenceType(); else { // C++ [expr.prim.lambda]p5: - // The closure type for a lambda-expression has a public inline - // function call operator [...]. This function call operator is - // declared const (9.3.1) if and only if the lambda-expression's + // The closure type for a lambda-expression has a public inline + // function call operator [...]. This function call operator is + // declared const (9.3.1) if and only if the lambda-expression's // parameter-declaration-clause is not followed by mutable. DeclRefType = CaptureType.getNonReferenceType(); if (!LSI->Mutable && !CaptureType->isReferenceType()) - DeclRefType.addConst(); + DeclRefType.addConst(); } - + // Add the capture. if (BuildAndDiagnose) - LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, + LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); - + return true; } @@ -14945,10 +14945,10 @@ bool Sema::tryCaptureVariable( DeclContext *VarDC = Var->getDeclContext(); if (Var->isInitCapture()) VarDC = VarDC->getParent(); - + DeclContext *DC = CurContext; - const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt - ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; + const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt + ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; // We need to sync up the Declaration Context with the // FunctionScopeIndexToStopAt if (FunctionScopeIndexToStopAt) { @@ -14959,7 +14959,7 @@ bool Sema::tryCaptureVariable( } } - + // If the variable is declared in the current context, there is no need to // capture it. if (VarDC == DC) return true; @@ -14975,7 +14975,7 @@ bool Sema::tryCaptureVariable( // performing the "simple" checks that don't depend on type. We stop when // we've either hit the declared scope of the variable or find an existing // capture of that variable. We start from the innermost capturing-entity - // (the DC) and ensure that all intervening capturing-entities + // (the DC) and ensure that all intervening capturing-entities // (blocks/lambdas etc.) between the innermost capturer and the variable`s // declcontext can either capture the variable or have already captured // the variable. @@ -14987,8 +14987,8 @@ bool Sema::tryCaptureVariable( do { // Only block literals, captured statements, and lambda expressions can // capture; other scopes don't work. - DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, - ExprLoc, + DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, + ExprLoc, BuildAndDiagnose, *this); // We need to check for the parent *first* because, if we *have* @@ -15007,29 +15007,29 @@ bool Sema::tryCaptureVariable( // Check whether we've already captured it. - if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, + if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, DeclRefType)) { CSI->getCapture(Var).markUsed(BuildAndDiagnose); break; } - // If we are instantiating a generic lambda call operator body, + // If we are instantiating a generic lambda call operator body, // we do not want to capture new variables. What was captured // during either a lambdas transformation or initial parsing - // should be used. + // should be used. if (isGenericLambdaCallOperatorSpecialization(DC)) { if (BuildAndDiagnose) { - LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); + LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); - Diag(Var->getLocation(), diag::note_previous_decl) + Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); - Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); + Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); } else diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); } return true; } - // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture + // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture // certain types of variables (unnamed, variably modified types etc.) // so check for eligibility. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) @@ -15070,11 +15070,11 @@ bool Sema::tryCaptureVariable( } } if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { - // No capture-default, and this is not an explicit capture - // so cannot capture this variable. + // No capture-default, and this is not an explicit capture + // so cannot capture this variable. if (BuildAndDiagnose) { Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); - Diag(Var->getLocation(), diag::note_previous_decl) + Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); if (cast<LambdaScopeInfo>(CSI)->Lambda) Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), @@ -15083,12 +15083,12 @@ bool Sema::tryCaptureVariable( // capture a variable that an inner lambda explicitly captures, we // should have the inner lambda do the explicit capture - because // it makes for cleaner diagnostics later. This would purely be done - // so that the diagnostic does not misleadingly claim that a variable - // can not be captured by a lambda implicitly even though it is captured + // so that the diagnostic does not misleadingly claim that a variable + // can not be captured by a lambda implicitly even though it is captured // explicitly. Suggestion: - // - create const bool VariableCaptureWasInitiallyExplicit = Explicit + // - create const bool VariableCaptureWasInitiallyExplicit = Explicit // at the function head - // - cache the StartingDeclContext - this must be a lambda + // - cache the StartingDeclContext - this must be a lambda // - captureInLambda in the innermost lambda the variable. } return true; @@ -15100,31 +15100,31 @@ bool Sema::tryCaptureVariable( } while (!VarDC->Equals(DC)); // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) - // computing the type of the capture at each step, checking type-specific - // requirements, and adding captures if requested. - // If the variable had already been captured previously, we start capturing - // at the lambda nested within that one. - for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; + // computing the type of the capture at each step, checking type-specific + // requirements, and adding captures if requested. + // If the variable had already been captured previously, we start capturing + // at the lambda nested within that one. + for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; ++I) { CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); - + if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { - if (!captureInBlock(BSI, Var, ExprLoc, - BuildAndDiagnose, CaptureType, + if (!captureInBlock(BSI, Var, ExprLoc, + BuildAndDiagnose, CaptureType, DeclRefType, Nested, *this)) return true; Nested = true; } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { - if (!captureInCapturedRegion(RSI, Var, ExprLoc, - BuildAndDiagnose, CaptureType, + if (!captureInCapturedRegion(RSI, Var, ExprLoc, + BuildAndDiagnose, CaptureType, DeclRefType, Nested, *this)) return true; Nested = true; } else { LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); - if (!captureInLambda(LSI, Var, ExprLoc, - BuildAndDiagnose, CaptureType, - DeclRefType, Nested, Kind, EllipsisLoc, + if (!captureInLambda(LSI, Var, ExprLoc, + BuildAndDiagnose, CaptureType, + DeclRefType, Nested, Kind, EllipsisLoc, /*IsTopScope*/I == N - 1, *this)) return true; Nested = true; @@ -15134,7 +15134,7 @@ bool Sema::tryCaptureVariable( } bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, - TryCaptureKind Kind, SourceLocation EllipsisLoc) { + TryCaptureKind Kind, SourceLocation EllipsisLoc) { QualType CaptureType; QualType DeclRefType; return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, @@ -15153,10 +15153,10 @@ bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { QualType CaptureType; QualType DeclRefType; - + // Determine whether we can capture this variable. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), - /*BuildAndDiagnose=*/false, CaptureType, + /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr)) return QualType(); @@ -15165,49 +15165,49 @@ QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { -// If either the type of the variable or the initializer is dependent, +// If either the type of the variable or the initializer is dependent, // return false. Otherwise, determine whether the variable is a constant // expression. Use this if you need to know if a variable that might or // might not be dependent is truly a constant expression. -static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, +static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, ASTContext &Context) { - - if (Var->getType()->isDependentType()) + + if (Var->getType()->isDependentType()) return false; const VarDecl *DefVD = nullptr; Var->getAnyInitializer(DefVD); - if (!DefVD) + if (!DefVD) return false; EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); Expr *Init = cast<Expr>(Eval->Value); - if (Init->isValueDependent()) + if (Init->isValueDependent()) return false; - return IsVariableAConstantExpression(Var, Context); + return IsVariableAConstantExpression(Var, Context); } void Sema::UpdateMarkingForLValueToRValue(Expr *E) { - // Per C++11 [basic.def.odr], a variable is odr-used "unless it is + // Per C++11 [basic.def.odr], a variable is odr-used "unless it is // an object that satisfies the requirements for appearing in a // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) // is immediately applied." This function handles the lvalue-to-rvalue // conversion part. MaybeODRUseExprs.erase(E->IgnoreParens()); - + // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers // to a variable that is a constant expression, and if so, identify it as - // a reference to a variable that does not involve an odr-use of that - // variable. + // a reference to a variable that does not involve an odr-use of that + // variable. if (LambdaScopeInfo *LSI = getCurLambda()) { Expr *SansParensExpr = E->IgnoreParens(); VarDecl *Var = nullptr; - if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) + if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) Var = dyn_cast<VarDecl>(ME->getMemberDecl()); - - if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) - LSI->markVariableExprAsNonODRUsed(SansParensExpr); + + if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) + LSI->markVariableExprAsNonODRUsed(SansParensExpr); } } @@ -15508,13 +15508,13 @@ namespace { class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { Sema &S; bool SkipLocalVariables; - + public: typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; - - EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) + + EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } - + void VisitDeclRefExpr(DeclRefExpr *E) { // If we were asked not to visit local variables, don't. if (SkipLocalVariables) { @@ -15522,7 +15522,7 @@ namespace { if (VD->hasLocalStorage()) return; } - + S.MarkDeclRefReferenced(E); } @@ -15530,13 +15530,13 @@ namespace { S.MarkMemberReferenced(E); Inherited::VisitMemberExpr(E); } - + void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { S.MarkFunctionReferenced(E->getLocStart(), const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); Visit(E->getSubExpr()); } - + void VisitCXXNewExpr(CXXNewExpr *E) { if (E->getOperatorNew()) S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); @@ -15551,18 +15551,18 @@ namespace { QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); - S.MarkFunctionReferenced(E->getLocStart(), + S.MarkFunctionReferenced(E->getLocStart(), S.LookupDestructor(Record)); } - + Inherited::VisitCXXDeleteExpr(E); } - + void VisitCXXConstructExpr(CXXConstructExpr *E) { S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); Inherited::VisitCXXConstructExpr(E); } - + void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { Visit(E->getExpr()); } @@ -15579,9 +15579,9 @@ namespace { /// Mark any declarations that appear within this expression or any /// potentially-evaluated subexpressions as "referenced". /// -/// \param SkipLocalVariables If true, don't mark local variables as +/// \param SkipLocalVariables If true, don't mark local variables as /// 'referenced'. -void Sema::MarkDeclarationsReferencedInExpr(Expr *E, +void Sema::MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables) { EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); } @@ -15661,7 +15661,7 @@ bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, class CallReturnIncompleteDiagnoser : public TypeDiagnoser { FunctionDecl *FD; CallExpr *CE; - + public: CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) : FD(FD), CE(CE) { } @@ -15672,14 +15672,14 @@ bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, << T << CE->getSourceRange(); return; } - + S.Diag(Loc, diag::err_call_function_incomplete_return) << CE->getSourceRange() << FD->getDeclName() << T; S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD->getDeclName(); } } Diagnoser(FD, CE); - + if (RequireCompleteType(Loc, ReturnType, Diagnoser)) return true; @@ -15762,7 +15762,7 @@ void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) == Expr::MLV_Valid) { SourceLocation Loc = opE->getOperatorLoc(); - + Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); SourceRange ParenERange = ParenE->getSourceRange(); Diag(Loc, diag::note_equality_comparison_silence) @@ -16099,7 +16099,7 @@ ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { } // Rebuild the appropriate pointer-to-function type. - switch (Kind) { + switch (Kind) { case FK_MemberFunction: // Nothing to do. break; @@ -16148,15 +16148,15 @@ ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { if (E->getCastKind() == CK_FunctionToPointerDecay) { assert(E->getValueKind() == VK_RValue); assert(E->getObjectKind() == OK_Ordinary); - + E->setType(DestType); - + // Rebuild the sub-expression as the pointee (function) type. DestType = DestType->castAs<PointerType>()->getPointeeType(); - + ExprResult Result = Visit(E->getSubExpr()); if (!Result.isUsable()) return ExprError(); - + E->setSubExpr(Result.get()); return E; } else if (E->getCastKind() == CK_LValueToRValue) { @@ -16218,7 +16218,7 @@ ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { SC_None, false/*isInlineSpecified*/, FD->hasPrototype(), false/*isConstexprSpecified*/); - + if (FD->getQualifier()) NewFD->setQualifierInfo(FD->getQualifierLoc()); @@ -16486,7 +16486,7 @@ Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { Sema::LookupOrdinaryName); if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { NamedDecl *ND = Result.getFoundDecl(); - if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) + if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) Context.setBOOLDecl(TD); } } diff --git a/lib/Sema/SemaExprMember.cpp b/lib/Sema/SemaExprMember.cpp index 3a8fee862c918..e6d2b5068fd56 100644 --- a/lib/Sema/SemaExprMember.cpp +++ b/lib/Sema/SemaExprMember.cpp @@ -120,7 +120,7 @@ static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, // member reference. if (Classes.empty()) return IMA_Static; - + // C++11 [expr.prim.general]p12: // An id-expression that denotes a non-static data member or non-static // member function of a class can only be used: @@ -166,7 +166,7 @@ static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, else contextClass = cast<CXXRecordDecl>(DC); - // [class.mfct.non-static]p3: + // [class.mfct.non-static]p3: // ...is used in the body of a non-static member function of class X, // if name lookup (3.4.1) resolves the name in the id-expression to a // non-static non-type member of some class C [...] @@ -417,14 +417,14 @@ CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK, QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize); // Now look up the TypeDefDecl from the vector type. Without this, // diagostics look bad. We want extended vector types to appear built-in. - for (Sema::ExtVectorDeclsType::iterator + for (Sema::ExtVectorDeclsType::iterator I = S.ExtVectorDecls.begin(S.getExternalSource()), - E = S.ExtVectorDecls.end(); + E = S.ExtVectorDecls.end(); I != E; ++I) { if ((*I)->getUnderlyingType() == VT) return S.Context.getTypedefType(*I); } - + return VT; // should never get here (a typedef type should always be found). } @@ -817,10 +817,10 @@ Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, // static data members cannot be anonymous structs or unions. // Supporting this is as easy as building a MemberExpr here. assert(!baseObjectExpr && "anonymous struct/union is static data member?"); - + DeclarationNameInfo baseNameInfo(DeclarationName(), loc); - - ExprResult result + + ExprResult result = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); if (result.isInvalid()) return ExprError(); @@ -855,10 +855,10 @@ Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, if (!result) return ExprError(); } - + // In all cases, we should now skip the first declaration in the chain. ++FI; - + while (FI != FEnd) { FieldDecl *field = cast<FieldDecl>(*FI++); @@ -873,7 +873,7 @@ Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, fakeFoundDecl, memberNameInfo) .get(); } - + return result; } @@ -965,8 +965,8 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, return ExprError(); BaseExpr = Converted.get(); } - - + + const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); DeclarationName MemberName = MemberNameInfo.getName(); SourceLocation MemberLoc = MemberNameInfo.getLoc(); @@ -1035,7 +1035,7 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, !SuppressQualifierCheck && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) return ExprError(); - + // Construct an unresolved result if we in fact got an unresolved // result. if (R.isOverloadedResult() || R.isUnresolvableResult()) { @@ -1421,7 +1421,7 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp)) if (UO->getOpcode() == UO_Deref) BaseExp = UO->getSubExpr()->IgnoreParenCasts(); - + if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp)) if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access); @@ -1431,7 +1431,7 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, if (warn) { if (ObjCMethodDecl *MD = S.getCurMethodDecl()) { ObjCMethodFamily MF = MD->getMethodFamily(); - warn = (MF != OMF_init && MF != OMF_dealloc && + warn = (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV)); } @@ -1732,7 +1732,7 @@ Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, } if (VK != VK_RValue && Field->isBitField()) OK = OK_BitField; - + // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] QualType MemberType = Field->getType(); if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) { @@ -1797,7 +1797,7 @@ Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, const TemplateArgumentListInfo *TemplateArgs, bool IsKnownInstance, const Scope *S) { assert(!R.empty() && !R.isAmbiguous()); - + SourceLocation loc = R.getNameLoc(); // If this is known to be an instance access, go ahead and build an diff --git a/lib/Sema/SemaExprObjC.cpp b/lib/Sema/SemaExprObjC.cpp index bf0ffeba06b2f..b291fc8691d50 100644 --- a/lib/Sema/SemaExprObjC.cpp +++ b/lib/Sema/SemaExprObjC.cpp @@ -73,7 +73,7 @@ ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, /*Pascal=*/false, StrTy, &StrLocs[0], StrLocs.size()); } - + return BuildObjCStringLiteral(AtLocs[0], S); } @@ -92,12 +92,12 @@ ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ } else if (getLangOpts().NoConstantCFStrings) { IdentifierInfo *NSIdent=nullptr; std::string StringClass(getLangOpts().ObjCConstantStringClass); - + if (StringClass.empty()) NSIdent = &Context.Idents.get("NSConstantString"); else NSIdent = &Context.Idents.get(StringClass); - + NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, LookupOrdinaryName); if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { @@ -126,10 +126,10 @@ ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ // being an 'id' type. Ty = Context.getObjCNSStringType(); if (Ty.isNull()) { - ObjCInterfaceDecl *NSStringIDecl = - ObjCInterfaceDecl::Create (Context, - Context.getTranslationUnitDecl(), - SourceLocation(), NSIdent, + ObjCInterfaceDecl *NSStringIDecl = + ObjCInterfaceDecl::Create (Context, + Context.getTranslationUnitDecl(), + SourceLocation(), NSIdent, nullptr, nullptr, SourceLocation()); Ty = Context.getObjCInterfaceType(NSStringIDecl); Context.setObjCNSStringType(Ty); @@ -252,16 +252,16 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, } return nullptr; } - + // If we already looked up this method, we're done. if (S.NSNumberLiteralMethods[*Kind]) return S.NSNumberLiteralMethods[*Kind]; - + Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, /*Instance=*/false); - + ASTContext &CX = S.Context; - + // Look up the NSNumber class, if we haven't done so already. It's cached // in the Sema instance. if (!S.NSNumberDecl) { @@ -277,7 +277,7 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); } - + // Look for the appropriate method within NSNumber. ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); if (!Method && S.getLangOpts().DebuggerObjCLiteral) { @@ -304,7 +304,7 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, // Note: if the parameter type is out-of-line, we'll catch it later in the // implicit conversion. - + S.NSNumberLiteralMethods[*Kind] = Method; return Method; } @@ -322,21 +322,21 @@ ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { case CharacterLiteral::UTF8: NumberType = Context.CharTy; break; - + case CharacterLiteral::Wide: NumberType = Context.getWideCharType(); break; - + case CharacterLiteral::UTF16: NumberType = Context.Char16Ty; break; - + case CharacterLiteral::UTF32: NumberType = Context.Char32Ty; break; } } - + // Look for the appropriate method within NSNumber. // Construct the literal. SourceRange NR(Number->getSourceRange()); @@ -355,33 +355,33 @@ ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { if (ConvertedNumber.isInvalid()) return ExprError(); Number = ConvertedNumber.get(); - + // Use the effective source range of the literal, including the leading '@'. return MaybeBindToTemporary( new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, SourceRange(AtLoc, NR.getEnd()))); } -ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, +ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value) { ExprResult Inner; if (getLangOpts().CPlusPlus) { Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); } else { - // C doesn't actually have a way to represent literal values of type + // C doesn't actually have a way to represent literal values of type // _Bool. So, we'll use 0/1 and implicit cast to _Bool. Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); - Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, + Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean); } - + return BuildObjCNumericLiteral(AtLoc, Inner.get()); } /// Check that the given expression is a valid element of an Objective-C /// collection literal. -static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, +static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, QualType T, bool ArrayLiteral = false) { // If the expression is type-dependent, there's nothing for us to do. @@ -393,7 +393,7 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, return ExprError(); Element = Result.get(); - // In C++, check for an implicit conversion to an Objective-C object pointer + // In C++, check for an implicit conversion to an Objective-C object pointer // type. if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { InitializedEntity Entity @@ -413,15 +413,15 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, Result = S.DefaultLvalueConversion(Element); if (Result.isInvalid()) return ExprError(); - Element = Result.get(); + Element = Result.get(); // Make sure that we have an Objective-C pointer type or block. if (!Element->getType()->isObjCObjectPointerType() && !Element->getType()->isBlockPointerType()) { bool Recovered = false; - + // If this is potentially an Objective-C numeric literal, add the '@'. - if (isa<IntegerLiteral>(OrigElement) || + if (isa<IntegerLiteral>(OrigElement) || isa<CharacterLiteral>(OrigElement) || isa<FloatingLiteral>(OrigElement) || isa<ObjCBoolLiteralExpr>(OrigElement) || @@ -431,16 +431,16 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, : (isa<CXXBoolLiteralExpr>(OrigElement) || isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 : 3; - + S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) << Which << OrigElement->getSourceRange() << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); - + Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), OrigElement); if (Result.isInvalid()) return ExprError(); - + Element = Result.get(); Recovered = true; } @@ -455,12 +455,12 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); if (Result.isInvalid()) return ExprError(); - + Element = Result.get(); Recovered = true; } } - + if (!Recovered) { S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) << Element->getType(); @@ -488,17 +488,17 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, } } - // Make sure that the element has the type that the container factory - // function expects. + // Make sure that the element has the type that the container factory + // function expects. return S.PerformCopyInitialization( - InitializedEntity::InitializeParameter(S.Context, T, + InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false), Element->getLocStart(), Element); } ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { if (ValueExpr->isTypeDependent()) { - ObjCBoxedExpr *BoxedExpr = + ObjCBoxedExpr *BoxedExpr = new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR); return BoxedExpr; } @@ -525,7 +525,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); } - + if (!StringWithUTF8StringMethod) { IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); @@ -561,7 +561,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { StringWithUTF8StringMethod = BoxingMethod; } - + BoxingMethod = StringWithUTF8StringMethod; BoxedType = NSStringPointer; // Transfer the nullability from method's return type. @@ -588,22 +588,22 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { case CharacterLiteral::UTF8: ValueType = Context.CharTy; break; - + case CharacterLiteral::Wide: ValueType = Context.getWideCharType(); break; - + case CharacterLiteral::UTF16: ValueType = Context.Char16Ty; break; - + case CharacterLiteral::UTF32: ValueType = Context.Char32Ty; break; } } // FIXME: Do I need to do anything special with BoolTy expressions? - + // Look for the appropriate method within NSNumber. BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType); BoxedType = NSNumberPointer; @@ -620,7 +620,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { } else if (ValueType->isObjCBoxableRecordType()) { // Support for structure types, that marked as objc_boxable // struct __attribute__((objc_boxable)) s { ... }; - + // Look up the NSValue class, if we haven't done so already. It's cached // in the Sema instance. if (!NSValueDecl) { @@ -634,14 +634,14 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl); NSValuePointer = Context.getObjCObjectPointerType(NSValueObject); } - + if (!ValueWithBytesObjCTypeMethod) { IdentifierInfo *II[] = { &Context.Idents.get("valueWithBytes"), &Context.Idents.get("objCType") }; Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II); - + // Look for the appropriate method within NSValue. BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType); if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { @@ -662,9 +662,9 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { /*isDefined=*/false, ObjCMethodDecl::Required, /*HasRelatedResultType=*/false); - + SmallVector<ParmVarDecl *, 2> Params; - + ParmVarDecl *bytes = ParmVarDecl::Create(Context, M, SourceLocation(), SourceLocation(), @@ -673,7 +673,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { /*TInfo=*/nullptr, SC_None, nullptr); Params.push_back(bytes); - + QualType ConstCharType = Context.CharTy.withConst(); ParmVarDecl *type = ParmVarDecl::Create(Context, M, @@ -683,18 +683,18 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { /*TInfo=*/nullptr, SC_None, nullptr); Params.push_back(type); - + M->setMethodParams(Context, Params, None); BoxingMethod = M; } - + if (!validateBoxingMethod(*this, Loc, NSValueDecl, ValueWithBytesObjCType, BoxingMethod)) return ExprError(); - + ValueWithBytesObjCTypeMethod = BoxingMethod; } - + if (!ValueType.isTriviallyCopyableType(Context)) { Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type) << ValueType << ValueExpr->getSourceRange(); @@ -710,13 +710,13 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { << ValueType << ValueExpr->getSourceRange(); return ExprError(); } - + DiagnoseUseOfDecl(BoxingMethod, Loc); ExprResult ConvertedValueExpr; if (ValueType->isObjCBoxableRecordType()) { InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType); - ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(), + ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(), ValueExpr); } else { // Convert the expression to the type that the parameter requires. @@ -726,12 +726,12 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(), ValueExpr); } - + if (ConvertedValueExpr.isInvalid()) return ExprError(); ValueExpr = ConvertedValueExpr.get(); - - ObjCBoxedExpr *BoxedExpr = + + ObjCBoxedExpr *BoxedExpr = new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, BoxingMethod, SR); return MaybeBindToTemporary(BoxedExpr); @@ -756,7 +756,7 @@ ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, if (Result.isInvalid()) return ExprError(); IndexExpr = Result.get(); - + // Perform lvalue-to-rvalue conversion on the base. Result = DefaultLvalueConversion(BaseExpr); if (Result.isInvalid()) @@ -821,24 +821,24 @@ ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { // Dig out the type that all elements should be converted to. QualType T = Method->parameters()[0]->getType(); const PointerType *PtrT = T->getAs<PointerType>(); - if (!PtrT || + if (!PtrT || !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->parameters()[0]->getLocation(), diag::note_objc_literal_method_param) - << 0 << T + << 0 << T << Context.getPointerType(IdT.withConst()); return ExprError(); } - + // Check that the 'count' parameter is integral. if (!Method->parameters()[1]->getType()->isIntegerType()) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->parameters()[1]->getLocation(), diag::note_objc_literal_method_param) - << 1 + << 1 << Method->parameters()[1]->getType() << "integral"; return ExprError(); @@ -860,11 +860,11 @@ ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { RequiredType, true); if (Converted.isInvalid()) return ExprError(); - + ElementsBuffer[I] = Converted.get(); } - - QualType Ty + + QualType Ty = Context.getObjCObjectPointerType( Context.getObjCInterfaceType(NSArrayDecl)); @@ -893,7 +893,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, NSAPI::NSDict_dictionaryWithObjectsForKeysCount); ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); if (!Method && getLangOpts().DebuggerObjCLiteral) { - Method = ObjCMethodDecl::Create(Context, + Method = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(), Sel, IdT, nullptr /*TypeSourceInfo */, @@ -938,7 +938,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, // Dig out the type that all values should be converted to. QualType ValueT = Method->parameters()[0]->getType(); const PointerType *PtrValue = ValueT->getAs<PointerType>(); - if (!PtrValue || + if (!PtrValue || !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; @@ -952,7 +952,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, // Dig out the type that all keys should be converted to. QualType KeyT = Method->parameters()[1]->getType(); const PointerType *PtrKey = KeyT->getAs<PointerType>(); - if (!PtrKey || + if (!PtrKey || !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), IdT)) { bool err = true; @@ -962,7 +962,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, if (ObjCProtocolDecl *NSCopyingPDecl = LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; - QIDNSCopying = + QIDNSCopying = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { }, llvm::makeArrayRef( (ObjCProtocolDecl**) PQ, @@ -975,7 +975,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), QIDNSCopying); } - + if (err) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; @@ -1008,7 +1008,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType(); QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); - // Check that each of the keys and values provided is valid in a collection + // Check that each of the keys and values provided is valid in a collection // literal, performing conversions as necessary. bool HasPackExpansions = false; for (ObjCDictionaryElement &Element : Elements) { @@ -1017,19 +1017,19 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, KeyT); if (Key.isInvalid()) return ExprError(); - + // Check the value. ExprResult Value = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT); if (Value.isInvalid()) return ExprError(); - + Element.Key = Key.get(); Element.Value = Value.get(); - + if (Element.EllipsisLoc.isInvalid()) continue; - + if (!Element.Key->containsUnexpandedParameterPack() && !Element.Value->containsUnexpandedParameterPack()) { Diag(Element.EllipsisLoc, @@ -1038,10 +1038,10 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, Element.Value->getLocEnd()); return ExprError(); } - + HasPackExpansions = true; } - + QualType Ty = Context.getObjCObjectPointerType( Context.getObjCInterfaceType(NSDictionaryDecl)); @@ -1147,7 +1147,7 @@ static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc, if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, Method, InstMethList)) Warned = true; - + // second, class methods ObjCMethodList &ClsMethList = b->second.second; if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, @@ -1175,7 +1175,7 @@ ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, Diag(SelLoc, diag::warn_undeclared_selector_with_typo) << Sel << MatchedSel << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); - + } else Diag(SelLoc, diag::warn_undeclared_selector) << Sel; } else @@ -1187,7 +1187,7 @@ ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, !getSourceManager().isInSystemHeader(Method->getLocation())) ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); - // In ARC, forbid the user from using @selector for + // In ARC, forbid the user from using @selector for // retain/release/autorelease/dealloc/retainCount. if (getLangOpts().ObjCAutoRefCount) { switch (Sel.getMethodFamily()) { @@ -1196,7 +1196,7 @@ ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, case OMF_autorelease: case OMF_retainCount: case OMF_dealloc: - Diag(AtLoc, diag::err_arc_illegal_selector) << + Diag(AtLoc, diag::err_arc_illegal_selector) << Sel << SourceRange(LParenLoc, RParenLoc); break; @@ -1269,7 +1269,7 @@ static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { if (T == Context.getObjCInstanceType()) return Context.getObjCIdType(); - + return origType; } @@ -1313,7 +1313,7 @@ static QualType getBaseMessageSendResultType(Sema &S, // was a class message send, T is the declared return type of the method // found if (Method->isInstanceMethod() && isClassMessage) - return stripObjCInstanceType(Context, + return stripObjCInstanceType(Context, Method->getSendResultType(ReceiverType)); // - if the receiver is super, T is a pointer to the class of the @@ -1334,7 +1334,7 @@ static QualType getBaseMessageSendResultType(Sema &S, // T is the declared return type of the method. if (ReceiverType->isObjCClassType() || ReceiverType->isObjCQualifiedClassType()) - return stripObjCInstanceType(Context, + return stripObjCInstanceType(Context, Method->getSendResultType(ReceiverType)); // - if the receiver is id, qualified id, Class, or qualified Class, T @@ -1424,14 +1424,14 @@ findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, if (const ObjCImplDecl *impl = dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { const ObjCContainerDecl *iface; - if (const ObjCCategoryImplDecl *catImpl = + if (const ObjCCategoryImplDecl *catImpl = dyn_cast<ObjCCategoryImplDecl>(impl)) { iface = catImpl->getCategoryDecl(); } else { iface = impl->getClassInterface(); } - const ObjCMethodDecl *ifaceMD = + const ObjCMethodDecl *ifaceMD = iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); } @@ -1481,11 +1481,11 @@ void Sema::EmitRelatedResultTypeNote(const Expr *E) { const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); if (!MsgSend) return; - + const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); if (!Method) return; - + if (!Method->hasRelatedResultType()) return; @@ -1496,7 +1496,7 @@ void Sema::EmitRelatedResultTypeNote(const Expr *E) { if (!Context.hasSameUnqualifiedType(Method->getReturnType(), Context.getObjCInstanceType())) return; - + Diag(Method->getLocation(), diag::note_related_result_type_inferred) << Method->isInstanceMethod() << Method->getSelector() << MsgSend->getType(); @@ -1560,7 +1560,7 @@ bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, } else Diag(SelLoc, DiagID) - << Sel << isClassMessage << SourceRange(SelectorLocs.front(), + << Sel << isClassMessage << SourceRange(SelectorLocs.front(), SelectorLocs.back()); // Find the class to which we are sending this message. if (ReceiverType->isObjCObjectPointerType()) { @@ -1587,7 +1587,7 @@ bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, return false; } - ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, + ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, isSuperMessage); VK = Expr::getValueKindForType(Method->getReturnType()); @@ -1751,7 +1751,7 @@ ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, return nullptr; } -/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier +/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier /// list of a qualified objective pointer type. ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, @@ -1785,14 +1785,14 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, } IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); - + SourceRange BaseRange = Super? SourceRange(SuperLoc) : BaseExpr->getSourceRange(); - if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), + if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), diag::err_property_not_found_forward_class, MemberName, BaseRange)) return ExprError(); - + if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration( Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { // Check whether we can reference this property. @@ -1832,7 +1832,7 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Selector Sel = PP.getSelectorTable().getNullarySelector(Member); ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); - + // May be found in property's qualified list. if (!Getter) Getter = LookupMethodInQualifiedType(Sel, OPT, true); @@ -1852,17 +1852,17 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, SelectorTable::constructSetterSelector(PP.getIdentifierTable(), PP.getSelectorTable(), Member); ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); - + // May be found in property's qualified list. if (!Setter) Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); - + if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. Setter = IFace->lookupPrivateMethod(SetterSel); } - + if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) return ExprError(); @@ -1926,23 +1926,23 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, } } ObjCInterfaceDecl *ClassDeclared; - if (ObjCIvarDecl *Ivar = + if (ObjCIvarDecl *Ivar = IFace->lookupInstanceVariable(Member, ClassDeclared)) { QualType T = Ivar->getType(); - if (const ObjCObjectPointerType * OBJPT = + if (const ObjCObjectPointerType * OBJPT = T->getAsObjCInterfacePointerType()) { - if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), + if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), diag::err_property_not_as_forward_class, MemberName, BaseExpr)) return ExprError(); } - Diag(MemberLoc, + Diag(MemberLoc, diag::err_ivar_access_using_property_syntax_suggest) << MemberName << QualType(OPT, 0) << Ivar->getDeclName() << FixItHint::CreateReplacement(OpLoc, "->"); return ExprError(); } - + Diag(MemberLoc, diag::err_property_not_found) << MemberName << QualType(OPT, 0); if (Setter) @@ -2086,10 +2086,10 @@ Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, // trailing dot, it's an instance message. if (IsSuper && S->isInObjcMethodScope()) return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; - + LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); LookupName(Result, S); - + switch (Result.getResultKind()) { case LookupResult::NotFound: // Normal name lookup didn't find anything. If we're in an @@ -2103,11 +2103,11 @@ Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, } ObjCInterfaceDecl *ClassDeclared; - if (Method->getClassInterface()->lookupInstanceVariable(Name, + if (Method->getClassInterface()->lookupInstanceVariable(Name, ClassDeclared)) return ObjCInstanceMessage; } - + // Break out; we'll perform typo correction below. break; @@ -2171,7 +2171,7 @@ Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, return ObjCInstanceMessage; } -ExprResult Sema::ActOnSuperMessage(Scope *S, +ExprResult Sema::ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, @@ -2213,7 +2213,7 @@ ExprResult Sema::ActOnSuperMessage(Scope *S, Sel, /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, Args); } - + // Since we are in a class method, this is a class message to // the superclass. return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr, @@ -2353,7 +2353,7 @@ DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S, } if (!Format || NumArgs <= Idx) return; - + Expr *FormatExpr = Args[Idx]; if (ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) { @@ -2401,7 +2401,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, - SourceLocation LBracLoc, + SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg ArgsIn, @@ -2431,7 +2431,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); } - + // Find the class to which we are sending this message. ObjCInterfaceDecl *Class = nullptr; const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); @@ -2446,7 +2446,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs); // Find the method we are messaging. if (!Method) { - SourceRange TypeRange + SourceRange TypeRange = SuperLoc.isValid()? SourceRange(SuperLoc) : ReceiverTypeInfo->getTypeLoc().getSourceRange(); if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), @@ -2455,7 +2455,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, : diag::warn_receiver_forward_class), TypeRange)) { // A forward class used in messaging is treated as a 'Class' - Method = LookupFactoryMethodInGlobalPool(Sel, + Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc)); if (Method && !getLangOpts().ObjCAutoRefCount) Diag(Method->getLocation(), diag::note_method_sent_forward_class) @@ -2490,7 +2490,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, RequireCompleteType(LBracLoc, Method->getReturnType(), diag::err_illegal_message_expr_incomplete_type)) return ExprError(); - + // Warn about explicit call of +initialize on its own class. But not on 'super'. if (Method && Method->getMethodFamily() == OMF_initialize) { if (!SuperLoc.isValid()) { @@ -2513,19 +2513,19 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, } } } - + DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); - + // Construct the appropriate ObjCMessageExpr. ObjCMessageExpr *Result; if (SuperLoc.isValid()) - Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, - SuperLoc, /*IsInstanceSuper=*/false, + Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, + SuperLoc, /*IsInstanceSuper=*/false, ReceiverType, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); else { - Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, + Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, ReceiverTypeInfo, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); @@ -2541,7 +2541,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, // ActOnClassMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). -ExprResult Sema::ActOnClassMessage(Scope *S, +ExprResult Sema::ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, @@ -2556,7 +2556,7 @@ ExprResult Sema::ActOnClassMessage(Scope *S, if (!ReceiverTypeInfo) ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); - return BuildClassMessage(ReceiverTypeInfo, ReceiverType, + return BuildClassMessage(ReceiverTypeInfo, ReceiverType, /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, Args); @@ -2625,7 +2625,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, - SourceLocation LBracLoc, + SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg ArgsIn, @@ -2691,15 +2691,15 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, // do nothing } else if (!getLangOpts().ObjCAutoRefCount && !Context.getObjCIdType().isNull() && - (ReceiverType->isPointerType() || + (ReceiverType->isPointerType() || ReceiverType->isIntegerType())) { // Implicitly convert integers and pointers to 'id' but emit a warning. // But not in ARC. Diag(Loc, diag::warn_bad_receiver_type) - << ReceiverType + << ReceiverType << Receiver->getSourceRange(); if (ReceiverType->isPointerType()) { - Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), + Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), CK_CPointerToObjCPointerCast).get(); } else { // TODO: specialized warning on null receivers? @@ -2828,7 +2828,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, // We allow sending a message to a qualified ID ("id<foo>"), which is ok as // long as one of the protocols implements the selector (if not, warn). // And as long as message is not deprecated/unavailable (warn if it is). - if (const ObjCObjectPointerType *QIdTy + if (const ObjCObjectPointerType *QIdTy = ReceiverType->getAsObjCQualifiedIdType()) { // Search protocols for instance methods. Method = LookupMethodInQualifiedType(Sel, QIdTy, true); @@ -2854,9 +2854,9 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, : SourceRange(SuperLoc))) { if (getLangOpts().ObjCAutoRefCount) return ExprError(); - + forwardClass = OCIType->getInterfaceDecl(); - Diag(Receiver ? Receiver->getLocStart() + Diag(Receiver ? Receiver->getLocStart() : SuperLoc, diag::note_receiver_is_id); Method = nullptr; } else { @@ -2866,7 +2866,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, if (!Method) // Search protocol qualifiers. Method = LookupMethodInQualifiedType(Sel, OCIType, true); - + if (!Method) { // If we have implementations in scope, check "private" methods. Method = ClassDecl->lookupPrivateMethod(Sel); @@ -2975,7 +2975,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, ReceiverType->isObjCQualifiedClassType()); if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), Sel, SelectorLocs, Method, - ClassMessage, SuperLoc.isValid(), + ClassMessage, SuperLoc.isValid(), LBracLoc, RBracLoc, RecRange, ReturnType, VK)) return ExprError(); @@ -2984,7 +2984,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, diag::err_illegal_message_expr_incomplete_type)) return ExprError(); - // In ARC, forbid the user from sending messages to + // In ARC, forbid the user from sending messages to // retain/release/autorelease/dealloc/retainCount explicitly. if (getLangOpts().ObjCAutoRefCount) { ObjCMethodFamily family = @@ -3013,13 +3013,13 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, Diag(SelLoc, diag::err_arc_illegal_explicit_message) << Sel << RecRange; break; - + case OMF_performSelector: if (Method && NumArgs >= 1) { if (const auto *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) { Selector ArgSel = SelExp->getSelector(); - ObjCMethodDecl *SelMethod = + ObjCMethodDecl *SelMethod = LookupInstanceMethodInGlobalPool(ArgSel, SelExp->getSourceRange()); if (!SelMethod) @@ -3036,8 +3036,8 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, case OMF_init: // Issue error, unless ns_returns_not_retained. if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { - // selector names a +1 method - Diag(SelLoc, + // selector names a +1 method + Diag(SelLoc, diag::err_arc_perform_selector_retains); Diag(SelMethod->getLocation(), diag::note_method_declared_at) << SelMethod->getDeclName(); @@ -3047,7 +3047,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, // +0 call. OK. unless ns_returns_retained. if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { // selector names a +1 method - Diag(SelLoc, + Diag(SelLoc, diag::err_arc_perform_selector_retains); Diag(SelMethod->getLocation(), diag::note_method_declared_at) << SelMethod->getDeclName(); @@ -3066,13 +3066,13 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, } DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); - + // Construct the appropriate ObjCMessageExpr instance. ObjCMessageExpr *Result; if (SuperLoc.isValid()) Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, SuperLoc, /*IsInstanceSuper=*/true, - ReceiverType, Sel, SelectorLocs, Method, + ReceiverType, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); else { @@ -3158,7 +3158,7 @@ static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). ExprResult Sema::ActOnInstanceMessage(Scope *S, - Expr *Receiver, + Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, @@ -3173,7 +3173,7 @@ ExprResult Sema::ActOnInstanceMessage(Scope *S, if (Result.isInvalid()) return ExprError(); Receiver = Result.get(); } - + if (RespondsToSelectorSel.isNull()) { IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); @@ -3218,13 +3218,13 @@ static bool isAnyCLike(ARCConversionTypeClass ACTC) { static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { bool isIndirect = false; - + // Ignore an outermost reference type. if (const ReferenceType *ref = type->getAs<ReferenceType>()) { type = ref->getPointeeType(); isIndirect = true; } - + // Drill through pointers and arrays recursively. while (true) { if (const PointerType *ptr = type->getAs<PointerType>()) { @@ -3242,7 +3242,7 @@ static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { } isIndirect = true; } - + if (isIndirect) { if (type->isObjCARCBridgableType()) return ACTC_indirectRetainable; @@ -3322,7 +3322,7 @@ namespace { return ACC_invalid; } - + /// Look through certain implicit and explicit casts. ACCResult VisitCastExpr(CastExpr *e) { switch (e->getCastKind()) { @@ -3428,10 +3428,10 @@ namespace { // Otherwise, don't do anything implicit with an unaudited function. if (!fn->hasAttr<CFAuditedTransferAttr>()) return ACC_invalid; - + // Otherwise, it's +0 unless it follows the create convention. if (ento::coreFoundation::followsCreateRule(fn)) - return Diagnose ? ACC_plusOne + return Diagnose ? ACC_plusOne : ACC_invalid; // ACC_plusOne if we start accepting this return ACC_plusZero; @@ -3458,7 +3458,7 @@ namespace { // return type is CF. if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) return ACC_invalid; - + // If the method is explicitly marked not-retained, it's +0. if (method->hasAttr<CFReturnsNotRetainedAttr>()) return ACC_plusZero; @@ -3517,12 +3517,12 @@ static void addFixitForObjCARCConversion(Sema &S, SourceRange range(NCE->getOperatorLoc(), NCE->getAngleBrackets().getEnd()); SmallString<32> BridgeCall; - + SourceManager &SM = S.getSourceManager(); char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) BridgeCall += ' '; - + BridgeCall += CFBridgeName; DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); } @@ -3623,7 +3623,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, Sema::CheckedConversionKind CCK) { SourceLocation loc = (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); - + if (S.makeUnavailableInSystemHeader(loc, UnavailableAttr::IR_ARCForbiddenConversion)) return; @@ -3637,7 +3637,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) return; - + unsigned srcKind = 0; switch (exprACTC) { case ACTC_none: @@ -3652,7 +3652,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, srcKind = 4; break; } - + // Check whether this could be fixed with a bridge cast. SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin()); SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; @@ -3671,12 +3671,12 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, << castRange << castExpr->getSourceRange(); bool br = S.isKnownName("CFBridgingRelease"); - ACCResult CreateRule = + ACCResult CreateRule = ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); assert(CreateRule != ACC_bottom && "This cast should already be accepted."); if (CreateRule != ACC_plusOne) { - DiagnosticBuilder DiagB = + DiagnosticBuilder DiagB = (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); @@ -3700,7 +3700,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, return; } - + // Bridge from a CF type to an ARC type. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { bool br = S.isKnownName("CFBridgingRetain"); @@ -3712,7 +3712,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, << castType << castRange << castExpr->getSourceRange(); - ACCResult CreateRule = + ACCResult CreateRule = ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); assert(CreateRule != ACC_bottom && "This cast should already be accepted."); if (CreateRule != ACC_plusOne) @@ -3740,7 +3740,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, return; } - + S.Diag(loc, diag::err_arc_mismatched_cast) << !convKindForDiag << srcKind << castExprType << castType @@ -3759,7 +3759,7 @@ static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, HadTheAttribute = true; if (Parm->isStr("id")) return true; - + NamedDecl *Target = nullptr; // Check for an existing type with this name. LookupResult R(S, DeclarationName(Parm), SourceLocation(), @@ -3897,7 +3897,7 @@ void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { HasObjCBridgeMutableAttr, false); if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) return; - + if (HasObjCBridgeAttr) CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, true); @@ -3918,7 +3918,7 @@ void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { HasObjCBridgeMutableAttr, false); if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) return; - + if (HasObjCBridgeAttr) CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, true); @@ -3940,7 +3940,7 @@ void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) { SrcType = Getter->getReturnType(); } } - + ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType); ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType); if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation) @@ -3977,7 +3977,7 @@ bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); if (!ObjCBAttr) return false; - + IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); @@ -4008,7 +4008,7 @@ bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, } return false; } - + // Check for an existing class method with the given selector name. if (CfToNs && CMId) { Selector Sel = Context.Selectors.getUnarySelector(CMId); @@ -4022,7 +4022,7 @@ bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, return false; } } - + // Check for an existing instance method with the given selector name. if (!CfToNs && IMId) { Selector Sel = Context.Selectors.getNullarySelector(IMId); @@ -4049,7 +4049,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); if (!CfToNs && !NsToCf) return false; - + ObjCInterfaceDecl *RelatedClass; ObjCMethodDecl *ClassMethod = nullptr; ObjCMethodDecl *InstanceMethod = nullptr; @@ -4058,7 +4058,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, ClassMethod, InstanceMethod, TDNDecl, CfToNs, Diagnose)) return false; - + if (CfToNs) { // Implicit conversion from CF to ObjC object is needed. if (ClassMethod) { @@ -4075,7 +4075,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); Diag(RelatedClass->getLocStart(), diag::note_declared_at); Diag(TDNDecl->getLocStart(), diag::note_declared_at); - + QualType receiverType = Context.getObjCInterfaceType(RelatedClass); // Argument. Expr *args[] = { SrcExpr }; @@ -4118,7 +4118,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, } Diag(RelatedClass->getLocStart(), diag::note_declared_at); Diag(TDNDecl->getLocStart(), diag::note_declared_at); - + ExprResult msg = BuildInstanceMessageImplicit(SrcExpr, SrcType, InstanceMethod->getLocation(), @@ -4144,7 +4144,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, QualType effCastType = castType; if (const ReferenceType *ref = castType->getAs<ReferenceType>()) effCastType = ref->getPointeeType(); - + ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); if (exprACTC == castACTC) { @@ -4167,7 +4167,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, if (QDT != castType && QDT.getObjCLifetime() != Qualifiers::OCL_None) { if (Diagnose) { - SourceLocation loc = (castRange.isValid() ? castRange.getBegin() + SourceLocation loc = (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); Diag(loc, diag::err_arc_nolifetime_behavior); } @@ -4188,7 +4188,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, // vice-versa). if (castACTC == ACTC_none && castType->isIntegralType(Context)) return ACR_okay; - + // Allow casts between pointers to lifetime types (e.g., __strong id*) // and pointers to void (e.g., cv void *). Casting from void* to lifetime* // must be explicit. @@ -4229,7 +4229,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, if (castACTC == ACTC_retainable && exprACTC == ACTC_none && ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose)) return ACR_error; - + // Do not issue "bridge cast" diagnostic when implicit casting // a retainable object to a CF type parameter belonging to an audited // CF API function. Let caller issue a normal type mismatched diagnostic @@ -4322,9 +4322,9 @@ Expr *Sema::stripARCUnbridgedCast(Expr *e) { bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, QualType exprType) { - QualType canCastType = + QualType canCastType = Context.getCanonicalType(castType).getUnqualifiedType(); - QualType canExprType = + QualType canExprType = Context.getCanonicalType(exprType).getUnqualifiedType(); if (isa<ObjCObjectPointerType>(canCastType) && castType.getObjCLifetime() == Qualifiers::OCL_Weak && @@ -4399,7 +4399,7 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, switch (Kind) { case OBC_Bridge: break; - + case OBC_BridgeRetained: { bool br = isKnownName("CFBridgingRelease"); Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) @@ -4413,14 +4413,14 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) << FromType << br - << FixItHint::CreateReplacement(BridgeKeywordLoc, - br ? "CFBridgingRelease " + << FixItHint::CreateReplacement(BridgeKeywordLoc, + br ? "CFBridgingRelease " : "__bridge_transfer "); Kind = OBC_Bridge; break; } - + case OBC_BridgeTransfer: // We must consume the Objective-C object produced by the cast. MustConsume = true; @@ -4435,14 +4435,14 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, // is very dangerous, so we don't do it. SubExpr = maybeUndoReclaimObject(SubExpr); break; - - case OBC_BridgeRetained: + + case OBC_BridgeRetained: // Produce the object before casting it. SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject, SubExpr, nullptr, VK_RValue); break; - + case OBC_BridgeTransfer: { bool br = isKnownName("CFBridgingRetain"); Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) @@ -4452,14 +4452,14 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, << T << SubExpr->getSourceRange() << Kind; - + Diag(BridgeKeywordLoc, diag::note_arc_bridge) << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) << T << br - << FixItHint::CreateReplacement(BridgeKeywordLoc, + << FixItHint::CreateReplacement(BridgeKeywordLoc, br ? "CFBridgingRetain " : "__bridge_retained"); - + Kind = OBC_Bridge; break; } @@ -4475,13 +4475,13 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, BridgeKeywordLoc, TSInfo, SubExpr); - + if (MustConsume) { Cleanup.setExprNeedsCleanups(true); - Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, + Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, nullptr, VK_RValue); } - + return Result; } @@ -4498,6 +4498,6 @@ ExprResult Sema::ActOnObjCBridgedCast(Scope *S, CheckTollFreeBridgeCast(T, SubExpr); if (!TSInfo) TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); - return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, + return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, SubExpr); } diff --git a/lib/Sema/SemaInit.cpp b/lib/Sema/SemaInit.cpp index 3ee5ec4a4929e..f006a677b6789 100644 --- a/lib/Sema/SemaInit.cpp +++ b/lib/Sema/SemaInit.cpp @@ -191,7 +191,7 @@ static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, if (SL->isPascal()) StrLength--; } - + // [dcl.init.string]p2 if (StrLength > CAT->getSize().getZExtValue()) S.Diag(Str->getLocStart(), @@ -450,7 +450,7 @@ ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef, IsInStd = true; } - if (IsInStd && llvm::StringSwitch<bool>(R->getName()) + if (IsInStd && llvm::StringSwitch<bool>(R->getName()) .Cases("basic_string", "deque", "forward_list", true) .Cases("list", "map", "multimap", "multiset", true) .Cases("priority_queue", "queue", "set", "stack", true) @@ -1578,7 +1578,7 @@ void InitListChecker::CheckVectorType(const InitializedEntity &Entity, T->getVectorKind() == VectorType::NeonPolyVector)) { // The ability to use vector initializer lists is a GNU vector extension // and is unrelated to the NEON intrinsics in arm_neon.h. On little - // endian machines it works fine, however on big endian machines it + // endian machines it works fine, however on big endian machines it // exhibits surprising behaviour: // // uint32x2_t x = {42, 64}; @@ -2225,7 +2225,7 @@ InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, SemaRef.Diag(D->getLocStart(), diag::warn_subobject_initializer_overrides) << SourceRange(D->getLocStart(), DIE->getLocEnd()); - + SemaRef.Diag(ExistingInit->getLocStart(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 @@ -3000,7 +3000,7 @@ DeclarationName InitializedEntity::getName() const { case EK_LambdaCapture: return DeclarationName(Capture.VarID); - + case EK_Result: case EK_StmtExprResult: case EK_Exception: @@ -3653,13 +3653,13 @@ ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, CandidateSet, SuppressUserConversions); else { // C++ [over.match.copy]p1: - // - When initializing a temporary to be bound to the first parameter + // - When initializing a temporary to be bound to the first parameter // of a constructor [for type T] that takes a reference to possibly // cv-qualified T as its first argument, called with a single // argument in the context of direct-initialization, explicit // conversion functions are also considered. // FIXME: What if a constructor template instantiates to such a signature? - bool AllowExplicitConv = AllowExplicit && !CopyInitializing && + bool AllowExplicitConv = AllowExplicit && !CopyInitializing && Args.size() == 1 && hasCopyOrMoveCtorParam(S.Context, Info); S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, @@ -4226,7 +4226,7 @@ static OverloadingResult TryRefInitWithConversionFunction( (void)DerivedToBase; (void)ObjCConversion; (void)ObjCLifetimeConversion; - + // Build the candidate set directly in the initialization sequence // structure, so that it will persist if we fail. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); @@ -4646,7 +4646,7 @@ static void TryReferenceInitializationCore(Sema &S, /*FIXME:InOverloadResolution=*/false, /*CStyle=*/Kind.isCStyleOrFunctionalCast(), /*AllowObjCWritebackConversion=*/false); - + if (ICS.isBad()) { // FIXME: Use the conversion function set stored in ICS to turn // this into an overloading ambiguity diagnostic. However, we need @@ -4787,7 +4787,7 @@ static void TryDefaultInitialization(Sema &S, // To default-initialize an object of type T means: // - if T is an array type, each element is default-initialized; QualType DestType = S.Context.getBaseElementType(Entity.getType()); - + // - if T is a (possibly cv-qualified) class type (Clause 9), the default // constructor for T is called (and the initialization is ill-formed if // T has no accessible default constructor); @@ -5043,11 +5043,11 @@ static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, // If we have a declaration reference, it had better be a local variable. } else if (isa<DeclRefExpr>(e)) { - // set isWeakAccess to true, to mean that there will be an implicit + // set isWeakAccess to true, to mean that there will be an implicit // load which requires a cleanup. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) isWeakAccess = true; - + if (!isAddressOf) return IIK_nonlocal; VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); @@ -5082,7 +5082,7 @@ static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { assert(src->isRValue()); bool isWeakAccess = false; InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); - // If isWeakAccess to true, there will be an implicit + // If isWeakAccess to true, there will be an implicit // load which requires a cleanup. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) S.Cleanup.setExprNeedsCleanups(true); @@ -5124,7 +5124,7 @@ static bool tryObjCWritebackConversion(Sema &S, ArgPointee = ArgArrayType->getElementType(); ArgType = S.Context.getPointerType(ArgPointee); } - + // Handle write-back conversion. QualType ConvertedArgType; if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), @@ -5151,10 +5151,10 @@ static bool tryObjCWritebackConversion(Sema &S, ICS.Standard.First = ICK_Lvalue_To_Rvalue; ResultType = Initializer->getType().getNonLValueExprType(S.Context); } - + Sequence.AddConversionSequenceStep(ICS, ResultType); } - + Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); return true; } @@ -5567,13 +5567,13 @@ void InitializationSequence::InitializeFrom(Sema &S, if (ICS.isStandard() && ICS.Standard.Second == ICK_Writeback_Conversion) { // Objective-C ARC writeback conversion. - + // We should copy unless we're passing to an argument explicitly // marked 'out'. bool ShouldCopy = true; if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); - + // If there was an lvalue adjustment, add it as a separate conversion. if (ICS.Standard.First == ICK_Array_To_Pointer || ICS.Standard.First == ICK_Lvalue_To_Rvalue) { @@ -5584,7 +5584,7 @@ void InitializationSequence::InitializeFrom(Sema &S, LvalueICS.Standard.First = ICS.Standard.First; AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); } - + AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); } else if (ICS.isBad()) { DeclAccessPair dap; @@ -5635,9 +5635,9 @@ getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { if (Entity.getDecl() && isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) return Sema::AA_Sending; - + return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; - + case InitializedEntity::EK_Result: case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. return Sema::AA_Returning; @@ -5743,7 +5743,7 @@ static SourceLocation getInitializationLoc(const InitializedEntity &Entity, case InitializedEntity::EK_LambdaCapture: return Entity.getCaptureLoc(); - + case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_Member: case InitializedEntity::EK_Parameter: @@ -6065,9 +6065,9 @@ PerformConstructorInitialization(Sema &S, ExprResult CurInit((Expr *)nullptr); // C++ [over.match.copy]p1: - // - When initializing a temporary to be bound to the first parameter - // of a constructor that takes a reference to possibly cv-qualified - // T as its first argument, called with a single argument in the + // - When initializing a temporary to be bound to the first parameter + // of a constructor that takes a reference to possibly cv-qualified + // T as its first argument, called with a single argument in the // context of direct-initialization, explicit conversion functions // are also considered. bool AllowExplicitConv = @@ -6322,12 +6322,14 @@ struct IndirectLocalPathEntry { AddressOf, VarInit, LValToRVal, + LifetimeBoundCall, } Kind; Expr *E; - Decl *D = nullptr; + const Decl *D = nullptr; IndirectLocalPathEntry() {} IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} - IndirectLocalPathEntry(EntryKind K, Expr *E, Decl *D) : Kind(K), E(E), D(D) {} + IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) + : Kind(K), E(E), D(D) {} }; using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; @@ -6361,6 +6363,68 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, Expr *Init, LocalVisitor Visit, bool RevisitSubinits); +static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, + Expr *Init, ReferenceKind RK, + LocalVisitor Visit); + +static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { + const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); + if (!TSI) + return false; + for (TypeLoc TL = TSI->getTypeLoc(); + auto ATL = TL.getAsAdjusted<AttributedTypeLoc>(); + TL = ATL.getModifiedLoc()) { + if (ATL.getAttrKind() == AttributedType::attr_lifetimebound) + return true; + } + return false; +} + +static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, + LocalVisitor Visit) { + const FunctionDecl *Callee; + ArrayRef<Expr*> Args; + + if (auto *CE = dyn_cast<CallExpr>(Call)) { + Callee = CE->getDirectCallee(); + Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); + } else { + auto *CCE = cast<CXXConstructExpr>(Call); + Callee = CCE->getConstructor(); + Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); + } + if (!Callee) + return; + + Expr *ObjectArg = nullptr; + if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { + ObjectArg = Args[0]; + Args = Args.slice(1); + } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { + ObjectArg = MCE->getImplicitObjectArgument(); + } + + auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { + Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); + if (Arg->isGLValue()) + visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, + Visit); + else + visitLocalsRetainedByInitializer(Path, Arg, Visit, true); + Path.pop_back(); + }; + + if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) + VisitLifetimeBoundArg(Callee, ObjectArg); + + for (unsigned I = 0, + N = std::min<unsigned>(Callee->getNumParams(), Args.size()); + I != N; ++I) { + if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) + VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); + } +} + /// Visit the locals that would be reachable through a reference bound to the /// glvalue expression \c Init. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, @@ -6420,6 +6484,9 @@ static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, true); } + if (isa<CallExpr>(Init)) + return visitLifetimeBoundArguments(Path, Init, Visit); + switch (Init->getStmtClass()) { case Stmt::DeclRefExprClass: { // If we find the name of a local non-reference parameter, we could have a @@ -6483,21 +6550,90 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, bool RevisitSubinits) { RevertToOldSizeRAII RAII(Path); - // Step into CXXDefaultInitExprs so we can diagnose cases where a - // constructor inherits one as an implicit mem-initializer. - if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { - Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); - Init = DIE->getExpr(); - } + Expr *Old; + do { + Old = Init; - if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) - Init = EWC->getSubExpr(); + // Step into CXXDefaultInitExprs so we can diagnose cases where a + // constructor inherits one as an implicit mem-initializer. + if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { + Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); + Init = DIE->getExpr(); + } - // Dig out the expression which constructs the extended temporary. - Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); + if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) + Init = EWC->getSubExpr(); + + // Dig out the expression which constructs the extended temporary. + Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); - if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) - Init = BTE->getSubExpr(); + if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) + Init = BTE->getSubExpr(); + + Init = Init->IgnoreParens(); + + // Step over value-preserving rvalue casts. + if (auto *CE = dyn_cast<CastExpr>(Init)) { + switch (CE->getCastKind()) { + case CK_LValueToRValue: + // If we can match the lvalue to a const object, we can look at its + // initializer. + Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); + return visitLocalsRetainedByReferenceBinding( + Path, Init, RK_ReferenceBinding, + [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { + if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { + auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); + if (VD && VD->getType().isConstQualified() && VD->getInit() && + !isVarOnPath(Path, VD)) { + Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); + visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true); + } + } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { + if (MTE->getType().isConstQualified()) + visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), + Visit, true); + } + return false; + }); + + // We assume that objects can be retained by pointers cast to integers, + // but not if the integer is cast to floating-point type or to _Complex. + // We assume that casts to 'bool' do not preserve enough information to + // retain a local object. + case CK_NoOp: + case CK_BitCast: + case CK_BaseToDerived: + case CK_DerivedToBase: + case CK_UncheckedDerivedToBase: + case CK_Dynamic: + case CK_ToUnion: + case CK_UserDefinedConversion: + case CK_ConstructorConversion: + case CK_IntegralToPointer: + case CK_PointerToIntegral: + case CK_VectorSplat: + case CK_IntegralCast: + case CK_CPointerToObjCPointerCast: + case CK_BlockPointerToObjCPointerCast: + case CK_AnyPointerToBlockPointerCast: + case CK_AddressSpaceConversion: + break; + + case CK_ArrayToPointerDecay: + // Model array-to-pointer decay as taking the address of the array + // lvalue. + Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); + return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), + RK_ReferenceBinding, Visit); + + default: + return; + } + + Init = CE->getSubExpr(); + } + } while (Old != Init); // C++17 [dcl.init.list]p6: // initializing an initializer_list object from the array extends the @@ -6558,66 +6694,9 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, return; } - // Step over value-preserving rvalue casts. - while (auto *CE = dyn_cast<CastExpr>(Init)) { - switch (CE->getCastKind()) { - case CK_LValueToRValue: - // If we can match the lvalue to a const object, we can look at its - // initializer. - Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); - return visitLocalsRetainedByReferenceBinding( - Path, Init, RK_ReferenceBinding, - [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { - if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { - auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); - if (VD && VD->getType().isConstQualified() && VD->getInit()) { - Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); - visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true); - } - } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { - if (MTE->getType().isConstQualified()) - visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), - Visit, true); - } - return false; - }); - - // We assume that objects can be retained by pointers cast to integers, - // but not if the integer is cast to floating-point type or to _Complex. - // We assume that casts to 'bool' do not preserve enough information to - // retain a local object. - case CK_NoOp: - case CK_BitCast: - case CK_BaseToDerived: - case CK_DerivedToBase: - case CK_UncheckedDerivedToBase: - case CK_Dynamic: - case CK_ToUnion: - case CK_IntegralToPointer: - case CK_PointerToIntegral: - case CK_VectorSplat: - case CK_IntegralCast: - case CK_CPointerToObjCPointerCast: - case CK_BlockPointerToObjCPointerCast: - case CK_AnyPointerToBlockPointerCast: - case CK_AddressSpaceConversion: - break; - - case CK_ArrayToPointerDecay: - // Model array-to-pointer decay as taking the address of the array - // lvalue. - Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); - return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), - RK_ReferenceBinding, Visit); - - default: - return; - } - - Init = CE->getSubExpr(); - } + if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) + return visitLifetimeBoundArguments(Path, Init, Visit); - Init = Init->IgnoreParens(); switch (Init->getStmtClass()) { case Stmt::UnaryOperatorClass: { auto *UO = cast<UnaryOperator>(Init); @@ -6697,6 +6776,7 @@ static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, switch (Path[I].Kind) { case IndirectLocalPathEntry::AddressOf: case IndirectLocalPathEntry::LValToRVal: + case IndirectLocalPathEntry::LifetimeBoundCall: // These exist primarily to mark the path as not permitting or // supporting lifetime extension. break; @@ -6767,8 +6847,9 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, return false; Diag(DiagLoc, diag::warn_dangling_variable) - << RK << !Entity.getParent() << ExtendingEntity->getDecl() - << Init->isGLValue() << DiagRange; + << RK << !Entity.getParent() + << ExtendingEntity->getDecl()->isImplicit() + << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; } break; } @@ -6875,6 +6956,10 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, // supporting lifetime extension. break; + case IndirectLocalPathEntry::LifetimeBoundCall: + // FIXME: Consider adding a note for this. + break; + case IndirectLocalPathEntry::DefaultInit: { auto *FD = cast<FieldDecl>(Elem.D); Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) @@ -6885,7 +6970,8 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, case IndirectLocalPathEntry::VarInit: const VarDecl *VD = cast<VarDecl>(Elem.D); Diag(VD->getLocation(), diag::note_local_var_initializer) - << VD->getType()->isReferenceType() << VD->getDeclName() + << VD->getType()->isReferenceType() + << VD->isImplicit() << VD->getDeclName() << nextPathEntryRange(Path, I + 1, L); break; } @@ -7129,7 +7215,7 @@ InitializationSequence::Perform(Sema &S, Args); } assert(Kind.getKind() == InitializationKind::IK_Copy || - Kind.isExplicitCast() || + Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList); return ExprResult(Args[0]); } @@ -7831,7 +7917,7 @@ InitializationSequence::Perform(Sema &S, // this has already been done when parsing the variable declaration. if (!Init->isConstantInitializer(S.Context, false)) break; - + if (!SourceType->isIntegerType() || 32 != S.Context.getIntWidth(SourceType)) { S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) @@ -7867,7 +7953,7 @@ InitializationSequence::Perform(Sema &S, break; } case SK_OCLZeroEvent: { - assert(Step->Type->isEventT() && + assert(Step->Type->isEventT() && "Event initialization on non-event type."); CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, @@ -8364,7 +8450,7 @@ bool InitializationSequence::Diagnose(Sema &S, llvm_unreachable("Inconsistent overload resolution?"); break; } - + // If this is a defaulted or implicitly-declared function, then // it was implicitly deleted. Make it clear that the deletion was // implicit. diff --git a/lib/Sema/SemaLambda.cpp b/lib/Sema/SemaLambda.cpp index a42b2e827e9bf..440567e032e48 100644 --- a/lib/Sema/SemaLambda.cpp +++ b/lib/Sema/SemaLambda.cpp @@ -25,28 +25,28 @@ using namespace clang; using namespace sema; /// Examines the FunctionScopeInfo stack to determine the nearest -/// enclosing lambda (to the current lambda) that is 'capture-ready' for +/// enclosing lambda (to the current lambda) that is 'capture-ready' for /// the variable referenced in the current lambda (i.e. \p VarToCapture). /// If successful, returns the index into Sema's FunctionScopeInfo stack /// of the capture-ready lambda's LambdaScopeInfo. -/// -/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current +/// +/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current /// lambda - is on top) to determine the index of the nearest enclosing/outer -/// lambda that is ready to capture the \p VarToCapture being referenced in -/// the current lambda. +/// lambda that is ready to capture the \p VarToCapture being referenced in +/// the current lambda. /// As we climb down the stack, we want the index of the first such lambda - -/// that is the lambda with the highest index that is 'capture-ready'. -/// +/// that is the lambda with the highest index that is 'capture-ready'. +/// /// A lambda 'L' is capture-ready for 'V' (var or this) if: /// - its enclosing context is non-dependent /// - and if the chain of lambdas between L and the lambda in which -/// V is potentially used (i.e. the lambda at the top of the scope info +/// V is potentially used (i.e. the lambda at the top of the scope info /// stack), can all capture or have already captured V. /// If \p VarToCapture is 'null' then we are trying to capture 'this'. -/// +/// /// Note that a lambda that is deemed 'capture-ready' still needs to be checked /// for whether it is 'capture-capable' (see -/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly +/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly /// capture. /// /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a @@ -120,7 +120,7 @@ getStackIndexOfNearestEnclosingCaptureReadyLambda( return NoLambdaIsCaptureReady; } EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); - + assert(CurScopeIndex); --CurScopeIndex; } while (!EnclosingDC->isTranslationUnit() && @@ -136,13 +136,13 @@ getStackIndexOfNearestEnclosingCaptureReadyLambda( } /// Examines the FunctionScopeInfo stack to determine the nearest -/// enclosing lambda (to the current lambda) that is 'capture-capable' for +/// enclosing lambda (to the current lambda) that is 'capture-capable' for /// the variable referenced in the current lambda (i.e. \p VarToCapture). /// If successful, returns the index into Sema's FunctionScopeInfo stack /// of the capture-capable lambda's LambdaScopeInfo. /// /// Given the current stack of lambdas being processed by Sema and -/// the variable of interest, to identify the nearest enclosing lambda (to the +/// the variable of interest, to identify the nearest enclosing lambda (to the /// current lambda at the top of the stack) that can truly capture /// a variable, it has to have the following two properties: /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': @@ -175,7 +175,7 @@ Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( VarDecl *VarToCapture, Sema &S) { const Optional<unsigned> NoLambdaIsCaptureCapable; - + const Optional<unsigned> OptionalStackIndex = getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, VarToCapture); @@ -190,7 +190,7 @@ Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); - + // If VarToCapture is null, we are attempting to capture 'this' const bool IsCapturingThis = !VarToCapture; const bool IsCapturingVariable = !IsCapturingThis; @@ -220,7 +220,7 @@ Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( &IndexOfCaptureReadyLambda); if (!CanCaptureThis) return NoLambdaIsCaptureCapable; - } + } return IndexOfCaptureReadyLambda; } @@ -245,18 +245,18 @@ getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, - bool KnownDependent, + bool KnownDependent, LambdaCaptureDefault CaptureDefault) { DeclContext *DC = CurContext; while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) DC = DC->getParent(); bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(), - *this); + *this); // Start constructing the lambda class. CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info, IntroducerRange.getBegin(), - KnownDependent, - IsGenericLambda, + KnownDependent, + IsGenericLambda, CaptureDefault); DC->addDecl(Class); @@ -270,10 +270,10 @@ static bool isInInlineFunction(const DeclContext *DC) { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) if (FD->isInlined()) return true; - + DC = DC->getLexicalParent(); } - + return false; } @@ -379,10 +379,10 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, ArrayRef<ParmVarDecl *> Params, const bool IsConstexprSpecified) { QualType MethodType = MethodTypeInfo->getType(); - TemplateParameterList *TemplateParams = + TemplateParameterList *TemplateParams = getGenericLambdaTemplateParameterList(getCurLambda(), *this); // If a lambda appears in a dependent context or is a generic lambda (has - // template parameters) and has an 'auto' return type, deduce it to a + // template parameters) and has an 'auto' return type, deduce it to a // dependent type. if (Class->isDependentContext() || TemplateParams) { const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); @@ -395,9 +395,9 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, } // C++11 [expr.prim.lambda]p5: - // The closure type for a lambda-expression has a public inline function + // The closure type for a lambda-expression has a public inline function // call operator (13.5.4) whose parameters and return type are described by - // the lambda-expression's parameter-declaration-clause and + // the lambda-expression's parameter-declaration-clause and // trailing-return-type respectively. DeclarationName MethodName = Context.DeclarationNames.getCXXOperatorName(OO_Call); @@ -408,7 +408,7 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, = IntroducerRange.getEnd().getRawEncoding(); CXXMethodDecl *Method = CXXMethodDecl::Create(Context, Class, EndLoc, - DeclarationNameInfo(MethodName, + DeclarationNameInfo(MethodName, IntroducerRange.getBegin(), MethodNameLoc), MethodType, MethodTypeInfo, @@ -417,14 +417,14 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, IsConstexprSpecified, EndLoc); Method->setAccess(AS_public); - + // Temporarily set the lexical declaration context to the current // context, so that the Scope stack matches the lexical nesting. - Method->setLexicalDeclContext(CurContext); + Method->setLexicalDeclContext(CurContext); // Create a function template if we have a template parameter list FunctionTemplateDecl *const TemplateMethod = TemplateParams ? FunctionTemplateDecl::Create(Context, Class, - Method->getLocation(), MethodName, + Method->getLocation(), MethodName, TemplateParams, Method) : nullptr; if (TemplateMethod) { @@ -432,7 +432,7 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, TemplateMethod->setAccess(AS_public); Method->setDescribedFunctionTemplate(TemplateMethod); } - + // Add parameters. if (!Params.empty()) { Method->setParams(Params); @@ -493,16 +493,16 @@ void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { LSI->finishedExplicitCaptures(); } -void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { +void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { // Introduce our parameters into the function scope - for (unsigned p = 0, NumParams = CallOperator->getNumParams(); + for (unsigned p = 0, NumParams = CallOperator->getNumParams(); p < NumParams; ++p) { ParmVarDecl *Param = CallOperator->getParamDecl(p); - + // If this has an identifier, add it to the scope stack. if (CurScope && Param->getIdentifier()) { CheckShadow(CurScope, Param); - + PushOnScopeChains(Param, CurScope); } } @@ -637,7 +637,7 @@ static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { assert(CSI.HasImplicitReturnType); // If it was ever a placeholder, it had to been deduced to DependentTy. - assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); + assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && "lambda expressions use auto deduction in C++14 onwards"); @@ -851,7 +851,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, SmallVector<ParmVarDecl *, 8> Params; if (ParamInfo.getNumTypeObjects() == 0) { // C++11 [expr.prim.lambda]p4: - // If a lambda-expression does not include a lambda-declarator, it is as + // If a lambda-expression does not include a lambda-declarator, it is as // if the lambda-declarator were (). FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( /*IsVariadic=*/false, /*IsCXXMethod=*/true)); @@ -878,8 +878,8 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); // C++11 [expr.prim.lambda]p5: - // This function call operator is declared const (9.3.1) if and only if - // the lambda-expression's parameter-declaration-clause is not followed + // This function call operator is declared const (9.3.1) if and only if + // the lambda-expression's parameter-declaration-clause is not followed // by mutable. It is neither virtual nor declared volatile. [...] if (!FTI.hasMutableQualifier()) FTI.TypeQuals |= DeclSpec::TQ_const; @@ -917,8 +917,8 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, // code_seg attribute on lambda apply to the method. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) Method->addAttr(A); - - // Attributes on the lambda apply to the method. + + // Attributes on the lambda apply to the method. ProcessDeclAttributes(CurScope, Method, ParamInfo); // CUDA lambdas get implicit attributes based on the scope in which they're @@ -928,7 +928,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, // Introduce the function call operator as the current declaration context. PushDeclContext(CurScope, Method); - + // Build the lambda scope. buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc, ExplicitParams, ExplicitResultType, !Method->isConst()); @@ -959,13 +959,13 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; PrevCaptureLoc = C->Loc, ++C) { if (C->Kind == LCK_This || C->Kind == LCK_StarThis) { - if (C->Kind == LCK_StarThis) + if (C->Kind == LCK_StarThis) Diag(C->Loc, !getLangOpts().CPlusPlus17 ? diag::ext_star_this_lambda_capture_cxx17 : diag::warn_cxx14_compat_star_this_lambda_capture); // C++11 [expr.prim.lambda]p8: - // An identifier or this shall not appear more than once in a + // An identifier or this shall not appear more than once in a // lambda-capture. if (LSI->isCXXThisCaptured()) { Diag(C->Loc, diag::err_capture_more_than_once) @@ -993,7 +993,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Diag(C->Loc, diag::err_this_capture) << true; continue; } - + CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true, /*FunctionScopeIndexToStopAtPtr*/ nullptr, C->Kind == LCK_StarThis); @@ -1018,9 +1018,9 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, // If the initializer expression is usable, but the InitCaptureType // is not, then an error has occurred - so ignore the capture for now. // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. - // FIXME: we should create the init capture variable and mark it invalid + // FIXME: we should create the init capture variable and mark it invalid // in this case. - if (C->InitCaptureType.get().isNull()) + if (C->InitCaptureType.get().isNull()) continue; unsigned InitStyle; @@ -1050,7 +1050,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, "init capture has valid but null init?"); // C++11 [expr.prim.lambda]p8: - // If a lambda-capture includes a capture-default that is &, the + // If a lambda-capture includes a capture-default that is &, the // identifiers in the lambda-capture shall not be preceded by &. // If a lambda-capture includes a capture-default that is =, [...] // each identifier it contains shall be preceded by &. @@ -1131,7 +1131,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, } else { Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) << SourceRange(C->Loc); - + // Just ignore the ellipsis. } } else if (Var->isParameterPack()) { @@ -1189,14 +1189,14 @@ QualType Sema::getLambdaConversionFunctionResultType( // The function type inside the pointer type is the same as the call // operator with some tweaks. The calling convention is the default free // function convention, and the type qualifications are lost. - const FunctionProtoType::ExtProtoInfo CallOpExtInfo = - CallOpProto->getExtProtoInfo(); + const FunctionProtoType::ExtProtoInfo CallOpExtInfo = + CallOpProto->getExtProtoInfo(); FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; CallingConv CC = Context.getDefaultCallingConvention( CallOpProto->isVariadic(), /*IsCXXMethod=*/false); InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); InvokerExtInfo.TypeQuals = 0; - assert(InvokerExtInfo.RefQualifier == RQ_None && + assert(InvokerExtInfo.RefQualifier == RQ_None && "Lambda's call operator should not have a reference qualifier"); return Context.getFunctionType(CallOpProto->getReturnType(), CallOpProto->getParamTypes(), InvokerExtInfo); @@ -1227,7 +1227,7 @@ static void addFunctionPointerConversion(Sema &S, /*IsVariadic=*/false, /*IsCXXMethod=*/true)); // The conversion function is always const. ConvExtInfo.TypeQuals = Qualifiers::Const; - QualType ConvTy = + QualType ConvTy = S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo); SourceLocation Loc = IntroducerRange.getBegin(); @@ -1236,8 +1236,8 @@ static void addFunctionPointerConversion(Sema &S, S.Context.getCanonicalType(PtrToFunctionTy)); DeclarationNameLoc ConvNameLoc; // Construct a TypeSourceInfo for the conversion function, and wire - // all the parameters appropriately for the FunctionProtoTypeLoc - // so that everything works during transformation/instantiation of + // all the parameters appropriately for the FunctionProtoTypeLoc + // so that everything works during transformation/instantiation of // generic lambdas. // The main reason for wiring up the parameters of the conversion // function with that of the call operator is so that constructs @@ -1247,46 +1247,46 @@ static void addFunctionPointerConversion(Sema &S, // return a; // }; // }; - // int (*fp)(int) = L(5); + // int (*fp)(int) = L(5); // Because the trailing return type can contain DeclRefExprs that refer - // to the original call operator's variables, we hijack the call + // to the original call operator's variables, we hijack the call // operators ParmVarDecls below. - TypeSourceInfo *ConvNamePtrToFunctionTSI = + TypeSourceInfo *ConvNamePtrToFunctionTSI = S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI; // The conversion function is a conversion to a pointer-to-function. TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); - FunctionProtoTypeLoc ConvTL = + FunctionProtoTypeLoc ConvTL = ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); // Get the result of the conversion function which is a pointer-to-function. - PointerTypeLoc PtrToFunctionTL = + PointerTypeLoc PtrToFunctionTL = ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); // Do the same for the TypeSourceInfo that is used to name the conversion // operator. - PointerTypeLoc ConvNamePtrToFunctionTL = + PointerTypeLoc ConvNamePtrToFunctionTL = ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); - + // Get the underlying function types that the conversion function will // be converting to (should match the type of the call operator). - FunctionProtoTypeLoc CallOpConvTL = + FunctionProtoTypeLoc CallOpConvTL = PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); - FunctionProtoTypeLoc CallOpConvNameTL = + FunctionProtoTypeLoc CallOpConvNameTL = ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); - + // Wire up the FunctionProtoTypeLocs with the call operator's parameters. // These parameter's are essentially used to transform the name and // the type of the conversion operator. By using the same parameters // as the call operator's we don't have to fix any back references that - // the trailing return type of the call operator's uses (such as + // the trailing return type of the call operator's uses (such as // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) - // - we can simply use the return type of the call operator, and - // everything should work. + // - we can simply use the return type of the call operator, and + // everything should work. SmallVector<ParmVarDecl *, 4> InvokerParams; for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { ParmVarDecl *From = CallOperator->getParamDecl(I); - InvokerParams.push_back(ParmVarDecl::Create(S.Context, + InvokerParams.push_back(ParmVarDecl::Create(S.Context, // Temporarily add to the TU. This is set to the invoker below. S.Context.getTranslationUnitDecl(), From->getLocStart(), @@ -1300,14 +1300,14 @@ static void addFunctionPointerConversion(Sema &S, CallOpConvNameTL.setParam(I, From); } - CXXConversionDecl *Conversion - = CXXConversionDecl::Create(S.Context, Class, Loc, - DeclarationNameInfo(ConversionName, + CXXConversionDecl *Conversion + = CXXConversionDecl::Create(S.Context, Class, Loc, + DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), - ConvTy, + ConvTy, ConvTSI, /*isInline=*/true, /*isExplicit=*/false, - /*isConstexpr=*/S.getLangOpts().CPlusPlus17, + /*isConstexpr=*/S.getLangOpts().CPlusPlus17, CallOperator->getBody()->getLocEnd()); Conversion->setAccess(AS_public); Conversion->setImplicit(true); @@ -1315,7 +1315,7 @@ static void addFunctionPointerConversion(Sema &S, if (Class->isGenericLambda()) { // Create a template version of the conversion operator, using the template // parameter list of the function call operator. - FunctionTemplateDecl *TemplateCallOperator = + FunctionTemplateDecl *TemplateCallOperator = CallOperator->getDescribedFunctionTemplate(); FunctionTemplateDecl *ConversionTemplate = FunctionTemplateDecl::Create(S.Context, Class, @@ -1337,19 +1337,19 @@ static void addFunctionPointerConversion(Sema &S, // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc // then rewire the parameters accordingly, by hoisting up the InvokeParams // loop below and then use its Params to set Invoke->setParams(...) below. - // This would avoid the 'const' qualifier of the calloperator from - // contaminating the type of the invoker, which is currently adjusted + // This would avoid the 'const' qualifier of the calloperator from + // contaminating the type of the invoker, which is currently adjusted // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the // trailing return type of the invoker would require a visitor to rebuild // the trailing return type and adjusting all back DeclRefExpr's to refer // to the new static invoker parameters - not the call operator's. CXXMethodDecl *Invoke - = CXXMethodDecl::Create(S.Context, Class, Loc, - DeclarationNameInfo(InvokerName, Loc), + = CXXMethodDecl::Create(S.Context, Class, Loc, + DeclarationNameInfo(InvokerName, Loc), InvokerFunctionTy, - CallOperator->getTypeSourceInfo(), + CallOperator->getTypeSourceInfo(), SC_Static, /*IsInline=*/true, - /*IsConstexpr=*/false, + /*IsConstexpr=*/false, CallOperator->getBody()->getLocEnd()); for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) InvokerParams[I]->setOwningFunction(Invoke); @@ -1357,7 +1357,7 @@ static void addFunctionPointerConversion(Sema &S, Invoke->setAccess(AS_private); Invoke->setImplicit(true); if (Class->isGenericLambda()) { - FunctionTemplateDecl *TemplateCallOperator = + FunctionTemplateDecl *TemplateCallOperator = CallOperator->getDescribedFunctionTemplate(); FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create( S.Context, Class, Loc, InvokerName, @@ -1372,7 +1372,7 @@ static void addFunctionPointerConversion(Sema &S, } /// Add a lambda's conversion to block pointer. -static void addBlockPointerConversion(Sema &S, +static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator) { @@ -1392,13 +1392,13 @@ static void addBlockPointerConversion(Sema &S, S.Context.getCanonicalType(BlockPtrTy)); DeclarationNameLoc NameLoc; NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); - CXXConversionDecl *Conversion - = CXXConversionDecl::Create(S.Context, Class, Loc, + CXXConversionDecl *Conversion + = CXXConversionDecl::Create(S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), - ConvTy, + ConvTy, S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), /*isInline=*/true, /*isExplicit=*/false, - /*isConstexpr=*/false, + /*isConstexpr=*/false, CallOperator->getBody()->getLocEnd()); Conversion->setAccess(AS_public); Conversion->setImplicit(true); @@ -1421,7 +1421,7 @@ static ExprResult performLambdaVarCaptureInitialization(Sema &S, // direct-initialized in increasing subscript order.) These // initializations are performed in the (unspecified) order in // which the non-static data members are declared. - + // C++ [expr.prim.lambda]p12: // An entity captured by a lambda-expression is odr-used (3.2) in // the scope containing the lambda-expression. @@ -1437,8 +1437,8 @@ static ExprResult performLambdaVarCaptureInitialization(Sema &S, InitializationSequence Init(S, Entity, InitKind, Ref); return Init.Perform(S, Entity, InitKind, Ref); } - -ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, + +ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope) { LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); ActOnFinishFunctionBody(LSI.CallOperator, Body); @@ -1531,9 +1531,9 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, IsGenericLambda = Class->isGenericLambda(); CallOperator->setLexicalDeclContext(Class); - Decl *TemplateOrNonTemplateCallOperatorDecl = - CallOperator->getDescribedFunctionTemplate() - ? CallOperator->getDescribedFunctionTemplate() + Decl *TemplateOrNonTemplateCallOperatorDecl = + CallOperator->getDescribedFunctionTemplate() + ? CallOperator->getDescribedFunctionTemplate() : cast<Decl>(CallOperator); TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); @@ -1646,7 +1646,7 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, // FIXME: Fix generic lambda to block conversions. if (getLangOpts().Blocks && getLangOpts().ObjC1 && !IsGenericLambda) addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); - + // Finalize the lambda class. SmallVector<Decl*, 4> Fields(Class->fields()); ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), @@ -1656,9 +1656,9 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, Cleanup.mergeFrom(LambdaCleanup); - LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, + LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, CaptureDefault, CaptureDefaultLoc, - Captures, + Captures, ExplicitParams, ExplicitResultType, CaptureInits, EndLoc, ContainsUnexpandedParameterPack); @@ -1718,7 +1718,7 @@ ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, Expr *Src) { // Make sure that the lambda call operator is marked used. CXXRecordDecl *Lambda = Conv->getParent(); - CXXMethodDecl *CallOperator + CXXMethodDecl *CallOperator = cast<CXXMethodDecl>( Lambda->lookup( Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); @@ -1731,10 +1731,10 @@ ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, CurrentLocation, Src); if (!Init.isInvalid()) Init = ActOnFinishFullExpr(Init.get()); - + if (Init.isInvalid()) return ExprError(); - + // Create the new block to be returned. BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); diff --git a/lib/Sema/SemaLookup.cpp b/lib/Sema/SemaLookup.cpp index 2732112c00b62..0ab70e9dca375 100644 --- a/lib/Sema/SemaLookup.cpp +++ b/lib/Sema/SemaLookup.cpp @@ -1621,7 +1621,7 @@ bool Sema::isVisibleSlow(const NamedDecl *D) { bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) { // FIXME: If there are both visible and hidden declarations, we need to take // into account whether redeclaration is possible. Example: - // + // // Non-imported module: // int f(T); // #1 // Some TU: @@ -1795,7 +1795,7 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { // actually exists in a Scope). while (S && !S->isDeclScope(D)) S = S->getParent(); - + // If the scope containing the declaration is the translation unit, // then we'll need to perform our checks based on the matching // DeclContexts rather than matching scopes. @@ -1806,7 +1806,7 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { DeclContext *DC = nullptr; if (!S) DC = (*I)->getDeclContext()->getRedeclContext(); - + IdentifierResolver::iterator LastI = I; for (++LastI; LastI != IEnd; ++LastI) { if (S) { @@ -1815,7 +1815,7 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { break; } else { // Match based on DeclContext. - DeclContext *LastDC + DeclContext *LastDC = (*LastI)->getDeclContext()->getRedeclContext(); if (!LastDC->Equals(DC)) break; @@ -1843,8 +1843,8 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { if (AllowBuiltinCreation && LookupBuiltin(*this, R)) return true; - // If we didn't find a use of this identifier, the ExternalSource - // may be able to handle the situation. + // If we didn't find a use of this identifier, the ExternalSource + // may be able to handle the situation. // Note: some lookup failures are expected! // See e.g. R.isForRedeclaration(). return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); @@ -2037,11 +2037,11 @@ bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool oldVal; DeclContext *Context; // Set flag in DeclContext informing debugger that we're looking for qualified name - QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) { - oldVal = ctx->setUseQualifiedLookup(); + QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) { + oldVal = ctx->setUseQualifiedLookup(); } - ~QualifiedLookupInScope() { - Context->setUseQualifiedLookup(oldVal); + ~QualifiedLookupInScope() { + Context->setUseQualifiedLookup(oldVal); } } QL(LookupCtx); @@ -2738,7 +2738,7 @@ addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { case Type::DeducedTemplateSpecialization: break; - // If T is an Objective-C object or interface type, or a pointer to an + // If T is an Objective-C object or interface type, or a pointer to an // object or interface type, the associated namespace is the global // namespace. case Type::ObjCObject: @@ -4434,7 +4434,7 @@ static void AddKeywordsToConsumer(Sema &SemaRef, // Add type-specifier keywords to the set of results. static const char *const CTypeSpecs[] = { "char", "const", "double", "enum", "float", "int", "long", "short", - "signed", "struct", "union", "unsigned", "void", "volatile", + "signed", "struct", "union", "unsigned", "void", "volatile", "_Complex", "_Imaginary", // storage-specifiers as well "extern", "inline", "static", "typedef" @@ -4450,7 +4450,7 @@ static void AddKeywordsToConsumer(Sema &SemaRef, Consumer.addKeywordResult("bool"); else if (SemaRef.getLangOpts().C99) Consumer.addKeywordResult("_Bool"); - + if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("class"); Consumer.addKeywordResult("typename"); diff --git a/lib/Sema/SemaObjCProperty.cpp b/lib/Sema/SemaObjCProperty.cpp index 2983ec51f49ef..3e55cf003fced 100644 --- a/lib/Sema/SemaObjCProperty.cpp +++ b/lib/Sema/SemaObjCProperty.cpp @@ -307,15 +307,15 @@ makePropertyAttributesAsWritten(unsigned Attributes) { attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic; if (Attributes & ObjCDeclSpec::DQ_PR_class) attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_class; - + return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten; } -static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, +static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, SourceLocation LParenLoc, SourceLocation &Loc) { if (LParenLoc.isMacroID()) return false; - + SourceManager &SM = Context.getSourceManager(); std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc); // Try to load the file buffer. @@ -324,7 +324,7 @@ static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, if (invalidTemp) return false; const char *tokenBegin = file.data() + locInfo.second; - + // Lex from the start of the given location. Lexer lexer(SM.getLocForStartOfFile(locInfo.first), Context.getLangOpts(), @@ -365,7 +365,7 @@ static void checkAtomicPropertyMismatch(Sema &S, if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic) return false; // Was 'atomic' specified directly? - if (Property->getPropertyAttributesAsWritten() & + if (Property->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_atomic) return false; @@ -382,7 +382,7 @@ static void checkAtomicPropertyMismatch(Sema &S, Attrs = Attrs & ~AtomicityMask; if (OldIsAtomic) Attrs |= ObjCPropertyDecl::OBJC_PR_atomic; - else + else Attrs |= ObjCPropertyDecl::OBJC_PR_nonatomic; NewProperty->overwritePropertyAttributes(Attrs); @@ -429,7 +429,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, DeclContext *DC = CurContext; IdentifierInfo *PropertyId = FD.D.getIdentifier(); ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface(); - + // We need to look in the @interface to see if the @property was // already declared. if (!CCPrimary) { @@ -445,7 +445,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, ObjCPropertyDecl *PIDecl = CCPrimary->FindPropertyVisibleInPrimaryClass( PropertyId, ObjCPropertyDecl::getQueryKind(isClassProperty)); - // If we found a property in an extension, complain. + // If we found a property in an extension, complain. if (PIDecl && isa<ObjCCategoryDecl>(PIDecl->getDeclContext())) { Diag(AtLoc, diag::err_duplicate_property); Diag(PIDecl->getLocation(), diag::note_property_declare); @@ -482,7 +482,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, << PIDecl->getGetterName() << GetterSel; Diag(PIDecl->getLocation(), diag::note_property_declare); } - + // Always adopt the getter from the original declaration. GetterSel = PIDecl->getGetterName(); Attributes |= ObjCDeclSpec::DQ_PR_getter; @@ -503,7 +503,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, Attributes = (Attributes & ~OwnershipMask) | ExistingOwnership; } - // If the redeclaration is 'weak' but the original property is not, + // If the redeclaration is 'weak' but the original property is not, if ((Attributes & ObjCPropertyDecl::OBJC_PR_weak) && !(PIDecl->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_weak) && @@ -511,7 +511,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, PIDecl->getType().getObjCLifetime() == Qualifiers::OCL_None) { Diag(AtLoc, diag::warn_property_implicitly_mismatched); Diag(PIDecl->getLocation(), diag::note_property_declare); - } + } } // Create a new ObjCPropertyDecl with the DeclContext being @@ -546,13 +546,13 @@ Sema::HandlePropertyInClassExtension(Scope *S, (!isObjCPointerConversion(ClassExtPropertyT, PrimaryClassPropertyT, ConvertedType, IncompatibleObjC)) || IncompatibleObjC) { - Diag(AtLoc, + Diag(AtLoc, diag::err_type_mismatch_continuation_class) << PDecl->getType(); Diag(PIDecl->getLocation(), diag::note_property_declare); return nullptr; } } - + // Check that atomicity of property in class extension matches the previous // declaration. checkAtomicPropertyMismatch(*this, PIDecl, PDecl, true); @@ -621,7 +621,7 @@ ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S, DeclContext *DC = CDecl; ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(), - PropertyId, AtLoc, + PropertyId, AtLoc, LParenLoc, T, TInfo); bool isClassProperty = (AttributesAsWritten & ObjCDeclSpec::DQ_PR_class) || @@ -770,7 +770,7 @@ static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc, S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership) << property->getDeclName() << ivar->getDeclName() - << ((property->getPropertyAttributesAsWritten() + << ((property->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_assign) != 0); break; @@ -794,12 +794,12 @@ static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc, /// life-time is assumed 'strong'. static void setImpliedPropertyAttributeForReadOnlyProperty( ObjCPropertyDecl *property, ObjCIvarDecl *ivar) { - Qualifiers::ObjCLifetime propertyLifetime = + Qualifiers::ObjCLifetime propertyLifetime = getImpliedARCOwnership(property->getPropertyAttributes(), property->getType()); if (propertyLifetime != Qualifiers::OCL_None) return; - + if (!ivar) { // if no backing ivar, make property 'strong'. property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); @@ -1094,7 +1094,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property); Diag(property->getLocation(), diag::note_property_declare); } - + if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) { if (!CD->IsClassExtension()) { @@ -1121,17 +1121,17 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } } } - + if (!ReadWriteProperty) { Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property) << property; SourceLocation readonlyLoc; - if (LocPropertyAttribute(Context, "readonly", + if (LocPropertyAttribute(Context, "readonly", property->getLParenLoc(), readonlyLoc)) { - SourceLocation endLoc = + SourceLocation endLoc = readonlyLoc.getLocWithOffset(strlen("readonly")-1); SourceRange ReadonlySourceRange(readonlyLoc, endLoc); - Diag(property->getLocation(), + Diag(property->getLocation(), diag::note_auto_readonly_iboutlet_fixup_suggest) << FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite"); } @@ -1194,10 +1194,10 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, (property->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_readonly) && PropertyIvarType->isObjCRetainableType()) { - setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar); + setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar); } - - ObjCPropertyDecl::PropertyAttributeKind kind + + ObjCPropertyDecl::PropertyAttributeKind kind = property->getPropertyAttributes(); bool isARCWeak = false; @@ -1244,16 +1244,16 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } if (AtLoc.isInvalid()) { - // Check when default synthesizing a property that there is + // Check when default synthesizing a property that there is // an ivar matching property name and issue warning; since this // is the most common case of not using an ivar used for backing // property in non-default synthesis case. ObjCInterfaceDecl *ClassDeclared=nullptr; - ObjCIvarDecl *originalIvar = - IDecl->lookupInstanceVariable(property->getIdentifier(), + ObjCIvarDecl *originalIvar = + IDecl->lookupInstanceVariable(property->getIdentifier(), ClassDeclared); if (originalIvar) { - Diag(PropertyDiagLoc, + Diag(PropertyDiagLoc, diag::warn_autosynthesis_property_ivar_match) << PropertyId << (Ivar == nullptr) << PropertyIvar << originalIvar->getIdentifier(); @@ -1261,7 +1261,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Diag(originalIvar->getLocation(), diag::note_ivar_decl); } } - + if (!Ivar) { // In ARC, give the ivar a lifetime qualifier based on the // property attributes. @@ -1280,10 +1280,10 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Qualifiers::ObjCLifetime lifetime = getImpliedARCOwnership(kind, PropertyIvarType); assert(lifetime && "no lifetime for property?"); - + Qualifiers qs; qs.addObjCLifetime(lifetime); - PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs); + PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs); } } @@ -1333,7 +1333,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, // Check that type of property and its ivar are type compatible. if (!Context.hasSameType(PropertyIvarType, IvarType)) { - if (isa<ObjCObjectPointerType>(PropertyIvarType) + if (isa<ObjCObjectPointerType>(PropertyIvarType) && isa<ObjCObjectPointerType>(IvarType)) compat = Context.canAssignObjCInterfaces( @@ -1390,7 +1390,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } else if (PropertyIvar) // @dynamic Diag(PropertyDiagLoc, diag::err_dynamic_property_ivar_decl); - + assert (property && "ActOnPropertyImplDecl - property declaration missing"); ObjCPropertyImplDecl *PIDecl = ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc, @@ -1412,7 +1412,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, // FIXME. Eventually we want to do this for Objective-C as well. SynthesizedFunctionScope Scope(*this, getterMethod); ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl(); - DeclRefExpr *SelfExpr = + DeclRefExpr *SelfExpr = new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(), VK_LValue, PropertyDiagLoc); MarkDeclRefReferenced(SelfExpr); @@ -1440,7 +1440,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } if (property->hasAttr<NSReturnsNotRetainedAttr>() && !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) { - Diag(getterMethod->getLocation(), + Diag(getterMethod->getLocation(), diag::warn_property_getter_owning_mismatch); Diag(property->getLocation(), diag::note_property_declare); } @@ -1464,7 +1464,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, // FIXME. Eventually we want to do this for Objective-C as well. SynthesizedFunctionScope Scope(*this, setterMethod); ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl(); - DeclRefExpr *SelfExpr = + DeclRefExpr *SelfExpr = new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(), VK_LValue, PropertyDiagLoc); MarkDeclRefReferenced(SelfExpr); @@ -1484,27 +1484,27 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T, VK_LValue, PropertyDiagLoc); MarkDeclRefReferenced(rhs); - ExprResult Res = BuildBinOp(S, PropertyDiagLoc, + ExprResult Res = BuildBinOp(S, PropertyDiagLoc, BO_Assign, lhs, rhs); - if (property->getPropertyAttributes() & + if (property->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic) { Expr *callExpr = Res.getAs<Expr>(); - if (const CXXOperatorCallExpr *CXXCE = + if (const CXXOperatorCallExpr *CXXCE = dyn_cast_or_null<CXXOperatorCallExpr>(callExpr)) if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee()) if (!FuncDecl->isTrivial()) if (property->getType()->isReferenceType()) { - Diag(PropertyDiagLoc, + Diag(PropertyDiagLoc, diag::err_atomic_property_nontrivial_assign_op) << property->getType(); - Diag(FuncDecl->getLocStart(), + Diag(FuncDecl->getLocStart(), diag::note_callee_decl) << FuncDecl; } } PIDecl->setSetterCXXAssignment(Res.getAs<Expr>()); } } - + if (IC) { if (Synthesize) if (ObjCPropertyImplDecl *PPIDecl = @@ -1537,9 +1537,9 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared); } // Issue diagnostics only if Ivar belongs to current class. - if (Ivar && Ivar->getSynthesize() && + if (Ivar && Ivar->getSynthesize() && declaresSameEntity(IC->getClassInterface(), ClassDeclared)) { - Diag(Ivar->getLocation(), diag::err_undeclared_var_use) + Diag(Ivar->getLocation(), diag::err_undeclared_var_use) << PropertyId; Ivar->setInvalidDecl(); } @@ -1582,7 +1582,7 @@ Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, Property->getPropertyAttributes(); ObjCPropertyDecl::PropertyAttributeKind SAttr = SuperProperty->getPropertyAttributes(); - + // We allow readonly properties without an explicit ownership // (assign/unsafe_unretained/weak/retain/strong/copy) in super class // to be overridden by a property with any explicit ownership in the subclass. @@ -1642,7 +1642,7 @@ Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, // FIXME. For future support of covariant property types, revisit this. bool IncompatibleObjC = false; QualType ConvertedType; - if (!isObjCPointerConversion(RHSType, LHSType, + if (!isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC) || IncompatibleObjC) { Diag(Property->getLocation(), diag::warn_property_types_are_incompatible) @@ -1683,7 +1683,7 @@ bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property, compat = false; } } - + if (!compat) { Diag(Loc, diag::warn_accessor_property_type_mismatch) << property->getDeclName() @@ -1744,9 +1744,9 @@ CollectImmediateProperties(ObjCContainerDecl *CDecl, ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())]; - // Exclude property for protocols which conform to class's super-class, + // Exclude property for protocols which conform to class's super-class, // as super-class has to implement the property. - if (!PropertyFromSuper || + if (!PropertyFromSuper || PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) { ObjCPropertyDecl *&PropEntry = PropMap[std::make_pair(Prop->getIdentifier(), @@ -1788,7 +1788,7 @@ Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, Method->isInstanceMethod()); if (!IMD || !IMD->isPropertyAccessor()) return false; - + // look up a property declaration whose one of its accessors is implemented // by this method. for (const auto *Property : IFace->instance_properties()) { @@ -1841,7 +1841,7 @@ void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, return; ObjCInterfaceDecl::PropertyMap SuperPropMap; CollectSuperClassPropertyImplementations(IDecl, SuperPropMap); - + for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) { ObjCPropertyDecl *Prop = PropertyOrder[i]; // Is there a matching property synthesize/dynamic? @@ -1997,7 +1997,7 @@ void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, } if (IDecl) CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap); - + // When SynthesizeProperties is true, we only check class properties. CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap, SynthesizeProperties/*CollectClassPropsOnly*/); @@ -2048,7 +2048,7 @@ void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, // Collect property accessors implemented in current implementation. for (const auto *I : IMPDecl->methods()) InsMap.insert(I); - + ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); ObjCInterfaceDecl *PrimaryClass = nullptr; if (C && !C->IsClassExtension()) @@ -2121,7 +2121,7 @@ Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl, for (const auto *Ext : IDecl->known_extensions()) for (auto *Prop : Ext->properties()) PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; - + for (ObjCContainerDecl::PropertyMap::iterator I = PM.begin(), E = PM.end(); I != E; ++I) { const ObjCPropertyDecl *Property = I->second; @@ -2191,7 +2191,7 @@ Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl, << FixItHint::CreateInsertion(AfterLParen, NonatomicStr); } else if (Property->getLParenLoc().isInvalid()) { //@property id etc. - SourceLocation startLoc = + SourceLocation startLoc = Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) @@ -2301,8 +2301,8 @@ static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod, ObjCPropertyDecl *Property) { // Should we just clone all attributes over? for (const auto *A : Property->attrs()) { - if (isa<DeprecatedAttr>(A) || - isa<UnavailableAttr>(A) || + if (isa<DeprecatedAttr>(A) || + isa<UnavailableAttr>(A) || isa<AvailabilityAttr>(A)) PropertyMethod->addAttr(A->clone(S.Context)); } @@ -2332,7 +2332,7 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { getClassMethod(property->getGetterName()) : CatDecl->getClassInterface()-> getInstanceMethod(property->getGetterName()); - + SetterMethod = IsClassProperty ? CD->getClassMethod(property->getSetterName()) : CD->getInstanceMethod(property->getSetterName()); @@ -2352,7 +2352,7 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { Diag(SetterMethod->getLocation(), diag::err_setter_type_void); if (SetterMethod->param_size() != 1 || !Context.hasSameUnqualifiedType( - (*SetterMethod->param_begin())->getType().getNonReferenceType(), + (*SetterMethod->param_begin())->getType().getNonReferenceType(), property->getType().getNonReferenceType())) { Diag(property->getLocation(), diag::warn_accessor_property_type_mismatch) @@ -2406,11 +2406,11 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { if (property->hasAttr<NSReturnsNotRetainedAttr>()) GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context, Loc)); - + if (property->hasAttr<ObjCReturnsInnerPointerAttr>()) GetterMethod->addAttr( ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc)); - + if (const SectionAttr *SA = property->getAttr<SectionAttr>()) GetterMethod->addAttr( SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section, @@ -2535,12 +2535,12 @@ void Sema::CheckObjCPropertyAttributes(Decl *PDecl, // FIXME: Improve the reported location. if (!PDecl || PDecl->isInvalidDecl()) return; - + if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "readonly" << "readwrite"; - + ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl); QualType PropertyTy = PropertyDecl->getType(); @@ -2656,19 +2656,19 @@ void Sema::CheckObjCPropertyAttributes(Decl *PDecl, if (Attributes & ObjCDeclSpec::DQ_PR_readonly) { // do nothing } else if (getLangOpts().ObjCAutoRefCount) { - // With arc, @property definitions should default to strong when + // With arc, @property definitions should default to strong when // not specified. PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); } else if (PropertyTy->isObjCObjectPointerType()) { - bool isAnyClassTy = - (PropertyTy->isObjCClassType() || + bool isAnyClassTy = + (PropertyTy->isObjCClassType() || PropertyTy->isObjCQualifiedClassType()); // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to // issue any warning. if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC) ; else if (propertyInPrimaryClass) { - // Don't issue warning on property with no life time in class + // Don't issue warning on property with no life time in class // extension as it is inherited from property in primary class. // Skip this warning in gc-only mode. if (getLangOpts().getGC() != LangOptions::GCOnly) @@ -2696,7 +2696,7 @@ void Sema::CheckObjCPropertyAttributes(Decl *PDecl, !(Attributes & ObjCDeclSpec::DQ_PR_strong) && PropertyTy->isBlockPointerType()) Diag(Loc, diag::warn_objc_property_retain_of_block); - + if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && (Attributes & ObjCDeclSpec::DQ_PR_setter)) Diag(Loc, diag::warn_objc_readonly_property_has_setter); diff --git a/lib/Sema/SemaPseudoObject.cpp b/lib/Sema/SemaPseudoObject.cpp index 4484e9b3513b8..a8af75d87c8d4 100644 --- a/lib/Sema/SemaPseudoObject.cpp +++ b/lib/Sema/SemaPseudoObject.cpp @@ -316,10 +316,10 @@ namespace { OpaqueValueExpr *InstanceKey; ObjCMethodDecl *AtIndexGetter; Selector AtIndexGetterSelector; - + ObjCMethodDecl *AtIndexSetter; Selector AtIndexSetterSelector; - + public: ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr, bool IsUnique) : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique), @@ -367,7 +367,7 @@ namespace { /// Capture the given expression in an OpaqueValueExpr. OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) { // Make a new OVE whose source is the given expression. - OpaqueValueExpr *captured = + OpaqueValueExpr *captured = new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(), e->getValueKind(), e->getObjectKind(), e); @@ -389,7 +389,7 @@ OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) { assert(ResultIndex == PseudoObjectExpr::NoResult); // If the expression hasn't already been captured, just capture it - // and set the new semantic + // and set the new semantic if (!isa<OpaqueValueExpr>(e)) { OpaqueValueExpr *cap = capture(e); setResultToLastSemantic(); @@ -618,11 +618,11 @@ bool ObjCPropertyOpBuilder::findGetter() { // Must build the getter selector the hard way. ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter(); assert(setter && "both setter and getter are null - cannot happen"); - IdentifierInfo *setterName = + IdentifierInfo *setterName = setter->getSelector().getIdentifierInfoForSlot(0); IdentifierInfo *getterName = &S.Context.Idents.get(setterName->getName().substr(3)); - GetterSelector = + GetterSelector = S.PP.getSelectorTable().getNullarySelector(getterName); return false; } @@ -636,7 +636,7 @@ bool ObjCPropertyOpBuilder::findGetter() { /// Try to find the most accurate setter declaration for the property /// reference. /// -/// \return true if a setter was found, in which case Setter +/// \return true if a setter was found, in which case Setter bool ObjCPropertyOpBuilder::findSetter(bool warn) { // For implicit properties, just trust the lookup we already did. if (RefExpr->isImplicitProperty()) { @@ -987,9 +987,9 @@ ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) { // ObjCSubscript build stuff. // -/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue +/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue /// conversion. -/// FIXME. Remove this routine if it is proven that no additional +/// FIXME. Remove this routine if it is proven that no additional /// specifity is needed. ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) { ExprResult result = PseudoOpBuilder::buildRValueOperation(op); @@ -1007,21 +1007,21 @@ ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc, // There must be a method to do the Index'ed assignment. if (!findAtIndexSetter()) return ExprError(); - + // Verify that we can do a compound assignment. if (opcode != BO_Assign && !findAtIndexGetter()) return ExprError(); - + ExprResult result = PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS); if (result.isInvalid()) return ExprError(); - + // Various warnings about objc Index'ed assignments in ARC. if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) { S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS); S.checkUnsafeExprAssigns(opcLoc, LHS, RHS); } - + return result; } @@ -1049,15 +1049,15 @@ Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { return syntacticBase; } -/// CheckSubscriptingKind - This routine decide what type +/// CheckSubscriptingKind - This routine decide what type /// of indexing represented by "FromE" is being done. -Sema::ObjCSubscriptKind +Sema::ObjCSubscriptKind Sema::CheckSubscriptingKind(Expr *FromE) { // If the expression already has integral or enumeration type, we're golden. QualType T = FromE->getType(); if (T->isIntegralOrEnumerationType()) return OS_Array; - + // If we don't have a class type in C++, there's no way we can get an // expression of integral or enumeration type. const RecordType *RecordTy = T->getAs<RecordType>(); @@ -1066,7 +1066,7 @@ Sema::ObjCSubscriptKind // All other scalar cases are assumed to be dictionary indexing which // caller handles, with diagnostics if needed. return OS_Dictionary; - if (!getLangOpts().CPlusPlus || + if (!getLangOpts().CPlusPlus || !RecordTy || RecordTy->isIncompleteType()) { // No indexing can be done. Issue diagnostics and quit. const Expr *IndexExpr = FromE->IgnoreParenImpCasts(); @@ -1078,12 +1078,12 @@ Sema::ObjCSubscriptKind << T; return OS_Error; } - + // We must have a complete class type. - if (RequireCompleteType(FromE->getExprLoc(), T, + if (RequireCompleteType(FromE->getExprLoc(), T, diag::err_objc_index_incomplete_class_type, FromE)) return OS_Error; - + // Look for a conversion to an integral, enumeration type, or // objective-C pointer type. int NoIntegrals=0, NoObjCIdPointers=0; @@ -1125,17 +1125,17 @@ Sema::ObjCSubscriptKind /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF /// objects used as dictionary subscript key objects. -static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, +static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, Expr *Key) { if (ContainerT.isNull()) return; // dictionary subscripting. // - (id)objectForKeyedSubscript:(id)key; IdentifierInfo *KeyIdents[] = { - &S.Context.Idents.get("objectForKeyedSubscript") + &S.Context.Idents.get("objectForKeyedSubscript") }; Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); - ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, + ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, true /*instance*/); if (!Getter) return; @@ -1147,25 +1147,25 @@ static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, bool ObjCSubscriptOpBuilder::findAtIndexGetter() { if (AtIndexGetter) return true; - + Expr *BaseExpr = RefExpr->getBaseExpr(); QualType BaseT = BaseExpr->getType(); - + QualType ResultType; if (const ObjCObjectPointerType *PTy = BaseT->getAs<ObjCObjectPointerType>()) { ResultType = PTy->getPointeeType(); } - Sema::ObjCSubscriptKind Res = + Sema::ObjCSubscriptKind Res = S.CheckSubscriptingKind(RefExpr->getKeyExpr()); if (Res == Sema::OS_Error) { if (S.getLangOpts().ObjCAutoRefCount) - CheckKeyForObjCARCConversion(S, ResultType, + CheckKeyForObjCARCConversion(S, ResultType, RefExpr->getKeyExpr()); return false; } bool arrayRef = (Res == Sema::OS_Array); - + if (ResultType.isNull()) { S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) << BaseExpr->getType() << arrayRef; @@ -1175,24 +1175,24 @@ bool ObjCSubscriptOpBuilder::findAtIndexGetter() { // dictionary subscripting. // - (id)objectForKeyedSubscript:(id)key; IdentifierInfo *KeyIdents[] = { - &S.Context.Idents.get("objectForKeyedSubscript") + &S.Context.Idents.get("objectForKeyedSubscript") }; AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); } else { // - (id)objectAtIndexedSubscript:(size_t)index; IdentifierInfo *KeyIdents[] = { - &S.Context.Idents.get("objectAtIndexedSubscript") + &S.Context.Idents.get("objectAtIndexedSubscript") }; - + AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); } - - AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, + + AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, true /*instance*/); - + if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) { - AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), + AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceLocation(), AtIndexGetterSelector, S.Context.getObjCIdType() /*ReturnType*/, nullptr /*TypeSourceInfo */, @@ -1220,20 +1220,20 @@ bool ObjCSubscriptOpBuilder::findAtIndexGetter() { << BaseExpr->getType() << 0 << arrayRef; return false; } - AtIndexGetter = - S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, - RefExpr->getSourceRange(), + AtIndexGetter = + S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, + RefExpr->getSourceRange(), true); } - + if (AtIndexGetter) { QualType T = AtIndexGetter->parameters()[0]->getType(); if ((arrayRef && !T->isIntegralOrEnumerationType()) || (!arrayRef && !T->isObjCObjectPointerType())) { - S.Diag(RefExpr->getKeyExpr()->getExprLoc(), + S.Diag(RefExpr->getKeyExpr()->getExprLoc(), arrayRef ? diag::err_objc_subscript_index_type : diag::err_objc_subscript_key_type) << T; - S.Diag(AtIndexGetter->parameters()[0]->getLocation(), + S.Diag(AtIndexGetter->parameters()[0]->getLocation(), diag::note_parameter_type) << T; return false; } @@ -1251,32 +1251,32 @@ bool ObjCSubscriptOpBuilder::findAtIndexGetter() { bool ObjCSubscriptOpBuilder::findAtIndexSetter() { if (AtIndexSetter) return true; - + Expr *BaseExpr = RefExpr->getBaseExpr(); QualType BaseT = BaseExpr->getType(); - + QualType ResultType; if (const ObjCObjectPointerType *PTy = BaseT->getAs<ObjCObjectPointerType>()) { ResultType = PTy->getPointeeType(); } - - Sema::ObjCSubscriptKind Res = + + Sema::ObjCSubscriptKind Res = S.CheckSubscriptingKind(RefExpr->getKeyExpr()); if (Res == Sema::OS_Error) { if (S.getLangOpts().ObjCAutoRefCount) - CheckKeyForObjCARCConversion(S, ResultType, + CheckKeyForObjCARCConversion(S, ResultType, RefExpr->getKeyExpr()); return false; } bool arrayRef = (Res == Sema::OS_Array); - + if (ResultType.isNull()) { S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) << BaseExpr->getType() << arrayRef; return false; } - + if (!arrayRef) { // dictionary subscripting. // - (void)setObject:(id)object forKeyedSubscript:(id)key; @@ -1294,7 +1294,7 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { }; AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents); } - AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, + AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, true /*instance*/); if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) { @@ -1328,35 +1328,35 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { Params.push_back(key); AtIndexSetter->setMethodParams(S.Context, Params, None); } - + if (!AtIndexSetter) { if (!BaseT->isObjCIdType()) { - S.Diag(BaseExpr->getExprLoc(), + S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found) << BaseExpr->getType() << 1 << arrayRef; return false; } - AtIndexSetter = - S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, - RefExpr->getSourceRange(), + AtIndexSetter = + S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, + RefExpr->getSourceRange(), true); } - + bool err = false; if (AtIndexSetter && arrayRef) { QualType T = AtIndexSetter->parameters()[1]->getType(); if (!T->isIntegralOrEnumerationType()) { - S.Diag(RefExpr->getKeyExpr()->getExprLoc(), + S.Diag(RefExpr->getKeyExpr()->getExprLoc(), diag::err_objc_subscript_index_type) << T; - S.Diag(AtIndexSetter->parameters()[1]->getLocation(), + S.Diag(AtIndexSetter->parameters()[1]->getLocation(), diag::note_parameter_type) << T; err = true; } T = AtIndexSetter->parameters()[0]->getType(); if (!T->isObjCObjectPointerType()) { - S.Diag(RefExpr->getBaseExpr()->getExprLoc(), + S.Diag(RefExpr->getBaseExpr()->getExprLoc(), diag::err_objc_subscript_object_type) << T << arrayRef; - S.Diag(AtIndexSetter->parameters()[0]->getLocation(), + S.Diag(AtIndexSetter->parameters()[0]->getLocation(), diag::note_parameter_type) << T; err = true; } @@ -1371,7 +1371,7 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { else S.Diag(RefExpr->getBaseExpr()->getExprLoc(), diag::err_objc_subscript_dic_object_type) << T; - S.Diag(AtIndexSetter->parameters()[i]->getLocation(), + S.Diag(AtIndexSetter->parameters()[i]->getLocation(), diag::note_parameter_type) << T; err = true; } @@ -1385,13 +1385,13 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { ExprResult ObjCSubscriptOpBuilder::buildGet() { if (!findAtIndexGetter()) return ExprError(); - + QualType receiverType = InstanceBase->getType(); - + // Build a message-send. ExprResult msg; Expr *Index = InstanceKey; - + // Arguments. Expr *args[] = { Index }; assert(InstanceBase); @@ -1417,17 +1417,17 @@ ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc); QualType receiverType = InstanceBase->getType(); Expr *Index = InstanceKey; - + // Arguments. Expr *args[] = { op, Index }; - + // Build a message-send. ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType, GenericLoc, AtIndexSetterSelector, AtIndexSetter, MultiExprArg(args, 2)); - + if (!msg.isInvalid() && captureSetValueAsResult) { ObjCMessageExpr *msgExpr = cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit()); @@ -1435,7 +1435,7 @@ ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, if (CanCaptureValue(arg)) msgExpr->setArg(0, captureValueAsResult(arg)); } - + return msg; } diff --git a/lib/Sema/SemaStmt.cpp b/lib/Sema/SemaStmt.cpp index b2f9783d44f1b..377e2c4dfa23f 100644 --- a/lib/Sema/SemaStmt.cpp +++ b/lib/Sema/SemaStmt.cpp @@ -216,7 +216,7 @@ void Sema::DiagnoseUnusedExprResult(const Stmt *S) { // expression is a call to a function with the warn_unused_result attribute, // we warn no matter the location. Because of the order in which the various // checks need to happen, we factor out the macro-related test here. - bool ShouldSuppress = + bool ShouldSuppress = SourceMgr.isMacroBodyExpansion(ExprLoc) || SourceMgr.isInSystemMacro(ExprLoc); @@ -1879,7 +1879,7 @@ Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl()); if (!D || D->isInvalidDecl()) return StmtError(); - + FirstType = D->getType(); // C99 6.8.5p3: The declaration part of a 'for' statement shall only // declare identifiers for objects having storage class 'auto' or @@ -2373,7 +2373,7 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, // Rather, we need to determine what it was when the array was first // created - so we resort to using sizeof(vla)/sizeof(element). // For e.g. - // void f(int b) { + // void f(int b) { // int vla[b]; // b = -1; <-- This should not affect the num of iterations below // for (int &c : vla) { .. } @@ -2399,7 +2399,7 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, EndVar->getSourceRange()); if (SizeOfVLAExprR.isInvalid()) return StmtError(); - + ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr( EndVar->getLocation(), UETT_SizeOf, /*isType=*/true, @@ -2416,7 +2416,7 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, SizeOfVLAExprR.get(), SizeOfEachElementExprR.get()); if (BoundExpr.isInvalid()) return StmtError(); - + } else { // Can't be a DependentSizedArrayType or an IncompleteArrayType since // UnqAT is not incomplete and Range is not type-dependent. @@ -3366,7 +3366,7 @@ bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, // statement with a non-type-dependent operand. assert(AT->isDeduced() && "should have deduced to dependent type"); return false; - } + } if (RetExpr) { // Otherwise, [...] deduce a value for U using the rules of template diff --git a/lib/Sema/SemaStmtAsm.cpp b/lib/Sema/SemaStmtAsm.cpp index 7e26b71c04826..0db15ea1f646a 100644 --- a/lib/Sema/SemaStmtAsm.cpp +++ b/lib/Sema/SemaStmtAsm.cpp @@ -603,7 +603,7 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, Context.getTargetInfo(), Context); if (ConstraintLoc.isValid()) return Diag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber); - + return NS; } diff --git a/lib/Sema/SemaTemplate.cpp b/lib/Sema/SemaTemplate.cpp index dd1163267119a..fa002de3f5f11 100644 --- a/lib/Sema/SemaTemplate.cpp +++ b/lib/Sema/SemaTemplate.cpp @@ -888,7 +888,7 @@ ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { // This is a normal type template argument. Note, if the type template // argument is an injected-class-name for a template, it has a dual nature - // and can be used as either a type or a template. We handle that in + // and can be used as either a type or a template. We handle that in // convertTypeTemplateArgumentToTemplate. return ParsedTemplateArgument(ParsedTemplateArgument::Type, ParsedType.get().getAsOpaquePtr(), @@ -1044,14 +1044,14 @@ NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, // Check that we have valid decl-specifiers specified. auto CheckValidDeclSpecifiers = [this, &D] { // C++ [temp.param] - // p1 + // p1 // template-parameter: // ... // parameter-declaration - // p2 + // p2 // ... A storage class shall not be specified in a template-parameter // declaration. - // [dcl.typedef]p1: + // [dcl.typedef]p1: // The typedef specifier [...] shall not be used in the decl-specifier-seq // of a parameter-declaration const DeclSpec &DS = D.getDeclSpec(); @@ -1061,22 +1061,22 @@ NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, }; if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) EmitDiag(DS.getStorageClassSpecLoc()); - + if (DS.getThreadStorageClassSpec() != TSCS_unspecified) EmitDiag(DS.getThreadStorageClassSpecLoc()); - - // [dcl.inline]p1: - // The inline specifier can be applied only to the declaration or + + // [dcl.inline]p1: + // The inline specifier can be applied only to the declaration or // definition of a variable or function. - + if (DS.isInlineSpecified()) EmitDiag(DS.getInlineSpecLoc()); - + // [dcl.constexpr]p1: - // The constexpr specifier shall be applied only to the definition of a - // variable or variable template or the declaration of a function or + // The constexpr specifier shall be applied only to the definition of a + // variable or variable template or the declaration of a function or // function template. - + if (DS.isConstexprSpecified()) EmitDiag(DS.getConstexprSpecLoc()); @@ -1094,7 +1094,7 @@ NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, }; CheckValidDeclSpecifiers(); - + if (TInfo->getType()->isUndeducedType()) { Diag(D.getIdentifierLoc(), diag::warn_cxx14_compat_template_nontype_parm_auto_type) @@ -1659,6 +1659,23 @@ DeclResult Sema::CheckClassTemplate( } namespace { +/// Tree transform to "extract" a transformed type from a class template's +/// constructor to a deduction guide. +class ExtractTypeForDeductionGuide + : public TreeTransform<ExtractTypeForDeductionGuide> { +public: + typedef TreeTransform<ExtractTypeForDeductionGuide> Base; + ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {} + + TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { + return TransformType( + TLB, + TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc()); + } +}; + /// Transform to convert portions of a constructor declaration into the /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. struct ConvertConstructorToDeductionGuideTransform { @@ -1880,9 +1897,7 @@ private: MultiLevelTemplateArgumentList &Args) { TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); TypeSourceInfo *NewDI; - if (!Args.getNumLevels()) - NewDI = OldDI; - else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { + if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { // Expand out the one and only element in each inner pack. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); NewDI = @@ -1898,23 +1913,17 @@ private: if (!NewDI) return nullptr; - // Canonicalize the type. This (for instance) replaces references to - // typedef members of the current instantiations with the definitions of - // those typedefs, avoiding triggering instantiation of the deduced type - // during deduction. - // FIXME: It would be preferable to retain type sugar and source - // information here (and handle this in substitution instead). - NewDI = SemaRef.Context.getTrivialTypeSourceInfo( - SemaRef.Context.getCanonicalType(NewDI->getType()), - OldParam->getLocation()); + // Extract the type. This (for instance) replaces references to typedef + // members of the current instantiations with the definitions of those + // typedefs, avoiding triggering instantiation of the deduced type during + // deduction. + NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI); // Resolving a wording defect, we also inherit default arguments from the // constructor. ExprResult NewDefArg; if (OldParam->hasDefaultArg()) { - NewDefArg = Args.getNumLevels() - ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args) - : OldParam->getDefaultArg(); + NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args); if (NewDefArg.isInvalid()) return nullptr; } @@ -1929,6 +1938,7 @@ private: NewDefArg.get()); NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), OldParam->getFunctionScopeIndex()); + SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); return NewParam; } diff --git a/lib/Sema/SemaTemplateDeduction.cpp b/lib/Sema/SemaTemplateDeduction.cpp index 633b2837e1fe9..df46d6115a200 100644 --- a/lib/Sema/SemaTemplateDeduction.cpp +++ b/lib/Sema/SemaTemplateDeduction.cpp @@ -4599,7 +4599,7 @@ bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent(); FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); - // For a generic lambda, instantiate the call operator if needed. + // For a generic lambda, instantiate the call operator if needed. if (auto *Args = FD->getTemplateSpecializationArgs()) { CallOp = InstantiateFunctionDeclaration( CallOp->getDescribedFunctionTemplate(), Args, Loc); diff --git a/lib/Sema/SemaTemplateInstantiate.cpp b/lib/Sema/SemaTemplateInstantiate.cpp index bc2ee42400b7a..1aa69bd35d67e 100644 --- a/lib/Sema/SemaTemplateInstantiate.cpp +++ b/lib/Sema/SemaTemplateInstantiate.cpp @@ -52,7 +52,7 @@ using namespace sema; /// used to determine the proper set of template instantiation arguments for /// friend function template specializations. MultiLevelTemplateArgumentList -Sema::getTemplateInstantiationArgs(NamedDecl *D, +Sema::getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost, bool RelativeToPrimary, const FunctionDecl *Pattern) { @@ -61,7 +61,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, if (Innermost) Result.addOuterTemplateArguments(Innermost); - + DeclContext *Ctx = dyn_cast<DeclContext>(D); if (!Ctx) { Ctx = D->getDeclContext(); @@ -100,7 +100,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, // use empty template parameter lists for all of the outer templates // to avoid performing any substitutions. if (Ctx->isTranslationUnit()) { - if (TemplateTemplateParmDecl *TTP + if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) Result.addOuterTemplateArguments(None); @@ -108,7 +108,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, } } } - + while (!Ctx->isFileContext()) { // Add template arguments from a class template instantiation. if (ClassTemplateSpecializationDecl *Spec @@ -119,8 +119,8 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, break; Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); - - // If this class template specialization was instantiated from a + + // If this class template specialization was instantiated from a // specialized member that is a class template, we're done. assert(Spec->getSpecializedTemplate() && "No class template?"); if (Spec->getSpecializedTemplate()->isMemberSpecialization()) @@ -129,11 +129,11 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, // Add template arguments from a function template specialization. else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { if (!RelativeToPrimary && - (Function->getTemplateSpecializationKind() == + (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && !Function->getClassScopeSpecializationPattern())) break; - + if (const TemplateArgumentList *TemplateArgs = Function->getTemplateSpecializationArgs()) { // Add the template arguments for this specialization. @@ -154,7 +154,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, // Add the "injected" template arguments. Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs()); } - + // If this is a friend declaration and it declares an entity at // namespace scope, take arguments from its lexical parent // instead of its semantic parent, unless of course the pattern we're @@ -200,7 +200,7 @@ bool Sema::CodeSynthesisContext::isInstantiationRecord() const { case DeclaringSpecialMember: case DefiningSynthesizedFunction: return false; - + // This function should never be called when Kind's value is Memoization. case Memoization: break; @@ -413,7 +413,7 @@ bool Sema::InstantiatingTemplate::CheckInstantiationDepth( SourceRange InstantiationRange) { assert(SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()); - if ((SemaRef.CodeSynthesisContexts.size() - + if ((SemaRef.CodeSynthesisContexts.size() - SemaRef.NonInstantiationEntries) <= SemaRef.getLangOpts().InstantiationDepth) return false; @@ -517,9 +517,9 @@ void Sema::PrintInstantiationStack() { FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity); Diags.Report(Active->PointOfInstantiation, diag::note_explicit_template_arg_substitution_here) - << FnTmpl - << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), - Active->TemplateArgs, + << FnTmpl + << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; break; @@ -531,8 +531,8 @@ void Sema::PrintInstantiationStack() { Diags.Report(Active->PointOfInstantiation, diag::note_function_template_deduction_instantiation_here) << FnTmpl - << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), - Active->TemplateArgs, + << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; } else { @@ -556,7 +556,7 @@ void Sema::PrintInstantiationStack() { Diags.Report(Active->PointOfInstantiation, diag::note_deduced_template_arg_substitution_here) << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity) - << getTemplateArgumentBindingsText(Params, Active->TemplateArgs, + << getTemplateArgumentBindingsText(Params, Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; } @@ -596,8 +596,8 @@ void Sema::PrintInstantiationStack() { diag::note_prior_template_arg_substitution) << isa<TemplateTemplateParmDecl>(Parm) << Name - << getTemplateArgumentBindingsText(TemplateParams, - Active->TemplateArgs, + << getTemplateArgumentBindingsText(TemplateParams, + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; break; @@ -614,8 +614,8 @@ void Sema::PrintInstantiationStack() { Diags.Report(Active->PointOfInstantiation, diag::note_template_default_arg_checking) - << getTemplateArgumentBindingsText(TemplateParams, - Active->TemplateArgs, + << getTemplateArgumentBindingsText(TemplateParams, + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; break; @@ -660,7 +660,7 @@ Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { Active = CodeSynthesisContexts.rbegin(), ActiveEnd = CodeSynthesisContexts.rend(); Active != ActiveEnd; - ++Active) + ++Active) { switch (Active->Kind) { case CodeSynthesisContext::TemplateInstantiation: @@ -678,7 +678,7 @@ Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { case CodeSynthesisContext::PriorTemplateArgumentSubstitution: case CodeSynthesisContext::DefaultTemplateArgumentChecking: // A default template argument instantiation and substitution into - // template parameters with arguments for prior parameters may or may + // template parameters with arguments for prior parameters may or may // not be a SFINAE context; look further up the stack. break; @@ -752,18 +752,18 @@ namespace { ArrayRef<UnexpandedParameterPack> Unexpanded, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions) { - return getSema().CheckParameterPacksForExpansion(EllipsisLoc, + return getSema().CheckParameterPacksForExpansion(EllipsisLoc, PatternRange, Unexpanded, - TemplateArgs, + TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions); } - void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { + void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); } - + TemplateArgument ForgetPartiallySubstitutedPack() { TemplateArgument Result; if (NamedDecl *PartialPack @@ -777,14 +777,14 @@ namespace { TemplateArgs.setArgument(Depth, Index, TemplateArgument()); } } - + return Result; } - + void RememberPartiallySubstitutedPack(TemplateArgument Arg) { if (Arg.isNull()) return; - + if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ MultiLevelTemplateArgumentList &TemplateArgs @@ -799,7 +799,7 @@ namespace { /// this declaration. Decl *TransformDecl(SourceLocation Loc, Decl *D); - void transformAttrs(Decl *Old, Decl *New) { + void transformAttrs(Decl *Old, Decl *New) { SemaRef.InstantiateAttrs(TemplateArgs, Old, New); } @@ -817,7 +817,7 @@ namespace { NewMD->setInstantiationOfMemberFunction(OldMD, TSK_ImplicitInstantiation); } - + SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); // We recreated a local declaration, but not by instantiating it. There @@ -825,7 +825,7 @@ namespace { if (auto *DC = dyn_cast<DeclContext>(Old)) SemaRef.PerformDependentDiagnostics(DC, TemplateArgs); } - + /// Transform the definition of the given declaration by /// instantiating it. Decl *TransformDefinition(SourceLocation Loc, Decl *D); @@ -833,20 +833,20 @@ namespace { /// Transform the first qualifier within a scope by instantiating the /// declaration. NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); - + /// Rebuild the exception declaration and register the declaration /// as an instantiated local. - VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, + VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, TypeSourceInfo *Declarator, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name); - /// Rebuild the Objective-C exception declaration and register the + /// Rebuild the Objective-C exception declaration and register the /// declaration as an instantiated local. - VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, + VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, TypeSourceInfo *TSInfo, QualType T); - + /// Check for tag mismatches when instantiating an /// elaborated type. QualType RebuildElaboratedType(SourceLocation KeywordLoc, @@ -921,11 +921,11 @@ namespace { TemplateParameterList *TransformTemplateParameterList( TemplateParameterList *OrigTPL) { if (!OrigTPL || !OrigTPL->size()) return OrigTPL; - + DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext(); - TemplateDeclInstantiator DeclInstantiator(getSema(), + TemplateDeclInstantiator DeclInstantiator(getSema(), /* DeclContext *Owner */ Owner, TemplateArgs); - return DeclInstantiator.SubstTemplateParams(OrigTPL); + return DeclInstantiator.SubstTemplateParams(OrigTPL); } private: ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm, @@ -937,17 +937,17 @@ namespace { bool TemplateInstantiator::AlreadyTransformed(QualType T) { if (T.isNull()) return true; - + if (T->isInstantiationDependentType() || T->isVariablyModifiedType()) return false; - + getSema().MarkDeclarationsReferencedInType(Loc, T); return true; } static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) { - assert(S.ArgumentPackSubstitutionIndex >= 0); + assert(S.ArgumentPackSubstitutionIndex >= 0); assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex]; if (Arg.isPackExpansion()) @@ -970,9 +970,9 @@ Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { return D; TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); - + if (TTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } @@ -1000,22 +1000,22 @@ Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { } NamedDecl * -TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, +TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) { - // If the first part of the nested-name-specifier was a template type + // If the first part of the nested-name-specifier was a template type // parameter, instantiate that type parameter down to a tag type. if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { - const TemplateTypeParmType *TTP + const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); - + if (TTP->getDepth() < TemplateArgs.getNumLevels()) { // FIXME: This needs testing w/ member access expressions. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); - + if (TTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) return nullptr; @@ -1025,16 +1025,16 @@ TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, QualType T = Arg.getAsType(); if (T.isNull()) return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); - + if (const TagType *Tag = T->getAs<TagType>()) return Tag->getDecl(); - + // The resulting type is not a tag; complain. getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; return nullptr; } } - + return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); } @@ -1051,8 +1051,8 @@ TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, return Var; } -VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, - TypeSourceInfo *TSInfo, +VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, + TypeSourceInfo *TSInfo, QualType T) { VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); if (Var) @@ -1107,13 +1107,13 @@ TemplateName TemplateInstantiator::TransformTemplateName( if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), TTP->getPosition())) return Name; - + TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); - + if (TTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We have the template argument pack to substitute, but we're not // actually expanding the enclosing pack expansion yet. So, just @@ -1123,7 +1123,7 @@ TemplateName TemplateInstantiator::TransformTemplateName( Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } - + TemplateName Template = Arg.getAsTemplate().getNameToSubstitute(); assert(!Template.isNull() && "Null template template argument"); assert(!Template.getAsQualifiedTemplateName() && @@ -1133,12 +1133,12 @@ TemplateName TemplateInstantiator::TransformTemplateName( return Template; } } - + if (SubstTemplateTemplateParmPackStorage *SubstPack = Name.getAsSubstTemplateTemplateParmPack()) { if (getSema().ArgumentPackSubstitutionIndex == -1) return Name; - + TemplateArgument Arg = SubstPack->getArgumentPack(); Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); return Arg.getAsTemplate().getNameToSubstitute(); @@ -1149,7 +1149,7 @@ TemplateName TemplateInstantiator::TransformTemplateName( AllowInjectedClassName); } -ExprResult +ExprResult TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { if (!E->isTypeDependent()) return E; @@ -1187,15 +1187,15 @@ TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, } if (NTTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We have an argument pack, but we can't select a particular argument // out of it yet. Therefore, we'll build an expression to hold on to that // argument pack. QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, - E->getLocation(), + E->getLocation(), NTTP->getDeclName()); if (TargetType.isNull()) return ExprError(); @@ -1205,7 +1205,7 @@ TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP, E->getLocation(), Arg); } - + Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } @@ -1260,12 +1260,12 @@ ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( // Propagate NULL template argument. VD = nullptr; } - + // Derive the type we want the substituted decl to have. This had // better be non-dependent, or these checks will have serious problems. if (parm->isExpandedParameterPack()) { type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex); - } else if (parm->isParameterPack() && + } else if (parm->isParameterPack() && isa<PackExpansionType>(parm->getType())) { type = SemaRef.SubstType( cast<PackExpansionType>(parm->getType())->getPattern(), @@ -1292,8 +1292,8 @@ ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( return new (SemaRef.Context) SubstNonTypeTemplateParmExpr( type, resultExpr->getValueKind(), loc, parm, resultExpr); } - -ExprResult + +ExprResult TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( SubstNonTypeTemplateParmPackExpr *E) { if (getSema().ArgumentPackSubstitutionIndex == -1) { @@ -1387,7 +1387,7 @@ TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { if (NTTP->getDepth() < TemplateArgs.getNumLevels()) return TransformTemplateParmRefExpr(E, NTTP); - + // We have a non-type template parameter that isn't fully substituted; // FindInstantiatedDecl will find it in the local instantiation scope. } @@ -1406,7 +1406,7 @@ ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."); return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(), - cast<FunctionDecl>(E->getParam()->getDeclContext()), + cast<FunctionDecl>(E->getParam()->getDeclContext()), E->getParam()); } @@ -1451,11 +1451,11 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, } TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); - + if (T->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We have the template argument pack, but we're not expanding the // enclosing pack expansion yet. Just save the template argument @@ -1467,10 +1467,10 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, NewTL.setNameLoc(TL.getNameLoc()); return Result; } - + Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } - + assert(Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"); @@ -1502,7 +1502,7 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, return Result; } -QualType +QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL) { @@ -1565,8 +1565,8 @@ TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, assert(!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); - - if (!T->getType()->isInstantiationDependentType() && + + if (!T->getType()->isInstantiationDependentType() && !T->getType()->isVariablyModifiedType()) return T; @@ -1582,11 +1582,11 @@ TypeSourceInfo *Sema::SubstType(TypeLoc TL, assert(!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); - + if (TL.getType().isNull()) return nullptr; - if (!TL.getType()->isInstantiationDependentType() && + if (!TL.getType()->isInstantiationDependentType() && !TL.getType()->isVariablyModifiedType()) { // FIXME: Make a copy of the TypeLoc data here, so that we can // return a new TypeSourceInfo. Inefficient! @@ -1716,7 +1716,7 @@ void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, UpdateExceptionSpec(New, ESI); } -ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, +ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, @@ -1727,9 +1727,9 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, TypeLoc OldTL = OldDI->getTypeLoc(); if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { - // We have a function parameter pack. Substitute into the pattern of the + // We have a function parameter pack. Substitute into the pattern of the // expansion. - NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, + NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, OldParm->getLocation(), OldParm->getDeclName()); if (!NewDI) return nullptr; @@ -1745,16 +1745,16 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, // itself is not a pack expansion type), so complain. This can occur when // the substitution goes through an alias template that "loses" the // pack expansion. - Diag(OldParm->getLocation(), + Diag(OldParm->getLocation(), diag::err_function_parameter_pack_without_parameter_packs) << NewDI->getType(); return nullptr; - } + } } else { - NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), + NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), OldParm->getDeclName()); } - + if (!NewDI) return nullptr; @@ -1801,15 +1801,15 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, } NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); - + if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { // Add the new parameter to the instantiated parameter pack. CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); } else { // Introduce an Old -> New mapping - CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); + CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); } - + // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext // can be anything, is this right ? NewParm->setDeclContext(CurContext); @@ -1819,7 +1819,7 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, InstantiateAttrs(TemplateArgs, OldParm, NewParm); - return NewParm; + return NewParm; } /// Substitute the given template arguments into the given set of @@ -1835,8 +1835,8 @@ bool Sema::SubstParmTypes( assert(!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); - - TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, + + TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, DeclarationName()); return Instantiator.TransformFunctionTypeParams( Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos); @@ -1875,21 +1875,21 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, bool ShouldExpand = false; bool RetainExpansion = false; Optional<unsigned> NumExpansions; - if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), + if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), Base.getSourceRange(), Unexpanded, - TemplateArgs, ShouldExpand, + TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions)) { Invalid = true; continue; } - + // If we should expand this pack expansion now, do so. if (ShouldExpand) { for (unsigned I = 0; I != *NumExpansions; ++I) { Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); - + TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), TemplateArgs, Base.getSourceRange().getBegin(), @@ -1898,7 +1898,7 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, Invalid = true; continue; } - + if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(Instantiation, Base.getSourceRange(), @@ -1910,10 +1910,10 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, else Invalid = true; } - + continue; } - + // The resulting base specifier will (still) be a pack expansion. EllipsisLoc = Base.getEllipsisLoc(); Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); @@ -1927,7 +1927,7 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, Base.getSourceRange().getBegin(), DeclarationName()); } - + if (!BaseTypeLoc) { Invalid = true; continue; @@ -1999,11 +1999,11 @@ Sema::InstantiateClass(SourceLocation PointOfInstantiation, Pattern = PatternDef; // Record the point of instantiation. - if (MemberSpecializationInfo *MSInfo + if (MemberSpecializationInfo *MSInfo = Instantiation->getMemberSpecializationInfo()) { MSInfo->setTemplateSpecializationKind(TSK); MSInfo->setPointOfInstantiation(PointOfInstantiation); - } else if (ClassTemplateSpecializationDecl *Spec + } else if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { Spec->setTemplateSpecializationKind(TSK); Spec->setPointOfInstantiation(PointOfInstantiation); @@ -2563,15 +2563,15 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, if (auto *Function = dyn_cast<FunctionDecl>(D)) { if (FunctionDecl *Pattern = Function->getInstantiatedFromMemberFunction()) { - MemberSpecializationInfo *MSInfo + MemberSpecializationInfo *MSInfo = Function->getMemberSpecializationInfo(); assert(MSInfo && "No member specialization information?"); if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) continue; - - if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, - Function, + + if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, + Function, MSInfo->getTemplateSpecializationKind(), MSInfo->getPointOfInstantiation(), SuppressNew) || @@ -2610,31 +2610,31 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) continue; - - if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, - Var, + + if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, + Var, MSInfo->getTemplateSpecializationKind(), MSInfo->getPointOfInstantiation(), SuppressNew) || SuppressNew) continue; - + if (TSK == TSK_ExplicitInstantiationDefinition) { // C++0x [temp.explicit]p8: // An explicit instantiation definition that names a class template - // specialization explicitly instantiates the class template - // specialization and is only an explicit instantiation definition - // of members whose definition is visible at the point of + // specialization explicitly instantiates the class template + // specialization and is only an explicit instantiation definition + // of members whose definition is visible at the point of // instantiation. if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) continue; - + Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); InstantiateVariableDefinition(PointOfInstantiation, Var); } else { Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); } - } + } } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) { // Always skip the injected-class-name, along with any // redeclarations of nested classes, since both would cause us @@ -2644,10 +2644,10 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, if (Record->isInjectedClassName() || Record->getPreviousDecl() || Record->isLambda()) continue; - + MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); assert(MSInfo && "No member specialization information?"); - + if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) continue; @@ -2660,33 +2660,33 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, continue; } - if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, - Record, + if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, + Record, MSInfo->getTemplateSpecializationKind(), MSInfo->getPointOfInstantiation(), SuppressNew) || SuppressNew) continue; - + CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); assert(Pattern && "Missing instantiated-from-template information"); - + if (!Record->getDefinition()) { if (!Pattern->getDefinition()) { // C++0x [temp.explicit]p8: // An explicit instantiation definition that names a class template - // specialization explicitly instantiates the class template - // specialization and is only an explicit instantiation definition - // of members whose definition is visible at the point of + // specialization explicitly instantiates the class template + // specialization and is only an explicit instantiation definition + // of members whose definition is visible at the point of // instantiation. if (TSK == TSK_ExplicitInstantiationDeclaration) { MSInfo->setTemplateSpecializationKind(TSK); MSInfo->setPointOfInstantiation(PointOfInstantiation); } - + continue; } - + InstantiateClass(PointOfInstantiation, Record, Pattern, TemplateArgs, TSK); @@ -2698,10 +2698,10 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, MarkVTableUsed(PointOfInstantiation, Record, true); } } - + Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); if (Pattern) - InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, + InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, TSK); } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); @@ -2816,10 +2816,10 @@ bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, NestedNameSpecifierLoc Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, - const MultiLevelTemplateArgumentList &TemplateArgs) { + const MultiLevelTemplateArgumentList &TemplateArgs) { if (!NNS) return NestedNameSpecifierLoc(); - + TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), DeclarationName()); return Instantiator.TransformNestedNameSpecifierLoc(NNS); @@ -2850,7 +2850,7 @@ bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, const MultiLevelTemplateArgumentList &TemplateArgs) { TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), DeclarationName()); - + return Instantiator.TransformTemplateArguments(Args, NumArgs, Result); } @@ -2884,7 +2884,7 @@ LocalInstantiationScope::findInstantiationOf(const Decl *D) { LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); if (Found != Current->LocalDecls.end()) return &Found->second; - + // If this is a tag declaration, it's possible that we need to look for // a previous declaration. if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) @@ -2892,8 +2892,8 @@ LocalInstantiationScope::findInstantiationOf(const Decl *D) { else CheckD = nullptr; } while (CheckD); - - // If we aren't combined with our outer scope, we're done. + + // If we aren't combined with our outer scope, we're done. if (!Current->CombineWithOuterScope) break; } @@ -2965,12 +2965,12 @@ void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { ArgumentPacks.push_back(Pack); } -void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, +void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs) { assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && "Already have a partially-substituted pack"); - assert((!PartiallySubstitutedPack + assert((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"); PartiallySubstitutedPack = Pack; @@ -2985,15 +2985,15 @@ NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( *ExplicitArgs = nullptr; if (NumExplicitArgs) *NumExplicitArgs = 0; - - for (const LocalInstantiationScope *Current = this; Current; + + for (const LocalInstantiationScope *Current = this; Current; Current = Current->Outer) { if (Current->PartiallySubstitutedPack) { if (ExplicitArgs) *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; if (NumExplicitArgs) *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; - + return Current->PartiallySubstitutedPack; } diff --git a/lib/Sema/SemaTemplateInstantiateDecl.cpp b/lib/Sema/SemaTemplateInstantiateDecl.cpp index 5109dc8290f92..86492716f6851 100644 --- a/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -729,7 +729,7 @@ Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, DI, D->getStorageClass()); // In ARC, infer 'retaining' for variables of retainable type. - if (SemaRef.getLangOpts().ObjCAutoRefCount && + if (SemaRef.getLangOpts().ObjCAutoRefCount && SemaRef.inferObjCARCLifetime(Var)) Var->setInvalidDecl(); @@ -2056,7 +2056,7 @@ TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, // previous declaration we just found. if (isFriend && Method->getPreviousDecl()) Method->setAccess(Method->getPreviousDecl()->getAccess()); - else + else Method->setAccess(D->getAccess()); if (FunctionTemplate) FunctionTemplate->setAccess(Method->getAccess()); @@ -3417,7 +3417,7 @@ TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, ThisContext = cast<CXXRecordDecl>(Owner); ThisTypeQuals = Method->getTypeQualifiers(); } - + TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), @@ -4890,14 +4890,14 @@ NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext) { DeclContext *ParentDC = D->getDeclContext(); - // FIXME: Parmeters of pointer to functions (y below) that are themselves + // FIXME: Parmeters of pointer to functions (y below) that are themselves // parameters (p below) can have their ParentDC set to the translation-unit - // - thus we can not consistently check if the ParentDC of such a parameter + // - thus we can not consistently check if the ParentDC of such a parameter // is Dependent or/and a FunctionOrMethod. - // For e.g. this code, during Template argument deduction tries to + // For e.g. this code, during Template argument deduction tries to // find an instantiated decl for (T y) when the ParentDC for y is - // the translation unit. - // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} + // the translation unit. + // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} // float baz(float(*)()) { return 0.0; } // Foo(baz); // The better fix here is perhaps to ensure that a ParmVarDecl, by the time diff --git a/lib/Sema/SemaTemplateVariadic.cpp b/lib/Sema/SemaTemplateVariadic.cpp index fc1641334273e..6f9dddf5c05ec 100644 --- a/lib/Sema/SemaTemplateVariadic.cpp +++ b/lib/Sema/SemaTemplateVariadic.cpp @@ -29,7 +29,7 @@ using namespace clang; namespace { /// A class that collects unexpanded parameter packs. class CollectUnexpandedParameterPacksVisitor : - public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> + public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> { typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> inherited; @@ -58,7 +58,7 @@ namespace { if (T->getDepth() < DepthLimit) Unexpanded.push_back({T, Loc}); } - + public: explicit CollectUnexpandedParameterPacksVisitor( SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) @@ -94,10 +94,10 @@ namespace { bool VisitDeclRefExpr(DeclRefExpr *E) { if (E->getDecl()->isParameterPack()) addUnexpanded(E->getDecl(), E->getLocation()); - + return true; } - + /// Record occurrences of template template parameter packs. bool TraverseTemplateName(TemplateName Template) { if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>( @@ -105,7 +105,7 @@ namespace { if (TTP->isParameterPack()) addUnexpanded(TTP); } - + return inherited::TraverseTemplateName(Template); } @@ -131,7 +131,7 @@ namespace { /// Suppress traversal into statements and expressions that /// do not contain unexpanded parameter packs. - bool TraverseStmt(Stmt *S) { + bool TraverseStmt(Stmt *S) { Expr *E = dyn_cast_or_null<Expr>(S); if ((E && E->containsUnexpandedParameterPack()) || InLambda) return inherited::TraverseStmt(S); @@ -151,7 +151,7 @@ namespace { /// Suppress traversal into types with location information /// that do not contain unexpanded parameter packs. bool TraverseTypeLoc(TypeLoc TL) { - if ((!TL.getType().isNull() && + if ((!TL.getType().isNull() && TL.getType()->containsUnexpandedParameterPack()) || InLambda) return inherited::TraverseTypeLoc(TL); @@ -160,7 +160,7 @@ namespace { } /// Suppress traversal of parameter packs. - bool TraverseDecl(Decl *D) { + bool TraverseDecl(Decl *D) { // A function parameter pack is a pack expansion, so cannot contain // an unexpanded parameter pack. Likewise for a template parameter // pack that contains any references to other packs. @@ -215,7 +215,7 @@ namespace { bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { if (ArgLoc.getArgument().isPackExpansion()) return true; - + return inherited::TraverseTemplateArgumentLoc(ArgLoc); } @@ -335,7 +335,7 @@ Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, return false; } } - + SmallVector<SourceLocation, 4> Locations; SmallVector<IdentifierInfo *, 4> Names; llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown; @@ -365,11 +365,11 @@ Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, return true; } -bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, +bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. if (!T->getType()->containsUnexpandedParameterPack()) return false; @@ -384,7 +384,7 @@ bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, bool Sema::DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. if (!E->containsUnexpandedParameterPack()) return false; @@ -398,9 +398,9 @@ bool Sema::DiagnoseUnexpandedParameterPack(Expr *E, bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. - if (!SS.getScopeRep() || + if (!SS.getScopeRep() || !SS.getScopeRep()->containsUnexpandedParameterPack()) return false; @@ -415,7 +415,7 @@ bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. switch (NameInfo.getName().getNameKind()) { case DeclarationName::Identifier: @@ -451,7 +451,7 @@ bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC) { - + if (Template.isNull() || !Template.containsUnexpandedParameterPack()) return false; @@ -464,10 +464,10 @@ bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC) { - if (Arg.getArgument().isNull() || + if (Arg.getArgument().isNull() || !Arg.getArgument().containsUnexpandedParameterPack()) return false; - + SmallVector<UnexpandedParameterPack, 2> Unexpanded; CollectUnexpandedParameterPacksVisitor(Unexpanded) .TraverseTemplateArgumentLoc(Arg); @@ -489,12 +489,12 @@ void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, void Sema::collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { - CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T); -} + CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T); +} void Sema::collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { - CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); + CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); } void Sema::collectUnexpandedParameterPacks( @@ -512,7 +512,7 @@ void Sema::collectUnexpandedParameterPacks( } -ParsedTemplateArgument +ParsedTemplateArgument Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc) { if (Arg.isInvalid()) @@ -524,7 +524,7 @@ Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, if (Result.isInvalid()) return ParsedTemplateArgument(); - return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), + return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), Arg.getLocation()); } @@ -532,11 +532,11 @@ Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc); if (Result.isInvalid()) return ParsedTemplateArgument(); - - return ParsedTemplateArgument(Arg.getKind(), Result.get(), + + return ParsedTemplateArgument(Arg.getKind(), Result.get(), Arg.getLocation()); } - + case ParsedTemplateArgument::Template: if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) { SourceRange R(Arg.getLocation()); @@ -546,13 +546,13 @@ Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, << R; return ParsedTemplateArgument(); } - + return Arg.getTemplatePackExpansion(EllipsisLoc); } llvm_unreachable("Unhandled template argument kind?"); } -TypeResult Sema::ActOnPackExpansion(ParsedType Type, +TypeResult Sema::ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc) { TypeSourceInfo *TSInfo; GetTypeFromParser(Type, &TSInfo); @@ -562,7 +562,7 @@ TypeResult Sema::ActOnPackExpansion(ParsedType Type, TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None); if (!TSResult) return true; - + return CreateParsedType(TSResult->getType(), TSResult); } @@ -570,7 +570,7 @@ TypeSourceInfo * Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions) { // Create the pack expansion type and source-location information. - QualType Result = CheckPackExpansion(Pattern->getType(), + QualType Result = CheckPackExpansion(Pattern->getType(), Pattern->getTypeLoc().getSourceRange(), EllipsisLoc, NumExpansions); if (Result.isNull()) @@ -608,7 +608,7 @@ ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions) { if (!Pattern) return ExprError(); - + // C++0x [temp.variadic]p5: // The pattern of a pack expansion shall name one or more // parameter packs that are not expanded by a nested pack @@ -618,7 +618,7 @@ ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, << Pattern->getSourceRange(); return ExprError(); } - + // Create the pack expansion expression and source-location information. return new (Context) PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions); @@ -643,7 +643,7 @@ bool Sema::CheckParameterPacksForExpansion( unsigned Depth = 0, Index = 0; IdentifierInfo *Name; bool IsFunctionParameterPack = false; - + if (const TemplateTypeParmType *TTP = i->first.dyn_cast<const TemplateTypeParmType *>()) { Depth = TTP->getDepth(); @@ -658,13 +658,13 @@ bool Sema::CheckParameterPacksForExpansion( Name = ND->getIdentifier(); } - + // Determine the size of this argument pack. - unsigned NewPackSize; + unsigned NewPackSize; if (IsFunctionParameterPack) { // Figure out whether we're instantiating to an argument pack or not. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; - + llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = CurrentInstantiationScope->findInstantiationOf( i->first.get<NamedDecl *>()); @@ -678,25 +678,25 @@ bool Sema::CheckParameterPacksForExpansion( continue; } } else { - // If we don't have a template argument at this depth/index, then we - // cannot expand the pack expansion. Make a note of this, but we still + // If we don't have a template argument at this depth/index, then we + // cannot expand the pack expansion. Make a note of this, but we still // want to check any parameter packs we *do* have arguments for. if (Depth >= TemplateArgs.getNumLevels() || !TemplateArgs.hasTemplateArgument(Depth, Index)) { ShouldExpand = false; continue; } - + // Determine the size of the argument pack. NewPackSize = TemplateArgs(Depth, Index).pack_size(); } - + // C++0x [temp.arg.explicit]p9: - // Template argument deduction can extend the sequence of template + // Template argument deduction can extend the sequence of template // arguments corresponding to a template parameter pack, even when the // sequence contains explicitly specified template arguments. if (!IsFunctionParameterPack && CurrentInstantiationScope) { - if (NamedDecl *PartialPack + if (NamedDecl *PartialPack = CurrentInstantiationScope->getPartiallySubstitutedPack()){ unsigned PartialDepth, PartialIndex; std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack); @@ -709,9 +709,9 @@ bool Sema::CheckParameterPacksForExpansion( } } } - + if (!NumExpansions) { - // The is the first pack we've seen for which we have an argument. + // The is the first pack we've seen for which we have an argument. // Record it. NumExpansions = NewPackSize; FirstPack.first = Name; @@ -719,10 +719,10 @@ bool Sema::CheckParameterPacksForExpansion( HaveFirstPack = true; continue; } - + if (NewPackSize != *NumExpansions) { // C++0x [temp.variadic]p5: - // All of the parameter packs expanded by a pack expansion shall have + // All of the parameter packs expanded by a pack expansion shall have // the same number of arguments specified. if (HaveFirstPack) Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) @@ -772,17 +772,17 @@ Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T, // Compute the depth and index for this parameter pack. unsigned Depth; unsigned Index; - + if (const TemplateTypeParmType *TTP = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) { Depth = TTP->getDepth(); Index = TTP->getIndex(); - } else { + } else { NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>(); if (isa<ParmVarDecl>(ND)) { // Function parameter pack. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; - + llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = CurrentInstantiationScope->findInstantiationOf( Unexpanded[I].first.get<NamedDecl *>()); @@ -804,13 +804,13 @@ Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T, // The pattern refers to an unknown template argument. We're not ready to // expand this pack yet. return None; - + // Determine the size of the argument pack. unsigned Size = TemplateArgs(Depth, Index).pack_size(); assert((!Result || *Result == Size) && "inconsistent pack sizes"); Result = Size; } - + return Result; } @@ -826,14 +826,14 @@ bool Sema::containsUnexpandedParameterPacks(Declarator &D) { return true; break; } - + case TST_typeofExpr: case TST_decltype: - if (DS.getRepAsExpr() && + if (DS.getRepAsExpr() && DS.getRepAsExpr()->containsUnexpandedParameterPack()) return true; break; - + case TST_unspecified: case TST_void: case TST_char: @@ -879,7 +879,7 @@ bool Sema::containsUnexpandedParameterPacks(Declarator &D) { case DeclaratorChunk::BlockPointer: // These declarator chunks cannot contain any parameter packs. break; - + case DeclaratorChunk::Array: if (Chunk.Arr.NumElts && Chunk.Arr.NumElts->containsUnexpandedParameterPack()) @@ -964,7 +964,7 @@ ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, case LookupResult::Found: ParameterPack = R.getFoundDecl(); break; - + case LookupResult::NotFound: case LookupResult::NotFoundInCurrentInstantiation: if (TypoCorrection Corrected = diff --git a/lib/Sema/SemaType.cpp b/lib/Sema/SemaType.cpp index ac04cecaf774c..284d34b22c04d 100644 --- a/lib/Sema/SemaType.cpp +++ b/lib/Sema/SemaType.cpp @@ -2851,7 +2851,7 @@ static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, case DeclaratorContext::ObjCParameterContext: case DeclaratorContext::ObjCResultContext: case DeclaratorContext::PrototypeContext: - Error = 0; + Error = 0; break; case DeclaratorContext::LambdaExprParameterContext: // In C++14, generic lambdas allow 'auto' in their parameters. @@ -2859,7 +2859,7 @@ static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) Error = 16; else { - // If auto is mentioned in a lambda parameter context, convert it to a + // If auto is mentioned in a lambda parameter context, convert it to a // template parameter type. sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); assert(LSI && "No LambdaScopeInfo on the stack!"); @@ -2877,7 +2877,7 @@ static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TemplateParameterDepth, AutoParameterPosition, /*Identifier*/nullptr, false, IsParameterPack); LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); - // Replace the 'auto' in the function parameter with this invented + // Replace the 'auto' in the function parameter with this invented // template type parameter. // FIXME: Retain some type sugar to indicate that this was written // as 'auto'. @@ -4440,7 +4440,7 @@ static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) << T << 0 /*pointer hint*/; D.setInvalidType(true); - } + } } else if (!S.getLangOpts().HalfArgsAndReturns) { S.Diag(D.getIdentifierLoc(), diag::err_parameters_retval_cannot_have_fp16_type) << 1; @@ -5233,6 +5233,8 @@ static ParsedAttr::Kind getAttrListKind(AttributedType::Kind kind) { return ParsedAttr::AT_ObjCKindOf; case AttributedType::attr_ns_returns_retained: return ParsedAttr::AT_NSReturnsRetained; + case AttributedType::attr_lifetimebound: + return ParsedAttr::AT_LifetimeBound; } llvm_unreachable("unexpected attribute kind!"); } @@ -5332,7 +5334,7 @@ namespace { TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); } - + } void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); @@ -5627,11 +5629,11 @@ Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, } for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { - + if (DependentAddressSpaceTypeLoc DASTL = CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs()); - CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc(); + CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc(); } // An AtomicTypeLoc might be produced by an atomic qualifier in this @@ -5727,13 +5729,13 @@ ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { // Type Attribute Processing //===----------------------------------------------------------------------===// -/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression -/// is uninstantiated. If instantiated it will apply the appropriate address space +/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression +/// is uninstantiated. If instantiated it will apply the appropriate address space /// to the type. This function allows dependent template variables to be used in -/// conjunction with the address_space attribute +/// conjunction with the address_space attribute QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc) { - if (!AddrSpace->isValueDependent()) { + if (!AddrSpace->isValueDependent()) { llvm::APSInt addrSpace(32); if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) { @@ -5783,8 +5785,8 @@ QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, } // A check with similar intentions as checking if a type already has an - // address space except for on a dependent types, basically if the - // current type is already a DependentAddressSpaceType then its already + // address space except for on a dependent types, basically if the + // current type is already a DependentAddressSpaceType then its already // lined up to have another address space on it and we can't have // multiple address spaces on the one pointer indirection if (T->getAs<DependentAddressSpaceType>()) { @@ -6116,7 +6118,7 @@ static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, attr.setInvalid(); return true; } - + // Check the attribute arguments. if (!attr.isArgIdent(0)) { S.Diag(attr.getLoc(), diag::err_attribute_argument_type) @@ -6327,7 +6329,7 @@ static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, << "'__sptr'" << "'__uptr'"; return true; } - + Desugared = AT->getEquivalentType(); AT = dyn_cast<AttributedType>(Desugared); } @@ -6384,7 +6386,7 @@ bool Sema::checkNullabilityTypeSpecifier(QualType &type, << FixItHint::CreateRemoval(nullabilityLoc); break; - } + } // Conflicting nullability. Diag(nullabilityLoc, diag::err_nullability_conflicting) @@ -6430,7 +6432,7 @@ bool Sema::checkNullabilityTypeSpecifier(QualType &type, << DiagNullabilityKind(nullability, isContextSensitive) << type; return true; } - + // For the context-sensitive keywords/Objective-C property // attributes, require that the type be a single-level pointer. if (isContextSensitive) { @@ -6472,7 +6474,7 @@ bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { // Find out if it's an Objective-C object or object pointer type; const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); - const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() + const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() : type->getAs<ObjCObjectType>(); // If not, we can't apply __kindof. @@ -6501,7 +6503,7 @@ bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { } // Build the attributed type to record where __kindof occurred. - type = Context.getAttributedType(AttributedType::attr_objc_kindof, + type = Context.getAttributedType(AttributedType::attr_objc_kindof, type, equivType); @@ -6601,7 +6603,7 @@ static bool distributeNullabilityTypeAttr(TypeProcessingState &state, } return false; - + // Don't walk through these. case DeclaratorChunk::Reference: case DeclaratorChunk::Pipe: @@ -6732,7 +6734,7 @@ static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) return true; - // If this is not a function type, warning will be asserted by subject + // If this is not a function type, warning will be asserted by subject // check. if (!unwrapped.isFunctionType()) return true; @@ -7194,6 +7196,18 @@ static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); } +static void HandleLifetimeBoundAttr(QualType &CurType, + const ParsedAttr &Attr, + Sema &S, Declarator &D) { + if (D.isDeclarationOfFunction()) { + CurType = S.Context.getAttributedType(AttributedType::attr_lifetimebound, + CurType, CurType); + } else { + Attr.diagnoseAppertainsTo(S, nullptr); + } +} + + static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, ParsedAttributesView &attrs) { @@ -7298,6 +7312,13 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type, HandleOpenCLAccessAttr(type, attr, state.getSema()); attr.setUsedAsTypeAttr(); break; + case ParsedAttr::AT_LifetimeBound: + if (TAL == TAL_DeclChunk) { + HandleLifetimeBoundAttr(type, attr, state.getSema(), + state.getDeclarator()); + attr.setUsedAsTypeAttr(); + } + break; MS_TYPE_ATTRS_CASELIST: if (!handleMSPointerTypeQualifierAttr(state, attr, type)) @@ -7972,7 +7993,7 @@ static QualType getDecltypeForExpr(Sema &S, Expr *E) { } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { return PE->getType(); } - + // C++11 [expr.lambda.prim]p18: // Every occurrence of decltype((x)) where x is a possibly // parenthesized id-expression that names an entity of automatic diff --git a/lib/Sema/TreeTransform.h b/lib/Sema/TreeTransform.h index 3b39539910009..de962d775d73b 100644 --- a/lib/Sema/TreeTransform.h +++ b/lib/Sema/TreeTransform.h @@ -1815,7 +1815,7 @@ public: OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { - return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc, + return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc, EndLoc); } @@ -3033,7 +3033,7 @@ public: Sel, Method, LBracLoc, SelectorLocs, RBracLoc, Args); - + } /// Build a new Objective-C ivar reference expression. @@ -6356,7 +6356,7 @@ TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB, TypeLocBuilder TypeArgBuilder; TypeArgBuilder.reserve(PatternLoc.getFullDataSize()); - QualType NewPatternType = getDerived().TransformType(TypeArgBuilder, + QualType NewPatternType = getDerived().TransformType(TypeArgBuilder, PatternLoc); if (NewPatternType.isNull()) return QualType(); @@ -10963,7 +10963,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { TypeSourceInfo *NewCallOpTSI = nullptr; { TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo(); - FunctionProtoTypeLoc OldCallOpFPTL = + FunctionProtoTypeLoc OldCallOpFPTL = OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); TypeLocBuilder NewCallOpTLBuilder; @@ -11059,7 +11059,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { // Rebuild init-captures, including the implied field declaration. if (E->isInitCapture(C)) { - InitCaptureInfoTy InitExprTypePair = + InitCaptureInfoTy InitExprTypePair = InitCaptureExprsAndTypes[C - E->capture_begin()]; ExprResult Init = InitExprTypePair.first; QualType InitQualType = InitExprTypePair.second; diff --git a/lib/Sema/TypeLocBuilder.h b/lib/Sema/TypeLocBuilder.h index a088fe9de667c..536ea1c07f49d 100644 --- a/lib/Sema/TypeLocBuilder.h +++ b/lib/Sema/TypeLocBuilder.h @@ -37,7 +37,7 @@ class TypeLocBuilder { /// The last type pushed on this builder. QualType LastTy; #endif - + /// The inline buffer. enum { BufferMaxAlignment = alignof(void *) }; llvm::AlignedCharArray<BufferMaxAlignment, InlineCapacity> InlineBuffer; @@ -81,7 +81,7 @@ class TypeLocBuilder { #endif Index = Capacity; NumBytesAtAlign4 = NumBytesAtAlign8 = 0; - } + } /// Tell the TypeLocBuilder that the type it is storing has been /// modified in some safe way that doesn't affect type-location information. @@ -90,7 +90,7 @@ class TypeLocBuilder { LastTy = T; #endif } - + /// Pushes space for a new TypeLoc of the given type. Invalidates /// any TypeLocs previously retrieved from this builder. template <class TyLocType> TyLocType push(QualType T) { @@ -112,13 +112,13 @@ class TypeLocBuilder { return DI; } - /// Copies the type-location information to the given AST context and + /// Copies the type-location information to the given AST context and /// returns a \c TypeLoc referring into the AST context. TypeLoc getTypeLocInContext(ASTContext &Context, QualType T) { #ifndef NDEBUG assert(T == LastTy && "type doesn't match last type pushed!"); #endif - + size_t FullDataSize = Capacity - Index; void *Mem = Context.Allocate(FullDataSize); memcpy(Mem, &Buffer[Index], FullDataSize); @@ -135,7 +135,7 @@ private: /// Retrieve a temporary TypeLoc that refers into this \c TypeLocBuilder /// object. /// - /// The resulting \c TypeLoc should only be used so long as the + /// The resulting \c TypeLoc should only be used so long as the /// \c TypeLocBuilder is active and has not had more type information /// pushed into it. TypeLoc getTemporaryTypeLoc(QualType T) { diff --git a/lib/Serialization/ASTReader.cpp b/lib/Serialization/ASTReader.cpp index 9a3b9e1da39a3..723839ff62bf3 100644 --- a/lib/Serialization/ASTReader.cpp +++ b/lib/Serialization/ASTReader.cpp @@ -2632,7 +2632,9 @@ ASTReader::ReadControlBlock(ModuleFile &F, if (M && M->Directory) { // If we're implicitly loading a module, the base directory can't // change between the build and use. - if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { + // Don't emit module relocation error if we have -fno-validate-pch + if (!PP.getPreprocessorOpts().DisablePCHValidation && + F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { const DirectoryEntry *BuildDir = PP.getFileManager().getDirectory(Blob); if (!BuildDir || BuildDir != M->Directory) { @@ -3602,7 +3604,8 @@ ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); auto &Map = PP.getHeaderSearchInfo().getModuleMap(); const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; - if (!ModMap) { + // Don't emit module relocation error if we have -fno-validate-pch + if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) { assert(ImportedBy && "top-level import should be verified"); if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { if (auto *ASTFE = M ? M->getASTFile() : nullptr) { @@ -5039,7 +5042,9 @@ ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { if (!ParentModule) { if (const FileEntry *CurFile = CurrentModule->getASTFile()) { - if (CurFile != F.File) { + // Don't emit module relocation error if we have -fno-validate-pch + if (!PP.getPreprocessorOpts().DisablePCHValidation && + CurFile != F.File) { if (!Diags.isDiagnosticInFlight()) { Diag(diag::err_module_file_conflict) << CurrentModule->getTopLevelModuleName() @@ -6032,7 +6037,7 @@ QualType ASTReader::readTypeRecord(unsigned Index) { } QualType ResultType = readType(*Loc.F, Record, Idx); FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], - (CallingConv)Record[4], Record[5], Record[6], + (CallingConv)Record[4], Record[5], Record[6], Record[7]); return Context.getFunctionNoProtoType(ResultType, Info); } diff --git a/lib/Serialization/ASTReaderDecl.cpp b/lib/Serialization/ASTReaderDecl.cpp index 7e2c4829b14ce..ad37a2978df1a 100644 --- a/lib/Serialization/ASTReaderDecl.cpp +++ b/lib/Serialization/ASTReaderDecl.cpp @@ -569,7 +569,7 @@ void ASTDeclReader::VisitDecl(Decl *D) { Reader.addPendingDeclContextInfo(D, SemaDCIDForTemplateParmDecl, LexicalDCIDForTemplateParmDecl); - D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); + D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); } else { auto *SemaDC = ReadDeclAs<DeclContext>(); auto *LexicalDC = ReadDeclAs<DeclContext>(); @@ -701,7 +701,7 @@ void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) { ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) { RedeclarableResult Redecl = VisitRedeclarable(TD); VisitTypeDecl(TD); - + TD->IdentifierNamespace = Record.readInt(); TD->setTagKind((TagDecl::TagKind)Record.readInt()); if (!isa<CXXRecordDecl>(TD)) @@ -710,7 +710,7 @@ ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) { TD->setFreeStanding(Record.readInt()); TD->setCompleteDefinitionRequired(Record.readInt()); TD->setBraceRange(ReadSourceRange()); - + switch (Record.readInt()) { case 0: break; @@ -1717,7 +1717,7 @@ void ASTDeclReader::ReadCXXDefinitionData( bool IsImplicit = Record.readInt(); auto Kind = static_cast<LambdaCaptureKind>(Record.readInt()); switch (Kind) { - case LCK_StarThis: + case LCK_StarThis: case LCK_This: case LCK_VLAType: *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation()); @@ -2691,8 +2691,8 @@ static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) { return false; } - if (isa<FileScopeAsmDecl>(D) || - isa<ObjCProtocolDecl>(D) || + if (isa<FileScopeAsmDecl>(D) || + isa<ObjCProtocolDecl>(D) || isa<ObjCImplDecl>(D) || isa<ImportDecl>(D) || isa<PragmaCommentDecl>(D) || @@ -3274,7 +3274,7 @@ ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) { } } UpToDate(Name.getAsIdentifierInfo()); - for (IdentifierResolver::iterator I = IdResolver.begin(Name), + for (IdentifierResolver::iterator I = IdResolver.begin(Name), IEnd = IdResolver.end(); I != IEnd; ++I) { if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage)) @@ -3439,22 +3439,16 @@ static void inheritDefaultTemplateArguments(ASTContext &Context, assert(FromTP->size() == ToTP->size() && "merged mismatched templates?"); for (unsigned I = 0, N = FromTP->size(); I != N; ++I) { - NamedDecl *FromParam = FromTP->getParam(N - I - 1); - if (FromParam->isParameterPack()) - continue; - NamedDecl *ToParam = ToTP->getParam(N - I - 1); + NamedDecl *FromParam = FromTP->getParam(I); + NamedDecl *ToParam = ToTP->getParam(I); - if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) { - if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam)) - break; - } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) { - if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam)) - break; - } else { - if (!inheritDefaultTemplateArgument( - Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam)) - break; - } + if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) + inheritDefaultTemplateArgument(Context, FTTP, ToParam); + else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) + inheritDefaultTemplateArgument(Context, FNTTP, ToParam); + else + inheritDefaultTemplateArgument( + Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam); } } @@ -3759,7 +3753,7 @@ Decl *ASTReader::ReadDeclRecord(DeclID ID) { Error("attempt to read a C++ ctor initializer record as a declaration"); return nullptr; case DECL_IMPORT: - // Note: last entry of the ImportDecl record is the number of stored source + // Note: last entry of the ImportDecl record is the number of stored source // locations. D = ImportDecl::CreateDeserialized(Context, ID, Record.back()); break; @@ -3819,7 +3813,7 @@ Decl *ASTReader::ReadDeclRecord(DeclID ID) { if (Class->isThisDeclarationADefinition() || PendingDefinitions.count(Class)) loadObjCCategories(ID, Class); - + // If we have deserialized a declaration that has a definition the // AST consumer might need to know about, queue it. // We don't pass it to the consumer immediately because we may be in recursive @@ -3981,17 +3975,17 @@ namespace { llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap; serialization::GlobalDeclID InterfaceID; unsigned PreviousGeneration; - + void add(ObjCCategoryDecl *Cat) { // Only process each category once. if (!Deserialized.erase(Cat)) return; - + // Check for duplicate categories. if (Cat->getDeclName()) { ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()]; - if (Existing && - Reader.getOwningModuleFile(Existing) + if (Existing && + Reader.getOwningModuleFile(Existing) != Reader.getOwningModuleFile(Cat)) { // FIXME: We should not warn for duplicates in diamond: // @@ -4001,8 +3995,8 @@ namespace { // \ / // // MB // // - // If there are duplicates in ML/MR, there will be warning when - // creating MB *and* when importing MB. We should not warn when + // If there are duplicates in ML/MR, there will be warning when + // creating MB *and* when importing MB. We should not warn when // importing. Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def) << Interface->getDeclName() << Cat->getDeclName(); @@ -4012,7 +4006,7 @@ namespace { Existing = Cat; } } - + // Add this category to the end of the chain. if (Tail) ASTDeclReader::setNextObjCCategory(Tail, Cat); @@ -4020,7 +4014,7 @@ namespace { Interface->setCategoryListRaw(Cat); Tail = Cat; } - + public: ObjCCategoriesVisitor(ASTReader &Reader, ObjCInterfaceDecl *Interface, @@ -4033,7 +4027,7 @@ namespace { for (auto *Cat : Interface->known_categories()) { if (Cat->getDeclName()) NameCategoryMap[Cat->getDeclName()] = Cat; - + // Keep track of the tail of the category list. Tail = Cat; } @@ -4044,8 +4038,8 @@ namespace { // this module file, we're done. if (M.Generation <= PreviousGeneration) return true; - - // Map global ID of the definition down to the local ID used in this + + // Map global ID of the definition down to the local ID used in this // module file. If there is no such mapping, we'll find nothing here // (or in any module it imports). DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID); @@ -4057,7 +4051,7 @@ namespace { const ObjCCategoriesInfo Compare = { LocalID, 0 }; const ObjCCategoriesInfo *Result = std::lower_bound(M.ObjCCategoriesMap, - M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, + M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, Compare); if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap || Result->DefinitionID != LocalID) { @@ -4066,7 +4060,7 @@ namespace { // so suppress further lookup. return Reader.isDeclIDFromModule(InterfaceID, M); } - + // We found something. Dig out all of the categories. unsigned Offset = Result->Offset; unsigned N = M.ObjCCategories[Offset]; diff --git a/lib/Serialization/ASTReaderInternals.h b/lib/Serialization/ASTReaderInternals.h index b5a1493a4f7e8..37a929907dcad 100644 --- a/lib/Serialization/ASTReaderInternals.h +++ b/lib/Serialization/ASTReaderInternals.h @@ -33,7 +33,7 @@ struct HeaderFileInfo; class HeaderSearch; class IdentifierTable; class ObjCMethodDecl; - + namespace serialization { class ModuleFile; @@ -45,7 +45,7 @@ namespace reader { class ASTDeclContextNameLookupTrait { ASTReader &Reader; ModuleFile &F; - + public: // Maximum number of lookup tables we allow before condensing the tables. static const int MaxTables = 4; @@ -141,31 +141,31 @@ public: } static hash_value_type ComputeHash(const internal_key_type& a); - + static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d); // This hopefully will just get inlined and removed by the optimizer. static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + // This hopefully will just get inlined and removed by the optimizer. static const external_key_type& GetExternalKey(const internal_key_type& x) { return x; } - static internal_key_type ReadKey(const unsigned char* d, unsigned n); + static internal_key_type ReadKey(const unsigned char* d, unsigned n); }; /// Class that performs lookup for an identifier stored in an AST file. class ASTIdentifierLookupTrait : public ASTIdentifierLookupTraitBase { ASTReader &Reader; ModuleFile &F; - + // If we know the IdentifierInfo in advance, it is here and we will // not build a new one. Used when deserializing information about an // identifier that was constructed before the AST file was read. IdentifierInfo *KnownII; - + public: using data_type = IdentifierInfo *; @@ -176,12 +176,12 @@ public: data_type ReadData(const internal_key_type& k, const unsigned char* d, unsigned DataLen); - + IdentID ReadIdentifierID(const unsigned char *d); ASTReader &getReader() const { return Reader; } }; - + /// The on-disk hash table used to contain information about /// all of the identifiers in the program. using ASTIdentifierLookupTable = @@ -192,7 +192,7 @@ using ASTIdentifierLookupTable = class ASTSelectorLookupTrait { ASTReader &Reader; ModuleFile &F; - + public: struct data_type { SelectorID ID; @@ -203,40 +203,40 @@ public: SmallVector<ObjCMethodDecl *, 2> Instance; SmallVector<ObjCMethodDecl *, 2> Factory; }; - + using external_key_type = Selector; using internal_key_type = external_key_type; using hash_value_type = unsigned; using offset_type = unsigned; - + ASTSelectorLookupTrait(ASTReader &Reader, ModuleFile &F) : Reader(Reader), F(F) {} - + static bool EqualKey(const internal_key_type& a, const internal_key_type& b) { return a == b; } - + static hash_value_type ComputeHash(Selector Sel); - + static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d); - + internal_key_type ReadKey(const unsigned char* d, unsigned); data_type ReadData(Selector, const unsigned char* d, unsigned DataLen); }; - + /// The on-disk hash table used for the global method pool. using ASTSelectorLookupTable = llvm::OnDiskChainedHashTable<ASTSelectorLookupTrait>; - + /// Trait class used to search the on-disk hash table containing all of /// the header search information. /// -/// The on-disk hash table contains a mapping from each header path to +/// The on-disk hash table contains a mapping from each header path to /// information about that header (how many times it has been included, its /// controlling macro, etc.). Note that we actually hash based on the size /// and mtime, and support "deep" comparisons of file names based on current @@ -259,31 +259,31 @@ public: }; using internal_key_ref = const internal_key_type &; - + using data_type = HeaderFileInfo; using hash_value_type = unsigned; using offset_type = unsigned; - + HeaderFileInfoTrait(ASTReader &Reader, ModuleFile &M, HeaderSearch *HS, const char *FrameworkStrings) : Reader(Reader), M(M), HS(HS), FrameworkStrings(FrameworkStrings) {} - + static hash_value_type ComputeHash(internal_key_ref ikey); internal_key_type GetInternalKey(const FileEntry *FE); bool EqualKey(internal_key_ref a, internal_key_ref b); - + static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d); - + static internal_key_type ReadKey(const unsigned char *d, unsigned); - + data_type ReadData(internal_key_ref,const unsigned char *d, unsigned DataLen); }; /// The on-disk hash table used for known header files. using HeaderFileInfoLookupTable = llvm::OnDiskChainedHashTable<HeaderFileInfoTrait>; - + } // namespace reader } // namespace serialization diff --git a/lib/Serialization/ASTWriterDecl.cpp b/lib/Serialization/ASTWriterDecl.cpp index 77e578f6bc57e..7286f2cac1785 100644 --- a/lib/Serialization/ASTWriterDecl.cpp +++ b/lib/Serialization/ASTWriterDecl.cpp @@ -271,7 +271,7 @@ void ASTDeclWriter::Visit(Decl *D) { // Handle FunctionDecl's body here and write it after all other Stmts/Exprs // have been written. We want it last because we will not read it back when - // retrieving it from the AST, we'll just lazily set the offset. + // retrieving it from the AST, we'll just lazily set the offset. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { Record.push_back(FD->doesThisDeclarationHaveABody()); if (FD->doesThisDeclarationHaveABody()) @@ -526,10 +526,10 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { VisitDeclaratorDecl(D); Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName()); Record.push_back(D->getIdentifierNamespace()); - + // FunctionDecl's body is handled last at ASTWriterDecl::Visit, // after everything else is written. - + Record.push_back((int)D->SClass); // FIXME: stable encoding Record.push_back(D->IsInline); Record.push_back(D->IsInlineSpecified); @@ -576,10 +576,10 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { Record.AddDeclRef(FTSInfo->getTemplate()); Record.push_back(FTSInfo->getTemplateSpecializationKind()); - + // Template arguments. Record.AddTemplateArgumentList(FTSInfo->TemplateArguments); - + // Template args as written. Record.push_back(FTSInfo->TemplateArgumentsAsWritten != nullptr); if (FTSInfo->TemplateArgumentsAsWritten) { @@ -591,7 +591,7 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { Record.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->LAngleLoc); Record.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->RAngleLoc); } - + Record.AddSourceLocation(FTSInfo->getPointOfInstantiation()); if (D->isCanonicalDecl()) { @@ -604,12 +604,12 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { DependentFunctionTemplateSpecializationInfo * DFTSInfo = D->getDependentSpecializationInfo(); - + // Templates. Record.push_back(DFTSInfo->getNumTemplates()); for (int i=0, e = DFTSInfo->getNumTemplates(); i != e; ++i) Record.AddDeclRef(DFTSInfo->getTemplate(i)); - + // Templates args. Record.push_back(DFTSInfo->getNumTemplateArgs()); for (int i=0, e = DFTSInfo->getNumTemplateArgs(); i != e; ++i) @@ -707,7 +707,7 @@ void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { if (D->isThisDeclarationADefinition()) { // Write the DefinitionData ObjCInterfaceDecl::DefinitionData &Data = D->data(); - + Record.AddTypeSourceInfo(D->getSuperClassTInfo()); Record.AddSourceLocation(D->getEndOfDefinitionLoc()); Record.push_back(Data.HasDesignatedInitializers); @@ -718,7 +718,7 @@ void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { Record.AddDeclRef(P); for (const auto &PL : D->protocol_locs()) Record.AddSourceLocation(PL); - + // Write out the protocols that are transitively referenced. Record.push_back(Data.AllReferencedProtocols.size()); for (ObjCList<ObjCProtocolDecl>::iterator @@ -727,17 +727,17 @@ void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { P != PEnd; ++P) Record.AddDeclRef(*P); - + if (ObjCCategoryDecl *Cat = D->getCategoryListRaw()) { // Ensure that we write out the set of categories for this class. Writer.ObjCClassesWithCategories.insert(D); - + // Make sure that the categories get serialized. for (; Cat; Cat = Cat->getNextClassCategoryRaw()) (void)Writer.GetDeclRef(Cat); } - } - + } + Code = serialization::DECL_OBJC_INTERFACE; } @@ -765,7 +765,7 @@ void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) { void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { VisitRedeclarable(D); VisitObjCContainerDecl(D); - + Record.push_back(D->isThisDeclarationADefinition()); if (D->isThisDeclarationADefinition()) { Record.push_back(D->protocol_size()); @@ -774,7 +774,7 @@ void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { for (const auto &PL : D->protocol_locs()) Record.AddSourceLocation(PL); } - + Code = serialization::DECL_OBJC_PROTOCOL; } @@ -964,7 +964,7 @@ void ASTDeclWriter::VisitVarDecl(VarDecl *D) { if (ModulesCodegen) Writer.ModularCodegenDecls.push_back(Writer.GetDeclRef(D)); } - + enum { VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization }; @@ -1158,7 +1158,7 @@ void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) { Record.AddDeclRef(D->getAnonymousNamespace()); Code = serialization::DECL_NAMESPACE; - if (Writer.hasChain() && D->isAnonymousNamespace() && + if (Writer.hasChain() && D->isAnonymousNamespace() && D == D->getMostRecentDecl()) { // This is a most recent reopening of the anonymous namespace. If its parent // is in a previous PCH (or is the TU), mark that parent for update, because @@ -1412,7 +1412,7 @@ void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) { if (D->getInstantiatedFromMemberTemplate()) Record.push_back(D->isMemberSpecialization()); } - + VisitTemplateDecl(D); Record.push_back(D->getIdentifierNamespace()); } @@ -1447,7 +1447,7 @@ void ASTDeclWriter::VisitClassTemplateSpecializationDecl( Record.push_back(D->isCanonicalDecl()); if (D->isCanonicalDecl()) { - // When reading, we'll add it to the folding set of the following template. + // When reading, we'll add it to the folding set of the following template. Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl()); } @@ -1573,18 +1573,18 @@ void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { // memory. if (D->isExpandedParameterPack()) Record.push_back(D->getNumExpansionTypes()); - + VisitDeclaratorDecl(D); // TemplateParmPosition. Record.push_back(D->getDepth()); Record.push_back(D->getPosition()); - + if (D->isExpandedParameterPack()) { for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { Record.AddTypeRef(D->getExpansionType(I)); Record.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I)); } - + Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK; } else { // Rest of NonTypeTemplateParmDecl. @@ -1709,7 +1709,7 @@ void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) { Record.AddDeclRef(FirstLocal); } - // Make sure that we serialize both the previous and the most-recent + // Make sure that we serialize both the previous and the most-recent // declarations, which (transitively) ensures that all declarations in the // chain get serialized. // @@ -2252,11 +2252,11 @@ void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) { serialization::DeclID &IDR = DeclIDs[D]; if (IDR == 0) IDR = NextDeclID++; - + ID = IDR; assert(ID >= FirstDeclID && "invalid decl ID"); - + RecordData Record; ASTDeclWriter W(*this, Context, Record); diff --git a/lib/Serialization/ASTWriterStmt.cpp b/lib/Serialization/ASTWriterStmt.cpp index 3efb6482dd420..48c3f79a43806 100644 --- a/lib/Serialization/ASTWriterStmt.cpp +++ b/lib/Serialization/ASTWriterStmt.cpp @@ -247,7 +247,7 @@ void ASTStmtWriter::VisitGCCAsmStmt(GCCAsmStmt *S) { Record.AddStmt(S->getAsmString()); // Outputs - for (unsigned I = 0, N = S->getNumOutputs(); I != N; ++I) { + for (unsigned I = 0, N = S->getNumOutputs(); I != N; ++I) { Record.AddIdentifierRef(S->getOutputIdentifier(I)); Record.AddStmt(S->getOutputConstraintLiteral(I)); Record.AddStmt(S->getOutputExpr(I)); @@ -1000,7 +1000,7 @@ void ASTStmtWriter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { Record.push_back(NumExpansions); } } - + Record.AddDeclRef(E->getDictWithObjectsMethod()); Record.AddSourceRange(E->getSourceRange()); Code = serialization::EXPR_OBJC_DICTIONARY_LITERAL; @@ -1064,7 +1064,7 @@ void ASTStmtWriter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { Record.push_back(2); Record.AddDeclRef(E->getClassReceiver()); } - + Code = serialization::EXPR_OBJC_PROPERTY_REF_EXPR; } @@ -1075,7 +1075,7 @@ void ASTStmtWriter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) { Record.AddStmt(E->getKeyExpr()); Record.AddDeclRef(E->getAtIndexMethodDecl()); Record.AddDeclRef(E->setAtIndexMethodDecl()); - + Code = serialization::EXPR_OBJC_SUBSCRIPT_REF_EXPR; } @@ -1108,9 +1108,9 @@ void ASTStmtWriter::VisitObjCMessageExpr(ObjCMessageExpr *E) { Record.AddDeclRef(E->getMethodDecl()); } else { Record.push_back(0); - Record.AddSelectorRef(E->getSelector()); + Record.AddSelectorRef(E->getSelector()); } - + Record.AddSourceLocation(E->getLeftLoc()); Record.AddSourceLocation(E->getRightLoc()); @@ -1296,14 +1296,14 @@ void ASTStmtWriter::VisitLambdaExpr(LambdaExpr *E) { Record.push_back(E->ExplicitParams); Record.push_back(E->ExplicitResultType); Record.AddSourceLocation(E->ClosingBrace); - + // Add capture initializers. for (LambdaExpr::capture_init_iterator C = E->capture_init_begin(), CEnd = E->capture_init_end(); C != CEnd; ++C) { Record.AddStmt(*C); } - + Code = serialization::EXPR_LAMBDA; } @@ -1450,7 +1450,7 @@ void ASTStmtWriter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { Record.AddDeclRef(E->getOperatorDelete()); Record.AddStmt(E->getArgument()); Record.AddSourceLocation(E->getSourceRange().getBegin()); - + Code = serialization::EXPR_CXX_DELETE; } @@ -2691,7 +2691,7 @@ void ASTWriter::WriteSubStmt(Stmt *S) { RecordData Record; ASTStmtWriter Writer(*this, Record); ++NumStatements; - + if (!S) { Stream.EmitRecord(serialization::STMT_NULL_PTR, Record); return; @@ -2724,7 +2724,7 @@ void ASTWriter::WriteSubStmt(Stmt *S) { #endif Writer.Visit(S); - + uint64_t Offset = Writer.Emit(); SubStmtEntries[S] = Offset; } @@ -2739,7 +2739,7 @@ void ASTRecordWriter::FlushStmts() { for (unsigned I = 0, N = StmtsToEmit.size(); I != N; ++I) { Writer->WriteSubStmt(StmtsToEmit[I]); - + assert(N == StmtsToEmit.size() && "record modified while being written!"); // Note that we are at the end of a full expression. Any diff --git a/lib/Serialization/Module.cpp b/lib/Serialization/Module.cpp index f0ada809ad99e..580e46e4f2400 100644 --- a/lib/Serialization/Module.cpp +++ b/lib/Serialization/Module.cpp @@ -30,16 +30,16 @@ ModuleFile::~ModuleFile() { } template<typename Key, typename Offset, unsigned InitialCapacity> -static void +static void dumpLocalRemap(StringRef Name, const ContinuousRangeMap<Key, Offset, InitialCapacity> &Map) { if (Map.begin() == Map.end()) return; - + using MapType = ContinuousRangeMap<Key, Offset, InitialCapacity>; llvm::errs() << " " << Name << ":\n"; - for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); + for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); I != IEnd; ++I) { llvm::errs() << " " << I->first << " -> " << I->second << "\n"; } @@ -56,12 +56,12 @@ LLVM_DUMP_METHOD void ModuleFile::dump() { } llvm::errs() << "\n"; } - + // Remapping tables. - llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset + llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset << '\n'; dumpLocalRemap("Source location offset local -> global map", SLocRemap); - + llvm::errs() << " Base identifier ID: " << BaseIdentifierID << '\n' << " Number of identifiers: " << LocalNumIdentifiers << '\n'; dumpLocalRemap("Identifier ID local -> global map", IdentifierRemap); @@ -77,18 +77,18 @@ LLVM_DUMP_METHOD void ModuleFile::dump() { llvm::errs() << " Base selector ID: " << BaseSelectorID << '\n' << " Number of selectors: " << LocalNumSelectors << '\n'; dumpLocalRemap("Selector ID local -> global map", SelectorRemap); - + llvm::errs() << " Base preprocessed entity ID: " << BasePreprocessedEntityID - << '\n' - << " Number of preprocessed entities: " + << '\n' + << " Number of preprocessed entities: " << NumPreprocessedEntities << '\n'; - dumpLocalRemap("Preprocessed entity ID local -> global map", + dumpLocalRemap("Preprocessed entity ID local -> global map", PreprocessedEntityRemap); - + llvm::errs() << " Base type index: " << BaseTypeIndex << '\n' << " Number of types: " << LocalNumTypes << '\n'; dumpLocalRemap("Type index local -> global map", TypeRemap); - + llvm::errs() << " Base decl ID: " << BaseDeclID << '\n' << " Number of decls: " << LocalNumDecls << '\n'; dumpLocalRemap("Decl ID local -> global map", DeclRemap); diff --git a/lib/Serialization/ModuleManager.cpp b/lib/Serialization/ModuleManager.cpp index b512fa452cc13..57ebaca10c998 100644 --- a/lib/Serialization/ModuleManager.cpp +++ b/lib/Serialization/ModuleManager.cpp @@ -340,7 +340,7 @@ void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor, unsigned N = size(); VisitOrder.clear(); VisitOrder.reserve(N); - + // Record the number of incoming edges for each module. When we // encounter a module with no incoming edges, push it into the queue // to seed the queue. @@ -477,21 +477,21 @@ namespace llvm { static ChildIteratorType child_end(NodeRef Node) { return Node->Imports.end(); } - + static nodes_iterator nodes_begin(const ModuleManager &Manager) { return nodes_iterator(Manager.begin()); } - + static nodes_iterator nodes_end(const ModuleManager &Manager) { return nodes_iterator(Manager.end()); } }; - + template<> struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits { explicit DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {} - + static bool renderGraphFromBottomUp() { return true; } std::string getNodeLabel(ModuleFile *M, const ModuleManager&) { diff --git a/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 278452ec994a6..12a576e5d80d5 100644 --- a/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -552,6 +552,7 @@ void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State, BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get()); auto Report = llvm::make_unique<BugReport>(*BT, WarningMsg, N); + Report->addRange(S->getSourceRange()); bugreporter::trackNullOrUndefValue(N, S, *Report); C.emitReport(std::move(Report)); } diff --git a/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp b/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp index ed877ab345189..29677f737f5cf 100644 --- a/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp @@ -91,37 +91,53 @@ public: ReserveFn("reserve"), ResizeFn("resize"), ShrinkToFitFn("shrink_to_fit"), SwapFn("swap") {} - /// Check whether the function called on the container object is a - /// member function that potentially invalidates pointers referring - /// to the objects's internal buffer. - bool mayInvalidateBuffer(const CallEvent &Call) const; - - /// Record the connection between the symbol returned by c_str() and the - /// corresponding string object region in the ProgramState. Mark the symbol - /// released if the string object is destroyed. + /// Check if the object of this member function call is a `basic_string`. + bool isCalledOnStringObject(const CXXInstanceCall *ICall) const; + + /// Check whether the called member function potentially invalidates + /// pointers referring to the container object's inner buffer. + bool isInvalidatingMemberFunction(const CallEvent &Call) const; + + /// Mark pointer symbols associated with the given memory region released + /// in the program state. + void markPtrSymbolsReleased(const CallEvent &Call, ProgramStateRef State, + const MemRegion *ObjRegion, + CheckerContext &C) const; + + /// Standard library functions that take a non-const `basic_string` argument by + /// reference may invalidate its inner pointers. Check for these cases and + /// mark the pointers released. + void checkFunctionArguments(const CallEvent &Call, ProgramStateRef State, + CheckerContext &C) const; + + /// Record the connection between raw pointers referring to a container + /// object's inner buffer and the object's memory region in the program state. + /// Mark potentially invalidated pointers released. void checkPostCall(const CallEvent &Call, CheckerContext &C) const; - /// Clean up the ProgramState map. + /// Clean up the program state map. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; }; } // end anonymous namespace -// [string.require] -// -// "References, pointers, and iterators referring to the elements of a -// basic_string sequence may be invalidated by the following uses of that -// basic_string object: -// -// -- TODO: As an argument to any standard library function taking a reference -// to non-const basic_string as an argument. For example, as an argument to -// non-member functions swap(), operator>>(), and getline(), or as an argument -// to basic_string::swap(). -// -// -- Calling non-const member functions, except operator[], at, front, back, -// begin, rbegin, end, and rend." -// -bool InnerPointerChecker::mayInvalidateBuffer(const CallEvent &Call) const { +bool InnerPointerChecker::isCalledOnStringObject( + const CXXInstanceCall *ICall) const { + const auto *ObjRegion = + dyn_cast_or_null<TypedValueRegion>(ICall->getCXXThisVal().getAsRegion()); + if (!ObjRegion) + return false; + + QualType ObjTy = ObjRegion->getValueType(); + if (ObjTy.isNull() || + ObjTy->getAsCXXRecordDecl()->getName() != "basic_string") + return false; + + return true; +} + +bool InnerPointerChecker::isInvalidatingMemberFunction( + const CallEvent &Call) const { if (const auto *MemOpCall = dyn_cast<CXXMemberOperatorCall>(&Call)) { OverloadedOperatorKind Opc = MemOpCall->getOriginExpr()->getOperator(); if (Opc == OO_Equal || Opc == OO_PlusEqual) @@ -137,53 +153,104 @@ bool InnerPointerChecker::mayInvalidateBuffer(const CallEvent &Call) const { Call.isCalled(SwapFn)); } -void InnerPointerChecker::checkPostCall(const CallEvent &Call, - CheckerContext &C) const { - const auto *ICall = dyn_cast<CXXInstanceCall>(&Call); - if (!ICall) +void InnerPointerChecker::markPtrSymbolsReleased(const CallEvent &Call, + ProgramStateRef State, + const MemRegion *MR, + CheckerContext &C) const { + if (const PtrSet *PS = State->get<RawPtrMap>(MR)) { + const Expr *Origin = Call.getOriginExpr(); + for (const auto Symbol : *PS) { + // NOTE: `Origin` may be null, and will be stored so in the symbol's + // `RefState` in MallocChecker's `RegionState` program state map. + State = allocation_state::markReleased(State, Symbol, Origin); + } + State = State->remove<RawPtrMap>(MR); + C.addTransition(State); return; + } +} - SVal Obj = ICall->getCXXThisVal(); - const auto *ObjRegion = dyn_cast_or_null<TypedValueRegion>(Obj.getAsRegion()); - if (!ObjRegion) - return; +void InnerPointerChecker::checkFunctionArguments(const CallEvent &Call, + ProgramStateRef State, + CheckerContext &C) const { + if (const auto *FC = dyn_cast<AnyFunctionCall>(&Call)) { + const FunctionDecl *FD = FC->getDecl(); + if (!FD || !FD->isInStdNamespace()) + return; - auto *TypeDecl = ObjRegion->getValueType()->getAsCXXRecordDecl(); - if (TypeDecl->getName() != "basic_string") - return; + for (unsigned I = 0, E = FD->getNumParams(); I != E; ++I) { + QualType ParamTy = FD->getParamDecl(I)->getType(); + if (!ParamTy->isReferenceType() || + ParamTy->getPointeeType().isConstQualified()) + continue; - ProgramStateRef State = C.getState(); + // In case of member operator calls, `this` is counted as an + // argument but not as a parameter. + bool isaMemberOpCall = isa<CXXMemberOperatorCall>(FC); + unsigned ArgI = isaMemberOpCall ? I+1 : I; - if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) { - SVal RawPtr = Call.getReturnValue(); - if (SymbolRef Sym = RawPtr.getAsSymbol(/*IncludeBaseRegions=*/true)) { - // Start tracking this raw pointer by adding it to the set of symbols - // associated with this container object in the program state map. - PtrSet::Factory &F = State->getStateManager().get_context<PtrSet>(); - const PtrSet *SetPtr = State->get<RawPtrMap>(ObjRegion); - PtrSet Set = SetPtr ? *SetPtr : F.getEmptySet(); - assert(C.wasInlined || !Set.contains(Sym)); - Set = F.add(Set, Sym); - State = State->set<RawPtrMap>(ObjRegion, Set); - C.addTransition(State); + SVal Arg = FC->getArgSVal(ArgI); + const auto *ArgRegion = + dyn_cast_or_null<TypedValueRegion>(Arg.getAsRegion()); + if (!ArgRegion) + continue; + + markPtrSymbolsReleased(Call, State, ArgRegion, C); } - return; } +} - if (mayInvalidateBuffer(Call)) { - if (const PtrSet *PS = State->get<RawPtrMap>(ObjRegion)) { - // Mark all pointer symbols associated with the deleted object released. - const Expr *Origin = Call.getOriginExpr(); - for (const auto Symbol : *PS) { - // NOTE: `Origin` may be null, and will be stored so in the symbol's - // `RefState` in MallocChecker's `RegionState` program state map. - State = allocation_state::markReleased(State, Symbol, Origin); +// [string.require] +// +// "References, pointers, and iterators referring to the elements of a +// basic_string sequence may be invalidated by the following uses of that +// basic_string object: +// +// -- As an argument to any standard library function taking a reference +// to non-const basic_string as an argument. For example, as an argument to +// non-member functions swap(), operator>>(), and getline(), or as an argument +// to basic_string::swap(). +// +// -- Calling non-const member functions, except operator[], at, front, back, +// begin, rbegin, end, and rend." + +void InnerPointerChecker::checkPostCall(const CallEvent &Call, + CheckerContext &C) const { + ProgramStateRef State = C.getState(); + + if (const auto *ICall = dyn_cast<CXXInstanceCall>(&Call)) { + if (isCalledOnStringObject(ICall)) { + const auto *ObjRegion = dyn_cast_or_null<TypedValueRegion>( + ICall->getCXXThisVal().getAsRegion()); + + if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) { + SVal RawPtr = Call.getReturnValue(); + if (SymbolRef Sym = RawPtr.getAsSymbol(/*IncludeBaseRegions=*/true)) { + // Start tracking this raw pointer by adding it to the set of symbols + // associated with this container object in the program state map. + + PtrSet::Factory &F = State->getStateManager().get_context<PtrSet>(); + const PtrSet *SetPtr = State->get<RawPtrMap>(ObjRegion); + PtrSet Set = SetPtr ? *SetPtr : F.getEmptySet(); + assert(C.wasInlined || !Set.contains(Sym)); + Set = F.add(Set, Sym); + + State = State->set<RawPtrMap>(ObjRegion, Set); + C.addTransition(State); + } + return; + } + + // Check [string.require] / second point. + if (isInvalidatingMemberFunction(Call)) { + markPtrSymbolsReleased(Call, State, ObjRegion, C); + return; } - State = State->remove<RawPtrMap>(ObjRegion); - C.addTransition(State); - return; } } + + // Check [string.require] / first point. + checkFunctionArguments(Call, State, C); } void InnerPointerChecker::checkDeadSymbols(SymbolReaper &SymReaper, @@ -216,7 +283,6 @@ InnerPointerChecker::InnerPointerBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, BugReport &BR) { - if (!isSymbolTracked(N->getState(), PtrToBuf) || isSymbolTracked(PrevN->getState(), PtrToBuf)) return nullptr; diff --git a/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp b/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp index 56c250cd16783..520c32e1c7703 100644 --- a/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp @@ -291,6 +291,7 @@ const ContainerData *getContainerData(ProgramStateRef State, const MemRegion *Cont); ProgramStateRef setContainerData(ProgramStateRef State, const MemRegion *Cont, const ContainerData &CData); +bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont); bool isOutOfRange(ProgramStateRef State, const IteratorPosition &Pos); bool isZero(ProgramStateRef State, const NonLoc &Val); } // namespace @@ -536,7 +537,11 @@ void IteratorChecker::checkDeadSymbols(SymbolReaper &SR, auto ContMap = State->get<ContainerMap>(); for (const auto Cont : ContMap) { if (!SR.isLiveRegion(Cont.first)) { - State = State->remove<ContainerMap>(Cont.first); + // We must keep the container data while it has live iterators to be able + // to compare them to the begin and the end of the container. + if (!hasLiveIterators(State, Cont.first)) { + State = State->remove<ContainerMap>(Cont.first); + } } } @@ -546,6 +551,8 @@ void IteratorChecker::checkDeadSymbols(SymbolReaper &SR, State = State->remove<IteratorComparisonMap>(Comp.first); } } + + C.addTransition(State); } ProgramStateRef IteratorChecker::evalAssume(ProgramStateRef State, SVal Cond, @@ -1188,6 +1195,22 @@ ProgramStateRef relateIteratorPositions(ProgramStateRef State, return NewState; } +bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont) { + auto RegionMap = State->get<IteratorRegionMap>(); + for (const auto Reg : RegionMap) { + if (Reg.second.getContainer() == Cont) + return true; + } + + auto SymbolMap = State->get<IteratorSymbolMap>(); + for (const auto Sym : SymbolMap) { + if (Sym.second.getContainer() == Cont) + return true; + } + + return false; +} + bool isZero(ProgramStateRef State, const NonLoc &Val) { auto &BVF = State->getBasicVals(); return compare(State, Val, diff --git a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index 8f07f413e81f6..ebaf79a780c07 100644 --- a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -179,11 +179,11 @@ public: II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr), II_if_nameindex(nullptr), II_if_freenameindex(nullptr), II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr), - II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr), - II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr), - II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr), - II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr), - II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr), + II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr), + II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr), + II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr), + II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr), + II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr), II_g_try_realloc_n(nullptr) {} /// In pessimistic mode, the checker assumes that it does not know which @@ -248,11 +248,11 @@ private: *II_realloc, *II_calloc, *II_valloc, *II_reallocf, *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc, *II_if_nameindex, *II_if_freenameindex, *II_wcsdup, - *II_win_wcsdup, *II_g_malloc, *II_g_malloc0, - *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0, - *II_g_try_realloc, *II_g_free, *II_g_memdup, - *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n, - *II_g_try_malloc_n, *II_g_try_malloc0_n, + *II_win_wcsdup, *II_g_malloc, *II_g_malloc0, + *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0, + *II_g_try_realloc, *II_g_free, *II_g_memdup, + *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n, + *II_g_try_malloc_n, *II_g_try_malloc0_n, *II_g_try_realloc_n; mutable Optional<uint64_t> KernelZeroFlagVal; @@ -346,7 +346,7 @@ private: ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE, bool FreesMemOnFailure, - ProgramStateRef State, + ProgramStateRef State, bool SuffixWithN = false) const; static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks, const Expr *BlockBytes); @@ -652,7 +652,7 @@ bool MallocChecker::isCMemFunction(const FunctionDecl *FD, initIdentifierInfo(C); if (Family == AF_Malloc && CheckFree) { - if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf || + if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf || FunI == II_g_free) return true; } @@ -662,12 +662,12 @@ bool MallocChecker::isCMemFunction(const FunctionDecl *FD, FunI == II_calloc || FunI == II_valloc || FunI == II_strdup || FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup || FunI == II_win_wcsdup || FunI == II_kmalloc || - FunI == II_g_malloc || FunI == II_g_malloc0 || - FunI == II_g_realloc || FunI == II_g_try_malloc || + FunI == II_g_malloc || FunI == II_g_malloc0 || + FunI == II_g_realloc || FunI == II_g_try_malloc || FunI == II_g_try_malloc0 || FunI == II_g_try_realloc || - FunI == II_g_memdup || FunI == II_g_malloc_n || - FunI == II_g_malloc0_n || FunI == II_g_realloc_n || - FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n || + FunI == II_g_memdup || FunI == II_g_malloc_n || + FunI == II_g_malloc0_n || FunI == II_g_realloc_n || + FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n || FunI == II_g_try_realloc_n) return true; } @@ -873,7 +873,7 @@ void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { return; State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State); State = ProcessZeroAllocation(C, CE, 0, State); - } else if (FunI == II_realloc || FunI == II_g_realloc || + } else if (FunI == II_realloc || FunI == II_g_realloc || FunI == II_g_try_realloc) { State = ReallocMemAux(C, CE, false, State); State = ProcessZeroAllocation(C, CE, 1, State); @@ -936,7 +936,7 @@ void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { return; State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State); State = ProcessZeroAllocation(C, CE, 1, State); - } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n || + } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n || FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) { if (CE->getNumArgs() < 2) return; @@ -2930,6 +2930,11 @@ std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode( OS << MemCallE->getMethodDecl()->getNameAsString(); } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) { OS << OpCallE->getDirectCallee()->getNameAsString(); + } else if (const auto *CallE = dyn_cast<CallExpr>(S)) { + auto &CEMgr = BRC.getStateManager().getCallEventManager(); + CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC); + const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl()); + OS << (D ? D->getNameAsString() : "unknown"); } OS << "'"; } diff --git a/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp b/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp index 2c1e139330d68..9c85c09837239 100644 --- a/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp @@ -4000,7 +4000,7 @@ void RetainCountChecker::checkEndFunction(const ReturnStmt *RS, // Don't process anything within synthesized bodies. const LocationContext *LCtx = Pred->getLocationContext(); if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) { - assert(!LCtx->inTopFrame()); + assert(!LCtx->inTopFrame()); return; } diff --git a/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp b/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp index 64b61a0213d28..55516a34d1a78 100644 --- a/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp @@ -45,9 +45,9 @@ const char * RunLoopBind = "NSRunLoopM"; const char * RunLoopRunBind = "RunLoopRunM"; const char * OtherMsgBind = "OtherMessageSentM"; const char * AutoreleasePoolBind = "AutoreleasePoolM"; +const char * OtherStmtAutoreleasePoolBind = "OtherAutoreleasePoolM"; -class RunLoopAutoreleaseLeakChecker : public Checker< - check::ASTCodeBody> { +class RunLoopAutoreleaseLeakChecker : public Checker<check::ASTCodeBody> { public: void checkASTCodeBody(const Decl *D, @@ -66,6 +66,8 @@ static TriBoolTy seenBeforeRec(const Stmt *Parent, const Stmt *A, const Stmt *B, MemoizationMapTy &Memoization) { for (const Stmt *C : Parent->children()) { + if (!C) continue; + if (C == A) return true; @@ -110,17 +112,20 @@ static void emitDiagnostics(BoundNodes &Match, const auto *AP = Match.getNodeAs<ObjCAutoreleasePoolStmt>(AutoreleasePoolBind); + const auto *OAP = + Match.getNodeAs<ObjCAutoreleasePoolStmt>(OtherStmtAutoreleasePoolBind); bool HasAutoreleasePool = (AP != nullptr); const auto *RL = Match.getNodeAs<ObjCMessageExpr>(RunLoopBind); const auto *RLR = Match.getNodeAs<Stmt>(RunLoopRunBind); assert(RLR && "Run loop launch not found"); - assert(ME != RLR); - if (HasAutoreleasePool && seenBefore(AP, RLR, ME)) + + // Launch of run loop occurs before the message-sent expression is seen. + if (seenBefore(DeclBody, RLR, ME)) return; - if (!HasAutoreleasePool && seenBefore(DeclBody, RLR, ME)) + if (HasAutoreleasePool && (OAP != AP)) return; PathDiagnosticLocation Location = PathDiagnosticLocation::createBegin( @@ -169,7 +174,8 @@ static void checkTempObjectsInSamePool(const Decl *D, AnalysisManager &AM, BugReporter &BR, const RunLoopAutoreleaseLeakChecker *Chkr) { StatementMatcher RunLoopRunM = getRunLoopRunM(); - StatementMatcher OtherMessageSentM = getOtherMessageSentM(); + StatementMatcher OtherMessageSentM = getOtherMessageSentM( + hasAncestor(autoreleasePoolStmt().bind(OtherStmtAutoreleasePoolBind))); StatementMatcher RunLoopInAutorelease = autoreleasePoolStmt( diff --git a/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp index feae9e59b343a..e7a20fa03a4ae 100644 --- a/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -129,7 +129,7 @@ bool StackAddrEscapeChecker::isSemaphoreCaptured(const BlockDecl &B) const { for (const auto &C : B.captures()) { const auto *T = C.getVariable()->getType()->getAs<TypedefType>(); if (T && T->getDecl()->getIdentifier() == dispatch_semaphore_tII) - return true; + return true; } return false; } @@ -175,9 +175,9 @@ void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures( // There is a not-too-uncommon idiom // where a block passed to dispatch_async captures a semaphore // and then the thread (which called dispatch_async) is blocked on waiting - // for the completion of the execution of the block - // via dispatch_semaphore_wait. To avoid false-positives (for now) - // we ignore all the blocks which have captured + // for the completion of the execution of the block + // via dispatch_semaphore_wait. To avoid false-positives (for now) + // we ignore all the blocks which have captured // a variable of the type "dispatch_semaphore_t". if (isSemaphoreCaptured(*B.getDecl())) return; @@ -263,7 +263,7 @@ void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS, if (const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R)) checkReturnedBlockCaptures(*B, C); - if (!isa<StackSpaceRegion>(R->getMemorySpace()) || + if (!isa<StackSpaceRegion>(R->getMemorySpace()) || isNotInCurrentFrame(R, C) || isArcManagedBlock(R, C)) return; diff --git a/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp index c87bc685d8b96..d4d33c1746ced 100644 --- a/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp +++ b/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp @@ -269,6 +269,8 @@ namespace { /// pointer dereference outside. class NoStoreFuncVisitor final : public BugReporterVisitor { const SubRegion *RegionOfInterest; + const SourceManager &SM; + const PrintingPolicy &PP; static constexpr const char *DiagnosticsMsg = "Returning without writing to '"; @@ -284,7 +286,10 @@ class NoStoreFuncVisitor final : public BugReporterVisitor { llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated; public: - NoStoreFuncVisitor(const SubRegion *R) : RegionOfInterest(R) {} + NoStoreFuncVisitor(const SubRegion *R) + : RegionOfInterest(R), + SM(R->getMemRegionManager()->getContext().getSourceManager()), + PP(R->getMemRegionManager()->getContext().getPrintingPolicy()) {} void Profile(llvm::FoldingSetNodeID &ID) const override { static int Tag = 0; @@ -307,8 +312,6 @@ public: CallEventRef<> Call = BRC.getStateManager().getCallEventManager().getCaller(SCtx, State); - const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy(); - const SourceManager &SM = BRC.getSourceManager(); // Region of interest corresponds to an IVar, exiting a method // which could have written into that IVar, but did not. @@ -318,16 +321,14 @@ public: IvarR->getDecl()) && !isRegionOfInterestModifiedInFrame(N)) return notModifiedMemberDiagnostics( - Ctx, SM, PP, *CallExitLoc, Call, - MC->getReceiverSVal().getAsRegion()); + Ctx, *CallExitLoc, Call, MC->getReceiverSVal().getAsRegion()); if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) { - const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion(); - if (RegionOfInterest->isSubRegionOf(ThisRegion) + const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion(); + if (RegionOfInterest->isSubRegionOf(ThisR) && !CCall->getDecl()->isImplicit() && !isRegionOfInterestModifiedInFrame(N)) - return notModifiedMemberDiagnostics(Ctx, SM, PP, *CallExitLoc, - CCall, ThisRegion); + return notModifiedMemberDiagnostics(Ctx, *CallExitLoc, Call, ThisR); } ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call); @@ -344,7 +345,7 @@ public: return nullptr; return notModifiedParameterDiagnostics( - Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel); + Ctx, *CallExitLoc, Call, PVD, R, IndirectionLevel); } QualType PT = T->getPointeeType(); if (PT.isNull() || PT->isVoidType()) break; @@ -446,8 +447,6 @@ private: /// in a given function. std::shared_ptr<PathDiagnosticPiece> notModifiedMemberDiagnostics( const LocationContext *Ctx, - const SourceManager &SM, - const PrintingPolicy &PP, CallExitBegin &CallExitLoc, CallEventRef<> Call, const MemRegion *ArgRegion) { @@ -474,8 +473,6 @@ private: /// before we get to the super region of \c RegionOfInterest std::shared_ptr<PathDiagnosticPiece> notModifiedParameterDiagnostics(const LocationContext *Ctx, - const SourceManager &SM, - const PrintingPolicy &PP, CallExitBegin &CallExitLoc, CallEventRef<> Call, const ParmVarDecl *PVD, @@ -612,8 +609,7 @@ public: const ExplodedNode *N, const MemRegion *R, bool EnableNullFPSuppression, BugReport &BR, const SVal V) { - AnalyzerOptions &Options = N->getState()->getStateManager() - .getOwningEngine()->getAnalysisManager().options; + AnalyzerOptions &Options = N->getState()->getAnalysisManager().options; if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths() && V.getAs<Loc>()) BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>( @@ -740,9 +736,7 @@ public: RetVal = State->getSVal(*LValue); // See if the return value is NULL. If so, suppress the report. - SubEngine *Eng = State->getStateManager().getOwningEngine(); - assert(Eng && "Cannot file a bug report without an owning engine"); - AnalyzerOptions &Options = Eng->getAnalysisManager().options; + AnalyzerOptions &Options = State->getAnalysisManager().options; bool EnableNullFPSuppression = false; if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()) @@ -1321,9 +1315,7 @@ SuppressInlineDefensiveChecksVisitor:: SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N) : V(Value) { // Check if the visitor is disabled. - SubEngine *Eng = N->getState()->getStateManager().getOwningEngine(); - assert(Eng && "Cannot file a bug report without an owning engine"); - AnalyzerOptions &Options = Eng->getAnalysisManager().options; + AnalyzerOptions &Options = N->getState()->getAnalysisManager().options; if (!Options.shouldSuppressInlinedDefensiveChecks()) IsSatisfied = true; @@ -1603,6 +1595,7 @@ bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, LVNode->getSVal(Inner).getAsRegion(); if (R) { + // Mark both the variable region and its contents as interesting. SVal V = LVState->getRawSVal(loc::MemRegionVal(R)); report.addVisitor( diff --git a/lib/StaticAnalyzer/Core/CallEvent.cpp b/lib/StaticAnalyzer/Core/CallEvent.cpp index 8db7b06f186da..fe9260e32dd8b 100644 --- a/lib/StaticAnalyzer/Core/CallEvent.cpp +++ b/lib/StaticAnalyzer/Core/CallEvent.cpp @@ -27,6 +27,7 @@ #include "clang/AST/Type.h" #include "clang/Analysis/AnalysisDeclContext.h" #include "clang/Analysis/CFG.h" +#include "clang/Analysis/CFGStmtMap.h" #include "clang/Analysis/ProgramPoint.h" #include "clang/CrossTU/CrossTranslationUnit.h" #include "clang/Basic/IdentifierTable.h" @@ -166,6 +167,68 @@ bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { return CheckerContext::isCLibraryFunction(FD, FunctionName); } +AnalysisDeclContext *CallEvent::getCalleeAnalysisDeclContext() const { + const Decl *D = getDecl(); + + // If the callee is completely unknown, we cannot construct the stack frame. + if (!D) + return nullptr; + + // FIXME: Skip virtual functions for now. There's no easy procedure to foresee + // the exact decl that should be used, especially when it's not a definition. + if (const Decl *RD = getRuntimeDefinition().getDecl()) + if (RD != D) + return nullptr; + + return LCtx->getAnalysisDeclContext()->getManager()->getContext(D); +} + +const StackFrameContext *CallEvent::getCalleeStackFrame() const { + AnalysisDeclContext *ADC = getCalleeAnalysisDeclContext(); + if (!ADC) + return nullptr; + + const Expr *E = getOriginExpr(); + if (!E) + return nullptr; + + // Recover CFG block via reverse lookup. + // TODO: If we were to keep CFG element information as part of the CallEvent + // instead of doing this reverse lookup, we would be able to build the stack + // frame for non-expression-based calls, and also we wouldn't need the reverse + // lookup. + CFGStmtMap *Map = LCtx->getAnalysisDeclContext()->getCFGStmtMap(); + const CFGBlock *B = Map->getBlock(E); + assert(B); + + // Also recover CFG index by scanning the CFG block. + unsigned Idx = 0, Sz = B->size(); + for (; Idx < Sz; ++Idx) + if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>()) + if (StmtElem->getStmt() == E) + break; + assert(Idx < Sz); + + return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, Idx); +} + +const VarRegion *CallEvent::getParameterLocation(unsigned Index) const { + const StackFrameContext *SFC = getCalleeStackFrame(); + // We cannot construct a VarRegion without a stack frame. + if (!SFC) + return nullptr; + + const ParmVarDecl *PVD = parameters()[Index]; + const VarRegion *VR = + State->getStateManager().getRegionManager().getVarRegion(PVD, SFC); + + // This sanity check would fail if our parameter declaration doesn't + // correspond to the stack frame's function declaration. + assert(VR->getStackFrame() == SFC); + + return VR; +} + /// Returns true if a type is a pointer-to-const or reference-to-const /// with no further indirection. static bool isPointerToConst(QualType Ty) { diff --git a/lib/StaticAnalyzer/Core/ExprEngine.cpp b/lib/StaticAnalyzer/Core/ExprEngine.cpp index 188316c096e38..2b4bdd754fdbc 100644 --- a/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ b/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -117,56 +117,42 @@ STATISTIC(NumTimesRetriedWithoutInlining, /// the construction context was present and contained references to these /// AST nodes. class ConstructedObjectKey { - typedef std::pair< - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *>, - const LocationContext *> ConstructedObjectKeyImpl; + typedef std::pair<ConstructionContextItem, const LocationContext *> + ConstructedObjectKeyImpl; - ConstructedObjectKeyImpl Impl; + const ConstructedObjectKeyImpl Impl; const void *getAnyASTNodePtr() const { - if (const Stmt *S = getStmt()) + if (const Stmt *S = getItem().getStmtOrNull()) return S; else - return getCXXCtorInitializer(); + return getItem().getCXXCtorInitializer(); } public: - ConstructedObjectKey( - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC) - : Impl(P, LC) { - // This is the full list of statements that require additional actions when - // encountered. This list may be expanded when new actions are implemented. - assert(getCXXCtorInitializer() || isa<DeclStmt>(getStmt()) || - isa<CXXNewExpr>(getStmt()) || isa<CXXBindTemporaryExpr>(getStmt()) || - isa<MaterializeTemporaryExpr>(getStmt()) || - isa<CXXConstructExpr>(getStmt())); - } - - const Stmt *getStmt() const { - return Impl.first.dyn_cast<const Stmt *>(); - } + explicit ConstructedObjectKey(const ConstructionContextItem &Item, + const LocationContext *LC) + : Impl(Item, LC) {} - const CXXCtorInitializer *getCXXCtorInitializer() const { - return Impl.first.dyn_cast<const CXXCtorInitializer *>(); - } - - const LocationContext *getLocationContext() const { - return Impl.second; - } + const ConstructionContextItem &getItem() const { return Impl.first; } + const LocationContext *getLocationContext() const { return Impl.second; } void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) { - OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ") "; - if (const Stmt *S = getStmt()) { + OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ',' + << getItem().getKindAsString(); + if (getItem().getKind() == ConstructionContextItem::ArgumentKind) + OS << " #" << getItem().getIndex(); + OS << ") "; + if (const Stmt *S = getItem().getStmtOrNull()) { S->printPretty(OS, Helper, PP); } else { - const CXXCtorInitializer *I = getCXXCtorInitializer(); + const CXXCtorInitializer *I = getItem().getCXXCtorInitializer(); OS << I->getAnyMember()->getNameAsString(); } } void Profile(llvm::FoldingSetNodeID &ID) const { - ID.AddPointer(Impl.first.getOpaqueValue()); + ID.Add(Impl.first); ID.AddPointer(Impl.second); } @@ -184,15 +170,6 @@ typedef llvm::ImmutableMap<ConstructedObjectKey, SVal> REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, ObjectsUnderConstructionMap) -// Additionally, track a set of destructors that correspond to elided -// constructors when copy elision occurs. -typedef std::pair<const CXXBindTemporaryExpr *, const LocationContext *> - ElidedDestructorItem; -typedef llvm::ImmutableSet<ElidedDestructorItem> - ElidedDestructorSet; -REGISTER_TRAIT_WITH_PROGRAMSTATE(ElidedDestructors, - ElidedDestructorSet) - //===----------------------------------------------------------------------===// // Engine construction and deletion. //===----------------------------------------------------------------------===// @@ -449,31 +426,32 @@ ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State, return State; } -ProgramStateRef ExprEngine::addObjectUnderConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC, SVal V) { - ConstructedObjectKey Key(P, LC->getStackFrame()); +ProgramStateRef +ExprEngine::addObjectUnderConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC, SVal V) { + ConstructedObjectKey Key(Item, LC->getStackFrame()); // FIXME: Currently the state might already contain the marker due to // incorrect handling of temporaries bound to default parameters. assert(!State->get<ObjectsUnderConstruction>(Key) || - isa<CXXBindTemporaryExpr>(Key.getStmt())); + Key.getItem().getKind() == + ConstructionContextItem::TemporaryDestructorKind); return State->set<ObjectsUnderConstruction>(Key, V); } -Optional<SVal> ExprEngine::getObjectUnderConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC) { - ConstructedObjectKey Key(P, LC->getStackFrame()); +Optional<SVal> +ExprEngine::getObjectUnderConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC) { + ConstructedObjectKey Key(Item, LC->getStackFrame()); return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key)); } -ProgramStateRef ExprEngine::finishObjectConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC) { - ConstructedObjectKey Key(P, LC->getStackFrame()); +ProgramStateRef +ExprEngine::finishObjectConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC) { + ConstructedObjectKey Key(Item, LC->getStackFrame()); assert(State->contains<ObjectsUnderConstruction>(Key)); return State->remove<ObjectsUnderConstruction>(Key); } @@ -481,25 +459,26 @@ ProgramStateRef ExprEngine::finishObjectConstruction( ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State, const CXXBindTemporaryExpr *BTE, const LocationContext *LC) { - ElidedDestructorItem I(BTE, LC); - assert(!State->contains<ElidedDestructors>(I)); - return State->add<ElidedDestructors>(I); + ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); + // FIXME: Currently the state might already contain the marker due to + // incorrect handling of temporaries bound to default parameters. + return State->set<ObjectsUnderConstruction>(Key, UnknownVal()); } ProgramStateRef ExprEngine::cleanupElidedDestructor(ProgramStateRef State, const CXXBindTemporaryExpr *BTE, const LocationContext *LC) { - ElidedDestructorItem I(BTE, LC); - assert(State->contains<ElidedDestructors>(I)); - return State->remove<ElidedDestructors>(I); + ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); + assert(State->contains<ObjectsUnderConstruction>(Key)); + return State->remove<ObjectsUnderConstruction>(Key); } bool ExprEngine::isDestructorElided(ProgramStateRef State, const CXXBindTemporaryExpr *BTE, const LocationContext *LC) { - ElidedDestructorItem I(BTE, LC); - return State->contains<ElidedDestructors>(I); + ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); + return State->contains<ObjectsUnderConstruction>(Key); } bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State, @@ -512,10 +491,6 @@ bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State, if (I.first.getLocationContext() == LC) return false; - for (auto I: State->get<ElidedDestructors>()) - if (I.second == LC) - return false; - LC = LC->getParent(); } return true; @@ -560,14 +535,6 @@ static void printObjectsUnderConstructionForContext(raw_ostream &Out, Key.print(Out, nullptr, PP); Out << " : " << Value << NL; } - - for (auto I : State->get<ElidedDestructors>()) { - if (I.second != LC) - continue; - Out << '(' << I.second << ',' << (const void *)I.first << ") "; - I.first->printPretty(Out, nullptr, PP); - Out << " : (constructor elided)" << NL; - } } void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, @@ -2252,25 +2219,14 @@ void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, for (auto I : State->get<ObjectsUnderConstruction>()) if (I.first.getLocationContext() == LC) { // The comment above only pardons us for not cleaning up a - // CXXBindTemporaryExpr. If any other statements are found here, + // temporary destructor. If any other statements are found here, // it must be a separate problem. - assert(isa<CXXBindTemporaryExpr>(I.first.getStmt())); + assert(I.first.getItem().getKind() == + ConstructionContextItem::TemporaryDestructorKind || + I.first.getItem().getKind() == + ConstructionContextItem::ElidedDestructorKind); State = State->remove<ObjectsUnderConstruction>(I.first); - // Also cleanup the elided destructor info. - ElidedDestructorItem Item( - cast<CXXBindTemporaryExpr>(I.first.getStmt()), - I.first.getLocationContext()); - State = State->remove<ElidedDestructors>(Item); } - - // Also suppress the assertion for elided destructors when temporary - // destructors are not provided at all by the CFG, because there's no - // good place to clean them up. - if (!AMgr.getAnalyzerOptions().includeTemporaryDtorsInCFG()) - for (auto I : State->get<ElidedDestructors>()) - if (I.second == LC) - State = State->remove<ElidedDestructors>(I); - LC = LC->getParent(); } if (State != Pred->getState()) { @@ -2338,7 +2294,7 @@ void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { // Evaluate the LHS of the case value. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType())); - + // Get the RHS of the case, if it exists. llvm::APSInt V2; if (const Expr *E = Case->getRHS()) @@ -2538,12 +2494,12 @@ void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet CheckedSet; getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); - ExplodedNodeSet EvalSet; - ValueDecl *Member = M->getMemberDecl(); + ExplodedNodeSet EvalSet; + ValueDecl *Member = M->getMemberDecl(); // Handle static member variables and enum constants accessed via // member syntax. - if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { + if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { for (const auto I : CheckedSet) VisitCommonDeclRefExpr(M, Member, I, EvalSet); } else { diff --git a/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/lib/StaticAnalyzer/Core/ExprEngineC.cpp index c7b1a9ac82f0b..61b7a290e42a9 100644 --- a/lib/StaticAnalyzer/Core/ExprEngineC.cpp +++ b/lib/StaticAnalyzer/Core/ExprEngineC.cpp @@ -684,7 +684,7 @@ void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, // known to be false, 1 if the value is known to be true and a new symbol // when the assumption is unknown. nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType())); - X = evalBinOp(N->getState(), BO_NE, + X = evalBinOp(N->getState(), BO_NE, svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()), Zero, B->getType()); } diff --git a/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp b/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp index dc124fc3ff2d2..4f1766a813c6d 100644 --- a/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp +++ b/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp @@ -221,25 +221,42 @@ std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction( // and construct directly into the final object. This call // also sets the CallOpts flags for us. SVal V; + // If the elided copy/move constructor is not supported, there's still + // benefit in trying to model the non-elided constructor. + // Stash our state before trying to elide, as it'll get overwritten. + ProgramStateRef PreElideState = State; + EvalCallOptions PreElideCallOpts = CallOpts; + std::tie(State, V) = prepareForObjectConstruction( CE, State, LCtx, TCC->getConstructionContextAfterElision(), CallOpts); - // Remember that we've elided the constructor. - State = addObjectUnderConstruction(State, CE, LCtx, V); + // FIXME: This definition of "copy elision has not failed" is unreliable. + // It doesn't indicate that the constructor will actually be inlined + // later; it is still up to evalCall() to decide. + if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { + // Remember that we've elided the constructor. + State = addObjectUnderConstruction(State, CE, LCtx, V); - // Remember that we've elided the destructor. - if (BTE) - State = elideDestructor(State, BTE, LCtx); + // Remember that we've elided the destructor. + if (BTE) + State = elideDestructor(State, BTE, LCtx); - // Instead of materialization, shamelessly return - // the final object destination. - if (MTE) - State = addObjectUnderConstruction(State, MTE, LCtx, V); + // Instead of materialization, shamelessly return + // the final object destination. + if (MTE) + State = addObjectUnderConstruction(State, MTE, LCtx, V); - return std::make_pair(State, V); + return std::make_pair(State, V); + } else { + // Copy elision failed. Revert the changes and proceed as if we have + // a simple temporary. + State = PreElideState; + CallOpts = PreElideCallOpts; + } + LLVM_FALLTHROUGH; } case ConstructionContext::SimpleTemporaryObjectKind: { - const auto *TCC = cast<SimpleTemporaryObjectConstructionContext>(CC); + const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr(); const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); SVal V = UnknownVal(); @@ -274,6 +291,10 @@ std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction( CallOpts.IsTemporaryCtorOrDtor = true; return std::make_pair(State, V); } + case ConstructionContext::ArgumentKind: { + // Function argument constructors. Not implemented yet. + break; + } } } // If we couldn't find an existing region to construct into, assume we're diff --git a/lib/StaticAnalyzer/Core/IssueHash.cpp b/lib/StaticAnalyzer/Core/IssueHash.cpp index 274ebe7a941bc..6c55c61dd399a 100644 --- a/lib/StaticAnalyzer/Core/IssueHash.cpp +++ b/lib/StaticAnalyzer/Core/IssueHash.cpp @@ -26,7 +26,7 @@ using namespace clang; -// Get a string representation of the parts of the signature that can be +// Get a string representation of the parts of the signature that can be // overloaded on. static std::string GetSignature(const FunctionDecl *Target) { if (!Target) diff --git a/lib/StaticAnalyzer/Core/ProgramState.cpp b/lib/StaticAnalyzer/Core/ProgramState.cpp index 2b401607293b7..94e2e00d8bbc5 100644 --- a/lib/StaticAnalyzer/Core/ProgramState.cpp +++ b/lib/StaticAnalyzer/Core/ProgramState.cpp @@ -11,6 +11,7 @@ // //===----------------------------------------------------------------------===// +#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/Analysis/CFG.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" @@ -494,6 +495,10 @@ void ProgramState::dumpTaint() const { printTaint(llvm::errs()); } +AnalysisManager& ProgramState::getAnalysisManager() const { + return stateMgr->getOwningEngine()->getAnalysisManager(); +} + //===----------------------------------------------------------------------===// // Generic Data Map. //===----------------------------------------------------------------------===// diff --git a/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp b/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp index beae0dfae2896..62c54fc956a96 100644 --- a/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp +++ b/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp @@ -440,7 +440,7 @@ static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, SymbolRef Sym, llvm::APSInt Int, QualType Ty) { return Sym->getType() == Ty && (!BinaryOperator::isComparisonOp(Op) || - (isWithinConstantOverflowBounds(Sym, State) && + (isWithinConstantOverflowBounds(Sym, State) && isWithinConstantOverflowBounds(Int))); } @@ -1236,11 +1236,21 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { return Sym == Val.getAsSymbol(); } + SVal cache(SymbolRef Sym, SVal V) { + Cached[Sym] = V; + return V; + } + + SVal skip(SymbolRef Sym) { + return cache(Sym, SVB.makeSymbolVal(Sym)); + } + public: Simplifier(ProgramStateRef State) : State(State), SVB(State->getStateManager().getSValBuilder()) {} SVal VisitSymbolData(const SymbolData *S) { + // No cache here. if (const llvm::APSInt *I = SVB.getKnownValue(State, SVB.makeSymbolVal(S))) return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I) @@ -1257,11 +1267,9 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { return I->second; SVal LHS = Visit(S->getLHS()); - if (isUnchanged(S->getLHS(), LHS)) { - SVal V = SVB.makeSymbolVal(S); - Cached[S] = V; - return V; - } + if (isUnchanged(S->getLHS(), LHS)) + return skip(S); + SVal RHS; // By looking at the APSInt in the right-hand side of S, we cannot // figure out if it should be treated as a Loc or as a NonLoc. @@ -1281,9 +1289,8 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { RHS = SVB.makeIntVal(S->getRHS()); } - SVal V = SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()); - Cached[S] = V; - return V; + return cache( + S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); } SVal VisitSymSymExpr(const SymSymExpr *S) { @@ -1291,16 +1298,21 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { if (I != Cached.end()) return I->second; + // For now don't try to simplify mixed Loc/NonLoc expressions + // because they often appear from LocAsInteger operations + // and we don't know how to combine a LocAsInteger + // with a concrete value. + if (Loc::isLocType(S->getLHS()->getType()) != + Loc::isLocType(S->getRHS()->getType())) + return skip(S); + SVal LHS = Visit(S->getLHS()); SVal RHS = Visit(S->getRHS()); - if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) { - SVal V = SVB.makeSymbolVal(S); - Cached[S] = V; - return V; - } - SVal V = SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()); - Cached[S] = V; - return V; + if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) + return skip(S); + + return cache( + S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); } SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); } diff --git a/lib/StaticAnalyzer/Core/Store.cpp b/lib/StaticAnalyzer/Core/Store.cpp index 5ab5c082269ba..94188a9ef698f 100644 --- a/lib/StaticAnalyzer/Core/Store.cpp +++ b/lib/StaticAnalyzer/Core/Store.cpp @@ -448,10 +448,10 @@ SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset, // value. See also the similar FIXME in getLValueFieldOrIvar(). if (Base.isUnknownOrUndef() || Base.getAs<loc::ConcreteInt>()) return Base; - + if (Base.getAs<loc::GotoLabel>()) return UnknownVal(); - + const SubRegion *BaseRegion = Base.castAs<loc::MemRegionVal>().getRegionAs<SubRegion>(); |