diff --git a/clang/include/clang/AST/APValue.h b/clang/include/clang/AST/APValue.h index 80d1107ce2d8e64038e6a1c10b8433830647b620..94d258d9e4e6d46678490415777248d4174152bf 100644 --- a/clang/include/clang/AST/APValue.h +++ b/clang/include/clang/AST/APValue.h @@ -37,16 +37,16 @@ public: }; private: ValueKind Kind; - - struct ComplexAPSInt { - APSInt Real, Imag; + + struct ComplexAPSInt { + APSInt Real, Imag; ComplexAPSInt() : Real(1), Imag(1) {} }; struct ComplexAPFloat { APFloat Real, Imag; ComplexAPFloat() : Real(0.0), Imag(0.0) {} }; - + struct LV { Expr* Base; uint64_t Offset; @@ -57,9 +57,9 @@ private: Vec() : Elts(0), NumElts(0) {} ~Vec() { delete[] Elts; } }; - + enum { - MaxSize = (sizeof(ComplexAPSInt) > sizeof(ComplexAPFloat) ? + MaxSize = (sizeof(ComplexAPSInt) > sizeof(ComplexAPFloat) ? sizeof(ComplexAPSInt) : sizeof(ComplexAPFloat)) }; @@ -94,7 +94,7 @@ public: ~APValue() { MakeUninit(); } - + ValueKind getKind() const { return Kind; } bool isUninit() const { return Kind == Uninitialized; } bool isInt() const { return Kind == Int; } @@ -103,10 +103,10 @@ public: bool isComplexFloat() const { return Kind == ComplexFloat; } bool isLValue() const { return Kind == LValue; } bool isVector() const { return Kind == Vector; } - + void print(llvm::raw_ostream &OS) const; void dump() const; - + APSInt &getInt() { assert(isInt() && "Invalid accessor"); return *(APSInt*)(char*)Data; @@ -114,7 +114,7 @@ public: const APSInt &getInt() const { return const_cast(this)->getInt(); } - + APFloat &getFloat() { assert(isFloat() && "Invalid accessor"); return *(APFloat*)(char*)Data; @@ -122,7 +122,7 @@ public: const APFloat &getFloat() const { return const_cast(this)->getFloat(); } - + APValue &getVectorElt(unsigned i) const { assert(isVector() && "Invalid accessor"); return ((Vec*)(char*)Data)->Elts[i]; @@ -131,7 +131,7 @@ public: assert(isVector() && "Invalid accessor"); return ((Vec*)(void *)Data)->NumElts; } - + APSInt &getComplexIntReal() { assert(isComplexInt() && "Invalid accessor"); return ((ComplexAPSInt*)(char*)Data)->Real; @@ -139,7 +139,7 @@ public: const APSInt &getComplexIntReal() const { return const_cast(this)->getComplexIntReal(); } - + APSInt &getComplexIntImag() { assert(isComplexInt() && "Invalid accessor"); return ((ComplexAPSInt*)(char*)Data)->Imag; @@ -147,7 +147,7 @@ public: const APSInt &getComplexIntImag() const { return const_cast(this)->getComplexIntImag(); } - + APFloat &getComplexFloatReal() { assert(isComplexFloat() && "Invalid accessor"); return ((ComplexAPFloat*)(char*)Data)->Real; @@ -172,7 +172,7 @@ public: assert(isLValue() && "Invalid accessor"); return ((const LV*)(const void*)Data)->Offset; } - + void setInt(const APSInt &I) { assert(isInt() && "Invalid accessor"); *(APSInt*)(char*)Data = I; @@ -189,14 +189,14 @@ public: ((Vec*)(char*)Data)->Elts[i] = E[i]; } void setComplexInt(const APSInt &R, const APSInt &I) { - assert(R.getBitWidth() == I.getBitWidth() && + assert(R.getBitWidth() == I.getBitWidth() && "Invalid complex int (type mismatch)."); assert(isComplexInt() && "Invalid accessor"); ((ComplexAPSInt*)(char*)Data)->Real = R; ((ComplexAPSInt*)(char*)Data)->Imag = I; } void setComplexFloat(const APFloat &R, const APFloat &I) { - assert(&R.getSemantics() == &I.getSemantics() && + assert(&R.getSemantics() == &I.getSemantics() && "Invalid complex float (type mismatch)."); assert(isComplexFloat() && "Invalid accessor"); ((ComplexAPFloat*)(char*)Data)->Real = R; @@ -207,9 +207,9 @@ public: ((LV*)(char*)Data)->Base = B; ((LV*)(char*)Data)->Offset = O; } - + const APValue &operator=(const APValue &RHS); - + private: void MakeUninit(); void MakeInt() { @@ -248,7 +248,7 @@ inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const APValue &V) { V.print(OS); return OS; } - + } // end namespace clang. #endif diff --git a/clang/include/clang/AST/ASTConsumer.h b/clang/include/clang/AST/ASTConsumer.h index 6dc7e13d8f70c3d610f94bd4f86d8e92edb7c338..af6bf30b6882d3b79436da603f815c5223b42093 100644 --- a/clang/include/clang/AST/ASTConsumer.h +++ b/clang/include/clang/AST/ASTConsumer.h @@ -36,27 +36,27 @@ public: ASTConsumer() : SemaConsumer(false) { } virtual ~ASTConsumer() {} - + /// Initialize - This is called to initialize the consumer, providing the /// ASTContext and the Action. virtual void Initialize(ASTContext &Context) {} - + /// HandleTopLevelDecl - Handle the specified top-level declaration. This is /// called by the parser to process every top-level Decl*. Note that D can /// be the head of a chain of Decls (e.g. for `int a, b` the chain will have /// two elements). Use Decl::getNextDeclarator() to walk the chain. virtual void HandleTopLevelDecl(DeclGroupRef D); - + /// HandleTranslationUnit - This method is called when the ASTs for entire /// translation unit have been parsed. - virtual void HandleTranslationUnit(ASTContext &Ctx) {} - + virtual void HandleTranslationUnit(ASTContext &Ctx) {} + /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl /// (e.g. struct, union, enum, class) is completed. This allows the client to /// hack on the type, which can occur at any point in the file (because these /// can be defined in declspecs). virtual void HandleTagDeclDefinition(TagDecl *D) {} - + /// \brief Callback invoked at the end of a translation unit to /// notify the consumer that the given tentative definition should /// be completed. diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index f9419fb3c28e8b479fc1253ef56d4f5aea7718c6..9c5e31cd7407d297fbc348ec4357039d24c5aeda 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -56,12 +56,12 @@ namespace clang { class TypedefDecl; class UnresolvedUsingDecl; class UsingDecl; - + namespace Builtin { class Context; } - + /// ASTContext - This class holds long-lived AST nodes (such as types and /// decls) that can be referred to throughout the semantic analysis of a file. -class ASTContext { +class ASTContext { std::vector Types; llvm::FoldingSet ExtQualTypes; llvm::FoldingSet ComplexTypes; @@ -87,7 +87,7 @@ class ASTContext { llvm::FoldingSet ObjCInterfaceTypes; llvm::FoldingSet ObjCObjectPointerTypes; llvm::FoldingSet ElaboratedTypes; - + llvm::FoldingSet QualifiedTemplateNames; llvm::FoldingSet DependentTemplateNames; @@ -108,7 +108,7 @@ class ASTContext { llvm::DenseMap SignedFixedWidthIntTypes; llvm::DenseMap UnsignedFixedWidthIntTypes; - + /// BuiltinVaListType - built-in va list type. /// This is initially null and set by Sema::LazilyCreateBuiltin when /// a builtin that takes a valist is encountered. @@ -116,33 +116,33 @@ class ASTContext { /// ObjCIdType - a pseudo built-in typedef type (set by Sema). QualType ObjCIdTypedefType; - + /// ObjCSelType - another pseudo built-in typedef type (set by Sema). QualType ObjCSelType; const RecordType *SelStructType; - + /// ObjCProtoType - another pseudo built-in typedef type (set by Sema). QualType ObjCProtoType; const RecordType *ProtoStructType; /// ObjCClassType - another pseudo built-in typedef type (set by Sema). QualType ObjCClassTypedefType; - + QualType ObjCConstantStringType; RecordDecl *CFConstantStringTypeDecl; RecordDecl *ObjCFastEnumerationStateTypeDecl; - + /// \brief The type for the C FILE type. TypeDecl *FILEDecl; - + /// \brief The type for the C jmp_buf type. TypeDecl *jmp_bufDecl; - + /// \brief The type for the C sigjmp_buf type. TypeDecl *sigjmp_bufDecl; - - /// \brief Keeps track of all declaration attributes. + + /// \brief Keeps track of all declaration attributes. /// /// Since so few decls have attrs, we keep them in a hash map instead of /// wasting space in the Decl class. @@ -153,7 +153,7 @@ class ASTContext { /// /// This data structure stores the mapping from instantiations of static /// data members to the static data member representations within the - /// class template from which they were instantiated. + /// class template from which they were instantiated. /// /// Given the following example: /// @@ -169,11 +169,11 @@ class ASTContext { /// int *x = &X::value; /// \endcode /// - /// This mapping will contain an entry that maps from the VarDecl for + /// This mapping will contain an entry that maps from the VarDecl for /// X::value to the corresponding VarDecl for X::value (within the - /// class template X). + /// class template X). llvm::DenseMap InstantiatedFromStaticDataMember; - + /// \brief Keeps track of the UnresolvedUsingDecls from which UsingDecls /// where created during instantiation. /// @@ -196,14 +196,14 @@ class ASTContext { /// B to the UnresolvedUsingDecl in B. llvm::DenseMap InstantiatedFromUnresolvedUsingDecl; - + llvm::DenseMap InstantiatedFromUnnamedFieldDecl; - + TranslationUnitDecl *TUDecl; /// SourceMgr - The associated SourceManager object. SourceManager &SourceMgr; - + /// LangOpts - The language options used to create the AST associated with /// this ASTContext object. LangOptions LangOpts; @@ -211,17 +211,17 @@ class ASTContext { /// \brief Whether we have already loaded comment source ranges from an /// external source. bool LoadedExternalComments; - + /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects. bool FreeMemory; llvm::MallocAllocator MallocAlloc; llvm::BumpPtrAllocator BumpAlloc; - + /// \brief Mapping from declarations to their comments, once we have /// already looked up the comment associated with a given declaration. llvm::DenseMap DeclComments; - -public: + +public: TargetInfo &Target; IdentifierTable &Idents; SelectorTable &Selectors; @@ -238,38 +238,38 @@ public: /// \brief Source ranges for all of the comments in the source file, /// sorted in order of appearance in the translation unit. std::vector Comments; - + SourceManager& getSourceManager() { return SourceMgr; } const SourceManager& getSourceManager() const { return SourceMgr; } void *Allocate(unsigned Size, unsigned Align = 8) { return FreeMemory ? MallocAlloc.Allocate(Size, Align) : BumpAlloc.Allocate(Size, Align); } - void Deallocate(void *Ptr) { + void Deallocate(void *Ptr) { if (FreeMemory) - MallocAlloc.Deallocate(Ptr); + MallocAlloc.Deallocate(Ptr); } const LangOptions& getLangOptions() const { return LangOpts; } - - FullSourceLoc getFullLoc(SourceLocation Loc) const { + + FullSourceLoc getFullLoc(SourceLocation Loc) const { return FullSourceLoc(Loc,SourceMgr); } /// \brief Retrieve the attributes for the given declaration. Attr*& getDeclAttrs(const Decl *D) { return DeclAttrs[D]; } - + /// \brief Erase the attributes corresponding to the given declaration. void eraseDeclAttrs(const Decl *D) { DeclAttrs.erase(D); } /// \brief If this variable is an instantiated static data member of a - /// class template specialization, returns the templated static data member + /// class template specialization, returns the templated static data member /// from which it was instantiated. VarDecl *getInstantiatedFromStaticDataMember(VarDecl *Var); - + /// \brief Note that the static data member \p Inst is an instantiation of /// the static data member template \p Tmpl of a class template. - void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl); - + void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl); + /// \brief If this using decl is instantiated from an unresolved using decl, /// return it. UnresolvedUsingDecl *getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD); @@ -278,17 +278,17 @@ public: /// the unresolved using decl \p Tmpl of a class template. void setInstantiatedFromUnresolvedUsingDecl(UsingDecl *Inst, UnresolvedUsingDecl *Tmpl); - - + + FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); - + void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); - + TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; } - + const char *getCommentForDecl(const Decl *D); - + // Builtin Types. QualType VoidTy; QualType BoolTy; @@ -331,27 +331,27 @@ public: //===--------------------------------------------------------------------===// // Type Constructors //===--------------------------------------------------------------------===// - - /// getAddSpaceQualType - Return the uniqued reference to the type for an - /// address space qualified type with the specified type and address space. - /// The resulting type has a union of the qualifiers from T and the address - /// space. If T already has an address space specifier, it is silently + + /// getAddSpaceQualType - Return the uniqued reference to the type for an + /// address space qualified type with the specified type and address space. + /// The resulting type has a union of the qualifiers from T and the address + /// space. If T already has an address space specifier, it is silently /// replaced. QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace); - + /// getObjCGCQualType - Returns the uniqued reference to the type for an /// objc gc qualified type. The retulting type has a union of the qualifiers /// from T and the gc attribute. QualType getObjCGCQualType(QualType T, QualType::GCAttrTypes gcAttr); - + /// getNoReturnType - Add the noreturn attribute to the given type which must /// be a FunctionType or a pointer to an allowable type or a BlockPointer. QualType getNoReturnType(QualType T); - + /// getComplexType - Return the uniqued reference to the type for a complex /// number with the specified element type. QualType getComplexType(QualType T); - + /// getPointerType - Return the uniqued reference to the type for a pointer to /// the specified type. QualType getPointerType(QualType T); @@ -379,7 +379,7 @@ public: ArrayType::ArraySizeModifier ASM, unsigned EltTypeQuals, SourceRange Brackets); - + /// getDependentSizedArrayType - Returns a non-unique reference to /// the type for a dependently-sized array of the specified element /// type. FIXME: We will need these to be uniqued, or at least @@ -430,7 +430,7 @@ public: /// the type for a dependently-sized vector of the specified element /// type. FIXME: We will need these to be uniqued, or at least /// comparable, at some point. - QualType getDependentSizedExtVectorType(QualType VectorType, + QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc); @@ -455,7 +455,7 @@ public: /// specified typename decl. QualType getTypedefType(TypedefDecl *Decl); - QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, + QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, IdentifierInfo *Name = 0); @@ -466,17 +466,17 @@ public: QualType getQualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType); - QualType getTypenameType(NestedNameSpecifier *NNS, + QualType getTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon = QualType()); - QualType getTypenameType(NestedNameSpecifier *NNS, + QualType getTypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *TemplateId, QualType Canon = QualType()); QualType getElaboratedType(QualType UnderlyingType, ElaboratedType::TagKind Tag); QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, - ObjCProtocolDecl **Protocols = 0, + ObjCProtocolDecl **Protocols = 0, unsigned NumProtocols = 0); /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for the @@ -484,18 +484,18 @@ public: QualType getObjCObjectPointerType(QualType OIT, ObjCProtocolDecl **ProtocolList = 0, unsigned NumProtocols = 0); - + /// getTypeOfType - GCC extension. QualType getTypeOfExprType(Expr *e); QualType getTypeOfType(QualType t); - + /// getDecltypeType - C++0x decltype. QualType getDecltypeType(Expr *e); - + /// getTagDeclType - Return the unique reference to the type for the /// specified TagDecl (struct/union/class/enum) decl. QualType getTagDeclType(const TagDecl *Decl); - + /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined /// in . The sizeof operator requires this (C99 6.5.3.4p4). QualType getSizeType() const; @@ -512,15 +512,15 @@ public: /// getUnsignedWCharType - Return the type of "unsigned wchar_t". /// Used when in C++, as a GCC extension. QualType getUnsignedWCharType() const; - + /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) /// defined in . Pointer - pointer requires this (C99 6.5.6p9). QualType getPointerDiffType() const; - + // getCFConstantStringType - Return the C structure type used to represent // constant CFStrings. - QualType getCFConstantStringType(); - + QualType getCFConstantStringType(); + /// Get the structure type used to representation CFStrings, or NULL /// if it hasn't yet been built. QualType getRawCFConstantStringType() { @@ -532,13 +532,13 @@ public: // This setter/getter represents the ObjC type for an NSConstantString. void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl); - QualType getObjCConstantStringInterface() const { - return ObjCConstantStringType; + QualType getObjCConstantStringInterface() const { + return ObjCConstantStringType; } //// This gets the struct used to keep track of fast enumerations. QualType getObjCFastEnumerationStateType(); - + /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet /// been built. QualType getRawObjCFastEnumerationStateType() { @@ -551,10 +551,10 @@ public: /// \brief Set the type for the C FILE type. void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; } - + /// \brief Retrieve the C FILE type. - QualType getFILEType() { - if (FILEDecl) + QualType getFILEType() { + if (FILEDecl) return getTypeDeclType(FILEDecl); return QualType(); } @@ -563,10 +563,10 @@ public: void setjmp_bufDecl(TypeDecl *jmp_bufDecl) { this->jmp_bufDecl = jmp_bufDecl; } - + /// \brief Retrieve the C jmp_buf type. - QualType getjmp_bufType() { - if (jmp_bufDecl) + QualType getjmp_bufType() { + if (jmp_bufDecl) return getTypeDeclType(jmp_bufDecl); return QualType(); } @@ -575,41 +575,41 @@ public: void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) { this->sigjmp_bufDecl = sigjmp_bufDecl; } - + /// \brief Retrieve the C sigjmp_buf type. - QualType getsigjmp_bufType() { - if (sigjmp_bufDecl) + QualType getsigjmp_bufType() { + if (sigjmp_bufDecl) return getTypeDeclType(sigjmp_bufDecl); return QualType(); } - + /// getObjCEncodingForType - Emit the ObjC type encoding for the /// given type into \arg S. If \arg NameFields is specified then /// record field names are also encoded. - void getObjCEncodingForType(QualType t, std::string &S, + void getObjCEncodingForType(QualType t, std::string &S, const FieldDecl *Field=0); void getLegacyIntegralTypeEncoding(QualType &t) const; - + // Put the string version of type qualifiers into S. - void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, + void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const; - + /// getObjCEncodingForMethodDecl - Return the encoded type for this method /// declaration. void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S); - + /// getObjCEncodingForPropertyDecl - Return the encoded type for /// this method declaration. If non-NULL, Container must be either /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should /// only be NULL when getting encodings for protocol properties. - void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, + void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container, std::string &S); - + bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto); - + /// getObjCEncodingTypeSize returns size of type for objective-c encoding /// purpose. int getObjCEncodingTypeSize(QualType t); @@ -618,32 +618,32 @@ public: /// Sema. id is always a (typedef for a) pointer type, a pointer to a struct. QualType getObjCIdType() const { return ObjCIdTypedefType; } void setObjCIdType(QualType T); - + void setObjCSelType(QualType T); QualType getObjCSelType() const { return ObjCSelType; } - + void setObjCProtoType(QualType QT); QualType getObjCProtoType() const { return ObjCProtoType; } - + /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by /// Sema. 'Class' is always a (typedef for a) pointer type, a pointer to a /// struct. QualType getObjCClassType() const { return ObjCClassTypedefType; } void setObjCClassType(QualType T); - + void setBuiltinVaListType(QualType T); QualType getBuiltinVaListType() const { return BuiltinVaListType; } QualType getFixedWidthIntType(unsigned Width, bool Signed); - TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, + TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template); - TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, + TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, OverloadedFunctionDecl *Template); - - TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, + + TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name); enum GetBuiltinTypeError { @@ -651,42 +651,42 @@ public: GE_Missing_stdio, //< Missing a type from GE_Missing_setjmp //< Missing a type from }; - + /// GetBuiltinType - Return the type for the specified builtin. QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error); - + private: QualType getFromTargetType(unsigned Type) const; //===--------------------------------------------------------------------===// // Type Predicates. //===--------------------------------------------------------------------===// - + public: /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's /// garbage collection attribute. /// QualType::GCAttrTypes getObjCGCAttrKind(const QualType &Ty) const; - + /// isObjCNSObjectType - Return true if this is an NSObject object with /// its NSObject attribute set. bool isObjCNSObjectType(QualType Ty) const; - + //===--------------------------------------------------------------------===// // Type Sizing and Analysis //===--------------------------------------------------------------------===// - + /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified /// scalar floating point type. const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const; - + /// getTypeInfo - Get the size and alignment of the specified complete type in /// bits. std::pair getTypeInfo(const Type *T); std::pair getTypeInfo(QualType T) { return getTypeInfo(T.getTypePtr()); } - + /// getTypeSize - Return the size of the specified type, in bits. This method /// does not work on incomplete types. uint64_t getTypeSize(QualType T) { @@ -695,7 +695,7 @@ public: uint64_t getTypeSize(const Type *T) { return getTypeInfo(T).first; } - + /// getTypeAlign - Return the ABI-specified alignment of a type, in bits. /// This method does not work on incomplete types. unsigned getTypeAlign(QualType T) { @@ -704,23 +704,23 @@ public: unsigned getTypeAlign(const Type *T) { return getTypeInfo(T).second; } - + /// 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 /// a data type. unsigned getPreferredTypeAlign(const Type *T); - + /// getDeclAlignInBytes - Return the alignment of the specified decl /// that should be returned by __alignof(). Note that bitfields do /// not have a valid alignment, so this method will assert on them. unsigned getDeclAlignInBytes(const Decl *D); - + /// getASTRecordLayout - Get or compute information about the layout of the /// specified record (struct/union/class), which indicates its size and field /// position information. const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D); - + /// getASTObjCInterfaceLayout - Get or compute information about the /// layout of the specified Objective-C interface. const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D); @@ -747,7 +747,7 @@ public: //===--------------------------------------------------------------------===// // Type Operators //===--------------------------------------------------------------------===// - + /// getCanonicalType - Return the canonical (structural) type corresponding to /// the specified potentially non-canonical type. The non-canonical version /// of a type may have many "decorated" versions of types. Decorators can @@ -763,7 +763,7 @@ public: bool hasSameType(QualType T1, QualType T2) { return getCanonicalType(T1) == getCanonicalType(T2); } - + /// \brief Determine whether the given types are equivalent after /// cvr-qualifiers have been removed. bool hasSameUnqualifiedType(QualType T1, QualType T2) { @@ -772,7 +772,7 @@ public: return T1.getUnqualifiedType() == T2.getUnqualifiedType(); } - /// \brief Retrieves the "canonical" declaration of + /// \brief Retrieves the "canonical" declaration of /// \brief Retrieves the "canonical" nested name specifier for a /// given nested name specifier. @@ -822,11 +822,11 @@ public: /// \brief Retrieve the "canonical" template argument. /// - /// The canonical template argument is the simplest template argument - /// (which may be a type, value, expression, or declaration) that + /// The canonical template argument is the simplest template argument + /// (which may be a type, value, expression, or declaration) that /// expresses the value of the argument. TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg); - + /// Type Query functions. If the type is an instance of the specified class, /// return the Type pointer for the underlying maximally pretty type. This /// is a member of ASTContext because this may need to do some amount of @@ -849,10 +849,10 @@ public: /// getBaseElementType - Returns the innermost element type of a type /// (which needn't actually be an array type). QualType getBaseElementType(QualType QT); - + /// getConstantArrayElementCount - Returns number of constant array elements. uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; - + /// getArrayDecayedType - Return the properly qualified result of decaying the /// specified array type to a pointer. This operation is non-trivial when /// handling typedefs etc. The canonical type of "T" must be an array type, @@ -860,7 +860,7 @@ public: /// /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. QualType getArrayDecayedType(QualType T); - + /// getPromotedIntegerType - Returns the type that Promotable will /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable /// integer type. @@ -873,22 +873,22 @@ public: /// promotion occurs. QualType isPromotableBitField(Expr *E); - /// getIntegerTypeOrder - Returns the highest ranked integer type: + /// getIntegerTypeOrder - Returns the highest ranked integer type: /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If - /// LHS < RHS, return -1. + /// LHS < RHS, return -1. int getIntegerTypeOrder(QualType LHS, QualType RHS); - + /// getFloatingTypeOrder - Compare the rank of the two specified floating /// point types, ignoring the domain of the type (i.e. 'double' == /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If - /// LHS < RHS, return -1. + /// LHS < RHS, return -1. int getFloatingTypeOrder(QualType LHS, QualType RHS); - /// getFloatingTypeOfSizeWithinDomain - Returns a real floating - /// point or a complex type (based on typeDomain/typeSize). + /// getFloatingTypeOfSizeWithinDomain - Returns a real floating + /// point or a complex type (based on typeDomain/typeSize). /// 'typeDomain' is a real floating point or complex type. /// 'typeSize' is a real floating point or complex type. - QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, + QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, QualType typeDomain) const; private: @@ -900,10 +900,10 @@ public: //===--------------------------------------------------------------------===// // Type Compatibility Predicates //===--------------------------------------------------------------------===// - + /// Compatibility predicates used to check assignment expressions. bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1 - + bool isObjCIdType(QualType T) const { return T == ObjCIdTypedefType; } @@ -950,15 +950,15 @@ public: //===--------------------------------------------------------------------===// // Type Iterators. //===--------------------------------------------------------------------===// - + typedef std::vector::iterator type_iterator; typedef std::vector::const_iterator const_type_iterator; - + type_iterator types_begin() { return Types.begin(); } type_iterator types_end() { return Types.end(); } const_type_iterator types_begin() const { return Types.begin(); } - const_type_iterator types_end() const { return Types.end(); } - + const_type_iterator types_end() const { return Types.end(); } + //===--------------------------------------------------------------------===// // Integer Values //===--------------------------------------------------------------------===// @@ -996,12 +996,12 @@ public: private: ASTContext(const ASTContext&); // DO NOT IMPLEMENT void operator=(const ASTContext&); // DO NOT IMPLEMENT - + void InitBuiltinTypes(); void InitBuiltinType(QualType &R, BuiltinType::Kind K); - + // Return the ObjC type encoding for a given type. - void getObjCEncodingForTypeImpl(QualType t, std::string &S, + void getObjCEncodingForTypeImpl(QualType t, std::string &S, bool ExpandPointedToStructures, bool ExpandStructures, const FieldDecl *Field, @@ -1009,7 +1009,7 @@ private: bool EncodingProperty = false); const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D, - const ObjCImplementationDecl *Impl); + const ObjCImplementationDecl *Impl); }; } // end namespace clang diff --git a/clang/include/clang/AST/ASTDiagnostic.h b/clang/include/clang/AST/ASTDiagnostic.h index e9f150574b050372bf3b70d35874363509e0f132..abd36f7e5f0fabbade7ef51d869b3318eb53c945 100644 --- a/clang/include/clang/AST/ASTDiagnostic.h +++ b/clang/include/clang/AST/ASTDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define ASTSTART diff --git a/clang/include/clang/AST/Attr.h b/clang/include/clang/AST/Attr.h index 43844d6e82ef0f20f1bea8362f818a2ef2cbd26d..f7a47364a7f611a5dd49a0c637726d74ac400de8 100644 --- a/clang/include/clang/AST/Attr.h +++ b/clang/include/clang/AST/Attr.h @@ -57,7 +57,7 @@ public: DLLImport, Deprecated, Destructor, - FastCall, + FastCall, Format, FormatArg, GNUInline, @@ -83,14 +83,14 @@ public: StdCall, TransparentUnion, Unavailable, - Unused, + Unused, Used, Visibility, WarnUnusedResult, Weak, WeakImport }; - + private: Attr *Next; Kind AttrKind; @@ -104,16 +104,16 @@ protected: void operator delete(void* data) throw() { assert(0 && "Attrs cannot be released with regular 'delete'."); } - + protected: Attr(Kind AK) : Next(0), AttrKind(AK), Inherited(false) {} virtual ~Attr() { assert(Next == 0 && "Destroy didn't work"); } public: - + void Destroy(ASTContext &C); - + /// \brief Whether this attribute should be merged to new /// declarations. virtual bool isMerged() const { return true; } @@ -130,18 +130,18 @@ public: return V; return 0; } - + bool isInherited() const { return Inherited; } void setInherited(bool value) { Inherited = value; } void addAttr(Attr *attr) { assert((attr != 0) && "addAttr(): attr is null"); - + // FIXME: This doesn't preserve the order in any way. attr->Next = Next; Next = attr; } - + // Clone this attribute. virtual Attr* clone(ASTContext &C) const = 0; @@ -169,8 +169,8 @@ public: /// getAlignment - The specified alignment in bits. unsigned getAlignment() const { return Alignment; } - virtual Attr* clone(ASTContext &C) const { - return ::new (C) PragmaPackAttr(Alignment); + virtual Attr* clone(ASTContext &C) const { + return ::new (C) PragmaPackAttr(Alignment); } // Implement isa/cast/dyncast/etc. @@ -179,7 +179,7 @@ public: } static bool classof(const PragmaPackAttr *A) { return true; } }; - + class AlignedAttr : public Attr { unsigned Alignment; public: @@ -189,7 +189,7 @@ public: unsigned getAlignment() const { return Alignment; } virtual Attr* clone(ASTContext &C) const { return ::new (C) AlignedAttr(Alignment); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Aligned; @@ -201,11 +201,11 @@ class AnnotateAttr : public Attr { std::string Annotation; public: AnnotateAttr(const std::string &ann) : Attr(Annotate), Annotation(ann) {} - + const std::string& getAnnotation() const { return Annotation; } virtual Attr* clone(ASTContext &C) const { return ::new (C) AnnotateAttr(Annotation); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Annotate; @@ -217,11 +217,11 @@ class AsmLabelAttr : public Attr { std::string Label; public: AsmLabelAttr(const std::string &L) : Attr(AsmLabel), Label(L) {} - + const std::string& getLabel() const { return Label; } - + virtual Attr* clone(ASTContext &C) const { return ::new (C) AsmLabelAttr(Label); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == AsmLabel; @@ -251,28 +251,28 @@ public: ConstructorAttr(int p) : Attr(Constructor), priority(p) {} int getPriority() const { return priority; } - + virtual Attr *clone(ASTContext &C) const { return ::new (C) ConstructorAttr(priority); } // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == Constructor; } + static bool classof(const Attr *A) { return A->getKind() == Constructor; } static bool classof(const ConstructorAttr *A) { return true; } -}; - +}; + class DestructorAttr : public Attr { int priority; public: DestructorAttr(int p) : Attr(Destructor), priority(p) {} int getPriority() const { return priority; } - + virtual Attr *clone(ASTContext &C) const { return ::new (C) DestructorAttr(priority); } // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == Destructor; } + static bool classof(const Attr *A) { return A->getKind() == Destructor; } static bool classof(const DestructorAttr *A) { return true; } -}; - +}; + class GNUInlineAttr : public Attr { public: GNUInlineAttr() : Attr(GNUInline) {} @@ -301,14 +301,14 @@ public: DEF_SIMPLE_ATTR(Malloc); DEF_SIMPLE_ATTR(NoReturn); -DEF_SIMPLE_ATTR(AnalyzerNoReturn); +DEF_SIMPLE_ATTR(AnalyzerNoReturn); DEF_SIMPLE_ATTR(Deprecated); class SectionAttr : public Attr { std::string Name; public: SectionAttr(const std::string &N) : Attr(Section), Name(N) {} - + const std::string& getName() const { return Name; } virtual Attr *clone(ASTContext &C) const { return ::new (C) SectionAttr(Name); } @@ -322,8 +322,8 @@ public: DEF_SIMPLE_ATTR(Unavailable); DEF_SIMPLE_ATTR(Unused); -DEF_SIMPLE_ATTR(Used); -DEF_SIMPLE_ATTR(Weak); +DEF_SIMPLE_ATTR(Used); +DEF_SIMPLE_ATTR(Weak); DEF_SIMPLE_ATTR(WeakImport); DEF_SIMPLE_ATTR(NoThrow); DEF_SIMPLE_ATTR(Const); @@ -335,14 +335,14 @@ class NonNullAttr : public Attr { public: NonNullAttr(unsigned* arg_nums = 0, unsigned size = 0) : Attr(NonNull), ArgNums(0), Size(0) { - + if (size == 0) return; assert(arg_nums); ArgNums = new unsigned[size]; Size = size; memcpy(ArgNums, arg_nums, sizeof(*ArgNums)*size); } - + virtual ~NonNullAttr() { delete [] ArgNums; } @@ -354,7 +354,7 @@ public: bool isNonNull(unsigned arg) const { return ArgNums ? std::binary_search(ArgNums, ArgNums+Size, arg) : true; - } + } virtual Attr *clone(ASTContext &C) const { return ::new (C) NonNullAttr(ArgNums, Size); } @@ -374,8 +374,8 @@ public: int getFormatIdx() const { return formatIdx; } int getFirstArg() const { return firstArg; } - virtual Attr *clone(ASTContext &C) const { - return ::new (C) FormatAttr(Type, formatIdx, firstArg); + virtual Attr *clone(ASTContext &C) const { + return ::new (C) FormatAttr(Type, formatIdx, firstArg); } // Implement isa/cast/dyncast/etc. @@ -452,8 +452,8 @@ public: virtual bool isMerged() const { return false; } - virtual Attr *clone(ASTContext &C) const { - return ::new (C) OverloadableAttr; + virtual Attr *clone(ASTContext &C) const { + return ::new (C) OverloadableAttr; } static bool classof(const Attr *A) { return A->getKind() == Overloadable; } @@ -480,15 +480,15 @@ public: }; class FunctionDecl; - + class CleanupAttr : public Attr { FunctionDecl *FD; - + public: CleanupAttr(FunctionDecl *fd) : Attr(Cleanup), FD(fd) {} const FunctionDecl *getFunctionDecl() const { return FD; } - + virtual Attr *clone(ASTContext &C) const { return ::new (C) CleanupAttr(FD); } // Implement isa/cast/dyncast/etc. @@ -497,7 +497,7 @@ public: }; DEF_SIMPLE_ATTR(NoDebug); -DEF_SIMPLE_ATTR(WarnUnusedResult); +DEF_SIMPLE_ATTR(WarnUnusedResult); DEF_SIMPLE_ATTR(NoInline); class RegparmAttr : public Attr { @@ -508,11 +508,11 @@ public: unsigned getNumParams() const { return NumParams; } - virtual Attr *clone(ASTContext &C) const { - return ::new (C) RegparmAttr(NumParams); + virtual Attr *clone(ASTContext &C) const { + return ::new (C) RegparmAttr(NumParams); } - // Implement isa/cast/dyncast/etc. + // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Regparm; } static bool classof(const RegparmAttr *A) { return true; } }; @@ -527,23 +527,23 @@ public: unsigned getYDim() const { return Y; } unsigned getZDim() const { return Z; } - virtual Attr *clone(ASTContext &C) const { - return ::new (C) ReqdWorkGroupSizeAttr(X, Y, Z); + virtual Attr *clone(ASTContext &C) const { + return ::new (C) ReqdWorkGroupSizeAttr(X, Y, Z); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == ReqdWorkGroupSize; } static bool classof(const ReqdWorkGroupSizeAttr *A) { return true; } }; - + // Checker-specific attributes. DEF_SIMPLE_ATTR(CFReturnsRetained); DEF_SIMPLE_ATTR(NSReturnsRetained); #undef DEF_SIMPLE_ATTR - + } // end namespace clang #endif diff --git a/clang/include/clang/AST/CanonicalType.h b/clang/include/clang/AST/CanonicalType.h index 186c677411ad901cf01a24278794535557f995bd..be163eb5a86950f6877fbd55bb9bd5a96ec2f388 100644 --- a/clang/include/clang/AST/CanonicalType.h +++ b/clang/include/clang/AST/CanonicalType.h @@ -21,69 +21,69 @@ #include namespace clang { - + template class CanProxy; template struct CanProxyAdaptor; //----------------------------------------------------------------------------// // Canonical, qualified type template //----------------------------------------------------------------------------// - + /// \brief Represents a canonical, potentially-qualified type. /// /// The CanQual template is a lightweight smart pointer that provides access /// to the canonical representation of a type, where all typedefs and other -/// syntactic sugar has been eliminated. A CanQualType may also have various +/// syntactic sugar has been eliminated. A CanQualType may also have various /// qualifiers (const, volatile, restrict) attached to it. /// -/// The template type parameter @p T is one of the Type classes (PointerType, +/// The template type parameter @p T is one of the Type classes (PointerType, /// BuiltinType, etc.). The type stored within @c CanQual will be of that /// type (or some subclass of that type). The typedef @c CanQualType is just /// a shorthand for @c CanQual. /// -/// An instance of @c CanQual can be implicitly converted to a +/// An instance of @c CanQual can be implicitly converted to a /// @c CanQual when T is derived from U, which essentially provides an -/// implicit upcast. For example, @c CanQual can be -/// converted to @c CanQual. Note that any @c CanQual type can +/// implicit upcast. For example, @c CanQual can be +/// converted to @c CanQual. Note that any @c CanQual type can /// be implicitly converted to a QualType, but the reverse operation requires /// a call to ASTContext::getCanonicalType(). -/// -/// +/// +/// template class CanQual { - /// \brief The actual, canonical type. + /// \brief The actual, canonical type. QualType Stored; - + public: /// \brief Constructs a NULL canonical type. CanQual() : Stored() { } - + /// \brief Converting constructor that permits implicit upcasting of /// canonical type pointers. template - CanQual(const CanQual& Other, + CanQual(const CanQual& Other, typename llvm::enable_if, int>::type = 0); - + /// \brief Implicit conversion to the underlying pointer. /// /// Also provides the ability to use canonical types in a boolean context, - /// e.g., + /// e.g., /// @code /// if (CanQual Ptr = T->getAs()) { ... } /// @endcode operator const T*() const { return getTypePtr(); } - - /// \brief Retrieve the underlying type pointer, which refers to a + + /// \brief Retrieve the underlying type pointer, which refers to a /// canonical type. T *getTypePtr() const { return cast_or_null(Stored.getTypePtr()); } - + /// \brief Implicit conversion to a qualified type. operator QualType() const { return Stored; } - + /// \brief Retrieve a canonical type pointer with a different static type, /// upcasting or downcasting as needed. /// - /// The getAs() function is typically used to try to downcast to a + /// The getAs() function is typically used to try to downcast to a /// more specific (canonical) type in the type system. For example: /// /// @code @@ -98,17 +98,17 @@ public: /// static type (@p U). If the dynamic type is not the specified static type /// or a derived class thereof, a NULL canonical type. template CanProxy getAs() const; - + /// \brief Overloaded arrow operator that produces a canonical type /// proxy. CanProxy operator->() const; - + /// \brief Retrieve the const/volatile/restrict qualifiers. unsigned getCVRQualifiers() const { return Stored.getCVRQualifiers(); } - + /// \brief Set the const/volatile/restrict qualifiers void setCVRQualifiers(unsigned Quals) { Stored.setCVRQualifiers(Quals); } - + bool isConstQualified() const { return (getCVRQualifiers() & QualType::Const) ? true : false; } @@ -117,42 +117,42 @@ public: } bool isRestrictQualified() const { return (getCVRQualifiers() & QualType::Restrict) ? true : false; - } - + } + /// \brief Retrieve the unqualified form of this type. CanQual getUnqualifiedType() const; - + CanQual getQualifiedType(unsigned TQs) const { return CanQual::CreateUnsafe(QualType(getTypePtr(), TQs)); } - - /// \brief Determines whether this canonical type is more qualified than + + /// \brief Determines whether this canonical type is more qualified than /// the @p Other canonical type. bool isMoreQualifiedThan(CanQual Other) const { return Stored.isMoreQualifiedThan(Other.Stored); } - + /// \brief Determines whether this canonical type is at least as qualified as /// the @p Other canonical type. bool isAtLeastAsQualifiedAs(CanQual Other) const { return Stored.isAtLeastAsQualifiedAs(Other.Stored); } - + /// \brief If the canonical type is a reference type, returns the type that /// it refers to; otherwise, returns the type itself. CanQual getNonReferenceType() const; - + /// \brief Retrieve the internal representation of this canonical type. void *getAsOpaquePtr() const { return Stored.getAsOpaquePtr(); } - + /// \brief Construct a canonical type from its internal representation. static CanQual getFromOpaquePtr(void *Ptr); - + /// \brief Builds a canonical type from a QualType. /// - /// This routine is inherently unsafe, because it requires the user to - /// ensure that the given type is a canonical type with the correct - // (dynamic) type. + /// This routine is inherently unsafe, because it requires the user to + /// ensure that the given type is a canonical type with the correct + // (dynamic) type. static CanQual CreateUnsafe(QualType Other); }; @@ -172,7 +172,7 @@ typedef CanQual CanQualType; //----------------------------------------------------------------------------// // Internal proxy classes used by canonical types //----------------------------------------------------------------------------// - + #define LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(Accessor) \ CanQualType Accessor() const { \ return CanQualType::CreateUnsafe(this->getTypePtr()->Accessor()); \ @@ -183,32 +183,32 @@ Type Accessor() const { return this->getTypePtr()->Accessor(); } /// \brief Base class of all canonical proxy types, which is responsible for /// storing the underlying canonical type and providing basic conversions. -template +template class CanProxyBase { protected: CanQual Stored; - + public: /// \brief Retrieve the pointer to the underlying Type T* getTypePtr() const { return Stored.getTypePtr(); } - + /// \brief Implicit conversion to the underlying pointer. /// /// Also provides the ability to use canonical type proxies in a Boolean - // context,e.g., + // context,e.g., /// @code /// if (CanQual Ptr = T->getAs()) { ... } /// @endcode operator const T*() const { return this->Stored.getTypePtr(); } - + /// \brief Try to convert the given canonical type to a specific structural /// type. - template CanProxy getAs() const { - return this->Stored.template getAs(); + template CanProxy getAs() const { + return this->Stored.template getAs(); } - + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Type::TypeClass, getTypeClass) - + // Type predicates LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjectType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIncompleteType) @@ -271,44 +271,44 @@ public: /// that provide accessors returning canonical types (@c CanQualType) rather /// than the more typical @c QualType, to propagate the notion of "canonical" /// through the system. -template +template struct CanProxyAdaptor : CanProxyBase { }; /// \brief Canonical proxy type returned when retrieving the members of a -/// canonical type or as the result of the @c CanQual::getAs member +/// canonical type or as the result of the @c CanQual::getAs member /// function. /// /// The CanProxy type mainly exists as a proxy through which operator-> will -/// look to either map down to a raw T* (e.g., PointerType*) or to a proxy +/// look to either map down to a raw T* (e.g., PointerType*) or to a proxy /// type that provides canonical-type access to the fields of the type. template class CanProxy : public CanProxyAdaptor { public: /// \brief Build a NULL proxy. CanProxy() { } - + /// \brief Build a proxy to the given canonical type. CanProxy(CanQual Stored) { this->Stored = Stored; } - + /// \brief Implicit conversion to the stored canonical type. operator CanQual() const { return this->Stored; } }; - + } // end namespace clang namespace llvm { - -/// Implement simplify_type for CanQual, so that we can dyn_cast from + +/// Implement simplify_type for CanQual, so that we can dyn_cast from /// CanQual to a specific Type class. We're prefer isa/dyn_cast/cast/etc. /// to return smart pointer (proxies?). -template +template struct simplify_type > { typedef T* SimpleType; static SimpleType getSimplifiedValue(const ::clang::CanQual &Val) { return Val.getTypePtr(); } }; -template +template struct simplify_type< ::clang::CanQual > : public simplify_type > {}; @@ -325,21 +325,21 @@ public: // CVR qualifiers go in low bits. enum { NumLowBitsAvailable = 0 }; }; - + } // end namespace llvm namespace clang { - + //----------------------------------------------------------------------------// // Canonical proxy adaptors for canonical type nodes. //----------------------------------------------------------------------------// - -/// \brief Iterator adaptor that turns an iterator over canonical QualTypes + +/// \brief Iterator adaptor that turns an iterator over canonical QualTypes /// into an iterator over CanQualTypes. template class CanTypeIterator { InputIterator Iter; - + public: typedef CanQualType value_type; typedef value_type reference; @@ -348,62 +348,62 @@ public: difference_type; typedef typename std::iterator_traits::iterator_category iterator_category; - + CanTypeIterator() : Iter() { } explicit CanTypeIterator(InputIterator Iter) : Iter(Iter) { } - + // Input iterator reference operator*() const { return CanQualType::CreateUnsafe(*Iter); } - + pointer operator->() const; - + CanTypeIterator &operator++() { ++Iter; return *this; } - + CanTypeIterator operator++(int) { CanTypeIterator Tmp(*this); ++Iter; return Tmp; } - + friend bool operator==(const CanTypeIterator& X, const CanTypeIterator &Y) { return X.Iter == Y.Iter; } friend bool operator!=(const CanTypeIterator& X, const CanTypeIterator &Y) { return X.Iter != Y.Iter; } - + // Bidirectional iterator CanTypeIterator &operator--() { --Iter; return *this; } - + CanTypeIterator operator--(int) { CanTypeIterator Tmp(*this); --Iter; return Tmp; } - + // Random access iterator reference operator[](difference_type n) const { return CanQualType::CreateUnsafe(Iter[n]); } - + CanTypeIterator &operator+=(difference_type n) { Iter += n; return *this; } - + CanTypeIterator &operator-=(difference_type n) { Iter -= n; return *this; } - + friend CanTypeIterator operator+(CanTypeIterator X, difference_type n) { X += n; return X; @@ -413,15 +413,15 @@ public: X += n; return X; } - + friend CanTypeIterator operator-(CanTypeIterator X, difference_type n) { X -= n; return X; } - - friend difference_type operator-(const CanTypeIterator &X, + + friend difference_type operator-(const CanTypeIterator &X, const CanTypeIterator &Y) { - return X - Y; + return X - Y; } }; @@ -431,7 +431,7 @@ struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(QualType::GCAttrTypes, getObjCGCAttr) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getAddressSpace) }; - + template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) @@ -441,66 +441,60 @@ template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) }; - + template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) }; - + template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const Type *, getClass) }; - + template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, getSizeModifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndexTypeQualifier) }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, getSizeModifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndexTypeQualifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const llvm::APInt &, getSize) }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, getSizeModifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndexTypeQualifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const llvm::APInt &, getSize) @@ -509,34 +503,31 @@ struct CanProxyAdaptor LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getLBracketLoc) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getRBracketLoc) }; - + template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, getSizeModifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndexTypeQualifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const llvm::APInt &, getSize) }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, getSizeModifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndexTypeQualifier) }; - + template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, getSizeModifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndexTypeQualifier) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Expr *, getSizeExpr) @@ -546,9 +537,8 @@ struct CanProxyAdaptor }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Expr *, getSizeExpr) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceRange, getBracketsRange) @@ -557,14 +547,13 @@ struct CanProxyAdaptor }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const Expr *, getSizeExpr) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getAttributeLoc) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getAttributeLoc) }; - + template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) @@ -583,28 +572,26 @@ struct CanProxyAdaptor : public CanProxyBase { }; template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getResultType) }; - + template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getResultType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumArgs); + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumArgs); CanQualType getArgType(unsigned i) const { return CanQualType::CreateUnsafe(this->getTypePtr()->getArgType(i)); } - + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVariadic) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getTypeQuals) - - typedef CanTypeIterator + + typedef CanTypeIterator arg_type_iterator; - + arg_type_iterator arg_type_begin() const { return arg_type_iterator(this->getTypePtr()->arg_type_begin()); } @@ -612,10 +599,10 @@ struct CanProxyAdaptor arg_type_iterator arg_type_end() const { return arg_type_iterator(this->getTypePtr()->arg_type_end()); } - + // Note: canonical function types never have exception specifications }; - + template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType) @@ -638,44 +625,42 @@ struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(RecordDecl *, getDecl) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasConstFields) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getAddressSpace) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getAddressSpace) }; - + template<> struct CanProxyAdaptor : public CanProxyBase { LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(EnumDecl *, getDecl) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined) }; - + template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getDepth) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndex) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isParameterPack) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(IdentifierInfo *, getName) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(IdentifierInfo *, getName) }; - + template<> -struct CanProxyAdaptor - : public CanProxyBase -{ +struct CanProxyAdaptor + : public CanProxyBase { LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) - LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const ObjCInterfaceType *, + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const ObjCInterfaceType *, getInterfaceType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCIdType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCClassType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedIdType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedClassType) - + typedef ObjCObjectPointerType::qual_iterator qual_iterator; LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_begin) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_end) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, qual_empty) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumProtocols) }; - + //----------------------------------------------------------------------------// // Method and function definitions //----------------------------------------------------------------------------// @@ -698,12 +683,12 @@ template CanQual CanQual::getFromOpaquePtr(void *Ptr) { CanQual Result; Result.Stored.setFromOpaqueValue(Ptr); - assert((!Result || Result.Stored.isCanonical()) + assert((!Result || Result.Stored.isCanonical()) && "Type is not canonical!"); return Result; } -template +template CanQual CanQual::CreateUnsafe(QualType Other) { assert((Other.isNull() || Other->isCanonical()) && "Type is not canonical!"); assert((Other.isNull() || isa(Other.getTypePtr())) && @@ -713,19 +698,19 @@ CanQual CanQual::CreateUnsafe(QualType Other) { return Result; } -template -template +template +template CanProxy CanQual::getAs() const { if (Stored.isNull()) return CanProxy(); - + if (isa(Stored.getTypePtr())) return CanQual::CreateUnsafe(Stored); - + if (const ExtQualType *EQ = Stored->getAs()) return CanQual::CreateUnsafe(QualType(EQ->getBaseType(), 0)) .template getAs(); - + return CanProxy(); } @@ -733,13 +718,13 @@ template CanProxy CanQual::operator->() const { return CanProxy(*this); } - + template -typename CanTypeIterator::pointer +typename CanTypeIterator::pointer CanTypeIterator::operator->() const { return CanProxy(*this); } - + } diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h index b91816e2adfb8d3c0474d008717d8af0756d0dbd..c4c7d26c5144bdfbe2cc6c6f348678cfb2052c6d 100644 --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -53,18 +53,18 @@ public: /// TranslationUnitDecl - The top declaration context. class TranslationUnitDecl : public Decl, public DeclContext { ASTContext &Ctx; - + explicit TranslationUnitDecl(ASTContext &ctx) : Decl(TranslationUnit, 0, SourceLocation()), DeclContext(TranslationUnit), Ctx(ctx) {} public: ASTContext &getASTContext() const { return Ctx; } - + static TranslationUnitDecl *Create(ASTContext &C); // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == TranslationUnit; } - static bool classof(const TranslationUnitDecl *D) { return true; } + static bool classof(const TranslationUnitDecl *D) { return true; } static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { return static_cast(const_cast(D)); } @@ -113,7 +113,7 @@ public: /// manipulation, so it should be called only when performance doesn't matter. /// For simple declarations, getNameAsCString() should suffice. std::string getNameAsString() const { return Name.getAsString(); } - + /// getQualifiedNameAsString - Returns human-readable qualified name for /// declaration, like A::B::i, for i being member of namespace A::B. /// If declaration is not member of context which can be named (record, @@ -141,7 +141,7 @@ public: const NamedDecl *getUnderlyingDecl() const { return const_cast(this)->getUnderlyingDecl(); } - + static bool classof(const Decl *D) { return D->getKind() >= NamedFirst && D->getKind() <= NamedLast; } @@ -151,7 +151,7 @@ public: /// NamespaceDecl - Represent a C++ namespace. class NamespaceDecl : public NamedDecl, public DeclContext { SourceLocation LBracLoc, RBracLoc; - + // For extended namespace definitions: // // namespace A { int x; } @@ -162,7 +162,7 @@ class NamespaceDecl : public NamedDecl, public DeclContext { // OrigNamespace points to the original namespace declaration. // OrigNamespace of the first namespace decl points to itself. NamespaceDecl *OrigNamespace, *NextNamespace; - + NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id) : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace) { OrigNamespace = this; @@ -171,7 +171,7 @@ class NamespaceDecl : public NamedDecl, public DeclContext { public: static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id); - + virtual void Destroy(ASTContext& C); NamespaceDecl *getNextNamespace() { return NextNamespace; } @@ -182,7 +182,7 @@ public: return OrigNamespace; } void setOriginalNamespace(NamespaceDecl *ND) { OrigNamespace = ND; } - + virtual SourceRange getSourceRange() const { return SourceRange(getLocation(), RBracLoc); } @@ -191,7 +191,7 @@ public: SourceLocation getRBracLoc() const { return RBracLoc; } void setLBracLoc(SourceLocation LBrace) { LBracLoc = LBrace; } void setRBracLoc(SourceLocation RBrace) { RBracLoc = RBrace; } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == Namespace; } static bool classof(const NamespaceDecl *D) { return true; } @@ -203,20 +203,20 @@ public: } }; -/// ValueDecl - Represent the declaration of a variable (in which case it is +/// ValueDecl - Represent the declaration of a variable (in which case it is /// an lvalue) a function (in which case it is a function designator) or -/// an enum constant. +/// an enum constant. class ValueDecl : public NamedDecl { QualType DeclType; protected: ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, - DeclarationName N, QualType T) + DeclarationName N, QualType T) : NamedDecl(DK, DC, L, N), DeclType(T) {} public: QualType getType() const { return DeclType; } void setType(QualType newType) { DeclType = newType; } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= ValueFirst && D->getKind() <= ValueLast; @@ -287,23 +287,23 @@ protected: /// argument. struct UnparsedDefaultArgument; - /// \brief Placeholder type used in Init to denote an uninstantiated C++ + /// \brief Placeholder type used in Init to denote an uninstantiated C++ /// default argument. struct UninstantiatedDefaultArgument; - typedef llvm::PointerUnion4 InitType; - - /// \brief The initializer for this variable or, for a ParmVarDecl, the + + /// \brief The initializer for this variable or, for a ParmVarDecl, the /// C++ default argument. mutable InitType Init; - + private: // FIXME: This can be packed into the bitfields in Decl. unsigned SClass : 3; bool ThreadSpecified : 1; - bool HasCXXDirectInit : 1; + bool HasCXXDirectInit : 1; /// DeclaredInCondition - Whether this variable was declared in a /// condition, e.g., if (int x = foo()) { ... }. @@ -315,8 +315,8 @@ protected: QualType T, DeclaratorInfo *DInfo, StorageClass SC) : DeclaratorDecl(DK, DC, L, Id, T, DInfo), Init(), ThreadSpecified(false), HasCXXDirectInit(false), - DeclaredInCondition(false) { - SClass = SC; + DeclaredInCondition(false) { + SClass = SC; } typedef Redeclarable redeclarable_base; @@ -326,7 +326,7 @@ public: typedef redeclarable_base::redecl_iterator redecl_iterator; redecl_iterator redecls_begin() const { return redeclarable_base::redecls_begin(); - } + } redecl_iterator redecls_end() const { return redeclarable_base::redecls_end(); } @@ -340,10 +340,10 @@ public: StorageClass getStorageClass() const { return (StorageClass)SClass; } void setStorageClass(StorageClass SC) { SClass = SC; } - + virtual SourceRange getSourceRange() const; - const Expr *getInit() const { + const Expr *getInit() const { if (Init.isNull()) return 0; @@ -352,9 +352,9 @@ public: if (EvaluatedStmt *ES = Init.dyn_cast()) S = ES->Value; } - return (const Expr*) S; + return (const Expr*) S; } - Expr *getInit() { + Expr *getInit() { if (Init.isNull()) return 0; @@ -364,26 +364,26 @@ public: S = ES->Value; } - return (Expr*) S; + return (Expr*) S; } /// \brief Retrieve the address of the initializer expression. Stmt **getInitAddress() { if (EvaluatedStmt *ES = Init.dyn_cast()) return &ES->Value; - + // This union hack tip-toes around strict-aliasing rules. union { InitType *InitPtr; Stmt **StmtPtr; }; - + InitPtr = &Init; return StmtPtr; } void setInit(ASTContext &C, Expr *I); - + /// \brief Note that constant evaluation has computed the given /// value for this variable's initializer. void setEvaluatedValue(ASTContext &C, const APValue &Value) const { @@ -398,7 +398,7 @@ public: Eval->WasEvaluated = true; Eval->Evaluated = Value; } - + /// \brief Return the already-evaluated value of this variable's /// initializer, or NULL if the value is not yet known. APValue *getEvaluatedValue() const { @@ -423,7 +423,7 @@ public: /// /// \pre isInitKnownICE() bool isInitICE() const { - assert(isInitKnownICE() && + assert(isInitKnownICE() && "Check whether we already know that the initializer is an ICE"); return Init.get()->IsICE; } @@ -465,7 +465,7 @@ public: bool hasCXXDirectInitializer() const { return HasCXXDirectInit; } - + /// isDeclaredInCondition - Whether this variable was declared as /// part of a condition in an if/switch/while statement, e.g., /// @code @@ -474,8 +474,8 @@ public: bool isDeclaredInCondition() const { return DeclaredInCondition; } - void setDeclaredInCondition(bool InCondition) { - DeclaredInCondition = InCondition; + void setDeclaredInCondition(bool InCondition) { + DeclaredInCondition = InCondition; } virtual VarDecl *getCanonicalDecl(); @@ -485,10 +485,10 @@ public: bool hasLocalStorage() const { if (getStorageClass() == None) return !isFileVarDecl(); - + // Return true for: Auto, Register. // Return false for: Extern, Static, PrivateExtern. - + return getStorageClass() <= Register; } @@ -515,7 +515,7 @@ public: return DC->getLookupContext()->isFunctionOrMethod(); return false; } - + /// \brief Determines whether this is a static data member. /// /// This will only be true in C++, and applies to, e.g., the @@ -530,10 +530,10 @@ public: } /// \brief If this variable is an instantiated static data member of a - /// class template specialization, returns the templated static data member + /// class template specialization, returns the templated static data member /// from which it was instantiated. - VarDecl *getInstantiatedFromStaticDataMember(); - + VarDecl *getInstantiatedFromStaticDataMember(); + /// isFileVarDecl - Returns true for file scoped variable declaration. bool isFileVarDecl() const { if (getKind() != Decl::Var) @@ -545,14 +545,14 @@ public: } if (isStaticDataMember()) return true; - + return false; } /// \brief Determine whether this is a tentative definition of a /// variable in C. bool isTentativeDefinition(ASTContext &Context) const; - + /// \brief Determines whether this variable is a variable with /// external, C linkage. bool isExternC(ASTContext &Context) const; @@ -567,7 +567,7 @@ public: class ImplicitParamDecl : public VarDecl { protected: ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L, - IdentifierInfo *Id, QualType Tw) + IdentifierInfo *Id, QualType Tw) : VarDecl(DK, DC, L, Id, Tw, /*DInfo=*/0, VarDecl::None) {} public: static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, @@ -584,15 +584,15 @@ class ParmVarDecl : public VarDecl { /// FIXME: Also can be paced into the bitfields in Decl. /// in, inout, etc. unsigned objcDeclQualifier : 6; - - /// \brief Retrieves the fake "value" of an unparsed + + /// \brief Retrieves the fake "value" of an unparsed static Expr *getUnparsedDefaultArgValue() { uintptr_t Value = (uintptr_t)-1; // Mask off the low bits Value &= ~(uintptr_t)0x07; return reinterpret_cast (Value); } - + protected: ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo, @@ -606,27 +606,27 @@ public: SourceLocation L,IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo, StorageClass S, Expr *DefArg); - + ObjCDeclQualifier getObjCDeclQualifier() const { return ObjCDeclQualifier(objcDeclQualifier); } void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { objcDeclQualifier = QTVal; } - - const Expr *getDefaultArg() const { + + const Expr *getDefaultArg() const { assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); - assert(!hasUninstantiatedDefaultArg() && + assert(!hasUninstantiatedDefaultArg() && "Default argument is not yet instantiated!"); return getInit(); } - Expr *getDefaultArg() { + Expr *getDefaultArg() { assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); - assert(!hasUninstantiatedDefaultArg() && + assert(!hasUninstantiatedDefaultArg() && "Default argument is not yet instantiated!"); return getInit(); } - void setDefaultArg(Expr *defarg) { + void setDefaultArg(Expr *defarg) { Init = reinterpret_cast(defarg); } @@ -636,14 +636,14 @@ public: Expr *getUninstantiatedDefaultArg() { return (Expr *)Init.get(); } - + /// hasDefaultArg - Determines whether this parameter has a default argument, /// either parsed or not. bool hasDefaultArg() const { - return getInit() || hasUnparsedDefaultArg() || + return getInit() || hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg(); } - + /// hasUnparsedDefaultArg - Determines whether this parameter has a /// default argument that has not yet been parsed. This will occur /// during the processing of a C++ class whose member functions have @@ -661,18 +661,18 @@ public: bool hasUninstantiatedDefaultArg() const { return Init.is(); } - + /// setUnparsedDefaultArg - Specify that this parameter has an /// unparsed default argument. The argument will be replaced with a /// real default argument via setDefaultArg when the class /// definition enclosing the function declaration that owns this /// default argument is completed. - void setUnparsedDefaultArg() { + void setUnparsedDefaultArg() { Init = (UnparsedDefaultArgument *)0; } QualType getOriginalType() const; - + /// setOwningFunction - Sets the function declaration that owns this /// ParmVarDecl. Since ParmVarDecls are often created before the /// FunctionDecls that own them, this routine is required to update @@ -680,9 +680,9 @@ public: void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return (D->getKind() == ParmVar || - D->getKind() == OriginalParmVar); + D->getKind() == OriginalParmVar); } static bool classof(const ParmVarDecl *D) { return true; } }; @@ -698,7 +698,7 @@ protected: private: OriginalParmVarDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, - DeclaratorInfo *DInfo, + DeclaratorInfo *DInfo, QualType OT, StorageClass S, Expr *DefArg) : ParmVarDecl(OriginalParmVar, DC, L, Id, T, DInfo, S, DefArg), @@ -715,7 +715,7 @@ public: static bool classof(const Decl *D) { return D->getKind() == OriginalParmVar; } static bool classof(const OriginalParmVarDecl *D) { return true; } }; - + // \brief Describes the kind of template specialization that a // particular template specialization declaration represents. enum TemplateSpecializationKind { @@ -730,17 +730,17 @@ enum TemplateSpecializationKind { /// specialization (C++ [temp.class.spec]). TSK_ExplicitSpecialization, /// This template specialization was instantiated from a template - /// due to an explicit instantiation declaration request + /// due to an explicit instantiation declaration request /// (C++0x [temp.explicit]). TSK_ExplicitInstantiationDeclaration, /// This template specialization was instantiated from a template - /// due to an explicit instantiation definition request + /// due to an explicit instantiation definition request /// (C++ [temp.explicit]). - TSK_ExplicitInstantiationDefinition + TSK_ExplicitInstantiationDefinition }; - + /// FunctionDecl - An instance of this class is created to represent a -/// function declaration or definition. +/// function declaration or definition. /// /// Since a given function can be declared several times in a program, /// there may be several FunctionDecls that correspond to that @@ -749,20 +749,20 @@ enum TemplateSpecializationKind { /// FunctionDecl (e.g., the translation unit); this FunctionDecl /// contains all of the information known about the function. Other, /// previous declarations of the function are available via the -/// getPreviousDeclaration() chain. +/// getPreviousDeclaration() chain. class FunctionDecl : public DeclaratorDecl, public DeclContext, public Redeclarable { public: enum StorageClass { None, Extern, Static, PrivateExtern }; - -private: + +private: /// ParamInfo - new[]'d array of pointers to VarDecls for the formal /// parameters of this function. This is null if a prototype or if there are /// no formals. ParmVarDecl **ParamInfo; - + LazyDeclStmtPtr Body; // FIXME: This can be packed into the bitfields in Decl. @@ -778,7 +778,7 @@ private: bool IsTrivial : 1; // sunk from CXXMethodDecl bool IsCopyAssignment : 1; // sunk from CXXMethodDecl bool HasImplicitReturnZero : 1; - + /// \brief End part of this FunctionDecl's source range. /// /// We could compute the full range in getSourceRange(). However, when we're @@ -790,15 +790,15 @@ private: /// \brief The template or declaration that this declaration /// describes or was instantiated from, respectively. - /// + /// /// For non-templates, this value will be NULL. For function /// declarations that describe a function template, this will be a /// pointer to a FunctionTemplateDecl. For member functions /// of class template specializations, this will be the /// FunctionDecl from which the member function was instantiated. - /// For function template specializations, this will be a + /// For function template specializations, this will be a /// FunctionTemplateSpecializationInfo, which contains information about - /// the template being specialized and the template arguments involved in + /// the template being specialized and the template arguments involved in /// that specialization. llvm::PointerUnion3 @@ -808,11 +808,11 @@ protected: FunctionDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, DeclaratorInfo *DInfo, StorageClass S, bool isInline) - : DeclaratorDecl(DK, DC, L, N, T, DInfo), + : DeclaratorDecl(DK, DC, L, N, T, DInfo), DeclContext(DK), ParamInfo(0), Body(), - SClass(S), IsInline(isInline), C99InlineDefinition(false), - IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false), + SClass(S), IsInline(isInline), C99InlineDefinition(false), + IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false), HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false), IsCopyAssignment(false), HasImplicitReturnZero(false), @@ -828,7 +828,7 @@ public: typedef redeclarable_base::redecl_iterator redecl_iterator; redecl_iterator redecls_begin() const { return redeclarable_base::redecls_begin(); - } + } redecl_iterator redecls_end() const { return redeclarable_base::redecls_end(); } @@ -888,7 +888,7 @@ public: /// the class has been fully built by Sema. bool isTrivial() const { return IsTrivial; } void setTrivial(bool IT) { IsTrivial = IT; } - + bool isCopyAssignment() const { return IsCopyAssignment; } void setCopyAssignment(bool CA) { IsCopyAssignment = CA; } @@ -902,10 +902,10 @@ public: /// was explicitly written or because it was "inherited" by merging /// a declaration without a prototype with a declaration that has a /// prototype. - bool hasPrototype() const { - return HasWrittenPrototype || HasInheritedPrototype; + bool hasPrototype() const { + return HasWrittenPrototype || HasInheritedPrototype; } - + bool hasWrittenPrototype() const { return HasWrittenPrototype; } void setHasWrittenPrototype(bool P) { HasWrittenPrototype = P; } @@ -953,23 +953,23 @@ public: unsigned getBuiltinID(ASTContext &Context) const; unsigned getNumParmVarDeclsFromType() const; - + // Iterator access to formal parameters. unsigned param_size() const { return getNumParams(); } typedef ParmVarDecl **param_iterator; typedef ParmVarDecl * const *param_const_iterator; - + param_iterator param_begin() { return ParamInfo; } param_iterator param_end() { return ParamInfo+param_size(); } - + param_const_iterator param_begin() const { return ParamInfo; } param_const_iterator param_end() const { return ParamInfo+param_size(); } - + /// getNumParams - Return the number of parameters this function must have /// based on its functiontype. This is the length of the PararmInfo array /// after it has been created. unsigned getNumParams() const; - + const ParmVarDecl *getParamDecl(unsigned i) const { assert(i < getNumParams() && "Illegal param #"); return ParamInfo[i]; @@ -986,7 +986,7 @@ public: /// arguments (in C++). unsigned getMinRequiredArguments() const; - QualType getResultType() const { + QualType getResultType() const { return getType()->getAsFunctionType()->getResultType(); } StorageClass getStorageClass() const { return StorageClass(SClass); } @@ -1015,7 +1015,7 @@ public: /// isOverloadedOperator - Whether this function declaration /// represents an C++ overloaded operator, e.g., "operator+". - bool isOverloadedOperator() const { + bool isOverloadedOperator() const { return getOverloadedOperator() != OO_None; }; @@ -1048,7 +1048,7 @@ public: /// \brief Specify that this record is an instantiation of the /// member function RD. - void setInstantiationOfMemberFunction(FunctionDecl *RD) { + void setInstantiationOfMemberFunction(FunctionDecl *RD) { TemplateOrSpecialization = RD; } @@ -1078,14 +1078,14 @@ public: /// If this function declaration is not a function template specialization, /// returns NULL. FunctionTemplateDecl *getPrimaryTemplate() const; - + /// \brief Retrieve the template arguments used to produce this function /// template specialization from the primary template. /// /// If this function declaration is not a function template specialization, /// returns NULL. - const TemplateArgumentList *getTemplateSpecializationArgs() const; - + const TemplateArgumentList *getTemplateSpecializationArgs() const; + /// \brief Specify that this function declaration is actually a function /// template specialization. /// @@ -1108,7 +1108,7 @@ public: /// \brief Determine what kind of template instantiation this function /// represents. void setTemplateSpecializationKind(TemplateSpecializationKind TSK); - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= FunctionFirst && D->getKind() <= FunctionLast; @@ -1123,21 +1123,21 @@ public: }; -/// FieldDecl - An instance of this class is created by Sema::ActOnField to +/// FieldDecl - An instance of this class is created by Sema::ActOnField to /// represent a member of a struct/union/class. class FieldDecl : public DeclaratorDecl { // FIXME: This can be packed into the bitfields in Decl. bool Mutable : 1; Expr *BitWidth; protected: - FieldDecl(Kind DK, DeclContext *DC, SourceLocation L, + FieldDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo, Expr *BW, bool Mutable) - : DeclaratorDecl(DK, DC, L, Id, T, DInfo), Mutable(Mutable), BitWidth(BW) - { } + : DeclaratorDecl(DK, DC, L, Id, T, DInfo), Mutable(Mutable), BitWidth(BW) { + } public: - static FieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, + static FieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo, Expr *BW, bool Mutable); @@ -1189,7 +1189,7 @@ public: SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V); - + virtual void Destroy(ASTContext& C); const Expr *getInitExpr() const { return (const Expr*) Init; } @@ -1198,11 +1198,11 @@ public: void setInitExpr(Expr *E) { Init = (Stmt*) E; } void setInitVal(const llvm::APSInt &V) { Val = V; } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == EnumConstant; } static bool classof(const EnumConstantDecl *D) { return true; } - + friend class StmtIteratorBase; }; @@ -1244,16 +1244,16 @@ class TypedefDecl : public TypeDecl { /// UnderlyingType - This is the type the typedef is set to. QualType UnderlyingType; TypedefDecl(DeclContext *DC, SourceLocation L, - IdentifierInfo *Id, QualType T) + IdentifierInfo *Id, QualType T) : TypeDecl(Typedef, DC, L, Id), UnderlyingType(T) {} virtual ~TypedefDecl() {} public: - + static TypedefDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,IdentifierInfo *Id, QualType T); - + QualType getUnderlyingType() const { return UnderlyingType; } void setUnderlyingType(QualType newType) { UnderlyingType = newType; } @@ -1263,9 +1263,9 @@ public: }; class TypedefDecl; - + /// TagDecl - Represents the declaration of a struct/union/class/enum. -class TagDecl +class TagDecl : public TypeDecl, public DeclContext, public Redeclarable { public: // This is really ugly. @@ -1283,7 +1283,7 @@ private: /// IsDefinition - True if this is a definition ("struct foo {};"), false if /// it is a declaration ("struct foo;"). bool IsDefinition : 1; - + /// TypedefForAnonDecl - If a TagDecl is anonymous and part of a typedef, /// this points to the TypedefDecl. Used for mangling. TypedefDecl *TypedefForAnonDecl; @@ -1302,19 +1302,19 @@ protected: IsDefinition = false; setPreviousDeclaration(PrevDecl); } - + typedef Redeclarable redeclarable_base; virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); } - + public: typedef redeclarable_base::redecl_iterator redecl_iterator; redecl_iterator redecls_begin() const { return redeclarable_base::redecls_begin(); - } + } redecl_iterator redecls_end() const { return redeclarable_base::redecls_end(); } - + SourceLocation getRBraceLoc() const { return RBraceLoc; } void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } @@ -1322,7 +1322,7 @@ public: void setTagKeywordLoc(SourceLocation TKL) { TagKeywordLoc = TKL; } virtual SourceRange getSourceRange() const; - + virtual TagDecl* getCanonicalDecl(); /// isDefinition - Return true if this decl has its body specified. @@ -1336,7 +1336,7 @@ public: bool isDependentType() const { return isDependentContext(); } /// @brief Starts the definition of this tag declaration. - /// + /// /// This method should be invoked at the beginning of the definition /// of this tag declaration. It will set the tag type into a state /// where it is in the process of being defined. @@ -1345,7 +1345,7 @@ public: /// @brief Completes the definition of this tag declaration. void completeDefinition(); - /// getDefinition - Returns the TagDecl that actually defines this + /// getDefinition - Returns the TagDecl that actually defines this /// struct/union/class/enum. When determining whether or not a /// struct/union/class/enum is completely defined, one should use this method /// as opposed to 'isDefinition'. 'isDefinition' indicates whether or not a @@ -1353,7 +1353,7 @@ public: /// struct/union/class/enum type is defined. This method returns NULL if /// there is no TagDecl that defines the struct/union/class/enum. TagDecl* getDefinition(ASTContext& C) const; - + const char *getKindName() const { return ElaboratedType::getNameForTagKind(getTagKind()); } @@ -1373,10 +1373,10 @@ public: bool isClass() const { return getTagKind() == TK_class; } bool isUnion() const { return getTagKind() == TK_union; } bool isEnum() const { return getTagKind() == TK_enum; } - + TypedefDecl *getTypedefForAnonDecl() const { return TypedefForAnonDecl; } void setTypedefForAnonDecl(TypedefDecl *TDD) { TypedefForAnonDecl = TDD; } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= TagFirst && D->getKind() <= TagLast; @@ -1419,7 +1419,7 @@ public: static EnumDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, SourceLocation TKL, EnumDecl *PrevDecl); - + virtual void Destroy(ASTContext& C); /// completeDefinition - When created, the EnumDecl corresponds to a @@ -1428,16 +1428,16 @@ public: /// added (via DeclContext::addDecl). NewType is the new underlying /// type of the enumeration type. void completeDefinition(ASTContext &C, QualType NewType); - + // enumerator_iterator - Iterates through the enumerators of this // enumeration. typedef specific_decl_iterator enumerator_iterator; - enumerator_iterator enumerator_begin() const { + enumerator_iterator enumerator_begin() const { return enumerator_iterator(this->decls_begin()); } - enumerator_iterator enumerator_end() const { + enumerator_iterator enumerator_end() const { return enumerator_iterator(this->decls_end()); } @@ -1477,14 +1477,14 @@ class RecordDecl : public TagDecl { /// AnonymousStructOrUnion - Whether this is the type of an /// anonymous struct or union. bool AnonymousStructOrUnion : 1; - + /// HasObjectMember - This is true if this struct has at least one - /// member containing an object + /// member containing an object bool HasObjectMember : 1; protected: RecordDecl(Kind DK, TagKind TK, DeclContext *DC, - SourceLocation L, IdentifierInfo *Id, + SourceLocation L, IdentifierInfo *Id, RecordDecl *PrevDecl, SourceLocation TKL); virtual ~RecordDecl(); @@ -1495,7 +1495,7 @@ public: RecordDecl* PrevDecl = 0); virtual void Destroy(ASTContext& C); - + bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } @@ -1505,7 +1505,7 @@ public: /// type declared, e.g., /// @code /// union { int i; float f; }; - /// @endcode + /// @endcode /// is an anonymous union but neither of the following are: /// @code /// union X { int i; float f; }; @@ -1518,7 +1518,7 @@ public: bool hasObjectMember() const { return HasObjectMember; } void setHasObjectMember (bool val) { HasObjectMember = val; } - + /// \brief Determines whether this declaration represents the /// injected class name. /// @@ -1534,7 +1534,7 @@ public: /// \endcode bool isInjectedClassName() const; - /// getDefinition - Returns the RecordDecl that actually defines this + /// getDefinition - Returns the RecordDecl that actually defines this /// struct/union/class. When determining whether or not a struct/union/class /// is completely defined, one should use this method as opposed to /// 'isDefinition'. 'isDefinition' indicates whether or not a specific @@ -1544,7 +1544,7 @@ public: RecordDecl* getDefinition(ASTContext& C) const { return cast_or_null(TagDecl::getDefinition(C)); } - + // Iterator access to field members. The field iterator only visits // the non-static data members of this class, ignoring any static // data members, functions, constructors, destructors, etc. @@ -1559,7 +1559,7 @@ public: // field_empty - Whether there are any fields (non-static data // members) in this record. - bool field_empty() const { + bool field_empty() const { return field_begin() == field_end(); } @@ -1588,7 +1588,7 @@ public: static bool classof(const Decl *D) { return D->getKind() == FileScopeAsm; } - static bool classof(const FileScopeAsmDecl *D) { return true; } + static bool classof(const FileScopeAsmDecl *D) { return true; } }; /// BlockDecl - This represents a block literal declaration, which is like an @@ -1603,12 +1603,12 @@ class BlockDecl : public Decl, public DeclContext { /// no formals. ParmVarDecl **ParamInfo; unsigned NumParams; - + Stmt *Body; - + protected: BlockDecl(DeclContext *DC, SourceLocation CaretLoc) - : Decl(Block, DC, CaretLoc), DeclContext(Block), + : Decl(Block, DC, CaretLoc), DeclContext(Block), isVariadic(false), ParamInfo(0), NumParams(0), Body(0) {} virtual ~BlockDecl(); @@ -1621,7 +1621,7 @@ public: bool IsVariadic() const { return isVariadic; } void setIsVariadic(bool value) { isVariadic = value; } - + CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } Stmt *getBody() const { return (Stmt*) Body; } void setBody(CompoundStmt *B) { Body = (Stmt*) B; } @@ -1630,14 +1630,14 @@ public: unsigned param_size() const { return getNumParams(); } typedef ParmVarDecl **param_iterator; typedef ParmVarDecl * const *param_const_iterator; - + bool param_empty() const { return NumParams == 0; } param_iterator param_begin() { return ParamInfo; } param_iterator param_end() { return ParamInfo+param_size(); } - + param_const_iterator param_begin() const { return ParamInfo; } param_const_iterator param_end() const { return ParamInfo+param_size(); } - + unsigned getNumParams() const; const ParmVarDecl *getParamDecl(unsigned i) const { assert(i < getNumParams() && "Illegal param #"); @@ -1648,10 +1648,10 @@ public: return ParamInfo[i]; } void setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NumParams); - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == Block; } - static bool classof(const BlockDecl *D) { return true; } + static bool classof(const BlockDecl *D) { return true; } static DeclContext *castToDeclContext(const BlockDecl *D) { return static_cast(const_cast(D)); } diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h index 6e04e553129b2ed4f955d8b7d08bce12b031240f..342eecbf5717300c00f92bd34841b6a1c0d542d6 100644 --- a/clang/include/clang/AST/DeclBase.h +++ b/clang/include/clang/AST/DeclBase.h @@ -60,8 +60,8 @@ public: namespace clang { -/// Decl - This represents one declaration (or definition), e.g. a variable, -/// typedef, function, struct, etc. +/// Decl - This represents one declaration (or definition), e.g. a variable, +/// typedef, function, struct, etc. /// class Decl { public: @@ -69,7 +69,7 @@ public: enum Kind { #define DECL(Derived, Base) Derived, #define DECL_RANGE(CommonBase, Start, End) \ - CommonBase##First = Start, CommonBase##Last = End, + CommonBase##First = Start, CommonBase##Last = End, #define LAST_DECL_RANGE(CommonBase, Start, End) \ CommonBase##First = Start, CommonBase##Last = End #include "clang/AST/DeclNodes.def" @@ -93,7 +93,7 @@ public: IDNS_OrdinaryFriend = 0x80, IDNS_TagFriend = 0x100 }; - + /// ObjCDeclQualifier - Qualifier used on types in method declarations /// for remote messaging. They are meant for the arguments though and /// applied to the Decls (ObjCMethodDecl and ParmVarDecl). @@ -106,7 +106,7 @@ public: OBJC_TQ_Byref = 0x10, OBJC_TQ_Oneway = 0x20 }; - + private: /// NextDeclInContext - The next declaration within the same lexical /// DeclContext. These pointers form the linked list that is @@ -119,8 +119,8 @@ private: DeclContext *SemanticDC; DeclContext *LexicalDC; }; - - + + /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. /// For declarations that don't contain C++ scope specifiers, it contains /// the DeclContext where the Decl was declared. @@ -144,16 +144,16 @@ private: inline DeclContext *getSemanticDC() const { return DeclCtx.get(); } - + /// Loc - The location that this decl. SourceLocation Loc; - + /// DeclKind - This indicates which class this is. Kind DeclKind : 8; - + /// InvalidDecl - This indicates a semantic error occurred. unsigned int InvalidDecl : 1; - + /// HasAttrs - This indicates whether the decl has attributes or not. unsigned int HasAttrs : 1; @@ -168,22 +168,22 @@ private: protected: /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. unsigned IdentifierNamespace : 16; - + private: #ifndef NDEBUG void CheckAccessDeclContext() const; #else void CheckAccessDeclContext() const { } #endif - + protected: /// Access - Used by C++ decls for the access specifier. // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum unsigned Access : 2; friend class CXXClassMemberWrapper; - Decl(Kind DK, DeclContext *DC, SourceLocation L) - : NextDeclInContext(0), DeclCtx(DC), + Decl(Kind DK, DeclContext *DC, SourceLocation L) + : NextDeclInContext(0), DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(0), HasAttrs(false), Implicit(false), Used(false), IdentifierNamespace(getIdentifierNamespaceForKind(DK)), Access(AS_none) { @@ -206,7 +206,7 @@ public: Kind getKind() const { return DeclKind; } const char *getDeclKindName() const; - + Decl *getNextDeclInContext() { return NextDeclInContext; } const Decl *getNextDeclInContext() const { return NextDeclInContext; } @@ -225,15 +225,15 @@ public: } ASTContext &getASTContext() const; - + void setAccess(AccessSpecifier AS) { - Access = AS; + Access = AS; CheckAccessDeclContext(); } - - AccessSpecifier getAccess() const { + + AccessSpecifier getAccess() const { CheckAccessDeclContext(); - return AccessSpecifier(Access); + return AccessSpecifier(Access); } bool hasAttrs() const { return HasAttrs; } @@ -251,11 +251,11 @@ public: return V; return 0; } - + template bool hasAttr() const { return getAttr() != 0; } - + /// setInvalidDecl - Indicates the Decl had a semantic error. This /// allows for graceful error recovery. void setInvalidDecl(bool Invalid = true) { InvalidDecl = Invalid; } @@ -266,12 +266,12 @@ public: /// was written explicitly in the source code. bool isImplicit() const { return Implicit; } void setImplicit(bool I = true) { Implicit = I; } - + /// \brief Whether this declaration was used, meaning that a definition /// is required. bool isUsed() const { return Used; } void setUsed(bool U = true) { Used = U; } - + unsigned getIdentifierNamespace() const { return IdentifierNamespace; } @@ -280,7 +280,7 @@ public: } static unsigned getIdentifierNamespaceForKind(Kind DK); - + /// getLexicalDeclContext - The declaration context where this Decl was /// lexically declared (LexicalDC). May be different from /// getDeclContext() (SemanticDC). @@ -303,7 +303,7 @@ public: bool isOutOfLine() const { return getLexicalDeclContext() != getDeclContext(); } - + /// setDeclContext - Set both the semantic and lexical DeclContext /// to DC. void setDeclContext(DeclContext *DC); @@ -324,7 +324,7 @@ public: /// \brief Whether this particular Decl is a canonical one. bool isCanonicalDecl() const { return getCanonicalDecl() == this; } - + protected: /// \brief Returns the next redeclaration or itself if this is the only decl. /// @@ -367,10 +367,10 @@ public: return tmp; } - friend bool operator==(redecl_iterator x, redecl_iterator y) { + friend bool operator==(redecl_iterator x, redecl_iterator y) { return x.Current == y.Current; } - friend bool operator!=(redecl_iterator x, redecl_iterator y) { + friend bool operator!=(redecl_iterator x, redecl_iterator y) { return x.Current != y.Current; } }; @@ -398,11 +398,11 @@ public: static void addDeclKind(Kind k); static bool CollectingStats(bool Enable = false); static void PrintStats(); - + /// isTemplateParameter - Determines whether this declaration is a /// template parameter. bool isTemplateParameter() const; - + /// isTemplateParameter - Determines whether this declaration is a /// template parameter pack. bool isTemplateParameterPack() const; @@ -445,12 +445,12 @@ public: if (!mask) return FOK_None; return (mask & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared : FOK_Undeclared); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *) { return true; } static DeclContext *castToDeclContext(const Decl *); static Decl *castFromDeclContext(const DeclContext *); - + /// Destroy - Call destructors and release memory. virtual void Destroy(ASTContext& C); @@ -478,10 +478,10 @@ public: PrettyStackTraceDecl(Decl *theDecl, SourceLocation L, SourceManager &sm, const char *Msg) : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} - + virtual void print(llvm::raw_ostream &OS) const; -}; - +}; + /// DeclContext - This is used only as base class of specific decl types that /// can act as declaration contexts. These decls are (only the top classes @@ -526,9 +526,9 @@ class DeclContext { mutable Decl *LastDecl; protected: - DeclContext(Decl::Kind K) + DeclContext(Decl::Kind K) : DeclKind(K), ExternalLexicalStorage(false), - ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0), + ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0), LastDecl(0) { } void DestroyDecls(ASTContext &C); @@ -548,7 +548,7 @@ public: const DeclContext *getParent() const { return const_cast(this)->getParent(); } - + /// getLexicalParent - Returns the containing lexical DeclContext. May be /// different from getParent, e.g.: /// @@ -563,7 +563,7 @@ public: } const DeclContext *getLexicalParent() const { return const_cast(this)->getLexicalParent(); - } + } ASTContext &getParentASTContext() const { return cast(this)->getASTContext(); @@ -604,10 +604,10 @@ public: /// context are semantically declared in the nearest enclosing /// non-transparent (opaque) context but are lexically declared in /// this context. For example, consider the enumerators of an - /// enumeration type: + /// enumeration type: /// @code /// enum E { - /// Val1 + /// Val1 /// }; /// @endcode /// Here, E is a transparent context, so its enumerator (Val1) will @@ -622,7 +622,7 @@ public: bool Equals(DeclContext *DC) { return this->getPrimaryContext() == DC->getPrimaryContext(); } - + /// \brief Determine whether this declaration context encloses the /// declaration context DC. bool Encloses(DeclContext *DC); @@ -643,7 +643,7 @@ public: const DeclContext *getLookupContext() const { return const_cast(this)->getLookupContext(); } - + /// \brief Retrieve the nearest enclosing namespace context. DeclContext *getEnclosingNamespaceContext(); const DeclContext *getEnclosingNamespaceContext() const { @@ -699,16 +699,16 @@ public: return tmp; } - friend bool operator==(decl_iterator x, decl_iterator y) { + friend bool operator==(decl_iterator x, decl_iterator y) { return x.Current == y.Current; } - friend bool operator!=(decl_iterator x, decl_iterator y) { + friend bool operator!=(decl_iterator x, decl_iterator y) { return x.Current != y.Current; } }; /// decls_begin/decls_end - Iterate over the declarations stored in - /// this context. + /// this context. decl_iterator decls_begin() const; decl_iterator decls_end() const; bool decls_empty() const; @@ -724,7 +724,7 @@ public: /// will either be NULL or will point to a declaration of /// type SpecificDecl. DeclContext::decl_iterator Current; - + /// SkipToNextDecl - Advances the current position up to the next /// declaration of type SpecificDecl that also meets the criteria /// required by Acceptable. @@ -769,13 +769,13 @@ public: ++(*this); return tmp; } - + friend bool operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) { return x.Current == y.Current; } - - friend bool + + friend bool operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) { return x.Current != y.Current; } @@ -796,7 +796,7 @@ public: /// will either be NULL or will point to a declaration of /// type SpecificDecl. DeclContext::decl_iterator Current; - + /// SkipToNextDecl - Advances the current position up to the next /// declaration of type SpecificDecl that also meets the criteria /// required by Acceptable. @@ -843,13 +843,13 @@ public: ++(*this); return tmp; } - + friend bool operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) { return x.Current == y.Current; } - - friend bool + + friend bool operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) { return x.Current != y.Current; } @@ -920,7 +920,7 @@ public: /// udir_iterator - Iterates through the using-directives stored /// within this context. typedef UsingDirectiveDecl * const * udir_iterator; - + typedef std::pair udir_iterator_range; udir_iterator_range getUsingDirectives() const; @@ -944,8 +944,8 @@ public: /// \brief State whether this DeclContext has external storage for /// declarations lexically in this context. - void setHasExternalLexicalStorage(bool ES = true) { - ExternalLexicalStorage = ES; + void setHasExternalLexicalStorage(bool ES = true) { + ExternalLexicalStorage = ES; } /// \brief Whether this DeclContext has external storage containing @@ -954,8 +954,8 @@ public: /// \brief State whether this DeclContext has external storage for /// declarations visible in this context. - void setHasExternalVisibleStorage(bool ES = true) { - ExternalVisibleStorage = ES; + void setHasExternalVisibleStorage(bool ES = true) { + ExternalVisibleStorage = ES; } static bool classof(const Decl *D); diff --git a/clang/include/clang/AST/DeclCXX.h b/clang/include/clang/AST/DeclCXX.h index ce6e925a9a6ff1060e2bbb1077a2d83488fc439c..23da3e02837b6ccecd67dae1761f8063429c4903 100644 --- a/clang/include/clang/AST/DeclCXX.h +++ b/clang/include/clang/AST/DeclCXX.h @@ -28,33 +28,33 @@ class CXXConversionDecl; class CXXMethodDecl; class ClassTemplateSpecializationDecl; -/// \brief Represents any kind of function declaration, whether it is a +/// \brief Represents any kind of function declaration, whether it is a /// concrete function or a function template. class AnyFunctionDecl { NamedDecl *Function; - + AnyFunctionDecl(NamedDecl *ND) : Function(ND) { } - + public: AnyFunctionDecl(FunctionDecl *FD) : Function(FD) { } AnyFunctionDecl(FunctionTemplateDecl *FTD); - - /// \brief Implicily converts any function or function template into a + + /// \brief Implicily converts any function or function template into a /// named declaration. operator NamedDecl *() const { return Function; } - + /// \brief Retrieve the underlying function or function template. NamedDecl *get() const { return Function; } - - static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) { + + static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) { return AnyFunctionDecl(ND); } }; - + } // end namespace clang namespace llvm { - /// Implement simplify_type for AnyFunctionDecl, so that we can dyn_cast from + /// Implement simplify_type for AnyFunctionDecl, so that we can dyn_cast from /// AnyFunctionDecl to any function or function template declaration. template<> struct simplify_type { typedef ::clang::NamedDecl* SimpleType; @@ -64,26 +64,26 @@ namespace llvm { }; template<> struct simplify_type< ::clang::AnyFunctionDecl> : public simplify_type {}; - + // Provide PointerLikeTypeTraits for non-cvr pointers. template<> class PointerLikeTypeTraits< ::clang::AnyFunctionDecl> { public: static inline void *getAsVoidPointer(::clang::AnyFunctionDecl F) { - return F.get(); + return F.get(); } static inline ::clang::AnyFunctionDecl getFromVoidPointer(void *P) { return ::clang::AnyFunctionDecl::getFromNamedDecl( static_cast< ::clang::NamedDecl*>(P)); } - + enum { NumLowBitsAvailable = 2 }; }; - + } // end namespace llvm namespace clang { - + /// OverloadedFunctionDecl - An instance of this class represents a /// set of overloaded functions. All of the functions have the same /// name and occur within the same scope. @@ -128,56 +128,56 @@ public: unsigned size() const { return Functions.size(); } // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { - return D->getKind() == OverloadedFunction; + static bool classof(const Decl *D) { + return D->getKind() == OverloadedFunction; } static bool classof(const OverloadedFunctionDecl *D) { return true; } }; - -/// \brief Provides uniform iteration syntax for an overload set, function, + +/// \brief Provides uniform iteration syntax for an overload set, function, /// or function template. class OverloadIterator { /// \brief An overloaded function set, function declaration, or /// function template declaration. NamedDecl *D; - + /// \brief If the declaration is an overloaded function set, this is the /// iterator pointing to the current position within that overloaded /// function set. OverloadedFunctionDecl::function_iterator Iter; - + public: typedef AnyFunctionDecl value_type; typedef value_type reference; typedef NamedDecl *pointer; typedef int difference_type; typedef std::forward_iterator_tag iterator_category; - + OverloadIterator() : D(0) { } - + OverloadIterator(FunctionDecl *FD) : D(FD) { } - OverloadIterator(FunctionTemplateDecl *FTD) + OverloadIterator(FunctionTemplateDecl *FTD) : D(reinterpret_cast(FTD)) { } - OverloadIterator(OverloadedFunctionDecl *Ovl) + OverloadIterator(OverloadedFunctionDecl *Ovl) : D(Ovl), Iter(Ovl->function_begin()) { } - + OverloadIterator(NamedDecl *ND); - + reference operator*() const; - + pointer operator->() const { return (**this).get(); } - + OverloadIterator &operator++(); - + OverloadIterator operator++(int) { OverloadIterator Temp(*this); ++(*this); return Temp; } - + bool Equals(const OverloadIterator &Other) const; }; - + inline bool operator==(const OverloadIterator &X, const OverloadIterator &Y) { return X.Equals(Y); } @@ -215,7 +215,7 @@ class CXXBaseSpecifier { /// struct (false). This determines the mapping from the access /// specifier as written in the source code to the access specifier /// used for semantic analysis. - bool BaseOfClass : 1; + bool BaseOfClass : 1; /// Access - Access specifier as written in the source code (which /// may be AS_none). The actual type of data stored here is an @@ -226,7 +226,7 @@ class CXXBaseSpecifier { /// BaseType - The type of the base class. This will be a class or /// struct (or a typedef of such). QualType BaseType; - + public: CXXBaseSpecifier() { } @@ -236,7 +236,7 @@ public: /// getSourceRange - Retrieves the source range that contains the /// entire base specifier. SourceRange getSourceRange() const { return Range; } - + /// isVirtual - Determines whether the base class is a virtual base /// class (or not). bool isVirtual() const { return Virtual; } @@ -246,11 +246,11 @@ public: /// semantic analysis, so the result can never be AS_none. To /// retrieve the access specifier as written in the source code, use /// getAccessSpecifierAsWritten(). - AccessSpecifier getAccessSpecifier() const { + AccessSpecifier getAccessSpecifier() const { if ((AccessSpecifier)Access == AS_none) return BaseOfClass? AS_private : AS_public; else - return (AccessSpecifier)Access; + return (AccessSpecifier)Access; } /// getAccessSpecifierAsWritten - Retrieves the access specifier as @@ -271,7 +271,7 @@ public: /// to deal with C++-specific things. class CXXRecordDecl : public RecordDecl { /// UserDeclaredConstructor - True when this class has a - /// user-declared constructor. + /// user-declared constructor. bool UserDeclaredConstructor : 1; /// UserDeclaredCopyConstructor - True when this class has a @@ -315,7 +315,7 @@ class CXXRecordDecl : public RecordDecl { /// * for all the nonstatic data members of its class that are of class type /// (or array thereof), each such class has a trivial constructor. bool HasTrivialConstructor : 1; - + /// HasTrivialCopyConstructor - True when this class has a trivial copy /// constructor. /// @@ -340,7 +340,7 @@ class CXXRecordDecl : public RecordDecl { /// operator; /// otherwise the copy assignment operator is non-trivial. bool HasTrivialCopyAssignment : 1; - + /// HasTrivialDestructor - True when this class has a trivial destructor. /// /// C++ [class.dtor]p3. A destructor is trivial if it is an @@ -360,10 +360,10 @@ class CXXRecordDecl : public RecordDecl { /// VBases - direct and indirect virtual base classes of this class. CXXBaseSpecifier *VBases; - + /// NumVBases - The number of virtual base class specifiers in VBases. unsigned NumVBases; - + /// Conversions - Overload set containing the conversion functions /// of this C++ class (but not its inherited conversion /// functions). Each of the entries in this overload set is a @@ -372,7 +372,7 @@ class CXXRecordDecl : public RecordDecl { /// \brief The template or declaration that this declaration /// describes or was instantiated from, respectively. - /// + /// /// For non-templates, this value will be NULL. For record /// declarations that describe a class template, this will be a /// pointer to a ClassTemplateDecl. For member @@ -417,9 +417,9 @@ public: SourceLocation TKL = SourceLocation(), CXXRecordDecl* PrevDecl=0, bool DelayTypeCreation = false); - + virtual void Destroy(ASTContext& C); - + bool isDynamicClass() const { return Polymorphic || NumVBases!=0; } @@ -448,11 +448,11 @@ public: reverse_base_class_const_iterator bases_rend() const { return reverse_base_class_const_iterator(bases_begin()); } - + /// getNumVBases - Retrieves the number of virtual base classes of this /// class. unsigned getNumVBases() const { return NumVBases; } - + base_class_iterator vbases_begin() { return VBases; } base_class_const_iterator vbases_begin() const { return VBases; } base_class_iterator vbases_end() { return VBases + NumVBases; } @@ -474,7 +474,7 @@ public: /// all method members of the class, including non-instance methods, /// special methods, etc. typedef specific_decl_iterator method_iterator; - + /// method_begin - Method begin iterator. Iterates in the order the methods /// were declared. method_iterator method_begin() const { @@ -487,7 +487,7 @@ public: /// Iterator access to constructor members. typedef specific_decl_iterator ctor_iterator; - + ctor_iterator ctor_begin() const { return ctor_iterator(decls_begin()); } @@ -500,13 +500,13 @@ public: bool hasConstCopyConstructor(ASTContext &Context) const; /// getCopyConstructor - Returns the copy constructor for this class - CXXConstructorDecl *getCopyConstructor(ASTContext &Context, + CXXConstructorDecl *getCopyConstructor(ASTContext &Context, unsigned TypeQuals) const; /// hasConstCopyAssignment - Determines whether this class has a /// copy assignment operator that accepts a const-qualified argument. /// It returns its decl in MD if found. - bool hasConstCopyAssignment(ASTContext &Context, + bool hasConstCopyAssignment(ASTContext &Context, const CXXMethodDecl *&MD) const; /// addedConstructor - Notify the class that another constructor has @@ -517,9 +517,9 @@ public: /// hasUserDeclaredConstructor - Whether this class has any /// user-declared constructors. When true, a default constructor /// will not be implicitly declared. - bool hasUserDeclaredConstructor() const { + bool hasUserDeclaredConstructor() const { assert((isDefinition() || - cast(getTypeForDecl())->isBeingDefined()) && + cast(getTypeForDecl())->isBeingDefined()) && "Incomplete record decl!"); return UserDeclaredConstructor; } @@ -551,23 +551,23 @@ public: /// setUserDeclaredDestructor - Set whether this class has a /// user-declared destructor. If not set by the time the class is /// fully defined, a destructor will be implicitly declared. - void setUserDeclaredDestructor(bool UCD) { - UserDeclaredDestructor = UCD; + void setUserDeclaredDestructor(bool UCD) { + UserDeclaredDestructor = UCD; } /// getConversions - Retrieve the overload set containing all of the /// conversion functions in this class. - OverloadedFunctionDecl *getConversionFunctions() { - assert((this->isDefinition() || + OverloadedFunctionDecl *getConversionFunctions() { + assert((this->isDefinition() || cast(getTypeForDecl())->isBeingDefined()) && "getConversionFunctions() called on incomplete type"); - return &Conversions; + return &Conversions; } - const OverloadedFunctionDecl *getConversionFunctions() const { - assert((this->isDefinition() || + const OverloadedFunctionDecl *getConversionFunctions() const { + assert((this->isDefinition() || cast(getTypeForDecl())->isBeingDefined()) && "getConversionFunctions() called on incomplete type"); - return &Conversions; + return &Conversions; } /// addConversionFunction - Add a new conversion function to the @@ -576,7 +576,7 @@ public: /// \brief Add a new conversion function template to the list of conversion /// functions. - void addConversionFunction(ASTContext &Context, + void addConversionFunction(ASTContext &Context, FunctionTemplateDecl *ConvDecl); /// isAggregate - Whether this class is an aggregate (C++ @@ -618,22 +618,22 @@ public: /// isAbstract - Whether this class is abstract (C++ [class.abstract]), /// which means that the class contains or inherits a pure virtual function. bool isAbstract() const { return Abstract; } - + /// setAbstract - Set whether this class is abstract (C++ [class.abstract]) void setAbstract(bool Abs) { Abstract = Abs; } - + // hasTrivialConstructor - Whether this class has a trivial constructor // (C++ [class.ctor]p5) bool hasTrivialConstructor() const { return HasTrivialConstructor; } - + // setHasTrivialConstructor - Set whether this class has a trivial constructor // (C++ [class.ctor]p5) void setHasTrivialConstructor(bool TC) { HasTrivialConstructor = TC; } - + // hasTrivialCopyConstructor - Whether this class has a trivial copy // constructor (C++ [class.copy]p6) bool hasTrivialCopyConstructor() const { return HasTrivialCopyConstructor; } - + // setHasTrivialCopyConstructor - Set whether this class has a trivial // copy constructor (C++ [class.copy]p6) void setHasTrivialCopyConstructor(bool TC) { HasTrivialCopyConstructor = TC; } @@ -641,7 +641,7 @@ public: // hasTrivialCopyAssignment - Whether this class has a trivial copy // assignment operator (C++ [class.copy]p11) bool hasTrivialCopyAssignment() const { return HasTrivialCopyAssignment; } - + // setHasTrivialCopyAssignment - Set whether this class has a // trivial copy assignment operator (C++ [class.copy]p11) void setHasTrivialCopyAssignment(bool TC) { HasTrivialCopyAssignment = TC; } @@ -649,11 +649,11 @@ public: // hasTrivialDestructor - Whether this class has a trivial destructor // (C++ [class.dtor]p3) bool hasTrivialDestructor() const { return HasTrivialDestructor; } - + // setHasTrivialDestructor - Set whether this class has a trivial destructor // (C++ [class.dtor]p3) void setHasTrivialDestructor(bool TC) { HasTrivialDestructor = TC; } - + /// \brief If this record is an instantiation of a member class, /// retrieves the member class from which it was instantiated. /// @@ -679,7 +679,7 @@ public: /// \brief Specify that this record is an instantiation of the /// member class RD. - void setInstantiationOfMemberClass(CXXRecordDecl *RD) { + void setInstantiationOfMemberClass(CXXRecordDecl *RD) { TemplateOrInstantiation = RD; } @@ -704,16 +704,16 @@ public: /// getDefaultConstructor - Returns the default constructor for this class CXXConstructorDecl *getDefaultConstructor(ASTContext &Context); - + /// getDestructor - Returns the destructor decl for this class. const CXXDestructorDecl *getDestructor(ASTContext &Context); - + /// isLocalClass - If the class is a local class [class.local], returns /// the enclosing function declaration. const FunctionDecl *isLocalClass() const { if (const CXXRecordDecl *RD = dyn_cast(getDeclContext())) return RD->isLocalClass(); - + return dyn_cast(getDeclContext()); } @@ -722,14 +722,14 @@ public: /// GraphViz. void viewInheritance(ASTContext& Context) const; - static bool classof(const Decl *D) { - return D->getKind() == CXXRecord || + static bool classof(const Decl *D) { + return D->getKind() == CXXRecord || D->getKind() == ClassTemplateSpecialization || - D->getKind() == ClassTemplatePartialSpecialization; + D->getKind() == ClassTemplatePartialSpecialization; } static bool classof(const CXXRecordDecl *D) { return true; } - static bool classof(const ClassTemplateSpecializationDecl *D) { - return true; + static bool classof(const ClassTemplateSpecializationDecl *D) { + return true; } }; @@ -749,32 +749,32 @@ public: QualType T, DeclaratorInfo *DInfo, bool isStatic = false, bool isInline = false); - + bool isStatic() const { return getStorageClass() == Static; } bool isInstance() const { return !isStatic(); } - bool isVirtual() const { + bool isVirtual() const { return isVirtualAsWritten() || (begin_overridden_methods() != end_overridden_methods()); } - /// + /// void addOverriddenMethod(const CXXMethodDecl *MD); - + typedef const CXXMethodDecl ** method_iterator; - + method_iterator begin_overridden_methods() const; method_iterator end_overridden_methods() const; - + /// getParent - Returns the parent of this method declaration, which /// is the class in which this method is defined. - const CXXRecordDecl *getParent() const { - return cast(FunctionDecl::getParent()); + const CXXRecordDecl *getParent() const { + return cast(FunctionDecl::getParent()); } - + /// getParent - Returns the parent of this method declaration, which /// is the class in which this method is defined. - CXXRecordDecl *getParent() { + CXXRecordDecl *getParent() { return const_cast( cast(FunctionDecl::getParent())); } @@ -788,7 +788,7 @@ public: } // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() >= CXXMethod && D->getKind() <= CXXConversion; } static bool classof(const CXXMethodDecl *D) { return true; } @@ -818,13 +818,13 @@ class CXXBaseOrMemberInitializer { /// Args - The arguments used to initialize the base or member. Stmt **Args; unsigned NumArgs; - + /// \brief Stores either the constructor to call to initialize this base or /// member (a CXXConstructorDecl pointer), or stores the anonymous union of /// which the initialized value is a member. /// - /// When the value is a FieldDecl pointer, 'BaseOrMember' is class's - /// anonymous union data member, this field holds the FieldDecl for the + /// When the value is a FieldDecl pointer, 'BaseOrMember' is class's + /// anonymous union data member, this field holds the FieldDecl for the /// member of the anonymous union being initialized. /// @code /// struct X { @@ -838,7 +838,7 @@ class CXXBaseOrMemberInitializer { /// In above example, BaseOrMember holds the field decl. for anonymous union /// and AnonUnionMember holds field decl for au_i1. llvm::PointerUnion CtorOrAnonUnion; - + /// IdLoc - Location of the id in ctor-initializer list. SourceLocation IdLoc; @@ -847,13 +847,13 @@ class CXXBaseOrMemberInitializer { public: /// CXXBaseOrMemberInitializer - Creates a new base-class initializer. - explicit + explicit CXXBaseOrMemberInitializer(QualType BaseType, Expr **Args, unsigned NumArgs, CXXConstructorDecl *C, SourceLocation L, SourceLocation R); /// CXXBaseOrMemberInitializer - Creates a new member initializer. - explicit + explicit CXXBaseOrMemberInitializer(FieldDecl *Member, Expr **Args, unsigned NumArgs, CXXConstructorDecl *C, SourceLocation L, SourceLocation R); @@ -872,7 +872,7 @@ public: /// getBaseOrMember - get the generic 'member' representing either the field /// or a base class. void* getBaseOrMember() const { return reinterpret_cast(BaseOrMember); } - + /// isBaseInitializer - Returns true when this initializer is /// initializing a base class. bool isBaseInitializer() const { return (BaseOrMember & 0x1) != 0; } @@ -885,8 +885,8 @@ public: /// type used to specify the initializer. The resulting type will be /// a class type or a typedef of a class type. If this is not a base /// class initializer, returns NULL. - Type *getBaseClass() { - if (isBaseInitializer()) + Type *getBaseClass() { + if (isBaseInitializer()) return reinterpret_cast(BaseOrMember & ~0x01); else return 0; @@ -896,8 +896,8 @@ public: /// type used to specify the initializer. The resulting type will be /// a class type or a typedef of a class type. If this is not a base /// class initializer, returns NULL. - const Type *getBaseClass() const { - if (isBaseInitializer()) + const Type *getBaseClass() const { + if (isBaseInitializer()) return reinterpret_cast(BaseOrMember & ~0x01); else return 0; @@ -906,9 +906,9 @@ public: /// getMember - If this is a member initializer, returns the /// declaration of the non-static data member being /// initialized. Otherwise, returns NULL. - FieldDecl *getMember() { + FieldDecl *getMember() { if (isMemberInitializer()) - return reinterpret_cast(BaseOrMember); + return reinterpret_cast(BaseOrMember); else return 0; } @@ -916,21 +916,21 @@ public: void setMember(FieldDecl * anonUnionField) { BaseOrMember = reinterpret_cast(anonUnionField); } - + FieldDecl *getAnonUnionMember() const { return CtorOrAnonUnion.dyn_cast(); } void setAnonUnionMember(FieldDecl *anonMember) { CtorOrAnonUnion = anonMember; } - - const CXXConstructorDecl *getConstructor() const { + + const CXXConstructorDecl *getConstructor() const { return CtorOrAnonUnion.dyn_cast(); } - + SourceLocation getSourceLocation() const { return IdLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } - + /// arg_begin() - Retrieve an iterator to the first initializer argument. arg_iterator arg_begin() { return Args; } /// arg_begin() - Retrieve an iterator to the first initializer argument. @@ -948,7 +948,7 @@ public: /// CXXConstructorDecl - Represents a C++ constructor within a /// class. For example: -/// +/// /// @code /// class X { /// public: @@ -966,23 +966,23 @@ class CXXConstructorDecl : public CXXMethodDecl { /// explicitly defaulted (i.e., defined with " = default") will have /// @c !Implicit && ImplicitlyDefined. bool ImplicitlyDefined : 1; - + /// Support for base and member initializers. - /// BaseOrMemberInitializers - The arguments used to initialize the base + /// BaseOrMemberInitializers - The arguments used to initialize the base /// or member. CXXBaseOrMemberInitializer **BaseOrMemberInitializers; unsigned NumBaseOrMemberInitializers; - + CXXConstructorDecl(CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, DeclaratorInfo *DInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared) : CXXMethodDecl(CXXConstructor, RD, L, N, T, DInfo, false, isInline), Explicit(isExplicit), ImplicitlyDefined(false), - BaseOrMemberInitializers(0), NumBaseOrMemberInitializers(0) { + BaseOrMemberInitializers(0), NumBaseOrMemberInitializers(0) { setImplicit(isImplicitlyDeclared); } virtual void Destroy(ASTContext& C); - + public: static CXXConstructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, @@ -990,59 +990,59 @@ public: bool isExplicit, bool isInline, bool isImplicitlyDeclared); - /// isExplicit - Whether this constructor was marked "explicit" or not. + /// isExplicit - Whether this constructor was marked "explicit" or not. bool isExplicit() const { return Explicit; } /// isImplicitlyDefined - Whether this constructor was implicitly /// defined. If false, then this constructor was defined by the /// user. This operation can only be invoked if the constructor has /// already been defined. - bool isImplicitlyDefined(ASTContext &C) const { - assert(isThisDeclarationADefinition() && + bool isImplicitlyDefined(ASTContext &C) const { + assert(isThisDeclarationADefinition() && "Can only get the implicit-definition flag once the " "constructor has been defined"); - return ImplicitlyDefined; + return ImplicitlyDefined; } /// setImplicitlyDefined - Set whether this constructor was /// implicitly defined or not. - void setImplicitlyDefined(bool ID) { - assert(isThisDeclarationADefinition() && + void setImplicitlyDefined(bool ID) { + assert(isThisDeclarationADefinition() && "Can only set the implicit-definition flag once the constructor " "has been defined"); - ImplicitlyDefined = ID; + ImplicitlyDefined = ID; } - + /// init_iterator - Iterates through the member/base initializer list. typedef CXXBaseOrMemberInitializer **init_iterator; - + /// init_const_iterator - Iterates through the memberbase initializer list. typedef CXXBaseOrMemberInitializer * const * init_const_iterator; - + /// init_begin() - Retrieve an iterator to the first initializer. init_iterator init_begin() { return BaseOrMemberInitializers; } /// begin() - Retrieve an iterator to the first initializer. init_const_iterator init_begin() const { return BaseOrMemberInitializers; } - + /// init_end() - Retrieve an iterator past the last initializer. - init_iterator init_end() { - return BaseOrMemberInitializers + NumBaseOrMemberInitializers; + init_iterator init_end() { + return BaseOrMemberInitializers + NumBaseOrMemberInitializers; } /// end() - Retrieve an iterator past the last initializer. - init_const_iterator init_end() const { - return BaseOrMemberInitializers + NumBaseOrMemberInitializers; + init_const_iterator init_end() const { + return BaseOrMemberInitializers + NumBaseOrMemberInitializers; } - + /// getNumArgs - Determine the number of arguments used to /// initialize the member or base. - unsigned getNumBaseOrMemberInitializers() const { - return NumBaseOrMemberInitializers; + unsigned getNumBaseOrMemberInitializers() const { + return NumBaseOrMemberInitializers; } - + void setNumBaseOrMemberInitializers(unsigned numBaseOrMemberInitializers) { NumBaseOrMemberInitializers = numBaseOrMemberInitializers; } - + void setBaseOrMemberInitializers(CXXBaseOrMemberInitializer ** initializers) { BaseOrMemberInitializers = initializers; } @@ -1079,7 +1079,7 @@ public: bool isConvertingConstructor(bool AllowExplicit) const; // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() == CXXConstructor; } static bool classof(const CXXConstructorDecl *D) { return true; } @@ -1087,7 +1087,7 @@ public: /// CXXDestructorDecl - Represents a C++ destructor within a /// class. For example: -/// +/// /// @code /// class X { /// public: @@ -1109,97 +1109,97 @@ private: /// explicitly defaulted (i.e., defined with " = default") will have /// @c !Implicit && ImplicitlyDefined. bool ImplicitlyDefined : 1; - + /// Support for base and member destruction. - /// BaseOrMemberDestructions - The arguments used to destruct the base + /// BaseOrMemberDestructions - The arguments used to destruct the base /// or member. Each uintptr_t value represents one of base classes (either /// virtual or direct non-virtual base), or non-static data member /// to be destroyed. The low two bits encode the kind of object /// being destroyed. uintptr_t *BaseOrMemberDestructions; unsigned NumBaseOrMemberDestructions; - + CXXDestructorDecl(CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isImplicitlyDeclared) : CXXMethodDecl(CXXDestructor, RD, L, N, T, /*DInfo=*/0, false, isInline), ImplicitlyDefined(false), - BaseOrMemberDestructions(0), NumBaseOrMemberDestructions(0) { + BaseOrMemberDestructions(0), NumBaseOrMemberDestructions(0) { setImplicit(isImplicitlyDeclared); } virtual void Destroy(ASTContext& C); - + public: static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, - QualType T, bool isInline, + QualType T, bool isInline, bool isImplicitlyDeclared); /// isImplicitlyDefined - Whether this destructor was implicitly /// defined. If false, then this destructor was defined by the /// user. This operation can only be invoked if the destructor has /// already been defined. - bool isImplicitlyDefined() const { - assert(isThisDeclarationADefinition() && + bool isImplicitlyDefined() const { + assert(isThisDeclarationADefinition() && "Can only get the implicit-definition flag once the destructor has been defined"); - return ImplicitlyDefined; + return ImplicitlyDefined; } /// setImplicitlyDefined - Set whether this destructor was /// implicitly defined or not. - void setImplicitlyDefined(bool ID) { - assert(isThisDeclarationADefinition() && + void setImplicitlyDefined(bool ID) { + assert(isThisDeclarationADefinition() && "Can only set the implicit-definition flag once the destructor has been defined"); - ImplicitlyDefined = ID; + ImplicitlyDefined = ID; } /// destr_iterator - Iterates through the member/base destruction list. - + /// destr_const_iterator - Iterates through the member/base destruction list. typedef uintptr_t const destr_const_iterator; - + /// destr_begin() - Retrieve an iterator to the first destructed member/base. - uintptr_t* destr_begin() { - return BaseOrMemberDestructions; + uintptr_t* destr_begin() { + return BaseOrMemberDestructions; } /// destr_begin() - Retrieve an iterator to the first destructed member/base. - uintptr_t* destr_begin() const { - return BaseOrMemberDestructions; + uintptr_t* destr_begin() const { + return BaseOrMemberDestructions; } - + /// destr_end() - Retrieve an iterator past the last destructed member/base. - uintptr_t* destr_end() { - return BaseOrMemberDestructions + NumBaseOrMemberDestructions; + uintptr_t* destr_end() { + return BaseOrMemberDestructions + NumBaseOrMemberDestructions; } /// destr_end() - Retrieve an iterator past the last destructed member/base. - uintptr_t* destr_end() const { - return BaseOrMemberDestructions + NumBaseOrMemberDestructions; + uintptr_t* destr_end() const { + return BaseOrMemberDestructions + NumBaseOrMemberDestructions; } - + /// getNumBaseOrMemberDestructions - Number of base and non-static members /// to destroy. - unsigned getNumBaseOrMemberDestructions() const { - return NumBaseOrMemberDestructions; + unsigned getNumBaseOrMemberDestructions() const { + return NumBaseOrMemberDestructions; } - + /// setNumBaseOrMemberDestructions - Set number of base and non-static members /// to destroy. void setNumBaseOrMemberDestructions(unsigned numBaseOrMemberDestructions) { NumBaseOrMemberDestructions = numBaseOrMemberDestructions; } - - /// getBaseOrMemberToDestroy - get the generic 'member' representing either + + /// getBaseOrMemberToDestroy - get the generic 'member' representing either /// the field or a base class. uintptr_t* getBaseOrMemberToDestroy() const { - return BaseOrMemberDestructions; + return BaseOrMemberDestructions; } - - /// setBaseOrMemberToDestroy - set the generic 'member' representing either + + /// setBaseOrMemberToDestroy - set the generic 'member' representing either /// the field or a base class. void setBaseOrMemberDestructions(uintptr_t* baseOrMemberDestructions) { BaseOrMemberDestructions = baseOrMemberDestructions; } - + /// isVbaseToDestroy - returns true, if object is virtual base. bool isVbaseToDestroy(uintptr_t Vbase) const { return (Vbase & VBASE) != 0; @@ -1209,7 +1209,7 @@ public: bool isDirectNonVBaseToDestroy(uintptr_t DrctNonVbase) const { return (DrctNonVbase & DRCTNONVBASE) != 0; } - /// isAnyBaseToDestroy - returns true, if object is any base (virtual or + /// isAnyBaseToDestroy - returns true, if object is any base (virtual or /// direct non-virtual) bool isAnyBaseToDestroy(uintptr_t AnyBase) const { return (AnyBase & ANYBASE) != 0; @@ -1225,9 +1225,9 @@ public: return 0; } /// getMemberToDestroy - Get the member for the given object. - FieldDecl *getMemberToDestroy(uintptr_t Member) const { + FieldDecl *getMemberToDestroy(uintptr_t Member) const { if (isMemberToDestroy(Member)) - return reinterpret_cast(Member); + return reinterpret_cast(Member); return 0; } /// getVbaseClassToDestroy - Get the virtual base. @@ -1242,9 +1242,9 @@ public: return reinterpret_cast(Base & ~0x02); return 0; } - + // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() == CXXDestructor; } static bool classof(const CXXDestructorDecl *D) { return true; } @@ -1252,7 +1252,7 @@ public: /// CXXConversionDecl - Represents a C++ conversion function within a /// class. For example: -/// +/// /// @code /// class X { /// public: @@ -1266,7 +1266,7 @@ class CXXConversionDecl : public CXXMethodDecl { bool Explicit : 1; CXXConversionDecl(CXXRecordDecl *RD, SourceLocation L, - DeclarationName N, QualType T, DeclaratorInfo *DInfo, + DeclarationName N, QualType T, DeclaratorInfo *DInfo, bool isInline, bool isExplicit) : CXXMethodDecl(CXXConversion, RD, L, N, T, DInfo, false, isInline), Explicit(isExplicit) { } @@ -1284,12 +1284,12 @@ public: /// getConversionType - Returns the type that this conversion /// function is converting to. - QualType getConversionType() const { - return getType()->getAsFunctionType()->getResultType(); + QualType getConversionType() const { + return getType()->getAsFunctionType()->getResultType(); } // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() == CXXConversion; } static bool classof(const CXXConversionDecl *D) { return true; } @@ -1325,8 +1325,8 @@ private: SourceLocation FriendL) : Decl(Decl::Friend, DC, L), Friend(Friend), - FriendLoc(FriendL) - {} + FriendLoc(FriendL) { + } public: static FriendDecl *Create(ASTContext &C, DeclContext *DC, @@ -1353,12 +1353,12 @@ public: } // Implement isa/cast/dyncast/etc. - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() == Decl::Friend; } static bool classof(const FriendDecl *D) { return true; } }; - + /// LinkageSpecDecl - This represents a linkage specification. For example: /// extern "C" void foo(); /// @@ -1378,14 +1378,14 @@ private: /// HadBraces - Whether this linkage specification had curly braces or not. bool HadBraces : 1; - LinkageSpecDecl(DeclContext *DC, SourceLocation L, LanguageIDs lang, + LinkageSpecDecl(DeclContext *DC, SourceLocation L, LanguageIDs lang, bool Braces) - : Decl(LinkageSpec, DC, L), + : Decl(LinkageSpec, DC, L), DeclContext(LinkageSpec), Language(lang), HadBraces(Braces) { } public: - static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, LanguageIDs Lang, + static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, LanguageIDs Lang, bool Braces); LanguageIDs getLanguage() const { return Language; } @@ -1452,8 +1452,8 @@ class UsingDirectiveDecl : public NamedDecl { NamespaceDecl *Nominated, DeclContext *CommonAncestor) : NamedDecl(Decl::UsingDirective, DC, L, getName()), - NamespaceLoc(NamespcLoc), QualifierRange(QualifierRange), - Qualifier(Qualifier), IdentLoc(IdentLoc), + NamespaceLoc(NamespcLoc), QualifierRange(QualifierRange), + Qualifier(Qualifier), IdentLoc(IdentLoc), NominatedNamespace(Nominated? Nominated->getOriginalNamespace() : 0), CommonAncestor(CommonAncestor) { } @@ -1518,20 +1518,20 @@ class NamespaceAliasDecl : public NamedDecl { /// \brief The nested-name-specifier that precedes the namespace /// name, if any. NestedNameSpecifier *Qualifier; - + /// IdentLoc - Location of namespace identifier. SourceLocation IdentLoc; - - /// Namespace - The Decl that this alias points to. Can either be a + + /// Namespace - The Decl that this alias points to. Can either be a /// NamespaceDecl or a NamespaceAliasDecl. NamedDecl *Namespace; - - NamespaceAliasDecl(DeclContext *DC, SourceLocation L, - SourceLocation AliasLoc, IdentifierInfo *Alias, + + NamespaceAliasDecl(DeclContext *DC, SourceLocation L, + SourceLocation AliasLoc, IdentifierInfo *Alias, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, SourceLocation IdentLoc, NamedDecl *Namespace) - : NamedDecl(Decl::NamespaceAlias, DC, L, Alias), AliasLoc(AliasLoc), + : NamedDecl(Decl::NamespaceAlias, DC, L, Alias), AliasLoc(AliasLoc), QualifierRange(QualifierRange), Qualifier(Qualifier), IdentLoc(IdentLoc), Namespace(Namespace) { } @@ -1550,7 +1550,7 @@ public: return cast(Namespace); } - + const NamespaceDecl *getNamespace() const { return const_cast(this)->getNamespace(); } @@ -1559,14 +1559,14 @@ public: /// may either be a NamespaceDecl or a NamespaceAliasDecl. NamedDecl *getAliasedNamespace() const { return Namespace; } - static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, SourceLocation AliasLoc, - IdentifierInfo *Alias, + static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, SourceLocation AliasLoc, + IdentifierInfo *Alias, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, - SourceLocation IdentLoc, + SourceLocation IdentLoc, NamedDecl *Namespace); - + static bool classof(const Decl *D) { return D->getKind() == Decl::NamespaceAlias; } @@ -1579,16 +1579,16 @@ class UsingDecl : public NamedDecl { /// \brief The source range that covers the nested-name-specifier /// preceding the declaration name. SourceRange NestedNameRange; - + /// \brief The source location of the target declaration name. SourceLocation TargetNameLocation; - + /// \brief The source location of the "using" location itself. SourceLocation UsingLocation; - + /// \brief Target declaration. NamedDecl* TargetDecl; - + /// \brief Target nested name specifier. NestedNameSpecifier* TargetNestedNameDecl; @@ -1601,7 +1601,7 @@ class UsingDecl : public NamedDecl { : NamedDecl(Decl::Using, DC, L, Target->getDeclName()), NestedNameRange(NNR), TargetNameLocation(TargetNL), UsingLocation(UL), TargetDecl(Target), - TargetNestedNameDecl(TargetNNS), IsTypeName(IsTypeNameArg) { + TargetNestedNameDecl(TargetNNS), IsTypeName(IsTypeNameArg) { this->IdentifierNamespace = TargetDecl->getIdentifierNamespace(); } @@ -1609,22 +1609,22 @@ public: /// \brief Returns the source range that covers the nested-name-specifier /// preceding the namespace name. SourceRange getNestedNameRange() { return NestedNameRange; } - + /// \brief Returns the source location of the target declaration name. SourceLocation getTargetNameLocation() { return TargetNameLocation; } - + /// \brief Returns the source location of the "using" location itself. SourceLocation getUsingLocation() { return UsingLocation; } - + /// \brief getTargetDecl - Returns target specified by using-decl. NamedDecl *getTargetDecl() { return TargetDecl; } const NamedDecl *getTargetDecl() const { return TargetDecl; } - + /// \brief Get target nested name declaration. - NestedNameSpecifier* getTargetNestedNameDecl() { - return TargetNestedNameDecl; + NestedNameSpecifier* getTargetNestedNameDecl() { + return TargetNestedNameDecl; } - + /// isTypeName - Return true if using decl has 'typename'. bool isTypeName() const { return IsTypeName; } @@ -1645,39 +1645,39 @@ class UnresolvedUsingDecl : public NamedDecl { /// \brief The source range that covers the nested-name-specifier /// preceding the declaration name. SourceRange TargetNestedNameRange; - + /// \brief The source location of the target declaration name. SourceLocation TargetNameLocation; - + NestedNameSpecifier *TargetNestedNameSpecifier; - + DeclarationName TargetName; - + // \brief Has 'typename' keyword. bool IsTypeName; - + UnresolvedUsingDecl(DeclContext *DC, SourceLocation UsingLoc, SourceRange TargetNNR, NestedNameSpecifier *TargetNNS, SourceLocation TargetNameLoc, DeclarationName TargetName, bool IsTypeNameArg) : NamedDecl(Decl::UnresolvedUsing, DC, UsingLoc, TargetName), - TargetNestedNameRange(TargetNNR), TargetNameLocation(TargetNameLoc), - TargetNestedNameSpecifier(TargetNNS), TargetName(TargetName), + TargetNestedNameRange(TargetNNR), TargetNameLocation(TargetNameLoc), + TargetNestedNameSpecifier(TargetNNS), TargetName(TargetName), IsTypeName(IsTypeNameArg) { } public: /// \brief Returns the source range that covers the nested-name-specifier /// preceding the namespace name. SourceRange getTargetNestedNameRange() const { return TargetNestedNameRange; } - + /// \brief Get target nested name declaration. - NestedNameSpecifier* getTargetNestedNameSpecifier() { - return TargetNestedNameSpecifier; + NestedNameSpecifier* getTargetNestedNameSpecifier() { + return TargetNestedNameSpecifier; } - + /// \brief Returns the source location of the target declaration name. SourceLocation getTargetNameLocation() const { return TargetNameLocation; } - + /// \brief Returns the source location of the target declaration name. DeclarationName getTargetName() const { return TargetName; } @@ -1690,33 +1690,33 @@ public: SourceLocation TargetNameLoc, DeclarationName TargetName, bool IsTypeNameArg); - + static bool classof(const Decl *D) { return D->getKind() == Decl::UnresolvedUsing; } static bool classof(const UnresolvedUsingDecl *D) { return true; } }; - + /// StaticAssertDecl - Represents a C++0x static_assert declaration. class StaticAssertDecl : public Decl { Expr *AssertExpr; StringLiteral *Message; - StaticAssertDecl(DeclContext *DC, SourceLocation L, + StaticAssertDecl(DeclContext *DC, SourceLocation L, Expr *assertexpr, StringLiteral *message) : Decl(StaticAssert, DC, L), AssertExpr(assertexpr), Message(message) { } - + public: static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, Expr *AssertExpr, StringLiteral *Message); - + Expr *getAssertExpr() { return AssertExpr; } const Expr *getAssertExpr() const { return AssertExpr; } - + StringLiteral *getMessage() { return Message; } const StringLiteral *getMessage() const { return Message; } - + virtual ~StaticAssertDecl(); virtual void Destroy(ASTContext& C); @@ -1730,7 +1730,7 @@ public: /// into a diagnostic with <<. const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, AccessSpecifier AS); - + } // end namespace clang #endif diff --git a/clang/include/clang/AST/DeclContextInternals.h b/clang/include/clang/AST/DeclContextInternals.h index 6c1231c0a73d5143e685ecaef2b63a05bca89742..d9e40d4789073fa97e75fcc6a578a1f3d870e077 100644 --- a/clang/include/clang/AST/DeclContextInternals.h +++ b/clang/include/clang/AST/DeclContextInternals.h @@ -57,13 +57,13 @@ public: Data = reinterpret_cast(New) | (Data & 0x03); } } - + ~StoredDeclsList() { // If this is a vector-form, free the vector. if (VectorTy *Vector = getAsVector()) delete Vector; } - + StoredDeclsList &operator=(const StoredDeclsList &RHS) { if (VectorTy *Vector = getAsVector()) delete Vector; @@ -74,9 +74,9 @@ public: } return *this; } - + bool isNull() const { return (Data & ~0x03) == 0; } - + NamedDecl *getAsDecl() const { if ((Data & 0x03) != DK_Decl) return 0; @@ -135,27 +135,27 @@ public: DeclContext::lookup_result getLookupResult(ASTContext &Context) { if (isNull()) return DeclContext::lookup_result(0, 0); - + if (hasDeclarationIDs()) materializeDecls(Context); // If we have a single NamedDecl, return it. if (getAsDecl()) { assert(!isNull() && "Empty list isn't allowed"); - + // Data is a raw pointer to a NamedDecl*, return it. void *Ptr = &Data; return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1); } - + assert(getAsVector() && "Must have a vector at this point"); VectorTy &Vector = *getAsVector(); - + // Otherwise, we have a range result. - return DeclContext::lookup_result((NamedDecl **)&Vector[0], + return DeclContext::lookup_result((NamedDecl **)&Vector[0], (NamedDecl **)&Vector[0]+Vector.size()); } - + /// HandleRedeclaration - If this is a redeclaration of an existing decl, /// replace the old one with D and return true. Otherwise return false. bool HandleRedeclaration(ASTContext &Context, NamedDecl *D) { @@ -169,7 +169,7 @@ public: setOnlyValue(D); return true; } - + // Determine if this declaration is actually a redeclaration. VectorTy &Vec = *getAsVector(); for (VectorTy::iterator OD = Vec.begin(), ODEnd = Vec.end(); @@ -183,10 +183,10 @@ public: return false; } - + /// AddSubsequentDecl - This is called on the second and later decl when it is /// not a redeclaration to merge it into the appropriate place in our list. - /// + /// void AddSubsequentDecl(NamedDecl *D) { assert(!hasDeclarationIDs() && "Must materialize before adding decls"); @@ -197,7 +197,7 @@ public: VT->push_back(reinterpret_cast(OldD)); Data = reinterpret_cast(VT) | DK_Decl_Vector; } - + VectorTy &Vec = *getAsVector(); if (isa(D) || D->getIdentifierNamespace() == Decl::IDNS_Tag) @@ -217,4 +217,4 @@ typedef llvm::DenseMap StoredDeclsMap; } // end namespace clang -#endif +#endif diff --git a/clang/include/clang/AST/DeclGroup.h b/clang/include/clang/AST/DeclGroup.h index 15a8adef8e57b3ec38d4f48eb6657b08339f4cd6..790ea3ca06624bbecfa0f40b934670784b0b655c 100644 --- a/clang/include/clang/AST/DeclGroup.h +++ b/clang/include/clang/AST/DeclGroup.h @@ -18,7 +18,7 @@ #include namespace clang { - + class ASTContext; class Decl; class DeclGroup; @@ -27,7 +27,7 @@ class DeclGroupIterator; class DeclGroup { // FIXME: Include a TypeSpecifier object. unsigned NumDecls; - + private: DeclGroup() : NumDecls(0) {} DeclGroup(unsigned numdecls, Decl** decls); @@ -38,34 +38,34 @@ public: unsigned size() const { return NumDecls; } - Decl*& operator[](unsigned i) { + Decl*& operator[](unsigned i) { assert (i < NumDecls && "Out-of-bounds access."); return *((Decl**) (this+1)); } - - Decl* const& operator[](unsigned i) const { + + Decl* const& operator[](unsigned i) const { assert (i < NumDecls && "Out-of-bounds access."); return *((Decl* const*) (this+1)); } }; - + class DeclGroupRef { // Note this is not a PointerIntPair because we need the address of the // non-group case to be valid as a Decl** for iteration. - enum Kind { SingleDeclKind=0x0, DeclGroupKind=0x1, Mask=0x1 }; + enum Kind { SingleDeclKind=0x0, DeclGroupKind=0x1, Mask=0x1 }; Decl* D; Kind getKind() const { return (Kind) (reinterpret_cast(D) & Mask); - } - -public: + } + +public: DeclGroupRef() : D(0) {} - + explicit DeclGroupRef(Decl* d) : D(d) {} explicit DeclGroupRef(DeclGroup* dg) : D((Decl*) (reinterpret_cast(dg) | DeclGroupKind)) {} - + static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls) { if (NumDecls == 0) return DeclGroupRef(); @@ -73,10 +73,10 @@ public: return DeclGroupRef(Decls[0]); return DeclGroupRef(DeclGroup::Create(C, Decls, NumDecls)); } - + typedef Decl** iterator; typedef Decl* const * const_iterator; - + bool isNull() const { return D == 0; } bool isSingleDecl() const { return getKind() == SingleDeclKind; } bool isDeclGroup() const { return getKind() == DeclGroupKind; } @@ -88,7 +88,7 @@ public: const Decl *getSingleDecl() const { return const_cast(this)->getSingleDecl(); } - + DeclGroup &getDeclGroup() { assert(isDeclGroup() && "Isn't a declgroup"); return *((DeclGroup*)(reinterpret_cast(D) & ~Mask)); @@ -96,7 +96,7 @@ public: const DeclGroup &getDeclGroup() const { return const_cast(this)->getDeclGroup(); } - + iterator begin() { if (isSingleDecl()) return D ? &D : 0; @@ -109,13 +109,13 @@ public: DeclGroup &G = getDeclGroup(); return &G[0] + G.size(); } - + const_iterator begin() const { if (isSingleDecl()) return D ? &D : 0; return &getDeclGroup()[0]; } - + const_iterator end() const { if (isSingleDecl()) return D ? &D+1 : 0; @@ -130,7 +130,7 @@ public: return X; } }; - + } // end clang namespace namespace llvm { diff --git a/clang/include/clang/AST/DeclObjC.h b/clang/include/clang/AST/DeclObjC.h index 5faa5d54b3e3a9f4d4c0d2b53b456e273be95f3c..6263246acf559c33611829431d1ad2811cc3ce31 100644 --- a/clang/include/clang/AST/DeclObjC.h +++ b/clang/include/clang/AST/DeclObjC.h @@ -43,17 +43,17 @@ public: ~ObjCListBase() { assert(List == 0 && "Destroy should have been called before dtor"); } - + void Destroy(ASTContext &Ctx); - + unsigned size() const { return NumElts; } bool empty() const { return NumElts == 0; } - + protected: void set(void *const* InList, unsigned Elts, ASTContext &Ctx); }; - - + + /// ObjCList - This is a simple template class used to hold various lists of /// decls etc, which is heavily used by the ObjC front-end. This only use case /// this supports is setting the list all at once and then reading elements out @@ -64,30 +64,30 @@ public: void set(T* const* InList, unsigned Elts, ASTContext &Ctx) { ObjCListBase::set(reinterpret_cast(InList), Elts, Ctx); } - + typedef T* const * iterator; iterator begin() const { return (iterator)List; } iterator end() const { return (iterator)List+NumElts; } - + T* operator[](unsigned Idx) const { assert(Idx < NumElts && "Invalid access"); return (T*)List[Idx]; } }; - + /// ObjCMethodDecl - Represents an instance or class method declaration. /// ObjC methods can be declared within 4 contexts: class interfaces, /// categories, protocols, and class implementations. While C++ member -/// functions leverage C syntax, Objective-C method syntax is modeled after -/// Smalltalk (using colons to specify argument types/expressions). +/// functions leverage C syntax, Objective-C method syntax is modeled after +/// Smalltalk (using colons to specify argument types/expressions). /// Here are some brief examples: /// /// Setter/getter instance methods: /// - (void)setMenu:(NSMenu *)menu; -/// - (NSMenu *)menu; -/// +/// - (NSMenu *)menu; +/// /// Instance method that takes 2 NSView arguments: /// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView; /// @@ -106,27 +106,27 @@ private: /// instance (true) or class (false) method. bool IsInstance : 1; bool IsVariadic : 1; - + // Synthesized declaration method for a property setter/getter bool IsSynthesized : 1; - + // NOTE: VC++ treats enums as signed, avoid using ImplementationControl enum /// @required/@optional unsigned DeclImplementation : 2; - + // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum /// in, inout, etc. unsigned objcDeclQualifier : 6; - + // Type of this method. QualType MethodDeclType; /// ParamInfo - List of pointers to VarDecls for the formal parameters of this /// Method. ObjCList ParamInfo; - + /// List of attributes for this method declaration. SourceLocation EndLoc; // the location of the ';' or '}'. - + // The following are only used for method definitions, null otherwise. // FIXME: space savings opportunity, consider a sub-class. Stmt *Body; @@ -137,7 +137,7 @@ private: /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily /// constructed by createImplicitParams. ImplicitParamDecl *CmdDecl; - + ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, DeclContext *contextDecl, @@ -150,7 +150,7 @@ private: IsInstance(isInstance), IsVariadic(isVariadic), IsSynthesized(isSynthesized), DeclImplementation(impControl), objcDeclQualifier(OBJC_TQ_None), - MethodDeclType(T), + MethodDeclType(T), EndLoc(endLoc), Body(0), SelfDecl(0), CmdDecl(0) {} virtual ~ObjCMethodDecl() {} @@ -161,12 +161,12 @@ private: virtual ObjCMethodDecl *getNextRedeclaration(); public: - + /// Destroy - Call destructors and release memory. virtual void Destroy(ASTContext& C); static ObjCMethodDecl *Create(ASTContext &C, - SourceLocation beginLoc, + SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, DeclContext *contextDecl, bool isInstance = true, @@ -180,25 +180,25 @@ public: return ObjCDeclQualifier(objcDeclQualifier); } void setObjCDeclQualifier(ObjCDeclQualifier QV) { objcDeclQualifier = QV; } - + // Location information, modeled after the Stmt API. SourceLocation getLocStart() const { return getLocation(); } SourceLocation getLocEnd() const { return EndLoc; } void setEndLoc(SourceLocation Loc) { EndLoc = Loc; } - virtual SourceRange getSourceRange() const { - return SourceRange(getLocation(), EndLoc); + virtual SourceRange getSourceRange() const { + return SourceRange(getLocation(), EndLoc); } - + ObjCInterfaceDecl *getClassInterface(); const ObjCInterfaceDecl *getClassInterface() const { return const_cast(this)->getClassInterface(); } - + Selector getSelector() const { return getDeclName().getObjCSelector(); } QualType getResultType() const { return MethodDeclType; } void setResultType(QualType T) { MethodDeclType = T; } - + // Iterator access to formal parameters. unsigned param_size() const { return ParamInfo.size(); } typedef ObjCList::iterator param_iterator; @@ -219,7 +219,7 @@ public: arg_type_iterator arg_type_end() const { return llvm::map_iterator(param_end(), deref_fun(&ParmVarDecl::getType)); } - + /// createImplicitParams - Used to lazily create the self and cmd /// implict parameters. This must be called prior to using getSelfDecl() /// or getCmdDecl(). The call is ignored if the implicit paramters @@ -230,27 +230,27 @@ public: void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; } ImplicitParamDecl * getCmdDecl() const { return CmdDecl; } void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; } - + bool isInstanceMethod() const { return IsInstance; } void setInstanceMethod(bool isInst) { IsInstance = isInst; } bool isVariadic() const { return IsVariadic; } void setVariadic(bool isVar) { IsVariadic = isVar; } - + bool isClassMethod() const { return !IsInstance; } bool isSynthesized() const { return IsSynthesized; } void setSynthesized(bool isSynth) { IsSynthesized = isSynth; } - + // Related to protocols declared in @protocol - void setDeclImplementation(ImplementationControl ic) { - DeclImplementation = ic; + void setDeclImplementation(ImplementationControl ic) { + DeclImplementation = ic; } - ImplementationControl getImplementationControl() const { - return ImplementationControl(DeclImplementation); + ImplementationControl getImplementationControl() const { + return ImplementationControl(DeclImplementation); } - virtual Stmt *getBody() const { - return (Stmt*) Body; + virtual Stmt *getBody() const { + return (Stmt*) Body; } CompoundStmt *getCompoundBody() { return (CompoundStmt*)Body; } void setBody(Stmt *B) { Body = B; } @@ -273,9 +273,9 @@ public: struct ObjCMethodList { ObjCMethodDecl *Method; ObjCMethodList *Next; - + ObjCMethodList() { - Method = 0; + Method = 0; Next = 0; } ObjCMethodList(ObjCMethodDecl *M, ObjCMethodList *C) { @@ -286,13 +286,13 @@ struct ObjCMethodList { /// ObjCContainerDecl - Represents a container for method declarations. /// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl, -/// ObjCProtocolDecl, and ObjCImplDecl. +/// ObjCProtocolDecl, and ObjCImplDecl. /// class ObjCContainerDecl : public NamedDecl, public DeclContext { SourceLocation AtEndLoc; // marks the end of the method container. public: - ObjCContainerDecl(Kind DK, DeclContext *DC, SourceLocation L, + ObjCContainerDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id) : NamedDecl(DK, DC, L, Id), DeclContext(DK) {} @@ -300,24 +300,24 @@ public: // Iterator access to properties. typedef specific_decl_iterator prop_iterator; - prop_iterator prop_begin() const { + prop_iterator prop_begin() const { return prop_iterator(decls_begin()); } - prop_iterator prop_end() const { + prop_iterator prop_end() const { return prop_iterator(decls_end()); } - + // Iterator access to instance/class methods. typedef specific_decl_iterator method_iterator; - method_iterator meth_begin() const { + method_iterator meth_begin() const { return method_iterator(decls_begin()); } - method_iterator meth_end() const { + method_iterator meth_end() const { return method_iterator(decls_end()); } - typedef filtered_decl_iterator + typedef filtered_decl_iterator instmeth_iterator; instmeth_iterator instmeth_begin() const { return instmeth_iterator(decls_begin()); @@ -326,8 +326,8 @@ public: return instmeth_iterator(decls_end()); } - typedef filtered_decl_iterator + typedef filtered_decl_iterator classmeth_iterator; classmeth_iterator classmeth_begin() const { return classmeth_iterator(decls_begin()); @@ -345,7 +345,7 @@ public: return getMethod(Sel, false/*isInstance*/); } ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const; - + ObjCPropertyDecl *FindPropertyDeclaration(IdentifierInfo *PropertyId) const; // Marks the end of the container. @@ -355,10 +355,10 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(getLocation(), getAtEndLoc()); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { - return D->getKind() >= ObjCContainerFirst && + return D->getKind() >= ObjCContainerFirst && D->getKind() <= ObjCContainerLast; } static bool classof(const ObjCContainerDecl *D) { return true; } @@ -374,11 +374,11 @@ public: /// ObjCInterfaceDecl - Represents an ObjC class declaration. For example: /// /// // MostPrimitive declares no super class (not particularly useful). -/// @interface MostPrimitive +/// @interface MostPrimitive /// // no instance variables or methods. /// @end /// -/// // NSResponder inherits from NSObject & implements NSCoding (a protocol). +/// // NSResponder inherits from NSObject & implements NSCoding (a protocol). /// @interface NSResponder : NSObject /// { // instance variables are represented by ObjCIvarDecl. /// id nextResponder; // nextResponder instance variable. @@ -397,32 +397,32 @@ class ObjCInterfaceDecl : public ObjCContainerDecl { /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType mutable Type *TypeForDecl; friend class ASTContext; - + /// Class's super class. ObjCInterfaceDecl *SuperClass; - + /// Protocols referenced in interface header declaration ObjCList ReferencedProtocols; - + /// Instance variables in the interface. ObjCList IVars; - + /// List of categories defined for this class. /// FIXME: Why is this a linked list?? ObjCCategoryDecl *CategoryList; - + bool ForwardDecl:1; // declared with @class. bool InternalInterface:1; // true - no @interface for @implementation - + SourceLocation ClassLoc; // location of the class identifier. SourceLocation SuperClassLoc; // location of the super class identifier. SourceLocation EndLoc; // marks the '>', '}', or identifier. ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, SourceLocation CLoc, bool FD, bool isInternal); - + virtual ~ObjCInterfaceDecl() {} - + public: /// Destroy - Call destructors and release memory. @@ -430,24 +430,24 @@ public: static ObjCInterfaceDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation atLoc, - IdentifierInfo *Id, + IdentifierInfo *Id, SourceLocation ClassLoc = SourceLocation(), bool ForwardDecl = false, bool isInternal = false); - const ObjCList &getReferencedProtocols() const { - return ReferencedProtocols; + const ObjCList &getReferencedProtocols() const { + return ReferencedProtocols; } ObjCImplementationDecl *getImplementation() const; void setImplementation(ObjCImplementationDecl *ImplD); ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const; - + // Get the local instance/class method declared in a category. ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const; ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const; ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const { - return isInstance ? getInstanceMethod(Sel) + return isInstance ? getInstanceMethod(Sel) : getClassMethod(Sel); } @@ -461,29 +461,29 @@ public: ivar_iterator ivar_end() const { return IVars.end(); } unsigned ivar_size() const { return IVars.size(); } bool ivar_empty() const { return IVars.empty(); } - + /// setProtocolList - Set the list of protocols that this interface /// implements. void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num, ASTContext &C) { ReferencedProtocols.set(List, Num, C); } - + void setIVarList(ObjCIvarDecl * const *List, unsigned Num, ASTContext &C) { IVars.set(List, Num, C); } bool isForwardDecl() const { return ForwardDecl; } void setForwardDecl(bool val) { ForwardDecl = val; } - + ObjCInterfaceDecl *getSuperClass() const { return SuperClass; } void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; } - + ObjCCategoryDecl* getCategoryList() const { return CategoryList; } - void setCategoryList(ObjCCategoryDecl *category) { + void setCategoryList(ObjCCategoryDecl *category) { CategoryList = category; } - + /// isSuperClassOf - Return true if this class is the specified class or is a /// super class of the specified interface class. bool isSuperClassOf(const ObjCInterfaceDecl *I) const { @@ -495,7 +495,7 @@ public: } return false; } - + ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared); ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) { @@ -518,25 +518,25 @@ public: SourceLocation getLocStart() const { return getLocation(); } // '@'interface SourceLocation getLocEnd() const { return EndLoc; } void setLocEnd(SourceLocation LE) { EndLoc = LE; }; - + void setClassLoc(SourceLocation Loc) { ClassLoc = Loc; } SourceLocation getClassLoc() const { return ClassLoc; } void setSuperClassLoc(SourceLocation Loc) { SuperClassLoc = Loc; } SourceLocation getSuperClassLoc() const { return SuperClassLoc; } - + /// isImplicitInterfaceDecl - check that this is an implicitly declared /// ObjCInterfaceDecl node. This is for legacy objective-c @implementation /// declaration without an @interface declaration. bool isImplicitInterfaceDecl() const { return InternalInterface; } void setImplicitInterfaceDecl(bool val) { InternalInterface = val; } - + /// ClassImplementsProtocol - Checks that 'lProto' protocol /// has been implemented in IDecl class, its super class or categories (if /// lookupCategory is true). bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID = false); - + // Low-level accessor Type *getTypeForDecl() const { return TypeForDecl; } void setTypeForDecl(Type *TD) const { TypeForDecl = TD; } @@ -565,19 +565,19 @@ public: enum AccessControl { None, Private, Protected, Public, Package }; - + private: ObjCIvarDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo, AccessControl ac, Expr *BW) - : FieldDecl(ObjCIvar, DC, L, Id, T, DInfo, BW, /*Mutable=*/false), + : FieldDecl(ObjCIvar, DC, L, Id, T, DInfo, BW, /*Mutable=*/false), DeclAccess(ac) {} - + public: static ObjCIvarDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo, AccessControl ac, Expr *BW = NULL); - + void setAccessControl(AccessControl ac) { DeclAccess = ac; } AccessControl getAccessControl() const { return AccessControl(DeclAccess); } @@ -585,7 +585,7 @@ public: AccessControl getCanonicalAccessControl() const { return DeclAccess == None ? Protected : AccessControl(DeclAccess); } - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == ObjCIvar; } static bool classof(const ObjCIvarDecl *D) { return true; } @@ -594,7 +594,7 @@ private: unsigned DeclAccess : 3; }; - + /// ObjCAtDefsFieldDecl - Represents a field declaration created by an /// @defs(...). class ObjCAtDefsFieldDecl : public FieldDecl { @@ -604,13 +604,13 @@ private: : FieldDecl(ObjCAtDefsField, DC, L, Id, T, /*DInfo=*/0, // FIXME: Do ObjCAtDefs have declarators ? BW, /*Mutable=*/false) {} - + public: static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *BW); - + virtual void Destroy(ASTContext& C); // Implement isa/cast/dyncast/etc. @@ -619,8 +619,8 @@ public: }; /// ObjCProtocolDecl - Represents a protocol declaration. ObjC protocols -/// declare a pure abstract type (i.e no instance variables are permitted). -/// Protocols orginally drew inspiration from C++ pure virtual functions (a C++ +/// declare a pure abstract type (i.e no instance variables are permitted). +/// Protocols orginally drew inspiration from C++ pure virtual functions (a C++ /// feature with nice semantics and lousy syntax:-). Here is an example: /// /// @protocol NSDraggingInfo @@ -637,7 +637,7 @@ public: /// /// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and /// protocols are in distinct namespaces. For example, Cocoa defines both -/// an NSObject protocol and class (which isn't allowed in Java). As a result, +/// an NSObject protocol and class (which isn't allowed in Java). As a result, /// protocols are referenced using angle brackets as follows: /// /// id anyObjectThatImplementsNSDraggingInfo; @@ -645,42 +645,42 @@ public: class ObjCProtocolDecl : public ObjCContainerDecl { /// Referenced protocols ObjCList ReferencedProtocols; - + bool isForwardProtoDecl; // declared with @protocol. - + SourceLocation EndLoc; // marks the '>' or identifier. - + ObjCProtocolDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id) - : ObjCContainerDecl(ObjCProtocol, DC, L, Id), + : ObjCContainerDecl(ObjCProtocol, DC, L, Id), isForwardProtoDecl(true) { } - + virtual ~ObjCProtocolDecl() {} - + public: - static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC, + static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id); /// Destroy - Call destructors and release memory. virtual void Destroy(ASTContext& C); - - const ObjCList &getReferencedProtocols() const { + + const ObjCList &getReferencedProtocols() const { return ReferencedProtocols; } typedef ObjCList::iterator protocol_iterator; protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();} protocol_iterator protocol_end() const { return ReferencedProtocols.end(); } unsigned protocol_size() const { return ReferencedProtocols.size(); } - + /// setProtocolList - Set the list of protocols that this interface /// implements. void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num, ASTContext &C) { ReferencedProtocols.set(List, Num, C); } - + ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName); - + // Lookup a method. First, we search locally. If a method isn't // found, we search referenced protocols and class categories. ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const; @@ -694,34 +694,34 @@ public: bool isForwardDecl() const { return isForwardProtoDecl; } void setForwardDecl(bool val) { isForwardProtoDecl = val; } - // Location information, modeled after the Stmt API. + // Location information, modeled after the Stmt API. SourceLocation getLocStart() const { return getLocation(); } // '@'protocol SourceLocation getLocEnd() const { return EndLoc; } void setLocEnd(SourceLocation LE) { EndLoc = LE; }; - + static bool classof(const Decl *D) { return D->getKind() == ObjCProtocol; } static bool classof(const ObjCProtocolDecl *D) { return true; } }; - + /// ObjCClassDecl - Specifies a list of forward class declarations. For example: /// /// @class NSCursor, NSImage, NSPasteboard, NSWindow; /// class ObjCClassDecl : public Decl { ObjCList ForwardDecls; - - ObjCClassDecl(DeclContext *DC, SourceLocation L, + + ObjCClassDecl(DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *const *Elts, unsigned nElts, ASTContext &C); virtual ~ObjCClassDecl() {} public: - + /// Destroy - Call destructors and release memory. virtual void Destroy(ASTContext& C); - + static ObjCClassDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, - ObjCInterfaceDecl *const *Elts = 0, + ObjCInterfaceDecl *const *Elts = 0, unsigned nElts = 0); - + typedef ObjCList::iterator iterator; iterator begin() const { return ForwardDecls.begin(); } iterator end() const { return ForwardDecls.end(); } @@ -731,33 +731,33 @@ public: void setClassList(ASTContext &C, ObjCInterfaceDecl*const*List, unsigned Num) { ForwardDecls.set(List, Num, C); } - + static bool classof(const Decl *D) { return D->getKind() == ObjCClass; } static bool classof(const ObjCClassDecl *D) { return true; } }; /// ObjCForwardProtocolDecl - Specifies a list of forward protocol declarations. /// For example: -/// +/// /// @protocol NSTextInput, NSChangeSpelling, NSDraggingInfo; -/// +/// class ObjCForwardProtocolDecl : public Decl { ObjCList ReferencedProtocols; - + ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L, ObjCProtocolDecl *const *Elts, unsigned nElts, - ASTContext &C); + ASTContext &C); virtual ~ObjCForwardProtocolDecl() {} - + public: static ObjCForwardProtocolDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, + SourceLocation L, ObjCProtocolDecl *const *Elts = 0, unsigned Num = 0); /// Destroy - Call destructors and release memory. virtual void Destroy(ASTContext& C); - + typedef ObjCList::iterator protocol_iterator; protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();} protocol_iterator protocol_end() const { return ReferencedProtocols.end(); } @@ -776,7 +776,7 @@ public: /// ObjCCategoryDecl - Represents a category declaration. A category allows /// you to add methods to an existing class (without subclassing or modifying -/// the original class interface or implementation:-). Categories don't allow +/// the original class interface or implementation:-). Categories don't allow /// you to add instance data. The following example adds "myMethod" to all /// NSView's within a process: /// @@ -788,31 +788,31 @@ public: /// several files (a feature more naturally supported in C++). /// /// Categories were originally inspired by dynamic languages such as Common -/// Lisp and Smalltalk. More traditional class-based languages (C++, Java) +/// Lisp and Smalltalk. More traditional class-based languages (C++, Java) /// don't support this level of dynamism, which is both powerful and dangerous. /// class ObjCCategoryDecl : public ObjCContainerDecl { /// Interface belonging to this category ObjCInterfaceDecl *ClassInterface; - + /// referenced protocols in this category. ObjCList ReferencedProtocols; - + /// Next category belonging to this class. /// FIXME: this should not be a singly-linked list. Move storage elsewhere. ObjCCategoryDecl *NextClassCategory; - + SourceLocation EndLoc; // marks the '>' or identifier. - + ObjCCategoryDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id) : ObjCContainerDecl(ObjCCategory, DC, L, Id), ClassInterface(0), NextClassCategory(0){ } public: - + static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id); - + ObjCInterfaceDecl *getClassInterface() { return ClassInterface; } const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; } void setClassInterface(ObjCInterfaceDecl *IDecl) { ClassInterface = IDecl; } @@ -826,16 +826,16 @@ public: ASTContext &C) { ReferencedProtocols.set(List, Num, C); } - - const ObjCList &getReferencedProtocols() const { + + const ObjCList &getReferencedProtocols() const { return ReferencedProtocols; } - + typedef ObjCList::iterator protocol_iterator; protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();} protocol_iterator protocol_end() const { return ReferencedProtocols.end(); } unsigned protocol_size() const { return ReferencedProtocols.size(); } - + ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; } void setNextClassCategory(ObjCCategoryDecl *Cat) { NextClassCategory = Cat; @@ -844,11 +844,11 @@ public: NextClassCategory = ClassInterface->getCategoryList(); ClassInterface->setCategoryList(this); } - // Location information, modeled after the Stmt API. + // Location information, modeled after the Stmt API. SourceLocation getLocStart() const { return getLocation(); } // '@'interface SourceLocation getLocEnd() const { return EndLoc; } void setLocEnd(SourceLocation LE) { EndLoc = LE; }; - + static bool classof(const Decl *D) { return D->getKind() == ObjCCategory; } static bool classof(const ObjCCategoryDecl *D) { return true; } }; @@ -856,43 +856,43 @@ public: class ObjCImplDecl : public ObjCContainerDecl { /// Class interface for this category implementation ObjCInterfaceDecl *ClassInterface; - + protected: ObjCImplDecl(Kind DK, DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *classInterface) - : ObjCContainerDecl(DK, DC, L, - classInterface? classInterface->getIdentifier() : 0), + : ObjCContainerDecl(DK, DC, L, + classInterface? classInterface->getIdentifier() : 0), ClassInterface(classInterface) {} - + public: virtual ~ObjCImplDecl() {} - + const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; } ObjCInterfaceDecl *getClassInterface() { return ClassInterface; } void setClassInterface(ObjCInterfaceDecl *IFace); - void addInstanceMethod(ObjCMethodDecl *method) { + void addInstanceMethod(ObjCMethodDecl *method) { // FIXME: Context should be set correctly before we get here. method->setLexicalDeclContext(this); - addDecl(method); + addDecl(method); } - void addClassMethod(ObjCMethodDecl *method) { + void addClassMethod(ObjCMethodDecl *method) { // FIXME: Context should be set correctly before we get here. method->setLexicalDeclContext(this); - addDecl(method); + addDecl(method); } - + void addPropertyImplementation(ObjCPropertyImplDecl *property); - + ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId) const; ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const; // Iterator access to properties. typedef specific_decl_iterator propimpl_iterator; - propimpl_iterator propimpl_begin() const { + propimpl_iterator propimpl_begin() const { return propimpl_iterator(decls_begin()); } - propimpl_iterator propimpl_end() const { + propimpl_iterator propimpl_end() const { return propimpl_iterator(decls_end()); } @@ -901,10 +901,10 @@ public: } static bool classof(const ObjCImplDecl *D) { return true; } }; - -/// ObjCCategoryImplDecl - An object of this class encapsulates a category -/// @implementation declaration. If a category class has declaration of a -/// property, its implementation must be specified in the category's + +/// ObjCCategoryImplDecl - An object of this class encapsulates a category +/// @implementation declaration. If a category class has declaration of a +/// property, its implementation must be specified in the category's /// @implementation declaration. Example: /// @interface I @end /// @interface I(CATEGORY) @@ -926,14 +926,14 @@ public: static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, ObjCInterfaceDecl *classInterface); - + /// getIdentifier - Get the identifier that names the class /// interface associated with this implementation. - IdentifierInfo *getIdentifier() const { - return Id; + IdentifierInfo *getIdentifier() const { + return Id; } void setIdentifier(IdentifierInfo *II) { Id = II; } - + ObjCCategoryDecl *getCategoryClass() const; /// getNameAsCString - Get the name of identifier for the class @@ -942,12 +942,12 @@ public: const char *getNameAsCString() const { return Id ? Id->getName() : ""; } - + /// @brief Get the name of the class associated with this interface. std::string getNameAsString() const { return Id ? Id->getName() : ""; } - + static bool classof(const Decl *D) { return D->getKind() == ObjCCategoryImpl;} static bool classof(const ObjCCategoryImplDecl *D) { return true; } }; @@ -961,30 +961,30 @@ public: /// @end /// @endcode /// -/// Typically, instance variables are specified in the class interface, +/// Typically, instance variables are specified in the class interface, /// *not* in the implementation. Nevertheless (for legacy reasons), we /// allow instance variables to be specified in the implementation. When /// specified, they need to be *identical* to the interface. /// -class ObjCImplementationDecl : public ObjCImplDecl { +class ObjCImplementationDecl : public ObjCImplDecl { /// Implementation Class's super class. ObjCInterfaceDecl *SuperClass; - - ObjCImplementationDecl(DeclContext *DC, SourceLocation L, + + ObjCImplementationDecl(DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *classInterface, ObjCInterfaceDecl *superDecl) - : ObjCImplDecl(ObjCImplementation, DC, L, classInterface), + : ObjCImplDecl(ObjCImplementation, DC, L, classInterface), SuperClass(superDecl){} -public: - static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, +public: + static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, ObjCInterfaceDecl *classInterface, ObjCInterfaceDecl *superDecl); - + /// getIdentifier - Get the identifier that names the class /// interface associated with this implementation. - IdentifierInfo *getIdentifier() const { - return getClassInterface()->getIdentifier(); + IdentifierInfo *getIdentifier() const { + return getClassInterface()->getIdentifier(); } /// getNameAsCString - Get the name of identifier for the class @@ -1002,35 +1002,35 @@ public: const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; } ObjCInterfaceDecl *getSuperClass() { return SuperClass; } - + void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; } - + typedef specific_decl_iterator ivar_iterator; - ivar_iterator ivar_begin() const { - return ivar_iterator(decls_begin()); + ivar_iterator ivar_begin() const { + return ivar_iterator(decls_begin()); } - ivar_iterator ivar_end() const { + ivar_iterator ivar_end() const { return ivar_iterator(decls_end()); } - unsigned ivar_size() const { + unsigned ivar_size() const { return std::distance(ivar_begin(), ivar_end()); } - bool ivar_empty() const { + bool ivar_empty() const { return ivar_begin() == ivar_end(); } - + static bool classof(const Decl *D) { return D->getKind() == ObjCImplementation; } static bool classof(const ObjCImplementationDecl *D) { return true; } }; -/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is +/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is /// declared as @compatibility_alias alias class. class ObjCCompatibleAliasDecl : public NamedDecl { /// Class that this is an alias of. ObjCInterfaceDecl *AliasedClass; - + ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, ObjCInterfaceDecl* aliasedClass) : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {} @@ -1042,12 +1042,12 @@ public: const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; } ObjCInterfaceDecl *getClassInterface() { return AliasedClass; } void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; } - + static bool classof(const Decl *D) { return D->getKind() == ObjCCompatibleAlias; } static bool classof(const ObjCCompatibleAliasDecl *D) { return true; } - + }; /// ObjCPropertyDecl - Represents one property declaration in an interface. @@ -1057,13 +1057,13 @@ public: class ObjCPropertyDecl : public NamedDecl { public: enum PropertyAttributeKind { - OBJC_PR_noattr = 0x00, - OBJC_PR_readonly = 0x01, + OBJC_PR_noattr = 0x00, + OBJC_PR_readonly = 0x01, OBJC_PR_getter = 0x02, - OBJC_PR_assign = 0x04, - OBJC_PR_readwrite = 0x08, + OBJC_PR_assign = 0x04, + OBJC_PR_readwrite = 0x08, OBJC_PR_retain = 0x10, - OBJC_PR_copy = 0x20, + OBJC_PR_copy = 0x20, OBJC_PR_nonatomic = 0x40, OBJC_PR_setter = 0x80 }; @@ -1073,27 +1073,27 @@ public: private: QualType DeclType; unsigned PropertyAttributes : 8; - + // @required/@optional unsigned PropertyImplementation : 2; - + Selector GetterName; // getter name of NULL if no getter Selector SetterName; // setter name of NULL if no setter - + ObjCMethodDecl *GetterMethodDecl; // Declaration of getter instance method ObjCMethodDecl *SetterMethodDecl; // Declaration of setter instance method ObjCIvarDecl *PropertyIvarDecl; // Synthesize ivar for this property - ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, + ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T) : NamedDecl(ObjCProperty, DC, L, Id), DeclType(T), PropertyAttributes(OBJC_PR_noattr), PropertyImplementation(None), - GetterName(Selector()), + GetterName(Selector()), SetterName(Selector()), GetterMethodDecl(0), SetterMethodDecl(0) , PropertyIvarDecl(0) {} public: - static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, + static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, IdentifierInfo *Id, QualType T, PropertyControl propControl = None); QualType getType() const { return DeclType; } @@ -1102,14 +1102,14 @@ public: PropertyAttributeKind getPropertyAttributes() const { return PropertyAttributeKind(PropertyAttributes); } - void setPropertyAttributes(PropertyAttributeKind PRVal) { + void setPropertyAttributes(PropertyAttributeKind PRVal) { PropertyAttributes |= PRVal; } void makeitReadWriteAttribute(void) { PropertyAttributes &= ~OBJC_PR_readonly; PropertyAttributes |= OBJC_PR_readwrite; - } + } // Helper methods for accessing attributes. @@ -1131,38 +1131,38 @@ public: Selector getGetterName() const { return GetterName; } void setGetterName(Selector Sel) { GetterName = Sel; } - + Selector getSetterName() const { return SetterName; } void setSetterName(Selector Sel) { SetterName = Sel; } - + ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; } void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; } ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; } void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; } - + // Related to @optional/@required declared in @protocol void setPropertyImplementation(PropertyControl pc) { PropertyImplementation = pc; } PropertyControl getPropertyImplementation() const { return PropertyControl(PropertyImplementation); - } - + } + void setPropertyIvarDecl(ObjCIvarDecl *Ivar) { PropertyIvarDecl = Ivar; } ObjCIvarDecl *getPropertyIvarDecl() const { return PropertyIvarDecl; } - + static bool classof(const Decl *D) { return D->getKind() == ObjCProperty; } static bool classof(const ObjCPropertyDecl *D) { return true; } }; -/// ObjCPropertyImplDecl - Represents implementation declaration of a property +/// ObjCPropertyImplDecl - Represents implementation declaration of a property /// in a class or category implementation block. For example: /// @synthesize prop1 = ivar1; /// @@ -1181,23 +1181,23 @@ private: ObjCIvarDecl *PropertyIvarDecl; ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L, - ObjCPropertyDecl *property, - Kind PK, + ObjCPropertyDecl *property, + Kind PK, ObjCIvarDecl *ivarDecl) - : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc), + : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl) { assert (PK == Dynamic || PropertyIvarDecl); } - + public: static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation atLoc, SourceLocation L, - ObjCPropertyDecl *property, - Kind PK, + SourceLocation atLoc, SourceLocation L, + ObjCPropertyDecl *property, + Kind PK, ObjCIvarDecl *ivarDecl); - virtual SourceRange getSourceRange() const { - return SourceRange(AtLoc, getLocation()); + virtual SourceRange getSourceRange() const { + return SourceRange(AtLoc, getLocation()); } SourceLocation getLocStart() const { return AtLoc; } void setAtLoc(SourceLocation Loc) { AtLoc = Loc; } @@ -1210,7 +1210,7 @@ public: Kind getPropertyImplementation() const { return PropertyIvarDecl ? Synthesize : Dynamic; } - + ObjCIvarDecl *getPropertyIvarDecl() const { return PropertyIvarDecl; } @@ -1219,7 +1219,7 @@ public: static bool classof(const Decl *D) { return D->getKind() == ObjCPropertyImpl; } - static bool classof(const ObjCPropertyImplDecl *D) { return true; } + static bool classof(const ObjCPropertyImplDecl *D) { return true; } }; } // end namespace clang diff --git a/clang/include/clang/AST/DeclTemplate.h b/clang/include/clang/AST/DeclTemplate.h index 24524dff3838a2a9188b03e7e0daa601f8318443..0232d9382e168ffa2cd9b69a1d286fe74d3dfd38 100644 --- a/clang/include/clang/AST/DeclTemplate.h +++ b/clang/include/clang/AST/DeclTemplate.h @@ -53,7 +53,7 @@ class TemplateParameterList { SourceLocation RAngleLoc); public: - static TemplateParameterList *Create(ASTContext &C, + static TemplateParameterList *Create(ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, Decl **Params, @@ -115,10 +115,10 @@ class TemplateArgument { bool CopyArgs; } Args; }; - + /// \brief Location of the beginning of this template argument. SourceLocation StartLoc; - + public: /// \brief The type of template argument we're storing. enum ArgKind { @@ -133,21 +133,21 @@ public: /// The template argument is a value- or type-dependent expression /// stored in an Expr*. Expression = 4, - + /// The template argument is actually a parameter pack. Arguments are stored /// in the Args struct. Pack = 5 } Kind; - + /// \brief Construct an empty, invalid template argument. TemplateArgument() : TypeOrValue(0), StartLoc(), Kind(Null) { } - + /// \brief Construct a template type argument. TemplateArgument(SourceLocation Loc, QualType T) : Kind(Type) { TypeOrValue = reinterpret_cast(T.getAsOpaquePtr()); StartLoc = Loc; } - + /// \brief Construct a template argument that refers to a /// declaration, which is either an external declaration or a /// template declaration. @@ -156,7 +156,7 @@ public: TypeOrValue = reinterpret_cast(D); StartLoc = Loc; } - + /// \brief Construct an integral constant template argument. TemplateArgument(SourceLocation Loc, const llvm::APSInt &Value, QualType Type) @@ -165,14 +165,14 @@ public: Integer.Type = Type.getAsOpaquePtr(); StartLoc = Loc; } - - /// \brief Construct a template argument that is an expression. + + /// \brief Construct a template argument that is an expression. /// /// This form of template argument only occurs in template argument /// lists used for dependent types and for expression; it will not /// occur in a non-dependent, canonical template argument list. TemplateArgument(Expr *E); - + /// \brief Copy constructor for a template argument. TemplateArgument(const TemplateArgument &Other) : Kind(Other.Kind) { if (Kind == Integral) { @@ -188,27 +188,27 @@ public: TypeOrValue = Other.TypeOrValue; StartLoc = Other.StartLoc; } - + TemplateArgument& operator=(const TemplateArgument& Other) { // FIXME: Does not provide the strong guarantee for exception // safety. using llvm::APSInt; - + // FIXME: Handle Packs assert(Kind != Pack && "FIXME: Handle packs"); assert(Other.Kind != Pack && "FIXME: Handle packs"); - + if (Kind == Other.Kind && Kind == Integral) { // Copy integral values. *this->getAsIntegral() = *Other.getAsIntegral(); - Integer.Type = Other.Integer.Type; + Integer.Type = Other.Integer.Type; } else { // Destroy the current integral value, if that's what we're holding. if (Kind == Integral) getAsIntegral()->~APSInt(); - + Kind = Other.Kind; - + if (Other.Kind == Integral) { new (Integer.Value) llvm::APSInt(*Other.getAsIntegral()); Integer.Type = Other.Integer.Type; @@ -216,127 +216,127 @@ public: TypeOrValue = Other.TypeOrValue; } StartLoc = Other.StartLoc; - + return *this; } - + ~TemplateArgument() { using llvm::APSInt; - + if (Kind == Integral) getAsIntegral()->~APSInt(); else if (Kind == Pack && Args.CopyArgs) delete[] Args.Args; } - + /// \brief Return the kind of stored template argument. ArgKind getKind() const { return Kind; } - + /// \brief Determine whether this template argument has no value. bool isNull() const { return Kind == Null; } - + /// \brief Retrieve the template argument as a type. QualType getAsType() const { if (Kind != Type) return QualType(); - + return QualType::getFromOpaquePtr(reinterpret_cast(TypeOrValue)); } - + /// \brief Retrieve the template argument as a declaration. Decl *getAsDecl() const { if (Kind != Declaration) return 0; return reinterpret_cast(TypeOrValue); } - + /// \brief Retrieve the template argument as an integral value. llvm::APSInt *getAsIntegral() { if (Kind != Integral) return 0; return reinterpret_cast(&Integer.Value[0]); } - + const llvm::APSInt *getAsIntegral() const { return const_cast(this)->getAsIntegral(); } - + /// \brief Retrieve the type of the integral value. QualType getIntegralType() const { if (Kind != Integral) return QualType(); - + return QualType::getFromOpaquePtr(Integer.Type); } - + void setIntegralType(QualType T) { - assert(Kind == Integral && + assert(Kind == Integral && "Cannot set the integral type of a non-integral template argument"); Integer.Type = T.getAsOpaquePtr(); }; - + /// \brief Retrieve the template argument as an expression. Expr *getAsExpr() const { if (Kind != Expression) return 0; - + return reinterpret_cast(TypeOrValue); } - + /// \brief Iterator that traverses the elements of a template argument pack. typedef const TemplateArgument * pack_iterator; - - /// \brief Iterator referencing the first argument of a template argument + + /// \brief Iterator referencing the first argument of a template argument /// pack. pack_iterator pack_begin() const { assert(Kind == Pack); return Args.Args; } - + /// \brief Iterator referencing one past the last argument of a template /// argument pack. pack_iterator pack_end() const { assert(Kind == Pack); return Args.Args + Args.NumArgs; } - + /// \brief The number of template arguments in the given template argument /// pack. unsigned pack_size() const { assert(Kind == Pack); return Args.NumArgs; } - + /// \brief Retrieve the location where the template argument starts. SourceLocation getLocation() const { return StartLoc; } - + /// \brief Construct a template argument pack. void setArgumentPack(TemplateArgument *Args, unsigned NumArgs, bool CopyArgs); - + /// \brief Used to insert TemplateArguments into FoldingSets. void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context) const { ID.AddInteger(Kind); switch (Kind) { case Null: break; - + case Type: getAsType().Profile(ID); break; - + case Declaration: ID.AddPointer(getAsDecl()? getAsDecl()->getCanonicalDecl() : 0); break; - + case Integral: getAsIntegral()->Profile(ID); getIntegralType().Profile(ID); break; - + case Expression: getAsExpr()->Profile(ID, Context, true); break; - + case Pack: ID.AddInteger(Args.NumArgs); for (unsigned I = 0; I != Args.NumArgs; ++I) @@ -350,47 +350,47 @@ class TemplateArgumentListBuilder { TemplateArgument *StructuredArgs; unsigned MaxStructuredArgs; unsigned NumStructuredArgs; - + TemplateArgument *FlatArgs; unsigned MaxFlatArgs; unsigned NumFlatArgs; - + bool AddingToPack; unsigned PackBeginIndex; - + public: TemplateArgumentListBuilder(const TemplateParameterList *Parameters, unsigned NumTemplateArgs) - : StructuredArgs(0), MaxStructuredArgs(Parameters->size()), - NumStructuredArgs(0), FlatArgs(0), + : StructuredArgs(0), MaxStructuredArgs(Parameters->size()), + NumStructuredArgs(0), FlatArgs(0), MaxFlatArgs(std::max(MaxStructuredArgs, NumTemplateArgs)), NumFlatArgs(0), AddingToPack(false), PackBeginIndex(0) { } - + void Append(const TemplateArgument& Arg); void BeginPack(); void EndPack(); - + void ReleaseArgs(); - - unsigned flatSize() const { + + unsigned flatSize() const { return NumFlatArgs; } const TemplateArgument *getFlatArguments() const { return FlatArgs; } - + unsigned structuredSize() const { // If we don't have any structured args, just reuse the flat size. if (!StructuredArgs) return flatSize(); - + return NumStructuredArgs; } const TemplateArgument *getStructuredArguments() const { // If we don't have any structured args, just reuse the flat args. if (!StructuredArgs) return getFlatArguments(); - + return StructuredArgs; } }; @@ -406,44 +406,44 @@ class TemplateArgumentList { /// The integer value will be non-zero to indicate that this /// template argument list does not own the pointer. llvm::PointerIntPair FlatArguments; - + /// \brief The number of template arguments in this template /// argument list. unsigned NumFlatArguments; - + llvm::PointerIntPair StructuredArguments; unsigned NumStructuredArguments; - + public: TemplateArgumentList(ASTContext &Context, TemplateArgumentListBuilder &Builder, bool TakeArgs); - + ~TemplateArgumentList(); - + /// \brief Retrieve the template argument at a given index. - const TemplateArgument &get(unsigned Idx) const { + const TemplateArgument &get(unsigned Idx) const { assert(Idx < NumFlatArguments && "Invalid template argument index"); return getFlatArgumentList()[Idx]; } - + /// \brief Retrieve the template argument at a given index. const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); } - + /// \brief Retrieve the number of template arguments in this /// template argument list. unsigned size() const { return NumFlatArguments; } - + /// \brief Retrieve the number of template arguments in the /// flattened template argument list. unsigned flat_size() const { return NumFlatArguments; } - + /// \brief Retrieve the flattened template argument list. - const TemplateArgument *getFlatArgumentList() const { + const TemplateArgument *getFlatArgumentList() const { return FlatArguments.getPointer(); } }; - + //===----------------------------------------------------------------------===// // Kinds of Templates //===----------------------------------------------------------------------===// @@ -457,15 +457,13 @@ protected: // This is probably never used. TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name) - : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) - { } + : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) { } // Construct a template decl with the given name and parameters. // Used when there is not templated element (tt-params, alias?). TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params) - : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) - { } + : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) { } // Construct a template decl with name, parameters, and templated element. TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, @@ -497,26 +495,26 @@ protected: NamedDecl *TemplatedDecl; TemplateParameterList* TemplateParams; }; - -/// \brief Provides information about a function template specialization, + +/// \brief Provides information about a function template specialization, /// which is a FunctionDecl that has been explicitly specialization or /// instantiated from a function template. class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode { public: - /// \brief The function template specialization that this structure + /// \brief The function template specialization that this structure /// describes. FunctionDecl *Function; - - /// \brief The function template from which this function template + + /// \brief The function template from which this function template /// specialization was generated. /// /// The two bits are contain the top 4 values of TemplateSpecializationKind. llvm::PointerIntPair Template; - + /// \brief The template arguments used to produce the function template /// specialization from the function template. const TemplateArgumentList *TemplateArguments; - + /// \brief Retrieve the template from which this function was specialized. FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); } @@ -527,61 +525,61 @@ public: /// \brief Set the template specialization kind. void setTemplateSpecializationKind(TemplateSpecializationKind TSK) { - assert(TSK != TSK_Undeclared && + assert(TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"); Template.setInt(TSK - 1); } - + void Profile(llvm::FoldingSetNodeID &ID) { - Profile(ID, TemplateArguments->getFlatArgumentList(), + Profile(ID, TemplateArguments->getFlatArgumentList(), TemplateArguments->flat_size(), - Function->getASTContext()); + Function->getASTContext()); } - - static void - Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs, + + static void + Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, ASTContext &Context) { ID.AddInteger(NumTemplateArgs); for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg) TemplateArgs[Arg].Profile(ID, Context); - } + } }; - + /// Declaration of a template function. -class FunctionTemplateDecl : public TemplateDecl { +class FunctionTemplateDecl : public TemplateDecl { protected: /// \brief Data that is common to all of the declarations of a given /// function template. struct Common { Common() : InstantiatedFromMember(0) { } - + /// \brief The function template specializations for this function /// template, including explicit specializations and instantiations. llvm::FoldingSet Specializations; - + /// \brief The member function template from which this was most /// directly instantiated (or null). - FunctionTemplateDecl *InstantiatedFromMember; + FunctionTemplateDecl *InstantiatedFromMember; }; - + /// \brief A pointer to the previous declaration (if this is a redeclaration) /// or to the data that is common to all declarations of this function /// template. llvm::PointerUnion CommonOrPrev; - - /// \brief Retrieves the "common" pointer shared by all + + /// \brief Retrieves the "common" pointer shared by all /// (re-)declarations of the same function template. Calling this routine /// may implicitly allocate memory for the common pointer. Common *getCommonPtr(); - + FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl) : TemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl), CommonOrPrev((Common*)0) { } - + public: void Destroy(ASTContext &C); - + /// Get the underlying function declaration of the template. FunctionDecl *getTemplatedDecl() const { return static_cast(TemplatedDecl); @@ -592,7 +590,7 @@ public: llvm::FoldingSet &getSpecializations() { return getCommonPtr()->Specializations; } - + /// \brief Retrieve the previous declaration of this function template, or /// NULL if no such declaration exists. const FunctionTemplateDecl *getPreviousDeclaration() const { @@ -604,16 +602,16 @@ public: FunctionTemplateDecl *getPreviousDeclaration() { return CommonOrPrev.dyn_cast(); } - + /// \brief Set the previous declaration of this function template. void setPreviousDeclaration(FunctionTemplateDecl *Prev) { if (Prev) CommonOrPrev = Prev; } - + virtual FunctionTemplateDecl *getCanonicalDecl(); - - /// \brief Retrieve the member function template that this function template + + /// \brief Retrieve the member function template that this function template /// was instantiated from. /// /// This routine will return non-NULL for member function templates of @@ -627,23 +625,23 @@ public: /// \endcode /// /// X::A is a CXXMethodDecl (whose parent is X, a - /// ClassTemplateSpecializationDecl) for which getPrimaryTemplate() will + /// ClassTemplateSpecializationDecl) for which getPrimaryTemplate() will /// return X::f, a FunctionTemplateDecl (whose parent is again /// X) for which getInstantiatedFromMemberTemplate() will return - /// X::f, a FunctionTemplateDecl (whose parent is X, a + /// X::f, a FunctionTemplateDecl (whose parent is X, a /// ClassTemplateDecl). /// - /// \returns NULL if this is not an instantiation of a member function + /// \returns NULL if this is not an instantiation of a member function /// template. FunctionTemplateDecl *getInstantiatedFromMemberTemplate() { return getCommonPtr()->InstantiatedFromMember; } - + void setInstantiatedFromMemberTemplate(FunctionTemplateDecl *FTD) { assert(!getCommonPtr()->InstantiatedFromMember); getCommonPtr()->InstantiatedFromMember = FTD; } - + /// Create a template function node. static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, @@ -669,8 +667,7 @@ public: /// the occurrence within the parameter list. /// This class is inheritedly privately by different kinds of template /// parameters and is not part of the Decl hierarchy. Just a facility. -class TemplateParmPosition -{ +class TemplateParmPosition { protected: // FIXME: This should probably never be called, but it's here as TemplateParmPosition() @@ -692,7 +689,7 @@ public: /// Get the position of the template parameter within its parameter list. unsigned getPosition() const { return Position; } - + /// Get the index of the template parameter within its parameter list. unsigned getIndex() const { return Position; } }; @@ -721,10 +718,10 @@ class TemplateTypeParmDecl : public TypeDecl { /// \brief The default template argument, if any. QualType DefaultArgument; - TemplateTypeParmDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, + TemplateTypeParmDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, bool Typename, QualType Type, bool ParameterPack) : TypeDecl(TemplateTypeParm, DC, L, Id), Typename(Typename), - InheritedDefault(false), ParameterPack(ParameterPack), DefaultArgument() { + InheritedDefault(false), ParameterPack(ParameterPack), DefaultArgument() { TypeForDecl = Type.getTypePtr(); } @@ -787,7 +784,7 @@ class NonTypeTemplateParmDecl unsigned P, IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo) : VarDecl(NonTypeTemplateParm, DC, L, Id, T, DInfo, VarDecl::None), - TemplateParmPosition(D, P), DefaultArgument(0) + TemplateParmPosition(D, P), DefaultArgument(0) { } public: @@ -798,7 +795,7 @@ public: using TemplateParmPosition::getDepth; using TemplateParmPosition::getPosition; using TemplateParmPosition::getIndex; - + /// \brief Determine whether this template parameter has a default /// argument. bool hasDefaultArgument() const { return DefaultArgument; } @@ -850,7 +847,7 @@ public: using TemplateParmPosition::getDepth; using TemplateParmPosition::getPosition; using TemplateParmPosition::getIndex; - + /// \brief Determine whether this template parameter has a default /// argument. bool hasDefaultArgument() const { return DefaultArgument; } @@ -882,26 +879,26 @@ public: /// /// \code /// template class array; -/// -/// template<> +/// +/// template<> /// class array { }; // class template specialization array /// \endcode -class ClassTemplateSpecializationDecl +class ClassTemplateSpecializationDecl : public CXXRecordDecl, public llvm::FoldingSetNode { - - /// \brief Structure that stores information about a class template + + /// \brief Structure that stores information about a class template /// specialization that was instantiated from a class template partial /// specialization. struct SpecializedPartialSpecialization { /// \brief The class template partial specialization from which this /// class template specialization was instantiated. ClassTemplatePartialSpecializationDecl *PartialSpecialization; - + /// \brief The template argument list deduced for the class template /// partial specialization itself. TemplateArgumentList *TemplateArgs; }; - + /// \brief The template that this specialization specializes llvm::PointerUnion SpecializedTemplate; @@ -919,7 +916,7 @@ protected: ClassTemplateDecl *SpecializedTemplate, TemplateArgumentListBuilder &Builder, ClassTemplateSpecializationDecl *PrevDecl); - + public: static ClassTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation L, @@ -932,9 +929,9 @@ public: /// \brief Retrieve the template that this specialization specializes. ClassTemplateDecl *getSpecializedTemplate() const; - /// \brief Retrieve the template arguments of the class template + /// \brief Retrieve the template arguments of the class template /// specialization. - const TemplateArgumentList &getTemplateArgs() const { + const TemplateArgumentList &getTemplateArgs() const { return TemplateArgs; } @@ -952,22 +949,22 @@ public: /// a template (rather than an explicit specialization), return the /// class template or class template partial specialization from which it /// was instantiated. - llvm::PointerUnion getInstantiatedFrom() const { if (getSpecializationKind() != TSK_ImplicitInstantiation && getSpecializationKind() != TSK_ExplicitInstantiationDefinition && getSpecializationKind() != TSK_ExplicitInstantiationDeclaration) return (ClassTemplateDecl*)0; - - if (SpecializedPartialSpecialization *PartialSpec + + if (SpecializedPartialSpecialization *PartialSpec = SpecializedTemplate.dyn_cast()) return PartialSpec->PartialSpecialization; - + return const_cast( SpecializedTemplate.get()); } - + /// \brief Retrieve the set of template arguments that should be used /// to instantiate members of the class template or class template partial /// specialization from which this class template specialization was @@ -980,25 +977,25 @@ public: /// deduced template arguments for the class template partial specialization /// itself. const TemplateArgumentList &getTemplateInstantiationArgs() const { - if (SpecializedPartialSpecialization *PartialSpec + if (SpecializedPartialSpecialization *PartialSpec = SpecializedTemplate.dyn_cast()) return *PartialSpec->TemplateArgs; - + return getTemplateArgs(); } - + /// \brief Note that this class template specialization is actually an /// instantiation of the given class template partial specialization whose /// template arguments have been deduced. void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, TemplateArgumentList *TemplateArgs) { - SpecializedPartialSpecialization *PS + SpecializedPartialSpecialization *PS = new (getASTContext()) SpecializedPartialSpecialization(); PS->PartialSpecialization = PartialSpec; PS->TemplateArgs = TemplateArgs; SpecializedTemplate = PS; } - + /// \brief Sets the type of this specialization as it was written by /// the user. This will be a class template specialization type. void setTypeAsWritten(QualType T) { @@ -1010,15 +1007,15 @@ public: getASTContext()); } - static void - Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs, + static void + Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, ASTContext &Context) { ID.AddInteger(NumTemplateArgs); for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg) TemplateArgs[Arg].Profile(ID, Context); } - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() == ClassTemplateSpecialization || D->getKind() == ClassTemplatePartialSpecialization; } @@ -1032,10 +1029,9 @@ public: } }; -class ClassTemplatePartialSpecializationDecl - : public ClassTemplateSpecializationDecl -{ - /// \brief The list of template parameters +class ClassTemplatePartialSpecializationDecl + : public ClassTemplateSpecializationDecl { + /// \brief The list of template parameters TemplateParameterList* TemplateParams; ClassTemplatePartialSpecializationDecl(ASTContext &Context, @@ -1044,7 +1040,7 @@ class ClassTemplatePartialSpecializationDecl ClassTemplateDecl *SpecializedTemplate, TemplateArgumentListBuilder &Builder, ClassTemplatePartialSpecializationDecl *PrevDecl) - : ClassTemplateSpecializationDecl(Context, + : ClassTemplateSpecializationDecl(Context, ClassTemplatePartialSpecialization, DC, L, SpecializedTemplate, Builder, PrevDecl), @@ -1065,7 +1061,7 @@ public: // FIXME: Add Profile support! - static bool classof(const Decl *D) { + static bool classof(const Decl *D) { return D->getKind() == ClassTemplatePartialSpecialization; } @@ -1088,7 +1084,7 @@ protected: /// \brief The class template partial specializations for this class /// template. - llvm::FoldingSet + llvm::FoldingSet PartialSpecializations; /// \brief The injected-class-name type for this class template. @@ -1104,11 +1100,11 @@ protected: /// \brief Pointer to the data that is common to all of the /// declarations of this class template. - /// + /// /// The first declaration of a class template (e.g., the declaration /// with no "previous declaration") owns this pointer. Common *CommonPtr; - + ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, ClassTemplateDecl *PrevDecl, Common *CommonPtr) @@ -1127,7 +1123,7 @@ public: ClassTemplateDecl *getPreviousDeclaration() const { return PreviousDeclaration; } - + virtual ClassTemplateDecl *getCanonicalDecl(); /// Create a class template node. @@ -1159,7 +1155,7 @@ public: /// \returns the class template partial specialization that exactly matches /// the type \p T, or NULL if no such partial specialization exists. ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T); - + /// \brief Retrieve the type of the injected-class-name for this /// class template. /// @@ -1215,7 +1211,7 @@ public: }; /// Implementation of inline functions that require the template declarations -inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD) +inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD) : Function(FTD) { } } /* end of namespace clang */ diff --git a/clang/include/clang/AST/DeclarationName.h b/clang/include/clang/AST/DeclarationName.h index 3d571b1ac073488b22648fbf30a13cc10517ffd9..9850e8fff092a757d43362a2857bc552989d3598 100644 --- a/clang/include/clang/AST/DeclarationName.h +++ b/clang/include/clang/AST/DeclarationName.h @@ -101,7 +101,7 @@ private: /// CXXSpecialName, returns a pointer to it. Otherwise, returns /// a NULL pointer. CXXSpecialName *getAsCXXSpecialName() const { - if (getNameKind() >= CXXConstructorName && + if (getNameKind() >= CXXConstructorName && getNameKind() <= CXXConversionFunctionName) return reinterpret_cast(Ptr & ~PtrMask); return 0; @@ -116,16 +116,16 @@ private: // Construct a declaration name from the name of a C++ constructor, // destructor, or conversion function. - DeclarationName(CXXSpecialName *Name) - : Ptr(reinterpret_cast(Name)) { + DeclarationName(CXXSpecialName *Name) + : Ptr(reinterpret_cast(Name)) { assert((Ptr & PtrMask) == 0 && "Improperly aligned CXXSpecialName"); Ptr |= StoredDeclarationNameExtra; } // Construct a declaration name from the name of a C++ overloaded // operator. - DeclarationName(CXXOperatorIdName *Name) - : Ptr(reinterpret_cast(Name)) { + DeclarationName(CXXOperatorIdName *Name) + : Ptr(reinterpret_cast(Name)) { assert((Ptr & PtrMask) == 0 && "Improperly aligned CXXOperatorId"); Ptr |= StoredDeclarationNameExtra; } @@ -145,8 +145,8 @@ public: DeclarationName() : Ptr(0) { } // Construct a declaration name from an IdentifierInfo *. - DeclarationName(const IdentifierInfo *II) - : Ptr(reinterpret_cast(II)) { + DeclarationName(const IdentifierInfo *II) + : Ptr(reinterpret_cast(II)) { assert((Ptr & PtrMask) == 0 && "Improperly aligned IdentifierInfo"); } @@ -158,8 +158,8 @@ public: // operator bool() - Evaluates true when this declaration name is // non-empty. - operator bool() const { - return ((Ptr & PtrMask) != 0) || + operator bool() const { + return ((Ptr & PtrMask) != 0) || (reinterpret_cast(Ptr & ~PtrMask)); } @@ -171,10 +171,10 @@ public: bool isObjCOneArgSelector() const { return getStoredNameKind() == StoredObjCOneArgSelector; } - + /// getNameKind - Determine what kind of name this is. NameKind getNameKind() const; - + /// getName - Retrieve the human-readable string for this name. std::string getAsString() const; @@ -182,7 +182,7 @@ public: /// getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in /// this declaration name, or NULL if this declaration name isn't a /// simple identifier. - IdentifierInfo *getAsIdentifierInfo() const { + IdentifierInfo *getAsIdentifierInfo() const { if (isIdentifier()) return reinterpret_cast(Ptr); return 0; @@ -201,7 +201,7 @@ public: N.Ptr = P; return N; } - + /// getCXXNameType - If this name is one of the C++ names (of a /// constructor, destructor, or conversion function), return the /// type associated with that name. @@ -310,13 +310,13 @@ public: /// getCXXSpecialName - Returns a declaration name for special kind /// of C++ name, e.g., for a constructor, destructor, or conversion /// function. - DeclarationName getCXXSpecialName(DeclarationName::NameKind Kind, + DeclarationName getCXXSpecialName(DeclarationName::NameKind Kind, CanQualType Ty); /// getCXXOperatorName - Get the name of the overloadable C++ /// operator corresponding to Op. DeclarationName getCXXOperatorName(OverloadedOperatorKind Op); -}; +}; /// Insertion operator for diagnostics. This allows sending DeclarationName's /// into a diagnostic with <<. @@ -326,8 +326,8 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, Diagnostic::ak_declarationname); return DB; } - - + + } // end namespace clang namespace llvm { @@ -345,7 +345,7 @@ struct DenseMapInfo { static unsigned getHashValue(clang::DeclarationName); - static inline bool + static inline bool isEqual(clang::DeclarationName LHS, clang::DeclarationName RHS) { return LHS == RHS; } diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h index 9c376c50a39804f1345737dcd904e818e2a5070f..604765f66d7d8a674f6073bc7d4cb83856da5c0a 100644 --- a/clang/include/clang/AST/Expr.h +++ b/clang/include/clang/AST/Expr.h @@ -42,20 +42,20 @@ class Expr : public Stmt { QualType TR; protected: - /// TypeDependent - Whether this expression is type-dependent + /// TypeDependent - Whether this expression is type-dependent /// (C++ [temp.dep.expr]). bool TypeDependent : 1; - /// ValueDependent - Whether this expression is value-dependent + /// ValueDependent - Whether this expression is value-dependent /// (C++ [temp.dep.constexpr]). bool ValueDependent : 1; // FIXME: Eventually, this constructor should go away and we should // require every subclass to provide type/value-dependence // information. - Expr(StmtClass SC, QualType T) + Expr(StmtClass SC, QualType T) : Stmt(SC), TypeDependent(false), ValueDependent(false) { - setType(T); + setType(T); } Expr(StmtClass SC, QualType T, bool TD, bool VD) @@ -66,7 +66,7 @@ protected: /// \brief Construct an empty expression. explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { } -public: +public: /// \brief Increases the reference count for this expression. /// /// Invoke the Retain() operation when this expression @@ -75,9 +75,9 @@ public: Stmt::Retain(); return this; } - + QualType getType() const { return TR; } - void setType(QualType t) { + void setType(QualType t) { // In C++, the type of an expression is always adjusted so that it // will not have reference type an expression will never have // reference type (C++ [expr]p6). Use @@ -85,16 +85,16 @@ public: // type. Additionally, inspect Expr::isLvalue to determine whether // an expression that is adjusted in this manner should be // considered an lvalue. - assert((TR.isNull() || !TR->isReferenceType()) && + assert((TR.isNull() || !TR->isReferenceType()) && "Expressions can't have reference type"); - TR = t; + TR = t; } /// isValueDependent - Determines whether this expression is /// value-dependent (C++ [temp.dep.constexpr]). For example, the /// array bound of "Chars" in the following example is - /// value-dependent. + /// value-dependent. /// @code /// template struct meta_string; /// @endcode @@ -109,7 +109,7 @@ public: /// example, the expressions "x" and "x + y" are type-dependent in /// the following code, but "y" is not type-dependent: /// @code - /// template + /// template /// void add(T x, int y) { /// x + y; /// } @@ -127,14 +127,14 @@ public: /// getExprLoc - Return the preferred location for the arrow when diagnosing /// a problem with a generic expression. virtual SourceLocation getExprLoc() const { return getLocStart(); } - + /// isUnusedResultAWarning - Return true if this immediate expression should /// 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 isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, SourceRange &R2) const; - + /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or /// incomplete type other than void. Nonarray expressions that can be lvalues: /// - name, where name must be a variable @@ -159,10 +159,10 @@ public: // Same as above, but excluding checks for non-object and void types in C isLvalueResult isLvalueInternal(ASTContext &Ctx) const; - + /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, /// does not have an incomplete type, does not have a const-qualified type, - /// and if it is a structure or union, does not have any member (including, + /// and if it is a structure or union, does not have any member (including, /// recursively, any member or element of all contained aggregates or unions) /// with a const-qualified type. /// @@ -186,7 +186,7 @@ public: }; isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = 0) const; - + /// \brief If this expression refers to a bit-field, retrieve the /// declaration of that bit-field. FieldDecl *getBitField(); @@ -194,7 +194,7 @@ public: const FieldDecl *getBitField() const { return const_cast(this)->getBitField(); } - + /// isIntegerConstantExpr - Return true if this expression is a valid integer /// constant expression, and, if so, return its value in Result. If not a /// valid i-c-e, return false and fill in Loc (if specified) with the location @@ -209,16 +209,16 @@ public: /// isConstantInitializer - Returns true if this expression is a constant /// initializer, which can be emitted at compile-time. bool isConstantInitializer(ASTContext &Ctx) const; - + /// EvalResult is a struct with detailed info about an evaluated expression. struct EvalResult { /// Val - This is the value the expression can be folded to. APValue Val; - + /// HasSideEffects - Whether the evaluated expression has side effects. /// For example, (f() && 0) can be folded, but it still has side effects. bool HasSideEffects; - + /// Diag - If the expression is unfoldable, then Diag contains a note /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret /// position for the error, and DiagExpr is the expression that caused @@ -230,7 +230,7 @@ public: unsigned Diag; const Expr *DiagExpr; SourceLocation DiagLoc; - + EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {} }; @@ -257,11 +257,11 @@ public: bool isNullPointerConstant(ASTContext &Ctx) const; /// isOBJCGCCandidate - Return true if this expression may be used in a read/ - /// write barrier. + /// write barrier. bool isOBJCGCCandidate(ASTContext &Ctx) const; - + /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return - /// its subexpression. If that subexpression is also a ParenExpr, + /// its subexpression. If that subexpression is also a ParenExpr, /// then this method recursively returns its subexpression, and so forth. /// Otherwise, the method returns the current Expr. Expr* IgnoreParens(); @@ -269,12 +269,12 @@ public: /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr /// or CastExprs, returning their operand. Expr *IgnoreParenCasts(); - + /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the /// value (including ptr->int casts of the same size). Strip off any /// ParenExpr or CastExprs, returning their operand. Expr *IgnoreParenNoopCasts(ASTContext &Ctx); - + const Expr* IgnoreParens() const { return const_cast(this)->IgnoreParens(); } @@ -284,18 +284,18 @@ public: const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const { return const_cast(this)->IgnoreParenNoopCasts(Ctx); } - + static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs); static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs); - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() >= firstExprConstant && - T->getStmtClass() <= lastExprConstant; + T->getStmtClass() <= lastExprConstant; } static bool classof(const Expr *) { return true; } }; - + //===----------------------------------------------------------------------===// // Primary Expressions. //===----------------------------------------------------------------------===// @@ -303,7 +303,7 @@ public: /// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function, /// enum, etc. class DeclRefExpr : public Expr { - NamedDecl *D; + NamedDecl *D; SourceLocation Loc; protected: @@ -319,14 +319,14 @@ protected: public: // FIXME: Eventually, this constructor will go away and all clients // will have to provide the type- and value-dependent flags. - DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) : + DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) : Expr(DeclRefExprClass, t), D(d), Loc(l) {} - DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD) : + DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD) : Expr(DeclRefExprClass, t, TD, VD), D(d), Loc(l) {} - + /// \brief Construct an empty declaration reference expression. - explicit DeclRefExpr(EmptyShell Empty) + explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) { } NamedDecl *getDecl() { return D; } @@ -336,14 +336,14 @@ public: SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == DeclRefExprClass || T->getStmtClass() == CXXConditionDeclExprClass || - T->getStmtClass() == QualifiedDeclRefExprClass; + T->getStmtClass() == QualifiedDeclRefExprClass; } static bool classof(const DeclRefExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -357,16 +357,16 @@ public: Function, PrettyFunction }; - + private: SourceLocation Loc; IdentType Type; public: - PredefinedExpr(SourceLocation l, QualType type, IdentType IT) + PredefinedExpr(SourceLocation l, QualType type, IdentType IT) : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {} - + /// \brief Construct an empty predefined expression. - explicit PredefinedExpr(EmptyShell Empty) + explicit PredefinedExpr(EmptyShell Empty) : Expr(PredefinedExprClass, Empty) { } IdentType getIdentType() const { return Type; } @@ -380,11 +380,11 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == PredefinedExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == PredefinedExprClass; } static bool classof(const PredefinedExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -394,7 +394,7 @@ class IntegerLiteral : public Expr { llvm::APInt Value; SourceLocation Loc; public: - // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, + // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, // or UnsignedLongLongTy IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l) : Expr(IntegerLiteralClass, type), Value(V), Loc(l) { @@ -402,7 +402,7 @@ public: } /// \brief Construct an empty integer literal. - explicit IntegerLiteral(EmptyShell Empty) + explicit IntegerLiteral(EmptyShell Empty) : Expr(IntegerLiteralClass, Empty) { } const llvm::APInt &getValue() const { return Value; } @@ -414,11 +414,11 @@ public: void setValue(const llvm::APInt &Val) { Value = Val; } void setLocation(SourceLocation Location) { Loc = Location; } - static bool classof(const Stmt *T) { - return T->getStmtClass() == IntegerLiteralClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == IntegerLiteralClass; } static bool classof(const IntegerLiteral *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -439,17 +439,17 @@ public: SourceLocation getLocation() const { return Loc; } bool isWide() const { return IsWide; } - + virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - + unsigned getValue() const { return Value; } void setLocation(SourceLocation Location) { Loc = Location; } void setWide(bool W) { IsWide = W; } void setValue(unsigned Val) { Value = Val; } - static bool classof(const Stmt *T) { - return T->getStmtClass() == CharacterLiteralClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == CharacterLiteralClass; } static bool classof(const CharacterLiteral *) { return true; } @@ -463,12 +463,12 @@ class FloatingLiteral : public Expr { bool IsExact : 1; SourceLocation Loc; public: - FloatingLiteral(const llvm::APFloat &V, bool isexact, + FloatingLiteral(const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L) - : Expr(FloatingLiteralClass, Type), Value(V), IsExact(isexact), Loc(L) {} + : Expr(FloatingLiteralClass, Type), Value(V), IsExact(isexact), Loc(L) {} /// \brief Construct an empty floating-point literal. - explicit FloatingLiteral(EmptyShell Empty) + explicit FloatingLiteral(EmptyShell Empty) : Expr(FloatingLiteralClass, Empty), Value(0.0) { } const llvm::APFloat &getValue() const { return Value; } @@ -481,7 +481,7 @@ public: /// double. Note that this may cause loss of precision, but is useful for /// debugging dumps, etc. double getValueAsApproximateDouble() const; - + SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } @@ -489,14 +489,14 @@ public: // into a method here that takes the inner-most code decl (a block, function // or objc method) that the expr lives in. This would allow sema and codegen // to be consistent for things like sizeof(__func__) etc. - + virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == FloatingLiteralClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == FloatingLiteralClass; } static bool classof(const FloatingLiteral *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -512,9 +512,9 @@ class ImaginaryLiteral : public Expr { public: ImaginaryLiteral(Expr *val, QualType Ty) : Expr(ImaginaryLiteralClass, Ty), Val(val) {} - + /// \brief Build an empty imaginary literal. - explicit ImaginaryLiteral(EmptyShell Empty) + explicit ImaginaryLiteral(EmptyShell Empty) : Expr(ImaginaryLiteralClass, Empty) { } const Expr *getSubExpr() const { return cast(Val); } @@ -522,11 +522,11 @@ public: void setSubExpr(Expr *E) { Val = E; } virtual SourceRange getSourceRange() const { return Val->getSourceRange(); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ImaginaryLiteralClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ImaginaryLiteralClass; } static bool classof(const ImaginaryLiteral *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -556,7 +556,7 @@ class StringLiteral : public Expr { SourceLocation TokLocs[1]; StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty) {} - + protected: virtual void DoDestroy(ASTContext &C); @@ -568,7 +568,7 @@ public: const SourceLocation *Loc, unsigned NumStrs); /// Simple constructor for string literals made from one token. - static StringLiteral *Create(ASTContext &C, const char *StrData, + static StringLiteral *Create(ASTContext &C, const char *StrData, unsigned ByteLength, bool Wide, QualType Ty, SourceLocation Loc) { return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1); @@ -595,12 +595,12 @@ public: /// getNumConcatenated - Get the number of string literal tokens that were /// concatenated in translation phase #6 to form this string literal. unsigned getNumConcatenated() const { return NumConcatenated; } - + SourceLocation getStrTokenLoc(unsigned TokNum) const { assert(TokNum < NumConcatenated && "Invalid tok number"); return TokLocs[TokNum]; } - void setStrTokenLoc(unsigned TokNum, SourceLocation L) { + void setStrTokenLoc(unsigned TokNum, SourceLocation L) { assert(TokNum < NumConcatenated && "Invalid tok number"); TokLocs[TokNum] = L; } @@ -609,14 +609,14 @@ public: tokloc_iterator tokloc_begin() const { return TokLocs; } tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; } - virtual SourceRange getSourceRange() const { - return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]); + virtual SourceRange getSourceRange() const { + return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == StringLiteralClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == StringLiteralClass; } static bool classof(const StringLiteral *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -630,11 +630,11 @@ class ParenExpr : public Expr { public: ParenExpr(SourceLocation l, SourceLocation r, Expr *val) : Expr(ParenExprClass, val->getType(), - val->isTypeDependent(), val->isValueDependent()), + val->isTypeDependent(), val->isValueDependent()), L(l), R(r), Val(val) {} - + /// \brief Construct an empty parenthesized expression. - explicit ParenExpr(EmptyShell Empty) + explicit ParenExpr(EmptyShell Empty) : Expr(ParenExprClass, Empty) { } const Expr *getSubExpr() const { return cast(Val); } @@ -651,11 +651,11 @@ public: SourceLocation getRParen() const { return R; } void setRParen(SourceLocation Loc) { R = Loc; } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ParenExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ParenExprClass; } static bool classof(const ParenExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -673,7 +673,7 @@ public: /// later returns zero in the type of the operand. /// /// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose -/// subexpression is a compound literal with the various MemberExpr and +/// subexpression is a compound literal with the various MemberExpr and /// ArraySubscriptExpr's applied to it. /// class UnaryOperator : public Expr { @@ -693,16 +693,16 @@ private: Stmt *Val; Opcode Opc; SourceLocation Loc; -public: +public: UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l) : Expr(UnaryOperatorClass, type, input->isTypeDependent() && opc != OffsetOf, - input->isValueDependent()), + input->isValueDependent()), Val(input), Opc(opc), Loc(l) {} /// \brief Build an empty unary operator. - explicit UnaryOperator(EmptyShell Empty) + explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty), Opc(AddrOf) { } Opcode getOpcode() const { return Opc; } @@ -731,8 +731,8 @@ public: bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; } bool isOffsetOfOp() const { return Opc == OffsetOf; } static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; } - bool isArithmeticOp() const { return isArithmeticOp(Opc); } - + bool isArithmeticOp() const { return isArithmeticOp(Opc); } + /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "sizeof" or "[pre]++" static const char *getOpcodeStr(Opcode Op); @@ -752,12 +752,12 @@ public: return SourceRange(Loc, Val->getLocEnd()); } virtual SourceLocation getExprLoc() const { return Loc; } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == UnaryOperatorClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == UnaryOperatorClass; } static bool classof(const UnaryOperator *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -778,7 +778,7 @@ protected: virtual void DoDestroy(ASTContext& C); public: - SizeOfAlignOfExpr(bool issizeof, QualType T, + SizeOfAlignOfExpr(bool issizeof, QualType T, QualType resultType, SourceLocation op, SourceLocation rp) : Expr(SizeOfAlignOfExprClass, resultType, @@ -789,7 +789,7 @@ public: Argument.Ty = T.getAsOpaquePtr(); } - SizeOfAlignOfExpr(bool issizeof, Expr *E, + SizeOfAlignOfExpr(bool issizeof, Expr *E, QualType resultType, SourceLocation op, SourceLocation rp) : Expr(SizeOfAlignOfExprClass, resultType, @@ -821,9 +821,9 @@ public: } void setArgument(Expr *E) { Argument.Ex = E; isType = false; } - void setArgument(QualType T) { - Argument.Ty = T.getAsOpaquePtr(); - isType = true; + void setArgument(QualType T) { + Argument.Ty = T.getAsOpaquePtr(); + isType = true; } /// Gets the argument type, or the type of the argument expression, whichever @@ -842,11 +842,11 @@ public: return SourceRange(OpLoc, RParenLoc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == SizeOfAlignOfExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == SizeOfAlignOfExprClass; } static bool classof(const SizeOfAlignOfExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -859,7 +859,7 @@ public: /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. class ArraySubscriptExpr : public Expr { enum { LHS, RHS, END_EXPR=2 }; - Stmt* SubExprs[END_EXPR]; + Stmt* SubExprs[END_EXPR]; SourceLocation RBracketLoc; public: ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, @@ -871,7 +871,7 @@ public: SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; } - + /// \brief Create an empty array subscript expression. explicit ArraySubscriptExpr(EmptyShell Shell) : Expr(ArraySubscriptExprClass, Shell) { } @@ -892,37 +892,37 @@ public: Expr *getRHS() { return cast(SubExprs[RHS]); } const Expr *getRHS() const { return cast(SubExprs[RHS]); } void setRHS(Expr *E) { SubExprs[RHS] = E; } - - Expr *getBase() { + + Expr *getBase() { return cast(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); } - - const Expr *getBase() const { + + const Expr *getBase() const { return cast(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); } - - Expr *getIdx() { + + Expr *getIdx() { return cast(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); } - + const Expr *getIdx() const { return cast(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); - } - - virtual SourceRange getSourceRange() const { + } + + virtual SourceRange getSourceRange() const { return SourceRange(getLHS()->getLocStart(), RBracketLoc); } - + SourceLocation getRBracketLoc() const { return RBracketLoc; } void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ArraySubscriptExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ArraySubscriptExprClass; } static bool classof(const ArraySubscriptExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -930,9 +930,9 @@ public: /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). -/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", +/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", /// while its subclasses may represent alternative syntax that (semantically) -/// results in a function call. For example, CXXOperatorCallExpr is +/// results in a function call. For example, CXXOperatorCallExpr is /// a subclass for overloaded operator calls that use operator syntax, e.g., /// "str1 + str2" to resolve to a function call. class CallExpr : public Expr { @@ -940,23 +940,23 @@ class CallExpr : public Expr { Stmt **SubExprs; unsigned NumArgs; SourceLocation RParenLoc; - + protected: // This version of the constructor is for derived classes. CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation rparenloc); virtual void DoDestroy(ASTContext& C); - + public: - CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, + CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation rparenloc); - + /// \brief Build an empty call expression. CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty); ~CallExpr() {} - + const Expr *getCallee() const { return cast(SubExprs[FN]); } Expr *getCallee() { return cast(SubExprs[FN]); } void setCallee(Expr *F) { SubExprs[FN] = F; } @@ -967,7 +967,7 @@ public: /// getNumArgs - Return the number of actual arguments to this call. /// unsigned getNumArgs() const { return NumArgs; } - + /// getArg - Return the specified argument. Expr *getArg(unsigned Arg) { assert(Arg < NumArgs && "Arg access out of range!"); @@ -977,26 +977,26 @@ public: assert(Arg < NumArgs && "Arg access out of range!"); return cast(SubExprs[Arg+ARGS_START]); } - + /// setArg - Set the specified argument. void setArg(unsigned Arg, Expr *ArgExpr) { assert(Arg < NumArgs && "Arg access out of range!"); SubExprs[Arg+ARGS_START] = ArgExpr; } - + /// setNumArgs - This changes the number of arguments present in this call. /// Any orphaned expressions are deleted by this, and any new operands are set /// to null. void setNumArgs(ASTContext& C, unsigned NumArgs); - + typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; - + arg_iterator arg_begin() { return SubExprs+ARGS_START; } arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); } const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; } const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();} - + /// getNumCommas - Return the number of commas that must have been present in /// this function call. unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } @@ -1004,23 +1004,23 @@ public: /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If /// not, return 0. unsigned isBuiltinCall(ASTContext &Context) const; - - /// getCallReturnType - Get the return type of the call expr. This is not - /// always the type of the expr itself, if the return type is a reference + + /// getCallReturnType - Get the return type of the call expr. This is not + /// always the type of the expr itself, if the return type is a reference /// type. QualType getCallReturnType() const; - + SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } - virtual SourceRange getSourceRange() const { + virtual SourceRange getSourceRange() const { return SourceRange(getCallee()->getLocStart(), RParenLoc); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == CallExprClass || T->getStmtClass() == CXXOperatorCallExprClass || - T->getStmtClass() == CXXMemberCallExprClass; + T->getStmtClass() == CXXMemberCallExprClass; } static bool classof(const CallExpr *) { return true; } static bool classof(const CXXOperatorCallExpr *) { return true; } @@ -1031,75 +1031,75 @@ public: virtual child_iterator child_end(); }; -/// \brief Represents the qualifier that may precede a C++ name, e.g., the +/// \brief Represents the qualifier that may precede a C++ name, e.g., the /// "std::" in "std::sort". struct NameQualifier { /// \brief The nested name specifier. NestedNameSpecifier *NNS; - + /// \brief The source range covered by the nested name specifier. SourceRange Range; }; /// \brief Represents an explicit template argument list in C++, e.g., -/// the "" in "sort". +/// the "" in "sort". struct ExplicitTemplateArgumentList { /// \brief The source location of the left angle bracket ('<'); SourceLocation LAngleLoc; - + /// \brief The source location of the right angle bracket ('>'); SourceLocation RAngleLoc; - + /// \brief The number of template arguments in TemplateArgs. - /// The actual template arguments (if any) are stored after the + /// The actual template arguments (if any) are stored after the /// ExplicitTemplateArgumentList structure. unsigned NumTemplateArgs; - + /// \brief Retrieve the template arguments - TemplateArgument *getTemplateArgs() { - return reinterpret_cast (this + 1); + TemplateArgument *getTemplateArgs() { + return reinterpret_cast (this + 1); } /// \brief Retrieve the template arguments const TemplateArgument *getTemplateArgs() const { - return reinterpret_cast (this + 1); + return reinterpret_cast (this + 1); } }; - + /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. /// class MemberExpr : public Expr { /// Base - the expression for the base pointer or structure references. In /// X.F, this is "X". Stmt *Base; - + /// MemberDecl - This is the decl being referenced by the field/member name. /// In X.F, this is the decl referenced by F. NamedDecl *MemberDecl; - + /// MemberLoc - This is the location of the member name. SourceLocation MemberLoc; - + /// IsArrow - True if this is "X->F", false if this is "X.F". bool IsArrow : 1; - + /// \brief True if this member expression used a nested-name-specifier to - /// refer to the member, e.g., "x->Base::f". When true, a NameQualifier + /// refer to the member, e.g., "x->Base::f". When true, a NameQualifier /// structure is allocated immediately after the MemberExpr. bool HasQualifier : 1; - + /// \brief True if this member expression specified a template argument list /// explicitly, e.g., x->f. When true, an ExplicitTemplateArgumentList /// structure (and its TemplateArguments) are allocated immediately after /// the MemberExpr or, if the member expression also has a qualifier, after /// the NameQualifier structure. bool HasExplicitTemplateArgumentList : 1; - + /// \brief Retrieve the qualifier that preceded the member name, if any. NameQualifier *getMemberQualifier() { if (!HasQualifier) return 0; - + return reinterpret_cast (this + 1); } @@ -1107,48 +1107,48 @@ class MemberExpr : public Expr { const NameQualifier *getMemberQualifier() const { return const_cast(this)->getMemberQualifier(); } - + /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() { if (!HasExplicitTemplateArgumentList) return 0; - + if (!HasQualifier) return reinterpret_cast(this + 1); - + return reinterpret_cast( getMemberQualifier() + 1); } - + /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const { return const_cast(this)->getExplicitTemplateArgumentList(); } - - MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual, + + MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual, SourceRange qualrange, NamedDecl *memberdecl, SourceLocation l, - bool has_explicit, SourceLocation langle, - const TemplateArgument *targs, unsigned numtargs, - SourceLocation rangle, QualType ty); + bool has_explicit, SourceLocation langle, + const TemplateArgument *targs, unsigned numtargs, + SourceLocation rangle, QualType ty); public: MemberExpr(Expr *base, bool isarrow, NamedDecl *memberdecl, SourceLocation l, - QualType ty) - : Expr(MemberExprClass, ty, + QualType ty) + : Expr(MemberExprClass, ty, base->isTypeDependent(), base->isValueDependent()), Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow), HasQualifier(false), HasExplicitTemplateArgumentList(false) {} /// \brief Build an empty member reference expression. - explicit MemberExpr(EmptyShell Empty) - : Expr(MemberExprClass, Empty), HasQualifier(false), + explicit MemberExpr(EmptyShell Empty) + : Expr(MemberExprClass, Empty), HasQualifier(false), HasExplicitTemplateArgumentList(false) { } - static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow, + static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow, NestedNameSpecifier *qual, SourceRange qualrange, - NamedDecl *memberdecl, + NamedDecl *memberdecl, SourceLocation l, bool has_explicit, SourceLocation langle, @@ -1156,7 +1156,7 @@ public: unsigned numtargs, SourceLocation rangle, QualType ty); - + void setBase(Expr *E) { Base = E; } Expr *getBase() const { return cast(Base); } @@ -1167,73 +1167,73 @@ public: NamedDecl *getMemberDecl() const { return MemberDecl; } void setMemberDecl(NamedDecl *D) { MemberDecl = D; } - /// \brief Determines whether this member expression actually had + /// \brief Determines whether this member expression actually had /// a C++ nested-name-specifier prior to the name of the member, e.g., /// x->Base::foo. bool hasQualifier() const { return HasQualifier; } - + /// \brief If the member name was qualified, retrieves the source range of /// the nested-name-specifier that precedes the member name. Otherwise, /// returns an empty source range. - SourceRange getQualifierRange() const { + SourceRange getQualifierRange() const { if (!HasQualifier) return SourceRange(); - + return getMemberQualifier()->Range; } - - /// \brief If the member name was qualified, retrieves the + + /// \brief If the member name was qualified, retrieves the /// nested-name-specifier that precedes the member name. Otherwise, returns /// NULL. - NestedNameSpecifier *getQualifier() const { + NestedNameSpecifier *getQualifier() const { if (!HasQualifier) return 0; - + return getMemberQualifier()->NNS; } /// \brief Determines whether this member expression actually had a C++ /// template argument list explicitly specified, e.g., x.f. - bool hasExplicitTemplateArgumentList() { - return HasExplicitTemplateArgumentList; + bool hasExplicitTemplateArgumentList() { + return HasExplicitTemplateArgumentList; } - - /// \brief Retrieve the location of the left angle bracket following the + + /// \brief Retrieve the location of the left angle bracket following the /// member name ('<'), if any. - SourceLocation getLAngleLoc() const { + SourceLocation getLAngleLoc() const { if (!HasExplicitTemplateArgumentList) return SourceLocation(); - + return getExplicitTemplateArgumentList()->LAngleLoc; } - + /// \brief Retrieve the template arguments provided as part of this /// template-id. - const TemplateArgument *getTemplateArgs() const { + const TemplateArgument *getTemplateArgs() const { if (!HasExplicitTemplateArgumentList) - return 0; - + return 0; + return getExplicitTemplateArgumentList()->getTemplateArgs(); } - + /// \brief Retrieve the number of template arguments provided as part of this /// template-id. - unsigned getNumTemplateArgs() const { + unsigned getNumTemplateArgs() const { if (!HasExplicitTemplateArgumentList) - return 0; - + return 0; + return getExplicitTemplateArgumentList()->NumTemplateArgs; } - - /// \brief Retrieve the location of the right angle bracket following the + + /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). - SourceLocation getRAngleLoc() const { + SourceLocation getRAngleLoc() const { if (!HasExplicitTemplateArgumentList) return SourceLocation(); - + return getExplicitTemplateArgumentList()->RAngleLoc; } - + bool isArrow() const { return IsArrow; } void setArrow(bool A) { IsArrow = A; } @@ -1248,26 +1248,26 @@ public: SourceLocation EndLoc = MemberLoc; if (HasExplicitTemplateArgumentList) EndLoc = getRAngleLoc(); - + SourceLocation BaseLoc = getBase()->getLocStart(); if (BaseLoc.isInvalid()) return SourceRange(MemberLoc, EndLoc); return SourceRange(BaseLoc, EndLoc); } - + virtual SourceLocation getExprLoc() const { return MemberLoc; } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == MemberExprClass; } static bool classof(const MemberExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; -/// CompoundLiteralExpr - [C99 6.5.2.5] +/// CompoundLiteralExpr - [C99 6.5.2.5] /// class CompoundLiteralExpr : public Expr { /// LParenLoc - If non-null, this is the location of the left paren in a @@ -1281,7 +1281,7 @@ public: bool fileScope) : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init), FileScope(fileScope) {} - + /// \brief Construct an empty compound literal. explicit CompoundLiteralExpr(EmptyShell Empty) : Expr(CompoundLiteralExprClass, Empty) { } @@ -1305,11 +1305,11 @@ public: return SourceRange(LParenLoc, Init->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == CompoundLiteralExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == CompoundLiteralExprClass; } static bool classof(const CompoundLiteralExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1324,74 +1324,74 @@ public: /// CastKind - the kind of cast this represents. enum CastKind { /// CK_Unknown - Unknown cast kind. - /// FIXME: The goal is to get rid of this and make all casts have a + /// FIXME: The goal is to get rid of this and make all casts have a /// kind so that the AST client doesn't have to try to figure out what's /// going on. CK_Unknown, - + /// CK_BitCast - Used for reinterpret_cast. CK_BitCast, - + /// CK_NoOp - Used for const_cast. CK_NoOp, - + /// CK_DerivedToBase - Derived to base class casts. CK_DerivedToBase, - + /// CK_Dynamic - Dynamic cast. CK_Dynamic, - + /// CK_ToUnion - Cast to union (GCC extension). CK_ToUnion, - + /// CK_ArrayToPointerDecay - Array to pointer decay. CK_ArrayToPointerDecay, - + // CK_FunctionToPointerDecay - Function to pointer decay. CK_FunctionToPointerDecay, - + /// CK_NullToMemberPointer - Null pointer to member pointer. CK_NullToMemberPointer, - + /// CK_BaseToDerivedMemberPointer - Member pointer in base class to /// member pointer in derived class. CK_BaseToDerivedMemberPointer, - /// CK_UserDefinedConversion - Conversion using a user defined type + /// CK_UserDefinedConversion - Conversion using a user defined type /// conversion function. CK_UserDefinedConversion, /// CK_ConstructorConversion - Conversion by constructor CK_ConstructorConversion }; - + struct CastInfo { const CastKind Kind; - + // FIXME: This should assert that the CastKind does not require extra // information. CastInfo(CastKind Kind) : Kind(Kind) { } }; - + private: CastKind Kind; Stmt *Op; protected: - CastExpr(StmtClass SC, QualType ty, const CastInfo &info, Expr *op) : + CastExpr(StmtClass SC, QualType ty, const CastInfo &info, Expr *op) : Expr(SC, ty, // Cast expressions are type-dependent if the type is // dependent (C++ [temp.dep.expr]p3). ty->isDependentType(), // Cast expressions are value-dependent if the type is // dependent or if the subexpression is value-dependent. - ty->isDependentType() || (op && op->isValueDependent())), + ty->isDependentType() || (op && op->isValueDependent())), Kind(info.Kind), Op(op) {} - + /// \brief Construct an empty cast. - CastExpr(StmtClass SC, EmptyShell Empty) + CastExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { } - + public: CastKind getCastKind() const { return Kind; } void setCastKind(CastKind K) { Kind = K; } @@ -1401,7 +1401,7 @@ public: const Expr *getSubExpr() const { return cast(Op); } void setSubExpr(Expr *E) { Op = E; } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { StmtClass SC = T->getStmtClass(); if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass) return true; @@ -1412,7 +1412,7 @@ public: return false; } static bool classof(const CastExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1430,7 +1430,7 @@ public: /// @code /// class Base { }; /// class Derived : public Base { }; -/// void f(Derived d) { +/// void f(Derived d) { /// Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base /// } /// @endcode @@ -1439,11 +1439,11 @@ class ImplicitCastExpr : public CastExpr { bool LvalueCast; public: - ImplicitCastExpr(QualType ty, const CastInfo &info, Expr *op, bool Lvalue) : + ImplicitCastExpr(QualType ty, const CastInfo &info, Expr *op, bool Lvalue) : CastExpr(ImplicitCastExprClass, ty, info, op), LvalueCast(Lvalue) { } /// \brief Construct an empty implicit cast. - explicit ImplicitCastExpr(EmptyShell Shell) + explicit ImplicitCastExpr(EmptyShell Shell) : CastExpr(ImplicitCastExprClass, Shell) { } @@ -1457,14 +1457,14 @@ public: /// setLvalueCast - Set whether this cast produces an lvalue. void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ImplicitCastExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ImplicitCastExprClass; } static bool classof(const ImplicitCastExpr *) { return true; } }; /// ExplicitCastExpr - An explicit cast written in the source -/// code. +/// code. /// /// This class is effectively an abstract class, because it provides /// the basic representation of an explicitly-written cast without @@ -1486,11 +1486,11 @@ class ExplicitCastExpr : public CastExpr { protected: ExplicitCastExpr(StmtClass SC, QualType exprTy, const CastInfo &info, - Expr *op, QualType writtenTy) + Expr *op, QualType writtenTy) : CastExpr(SC, exprTy, info, op), TypeAsWritten(writtenTy) {} /// \brief Construct an empty explicit cast. - ExplicitCastExpr(StmtClass SC, EmptyShell Shell) + ExplicitCastExpr(StmtClass SC, EmptyShell Shell) : CastExpr(SC, Shell) { } public: @@ -1499,7 +1499,7 @@ public: QualType getTypeAsWritten() const { return TypeAsWritten; } void setTypeAsWritten(QualType T) { TypeAsWritten = T; } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { StmtClass SC = T->getStmtClass(); if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass) return true; @@ -1518,13 +1518,13 @@ class CStyleCastExpr : public ExplicitCastExpr { SourceLocation LPLoc; // the location of the left paren SourceLocation RPLoc; // the location of the right paren public: - CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op, QualType writtenTy, - SourceLocation l, SourceLocation r) : - ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, writtenTy), + CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op, QualType writtenTy, + SourceLocation l, SourceLocation r) : + ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, writtenTy), LPLoc(l), RPLoc(r) {} /// \brief Construct an empty C-style explicit cast. - explicit CStyleCastExpr(EmptyShell Shell) + explicit CStyleCastExpr(EmptyShell Shell) : ExplicitCastExpr(CStyleCastExprClass, Shell) { } SourceLocation getLParenLoc() const { return LPLoc; } @@ -1536,8 +1536,8 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == CStyleCastExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == CStyleCastExprClass; } static bool classof(const CStyleCastExpr *) { return true; } }; @@ -1589,22 +1589,22 @@ private: Stmt* SubExprs[END_EXPR]; Opcode Opc; SourceLocation OpLoc; -public: - +public: + BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, SourceLocation opLoc) : Expr(BinaryOperatorClass, ResTy, lhs->isTypeDependent() || rhs->isTypeDependent(), - lhs->isValueDependent() || rhs->isValueDependent()), + lhs->isValueDependent() || rhs->isValueDependent()), Opc(opc), OpLoc(opLoc) { SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; - assert(!isCompoundAssignmentOp() && + assert(!isCompoundAssignmentOp() && "Use ArithAssignBinaryOperator for compound assignments"); } /// \brief Construct an empty binary operator. - explicit BinaryOperator(EmptyShell Empty) + explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty), Opc(Comma) { } SourceLocation getOperatorLoc() const { return OpLoc; } @@ -1621,7 +1621,7 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd()); } - + /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "<<=". static const char *getOpcodeStr(Opcode Op); @@ -1643,19 +1643,19 @@ public: static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; } bool isRelationalOp() const { return isRelationalOp(Opc); } - static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; } + static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; } bool isEqualityOp() const { return isEqualityOp(Opc); } - + static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; } bool isLogicalOp() const { return isLogicalOp(Opc); } bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; } bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;} bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; } - - static bool classof(const Stmt *S) { + + static bool classof(const Stmt *S) { return S->getStmtClass() == BinaryOperatorClass || - S->getStmtClass() == CompoundAssignOperatorClass; + S->getStmtClass() == CompoundAssignOperatorClass; } static bool classof(const BinaryOperator *) { return true; } @@ -1671,7 +1671,7 @@ protected: SubExprs[RHS] = rhs; } - BinaryOperator(StmtClass SC, EmptyShell Empty) + BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty), Opc(MulAssign) { } }; @@ -1692,7 +1692,7 @@ public: : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true), ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) { - assert(isCompoundAssignmentOp() && + assert(isCompoundAssignmentOp() && "Only should be used for compound assignments"); } @@ -1710,8 +1710,8 @@ public: void setComputationResultType(QualType T) { ComputationResultType = T; } static bool classof(const CompoundAssignOperator *) { return true; } - static bool classof(const Stmt *S) { - return S->getStmtClass() == CompoundAssignOperatorClass; + static bool classof(const Stmt *S) { + return S->getStmtClass() == CompoundAssignOperatorClass; } }; @@ -1730,7 +1730,7 @@ public: // depend on the type of the conditional, but the standard // seems to imply that it could. File a bug! ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())), - (cond->isValueDependent() || + (cond->isValueDependent() || (lhs && lhs->isValueDependent()) || (rhs && rhs->isValueDependent()))), QuestionLoc(QLoc), @@ -1754,15 +1754,15 @@ public: // will be the same as getLHS() except a GCC extension allows the left // subexpression to be omitted, and instead of the condition be returned. // e.g: x ?: y is shorthand for x ? x : y, except that the expression "x" - // is only evaluated once. + // is only evaluated once. Expr *getTrueExpr() const { return cast(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]); } - + // getTrueExpr - Return the subexpression representing the value of the ?: // expression if the condition evaluates to false. This is the same as getRHS. Expr *getFalseExpr() const { return cast(SubExprs[RHS]); } - + Expr *getLHS() const { return cast_or_null(SubExprs[LHS]); } void setLHS(Expr *E) { SubExprs[LHS] = E; } @@ -1778,11 +1778,11 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ConditionalOperatorClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ConditionalOperatorClass; } static bool classof(const ConditionalOperator *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1796,9 +1796,9 @@ public: AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L, QualType t) : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} - + /// \brief Build an empty address of a label expression. - explicit AddrLabelExpr(EmptyShell Empty) + explicit AddrLabelExpr(EmptyShell Empty) : Expr(AddrLabelExprClass, Empty) { } SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } @@ -1809,15 +1809,15 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(AmpAmpLoc, LabelLoc); } - + LabelStmt *getLabel() const { return Label; } void setLabel(LabelStmt *S) { Label = S; } static bool classof(const Stmt *T) { - return T->getStmtClass() == AddrLabelExprClass; + return T->getStmtClass() == AddrLabelExprClass; } static bool classof(const AddrLabelExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1833,7 +1833,7 @@ public: StmtExpr(CompoundStmt *substmt, QualType T, SourceLocation lp, SourceLocation rp) : Expr(StmtExprClass, T), SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } - + /// \brief Build an empty statement expression. explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } @@ -1844,17 +1844,17 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(LParenLoc, RParenLoc); } - + SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } - + static bool classof(const Stmt *T) { - return T->getStmtClass() == StmtExprClass; + return T->getStmtClass() == StmtExprClass; } static bool classof(const StmtExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1869,8 +1869,8 @@ class TypesCompatibleExpr : public Expr { QualType Type2; SourceLocation BuiltinLoc, RParenLoc; public: - TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc, - QualType t1, QualType t2, SourceLocation RP) : + TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc, + QualType t1, QualType t2, SourceLocation RP) : Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2), BuiltinLoc(BLoc), RParenLoc(RP) {} @@ -1882,21 +1882,21 @@ public: void setArgType1(QualType T) { Type1 = T; } QualType getArgType2() const { return Type2; } void setArgType2(QualType T) { Type2 = T; } - + SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } - + SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } - + virtual SourceRange getSourceRange() const { return SourceRange(BuiltinLoc, RParenLoc); } static bool classof(const Stmt *T) { - return T->getStmtClass() == TypesCompatibleExprClass; + return T->getStmtClass() == TypesCompatibleExprClass; } static bool classof(const TypesCompatibleExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1919,27 +1919,27 @@ class ShuffleVectorExpr : public Expr { unsigned NumExprs; protected: - virtual void DoDestroy(ASTContext &C); + virtual void DoDestroy(ASTContext &C); public: ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr, - QualType Type, SourceLocation BLoc, - SourceLocation RP) : + QualType Type, SourceLocation BLoc, + SourceLocation RP) : Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) { - + SubExprs = new (C) Stmt*[nexpr]; for (unsigned i = 0; i < nexpr; i++) SubExprs[i] = args[i]; } /// \brief Build an empty vector-shuffle expression. - explicit ShuffleVectorExpr(EmptyShell Empty) + explicit ShuffleVectorExpr(EmptyShell Empty) : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { } SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } - + SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } @@ -1947,17 +1947,17 @@ public: return SourceRange(BuiltinLoc, RParenLoc); } static bool classof(const Stmt *T) { - return T->getStmtClass() == ShuffleVectorExprClass; + return T->getStmtClass() == ShuffleVectorExprClass; } static bool classof(const ShuffleVectorExpr *) { return true; } - + ~ShuffleVectorExpr() {} - + /// getNumSubExprs - Return the size of the SubExprs array. This includes the /// constant expression, the actual arguments passed in, and the function /// pointers. unsigned getNumSubExprs() const { return NumExprs; } - + /// getExpr - Return the Expr at the specified index. Expr *getExpr(unsigned Index) { assert((Index < NumExprs) && "Arg access out of range!"); @@ -1967,21 +1967,21 @@ public: assert((Index < NumExprs) && "Arg access out of range!"); return cast(SubExprs[Index]); } - + void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs); unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) { assert((N < NumExprs - 2) && "Shuffle idx out of range!"); return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue(); } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. -/// This AST node is similar to the conditional operator (?:) in C, with +/// This AST node is similar to the conditional operator (?:) in C, with /// the following exceptions: /// - the test expression must be a integer constant expression. /// - the expression returned acts like the chosen subexpression in every @@ -1996,12 +1996,12 @@ class ChooseExpr : public Expr { public: ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t, SourceLocation RP) - : Expr(ChooseExprClass, t), + : Expr(ChooseExprClass, t), BuiltinLoc(BLoc), RParenLoc(RP) { SubExprs[COND] = cond; SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; - } + } /// \brief Build an empty __builtin_choose_expr. explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } @@ -2025,7 +2025,7 @@ public: SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } - + SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } @@ -2033,10 +2033,10 @@ public: return SourceRange(BuiltinLoc, RParenLoc); } static bool classof(const Stmt *T) { - return T->getStmtClass() == ChooseExprClass; + return T->getStmtClass() == ChooseExprClass; } static bool classof(const ChooseExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -2053,7 +2053,7 @@ class GNUNullExpr : public Expr { SourceLocation TokenLoc; public: - GNUNullExpr(QualType Ty, SourceLocation Loc) + GNUNullExpr(QualType Ty, SourceLocation Loc) : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { } /// \brief Build an empty GNU __null expression. @@ -2067,10 +2067,10 @@ public: return SourceRange(TokenLoc); } static bool classof(const Stmt *T) { - return T->getStmtClass() == GNUNullExprClass; + return T->getStmtClass() == GNUNullExprClass; } static bool classof(const GNUNullExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -2086,7 +2086,7 @@ public: Val(e), BuiltinLoc(BLoc), RParenLoc(RPLoc) { } - + /// \brief Create an empty __builtin_va_start expression. explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { } @@ -2096,23 +2096,23 @@ public: SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } - + SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } virtual SourceRange getSourceRange() const { return SourceRange(BuiltinLoc, RParenLoc); - } + } static bool classof(const Stmt *T) { return T->getStmtClass() == VAArgExprClass; } static bool classof(const VAArgExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); - virtual child_iterator child_end(); + virtual child_iterator child_end(); }; - + /// @brief Describes an C or C++ initializer list. /// /// InitListExpr describes an initializer list, which can be used to @@ -2154,7 +2154,7 @@ class InitListExpr : public Expr { // FIXME: Eliminate this vector in favor of ASTContext allocation std::vector InitExprs; SourceLocation LBraceLoc, RBraceLoc; - + /// Contains the initializer list that describes the syntactic form /// written in the source code. InitListExpr *SyntacticForm; @@ -2173,27 +2173,27 @@ public: /// \brief Build an empty initializer list. explicit InitListExpr(EmptyShell Empty) : Expr(InitListExprClass, Empty) { } - + unsigned getNumInits() const { return InitExprs.size(); } - - const Expr* getInit(unsigned Init) const { + + const Expr* getInit(unsigned Init) const { assert(Init < getNumInits() && "Initializer access out of range!"); return cast_or_null(InitExprs[Init]); } - - Expr* getInit(unsigned Init) { + + Expr* getInit(unsigned Init) { assert(Init < getNumInits() && "Initializer access out of range!"); return cast_or_null(InitExprs[Init]); } - - void setInit(unsigned Init, Expr *expr) { + + void setInit(unsigned Init, Expr *expr) { assert(Init < getNumInits() && "Initializer access out of range!"); InitExprs[Init] = expr; } /// \brief Reserve space for some number of initializers. void reserveInits(unsigned NumInits); - + /// @brief Specify the number of initializers /// /// If there are more than @p NumInits initializers, the remaining @@ -2225,7 +2225,7 @@ public: bool isExplicit() { return LBraceLoc.isValid() && RBraceLoc.isValid(); } - + SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } SourceLocation getRBraceLoc() const { return RBraceLoc; } @@ -2234,30 +2234,30 @@ public: /// @brief Retrieve the initializer list that describes the /// syntactic form of the initializer. /// - /// + /// InitListExpr *getSyntacticForm() const { return SyntacticForm; } void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; } bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; } - void sawArrayRangeDesignator(bool ARD = true) { + void sawArrayRangeDesignator(bool ARD = true) { HadArrayRangeDesignator = ARD; } virtual SourceRange getSourceRange() const { return SourceRange(LBraceLoc, RBraceLoc); - } + } static bool classof(const Stmt *T) { - return T->getStmtClass() == InitListExprClass; + return T->getStmtClass() == InitListExprClass; } static bool classof(const InitListExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); - + typedef std::vector::iterator iterator; typedef std::vector::reverse_iterator reverse_iterator; - + iterator begin() { return InitExprs.begin(); } iterator end() { return InitExprs.end(); } reverse_iterator rbegin() { return InitExprs.rbegin(); } @@ -2271,7 +2271,7 @@ public: /// designators, or GNU array-range designators) followed by an /// expression that initializes the field or element(s) that the /// designators refer to. For example, given: -/// +/// /// @code /// struct point { /// double x; @@ -2311,7 +2311,7 @@ private: unsigned NumSubExprs : 16; - DesignatedInitExpr(QualType Ty, unsigned NumDesignators, + DesignatedInitExpr(QualType Ty, unsigned NumDesignators, const Designator *Designators, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr **IndexExprs, unsigned NumIndexExprs, @@ -2322,7 +2322,7 @@ private: NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { } protected: - virtual void DoDestroy(ASTContext &C); + virtual void DoDestroy(ASTContext &C); public: /// A field designator, e.g., ".x". @@ -2334,10 +2334,10 @@ public: /// IdentifierInfo*. After semantic analysis has resolved that /// name, the field designator will instead store a FieldDecl*. uintptr_t NameOrField; - + /// The location of the '.' in the designated initializer. unsigned DotLoc; - + /// The location of the field name in the designated initializer. unsigned FieldLoc; }; @@ -2353,7 +2353,7 @@ public: /// indices. Only valid for GNU array-range designators. unsigned EllipsisLoc; /// The location of the ']' terminating the array range designator. - unsigned RBracketLoc; + unsigned RBracketLoc; }; /// @brief Represents a single C99 designator. @@ -2382,8 +2382,8 @@ public: Designator() {} /// @brief Initializes a field designator. - Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, - SourceLocation FieldLoc) + Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, + SourceLocation FieldLoc) : Kind(FieldDesignator) { Field.NameOrField = reinterpret_cast(FieldName) | 0x01; Field.DotLoc = DotLoc.getRawEncoding(); @@ -2391,7 +2391,7 @@ public: } /// @brief Initializes an array designator. - Designator(unsigned Index, SourceLocation LBracketLoc, + Designator(unsigned Index, SourceLocation LBracketLoc, SourceLocation RBracketLoc) : Kind(ArrayDesignator) { ArrayOrRange.Index = Index; @@ -2401,7 +2401,7 @@ public: } /// @brief Initializes a GNU array-range designator. - Designator(unsigned Index, SourceLocation LBracketLoc, + Designator(unsigned Index, SourceLocation LBracketLoc, SourceLocation EllipsisLoc, SourceLocation RBracketLoc) : Kind(ArrayRangeDesignator) { ArrayOrRange.Index = Index; @@ -2471,7 +2471,7 @@ public: } }; - static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators, + static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators, unsigned NumDesignators, Expr **IndexExprs, unsigned NumIndexExprs, SourceLocation EqualOrColonLoc, @@ -2485,8 +2485,8 @@ public: // Iterator access to the designators. typedef Designator* designators_iterator; designators_iterator designators_begin() { return Designators; } - designators_iterator designators_end() { - return Designators + NumDesignators; + designators_iterator designators_end() { + return Designators + NumDesignators; } Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; } @@ -2508,7 +2508,7 @@ public: void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } /// @brief Retrieve the initializer value. - Expr *getInit() const { + Expr *getInit() const { return cast(*const_cast(this)->child_begin()); } @@ -2538,19 +2538,19 @@ public: /// \brief Replaces the designator at index @p Idx with the series /// of designators in [First, Last). - void ExpandDesignator(unsigned Idx, const Designator *First, + void ExpandDesignator(unsigned Idx, const Designator *First, const Designator *Last); virtual SourceRange getSourceRange() const; static bool classof(const Stmt *T) { - return T->getStmtClass() == DesignatedInitExprClass; + return T->getStmtClass() == DesignatedInitExprClass; } static bool classof(const DesignatedInitExpr *) { return true; } // Iterators virtual child_iterator child_begin(); - virtual child_iterator child_end(); + virtual child_iterator child_end(); }; /// \brief Represents an implicitly-generated value initialization of @@ -2561,16 +2561,16 @@ public: /// initializations not explicitly specified by the user. /// /// \see InitListExpr -class ImplicitValueInitExpr : public Expr { +class ImplicitValueInitExpr : public Expr { public: - explicit ImplicitValueInitExpr(QualType ty) + explicit ImplicitValueInitExpr(QualType ty) : Expr(ImplicitValueInitExprClass, ty) { } /// \brief Construct an empty implicit value initialization. explicit ImplicitValueInitExpr(EmptyShell Empty) : Expr(ImplicitValueInitExprClass, Empty) { } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == ImplicitValueInitExprClass; } static bool classof(const ImplicitValueInitExpr *) { return true; } @@ -2581,7 +2581,7 @@ public: // Iterators virtual child_iterator child_begin(); - virtual child_iterator child_end(); + virtual child_iterator child_end(); }; @@ -2590,49 +2590,49 @@ class ParenListExpr : public Expr { unsigned NumExprs; SourceLocation LParenLoc, RParenLoc; -protected: +protected: virtual void DoDestroy(ASTContext& C); - + public: - ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs, + ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs, unsigned numexprs, SourceLocation rparenloc); ~ParenListExpr() {} /// \brief Build an empty paren list. //explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } - + unsigned getNumExprs() const { return NumExprs; } - - const Expr* getExpr(unsigned Init) const { + + const Expr* getExpr(unsigned Init) const { assert(Init < getNumExprs() && "Initializer access out of range!"); return cast_or_null(Exprs[Init]); } - - Expr* getExpr(unsigned Init) { + + Expr* getExpr(unsigned Init) { assert(Init < getNumExprs() && "Initializer access out of range!"); return cast_or_null(Exprs[Init]); } Expr **getExprs() { return reinterpret_cast(Exprs); } - + SourceLocation getLParenLoc() const { return LParenLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(LParenLoc, RParenLoc); - } + } static bool classof(const Stmt *T) { - return T->getStmtClass() == ParenListExprClass; + return T->getStmtClass() == ParenListExprClass; } static bool classof(const ParenListExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + //===----------------------------------------------------------------------===// // Clang Extensions //===----------------------------------------------------------------------===// @@ -2652,9 +2652,9 @@ class ExtVectorElementExpr : public Expr { public: ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor, SourceLocation loc) - : Expr(ExtVectorElementExprClass, ty), + : Expr(ExtVectorElementExprClass, ty), Base(base), Accessor(&accessor), AccessorLoc(loc) {} - + /// \brief Build an empty vector element expression. explicit ExtVectorElementExpr(EmptyShell Empty) : Expr(ExtVectorElementExprClass, Empty) { } @@ -2671,28 +2671,28 @@ public: /// getNumElements - Get the number of components being selected. unsigned getNumElements() const; - + /// containsDuplicateElements - Return true if any element access is /// repeated. bool containsDuplicateElements() const; - + /// getEncodedElementAccess - Encode the elements accessed into an llvm /// aggregate Constant of ConstantInt(s). void getEncodedElementAccess(llvm::SmallVectorImpl &Elts) const; - + virtual SourceRange getSourceRange() const { return SourceRange(getBase()->getLocStart(), AccessorLoc); } - + /// isArrow - Return true if the base expression is a pointer to vector, /// return false if the base expression is a vector. bool isArrow() const; - - static bool classof(const Stmt *T) { - return T->getStmtClass() == ExtVectorElementExprClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == ExtVectorElementExprClass; } static bool classof(const ExtVectorElementExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -2707,7 +2707,7 @@ protected: bool HasBlockDeclRefExprs; public: BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs) - : Expr(BlockExprClass, ty), + : Expr(BlockExprClass, ty), TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {} /// \brief Build an empty block expression. @@ -2734,25 +2734,25 @@ public: bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; } void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == BlockExprClass; } static bool classof(const BlockExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + /// BlockDeclRefExpr - A reference to a declared variable, function, /// enum, etc. class BlockDeclRefExpr : public Expr { - ValueDecl *D; + ValueDecl *D; SourceLocation Loc; bool IsByRef : 1; bool ConstQualAdded : 1; public: - BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef, + BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef, bool constAdded = false) : Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded) {} @@ -2761,7 +2761,7 @@ public: // block. explicit BlockDeclRefExpr(EmptyShell Empty) : Expr(BlockDeclRefExprClass, Empty) { } - + ValueDecl *getDecl() { return D; } const ValueDecl *getDecl() const { return D; } void setDecl(ValueDecl *VD) { D = VD; } @@ -2770,18 +2770,18 @@ public: void setLocation(SourceLocation L) { Loc = L; } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - + bool isByRef() const { return IsByRef; } void setByRef(bool BR) { IsByRef = BR; } - + bool isConstQualAdded() const { return ConstQualAdded; } void setConstQualAdded(bool C) { ConstQualAdded = C; } - static bool classof(const Stmt *T) { - return T->getStmtClass() == BlockDeclRefExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == BlockDeclRefExprClass; } static bool classof(const BlockDeclRefExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); diff --git a/clang/include/clang/AST/ExprCXX.h b/clang/include/clang/AST/ExprCXX.h index 0d9b4cef547c0fed630b514bcba00194f23fc183..91b5fd27073b0e60cf04449b7175f800db338227 100644 --- a/clang/include/clang/AST/ExprCXX.h +++ b/clang/include/clang/AST/ExprCXX.h @@ -47,14 +47,14 @@ class CXXOperatorCallExpr : public CallExpr { OverloadedOperatorKind Operator; public: - CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn, - Expr **args, unsigned numargs, QualType t, + CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn, + Expr **args, unsigned numargs, QualType t, SourceLocation operatorloc) : CallExpr(C, CXXOperatorCallExprClass, fn, args, numargs, t, operatorloc), Operator(Op) {} - explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) : + explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) : CallExpr(C, CXXOperatorCallExprClass, Empty) { } - + /// getOperator - Returns the kind of overloaded operator that this /// expression refers to. @@ -69,9 +69,9 @@ public: SourceLocation getOperatorLoc() const { return getRParenLoc(); } virtual SourceRange getSourceRange() const; - - static bool classof(const Stmt *T) { - return T->getStmtClass() == CXXOperatorCallExprClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == CXXOperatorCallExprClass; } static bool classof(const CXXOperatorCallExpr *) { return true; } }; @@ -95,7 +95,7 @@ public: /// operation would return "x". Expr *getImplicitObjectArgument(); - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXMemberCallExprClass; } static bool classof(const CXXMemberCallExpr *) { return true; } @@ -113,7 +113,7 @@ private: SourceLocation Loc; // the location of the casting op protected: - CXXNamedCastExpr(StmtClass SC, QualType ty, const CastInfo &info, Expr *op, + CXXNamedCastExpr(StmtClass SC, QualType ty, const CastInfo &info, Expr *op, QualType writtenTy, SourceLocation l) : ExplicitCastExpr(SC, ty, info, op, writtenTy), Loc(l) {} @@ -128,7 +128,7 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(Loc, getSubExpr()->getSourceRange().getEnd()); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { switch (T->getStmtClass()) { case CXXNamedCastExprClass: case CXXStaticCastExprClass: @@ -144,34 +144,34 @@ public: }; /// CXXStaticCastExpr - A C++ @c static_cast expression (C++ [expr.static.cast]). -/// +/// /// This expression node represents a C++ static cast, e.g., /// @c static_cast(1.0). class CXXStaticCastExpr : public CXXNamedCastExpr { public: - CXXStaticCastExpr(QualType ty, const CastInfo &info, Expr *op, + CXXStaticCastExpr(QualType ty, const CastInfo &info, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXStaticCastExprClass, ty, info, op, writtenTy, l) {} - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXStaticCastExprClass; } static bool classof(const CXXStaticCastExpr *) { return true; } }; /// CXXDynamicCastExpr - A C++ @c dynamic_cast expression -/// (C++ [expr.dynamic.cast]), which may perform a run-time check to +/// (C++ [expr.dynamic.cast]), which may perform a run-time check to /// determine how to perform the type cast. -/// +/// /// This expression node represents a dynamic cast, e.g., /// @c dynamic_cast(BasePtr). class CXXDynamicCastExpr : public CXXNamedCastExpr { public: - CXXDynamicCastExpr(QualType ty, CastKind kind, Expr *op, QualType writtenTy, + CXXDynamicCastExpr(QualType ty, CastKind kind, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, kind, op, writtenTy, l) {} - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXDynamicCastExprClass; } static bool classof(const CXXDynamicCastExpr *) { return true; } @@ -180,17 +180,17 @@ public: /// CXXReinterpretCastExpr - A C++ @c reinterpret_cast expression (C++ /// [expr.reinterpret.cast]), which provides a differently-typed view /// of a value but performs no actual work at run time. -/// +/// /// This expression node represents a reinterpret cast, e.g., /// @c reinterpret_cast(VoidPtr). class CXXReinterpretCastExpr : public CXXNamedCastExpr { public: - CXXReinterpretCastExpr(QualType ty, Expr *op, QualType writtenTy, + CXXReinterpretCastExpr(QualType ty, Expr *op, QualType writtenTy, SourceLocation l) - : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, CK_BitCast, op, + : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, CK_BitCast, op, writtenTy, l) {} - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXReinterpretCastExprClass; } static bool classof(const CXXReinterpretCastExpr *) { return true; } @@ -198,39 +198,39 @@ public: /// CXXConstCastExpr - A C++ @c const_cast expression (C++ [expr.const.cast]), /// which can remove type qualifiers but does not change the underlying value. -/// +/// /// This expression node represents a const cast, e.g., /// @c const_cast(PtrToConstChar). class CXXConstCastExpr : public CXXNamedCastExpr { public: - CXXConstCastExpr(QualType ty, Expr *op, QualType writtenTy, + CXXConstCastExpr(QualType ty, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXConstCastExprClass, ty, CK_NoOp, op, writtenTy, l) {} - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConstCastExprClass; } static bool classof(const CXXConstCastExpr *) { return true; } }; /// CXXBoolLiteralExpr - [C++ 2.13.5] C++ Boolean Literal. -/// +/// class CXXBoolLiteralExpr : public Expr { bool Value; SourceLocation Loc; public: - CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) : + CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) : Expr(CXXBoolLiteralExprClass, Ty), Value(val), Loc(l) {} bool getValue() const { return Value; } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXBoolLiteralExprClass; } static bool classof(const CXXBoolLiteralExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -322,7 +322,7 @@ class CXXThisExpr : public Expr { SourceLocation Loc; public: - CXXThisExpr(SourceLocation L, QualType Type) + CXXThisExpr(SourceLocation L, QualType Type) : Expr(CXXThisExprClass, Type, // 'this' is type-dependent if the class type of the enclosing // member function is dependent (C++ [temp.dep.expr]p2) @@ -331,7 +331,7 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXThisExprClass; } static bool classof(const CXXThisExpr *) { return true; } @@ -383,14 +383,14 @@ public: /// supply arguments for all of the parameters. class CXXDefaultArgExpr : public Expr { ParmVarDecl *Param; - + protected: - CXXDefaultArgExpr(StmtClass SC, ParmVarDecl *param) - : Expr(SC, param->hasUnparsedDefaultArg() ? + CXXDefaultArgExpr(StmtClass SC, ParmVarDecl *param) + : Expr(SC, param->hasUnparsedDefaultArg() ? param->getType().getNonReferenceType() : param->getDefaultArg()->getType()), Param(param) { } - + public: // Param is the parameter whose default argument is used by this // expression. @@ -426,39 +426,39 @@ public: class CXXTemporary { /// Destructor - The destructor that needs to be called. const CXXDestructorDecl *Destructor; - + CXXTemporary(const CXXDestructorDecl *destructor) : Destructor(destructor) { } ~CXXTemporary() { } public: - static CXXTemporary *Create(ASTContext &C, + static CXXTemporary *Create(ASTContext &C, const CXXDestructorDecl *Destructor); - + void Destroy(ASTContext &Ctx); - + const CXXDestructorDecl *getDestructor() const { return Destructor; } }; -/// CXXBindTemporaryExpr - Represents binding an expression to a temporary, +/// CXXBindTemporaryExpr - Represents binding an expression to a temporary, /// so its destructor can be called later. class CXXBindTemporaryExpr : public Expr { CXXTemporary *Temp; - + Stmt *SubExpr; - CXXBindTemporaryExpr(CXXTemporary *temp, Expr* subexpr) + CXXBindTemporaryExpr(CXXTemporary *temp, Expr* subexpr) : Expr(CXXBindTemporaryExprClass, subexpr->getType()), Temp(temp), SubExpr(subexpr) { } - ~CXXBindTemporaryExpr() { } + ~CXXBindTemporaryExpr() { } protected: virtual void DoDestroy(ASTContext &C); public: - static CXXBindTemporaryExpr *Create(ASTContext &C, CXXTemporary *Temp, + static CXXBindTemporaryExpr *Create(ASTContext &C, CXXTemporary *Temp, Expr* SubExpr); - + CXXTemporary *getTemporary() { return Temp; } const CXXTemporary *getTemporary() const { return Temp; } @@ -484,24 +484,24 @@ class CXXConstructExpr : public Expr { CXXConstructorDecl *Constructor; bool Elidable; - + Stmt **Args; unsigned NumArgs; - + protected: - CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T, + CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T, CXXConstructorDecl *d, bool elidable, Expr **args, unsigned numargs); - ~CXXConstructExpr() { } + ~CXXConstructExpr() { } virtual void DoDestroy(ASTContext &C); public: static CXXConstructExpr *Create(ASTContext &C, QualType T, - CXXConstructorDecl *D, bool Elidable, + CXXConstructorDecl *D, bool Elidable, Expr **Args, unsigned NumArgs); - - + + CXXConstructorDecl* getConstructor() const { return Constructor; } /// \brief Whether this construction is elidable. @@ -509,7 +509,7 @@ public: typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; - + arg_iterator arg_begin() { return Args; } arg_iterator arg_end() { return Args + NumArgs; } const_arg_iterator arg_begin() const { return Args; } @@ -526,7 +526,7 @@ public: assert(Arg < NumArgs && "Arg access out of range!"); return cast(Args[Arg]); } - + /// setArg - Set the specified argument. void setArg(unsigned Arg, Expr *ArgExpr) { assert(Arg < NumArgs && "Arg access out of range!"); @@ -535,12 +535,12 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConstructExprClass || T->getStmtClass() == CXXTemporaryObjectExprClass; } static bool classof(const CXXConstructExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -554,24 +554,24 @@ class CXXFunctionalCastExpr : public ExplicitCastExpr { SourceLocation TyBeginLoc; SourceLocation RParenLoc; public: - CXXFunctionalCastExpr(QualType ty, QualType writtenTy, - SourceLocation tyBeginLoc, CastKind kind, + CXXFunctionalCastExpr(QualType ty, QualType writtenTy, + SourceLocation tyBeginLoc, CastKind kind, Expr *castExpr, CXXMethodDecl *typeConversionMethod, - SourceLocation rParenLoc) : + SourceLocation rParenLoc) : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, kind, castExpr, writtenTy), TypeConversionMethod(typeConversionMethod), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {} - CXXMethodDecl *getTypeConversionMethod() const + CXXMethodDecl *getTypeConversionMethod() const { return TypeConversionMethod; } SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } - + virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == CXXFunctionalCastExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == CXXFunctionalCastExprClass; } static bool classof(const CXXFunctionalCastExpr *) { return true; } }; @@ -579,7 +579,7 @@ public: /// @brief Represents a C++ functional cast expression that builds a /// temporary object. /// -/// This expression type represents a C++ "functional" cast +/// This expression type represents a C++ "functional" cast /// (C++[expr.type.conv]) with N != 1 arguments that invokes a /// constructor to build a temporary object. If N == 0 but no /// constructor will be called (because the functional cast is @@ -600,12 +600,12 @@ class CXXTemporaryObjectExpr : public CXXConstructExpr { SourceLocation RParenLoc; public: - CXXTemporaryObjectExpr(ASTContext &C, CXXConstructorDecl *Cons, - QualType writtenTy, SourceLocation tyBeginLoc, - Expr **Args,unsigned NumArgs, + CXXTemporaryObjectExpr(ASTContext &C, CXXConstructorDecl *Cons, + QualType writtenTy, SourceLocation tyBeginLoc, + Expr **Args,unsigned NumArgs, SourceLocation rParenLoc); - ~CXXTemporaryObjectExpr() { } + ~CXXTemporaryObjectExpr() { } SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } @@ -613,7 +613,7 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXTemporaryObjectExprClass; } static bool classof(const CXXTemporaryObjectExpr *) { return true; } @@ -630,28 +630,28 @@ class CXXZeroInitValueExpr : public Expr { public: CXXZeroInitValueExpr(QualType ty, SourceLocation tyBeginLoc, - SourceLocation rParenLoc ) : + SourceLocation rParenLoc ) : Expr(CXXZeroInitValueExprClass, ty, false, false), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {} - + SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } /// @brief Whether this initialization expression was /// implicitly-generated. - bool isImplicit() const { - return TyBeginLoc.isInvalid() && RParenLoc.isInvalid(); + bool isImplicit() const { + return TyBeginLoc.isInvalid() && RParenLoc.isInvalid(); } virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXZeroInitValueExprClass; } static bool classof(const CXXZeroInitValueExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -666,26 +666,26 @@ class CXXConditionDeclExpr : public DeclRefExpr { public: CXXConditionDeclExpr(SourceLocation startLoc, SourceLocation eqLoc, VarDecl *var) - : DeclRefExpr(CXXConditionDeclExprClass, var, + : DeclRefExpr(CXXConditionDeclExprClass, var, var->getType().getNonReferenceType(), startLoc, var->getType()->isDependentType(), /*FIXME:integral constant?*/ var->getType()->isDependentType()) {} SourceLocation getStartLoc() const { return getLocation(); } - + VarDecl *getVarDecl() { return cast(getDecl()); } const VarDecl *getVarDecl() const { return cast(getDecl()); } virtual SourceRange getSourceRange() const { return SourceRange(getStartLoc(), getVarDecl()->getInit()->getLocEnd()); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConditionDeclExprClass; } static bool classof(const CXXConditionDeclExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -866,7 +866,7 @@ public: /// Example: /// /// \code -/// template +/// template /// void destroy(T* ptr) { /// ptr->~T(); /// } @@ -874,67 +874,67 @@ public: /// /// When the template is parsed, the expression \c ptr->~T will be stored as /// a member reference expression. If it then instantiated with a scalar type -/// as a template argument for T, the resulting expression will be a +/// as a template argument for T, the resulting expression will be a /// pseudo-destructor expression. class CXXPseudoDestructorExpr : public Expr { /// \brief The base expression (that is being destroyed). Stmt *Base; - + /// \brief Whether the operator was an arrow ('->'); otherwise, it was a /// period ('.'). bool IsArrow : 1; - + /// \brief The location of the '.' or '->' operator. SourceLocation OperatorLoc; - + /// \brief The nested-name-specifier that follows the operator, if present. NestedNameSpecifier *Qualifier; - - /// \brief The source range that covers the nested-name-specifier, if + + /// \brief The source range that covers the nested-name-specifier, if /// present. SourceRange QualifierRange; - + /// \brief The type being destroyed. QualType DestroyedType; - + /// \brief The location of the type after the '~'. SourceLocation DestroyedTypeLoc; - + public: CXXPseudoDestructorExpr(ASTContext &Context, Expr *Base, bool isArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - QualType DestroyedType, + QualType DestroyedType, SourceLocation DestroyedTypeLoc) - : Expr(CXXPseudoDestructorExprClass, + : Expr(CXXPseudoDestructorExprClass, Context.getPointerType(Context.getFunctionType(Context.VoidTy, 0, 0, false, 0)), /*isTypeDependent=*/false, /*isValueDependent=*/Base->isValueDependent()), - Base(static_cast(Base)), IsArrow(isArrow), + Base(static_cast(Base)), IsArrow(isArrow), OperatorLoc(OperatorLoc), Qualifier(Qualifier), QualifierRange(QualifierRange), DestroyedType(DestroyedType), DestroyedTypeLoc(DestroyedTypeLoc) { } - + void setBase(Expr *E) { Base = E; } Expr *getBase() const { return cast(Base); } - - /// \brief Determines whether this member expression actually had + + /// \brief Determines whether this member expression actually had /// a C++ nested-name-specifier prior to the name of the member, e.g., /// x->Base::foo. bool hasQualifier() const { return Qualifier != 0; } - + /// \brief If the member name was qualified, retrieves the source range of /// the nested-name-specifier that precedes the member name. Otherwise, /// returns an empty source range. SourceRange getQualifierRange() const { return QualifierRange; } - - /// \brief If the member name was qualified, retrieves the + + /// \brief If the member name was qualified, retrieves the /// nested-name-specifier that precedes the member name. Otherwise, returns /// NULL. NestedNameSpecifier *getQualifier() const { return Qualifier; } - + /// \brief Determine whether this pseudo-destructor expression was written /// using an '->' (otherwise, it used a '.'). bool isArrow() const { return IsArrow; } @@ -942,27 +942,27 @@ public: /// \brief Retrieve the location of the '.' or '->' operator. SourceLocation getOperatorLoc() const { return OperatorLoc; } - + /// \brief Retrieve the type that is being destroyed. QualType getDestroyedType() const { return DestroyedType; } - + /// \brief Retrieve the location of the type being destroyed. SourceLocation getDestroyedTypeLoc() const { return DestroyedTypeLoc; } - + virtual SourceRange getSourceRange() const { return SourceRange(Base->getLocStart(), DestroyedTypeLoc); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXPseudoDestructorExprClass; } static bool classof(const CXXPseudoDestructorExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); - virtual child_iterator child_end(); + virtual child_iterator child_end(); }; - + /// \brief Represents the name of a function that has not been /// resolved to any declaration. /// @@ -980,7 +980,7 @@ public: /// } /// @endcode class UnresolvedFunctionNameExpr : public Expr { - /// The name that was present in the source + /// The name that was present in the source DeclarationName Name; /// The location of this name in the source code @@ -999,7 +999,7 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == UnresolvedFunctionNameExprClass; } static bool classof(const UnresolvedFunctionNameExpr *) { return true; } @@ -1064,9 +1064,9 @@ class QualifiedDeclRefExpr : public DeclRefExpr { NestedNameSpecifier *NNS; public: - QualifiedDeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, + QualifiedDeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD, SourceRange R, NestedNameSpecifier *NNS) - : DeclRefExpr(QualifiedDeclRefExprClass, d, t, l, TD, VD), + : DeclRefExpr(QualifiedDeclRefExprClass, d, t, l, TD, VD), QualifierRange(R), NNS(NNS) { } /// \brief Retrieve the source range of the nested-name-specifier. @@ -1076,8 +1076,8 @@ public: /// declaration. NestedNameSpecifier *getQualifier() const { return NNS; } - virtual SourceRange getSourceRange() const { - return SourceRange(QualifierRange.getBegin(), getLocation()); + virtual SourceRange getSourceRange() const { + return SourceRange(QualifierRange.getBegin(), getLocation()); } static bool classof(const Stmt *T) { @@ -1117,13 +1117,13 @@ class UnresolvedDeclRefExpr : public Expr { /// \brief Whether this expr is an address of (&) operand. bool IsAddressOfOperand; - + public: UnresolvedDeclRefExpr(DeclarationName N, QualType T, SourceLocation L, - SourceRange R, NestedNameSpecifier *NNS, + SourceRange R, NestedNameSpecifier *NNS, bool IsAddressOfOperand) - : Expr(UnresolvedDeclRefExprClass, T, true, true), - Name(N), Loc(L), QualifierRange(R), NNS(NNS), + : Expr(UnresolvedDeclRefExprClass, T, true, true), + Name(N), Loc(L), QualifierRange(R), NNS(NNS), IsAddressOfOperand(IsAddressOfOperand) { } /// \brief Retrieve the name that this expression refers to. @@ -1140,10 +1140,10 @@ public: NestedNameSpecifier *getQualifier() const { return NNS; } /// \brief Retrieve whether this is an address of (&) operand. - + bool isAddressOfOperand() const { return IsAddressOfOperand; } - virtual SourceRange getSourceRange() const { - return SourceRange(QualifierRange.getBegin(), getLocation()); + virtual SourceRange getSourceRange() const { + return SourceRange(QualifierRange.getBegin(), getLocation()); } static bool classof(const Stmt *T) { @@ -1155,42 +1155,42 @@ public: virtual StmtIterator child_end(); }; -/// \brief An expression that refers to a C++ template-id, such as -/// @c isa. +/// \brief An expression that refers to a C++ template-id, such as +/// @c isa. class TemplateIdRefExpr : public Expr { /// \brief If this template-id was qualified-id, e.g., @c std::sort, /// this nested name specifier contains the @c std::. NestedNameSpecifier *Qualifier; - + /// \brief If this template-id was a qualified-id, e.g., @c std::sort, /// this covers the source code range of the @c std::. SourceRange QualifierRange; - + /// \brief The actual template to which this template-id refers. TemplateName Template; - + /// \brief The source location of the template name. SourceLocation TemplateNameLoc; /// \brief The source location of the left angle bracket ('<'); SourceLocation LAngleLoc; - + /// \brief The source location of the right angle bracket ('>'); SourceLocation RAngleLoc; - + /// \brief The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; - + TemplateIdRefExpr(QualType T, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, TemplateName Template, SourceLocation TemplateNameLoc, - SourceLocation LAngleLoc, + SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); - + virtual void DoDestroy(ASTContext &Context); - + public: static TemplateIdRefExpr * Create(ASTContext &Context, QualType T, @@ -1198,66 +1198,66 @@ public: TemplateName Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); - + /// \brief Retrieve the nested name specifier used to qualify the name of /// this template-id, e.g., the "std::sort" in @c std::sort, or NULL /// if this template-id was an unqualified-id. NestedNameSpecifier *getQualifier() const { return Qualifier; } - + /// \brief Retrieve the source range describing the nested name specifier /// used to qualified the name of this template-id, if the name was qualified. SourceRange getQualifierRange() const { return QualifierRange; } - + /// \brief Retrieve the name of the template referenced, e.g., "sort" in /// @c std::sort; TemplateName getTemplateName() const { return Template; } - + /// \brief Retrieve the location of the name of the template referenced, e.g., /// the location of "sort" in @c std::sort. SourceLocation getTemplateNameLoc() const { return TemplateNameLoc; } - - /// \brief Retrieve the location of the left angle bracket following the + + /// \brief Retrieve the location of the left angle bracket following the /// template name ('<'). SourceLocation getLAngleLoc() const { return LAngleLoc; } - + /// \brief Retrieve the template arguments provided as part of this /// template-id. - const TemplateArgument *getTemplateArgs() const { + const TemplateArgument *getTemplateArgs() const { return reinterpret_cast(this + 1); } - + /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { return NumTemplateArgs; } - - /// \brief Retrieve the location of the right angle bracket following the + + /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). SourceLocation getRAngleLoc() const { return RAngleLoc; } - + virtual SourceRange getSourceRange() const { return SourceRange(Qualifier? QualifierRange.getBegin() : TemplateNameLoc, RAngleLoc); } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == TemplateIdRefExprClass; } static bool classof(const TemplateIdRefExpr *) { return true; } }; - + class CXXExprWithTemporaries : public Expr { Stmt *SubExpr; - + CXXTemporary **Temps; unsigned NumTemps; bool ShouldDestroyTemps; - - CXXExprWithTemporaries(Expr *SubExpr, CXXTemporary **Temps, + + CXXExprWithTemporaries(Expr *SubExpr, CXXTemporary **Temps, unsigned NumTemps, bool ShouldDestroyTemps); ~CXXExprWithTemporaries(); @@ -1268,7 +1268,7 @@ public: static CXXExprWithTemporaries *Create(ASTContext &C, Expr *SubExpr, CXXTemporary **Temps, unsigned NumTemps, bool ShouldDestroyTemporaries); - + unsigned getNumTemporaries() const { return NumTemps; } CXXTemporary *getTemporary(unsigned i) { assert(i < NumTemps && "Index out of range"); @@ -1278,11 +1278,11 @@ public: assert(i < NumTemps && "Index out of range"); return Temps[i]; } - + bool shouldDestroyTemporaries() const { return ShouldDestroyTemps; } - + void removeLastTemporary() { NumTemps--; } - + Expr *getSubExpr() { return cast(SubExpr); } const Expr *getSubExpr() const { return cast(SubExpr); } void setSubExpr(Expr *E) { SubExpr = E; } @@ -1336,7 +1336,7 @@ class CXXUnresolvedConstructExpr : public Expr { /// \brief The number of arguments used to construct the type. unsigned NumArgs; - + CXXUnresolvedConstructExpr(SourceLocation TyBegin, QualType T, SourceLocation LParenLoc, @@ -1345,7 +1345,7 @@ class CXXUnresolvedConstructExpr : public Expr { SourceLocation RParenLoc); public: - static CXXUnresolvedConstructExpr *Create(ASTContext &C, + static CXXUnresolvedConstructExpr *Create(ASTContext &C, SourceLocation TyBegin, QualType T, SourceLocation LParenLoc, @@ -1387,7 +1387,7 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXUnresolvedConstructExprClass; } static bool classof(const CXXUnresolvedConstructExpr *) { return true; } @@ -1404,7 +1404,7 @@ class CXXUnresolvedMemberExpr : public Expr { /// \brief The expression for the base pointer or class reference, /// e.g., the \c x in x.f. Stmt *Base; - + /// \brief Whether this member expression used the '->' operator or /// the '.' operator. bool IsArrow : 1; @@ -1412,25 +1412,25 @@ class CXXUnresolvedMemberExpr : public Expr { /// \brief Whether this member expression has explicitly-specified template /// arguments. bool HasExplicitTemplateArgumentList : 1; - + /// \brief The location of the '->' or '.' operator. SourceLocation OperatorLoc; /// \brief The nested-name-specifier that precedes the member name, if any. NestedNameSpecifier *Qualifier; - + /// \brief The source range covering the nested name specifier. SourceRange QualifierRange; - + /// \brief In a qualified member access expression such as t->Base::f, this - /// member stores the resolves of name lookup in the context of the member + /// member stores the resolves of name lookup in the context of the member /// access expression, to be used at instantiation time. /// /// FIXME: This member, along with the Qualifier and QualifierRange, could /// be stuck into a structure that is optionally allocated at the end of /// the CXXUnresolvedMemberExpr, to save space in the common case. NamedDecl *FirstQualifierFoundInScope; - + /// \brief The member to which this member expression refers, which /// can be name, overloaded operator, or destructor. /// FIXME: could also be a template-id @@ -1438,25 +1438,25 @@ class CXXUnresolvedMemberExpr : public Expr { /// \brief The location of the member name. SourceLocation MemberLoc; - + /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() { if (!HasExplicitTemplateArgumentList) return 0; - + return reinterpret_cast(this + 1); } - + /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const { return const_cast(this) ->getExplicitTemplateArgumentList(); } - - CXXUnresolvedMemberExpr(ASTContext &C, - Expr *Base, bool IsArrow, + + CXXUnresolvedMemberExpr(ASTContext &C, + Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, @@ -1468,10 +1468,10 @@ class CXXUnresolvedMemberExpr : public Expr { const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); - + public: - CXXUnresolvedMemberExpr(ASTContext &C, - Expr *Base, bool IsArrow, + CXXUnresolvedMemberExpr(ASTContext &C, + Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, @@ -1484,10 +1484,10 @@ public: Qualifier(Qualifier), QualifierRange(QualifierRange), FirstQualifierFoundInScope(FirstQualifierFoundInScope), Member(Member), MemberLoc(MemberLoc) { } - + static CXXUnresolvedMemberExpr * - Create(ASTContext &C, - Expr *Base, bool IsArrow, + Create(ASTContext &C, + Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, @@ -1499,7 +1499,7 @@ public: const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); - + /// \brief Retrieve the base object of this member expressions, /// e.g., the \c x in \c x.m. Expr *getBase() { return cast(Base); } @@ -1517,26 +1517,26 @@ public: /// \brief Retrieve the nested-name-specifier that qualifies the member /// name. NestedNameSpecifier *getQualifier() const { return Qualifier; } - + /// \brief Retrieve the source range covering the nested-name-specifier /// that qualifies the member name. SourceRange getQualifierRange() const { return QualifierRange; } - + /// \brief Retrieve the first part of the nested-name-specifier that was /// found in the scope of the member access expression when the member access /// was initially parsed. /// /// This function only returns a useful result when member access expression - /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration - /// returned by this function describes what was found by unqualified name + /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration + /// returned by this function describes what was found by unqualified name /// lookup for the identifier "Base" within the scope of the member access /// expression itself. At template instantiation time, this information is /// combined with the results of name lookup into the type of the object /// expression itself (the class type of x). - NamedDecl *getFirstQualifierFoundInScope() const { + NamedDecl *getFirstQualifierFoundInScope() const { return FirstQualifierFoundInScope; } - + /// \brief Retrieve the name of the member that this expression /// refers to. DeclarationName getMember() const { return Member; } @@ -1549,56 +1549,56 @@ public: /// \brief Determines whether this member expression actually had a C++ /// template argument list explicitly specified, e.g., x.f. - bool hasExplicitTemplateArgumentList() { - return HasExplicitTemplateArgumentList; + bool hasExplicitTemplateArgumentList() { + return HasExplicitTemplateArgumentList; } - - /// \brief Retrieve the location of the left angle bracket following the + + /// \brief Retrieve the location of the left angle bracket following the /// member name ('<'), if any. - SourceLocation getLAngleLoc() const { + SourceLocation getLAngleLoc() const { if (!HasExplicitTemplateArgumentList) return SourceLocation(); - + return getExplicitTemplateArgumentList()->LAngleLoc; } - + /// \brief Retrieve the template arguments provided as part of this /// template-id. - const TemplateArgument *getTemplateArgs() const { + const TemplateArgument *getTemplateArgs() const { if (!HasExplicitTemplateArgumentList) - return 0; - + return 0; + return getExplicitTemplateArgumentList()->getTemplateArgs(); } - + /// \brief Retrieve the number of template arguments provided as part of this /// template-id. - unsigned getNumTemplateArgs() const { + unsigned getNumTemplateArgs() const { if (!HasExplicitTemplateArgumentList) - return 0; - + return 0; + return getExplicitTemplateArgumentList()->NumTemplateArgs; } - - /// \brief Retrieve the location of the right angle bracket following the + + /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). - SourceLocation getRAngleLoc() const { + SourceLocation getRAngleLoc() const { if (!HasExplicitTemplateArgumentList) return SourceLocation(); - + return getExplicitTemplateArgumentList()->RAngleLoc; } - + virtual SourceRange getSourceRange() const { if (HasExplicitTemplateArgumentList) return SourceRange(Base->getSourceRange().getBegin(), getRAngleLoc()); - + return SourceRange(Base->getSourceRange().getBegin(), MemberLoc); } - - static bool classof(const Stmt *T) { + + static bool classof(const Stmt *T) { return T->getStmtClass() == CXXUnresolvedMemberExprClass; } static bool classof(const CXXUnresolvedMemberExpr *) { return true; } diff --git a/clang/include/clang/AST/ExprObjC.h b/clang/include/clang/AST/ExprObjC.h index 1070a11eb3b965dbe3ca28202a3eb202abd73ed3..0613f4c095f8e4e8fd5fc010b76518cf94a7e963 100644 --- a/clang/include/clang/AST/ExprObjC.h +++ b/clang/include/clang/AST/ExprObjC.h @@ -22,7 +22,7 @@ namespace clang { class ASTContext; class ObjCMethodDecl; class ObjCPropertyDecl; - + /// ObjCStringLiteral, used for Objective-C string literals /// i.e. @"foo". class ObjCStringLiteral : public Expr { @@ -41,20 +41,20 @@ public: SourceLocation getAtLoc() const { return AtLoc; } void setAtLoc(SourceLocation L) { AtLoc = L; } - virtual SourceRange getSourceRange() const { + virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, String->getLocEnd()); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == ObjCStringLiteralClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == ObjCStringLiteralClass; } - static bool classof(const ObjCStringLiteral *) { return true; } - + static bool classof(const ObjCStringLiteral *) { return true; } + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + /// ObjCEncodeExpr, used for @encode in Objective-C. @encode has the same type /// and behavior as StringLiteral except that the string initializer is obtained /// from ASTContext with the encoding type as an argument. @@ -62,32 +62,32 @@ class ObjCEncodeExpr : public Expr { QualType EncType; SourceLocation AtLoc, RParenLoc; public: - ObjCEncodeExpr(QualType T, QualType ET, + ObjCEncodeExpr(QualType T, QualType ET, SourceLocation at, SourceLocation rp) - : Expr(ObjCEncodeExprClass, T, ET->isDependentType(), + : Expr(ObjCEncodeExprClass, T, ET->isDependentType(), ET->isDependentType()), EncType(ET), AtLoc(at), RParenLoc(rp) {} - + explicit ObjCEncodeExpr(EmptyShell Empty) : Expr(ObjCEncodeExprClass, Empty){} - + SourceLocation getAtLoc() const { return AtLoc; } void setAtLoc(SourceLocation L) { AtLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } - + QualType getEncodedType() const { return EncType; } void setEncodedType(QualType T) { EncType = T; } - + virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, RParenLoc); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCEncodeExprClass; } static bool classof(const ObjCEncodeExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -106,7 +106,7 @@ public: Selector getSelector() const { return SelName; } void setSelector(Selector S) { SelName = S; } - + SourceLocation getAtLoc() const { return AtLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } void setAtLoc(SourceLocation L) { AtLoc = L; } @@ -115,26 +115,26 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, RParenLoc); } - + /// getNumArgs - Return the number of actual arguments to this call. unsigned getNumArgs() const { return SelName.getNumArgs(); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCSelectorExprClass; } static bool classof(const ObjCSelectorExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + /// ObjCProtocolExpr used for protocol expression in Objective-C. This is used /// as: @protocol(foo), as in: /// obj conformsToProtocol:@protocol(foo)] /// The return type is "Protocol*". -class ObjCProtocolExpr : public Expr { - ObjCProtocolDecl *TheProtocol; +class ObjCProtocolExpr : public Expr { + ObjCProtocolDecl *TheProtocol; SourceLocation AtLoc, RParenLoc; public: ObjCProtocolExpr(QualType T, ObjCProtocolDecl *protocol, @@ -146,7 +146,7 @@ public: ObjCProtocolDecl *getProtocol() const { return TheProtocol; } void setProtocol(ObjCProtocolDecl *P) { TheProtocol = P; } - + SourceLocation getAtLoc() const { return AtLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } void setAtLoc(SourceLocation L) { AtLoc = L; } @@ -155,12 +155,12 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, RParenLoc); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCProtocolExprClass; } static bool classof(const ObjCProtocolExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -173,44 +173,44 @@ class ObjCIvarRefExpr : public Expr { Stmt *Base; bool IsArrow:1; // True if this is "X->F", false if this is "X.F". bool IsFreeIvar:1; // True if ivar reference has no base (self assumed). - + public: ObjCIvarRefExpr(ObjCIvarDecl *d, - QualType t, SourceLocation l, Expr *base=0, - bool arrow = false, bool freeIvar = false) : + QualType t, SourceLocation l, Expr *base=0, + bool arrow = false, bool freeIvar = false) : Expr(ObjCIvarRefExprClass, t), D(d), Loc(l), Base(base), IsArrow(arrow), IsFreeIvar(freeIvar) {} - + explicit ObjCIvarRefExpr(EmptyShell Empty) : Expr(ObjCIvarRefExprClass, Empty) {} ObjCIvarDecl *getDecl() { return D; } const ObjCIvarDecl *getDecl() const { return D; } void setDecl(ObjCIvarDecl *d) { D = d; } - + const Expr *getBase() const { return cast(Base); } Expr *getBase() { return cast(Base); } void setBase(Expr * base) { Base = base; } - + bool isArrow() const { return IsArrow; } bool isFreeIvar() const { return IsFreeIvar; } void setIsArrow(bool A) { IsArrow = A; } void setIsFreeIvar(bool A) { IsFreeIvar = A; } - + SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } - virtual SourceRange getSourceRange() const { + virtual SourceRange getSourceRange() const { return isFreeIvar() ? SourceRange(Loc) - : SourceRange(getBase()->getLocStart(), Loc); + : SourceRange(getBase()->getLocStart(), Loc); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == ObjCIvarRefExprClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == ObjCIvarRefExprClass; } static bool classof(const ObjCIvarRefExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -225,48 +225,48 @@ private: SourceLocation IdLoc; Stmt *Base; public: - ObjCPropertyRefExpr(ObjCPropertyDecl *PD, QualType t, + ObjCPropertyRefExpr(ObjCPropertyDecl *PD, QualType t, SourceLocation l, Expr *base) : Expr(ObjCPropertyRefExprClass, t), AsProperty(PD), IdLoc(l), Base(base) { } - + explicit ObjCPropertyRefExpr(EmptyShell Empty) : Expr(ObjCPropertyRefExprClass, Empty) {} ObjCPropertyDecl *getProperty() const { return AsProperty; } void setProperty(ObjCPropertyDecl *D) { AsProperty = D; } - + const Expr *getBase() const { return cast(Base); } Expr *getBase() { return cast(Base); } void setBase(Expr *base) { Base = base; } - + SourceLocation getLocation() const { return IdLoc; } void setLocation(SourceLocation L) { IdLoc = L; } virtual SourceRange getSourceRange() const { return SourceRange(getBase()->getLocStart(), IdLoc); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == ObjCPropertyRefExprClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == ObjCPropertyRefExprClass; } static bool classof(const ObjCPropertyRefExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; -/// ObjCImplicitSetterGetterRefExpr - A dot-syntax expression to access two -/// methods; one to set a value to an 'ivar' (Setter) and the other to access -/// an 'ivar' (Setter). +/// ObjCImplicitSetterGetterRefExpr - A dot-syntax expression to access two +/// methods; one to set a value to an 'ivar' (Setter) and the other to access +/// an 'ivar' (Setter). /// An example for use of this AST is: /// @code /// @interface Test { } /// - (Test *)crash; /// - (void)setCrash: (Test*)value; /// @end -/// void foo(Test *p1, Test *p2) +/// void foo(Test *p1, Test *p2) /// { /// p2.crash = p1.crash; // Uses ObjCImplicitSetterGetterRefExpr AST /// } @@ -285,10 +285,10 @@ class ObjCImplicitSetterGetterRefExpr : public Expr { /// Location of the receiver class in the dot syntax notation /// used to call a class method setter/getter. SourceLocation ClassLoc; - + public: ObjCImplicitSetterGetterRefExpr(ObjCMethodDecl *getter, - QualType t, + QualType t, ObjCMethodDecl *setter, SourceLocation l, Expr *base) : Expr(ObjCImplicitSetterGetterRefExprClass, t), Setter(setter), @@ -296,13 +296,13 @@ public: ClassLoc(SourceLocation()) { } ObjCImplicitSetterGetterRefExpr(ObjCMethodDecl *getter, - QualType t, + QualType t, ObjCMethodDecl *setter, SourceLocation l, ObjCInterfaceDecl *C, SourceLocation CL) : Expr(ObjCImplicitSetterGetterRefExprClass, t), Setter(setter), Getter(getter), MemberLoc(l), Base(0), InterfaceDecl(C), ClassLoc(CL) { } - explicit ObjCImplicitSetterGetterRefExpr(EmptyShell Empty) + explicit ObjCImplicitSetterGetterRefExpr(EmptyShell Empty) : Expr(ObjCImplicitSetterGetterRefExprClass, Empty){} ObjCMethodDecl *getGetterMethod() const { return Getter; } @@ -311,7 +311,7 @@ public: void setGetterMethod(ObjCMethodDecl *D) { Getter = D; } void setSetterMethod(ObjCMethodDecl *D) { Setter = D; } void setInterfaceDecl(ObjCInterfaceDecl *D) { InterfaceDecl = D; } - + virtual SourceRange getSourceRange() const { if (Base) return SourceRange(getBase()->getLocStart(), MemberLoc); @@ -320,34 +320,34 @@ public: const Expr *getBase() const { return cast_or_null(Base); } Expr *getBase() { return cast_or_null(Base); } void setBase(Expr *base) { Base = base; } - + SourceLocation getLocation() const { return MemberLoc; } void setLocation(SourceLocation L) { MemberLoc = L; } SourceLocation getClassLoc() const { return ClassLoc; } void setClassLoc(SourceLocation L) { ClassLoc = L; } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == ObjCImplicitSetterGetterRefExprClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == ObjCImplicitSetterGetterRefExprClass; } static bool classof(const ObjCImplicitSetterGetterRefExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + class ObjCMessageExpr : public Expr { // SubExprs - The receiver and arguments of the message expression. Stmt **SubExprs; - + // NumArgs - The number of arguments (not including the receiver) to the // message expression. unsigned NumArgs; - + // A unigue name for this message. Selector SelName; - - // A method prototype for this message (optional). + + // A method prototype for this message (optional). // FIXME: Since method decls contain the selector, and most messages have a // prototype, consider devising a scheme for unifying SelName/MethodProto. ObjCMethodDecl *MethodProto; @@ -360,7 +360,7 @@ class ObjCMessageExpr : public Expr { // Bit-swizzling flags. enum { IsInstMeth=0, IsClsMethDeclUnknown, IsClsMethDeclKnown, Flags=0x3 }; unsigned getFlag() const { return (uintptr_t) SubExprs[RECEIVER] & Flags; } - + public: /// This constructor is used to represent class messages where the /// ObjCInterfaceDecl* of the receiver is not known. @@ -376,28 +376,28 @@ public: QualType retType, ObjCMethodDecl *methDecl, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned NumArgs); - + // constructor for instance messages. ObjCMessageExpr(Expr *receiver, Selector selInfo, QualType retType, ObjCMethodDecl *methDecl, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned NumArgs); - + explicit ObjCMessageExpr(EmptyShell Empty) : Expr(ObjCMessageExprClass, Empty), SubExprs(0), NumArgs(0) {} - + ~ObjCMessageExpr() { delete [] SubExprs; } - + /// getReceiver - Returns the receiver of the message expression. /// This can be NULL if the message is for class methods. For /// class methods, use getClassName. /// FIXME: need to handle/detect 'super' usage within a class method. - Expr *getReceiver() { + Expr *getReceiver() { uintptr_t x = (uintptr_t) SubExprs[RECEIVER]; return (x & Flags) == IsInstMeth ? (Expr*) x : 0; - } + } const Expr *getReceiver() const { return const_cast(this)->getReceiver(); } @@ -405,36 +405,36 @@ public: void setReceiver(Expr *rec) { SubExprs[RECEIVER] = rec; } Selector getSelector() const { return SelName; } void setSelector(Selector S) { SelName = S; } - + const ObjCMethodDecl *getMethodDecl() const { return MethodProto; } ObjCMethodDecl *getMethodDecl() { return MethodProto; } void setMethodDecl(ObjCMethodDecl *MD) { MethodProto = MD; } - + typedef std::pair ClassInfo; - + /// getClassInfo - For class methods, this returns both the ObjCInterfaceDecl* /// and IdentifierInfo* of the invoked class. Both can be NULL if this /// is an instance message, and the ObjCInterfaceDecl* can be NULL if none - /// was available when this ObjCMessageExpr object was constructed. - ClassInfo getClassInfo() const; + /// was available when this ObjCMessageExpr object was constructed. + ClassInfo getClassInfo() const; void setClassInfo(const ClassInfo &C); - + /// getClassName - For class methods, this returns the invoked class, - /// and returns NULL otherwise. For instance methods, use getReceiver. + /// and returns NULL otherwise. For instance methods, use getReceiver. IdentifierInfo *getClassName() const { return getClassInfo().second; } - + /// getNumArgs - Return the number of actual arguments to this call. unsigned getNumArgs() const { return NumArgs; } - void setNumArgs(unsigned nArgs) { - NumArgs = nArgs; + void setNumArgs(unsigned nArgs) { + NumArgs = nArgs; // FIXME: should always allocate SubExprs via the ASTContext's // allocator. if (!SubExprs) SubExprs = new Stmt* [NumArgs + 1]; } - + /// getArg - Return the specified argument. Expr *getArg(unsigned Arg) { assert(Arg < NumArgs && "Arg access out of range!"); @@ -449,13 +449,13 @@ public: assert(Arg < NumArgs && "Arg access out of range!"); SubExprs[Arg+ARGS_START] = ArgExpr; } - + SourceLocation getLeftLoc() const { return LBracloc; } SourceLocation getRightLoc() const { return RBracloc; } void setLeftLoc(SourceLocation L) { LBracloc = L; } void setRightLoc(SourceLocation L) { RBracloc = L; } - + void setSourceRange(SourceRange R) { LBracloc = R.getBegin(); RBracloc = R.getEnd(); @@ -468,14 +468,14 @@ public: return T->getStmtClass() == ObjCMessageExprClass; } static bool classof(const ObjCMessageExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); - + typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; - + arg_iterator arg_begin() { return &SubExprs[ARGS_START]; } arg_iterator arg_end() { return &SubExprs[ARGS_START] + NumArgs; } const_arg_iterator arg_begin() const { return &SubExprs[ARGS_START]; } @@ -487,16 +487,16 @@ public: class ObjCSuperExpr : public Expr { SourceLocation Loc; public: - ObjCSuperExpr(SourceLocation L, QualType Type) + ObjCSuperExpr(SourceLocation L, QualType Type) : Expr(ObjCSuperExprClass, Type), Loc(L) { } explicit ObjCSuperExpr(EmptyShell Empty) : Expr(ObjCSuperExprClass, Empty) {} SourceLocation getLoc() const { return Loc; } void setLoc(SourceLocation L) { Loc = L; } - + virtual SourceRange getSourceRange() const { return SourceRange(Loc); } - static bool classof(const Stmt *T) { + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCSuperExprClass; } static bool classof(const ObjCSuperExpr *) { return true; } @@ -511,23 +511,23 @@ public: class ObjCIsaExpr : public Expr { /// Base - the expression for the base object pointer. Stmt *Base; - + /// IsaMemberLoc - This is the location of the 'isa'. SourceLocation IsaMemberLoc; - + /// IsArrow - True if this is "X->F", false if this is "X.F". bool IsArrow; public: - ObjCIsaExpr(Expr *base, bool isarrow, SourceLocation l, QualType ty) + ObjCIsaExpr(Expr *base, bool isarrow, SourceLocation l, QualType ty) : Expr(ObjCIsaExprClass, ty), Base(base), IsaMemberLoc(l), IsArrow(isarrow) {} - + /// \brief Build an empty expression. explicit ObjCIsaExpr(EmptyShell Empty) : Expr(ObjCIsaExprClass, Empty) { } - + void setBase(Expr *E) { Base = E; } Expr *getBase() const { return cast(Base); } - + bool isArrow() const { return IsArrow; } void setArrow(bool A) { IsArrow = A; } @@ -539,14 +539,14 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(getBase()->getLocStart(), IsaMemberLoc); } - + virtual SourceLocation getExprLoc() const { return IsaMemberLoc; } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ObjCIsaExprClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ObjCIsaExprClass; } static bool classof(const ObjCIsaExpr *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); diff --git a/clang/include/clang/AST/ExternalASTSource.h b/clang/include/clang/AST/ExternalASTSource.h index 6f862a55d4bad9f8e510b3897cc90546ee9a391c..0670d1a620945b5223841a2bb664e98e6784f6e7 100644 --- a/clang/include/clang/AST/ExternalASTSource.h +++ b/clang/include/clang/AST/ExternalASTSource.h @@ -33,7 +33,7 @@ struct VisibleDeclaration { /// \brief The name of the declarations. DeclarationName Name; - /// \brief The ID numbers of all of the declarations with this name. + /// \brief The ID numbers of all of the declarations with this name. /// /// These declarations have not necessarily been de-serialized. llvm::SmallVector Declarations; @@ -65,7 +65,7 @@ public: /// replaced with the sorted set of source ranges corresponding to /// comments in the source code. virtual void ReadComments(std::vector &Comments) = 0; - + /// \brief Resolve a type ID into a type, potentially building a new /// type. virtual QualType GetType(uint32_t ID) = 0; @@ -151,7 +151,7 @@ public: this->Ptr = reinterpret_cast(Ptr); return *this; } - + LazyOffsetPtr &operator=(uint64_t Offset) { assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits"); if (Offset == 0) @@ -177,7 +177,7 @@ public: /// \returns a pointer to the AST node. T* get(ExternalASTSource *Source) const { if (isOffset()) { - assert(Source && + assert(Source && "Cannot deserialize a lazy pointer without an AST source"); Ptr = reinterpret_cast((Source->*Get)(Ptr >> 1)); } diff --git a/clang/include/clang/AST/NestedNameSpecifier.h b/clang/include/clang/AST/NestedNameSpecifier.h index 5c76064ae1392e6ed5111add0e131b5f494057da..1594b090fea5d10a0798e140cc24cb132e525843 100644 --- a/clang/include/clang/AST/NestedNameSpecifier.h +++ b/clang/include/clang/AST/NestedNameSpecifier.h @@ -81,8 +81,8 @@ private: /// \brief Copy constructor used internally to clone nested name /// specifiers. - NestedNameSpecifier(const NestedNameSpecifier &Other) - : llvm::FoldingSetNode(Other), Prefix(Other.Prefix), + NestedNameSpecifier(const NestedNameSpecifier &Other) + : llvm::FoldingSetNode(Other), Prefix(Other.Prefix), Specifier(Other.Specifier) { } @@ -90,7 +90,7 @@ private: /// \brief Either find or insert the given nested name specifier /// mockup in the given context. - static NestedNameSpecifier *FindOrInsert(ASTContext &Context, + static NestedNameSpecifier *FindOrInsert(ASTContext &Context, const NestedNameSpecifier &Mockup); public: @@ -99,18 +99,18 @@ public: /// The prefix must be dependent, since nested name specifiers /// referencing an identifier are only permitted when the identifier /// cannot be resolved. - static NestedNameSpecifier *Create(ASTContext &Context, - NestedNameSpecifier *Prefix, + static NestedNameSpecifier *Create(ASTContext &Context, + NestedNameSpecifier *Prefix, IdentifierInfo *II); /// \brief Builds a nested name specifier that names a namespace. - static NestedNameSpecifier *Create(ASTContext &Context, - NestedNameSpecifier *Prefix, + static NestedNameSpecifier *Create(ASTContext &Context, + NestedNameSpecifier *Prefix, NamespaceDecl *NS); /// \brief Builds a nested name specifier that names a type. - static NestedNameSpecifier *Create(ASTContext &Context, - NestedNameSpecifier *Prefix, + static NestedNameSpecifier *Create(ASTContext &Context, + NestedNameSpecifier *Prefix, bool Template, Type *T); /// \brief Builds a specifier that consists of just an identifier. @@ -120,7 +120,7 @@ public: /// nested name specifier, e.g., in "x->Base::f", the "x" has a dependent /// type. static NestedNameSpecifier *Create(ASTContext &Context, IdentifierInfo *II); - + /// \brief Returns the nested name specifier representing the global /// scope. static NestedNameSpecifier *GlobalSpecifier(ASTContext &Context); @@ -135,10 +135,10 @@ public: NestedNameSpecifier *getPrefix() const { return Prefix.getPointer(); } /// \brief Determine what kind of nested name specifier is stored. - SpecifierKind getKind() const { + SpecifierKind getKind() const { if (Specifier == 0) return Global; - return (SpecifierKind)Prefix.getInt(); + return (SpecifierKind)Prefix.getInt(); } /// \brief Retrieve the identifier stored in this nested name @@ -149,7 +149,7 @@ public: return 0; } - + /// \brief Retrieve the namespace stored in this nested name /// specifier. NamespaceDecl *getAsNamespace() const { @@ -161,7 +161,7 @@ public: /// \brief Retrieve the type stored in this nested name specifier. Type *getAsType() const { - if (Prefix.getInt() == TypeSpec || + if (Prefix.getInt() == TypeSpec || Prefix.getInt() == TypeSpecWithTemplate) return (Type *)Specifier; @@ -192,11 +192,11 @@ public: /// into a diagnostic with <<. inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, NestedNameSpecifier *NNS) { - DB.AddTaggedVal(reinterpret_cast(NNS), + DB.AddTaggedVal(reinterpret_cast(NNS), Diagnostic::ak_nestednamespec); return DB; } - + } #endif diff --git a/clang/include/clang/AST/ParentMap.h b/clang/include/clang/AST/ParentMap.h index c669991ccc088ff099b36159114de4f51366fa33..f826e1117b66c73595d710dc13dc477b9eec796b 100644 --- a/clang/include/clang/AST/ParentMap.h +++ b/clang/include/clang/AST/ParentMap.h @@ -17,7 +17,7 @@ namespace clang { class Stmt; class Expr; - + class ParentMap { void* Impl; public: @@ -30,7 +30,7 @@ public: const Stmt *getParent(const Stmt* S) const { return getParent(const_cast(S)); } - + const Stmt *getParentIgnoreParens(const Stmt *S) const { return getParentIgnoreParens(const_cast(S)); } @@ -38,13 +38,13 @@ public: bool hasParent(Stmt* S) const { return getParent(S) != 0; } - + bool isConsumedExpr(Expr *E) const; - + bool isConsumedExpr(const Expr *E) const { return isConsumedExpr(const_cast(E)); } }; - + } // end clang namespace #endif diff --git a/clang/include/clang/AST/PrettyPrinter.h b/clang/include/clang/AST/PrettyPrinter.h index bc4c82f2be62b99360f4d55a33a81bdebd165915..0635ec5dcd51e35b9d69676b2e09fe7f787575eb 100644 --- a/clang/include/clang/AST/PrettyPrinter.h +++ b/clang/include/clang/AST/PrettyPrinter.h @@ -34,7 +34,7 @@ public: /// declarations should be printed. struct PrintingPolicy { /// \brief Create a default printing policy for C. - PrintingPolicy(const LangOptions &LO) + PrintingPolicy(const LangOptions &LO) : Indentation(2), LangOpts(LO), SuppressSpecifiers(false), SuppressTag(false), SuppressTagKind(false), SuppressScope(false), Dump(false), ConstantArraySizeAsWritten(false) { } diff --git a/clang/include/clang/AST/RecordLayout.h b/clang/include/clang/AST/RecordLayout.h index 77e8553d748596e239e6644c5df976e494d669bd..66792d715d76cfbb33b1f650f5185b50a794790a 100644 --- a/clang/include/clang/AST/RecordLayout.h +++ b/clang/include/clang/AST/RecordLayout.h @@ -22,38 +22,38 @@ namespace clang { class RecordDecl; class CXXRecordDecl; -/// ASTRecordLayout - +/// ASTRecordLayout - /// This class contains layout information for one RecordDecl, /// which is a struct/union/class. The decl represented must be a definition, -/// not a forward declaration. -/// This class is also used to contain layout information for one +/// not a forward declaration. +/// This class is also used to contain layout information for one /// ObjCInterfaceDecl. FIXME - Find appropriate name. /// These objects are managed by ASTContext. class ASTRecordLayout { /// Size - Size of record in bits. uint64_t Size; - + /// DataSize - Size of record in bits without tail padding. uint64_t DataSize; - + /// FieldOffsets - Array of field offsets in bits. uint64_t *FieldOffsets; - + // Alignment - Alignment of record in bits. - unsigned Alignment; - + unsigned Alignment; + // FieldCount - Number of fields. unsigned FieldCount; struct CXXRecordLayoutInfo { - /// NonVirtualSize - The non-virtual size (in bits) of an object, which is + /// NonVirtualSize - The non-virtual size (in bits) of an object, which is /// the size of the object without virtual bases. uint64_t NonVirtualSize; - + /// NonVirtualAlign - The non-virtual alignment (in bits) of an object, /// which is the alignment of the object without virtual bases. uint64_t NonVirtualAlign; - + /// PrimaryBase - The primary base for our vtable. const CXXRecordDecl *PrimaryBase; /// PrimaryBase - Wether or not the primary base was a virtual base. @@ -67,16 +67,16 @@ class ASTRecordLayout { /// FIXME: This should really use a SmallPtrMap, once we have one in LLVM :) llvm::DenseMap VBaseOffsets; }; - - /// CXXInfo - If the record layout is for a C++ record, this will have + + /// CXXInfo - If the record layout is for a C++ record, this will have /// C++ specific information about the record. CXXRecordLayoutInfo *CXXInfo; - + friend class ASTContext; friend class ASTRecordLayoutBuilder; ASTRecordLayout(uint64_t size, unsigned alignment, unsigned datasize, - const uint64_t *fieldoffsets, unsigned fieldcount) + const uint64_t *fieldoffsets, unsigned fieldcount) : Size(size), DataSize(datasize), FieldOffsets(0), Alignment(alignment), FieldCount(fieldcount), CXXInfo(0) { if (FieldCount > 0) { @@ -85,7 +85,7 @@ class ASTRecordLayout { FieldOffsets[i] = fieldoffsets[i]; } } - + // Constructor for C++ records. ASTRecordLayout(uint64_t size, unsigned alignment, uint64_t datasize, const uint64_t *fieldoffsets, unsigned fieldcount, @@ -101,7 +101,7 @@ class ASTRecordLayout { for (unsigned i = 0; i < FieldCount; ++i) FieldOffsets[i] = fieldoffsets[i]; } - + CXXInfo->PrimaryBase = PB; CXXInfo->PrimaryBaseWasVirtual = PBVirtual; CXXInfo->NonVirtualSize = nonvirtualsize; @@ -111,7 +111,7 @@ class ASTRecordLayout { for (unsigned i = 0; i != vbasecount; ++i) CXXInfo->VBaseOffsets[vbases[i]] = vbaseoffsets[i]; } - + ~ASTRecordLayout() { delete [] FieldOffsets; delete CXXInfo; @@ -120,55 +120,55 @@ class ASTRecordLayout { ASTRecordLayout(const ASTRecordLayout&); // DO NOT IMPLEMENT void operator=(const ASTRecordLayout&); // DO NOT IMPLEMENT public: - + /// getAlignment - Get the record alignment in bits. unsigned getAlignment() const { return Alignment; } /// getSize - Get the record size in bits. uint64_t getSize() const { return Size; } - + /// getFieldCount - Get the number of fields in the layout. unsigned getFieldCount() const { return FieldCount; } - + /// getFieldOffset - Get the offset of the given field index, in /// bits. uint64_t getFieldOffset(unsigned FieldNo) const { assert (FieldNo < FieldCount && "Invalid Field No"); return FieldOffsets[FieldNo]; } - + /// getDataSize() - Get the record data size, which is the record size /// without tail padding, in bits. uint64_t getDataSize() const { return DataSize; } - - /// getNonVirtualSize - Get the non-virtual size (in bits) of an object, + + /// getNonVirtualSize - Get the non-virtual size (in bits) of an object, /// which is the size of the object without virtual bases. - uint64_t getNonVirtualSize() const { + uint64_t getNonVirtualSize() const { assert(CXXInfo && "Record layout does not have C++ specific info!"); - + return CXXInfo->NonVirtualSize; } - + /// getNonVirtualSize - Get the non-virtual alignment (in bits) of an object, /// which is the alignment of the object without virtual bases. unsigned getNonVirtualAlign() const { assert(CXXInfo && "Record layout does not have C++ specific info!"); - + return CXXInfo->NonVirtualAlign; } - + /// getPrimaryBase - Get the primary base. const CXXRecordDecl *getPrimaryBase() const { assert(CXXInfo && "Record layout does not have C++ specific info!"); - + return CXXInfo->PrimaryBase; } /// getPrimaryBaseWasVirtual - Indicates if the primary base was virtual. bool getPrimaryBaseWasVirtual() const { assert(CXXInfo && "Record layout does not have C++ specific info!"); - + return CXXInfo->PrimaryBaseWasVirtual; } @@ -176,7 +176,7 @@ public: uint64_t getBaseClassOffset(const CXXRecordDecl *Base) const { assert(CXXInfo && "Record layout does not have C++ specific info!"); assert(CXXInfo->BaseOffsets.count(Base) && "Did not find base!"); - + return CXXInfo->BaseOffsets[Base]; } @@ -184,7 +184,7 @@ public: uint64_t getVBaseClassOffset(const CXXRecordDecl *VBase) const { assert(CXXInfo && "Record layout does not have C++ specific info!"); assert(CXXInfo->VBaseOffsets.count(VBase) && "Did not find base!"); - + return CXXInfo->VBaseOffsets[VBase]; } }; diff --git a/clang/include/clang/AST/Redeclarable.h b/clang/include/clang/AST/Redeclarable.h index ea36353bf25b097f2d170204d4beec21ec9c1be6..5cd50686c599a7514727fa6f6df1ead64d63ccdb 100644 --- a/clang/include/clang/AST/Redeclarable.h +++ b/clang/include/clang/AST/Redeclarable.h @@ -26,10 +26,10 @@ protected: struct DeclLink : public llvm::PointerIntPair { DeclLink(decl_type *D, bool isLatest) : llvm::PointerIntPair(D, isLatest) { } - + typedef llvm::PointerIntPair base_type; - bool NextIsPrevious() const { return base_type::getInt() == false; } + bool NextIsPrevious() const { return base_type::getInt() == false; } bool NextIsLatest() const { return base_type::getInt() == true; } decl_type *getNext() const { return base_type::getPointer(); } }; @@ -69,7 +69,7 @@ public: return const_cast( static_cast(this))->getPreviousDeclaration(); } - + /// \brief Return the first declaration of this declaration or itself if this /// is the only declaration. decl_type *getFirstDeclaration() { @@ -91,7 +91,7 @@ public: assert(First->RedeclLink.NextIsLatest() && "Expected first"); } else { // Make this first. - First = static_cast(this); + First = static_cast(this); } // First one will point to this one as latest. @@ -131,10 +131,10 @@ public: return tmp; } - friend bool operator==(redecl_iterator x, redecl_iterator y) { + friend bool operator==(redecl_iterator x, redecl_iterator y) { return x.Current == y.Current; } - friend bool operator!=(redecl_iterator x, redecl_iterator y) { + friend bool operator!=(redecl_iterator x, redecl_iterator y) { return x.Current != y.Current; } }; diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h index f34776373b2c6c478e0e2685d87046905256fdca..125279c1eda17d993cbeeae4488988382adb3f8c 100644 --- a/clang/include/clang/AST/Stmt.h +++ b/clang/include/clang/AST/Stmt.h @@ -39,21 +39,21 @@ namespace clang { class SourceManager; class StringLiteral; class SwitchStmt; - + //===----------------------------------------------------------------------===// // ExprIterator - Iterators for iterating over Stmt* arrays that contain // only Expr*. This is needed because AST nodes use Stmt* arrays to store // references to children (to be compatible with StmtIterator). //===----------------------------------------------------------------------===// - + class Stmt; class Expr; - + class ExprIterator { Stmt** I; public: ExprIterator(Stmt** i) : I(i) {} - ExprIterator() : I(0) {} + ExprIterator() : I(0) {} ExprIterator& operator++() { ++I; return *this; } ExprIterator operator-(size_t i) { return I-i; } ExprIterator operator+(size_t i) { return I+i; } @@ -67,12 +67,12 @@ namespace clang { bool operator>(const ExprIterator& R) const { return I > R.I; } bool operator>=(const ExprIterator& R) const { return I >= R.I; } }; - + class ConstExprIterator { Stmt* const * I; public: ConstExprIterator(Stmt* const* i) : I(i) {} - ConstExprIterator() : I(0) {} + ConstExprIterator() : I(0) {} ConstExprIterator& operator++() { ++I; return *this; } ConstExprIterator operator+(size_t i) { return I+i; } ConstExprIterator operator-(size_t i) { return I-i; } @@ -84,12 +84,12 @@ namespace clang { bool operator!=(const ConstExprIterator& R) const { return I != R.I; } bool operator>(const ConstExprIterator& R) const { return I > R.I; } bool operator>=(const ConstExprIterator& R) const { return I >= R.I; } - }; - + }; + //===----------------------------------------------------------------------===// // AST classes for statements. //===----------------------------------------------------------------------===// - + /// Stmt - This represents one statement. /// class Stmt { @@ -106,7 +106,7 @@ public: private: /// \brief The statement class. const unsigned sClass : 8; - + /// \brief The reference count for this statement. unsigned RefCount : 24; @@ -119,20 +119,20 @@ protected: void operator delete(void* data) throw() { assert(0 && "Stmts cannot be released with regular 'delete'."); } - + public: // Only allow allocation of Stmts using the allocator in ASTContext - // or by doing a placement new. + // or by doing a placement new. void* operator new(size_t bytes, ASTContext& C, unsigned alignment = 16) throw() { return ::operator new(bytes, C, alignment); } - + void* operator new(size_t bytes, ASTContext* C, unsigned alignment = 16) throw() { return ::operator new(bytes, *C, alignment); } - + void* operator new(size_t bytes, void* mem) throw() { return mem; } @@ -152,9 +152,9 @@ protected: /// DestroyChildren - Invoked by destructors of subclasses of Stmt to /// recursively release child AST nodes. void DestroyChildren(ASTContext& Ctx); - + /// \brief Construct an empty statement. - explicit Stmt(StmtClass SC, EmptyShell) : sClass(SC), RefCount(1) { + explicit Stmt(StmtClass SC, EmptyShell) : sClass(SC), RefCount(1) { if (Stmt::CollectingStats()) Stmt::addStmtClass(SC); } @@ -164,18 +164,18 @@ protected: /// Subclasses should override this method (not Destroy()) to /// provide class-specific destruction. virtual void DoDestroy(ASTContext &Ctx); - + public: - Stmt(StmtClass SC) : sClass(SC), RefCount(1) { + Stmt(StmtClass SC) : sClass(SC), RefCount(1) { if (Stmt::CollectingStats()) Stmt::addStmtClass(SC); } virtual ~Stmt() {} - + /// \brief Destroy the current statement and its children. - void Destroy(ASTContext &Ctx) { + void Destroy(ASTContext &Ctx) { assert(RefCount >= 1); if (--RefCount == 0) - DoDestroy(Ctx); + DoDestroy(Ctx); } /// \brief Increases the reference count for this statement. @@ -187,10 +187,10 @@ public: ++RefCount; return this; } - + StmtClass getStmtClass() const { return (StmtClass)sClass; } const char *getStmtClassName() const; - + /// SourceLocation tokens are not useful in isolation - they are low level /// value objects created/interpreted by SourceManager. We assume AST /// clients will have a pointer to the respective SourceManager. @@ -216,23 +216,23 @@ public: /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST /// back to its original source language syntax. void dumpPretty(ASTContext& Context) const; - void printPretty(llvm::raw_ostream &OS, PrinterHelper *Helper, + void printPretty(llvm::raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation = 0) const { printPretty(OS, *(ASTContext*)0, Helper, Policy, Indentation); } void printPretty(llvm::raw_ostream &OS, ASTContext &Context, - PrinterHelper *Helper, + PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation = 0) const; - + /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only /// works on systems with GraphViz (Mac OS X) or dot+gv installed. void viewAST() const; - + // Implement isa support. - static bool classof(const Stmt *) { return true; } - + static bool classof(const Stmt *) { return true; } + /// hasImplicitControlFlow - Some statements (e.g. short circuited operations) /// contain implicit control-flow in the order their subexpressions /// are evaluated. This predicate returns true if this statement has @@ -245,14 +245,14 @@ public: /// AST node. This permits easy iteration over all nodes in the AST. typedef StmtIterator child_iterator; typedef ConstStmtIterator const_child_iterator; - + virtual child_iterator child_begin() = 0; virtual child_iterator child_end() = 0; - + const_child_iterator child_begin() const { return const_child_iterator(const_cast(this)->child_begin()); } - + const_child_iterator child_end() const { return const_child_iterator(const_cast(this)->child_end()); } @@ -266,7 +266,7 @@ public: /// /// \brief Canonical whether the profile should be based on the canonical /// representation of this statement (e.g., where non-type template - /// parameters are identified by index/level rather than their + /// parameters are identified by index/level rather than their /// declaration pointers) or the exact representation of the statement as /// written in the source. void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, @@ -275,18 +275,18 @@ public: /// DeclStmt - Adaptor class for mixing declarations with statements and /// expressions. For example, CompoundStmt mixes statements, expressions -/// and declarations (variables, types). Another example is ForStmt, where +/// and declarations (variables, types). Another example is ForStmt, where /// the first statement can be an expression or a declaration. /// class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; - + public: - DeclStmt(DeclGroupRef dg, SourceLocation startLoc, + DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {} - + /// \brief Build an empty declaration statement. explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) { } @@ -295,10 +295,10 @@ public: bool isSingleDecl() const { return DG.isSingleDecl(); } - + const Decl *getSingleDecl() const { return DG.getSingleDecl(); } - Decl *getSingleDecl() { return DG.getSingleDecl(); } - + Decl *getSingleDecl() { return DG.getSingleDecl(); } + const DeclGroupRef getDeclGroup() const { return DG; } DeclGroupRef getDeclGroup() { return DG; } void setDeclGroup(DeclGroupRef DGR) { DG = DGR; } @@ -311,19 +311,19 @@ public: SourceRange getSourceRange() const { return SourceRange(StartLoc, EndLoc); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == DeclStmtClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == DeclStmtClass; } static bool classof(const DeclStmt *) { return true; } - + // Iterators over subexpressions. virtual child_iterator child_begin(); virtual child_iterator child_end(); - + typedef DeclGroupRef::iterator decl_iterator; typedef DeclGroupRef::const_iterator const_decl_iterator; - + decl_iterator decl_begin() { return DG.begin(); } decl_iterator decl_end() { return DG.end(); } const_decl_iterator decl_begin() const { return DG.begin(); } @@ -344,12 +344,12 @@ public: void setSemiLoc(SourceLocation L) { SemiLoc = L; } virtual SourceRange getSourceRange() const { return SourceRange(SemiLoc); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == NullStmtClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == NullStmtClass; } static bool classof(const NullStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -362,24 +362,24 @@ class CompoundStmt : public Stmt { unsigned NumStmts; SourceLocation LBracLoc, RBracLoc; public: - CompoundStmt(ASTContext& C, Stmt **StmtStart, unsigned numStmts, + CompoundStmt(ASTContext& C, Stmt **StmtStart, unsigned numStmts, SourceLocation LB, SourceLocation RB) : Stmt(CompoundStmtClass), NumStmts(numStmts), LBracLoc(LB), RBracLoc(RB) { if (NumStmts == 0) { Body = 0; return; } - + Body = new (C) Stmt*[NumStmts]; memcpy(Body, StmtStart, numStmts * sizeof(*Body)); - } + } // \brief Build an empty compound statement. explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty), Body(0), NumStmts(0) { } void setStmts(ASTContext &C, Stmt **Stmts, unsigned NumStmts); - + bool body_empty() const { return NumStmts == 0; } unsigned size() const { return NumStmts; } @@ -407,25 +407,25 @@ public: const_reverse_body_iterator body_rbegin() const { return const_reverse_body_iterator(body_end()); } - + const_reverse_body_iterator body_rend() const { return const_reverse_body_iterator(body_begin()); } - - virtual SourceRange getSourceRange() const { - return SourceRange(LBracLoc, RBracLoc); + + virtual SourceRange getSourceRange() const { + return SourceRange(LBracLoc, RBracLoc); } - + SourceLocation getLBracLoc() const { return LBracLoc; } void setLBracLoc(SourceLocation L) { LBracLoc = L; } SourceLocation getRBracLoc() const { return RBracLoc; } void setRBracLoc(SourceLocation L) { RBracLoc = L; } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == CompoundStmtClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == CompoundStmtClass; } static bool classof(const CompoundStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -439,7 +439,7 @@ protected: SwitchCase *NextSwitchCase; SwitchCase(StmtClass SC) : Stmt(SC), NextSwitchCase(0) {} - + public: const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; } @@ -450,19 +450,19 @@ public: Stmt *getSubStmt() { return v_getSubStmt(); } virtual SourceRange getSourceRange() const { return SourceRange(); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == CaseStmtClass || + + static bool classof(const Stmt *T) { + return T->getStmtClass() == CaseStmtClass || T->getStmtClass() == DefaultStmtClass; } static bool classof(const SwitchCase *) { return true; } protected: - virtual Stmt* v_getSubStmt() = 0; + virtual Stmt* v_getSubStmt() = 0; }; class CaseStmt : public SwitchCase { enum { SUBSTMT, LHS, RHS, END_EXPR }; - Stmt* SubExprs[END_EXPR]; // The expression for the RHS is Non-null for + Stmt* SubExprs[END_EXPR]; // The expression for the RHS is Non-null for // GNU "case 1 ... 4" extension SourceLocation CaseLoc; SourceLocation EllipsisLoc; @@ -471,7 +471,7 @@ class CaseStmt : public SwitchCase { virtual Stmt* v_getSubStmt() { return getSubStmt(); } public: CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc, - SourceLocation ellipsisLoc, SourceLocation colonLoc) + SourceLocation ellipsisLoc, SourceLocation colonLoc) : SwitchCase(CaseStmtClass) { SubExprs[SUBSTMT] = 0; SubExprs[LHS] = reinterpret_cast(lhs); @@ -495,32 +495,32 @@ public: Expr *getRHS() { return reinterpret_cast(SubExprs[RHS]); } Stmt *getSubStmt() { return SubExprs[SUBSTMT]; } - const Expr *getLHS() const { - return reinterpret_cast(SubExprs[LHS]); + const Expr *getLHS() const { + return reinterpret_cast(SubExprs[LHS]); } - const Expr *getRHS() const { - return reinterpret_cast(SubExprs[RHS]); + const Expr *getRHS() const { + return reinterpret_cast(SubExprs[RHS]); } const Stmt *getSubStmt() const { return SubExprs[SUBSTMT]; } void setSubStmt(Stmt *S) { SubExprs[SUBSTMT] = S; } void setLHS(Expr *Val) { SubExprs[LHS] = reinterpret_cast(Val); } void setRHS(Expr *Val) { SubExprs[RHS] = reinterpret_cast(Val); } - - + + virtual SourceRange getSourceRange() const { // Handle deeply nested case statements with iteration instead of recursion. const CaseStmt *CS = this; while (const CaseStmt *CS2 = dyn_cast(CS->getSubStmt())) CS = CS2; - - return SourceRange(CaseLoc, CS->getSubStmt()->getLocEnd()); + + return SourceRange(CaseLoc, CS->getSubStmt()->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == CaseStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == CaseStmtClass; } static bool classof(const CaseStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -532,7 +532,7 @@ class DefaultStmt : public SwitchCase { SourceLocation ColonLoc; virtual Stmt* v_getSubStmt() { return getSubStmt(); } public: - DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt) : + DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt) : SwitchCase(DefaultStmtClass), SubStmt(substmt), DefaultLoc(DL), ColonLoc(CL) {} @@ -548,14 +548,14 @@ public: SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } - virtual SourceRange getSourceRange() const { - return SourceRange(DefaultLoc, SubStmt->getLocEnd()); + virtual SourceRange getSourceRange() const { + return SourceRange(DefaultLoc, SubStmt->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == DefaultStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == DefaultStmtClass; } static bool classof(const DefaultStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -566,13 +566,13 @@ class LabelStmt : public Stmt { Stmt *SubStmt; SourceLocation IdentLoc; public: - LabelStmt(SourceLocation IL, IdentifierInfo *label, Stmt *substmt) - : Stmt(LabelStmtClass), Label(label), + LabelStmt(SourceLocation IL, IdentifierInfo *label, Stmt *substmt) + : Stmt(LabelStmtClass), Label(label), SubStmt(substmt), IdentLoc(IL) {} // \brief Build an empty label statement. explicit LabelStmt(EmptyShell Empty) : Stmt(LabelStmtClass, Empty) { } - + SourceLocation getIdentLoc() const { return IdentLoc; } IdentifierInfo *getID() const { return Label; } void setID(IdentifierInfo *II) { Label = II; } @@ -582,14 +582,14 @@ public: void setIdentLoc(SourceLocation L) { IdentLoc = L; } void setSubStmt(Stmt *SS) { SubStmt = SS; } - virtual SourceRange getSourceRange() const { - return SourceRange(IdentLoc, SubStmt->getLocEnd()); - } - static bool classof(const Stmt *T) { - return T->getStmtClass() == LabelStmtClass; + virtual SourceRange getSourceRange() const { + return SourceRange(IdentLoc, SubStmt->getLocEnd()); + } + static bool classof(const Stmt *T) { + return T->getStmtClass() == LabelStmtClass; } static bool classof(const LabelStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -604,8 +604,8 @@ class IfStmt : public Stmt { SourceLocation IfLoc; SourceLocation ElseLoc; public: - IfStmt(SourceLocation IL, Expr *cond, Stmt *then, - SourceLocation EL = SourceLocation(), Stmt *elsev = 0) + IfStmt(SourceLocation IL, Expr *cond, Stmt *then, + SourceLocation EL = SourceLocation(), Stmt *elsev = 0) : Stmt(IfStmtClass) { SubExprs[COND] = reinterpret_cast(cond); SubExprs[THEN] = then; @@ -613,14 +613,14 @@ public: IfLoc = IL; ElseLoc = EL; } - + /// \brief Build an empty if/then/else statement explicit IfStmt(EmptyShell Empty) : Stmt(IfStmtClass, Empty) { } const Expr *getCond() const { return reinterpret_cast(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast(E); } const Stmt *getThen() const { return SubExprs[THEN]; } - void setThen(Stmt *S) { SubExprs[THEN] = S; } + void setThen(Stmt *S) { SubExprs[THEN] = S; } const Stmt *getElse() const { return SubExprs[ELSE]; } void setElse(Stmt *S) { SubExprs[ELSE] = S; } @@ -633,18 +633,18 @@ public: SourceLocation getElseLoc() const { return ElseLoc; } void setElseLoc(SourceLocation L) { ElseLoc = L; } - virtual SourceRange getSourceRange() const { + virtual SourceRange getSourceRange() const { if (SubExprs[ELSE]) return SourceRange(IfLoc, SubExprs[ELSE]->getLocEnd()); else return SourceRange(IfLoc, SubExprs[THEN]->getLocEnd()); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == IfStmtClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == IfStmtClass; } static bool classof(const IfStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -654,20 +654,20 @@ public: /// class SwitchStmt : public Stmt { enum { COND, BODY, END_EXPR }; - Stmt* SubExprs[END_EXPR]; + Stmt* SubExprs[END_EXPR]; // This points to a linked list of case and default statements. SwitchCase *FirstCase; SourceLocation SwitchLoc; - + protected: virtual void DoDestroy(ASTContext &Ctx); - + public: SwitchStmt(Expr *cond) : Stmt(SwitchStmtClass), FirstCase(0) { SubExprs[COND] = reinterpret_cast(cond); SubExprs[BODY] = NULL; } - + /// \brief Build a empty switch statement. explicit SwitchStmt(EmptyShell Empty) : Stmt(SwitchStmtClass, Empty) { } @@ -680,7 +680,7 @@ public: Stmt *getBody() { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SwitchCase *getSwitchCaseList() { return FirstCase; } - + /// \brief Set the case list for this switch statement. /// /// The caller is responsible for incrementing the retain counts on @@ -690,24 +690,24 @@ public: SourceLocation getSwitchLoc() const { return SwitchLoc; } void setSwitchLoc(SourceLocation L) { SwitchLoc = L; } - void setBody(Stmt *S, SourceLocation SL) { - SubExprs[BODY] = S; + void setBody(Stmt *S, SourceLocation SL) { + SubExprs[BODY] = S; SwitchLoc = SL; - } + } void addSwitchCase(SwitchCase *SC) { assert(!SC->getNextSwitchCase() && "case/default already added to a switch"); SC->Retain(); SC->setNextSwitchCase(FirstCase); FirstCase = SC; } - virtual SourceRange getSourceRange() const { - return SourceRange(SwitchLoc, SubExprs[BODY]->getLocEnd()); + virtual SourceRange getSourceRange() const { + return SourceRange(SwitchLoc, SubExprs[BODY]->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == SwitchStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == SwitchStmtClass; } static bool classof(const SwitchStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -726,7 +726,7 @@ public: SubExprs[BODY] = body; WhileLoc = WL; } - + /// \brief Build an empty while statement. explicit WhileStmt(EmptyShell Empty) : Stmt(WhileStmtClass, Empty) { } @@ -740,14 +740,14 @@ public: SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } - virtual SourceRange getSourceRange() const { - return SourceRange(WhileLoc, SubExprs[BODY]->getLocEnd()); + virtual SourceRange getSourceRange() const { + return SourceRange(WhileLoc, SubExprs[BODY]->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == WhileStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == WhileStmtClass; } static bool classof(const WhileStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -768,16 +768,16 @@ public: : Stmt(DoStmtClass), DoLoc(DL), WhileLoc(WL), RParenLoc(RP) { SubExprs[COND] = reinterpret_cast(cond); SubExprs[BODY] = body; - } + } /// \brief Build an empty do-while statement. explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) { } - + Expr *getCond() { return reinterpret_cast(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast(E); } Stmt *getBody() { return SubExprs[BODY]; } - const Stmt *getBody() const { return SubExprs[BODY]; } + const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getDoLoc() const { return DoLoc; } @@ -788,11 +788,11 @@ public: SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } - virtual SourceRange getSourceRange() const { - return SourceRange(DoLoc, RParenLoc); + virtual SourceRange getSourceRange() const { + return SourceRange(DoLoc, RParenLoc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == DoStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == DoStmtClass; } static bool classof(const DoStmt *) { return true; } @@ -814,7 +814,7 @@ class ForStmt : public Stmt { public: ForStmt(Stmt *Init, Expr *Cond, Expr *Inc, Stmt *Body, SourceLocation FL, - SourceLocation LP, SourceLocation RP) + SourceLocation LP, SourceLocation RP) : Stmt(ForStmtClass) { SubExprs[INIT] = Init; SubExprs[COND] = reinterpret_cast(Cond); @@ -824,7 +824,7 @@ public: LParenLoc = LP; RParenLoc = RP; } - + /// \brief Build an empty for statement. explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) { } @@ -850,19 +850,19 @@ public: SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } - virtual SourceRange getSourceRange() const { - return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd()); + virtual SourceRange getSourceRange() const { + return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ForStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ForStmtClass; } static bool classof(const ForStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + /// GotoStmt - This represents a direct goto. /// class GotoStmt : public Stmt { @@ -870,9 +870,9 @@ class GotoStmt : public Stmt { SourceLocation GotoLoc; SourceLocation LabelLoc; public: - GotoStmt(LabelStmt *label, SourceLocation GL, SourceLocation LL) + GotoStmt(LabelStmt *label, SourceLocation GL, SourceLocation LL) : Stmt(GotoStmtClass), Label(label), GotoLoc(GL), LabelLoc(LL) {} - + /// \brief Build an empty goto statement. explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) { } @@ -884,14 +884,14 @@ public: SourceLocation getLabelLoc() const { return LabelLoc; } void setLabelLoc(SourceLocation L) { LabelLoc = L; } - virtual SourceRange getSourceRange() const { - return SourceRange(GotoLoc, LabelLoc); + virtual SourceRange getSourceRange() const { + return SourceRange(GotoLoc, LabelLoc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == GotoStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == GotoStmtClass; } static bool classof(const GotoStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -904,20 +904,20 @@ class IndirectGotoStmt : public Stmt { SourceLocation StarLoc; Stmt *Target; public: - IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, + IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target) : Stmt(IndirectGotoStmtClass), GotoLoc(gotoLoc), StarLoc(starLoc), Target((Stmt*)target) {} /// \brief Build an empty indirect goto statement. - explicit IndirectGotoStmt(EmptyShell Empty) + explicit IndirectGotoStmt(EmptyShell Empty) : Stmt(IndirectGotoStmtClass, Empty) { } - + void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getGotoLoc() const { return GotoLoc; } void setStarLoc(SourceLocation L) { StarLoc = L; } SourceLocation getStarLoc() const { return StarLoc; } - + Expr *getTarget(); const Expr *getTarget() const; void setTarget(Expr *E) { Target = reinterpret_cast(E); } @@ -925,12 +925,12 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(GotoLoc, Target->getLocEnd()); } - - static bool classof(const Stmt *T) { - return T->getStmtClass() == IndirectGotoStmtClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == IndirectGotoStmtClass; } static bool classof(const IndirectGotoStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -943,22 +943,22 @@ class ContinueStmt : public Stmt { SourceLocation ContinueLoc; public: ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass), ContinueLoc(CL) {} - + /// \brief Build an empty continue statement. explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) { } SourceLocation getContinueLoc() const { return ContinueLoc; } void setContinueLoc(SourceLocation L) { ContinueLoc = L; } - virtual SourceRange getSourceRange() const { - return SourceRange(ContinueLoc); + virtual SourceRange getSourceRange() const { + return SourceRange(ContinueLoc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ContinueStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ContinueStmtClass; } static bool classof(const ContinueStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -970,7 +970,7 @@ class BreakStmt : public Stmt { SourceLocation BreakLoc; public: BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass), BreakLoc(BL) {} - + /// \brief Build an empty break statement. explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) { } @@ -979,11 +979,11 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(BreakLoc); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == BreakStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == BreakStmtClass; } static bool classof(const BreakStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1003,7 +1003,7 @@ class ReturnStmt : public Stmt { Stmt *RetExpr; SourceLocation RetLoc; public: - ReturnStmt(SourceLocation RL, Expr *E = 0) : Stmt(ReturnStmtClass), + ReturnStmt(SourceLocation RL, Expr *E = 0) : Stmt(ReturnStmtClass), RetExpr((Stmt*) E), RetLoc(RL) {} /// \brief Build an empty return expression. @@ -1017,12 +1017,12 @@ public: void setReturnLoc(SourceLocation L) { RetLoc = L; } virtual SourceRange getSourceRange() const; - - static bool classof(const Stmt *T) { - return T->getStmtClass() == ReturnStmtClass; + + static bool classof(const Stmt *T) { + return T->getStmtClass() == ReturnStmtClass; } static bool classof(const ReturnStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); @@ -1036,18 +1036,18 @@ class AsmStmt : public Stmt { bool IsSimple; bool IsVolatile; - + unsigned NumOutputs; unsigned NumInputs; - + llvm::SmallVector Names; llvm::SmallVector Constraints; llvm::SmallVector Exprs; llvm::SmallVector Clobbers; public: - AsmStmt(SourceLocation asmloc, bool issimple, bool isvolatile, - unsigned numoutputs, unsigned numinputs, + AsmStmt(SourceLocation asmloc, bool issimple, bool isvolatile, + unsigned numoutputs, unsigned numinputs, std::string *names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, SourceLocation rparenloc); @@ -1090,10 +1090,10 @@ public: : MyKind(Operand), Str(), OperandNo(OpNo) { Str += Modifier; } - + bool isString() const { return MyKind == String; } bool isOperand() const { return MyKind == Operand; } - + const std::string &getString() const { assert(isString()); return Str; @@ -1103,7 +1103,7 @@ public: assert(isOperand()); return OperandNo; } - + /// getModifier - Get the modifier for this operand, if present. This /// returns '\0' if there was no modifier. char getModifier() const { @@ -1111,16 +1111,16 @@ public: return Str[0]; } }; - + /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing /// it into pieces. If the asm string is erroneous, emit errors and return /// true, otherwise return false. This handles canonicalization and /// translation of strings from GCC syntax to LLVM IR syntax, and handles - //// flattening of named references like %[foo] to Operand AsmStringPiece's. + //// flattening of named references like %[foo] to Operand AsmStringPiece's. unsigned AnalyzeAsmString(llvm::SmallVectorImpl &Pieces, ASTContext &C, unsigned &DiagOffs) const; - - + + //===--- Output operands ---===// unsigned getNumOutputs() const { return NumOutputs; } @@ -1133,72 +1133,72 @@ public: /// output operand. All output constraints are known to be non-empty (either /// '=' or '+'). std::string getOutputConstraint(unsigned i) const; - + const StringLiteral *getOutputConstraintLiteral(unsigned i) const { return Constraints[i]; } StringLiteral *getOutputConstraintLiteral(unsigned i) { return Constraints[i]; } - - + + Expr *getOutputExpr(unsigned i); - + const Expr *getOutputExpr(unsigned i) const { return const_cast(this)->getOutputExpr(i); } - + /// isOutputPlusConstraint - Return true if the specified output constraint /// is a "+" constraint (which is both an input and an output) or false if it /// is an "=" constraint (just an output). bool isOutputPlusConstraint(unsigned i) const { return getOutputConstraint(i)[0] == '+'; } - + /// getNumPlusOperands - Return the number of output operands that have a "+" /// constraint. unsigned getNumPlusOperands() const; - + //===--- Input operands ---===// - - unsigned getNumInputs() const { return NumInputs; } - + + unsigned getNumInputs() const { return NumInputs; } + const std::string &getInputName(unsigned i) const { return Names[i + NumOutputs]; } - + /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. std::string getInputConstraint(unsigned i) const; - + const StringLiteral *getInputConstraintLiteral(unsigned i) const { return Constraints[i + NumOutputs]; } StringLiteral *getInputConstraintLiteral(unsigned i) { return Constraints[i + NumOutputs]; } - - + + Expr *getInputExpr(unsigned i); - + const Expr *getInputExpr(unsigned i) const { return const_cast(this)->getInputExpr(i); } void setOutputsAndInputs(unsigned NumOutputs, - unsigned NumInputs, + unsigned NumInputs, const std::string *Names, StringLiteral **Constraints, Stmt **Exprs); //===--- Other ---===// - + /// getNamedOperand - Given a symbolic operand reference like %[foo], /// translate this into a numeric value needed to reference the same operand. /// This returns -1 if the operand name is invalid. int getNamedOperand(const std::string &SymbolicName) const; - + unsigned getNumClobbers() const { return Clobbers.size(); } StringLiteral *getClobber(unsigned i) { return Clobbers[i]; } @@ -1208,62 +1208,62 @@ public: virtual SourceRange getSourceRange() const { return SourceRange(AsmLoc, RParenLoc); } - + static bool classof(const Stmt *T) {return T->getStmtClass() == AsmStmtClass;} static bool classof(const AsmStmt *) { return true; } - + // Input expr iterators. - + typedef ExprIterator inputs_iterator; typedef ConstExprIterator const_inputs_iterator; - + inputs_iterator begin_inputs() { return Exprs.data() + NumOutputs; } - + inputs_iterator end_inputs() { return Exprs.data() + NumOutputs + NumInputs; } - + const_inputs_iterator begin_inputs() const { return Exprs.data() + NumOutputs; } - + const_inputs_iterator end_inputs() const { return Exprs.data() + NumOutputs + NumInputs; } - + // Output expr iterators. - + typedef ExprIterator outputs_iterator; typedef ConstExprIterator const_outputs_iterator; - + outputs_iterator begin_outputs() { return Exprs.data(); } outputs_iterator end_outputs() { return Exprs.data() + NumOutputs; } - + const_outputs_iterator begin_outputs() const { return Exprs.data(); } const_outputs_iterator end_outputs() const { return Exprs.data() + NumOutputs; } - + // Input name iterator. - + const std::string *begin_output_names() const { return &Names[0]; } - + const std::string *end_output_names() const { return &Names[0] + NumOutputs; } - - // Child iterators - + + // Child iterators + virtual child_iterator child_begin(); virtual child_iterator child_end(); }; diff --git a/clang/include/clang/AST/StmtGraphTraits.h b/clang/include/clang/AST/StmtGraphTraits.h index 1bfac6a9587e8f75f219ca32dadb2eabf2df2515..25d015287b7576e4686a74b0927fd119b4676c8b 100644 --- a/clang/include/clang/AST/StmtGraphTraits.h +++ b/clang/include/clang/AST/StmtGraphTraits.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines a template specialization of llvm::GraphTraits to +// This file defines a template specialization of llvm::GraphTraits to // treat ASTs (Stmt*) as graphs // //===----------------------------------------------------------------------===// @@ -20,7 +20,7 @@ #include "llvm/ADT/DepthFirstIterator.h" namespace llvm { - + //template struct GraphTraits; @@ -28,23 +28,23 @@ template <> struct GraphTraits { typedef clang::Stmt NodeType; typedef clang::Stmt::child_iterator ChildIteratorType; typedef llvm::df_iterator nodes_iterator; - + static NodeType* getEntryNode(clang::Stmt* S) { return S; } - + static inline ChildIteratorType child_begin(NodeType* N) { if (N) return N->child_begin(); else return ChildIteratorType(); } - + static inline ChildIteratorType child_end(NodeType* N) { if (N) return N->child_end(); else return ChildIteratorType(); } - + static nodes_iterator nodes_begin(clang::Stmt* S) { return df_begin(S); } - + static nodes_iterator nodes_end(clang::Stmt* S) { return df_end(S); } @@ -55,29 +55,29 @@ template <> struct GraphTraits { typedef const clang::Stmt NodeType; typedef clang::Stmt::const_child_iterator ChildIteratorType; typedef llvm::df_iterator nodes_iterator; - + static NodeType* getEntryNode(const clang::Stmt* S) { return S; } - + static inline ChildIteratorType child_begin(NodeType* N) { if (N) return N->child_begin(); - else return ChildIteratorType(); + else return ChildIteratorType(); } - + static inline ChildIteratorType child_end(NodeType* N) { if (N) return N->child_end(); else return ChildIteratorType(); } - + static nodes_iterator nodes_begin(const clang::Stmt* S) { return df_begin(S); } - + static nodes_iterator nodes_end(const clang::Stmt* S) { return df_end(S); } }; - + } // end namespace llvm #endif diff --git a/clang/include/clang/AST/StmtIterator.h b/clang/include/clang/AST/StmtIterator.h index 2a4adc6f7939b3f76197f5ce771e8348c5f5ca53..2d523fffce740435c1e5f777f41517d94ceb405b 100644 --- a/clang/include/clang/AST/StmtIterator.h +++ b/clang/include/clang/AST/StmtIterator.h @@ -23,45 +23,45 @@ namespace clang { class Stmt; class Decl; class VariableArrayType; - + class StmtIteratorBase { protected: enum { DeclMode = 0x1, SizeOfTypeVAMode = 0x2, DeclGroupMode = 0x3, Flags = 0x3 }; - + union { Stmt** stmt; Decl* decl; Decl** DGI; }; - uintptr_t RawVAPtr; + uintptr_t RawVAPtr; Decl** DGE; bool inDecl() const { return (RawVAPtr & Flags) == DeclMode; } - + bool inDeclGroup() const { return (RawVAPtr & Flags) == DeclGroupMode; } - - bool inSizeOfTypeVA() const { + + bool inSizeOfTypeVA() const { return (RawVAPtr & Flags) == SizeOfTypeVAMode; } - + bool inStmt() const { return (RawVAPtr & Flags) == 0; } - + VariableArrayType* getVAPtr() const { return reinterpret_cast(RawVAPtr & ~Flags); } - + void setVAPtr(VariableArrayType* P) { - assert (inDecl() || inDeclGroup() || inSizeOfTypeVA()); + assert (inDecl() || inDeclGroup() || inSizeOfTypeVA()); RawVAPtr = reinterpret_cast(P) | (RawVAPtr & Flags); } - + void NextDecl(bool ImmediateAdvance = true); bool HandleDecl(Decl* D); void NextVA(); - + Stmt*& GetDeclExpr() const; StmtIteratorBase(Stmt** s) : stmt(s), RawVAPtr(0) {} @@ -70,22 +70,22 @@ protected: StmtIteratorBase(Decl** dgi, Decl** dge); StmtIteratorBase() : stmt(NULL), RawVAPtr(0) {} }; - - + + template -class StmtIteratorImpl : public StmtIteratorBase, +class StmtIteratorImpl : public StmtIteratorBase, public std::iterator { + REFERENCE, ptrdiff_t, + REFERENCE, REFERENCE> { protected: StmtIteratorImpl(const StmtIteratorBase& RHS) : StmtIteratorBase(RHS) {} public: - StmtIteratorImpl() {} + StmtIteratorImpl() {} StmtIteratorImpl(Stmt** s) : StmtIteratorBase(s) {} StmtIteratorImpl(Decl** dgi, Decl** dge) : StmtIteratorBase(dgi, dge) {} StmtIteratorImpl(Decl* d) : StmtIteratorBase(d) {} StmtIteratorImpl(VariableArrayType* t) : StmtIteratorBase(t) {} - + DERIVED& operator++() { if (inDecl() || inDeclGroup()) { if (getVAPtr()) NextVA(); @@ -95,36 +95,36 @@ public: NextVA(); else ++stmt; - + return static_cast(*this); } - + DERIVED operator++(int) { DERIVED tmp = static_cast(*this); operator++(); return tmp; } - + bool operator==(const DERIVED& RHS) const { return stmt == RHS.stmt && RawVAPtr == RHS.RawVAPtr; } - + bool operator!=(const DERIVED& RHS) const { return stmt != RHS.stmt || RawVAPtr != RHS.RawVAPtr; } - - REFERENCE operator*() const { + + REFERENCE operator*() const { return (REFERENCE) (inStmt() ? *stmt : GetDeclExpr()); } - - REFERENCE operator->() const { return operator*(); } + + REFERENCE operator->() const { return operator*(); } }; struct StmtIterator : public StmtIteratorImpl { explicit StmtIterator() : StmtIteratorImpl() {} StmtIterator(Stmt** S) : StmtIteratorImpl(S) {} - StmtIterator(Decl** dgi, Decl** dge) + StmtIterator(Decl** dgi, Decl** dge) : StmtIteratorImpl(dgi, dge) {} StmtIterator(VariableArrayType* t):StmtIteratorImpl(t) {} @@ -133,10 +133,10 @@ struct StmtIterator : public StmtIteratorImpl { struct ConstStmtIterator : public StmtIteratorImpl { - explicit ConstStmtIterator() : + explicit ConstStmtIterator() : StmtIteratorImpl() {} - - ConstStmtIterator(const StmtIterator& RHS) : + + ConstStmtIterator(const StmtIterator& RHS) : StmtIteratorImpl(RHS) {} }; diff --git a/clang/include/clang/AST/StmtObjC.h b/clang/include/clang/AST/StmtObjC.h index 8ae707174403aefe4abf6a27eb4744838c7eeeab..3fd8f1672deb2c662f528eafd75b5bd846c63437 100644 --- a/clang/include/clang/AST/StmtObjC.h +++ b/clang/include/clang/AST/StmtObjC.h @@ -27,47 +27,47 @@ class ObjCForCollectionStmt : public Stmt { SourceLocation ForLoc; SourceLocation RParenLoc; public: - ObjCForCollectionStmt(Stmt *Elem, Expr *Collect, Stmt *Body, + ObjCForCollectionStmt(Stmt *Elem, Expr *Collect, Stmt *Body, SourceLocation FCL, SourceLocation RPL); - explicit ObjCForCollectionStmt(EmptyShell Empty) : + explicit ObjCForCollectionStmt(EmptyShell Empty) : Stmt(ObjCForCollectionStmtClass, Empty) { } - + Stmt *getElement() { return SubExprs[ELEM]; } - Expr *getCollection() { - return reinterpret_cast(SubExprs[COLLECTION]); + Expr *getCollection() { + return reinterpret_cast(SubExprs[COLLECTION]); } Stmt *getBody() { return SubExprs[BODY]; } - + const Stmt *getElement() const { return SubExprs[ELEM]; } - const Expr *getCollection() const { + const Expr *getCollection() const { return reinterpret_cast(SubExprs[COLLECTION]); } const Stmt *getBody() const { return SubExprs[BODY]; } - + void setElement(Stmt *S) { SubExprs[ELEM] = S; } - void setCollection(Expr *E) { + void setCollection(Expr *E) { SubExprs[COLLECTION] = reinterpret_cast(E); } void setBody(Stmt *S) { SubExprs[BODY] = S; } - + SourceLocation getForLoc() const { return ForLoc; } void setForLoc(SourceLocation Loc) { ForLoc = Loc; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; } - - virtual SourceRange getSourceRange() const { - return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd()); + + virtual SourceRange getSourceRange() const { + return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd()); } - static bool classof(const Stmt *T) { - return T->getStmtClass() == ObjCForCollectionStmtClass; + static bool classof(const Stmt *T) { + return T->getStmtClass() == ObjCForCollectionStmtClass; } static bool classof(const ObjCForCollectionStmt *) { return true; } - + // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); -}; - +}; + /// ObjCAtCatchStmt - This represents objective-c's @catch statement. class ObjCAtCatchStmt : public Stmt { private: @@ -78,95 +78,95 @@ private: public: ObjCAtCatchStmt(SourceLocation atCatchLoc, SourceLocation rparenloc, - ParmVarDecl *catchVarDecl, + ParmVarDecl *catchVarDecl, Stmt *atCatchStmt, Stmt *atCatchList); - explicit ObjCAtCatchStmt(EmptyShell Empty) : + explicit ObjCAtCatchStmt(EmptyShell Empty) : Stmt(ObjCAtCatchStmtClass, Empty) { } - + const Stmt *getCatchBody() const { return SubExprs[BODY]; } Stmt *getCatchBody() { return SubExprs[BODY]; } void setCatchBody(Stmt *S) { SubExprs[BODY] = S; } - + const ObjCAtCatchStmt *getNextCatchStmt() const { return static_cast(SubExprs[NEXT_CATCH]); } - ObjCAtCatchStmt *getNextCatchStmt() { + ObjCAtCatchStmt *getNextCatchStmt() { return static_cast(SubExprs[NEXT_CATCH]); } void setNextCatchStmt(Stmt *S) { SubExprs[NEXT_CATCH] = S; } - - const ParmVarDecl *getCatchParamDecl() const { - return ExceptionDecl; + + const ParmVarDecl *getCatchParamDecl() const { + return ExceptionDecl; } - ParmVarDecl *getCatchParamDecl() { - return ExceptionDecl; + ParmVarDecl *getCatchParamDecl() { + return ExceptionDecl; } void setCatchParamDecl(ParmVarDecl *D) { ExceptionDecl = D; } - + SourceLocation getAtCatchLoc() const { return AtCatchLoc; } void setAtCatchLoc(SourceLocation Loc) { AtCatchLoc = Loc; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; } - - virtual SourceRange getSourceRange() const { - return SourceRange(AtCatchLoc, SubExprs[BODY]->getLocEnd()); + + virtual SourceRange getSourceRange() const { + return SourceRange(AtCatchLoc, SubExprs[BODY]->getLocEnd()); } bool hasEllipsis() const { return getCatchParamDecl() == 0; } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtCatchStmtClass; } static bool classof(const ObjCAtCatchStmt *) { return true; } - + virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - -/// ObjCAtFinallyStmt - This represent objective-c's @finally Statement + +/// ObjCAtFinallyStmt - This represent objective-c's @finally Statement class ObjCAtFinallyStmt : public Stmt { Stmt *AtFinallyStmt; - SourceLocation AtFinallyLoc; + SourceLocation AtFinallyLoc; public: ObjCAtFinallyStmt(SourceLocation atFinallyLoc, Stmt *atFinallyStmt) - : Stmt(ObjCAtFinallyStmtClass), + : Stmt(ObjCAtFinallyStmtClass), AtFinallyStmt(atFinallyStmt), AtFinallyLoc(atFinallyLoc) {} - explicit ObjCAtFinallyStmt(EmptyShell Empty) : + explicit ObjCAtFinallyStmt(EmptyShell Empty) : Stmt(ObjCAtFinallyStmtClass, Empty) { } - + const Stmt *getFinallyBody() const { return AtFinallyStmt; } Stmt *getFinallyBody() { return AtFinallyStmt; } void setFinallyBody(Stmt *S) { AtFinallyStmt = S; } - - virtual SourceRange getSourceRange() const { - return SourceRange(AtFinallyLoc, AtFinallyStmt->getLocEnd()); + + virtual SourceRange getSourceRange() const { + return SourceRange(AtFinallyLoc, AtFinallyStmt->getLocEnd()); } - + SourceLocation getAtFinallyLoc() const { return AtFinallyLoc; } void setAtFinallyLoc(SourceLocation Loc) { AtFinallyLoc = Loc; } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtFinallyStmtClass; } static bool classof(const ObjCAtFinallyStmt *) { return true; } - + virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - -/// ObjCAtTryStmt - This represent objective-c's over-all + +/// ObjCAtTryStmt - This represent objective-c's over-all /// @try ... @catch ... @finally statement. class ObjCAtTryStmt : public Stmt { private: enum { TRY, CATCH, FINALLY, END_EXPR }; - Stmt* SubStmts[END_EXPR]; - - SourceLocation AtTryLoc; + Stmt* SubStmts[END_EXPR]; + + SourceLocation AtTryLoc; public: - ObjCAtTryStmt(SourceLocation atTryLoc, Stmt *atTryStmt, - Stmt *atCatchStmt, + ObjCAtTryStmt(SourceLocation atTryLoc, Stmt *atTryStmt, + Stmt *atCatchStmt, Stmt *atFinallyStmt) : Stmt(ObjCAtTryStmtClass) { SubStmts[TRY] = atTryStmt; @@ -174,41 +174,41 @@ public: SubStmts[FINALLY] = atFinallyStmt; AtTryLoc = atTryLoc; } - explicit ObjCAtTryStmt(EmptyShell Empty) : + explicit ObjCAtTryStmt(EmptyShell Empty) : Stmt(ObjCAtTryStmtClass, Empty) { } - + SourceLocation getAtTryLoc() const { return AtTryLoc; } void setAtTryLoc(SourceLocation Loc) { AtTryLoc = Loc; } - + const Stmt *getTryBody() const { return SubStmts[TRY]; } Stmt *getTryBody() { return SubStmts[TRY]; } void setTryBody(Stmt *S) { SubStmts[TRY] = S; } - - const ObjCAtCatchStmt *getCatchStmts() const { - return dyn_cast_or_null(SubStmts[CATCH]); + + const ObjCAtCatchStmt *getCatchStmts() const { + return dyn_cast_or_null(SubStmts[CATCH]); } - ObjCAtCatchStmt *getCatchStmts() { - return dyn_cast_or_null(SubStmts[CATCH]); + ObjCAtCatchStmt *getCatchStmts() { + return dyn_cast_or_null(SubStmts[CATCH]); } void setCatchStmts(Stmt *S) { SubStmts[CATCH] = S; } - - const ObjCAtFinallyStmt *getFinallyStmt() const { - return dyn_cast_or_null(SubStmts[FINALLY]); + + const ObjCAtFinallyStmt *getFinallyStmt() const { + return dyn_cast_or_null(SubStmts[FINALLY]); } - ObjCAtFinallyStmt *getFinallyStmt() { - return dyn_cast_or_null(SubStmts[FINALLY]); + ObjCAtFinallyStmt *getFinallyStmt() { + return dyn_cast_or_null(SubStmts[FINALLY]); } void setFinallyStmt(Stmt *S) { SubStmts[FINALLY] = S; } - virtual SourceRange getSourceRange() const { - return SourceRange(AtTryLoc, SubStmts[TRY]->getLocEnd()); + virtual SourceRange getSourceRange() const { + return SourceRange(AtTryLoc, SubStmts[TRY]->getLocEnd()); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtTryStmtClass; } static bool classof(const ObjCAtTryStmt *) { return true; } - + virtual child_iterator child_begin(); virtual child_iterator child_end(); }; @@ -223,7 +223,7 @@ private: enum { SYNC_EXPR, SYNC_BODY, END_EXPR }; Stmt* SubStmts[END_EXPR]; SourceLocation AtSynchronizedLoc; - + public: ObjCAtSynchronizedStmt(SourceLocation atSynchronizedLoc, Stmt *synchExpr, Stmt *synchBody) @@ -232,41 +232,41 @@ public: SubStmts[SYNC_BODY] = synchBody; AtSynchronizedLoc = atSynchronizedLoc; } - explicit ObjCAtSynchronizedStmt(EmptyShell Empty) : + explicit ObjCAtSynchronizedStmt(EmptyShell Empty) : Stmt(ObjCAtSynchronizedStmtClass, Empty) { } - + SourceLocation getAtSynchronizedLoc() const { return AtSynchronizedLoc; } void setAtSynchronizedLoc(SourceLocation Loc) { AtSynchronizedLoc = Loc; } - + const CompoundStmt *getSynchBody() const { return reinterpret_cast(SubStmts[SYNC_BODY]); } - CompoundStmt *getSynchBody() { - return reinterpret_cast(SubStmts[SYNC_BODY]); + CompoundStmt *getSynchBody() { + return reinterpret_cast(SubStmts[SYNC_BODY]); } void setSynchBody(Stmt *S) { SubStmts[SYNC_BODY] = S; } - - const Expr *getSynchExpr() const { - return reinterpret_cast(SubStmts[SYNC_EXPR]); + + const Expr *getSynchExpr() const { + return reinterpret_cast(SubStmts[SYNC_EXPR]); } - Expr *getSynchExpr() { - return reinterpret_cast(SubStmts[SYNC_EXPR]); + Expr *getSynchExpr() { + return reinterpret_cast(SubStmts[SYNC_EXPR]); } void setSynchExpr(Stmt *S) { SubStmts[SYNC_EXPR] = S; } - - virtual SourceRange getSourceRange() const { - return SourceRange(AtSynchronizedLoc, getSynchBody()->getLocEnd()); + + virtual SourceRange getSourceRange() const { + return SourceRange(AtSynchronizedLoc, getSynchBody()->getLocEnd()); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtSynchronizedStmtClass; } static bool classof(const ObjCAtSynchronizedStmt *) { return true; } - + virtual child_iterator child_begin(); virtual child_iterator child_end(); }; - + /// ObjCAtThrowStmt - This represents objective-c's @throw statement. class ObjCAtThrowStmt : public Stmt { Stmt *Throw; @@ -276,28 +276,28 @@ public: : Stmt(ObjCAtThrowStmtClass), Throw(throwExpr) { AtThrowLoc = atThrowLoc; } - explicit ObjCAtThrowStmt(EmptyShell Empty) : + explicit ObjCAtThrowStmt(EmptyShell Empty) : Stmt(ObjCAtThrowStmtClass, Empty) { } - + const Expr *getThrowExpr() const { return reinterpret_cast(Throw); } Expr *getThrowExpr() { return reinterpret_cast(Throw); } void setThrowExpr(Stmt *S) { Throw = S; } - + SourceLocation getThrowLoc() { return AtThrowLoc; } void setThrowLoc(SourceLocation Loc) { AtThrowLoc = Loc; } - + virtual SourceRange getSourceRange() const { if (Throw) - return SourceRange(AtThrowLoc, Throw->getLocEnd()); - else + return SourceRange(AtThrowLoc, Throw->getLocEnd()); + else return SourceRange(AtThrowLoc); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtThrowStmtClass; } static bool classof(const ObjCAtThrowStmt *) { return true; } - + virtual child_iterator child_begin(); virtual child_iterator child_end(); }; diff --git a/clang/include/clang/AST/StmtVisitor.h b/clang/include/clang/AST/StmtVisitor.h index 4f4066ab8602275864d3303ebb5a64e4cf63dacc..3a525507dad33879f7a17ec0cc250844ba4a2ab5 100644 --- a/clang/include/clang/AST/StmtVisitor.h +++ b/clang/include/clang/AST/StmtVisitor.h @@ -20,17 +20,17 @@ #include "clang/AST/StmtObjC.h" namespace clang { - + #define DISPATCH(NAME, CLASS) \ return static_cast(this)->Visit ## NAME(static_cast(S)) - + /// StmtVisitor - This class implements a simple visitor for Stmt subclasses. /// Since Expr derives from Stmt, this also includes support for visiting Exprs. template class StmtVisitor { public: RetTy Visit(Stmt *S) { - + // If we have a binary expr, dispatch to the subcode of the binop. A smart // optimizer (e.g. LLVM) will fold this comparison into the switch stmt // below. @@ -53,7 +53,7 @@ public: case BinaryOperator::GE: DISPATCH(BinGE, BinaryOperator); case BinaryOperator::EQ: DISPATCH(BinEQ, BinaryOperator); case BinaryOperator::NE: DISPATCH(BinNE, BinaryOperator); - + case BinaryOperator::And: DISPATCH(BinAnd, BinaryOperator); case BinaryOperator::Xor: DISPATCH(BinXor, BinaryOperator); case BinaryOperator::Or : DISPATCH(BinOr, BinaryOperator); @@ -101,7 +101,7 @@ public: case UnaryOperator::OffsetOf: DISPATCH(UnaryOffsetOf, UnaryOperator); } } - + // Top switch stmt: dispatch to VisitFooStmt for each FooStmt. switch (S->getStmtClass()) { default: assert(0 && "Unknown stmt kind!"); @@ -110,7 +110,7 @@ public: #include "clang/AST/StmtNodes.def" } } - + // If the implementation chooses not to implement a certain visit method, fall // back on VisitExpr or whatever else is the superclass. #define STMT(CLASS, PARENT) \ @@ -127,7 +127,7 @@ public: BINOP_FALLBACK(Mul) BINOP_FALLBACK(Div) BINOP_FALLBACK(Rem) BINOP_FALLBACK(Add) BINOP_FALLBACK(Sub) BINOP_FALLBACK(Shl) BINOP_FALLBACK(Shr) - + BINOP_FALLBACK(LT) BINOP_FALLBACK(GT) BINOP_FALLBACK(LE) BINOP_FALLBACK(GE) BINOP_FALLBACK(EQ) BINOP_FALLBACK(NE) BINOP_FALLBACK(And) BINOP_FALLBACK(Xor) BINOP_FALLBACK(Or) @@ -148,7 +148,7 @@ public: CAO_FALLBACK(ShrAssign) CAO_FALLBACK(AndAssign) CAO_FALLBACK(OrAssign) CAO_FALLBACK(XorAssign) #undef CAO_FALLBACK - + // If the implementation doesn't implement unary operator methods, fall back // on VisitUnaryOperator. #define UNARYOP_FALLBACK(NAME) \ @@ -158,13 +158,13 @@ public: UNARYOP_FALLBACK(PostInc) UNARYOP_FALLBACK(PostDec) UNARYOP_FALLBACK(PreInc) UNARYOP_FALLBACK(PreDec) UNARYOP_FALLBACK(AddrOf) UNARYOP_FALLBACK(Deref) - + UNARYOP_FALLBACK(Plus) UNARYOP_FALLBACK(Minus) UNARYOP_FALLBACK(Not) UNARYOP_FALLBACK(LNot) UNARYOP_FALLBACK(Real) UNARYOP_FALLBACK(Imag) UNARYOP_FALLBACK(Extension) UNARYOP_FALLBACK(OffsetOf) #undef UNARYOP_FALLBACK - + // Base case, ignore it. :) RetTy VisitStmt(Stmt *Node) { return RetTy(); } }; diff --git a/clang/include/clang/AST/TemplateName.h b/clang/include/clang/AST/TemplateName.h index 67d3f73c37a861eb288bb1effb48cee8684d638c..66ff34cf1e31815131f1a0fcc8abeba5f456ff4d 100644 --- a/clang/include/clang/AST/TemplateName.h +++ b/clang/include/clang/AST/TemplateName.h @@ -61,7 +61,7 @@ class OverloadedFunctionDecl; /// only be understood in the context of class TemplateName { typedef llvm::PointerUnion4 StorageType; StorageType Storage; @@ -80,25 +80,25 @@ public: /// \brief Determine whether this template name is NULL. bool isNull() const { return Storage.isNull(); } - + /// \brief Retrieve the the underlying template declaration that /// this template name refers to, if known. /// /// \returns The template declaration that this template name refers /// to, if any. If the template name does not refer to a specific - /// declaration because it is a dependent name, or if it refers to a + /// declaration because it is a dependent name, or if it refers to a /// set of function templates, returns NULL. TemplateDecl *getAsTemplateDecl() const; - /// \brief Retrieve the the underlying, overloaded function template + /// \brief Retrieve the the underlying, overloaded function template // declarations that this template name refers to, if known. /// - /// \returns The set of overloaded function templates that this template - /// name refers to, if known. If the template name does not refer to a + /// \returns The set of overloaded function templates that this template + /// name refers to, if known. If the template name does not refer to a /// specific set of function templates because it is a dependent name or /// refers to a single template, returns NULL. OverloadedFunctionDecl *getAsOverloadedFunctionDecl() const; - + /// \brief Retrieve the underlying qualified template name /// structure, if any. QualifiedTemplateName *getAsQualifiedTemplateName() const { @@ -137,8 +137,8 @@ public: void *getAsVoidPointer() const { return Storage.getOpaqueValue(); } /// \brief Build a template name from a void pointer. - static TemplateName getFromVoidPointer(void *Ptr) { - return TemplateName(Ptr); + static TemplateName getFromVoidPointer(void *Ptr) { + return TemplateName(Ptr); } }; @@ -171,14 +171,14 @@ class QualifiedTemplateName : public llvm::FoldingSetNode { QualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) - : Qualifier(NNS, TemplateKeyword? 1 : 0), + : Qualifier(NNS, TemplateKeyword? 1 : 0), Template(reinterpret_cast(Template)) { } QualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, OverloadedFunctionDecl *Template) - : Qualifier(NNS, TemplateKeyword? 1 : 0), + : Qualifier(NNS, TemplateKeyword? 1 : 0), Template(reinterpret_cast(Template)) { } - + public: /// \brief Return the nested name specifier that qualifies this name. NestedNameSpecifier *getQualifier() const { return Qualifier.getPointer(); } @@ -190,22 +190,22 @@ public: /// \brief The template declaration or set of overloaded functions that /// that qualified name refers to. NamedDecl *getDecl() const { return Template; } - + /// \brief The template declaration to which this qualified name /// refers, or NULL if this qualified name refers to a set of overloaded /// function templates. TemplateDecl *getTemplateDecl() const; /// \brief The set of overloaded function tempaltes to which this qualified - /// name refers, or NULL if this qualified name refers to a single + /// name refers, or NULL if this qualified name refers to a single /// template declaration. OverloadedFunctionDecl *getOverloadedFunctionDecl() const; - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getQualifier(), hasTemplateKeyword(), getDecl()); } - static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS, + static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS, bool TemplateKeyword, NamedDecl *Template) { ID.AddPointer(NNS); ID.AddBoolean(TemplateKeyword); @@ -239,11 +239,11 @@ class DependentTemplateName : public llvm::FoldingSetNode { friend class ASTContext; - DependentTemplateName(NestedNameSpecifier *Qualifier, + DependentTemplateName(NestedNameSpecifier *Qualifier, const IdentifierInfo *Name) : Qualifier(Qualifier), Name(Name), CanonicalTemplateName(this) { } - DependentTemplateName(NestedNameSpecifier *Qualifier, + DependentTemplateName(NestedNameSpecifier *Qualifier, const IdentifierInfo *Name, TemplateName Canon) : Qualifier(Qualifier), Name(Name), CanonicalTemplateName(Canon) { } @@ -260,7 +260,7 @@ public: Profile(ID, getQualifier(), getName()); } - static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS, + static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS, const IdentifierInfo *Name) { ID.AddPointer(NNS); ID.AddPointer(Name); diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h index 4cebdcdf212e8d7c934e2657070469809e6a20b5..4ebda908a30ffc412eacc101f8824a92c80cbaf1 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -92,7 +92,7 @@ public: Volatile = 0x4, CVRFlags = Const|Restrict|Volatile }; - + enum GCAttrTypes { GCNone = 0, Weak, @@ -101,23 +101,23 @@ public: // 24 bits should be enough for anyone. static const unsigned MaxAddressSpace = 0xffffffu; - + QualType() {} - + QualType(const Type *Ptr, unsigned Quals) : Value(const_cast(Ptr), Quals) {} unsigned getCVRQualifiers() const { return Value.getInt(); } void setCVRQualifiers(unsigned Quals) { Value.setInt(Quals); } Type *getTypePtr() const { return Value.getPointer(); } - + void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } static QualType getFromOpaquePtr(void *Ptr) { QualType T; T.Value.setFromOpaqueValue(Ptr); return T; } - + Type &operator*() const { return *getTypePtr(); } @@ -125,7 +125,7 @@ public: Type *operator->() const { return getTypePtr(); } - + /// isNull - Return true if this QualType doesn't point to a type yet. bool isNull() const { return getTypePtr() == 0; @@ -142,7 +142,7 @@ public: } bool isConstant(ASTContext& Ctx) const; - + /// addConst/addVolatile/addRestrict - add the specified type qual to this /// QualType. void addConst() { Value.setInt(Value.getInt() | Const); } @@ -163,12 +163,12 @@ public: QualType withConst() const { return getWithAdditionalQualifiers(Const); } QualType withVolatile() const { return getWithAdditionalQualifiers(Volatile);} QualType withRestrict() const { return getWithAdditionalQualifiers(Restrict);} - + QualType getUnqualifiedType() const; bool isMoreQualifiedThan(QualType Other) const; bool isAtLeastAsQualifiedAs(QualType Other) const; QualType getNonReferenceType() const; - + /// getDesugaredType - Return the specified type with any "sugar" removed from /// the type. This takes off typedefs, typeof's etc. If the outer level of /// the type is already concrete, it returns it unmodified. This is similar @@ -194,19 +194,19 @@ public: } void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const; - + void dump(const char *s) const; void dump() const; - + void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddPointer(getAsOpaquePtr()); } public: - + /// getAddressSpace - Return the address space of this type. inline unsigned getAddressSpace() const; - + /// GCAttrTypesAttr - Returns gc attribute of this type. inline QualType::GCAttrTypes getObjCGCAttr() const; @@ -238,7 +238,7 @@ template<> struct simplify_type { }; template<> struct simplify_type< ::clang::QualType> : public simplify_type {}; - + // Teach SmallPtrSet that QualType is "basically a pointer". template<> class PointerLikeTypeTraits { @@ -252,7 +252,7 @@ public: // CVR qualifiers go in low bits. enum { NumLowBitsAvailable = 0 }; }; - + } // end namespace llvm namespace clang { @@ -316,15 +316,15 @@ protected: virtual ~Type() {} virtual void Destroy(ASTContext& C); friend class ASTContext; - + public: TypeClass getTypeClass() const { return static_cast(TC); } - + bool isCanonical() const { return CanonicalType.getTypePtr() == this; } - /// Types are partitioned into 3 broad categories (C99 6.2.5p1): + /// Types are partitioned into 3 broad categories (C99 6.2.5p1): /// object types, function types, and incomplete types. - + /// \brief Determines whether the type describes an object in memory. /// /// Note that this definition of object type corresponds to the C++ @@ -336,7 +336,7 @@ public: /// isIncompleteType - Return true if this is an incomplete type. /// A type that can describe objects, but which lacks information needed to /// determine its size (e.g. void, or a fwd declared struct). Clients of this - /// routine will need to determine if the size is actually required. + /// routine will need to determine if the size is actually required. bool isIncompleteType() const; /// isIncompleteOrObjectType - Return true if this is an incomplete or object @@ -351,13 +351,13 @@ public: /// isVariablyModifiedType (C99 6.7.5.2p2) - Return true for variable array /// types that have a non-constant expression. This does not include "[]". bool isVariablyModifiedType() const; - + /// Helper methods to distinguish type categories. All type predicates /// operate on the canonical type, ignoring typedefs and qualifiers. /// isSpecificBuiltinType - Test for a particular builtin type. bool isSpecificBuiltinType(unsigned K) const; - + /// isIntegerType() does *not* include complex integers (a GCC extension). /// isComplexIntegerType() can be used to test for complex integers. bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) @@ -366,7 +366,7 @@ public: bool isCharType() const; bool isWideCharType() const; bool isIntegralType() const; - + /// Floating point categories. bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) /// isComplexType() does *not* include complex integers (a GCC extension). @@ -380,7 +380,7 @@ public: bool isDerivedType() const; // C99 6.2.5p20 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) bool isAggregateType() const; - + // Type Predicates: Check to see if this type is structurally the specified // type, ignoring typedefs and qualifiers. bool isFunctionType() const; @@ -402,8 +402,8 @@ public: bool isVariableArrayType() const; bool isDependentSizedArrayType() const; bool isRecordType() const; - bool isClassType() const; - bool isStructureType() const; + bool isClassType() const; + bool isStructureType() const; bool isUnionType() const; bool isComplexIntegerType() const; // GCC _Complex integer type. bool isVectorType() const; // GCC vector type. @@ -422,7 +422,7 @@ public: bool isNullPtrType() const; // C++0x nullptr_t /// isDependentType - Whether this type is a dependent type, meaning - /// that its definition somehow depends on a template parameter + /// that its definition somehow depends on a template parameter /// (C++ [temp.dep.type]). bool isDependentType() const { return Dependent; } bool isOverloadableType() const; @@ -435,7 +435,7 @@ public: /// hasObjCPointerRepresentation - Whether this type can represent /// an objective pointer type for the purpose of GC'ability - bool hasObjCPointerRepresentation() const; + bool hasObjCPointerRepresentation() const; // Type Checking Functions: Check to see if this type is structurally the // specified type, ignoring typedefs and qualifiers, and return a pointer to @@ -462,14 +462,14 @@ public: const ObjCInterfaceType *getAsObjCQualifiedInterfaceType() const; const TemplateTypeParmType *getAsTemplateTypeParmType() const; const CXXRecordDecl *getCXXRecordDeclForPointerType() const; - + // Member-template getAs'. This scheme will eventually // replace the specific getAsXXXX methods above. template const T *getAs() const; - + const TemplateSpecializationType * getAsTemplateSpecializationType() const; - + /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC /// interface, return the interface type, otherwise return null. const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const; @@ -478,11 +478,11 @@ public: /// element type of the array, potentially with type qualifiers missing. /// This method should never be used when type qualifiers are meaningful. const Type *getArrayElementTypeNoTypeQual() const; - + /// getPointeeType - If this is a pointer, ObjC object pointer, or block /// pointer, this returns the respective pointee. QualType getPointeeType() const; - + /// getDesugaredType - Return the specified type with any "sugar" removed from /// the type. This takes off typedefs, typeof's etc. If the outer level of /// the type is already concrete, it returns it unmodified. This is similar @@ -490,7 +490,7 @@ public: /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is /// concrete. QualType getDesugaredType(bool ForDisplay = false) const; - + /// More type predicates useful for type checking/promotion bool isPromotableIntegerType() const; // C99 6.3.1.1p2 @@ -517,12 +517,12 @@ public: QualType getCanonicalTypeInternal() const { return CanonicalType; } void dump() const; - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const = 0; static bool classof(const Type *) { return true; } }; -/// ExtQualType - TR18037 (C embedded extensions) 6.2.5p26 +/// ExtQualType - TR18037 (C embedded extensions) 6.2.5p26 /// This supports all kinds of type attributes; including, /// address space qualified types, objective-c's __weak and /// __strong attributes. @@ -537,7 +537,7 @@ class ExtQualType : public Type, public llvm::FoldingSetNode { unsigned AddressSpace; /// GC __weak/__strong attributes QualType::GCAttrTypes GCAttrType; - + ExtQualType(Type *Base, QualType CanonicalPtr, unsigned AddrSpace, QualType::GCAttrTypes gcAttr) : Type(ExtQual, CanonicalPtr, Base->isDependentType()), BaseType(Base), @@ -551,19 +551,19 @@ public: QualType::GCAttrTypes getObjCGCAttr() const { return GCAttrType; } unsigned getAddressSpace() const { return AddressSpace; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getBaseType(), AddressSpace, GCAttrType); } - static void Profile(llvm::FoldingSetNodeID &ID, Type *Base, + static void Profile(llvm::FoldingSetNodeID &ID, Type *Base, unsigned AddrSpace, QualType::GCAttrTypes gcAttr) { ID.AddPointer(Base); ID.AddInteger(AddrSpace); ID.AddInteger(gcAttr); } - + static bool classof(const Type *T) { return T->getTypeClass() == ExtQual; } static bool classof(const ExtQualType *) { return true; } }; @@ -637,7 +637,7 @@ public: } bool operator==(QualifierSet& Other) { return Mask == Other.Mask; } - + private: void setAddressSpace(unsigned space) { assert(space <= MaxAddressSpace); @@ -668,7 +668,7 @@ class BuiltinType : public Type { public: enum Kind { Void, - + Bool, // This is bool and/or _Bool. Char_U, // This is 'char' for targets where char is unsigned. UChar, // This is explicitly qualified unsigned char. @@ -679,7 +679,7 @@ public: ULong, ULongLong, UInt128, // __uint128_t - + Char_S, // This is 'char' for targets where char is signed. SChar, // This is explicitly qualified signed char. WChar, // This is 'wchar_t' for C++. @@ -688,14 +688,14 @@ public: Long, LongLong, Int128, // __int128_t - + Float, Double, LongDouble, NullPtr, // This is the type of C++0x 'nullptr'. Overload, // This represents the type of an overloaded function declaration. Dependent, // This represents the type of a type-dependent expression. - + UndeducedAuto, // In C++0x, this represents the type of an auto variable // that has not been deduced yet. ObjCId, // This represents the ObjC 'id' type. @@ -704,16 +704,16 @@ public: private: Kind TypeKind; public: - BuiltinType(Kind K) - : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)), + BuiltinType(Kind K) + : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)), TypeKind(K) {} - + Kind getKind() const { return TypeKind; } const char *getName(const LangOptions &LO) const; - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } static bool classof(const BuiltinType *) { return true; } }; @@ -728,14 +728,14 @@ private: public: FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false), Width(W), Signed(S) {} - + unsigned getWidth() const { return Width; } bool isSigned() const { return Signed; } const char *getName() const; - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; } static bool classof(const FixedWidthIntType *) { return true; } }; @@ -746,23 +746,23 @@ public: class ComplexType : public Type, public llvm::FoldingSetNode { QualType ElementType; ComplexType(QualType Element, QualType CanonicalPtr) : - Type(Complex, CanonicalPtr, Element->isDependentType()), + Type(Complex, CanonicalPtr, Element->isDependentType()), ElementType(Element) { } friend class ASTContext; // ASTContext creates these. public: QualType getElementType() const { return ElementType; } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { ID.AddPointer(Element.getAsOpaquePtr()); } - + static bool classof(const Type *T) { return T->getTypeClass() == Complex; } static bool classof(const ComplexType *) { return true; } }; @@ -777,10 +777,10 @@ class PointerType : public Type, public llvm::FoldingSetNode { } friend class ASTContext; // ASTContext creates these. public: - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + QualType getPointeeType() const { return PointeeType; } void Profile(llvm::FoldingSetNodeID &ID) { @@ -789,7 +789,7 @@ public: static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { ID.AddPointer(Pointee.getAsOpaquePtr()); } - + static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } static bool classof(const PointerType *) { return true; } }; @@ -801,27 +801,27 @@ public: class BlockPointerType : public Type, public llvm::FoldingSetNode { QualType PointeeType; // Block is some kind of pointer type BlockPointerType(QualType Pointee, QualType CanonicalCls) : - Type(BlockPointer, CanonicalCls, Pointee->isDependentType()), + Type(BlockPointer, CanonicalCls, Pointee->isDependentType()), PointeeType(Pointee) { } friend class ASTContext; // ASTContext creates these. public: - + // Get the pointee type. Pointee is required to always be a function type. QualType getPointeeType() const { return PointeeType; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getPointeeType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { ID.AddPointer(Pointee.getAsOpaquePtr()); } - - static bool classof(const Type *T) { - return T->getTypeClass() == BlockPointer; + + static bool classof(const Type *T) { + return T->getTypeClass() == BlockPointer; } static bool classof(const BlockPointerType *) { return true; } }; @@ -861,7 +861,7 @@ class LValueReferenceType : public ReferenceType { } friend class ASTContext; // ASTContext creates these public: - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; static bool classof(const Type *T) { @@ -878,7 +878,7 @@ class RValueReferenceType : public ReferenceType { } friend class ASTContext; // ASTContext creates these public: - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; static bool classof(const Type *T) { @@ -907,7 +907,7 @@ public: const Type *getClass() const { return Class; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { @@ -939,15 +939,15 @@ public: private: /// ElementType - The element type of the array. QualType ElementType; - + // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum /// NOTE: These fields are packed into the bitfields space in the Type class. unsigned SizeModifier : 2; - + /// IndexTypeQuals - Capture qualifiers in declarations like: /// 'int X[static restrict 4]'. For function parameters only. unsigned IndexTypeQuals : 3; - + protected: // C++ [temp.dep.type]p1: // A type is dependent if it is... @@ -966,7 +966,7 @@ public: return ArraySizeModifier(SizeModifier); } unsigned getIndexTypeQualifier() const { return IndexTypeQuals; } - + static bool classof(const Type *T) { return T->getTypeClass() == ConstantArray || T->getTypeClass() == ConstantArrayWithExpr || @@ -984,7 +984,7 @@ public: /// type is 'int' and the size is 404. class ConstantArrayType : public ArrayType { llvm::APInt Size; // Allows us to unique the type. - + ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, ArraySizeModifier sm, unsigned tq) : ArrayType(ConstantArray, et, can, sm, tq), @@ -996,11 +996,11 @@ protected: friend class ASTContext; // ASTContext creates these. public: const llvm::APInt &getSize() const { return Size; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + void Profile(llvm::FoldingSetNodeID &ID) { - Profile(ID, getElementType(), getSize(), + Profile(ID, getElementType(), getSize(), getSizeModifier(), getIndexTypeQualifier()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, @@ -1096,20 +1096,20 @@ class IncompleteArrayType : public ArrayType { : ArrayType(IncompleteArray, et, can, sm, tq) {} friend class ASTContext; // ASTContext creates these. public: - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - static bool classof(const Type *T) { - return T->getTypeClass() == IncompleteArray; + static bool classof(const Type *T) { + return T->getTypeClass() == IncompleteArray; } static bool classof(const IncompleteArrayType *) { return true; } - + friend class StmtIteratorBase; - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType(), getSizeModifier(), getIndexTypeQualifier()); } - + static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, ArraySizeModifier SizeMod, unsigned TypeQuals) { ID.AddPointer(ET.getAsOpaquePtr()); @@ -1134,8 +1134,8 @@ public: /// } /// class VariableArrayType : public ArrayType { - /// SizeExpr - An assignment expression. VLA's are only permitted within - /// a function block. + /// SizeExpr - An assignment expression. VLA's are only permitted within + /// a function block. Stmt *SizeExpr; /// Brackets - The left and right array brackets. SourceRange Brackets; @@ -1149,7 +1149,7 @@ class VariableArrayType : public ArrayType { virtual void Destroy(ASTContext& C); public: - Expr *getSizeExpr() const { + Expr *getSizeExpr() const { // We use C-style casts instead of cast<> here because we do not wish // to have a dependency of Type.h on Stmt.h/Expr.h. return (Expr*) SizeExpr; @@ -1157,17 +1157,17 @@ public: SourceRange getBracketsRange() const { return Brackets; } SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - - static bool classof(const Type *T) { - return T->getTypeClass() == VariableArray; + + static bool classof(const Type *T) { + return T->getTypeClass() == VariableArray; } static bool classof(const VariableArrayType *) { return true; } - + friend class StmtIteratorBase; - + void Profile(llvm::FoldingSetNodeID &ID) { assert(0 && "Cannnot unique VariableArrayTypes."); } @@ -1176,7 +1176,7 @@ public: /// DependentSizedArrayType - This type represents an array type in /// C++ whose size is a value-dependent expression. For example: /// @code -/// template +/// template /// class array { /// T data[Size]; /// }; @@ -1186,14 +1186,14 @@ public: /// become either a ConstantArrayType or a VariableArrayType. class DependentSizedArrayType : public ArrayType { ASTContext &Context; - + /// SizeExpr - An assignment expression that will instantiate to the /// size of the array. Stmt *SizeExpr; /// Brackets - The left and right array brackets. SourceRange Brackets; - - DependentSizedArrayType(ASTContext &Context, QualType et, QualType can, + + DependentSizedArrayType(ASTContext &Context, QualType et, QualType can, Expr *e, ArraySizeModifier sm, unsigned tq, SourceRange brackets) : ArrayType(DependentSizedArray, et, can, sm, tq), @@ -1202,7 +1202,7 @@ class DependentSizedArrayType : public ArrayType { virtual void Destroy(ASTContext& C); public: - Expr *getSizeExpr() const { + Expr *getSizeExpr() const { // We use C-style casts instead of cast<> here because we do not wish // to have a dependency of Type.h on Stmt.h/Expr.h. return (Expr*) SizeExpr; @@ -1210,25 +1210,25 @@ public: SourceRange getBracketsRange() const { return Brackets; } SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - - static bool classof(const Type *T) { - return T->getTypeClass() == DependentSizedArray; + + static bool classof(const Type *T) { + return T->getTypeClass() == DependentSizedArray; } static bool classof(const DependentSizedArrayType *) { return true; } - + friend class StmtIteratorBase; - - + + void Profile(llvm::FoldingSetNodeID &ID) { - Profile(ID, Context, getElementType(), + Profile(ID, Context, getElementType(), getSizeModifier(), getIndexTypeQualifier(), getSizeExpr()); } - - static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, - QualType ET, ArraySizeModifier SizeMod, + + static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, + QualType ET, ArraySizeModifier SizeMod, unsigned TypeQuals, Expr *E); }; @@ -1246,11 +1246,11 @@ class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { /// ElementType - The element type of the array. QualType ElementType; SourceLocation loc; - - DependentSizedExtVectorType(ASTContext &Context, QualType ElementType, + + DependentSizedExtVectorType(ASTContext &Context, QualType ElementType, QualType can, Expr *SizeExpr, SourceLocation loc) - : Type (DependentSizedExtVector, can, true), - Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), + : Type (DependentSizedExtVector, can, true), + Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {} friend class ASTContext; virtual void Destroy(ASTContext& C); @@ -1260,62 +1260,62 @@ public: QualType getElementType() const { return ElementType; } SourceLocation getAttributeLoc() const { return loc; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - - static bool classof(const Type *T) { - return T->getTypeClass() == DependentSizedExtVector; + + static bool classof(const Type *T) { + return T->getTypeClass() == DependentSizedExtVector; } - static bool classof(const DependentSizedExtVectorType *) { return true; } + static bool classof(const DependentSizedExtVectorType *) { return true; } void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Context, getElementType(), getSizeExpr()); } - + static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, QualType ElementType, Expr *SizeExpr); }; - + /// VectorType - GCC generic vector type. This type is created using -/// __attribute__((vector_size(n)), where "n" specifies the vector size in -/// bytes. Since the constructor takes the number of vector elements, the +/// __attribute__((vector_size(n)), where "n" specifies the vector size in +/// bytes. Since the constructor takes the number of vector elements, the /// client is responsible for converting the size into the number of elements. class VectorType : public Type, public llvm::FoldingSetNode { protected: /// ElementType - The element type of the vector. QualType ElementType; - + /// NumElements - The number of elements in the vector. unsigned NumElements; - + VectorType(QualType vecType, unsigned nElements, QualType canonType) : - Type(Vector, canonType, vecType->isDependentType()), - ElementType(vecType), NumElements(nElements) {} - VectorType(TypeClass tc, QualType vecType, unsigned nElements, - QualType canonType) - : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType), - NumElements(nElements) {} + Type(Vector, canonType, vecType->isDependentType()), + ElementType(vecType), NumElements(nElements) {} + VectorType(TypeClass tc, QualType vecType, unsigned nElements, + QualType canonType) + : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType), + NumElements(nElements) {} friend class ASTContext; // ASTContext creates these. public: - + QualType getElementType() const { return ElementType; } - unsigned getNumElements() const { return NumElements; } + unsigned getNumElements() const { return NumElements; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType(), getNumElements(), getTypeClass()); } - static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, + static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, unsigned NumElements, TypeClass TypeClass) { ID.AddPointer(ElementType.getAsOpaquePtr()); ID.AddInteger(NumElements); ID.AddInteger(TypeClass); } - static bool classof(const Type *T) { - return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; + static bool classof(const Type *T) { + return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; } static bool classof(const VectorType *) { return true; } }; @@ -1327,7 +1327,7 @@ public: /// points, colors, and textures (modeled after OpenGL Shading Language). class ExtVectorType : public VectorType { ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) : - VectorType(ExtVector, vecType, nElements, canonType) {} + VectorType(ExtVector, vecType, nElements, canonType) {} friend class ASTContext; // ASTContext creates these. public: static int getPointAccessorIdx(char c) { @@ -1366,22 +1366,22 @@ public: case 'f': return 15; } } - + static int getAccessorIdx(char c) { if (int idx = getPointAccessorIdx(c)+1) return idx-1; return getNumericAccessorIdx(c); } - + bool isAccessorWithinNumElements(char c) const { if (int idx = getAccessorIdx(c)+1) return unsigned(idx-1) < NumElements; return false; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - static bool classof(const Type *T) { - return T->getTypeClass() == ExtVector; + static bool classof(const Type *T) { + return T->getTypeClass() == ExtVector; } static bool classof(const ExtVectorType *) { return true; } }; @@ -1405,7 +1405,7 @@ class FunctionType : public Type { /// NoReturn - Indicates if the function type is attribute noreturn. unsigned NoReturn : 1; - + // The type returned by the function. QualType ResultType; protected: @@ -1418,11 +1418,11 @@ protected: bool getSubClassData() const { return SubClassData; } unsigned getTypeQuals() const { return TypeQuals; } public: - + QualType getResultType() const { return ResultType; } bool getNoReturnAttr() const { return NoReturn; } - + static bool classof(const Type *T) { return T->getTypeClass() == FunctionNoProto || T->getTypeClass() == FunctionProto; @@ -1435,13 +1435,13 @@ public: class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { FunctionNoProtoType(QualType Result, QualType Canonical, bool NoReturn = false) - : FunctionType(FunctionNoProto, Result, false, 0, Canonical, + : FunctionType(FunctionNoProto, Result, false, 0, Canonical, /*Dependent=*/false, NoReturn) {} friend class ASTContext; // ASTContext creates these. public: // No additional state past what FunctionType provides. - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { @@ -1452,7 +1452,7 @@ public: ID.AddInteger(NoReturn); ID.AddPointer(ResultType.getAsOpaquePtr()); } - + static bool classof(const Type *T) { return T->getTypeClass() == FunctionNoProto; } @@ -1480,7 +1480,7 @@ class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode { bool hasAnyExs, const QualType *ExArray, unsigned numExs, QualType Canonical, bool NoReturn) : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical, - (Result->isDependentType() || + (Result->isDependentType() || hasAnyDependentType(ArgArray, numArgs)), NoReturn), NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs), AnyExceptionSpec(hasAnyExs) { @@ -1528,14 +1528,14 @@ public: assert(i < NumExceptions && "Invalid exception number!"); return exception_begin()[i]; } - bool hasEmptyExceptionSpec() const { - return hasExceptionSpec() && !hasAnyExceptionSpec() && + bool hasEmptyExceptionSpec() const { + return hasExceptionSpec() && !hasAnyExceptionSpec() && getNumExceptions() == 0; } bool isVariadic() const { return getSubClassData(); } unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); } - + typedef const QualType *arg_type_iterator; arg_type_iterator arg_type_begin() const { return reinterpret_cast(this+1); @@ -1551,7 +1551,7 @@ public: return exception_begin() + NumExceptions; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; static bool classof(const Type *T) { @@ -1572,15 +1572,15 @@ public: class TypedefType : public Type { TypedefDecl *Decl; protected: - TypedefType(TypeClass tc, TypedefDecl *D, QualType can) + TypedefType(TypeClass tc, TypedefDecl *D, QualType can) : Type(tc, can, can->isDependentType()), Decl(D) { assert(!isa(can) && "Invalid canonical type"); } friend class ASTContext; // ASTContext creates these. public: - + TypedefDecl *getDecl() const { return Decl; } - + /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to /// potentially looking through *all* consecutive typedefs. This returns the /// sum of the type qualifiers, so if you have: @@ -1588,8 +1588,8 @@ public: /// typedef volatile A B; /// looking through the typedefs for B will give you "const volatile A". QualType LookThroughTypedefs() const; - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } @@ -1599,50 +1599,50 @@ public: /// TypeOfExprType (GCC extension). class TypeOfExprType : public Type { Expr *TOExpr; - + protected: TypeOfExprType(Expr *E, QualType can = QualType()); friend class ASTContext; // ASTContext creates these. public: Expr *getUnderlyingExpr() const { return TOExpr; } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } static bool classof(const TypeOfExprType *) { return true; } }; -/// Subclass of TypeOfExprType that is used for canonical, dependent -/// typeof(expr) types. -class DependentTypeOfExprType +/// Subclass of TypeOfExprType that is used for canonical, dependent +/// typeof(expr) types. +class DependentTypeOfExprType : public TypeOfExprType, public llvm::FoldingSetNode { ASTContext &Context; - + public: - DependentTypeOfExprType(ASTContext &Context, Expr *E) + DependentTypeOfExprType(ASTContext &Context, Expr *E) : TypeOfExprType(E), Context(Context) { } - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Context, getUnderlyingExpr()); } - + static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, Expr *E); }; - + /// TypeOfType (GCC extension). class TypeOfType : public Type { QualType TOType; - TypeOfType(QualType T, QualType can) + TypeOfType(QualType T, QualType can) : Type(TypeOf, can, T->isDependentType()), TOType(T) { assert(!isa(can) && "Invalid canonical type"); } friend class ASTContext; // ASTContext creates these. public: QualType getUnderlyingType() const { return TOType; } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } @@ -1652,12 +1652,12 @@ public: /// DecltypeType (C++0x) class DecltypeType : public Type { Expr *E; - + // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr // from it. QualType UnderlyingType; - + protected: DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); friend class ASTContext; // ASTContext creates these. @@ -1665,29 +1665,29 @@ public: Expr *getUnderlyingExpr() const { return E; } QualType getUnderlyingType() const { return UnderlyingType; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } static bool classof(const DecltypeType *) { return true; } }; - -/// Subclass of DecltypeType that is used for canonical, dependent -/// C++0x decltype types. + +/// Subclass of DecltypeType that is used for canonical, dependent +/// C++0x decltype types. class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { ASTContext &Context; - + public: DependentDecltypeType(ASTContext &Context, Expr *E); - + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Context, getUnderlyingExpr()); } - + static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, - Expr *E); + Expr *E); }; - + class TagType : public Type { /// Stores the TagDecl associated with this type. The decl will /// point to the TagDecl that actually defines the entity (or is a @@ -1701,18 +1701,18 @@ class TagType : public Type { protected: TagType(TypeClass TC, TagDecl *D, QualType can); -public: +public: TagDecl *getDecl() const { return decl.getPointer(); } - + /// @brief Determines whether this type is in the process of being - /// defined. + /// defined. bool isBeingDefined() const { return decl.getInt(); } void setBeingDefined(bool Def) { decl.setInt(Def? 1 : 0); } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - static bool classof(const Type *T) { + static bool classof(const Type *T) { return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast; } static bool classof(const TagType *) { return true; } @@ -1730,20 +1730,20 @@ protected: : TagType(TC, reinterpret_cast(D), QualType()) { } friend class ASTContext; // ASTContext creates these. public: - + RecordDecl *getDecl() const { return reinterpret_cast(TagType::getDecl()); } - - // FIXME: This predicate is a helper to QualType/Type. It needs to + + // FIXME: This predicate is a helper to QualType/Type. It needs to // recursively check all fields for const-ness. If any field is declared - // const, it needs to return false. + // const, it needs to return false. bool hasConstFields() const { return false; } // FIXME: RecordType needs to check when it is created that all fields are in // the same address space, and return that. unsigned getAddressSpace() const { return 0; } - + static bool classof(const TagType *T); static bool classof(const Type *T) { return isa(T) && classof(cast(T)); @@ -1758,11 +1758,11 @@ class EnumType : public TagType { : TagType(Enum, reinterpret_cast(D), QualType()) { } friend class ASTContext; // ASTContext creates these. public: - + EnumDecl *getDecl() const { return reinterpret_cast(TagType::getDecl()); } - + static bool classof(const TagType *T); static bool classof(const Type *T) { return isa(T) && classof(cast(T)); @@ -1814,7 +1814,7 @@ public: } } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { @@ -1835,12 +1835,12 @@ class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { unsigned ParameterPack : 1; IdentifierInfo *Name; - TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N, - QualType Canon) + TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N, + QualType Canon) : Type(TemplateTypeParm, Canon, /*Dependent=*/true), Depth(D), Index(I), ParameterPack(PP), Name(N) { } - TemplateTypeParmType(unsigned D, unsigned I, bool PP) + TemplateTypeParmType(unsigned D, unsigned I, bool PP) : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true), Depth(D), Index(I), ParameterPack(PP), Name(0) { } @@ -1851,16 +1851,16 @@ public: unsigned getIndex() const { return Index; } bool isParameterPack() const { return ParameterPack; } IdentifierInfo *getName() const { return Name; } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Depth, Index, ParameterPack, Name); } - static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, - unsigned Index, bool ParameterPack, + static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, + unsigned Index, bool ParameterPack, IdentifierInfo *Name) { ID.AddInteger(Depth); ID.AddInteger(Index); @@ -1868,8 +1868,8 @@ public: ID.AddPointer(Name); } - static bool classof(const Type *T) { - return T->getTypeClass() == TemplateTypeParm; + static bool classof(const Type *T) { + return T->getTypeClass() == TemplateTypeParm; } static bool classof(const TemplateTypeParmType *T) { return true; } }; @@ -1883,18 +1883,18 @@ public: /// type will point to some other type node that represents the /// instantiation or class template specialization. For example, a /// class template specialization type of @c vector will refer to -/// a tag type for the instantiation +/// a tag type for the instantiation /// @c std::vector>. /// /// Other template specialization types, for which the template name /// is dependent, may be canonical types. These types are always /// dependent. -class TemplateSpecializationType +class TemplateSpecializationType : public Type, public llvm::FoldingSetNode { // FIXME: Currently needed for profiling expressions; can we avoid this? ASTContext &Context; - + /// \brief The name of the template being specialized. TemplateName Template; @@ -1915,7 +1915,7 @@ public: /// \brief Determine whether any of the given template arguments are /// dependent. static bool anyDependentTemplateArguments(const TemplateArgument *Args, - unsigned NumArgs); + unsigned NumArgs); /// \brief Print a template argument list, including the '<' and '>' /// enclosing the template arguments. @@ -1932,7 +1932,7 @@ public: TemplateName getTemplateName() const { return Template; } /// \brief Retrieve the template arguments. - const TemplateArgument *getArgs() const { + const TemplateArgument *getArgs() const { return reinterpret_cast(this + 1); } @@ -1943,7 +1943,7 @@ public: /// \precondition @c isArgType(Arg) const TemplateArgument &getArg(unsigned Idx) const; - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { @@ -1954,8 +1954,8 @@ public: const TemplateArgument *Args, unsigned NumArgs, ASTContext &Context); - static bool classof(const Type *T) { - return T->getTypeClass() == TemplateSpecialization; + static bool classof(const Type *T) { + return T->getTypeClass() == TemplateSpecialization; } static bool classof(const TemplateSpecializationType *T) { return true; } }; @@ -1988,7 +1988,7 @@ public: /// \brief Retrieve the type named by the qualified-id. QualType getNamedType() const { return NamedType; } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { @@ -2001,8 +2001,8 @@ public: NamedType.Profile(ID); } - static bool classof(const Type *T) { - return T->getTypeClass() == QualifiedName; + static bool classof(const Type *T) { + return T->getTypeClass() == QualifiedName; } static bool classof(const QualifiedNameType *T) { return true; } }; @@ -2023,7 +2023,7 @@ class TypenameType : public Type, public llvm::FoldingSetNode { /// \brief The nested name specifier containing the qualifier. NestedNameSpecifier *NNS; - typedef llvm::PointerUnion NameType; /// \brief The type that this typename specifier refers to. @@ -2031,15 +2031,15 @@ class TypenameType : public Type, public llvm::FoldingSetNode { TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType CanonType) - : Type(Typename, CanonType, true), NNS(NNS), Name(Name) { - assert(NNS->isDependent() && + : Type(Typename, CanonType, true), NNS(NNS), Name(Name) { + assert(NNS->isDependent() && "TypenameType requires a dependent nested-name-specifier"); } TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty, QualType CanonType) - : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) { - assert(NNS->isDependent() && + : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) { + assert(NNS->isDependent() && "TypenameType requires a dependent nested-name-specifier"); } @@ -2055,8 +2055,8 @@ public: /// This routine will return a non-NULL identifier pointer when the /// form of the original typename was terminated by an identifier, /// e.g., "typename T::type". - const IdentifierInfo *getIdentifier() const { - return Name.dyn_cast(); + const IdentifierInfo *getIdentifier() const { + return Name.dyn_cast(); } /// \brief Retrieve the type named by the typename specifier as a @@ -2065,7 +2065,7 @@ public: return Name.dyn_cast(); } - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; void Profile(llvm::FoldingSetNodeID &ID) { @@ -2078,8 +2078,8 @@ public: ID.AddPointer(Name.getOpaqueValue()); } - static bool classof(const Type *T) { - return T->getTypeClass() == Typename; + static bool classof(const Type *T) { + return T->getTypeClass() == Typename; } static bool classof(const TypenameType *T) { return true; } }; @@ -2097,13 +2097,13 @@ class ObjCInterfaceType : public Type, public llvm::FoldingSetNode { llvm::SmallVector Protocols; ObjCInterfaceType(ObjCInterfaceDecl *D, - ObjCProtocolDecl **Protos, unsigned NumP) : - Type(ObjCInterface, QualType(), /*Dependent=*/false), + ObjCProtocolDecl **Protos, unsigned NumP) : + Type(ObjCInterface, QualType(), /*Dependent=*/false), Decl(D), Protocols(Protos, Protos+NumP) { } friend class ASTContext; // ASTContext creates these. public: ObjCInterfaceDecl *getDecl() const { return Decl; } - + /// getNumProtocols - Return the number of qualifying protocols in this /// interface type, or 0 if there are none. unsigned getNumProtocols() const { return Protocols.size(); } @@ -2114,17 +2114,17 @@ public: qual_iterator qual_begin() const { return Protocols.begin(); } qual_iterator qual_end() const { return Protocols.end(); } bool qual_empty() const { return Protocols.size() == 0; } - - virtual void getAsStringInternal(std::string &InnerString, + + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - + void Profile(llvm::FoldingSetNodeID &ID); - static void Profile(llvm::FoldingSetNodeID &ID, + static void Profile(llvm::FoldingSetNodeID &ID, const ObjCInterfaceDecl *Decl, ObjCProtocolDecl **protocols, unsigned NumProtocols); - - static bool classof(const Type *T) { - return T->getTypeClass() == ObjCInterface; + + static bool classof(const Type *T) { + return T->getTypeClass() == ObjCInterface; } static bool classof(const ObjCInterfaceType *) { return true; } }; @@ -2136,7 +2136,7 @@ public: /// alphabetical order. class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { QualType PointeeType; // A builtin or interface type. - + // List of protocols for this protocol conforming object type // List is sorted on protocol name. No protocol is entered more than once. llvm::SmallVector Protocols; @@ -2145,7 +2145,7 @@ class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { Type(ObjCObjectPointer, QualType(), /*Dependent=*/false), PointeeType(T), Protocols(Protos, Protos+NumP) { } friend class ASTContext; // ASTContext creates these. - + public: // Get the pointee type. Pointee will either be: // - a built-in type (for 'id' and 'Class'). @@ -2154,8 +2154,8 @@ public: // For example: typedef NSObject T; T *var; QualType getPointeeType() const { return PointeeType; } - const ObjCInterfaceType *getInterfaceType() const { - return PointeeType->getAsObjCInterfaceType(); + const ObjCInterfaceType *getInterfaceType() const { + return PointeeType->getAsObjCInterfaceType(); } /// getInterfaceDecl - returns an interface decl for user-defined types. ObjCInterfaceDecl *getInterfaceDecl() const { @@ -2163,22 +2163,22 @@ public: } /// isObjCIdType - true for "id". bool isObjCIdType() const { - return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) && + return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) && !Protocols.size(); } /// isObjCClassType - true for "Class". bool isObjCClassType() const { - return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) && + return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) && !Protocols.size(); } /// isObjCQualifiedIdType - true for "id

". - bool isObjCQualifiedIdType() const { - return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) && - Protocols.size(); + bool isObjCQualifiedIdType() const { + return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) && + Protocols.size(); } /// isObjCQualifiedClassType - true for "Class

". bool isObjCQualifiedClassType() const { - return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) && + return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) && Protocols.size(); } /// qual_iterator and friends: this provides access to the (potentially empty) @@ -2196,10 +2196,10 @@ public: void Profile(llvm::FoldingSetNodeID &ID); static void Profile(llvm::FoldingSetNodeID &ID, QualType T, ObjCProtocolDecl **protocols, unsigned NumProtocols); - virtual void getAsStringInternal(std::string &InnerString, + virtual void getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const; - static bool classof(const Type *T) { - return T->getTypeClass() == ObjCObjectPointer; + static bool classof(const Type *T) { + return T->getTypeClass() == ObjCObjectPointer; } static bool classof(const ObjCObjectPointerType *) { return true; } }; @@ -2234,10 +2234,10 @@ inline QualType::GCAttrTypes QualType::getObjCGCAttr() const { if (const ExtQualType *EXTQT = dyn_cast(CT)) return EXTQT->getObjCGCAttr(); if (const ObjCObjectPointerType *PT = CT->getAsObjCObjectPointerType()) - return PT->getPointeeType().getObjCGCAttr(); + return PT->getPointeeType().getObjCGCAttr(); // We most look at all pointer types, not just pointer to interface types. if (const PointerType *PT = CT->getAs()) - return PT->getPointeeType().getObjCGCAttr(); + return PT->getPointeeType().getObjCGCAttr(); return GCNone; } @@ -2253,7 +2253,7 @@ inline bool QualType::getNoReturnAttr() const { return false; } - + /// isMoreQualifiedThan - Determine whether this type is more /// qualified than the Other type. For example, "const volatile int" /// is more qualified than "const int", "volatile int", and @@ -2303,20 +2303,20 @@ inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const { return PT->getPointeeType()->getAsObjCInterfaceType(); return 0; } - + // NOTE: All of these methods use "getUnqualifiedType" to strip off address // space qualifiers if present. inline bool Type::isFunctionType() const { return isa(CanonicalType.getUnqualifiedType()); } inline bool Type::isPointerType() const { - return isa(CanonicalType.getUnqualifiedType()); + return isa(CanonicalType.getUnqualifiedType()); } inline bool Type::isAnyPointerType() const { return isPointerType() || isObjCObjectPointerType(); } inline bool Type::isBlockPointerType() const { - return isa(CanonicalType.getUnqualifiedType()); + return isa(CanonicalType.getUnqualifiedType()); } inline bool Type::isReferenceType() const { return isa(CanonicalType.getUnqualifiedType()); @@ -2417,12 +2417,12 @@ inline bool Type::isOverloadableType() const { inline bool Type::hasPointerRepresentation() const { return (isPointerType() || isReferenceType() || isBlockPointerType() || - isObjCInterfaceType() || isObjCObjectPointerType() || + isObjCInterfaceType() || isObjCObjectPointerType() || isObjCQualifiedInterfaceType() || isNullPtrType()); } inline bool Type::hasObjCPointerRepresentation() const { - return (isObjCInterfaceType() || isObjCObjectPointerType() || + return (isObjCInterfaceType() || isObjCObjectPointerType() || isObjCQualifiedInterfaceType()); } @@ -2434,13 +2434,13 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, Diagnostic::ak_qualtype); return DB; } - + /// Member-template getAs'. template const T *Type::getAs() const { // If this is directly a T type, return it. if (const T *Ty = dyn_cast(this)) return Ty; - + // If the canonical form of this type isn't the right kind, reject it. if (!isa(CanonicalType)) { // Look through type qualifiers @@ -2448,11 +2448,11 @@ template const T *Type::getAs() const { return CanonicalType.getUnqualifiedType()->getAs(); return 0; } - + // If this is a typedef for a pointer type, strip the typedef off without // losing all typedef information. return cast(getDesugaredType()); -} +} } // end namespace clang diff --git a/clang/include/clang/AST/TypeLoc.h b/clang/include/clang/AST/TypeLoc.h index 29955d37a972b0fd1cb5a2dbfa32e18e166fbc09..bb9744a20202655399f00ce4e0fc2b3260c6bab8 100644 --- a/clang/include/clang/AST/TypeLoc.h +++ b/clang/include/clang/AST/TypeLoc.h @@ -30,7 +30,7 @@ class TypeLoc { protected: QualType Ty; void *Data; - + TypeLoc(QualType ty, void *data) : Ty(ty), Data(data) { } static TypeLoc Create(QualType ty, void *data) { return TypeLoc(ty,data); } friend class DeclaratorInfo; @@ -86,7 +86,7 @@ public: class DeclaratorLoc : public TypeLoc { public: /// \brief Find the TypeSpecLoc that is part of this DeclaratorLoc. - TypeSpecLoc getTypeSpecLoc() const; + TypeSpecLoc getTypeSpecLoc() const; static bool classof(const TypeLoc *TL); static bool classof(const DeclaratorLoc *TL) { return true; } @@ -98,7 +98,7 @@ class DefaultTypeSpecLoc : public TypeSpecLoc { struct Info { SourceLocation StartLoc; }; - + public: SourceLocation getStartLoc() const { return static_cast(Data)->StartLoc; @@ -137,7 +137,7 @@ public: SourceRange getSourceRange() const { return SourceRange(getNameLoc(), getNameLoc()); } - + /// \brief Returns the size of the type source info data block that is /// specific to this type. unsigned getLocalDataSize() const { return sizeof(Info); } @@ -445,7 +445,7 @@ class TypeLocVisitor { #define TYPELOC(CLASS, PARENT, TYPE) \ RetTy Visit##TYPE(TYPE *) { \ return Impl->Visit##CLASS(reinterpret_cast(TyLoc)); \ - } + } #include "clang/AST/TypeLocNodes.def" }; diff --git a/clang/include/clang/AST/TypeOrdering.h b/clang/include/clang/AST/TypeOrdering.h index 4f60273d68095c16091e857a132b913db26d428f..652f4f70bd16d3d3d56e2002b14d5bb1843e9ef1 100644 --- a/clang/include/clang/AST/TypeOrdering.h +++ b/clang/include/clang/AST/TypeOrdering.h @@ -37,7 +37,7 @@ namespace llvm { template<> struct DenseMapInfo { static inline clang::QualType getEmptyKey() { return clang::QualType(); } - static inline clang::QualType getTombstoneKey() { + static inline clang::QualType getTombstoneKey() { using clang::QualType; return QualType::getFromOpaquePtr(reinterpret_cast(-1)); } @@ -51,11 +51,11 @@ namespace llvm { return LHS == RHS; } - static bool isPod() { + static bool isPod() { // QualType isn't *technically* a POD type. However, we can get // away with calling it a POD type since its copy constructor, // copy assignment operator, and destructor are all trivial. - return true; + return true; } }; } diff --git a/clang/include/clang/AST/TypeVisitor.h b/clang/include/clang/AST/TypeVisitor.h index 8386bfc620c9b04184e335fb813e2535e7b2c6e1..19f7f42a897a84c9901c4b57769702106fbc07b1 100644 --- a/clang/include/clang/AST/TypeVisitor.h +++ b/clang/include/clang/AST/TypeVisitor.h @@ -17,10 +17,10 @@ #include "clang/AST/Type.h" namespace clang { - + #define DISPATCH(CLASS) \ return static_cast(this)->Visit ## CLASS(static_cast(T)) - + template class TypeVisitor { public: @@ -28,12 +28,12 @@ public: // Top switch stmt: dispatch to VisitFooStmt for each FooStmt. switch (T->getTypeClass()) { default: assert(0 && "Unknown type class!"); -#define ABSTRACT_TYPE(CLASS, PARENT) +#define ABSTRACT_TYPE(CLASS, PARENT) #define TYPE(CLASS, PARENT) case Type::CLASS: DISPATCH(CLASS##Type); #include "clang/AST/TypeNodes.def" } } - + // If the implementation chooses not to implement a certain visit method, fall // back on superclass. #define TYPE(CLASS, PARENT) RetTy Visit##CLASS##Type(CLASS##Type *T) { \ diff --git a/clang/include/clang/Analysis/Analyses/LiveVariables.h b/clang/include/clang/Analysis/Analyses/LiveVariables.h index b41cd684e951c3ab9e47a898c150f7a898bcc4b5..17f772da0c6dae7db933fd0c27ad403fb14172ca 100644 --- a/clang/include/clang/Analysis/Analyses/LiveVariables.h +++ b/clang/include/clang/Analysis/Analyses/LiveVariables.h @@ -23,7 +23,7 @@ namespace clang { class Stmt; class DeclRefExpr; class SourceManager; - + struct LiveVariables_ValueTypes { struct ObserverTy; @@ -35,77 +35,77 @@ struct LiveVariables_ValueTypes { // (so that we don't explore such expressions twice). We also want // to compute liveness information for block-level expressions, since these // act as "temporary" values. - + struct AnalysisDataTy : public StmtDeclBitVector_Types::AnalysisDataTy { ObserverTy* Observer; ValTy AlwaysLive; - + AnalysisDataTy() : Observer(NULL) {} }; - + //===-----------------------------------------------------===// // ObserverTy - Observer for uninitialized values queries. //===-----------------------------------------------------===// struct ObserverTy { virtual ~ObserverTy() {} - + /// ObserveStmt - A callback invoked right before invoking the /// liveness transfer function on the given statement. - virtual void ObserveStmt(Stmt* S, const AnalysisDataTy& AD, + virtual void ObserveStmt(Stmt* S, const AnalysisDataTy& AD, const ValTy& V) {} - + virtual void ObserverKill(DeclRefExpr* DR) {} }; }; class LiveVariables : public DataflowValues { - - + + public: typedef LiveVariables_ValueTypes::ObserverTy ObserverTy; - + LiveVariables(ASTContext& Ctx, CFG& cfg); - + /// IsLive - Return true if a variable is live at beginning of a /// specified block. bool isLive(const CFGBlock* B, const VarDecl* D) const; - + /// IsLive - Returns true if a variable is live at the beginning of the /// the statement. This query only works if liveness information /// has been recorded at the statement level (see runOnAllBlocks), and /// only returns liveness information for block-level expressions. bool isLive(const Stmt* S, const VarDecl* D) const; - + /// IsLive - Returns true the block-level expression "value" is live /// before the given block-level expression (see runOnAllBlocks). bool isLive(const Stmt* Loc, const Stmt* StmtVal) const; - + /// IsLive - Return true if a variable is live according to the /// provided livness bitvector. bool isLive(const ValTy& V, const VarDecl* D) const; - + /// dumpLiveness - Print to stderr the liveness information encoded /// by a specified bitvector. void dumpLiveness(const ValTy& V, SourceManager& M) const; - + /// dumpBlockLiveness - Print to stderr the liveness information /// associated with each basic block. void dumpBlockLiveness(SourceManager& M) const; - + /// getNumDecls - Return the number of variables (declarations) that /// whose liveness status is being tracked by the dataflow /// analysis. unsigned getNumDecls() const { return getAnalysisData().getNumDecls(); } - + /// IntializeValues - This routine can perform extra initialization, but /// for LiveVariables this does nothing since all that logic is in - /// the constructor. + /// the constructor. void InitializeValues(const CFG& cfg) {} - + void runOnCFG(CFG& cfg); - + /// runOnAllBlocks - Propagate the dataflow values once for each block, /// starting from the current dataflow values. 'recordStmtValues' indicates /// whether the method should store dataflow values per each individual diff --git a/clang/include/clang/Analysis/Analyses/UninitializedValues.h b/clang/include/clang/Analysis/Analyses/UninitializedValues.h index 7a9da03e4bd287c227ed8b97615cb4e2eb774f92..8a967c3f6edce006569809e9738a2dc435911e2a 100644 --- a/clang/include/clang/Analysis/Analyses/UninitializedValues.h +++ b/clang/include/clang/Analysis/Analyses/UninitializedValues.h @@ -24,7 +24,7 @@ namespace clang { class Expr; class DeclRefExpr; class VarDecl; - + /// UninitializedValues_ValueTypes - Utility class to wrap type declarations /// for dataflow values and dataflow analysis state for the /// Unitialized Values analysis. @@ -32,39 +32,39 @@ class UninitializedValues_ValueTypes { public: struct ObserverTy; - - struct AnalysisDataTy : public StmtDeclBitVector_Types::AnalysisDataTy { + + struct AnalysisDataTy : public StmtDeclBitVector_Types::AnalysisDataTy { AnalysisDataTy() : Observer(NULL), FullUninitTaint(true) {} virtual ~AnalysisDataTy() {}; - + ObserverTy* Observer; bool FullUninitTaint; }; - + typedef StmtDeclBitVector_Types::ValTy ValTy; - + //===--------------------------------------------------------------------===// // ObserverTy - Observer for querying DeclRefExprs that use an uninitalized // value. //===--------------------------------------------------------------------===// - + struct ObserverTy { virtual ~ObserverTy(); - virtual void ObserveDeclRefExpr(ValTy& Val, AnalysisDataTy& AD, + virtual void ObserveDeclRefExpr(ValTy& Val, AnalysisDataTy& AD, DeclRefExpr* DR, VarDecl* VD) = 0; - }; + }; }; /// UninitializedValues - Objects of this class encapsulate dataflow analysis /// information regarding what variable declarations in a function are /// potentially unintialized. -class UninitializedValues : - public DataflowValues { +class UninitializedValues : + public DataflowValues { public: typedef UninitializedValues_ValueTypes::ObserverTy ObserverTy; UninitializedValues(CFG &cfg) { getAnalysisData().setCFG(cfg); } - + /// IntializeValues - Create initial dataflow values and meta data for /// a given CFG. This is intended to be called by the dataflow solver. void InitializeValues(const CFG& cfg); diff --git a/clang/include/clang/Analysis/AnalysisDiagnostic.h b/clang/include/clang/Analysis/AnalysisDiagnostic.h index 3ee733518595b8d7d23d62be1de3bbbb34e15040..114ae74b0c061a4abe96cff5b0065733c9ac2aa5 100644 --- a/clang/include/clang/Analysis/AnalysisDiagnostic.h +++ b/clang/include/clang/Analysis/AnalysisDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define ANALYSISSTART diff --git a/clang/include/clang/Analysis/CFG.h b/clang/include/clang/Analysis/CFG.h index 34dedc074a0d55376e500532aa452dabd144b50c..dab718cbac817a365245869c5fa92acfa3474f25 100644 --- a/clang/include/clang/Analysis/CFG.h +++ b/clang/include/clang/Analysis/CFG.h @@ -65,27 +65,27 @@ class CFGBlock { /// statements in the block. When this variable is non-NULL, it is /// either an instance of LabelStmt or SwitchCase. Stmt *Label; - + /// Terminator - The terminator for a basic block that /// indicates the type of control-flow that occurs between a block /// and its successors. Stmt *Terminator; - + /// LoopTarget - Some blocks are used to represent the "loop edge" to /// the start of a loop from within the loop body. This Stmt* will be /// refer to the loop statement for such blocks (and be null otherwise). - const Stmt *LoopTarget; - + const Stmt *LoopTarget; + /// BlockID - A numerical ID assigned to a CFGBlock during construction /// of the CFG. unsigned BlockID; - + /// Predecessors/Successors - Keep track of the predecessor / successor /// CFG blocks. typedef std::vector AdjacentBlocks; AdjacentBlocks Preds; AdjacentBlocks Succs; - + public: explicit CFGBlock(unsigned blockid) : Label(NULL), Terminator(NULL), LoopTarget(NULL), BlockID(blockid) {} @@ -96,25 +96,25 @@ public: typedef StatementListTy::const_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; - + Stmt* front() const { return Stmts.front(); } Stmt* back() const { return Stmts.back(); } - + iterator begin() { return Stmts.begin(); } iterator end() { return Stmts.end(); } const_iterator begin() const { return Stmts.begin(); } - const_iterator end() const { return Stmts.end(); } + const_iterator end() const { return Stmts.end(); } reverse_iterator rbegin() { return Stmts.rbegin(); } reverse_iterator rend() { return Stmts.rend(); } const_reverse_iterator rbegin() const { return Stmts.rbegin(); } const_reverse_iterator rend() const { return Stmts.rend(); } - + unsigned size() const { return Stmts.size(); } bool empty() const { return Stmts.empty(); } Stmt* operator[](size_t i) const { assert (i < size()); return Stmts[i]; } - + // CFG iterators typedef AdjacentBlocks::iterator pred_iterator; typedef AdjacentBlocks::const_iterator const_pred_iterator; @@ -125,22 +125,22 @@ public: typedef AdjacentBlocks::const_iterator const_succ_iterator; typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator; typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator; - + pred_iterator pred_begin() { return Preds.begin(); } pred_iterator pred_end() { return Preds.end(); } const_pred_iterator pred_begin() const { return Preds.begin(); } const_pred_iterator pred_end() const { return Preds.end(); } - + pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); } - pred_reverse_iterator pred_rend() { return Preds.rend(); } + pred_reverse_iterator pred_rend() { return Preds.rend(); } const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); } const_pred_reverse_iterator pred_rend() const { return Preds.rend(); } - succ_iterator succ_begin() { return Succs.begin(); } + succ_iterator succ_begin() { return Succs.begin(); } succ_iterator succ_end() { return Succs.end(); } const_succ_iterator succ_begin() const { return Succs.begin(); } - const_succ_iterator succ_end() const { return Succs.end(); } - + const_succ_iterator succ_end() const { return Succs.end(); } + succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); } succ_reverse_iterator succ_rend() { return Succs.rend(); } const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); } @@ -151,9 +151,9 @@ public: unsigned pred_size() const { return Preds.size(); } bool pred_empty() const { return Preds.empty(); } - + // Manipulation of block contents - + void appendStmt(Stmt* Statement) { Stmts.push_back(Statement); } void setTerminator(Stmt* Statement) { Terminator = Statement; } void setLabel(Stmt* Statement) { Label = Statement; } @@ -161,35 +161,35 @@ public: Stmt* getTerminator() { return Terminator; } const Stmt* getTerminator() const { return Terminator; } - + Stmt* getTerminatorCondition(); - + const Stmt* getTerminatorCondition() const { return const_cast(this)->getTerminatorCondition(); } - + const Stmt *getLoopTarget() const { return LoopTarget; } - + bool hasBinaryBranchTerminator() const; - + Stmt* getLabel() { return Label; } const Stmt* getLabel() const { return Label; } - + void reverseStmts(); - + void addSuccessor(CFGBlock* Block) { if (Block) Block->Preds.push_back(this); Succs.push_back(Block); } - + unsigned getBlockID() const { return BlockID; } - + void dump(const CFG *cfg, const LangOptions &LO) const; void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const; void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const; }; - + /// CFG - Represents a source-level, intra-procedural CFG that represents the /// control-flow of a Stmt. The Stmt can represent an entire function body, @@ -205,28 +205,28 @@ public: //===--------------------------------------------------------------------===// /// buildCFG - Builds a CFG from an AST. The responsibility to free the - /// constructed CFG belongs to the caller. - static CFG* buildCFG(Stmt* AST, ASTContext *C); - + /// constructed CFG belongs to the caller. + static CFG* buildCFG(Stmt* AST, ASTContext *C); + /// createBlock - Create a new block in the CFG. The CFG owns the block; /// the caller should not directly free it. CFGBlock* createBlock(); - + /// setEntry - Set the entry block of the CFG. This is typically used /// only during CFG construction. Most CFG clients expect that the /// entry block has no predecessors and contains no statements. void setEntry(CFGBlock *B) { Entry = B; } - + /// setIndirectGotoBlock - Set the block used for indirect goto jumps. /// This is typically used only during CFG construction. void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; } - + //===--------------------------------------------------------------------===// // Block Iterators //===--------------------------------------------------------------------===// typedef std::list CFGBlockListTy; - + typedef CFGBlockListTy::iterator iterator; typedef CFGBlockListTy::const_iterator const_iterator; typedef std::reverse_iterator reverse_iterator; @@ -234,17 +234,17 @@ public: CFGBlock& front() { return Blocks.front(); } CFGBlock& back() { return Blocks.back(); } - + iterator begin() { return Blocks.begin(); } iterator end() { return Blocks.end(); } const_iterator begin() const { return Blocks.begin(); } - const_iterator end() const { return Blocks.end(); } - + const_iterator end() const { return Blocks.end(); } + reverse_iterator rbegin() { return Blocks.rbegin(); } reverse_iterator rend() { return Blocks.rend(); } const_reverse_iterator rbegin() const { return Blocks.rbegin(); } const_reverse_iterator rend() const { return Blocks.rend(); } - + CFGBlock& getEntry() { return *Entry; } const CFGBlock& getEntry() const { return *Entry; } CFGBlock& getExit() { return *Exit; } @@ -252,18 +252,18 @@ public: CFGBlock* getIndirectGotoBlock() { return IndirectGotoBlock; } const CFGBlock* getIndirectGotoBlock() const { return IndirectGotoBlock; } - + //===--------------------------------------------------------------------===// // Member templates useful for various batch operations over CFGs. //===--------------------------------------------------------------------===// - + template void VisitBlockStmts(CALLBACK& O) const { for (const_iterator I=begin(), E=end(); I != E; ++I) for (CFGBlock::const_iterator BI=I->begin(), BE=I->end(); BI != BE; ++BI) O(*BI); - } - + } + //===--------------------------------------------------------------------===// // CFG Introspection. //===--------------------------------------------------------------------===// @@ -275,11 +275,11 @@ public: operator bool() const { return Idx >= 0; } operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; } }; - + bool isBlkExpr(const Stmt* S) { return getBlkExprNum(S); } BlkExprNumTy getBlkExprNum(const Stmt* S); unsigned getNumBlkExprs(); - + /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which /// start at 0). unsigned getNumBlockIDs() const { return NumBlockIDs; } @@ -296,15 +296,15 @@ public: // Internal: constructors and data. //===--------------------------------------------------------------------===// - CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0), + CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0), BlkExprMap(NULL) {}; - + ~CFG(); - + llvm::BumpPtrAllocator& getAllocator() { return Alloc; } - + private: CFGBlock* Entry; CFGBlock* Exit; @@ -312,14 +312,14 @@ private: // for indirect gotos CFGBlockListTy Blocks; unsigned NumBlockIDs; - + // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h. - // It represents a map from Expr* to integers to record the set of + // It represents a map from Expr* to integers to record the set of // block-level expressions and their "statement number" in the CFG. void* BlkExprMap; - + /// Alloc - An internal allocator. - llvm::BumpPtrAllocator Alloc; + llvm::BumpPtrAllocator Alloc; }; } // end namespace clang @@ -334,13 +334,13 @@ namespace llvm { template <> struct GraphTraits { typedef clang::CFGBlock NodeType; typedef clang::CFGBlock::succ_iterator ChildIteratorType; - + static NodeType* getEntryNode(clang::CFGBlock* BB) { return BB; } static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } - + static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } }; @@ -348,13 +348,13 @@ template <> struct GraphTraits { template <> struct GraphTraits { typedef const clang::CFGBlock NodeType; typedef clang::CFGBlock::const_succ_iterator ChildIteratorType; - + static NodeType* getEntryNode(const clang::CFGBlock* BB) { return BB; } - + static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } - + static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } }; @@ -368,27 +368,27 @@ template <> struct GraphTraits > { static inline ChildIteratorType child_begin(NodeType* N) { return N->pred_begin(); } - + static inline ChildIteratorType child_end(NodeType* N) { return N->pred_end(); } }; // Traits for: CFG -template <> struct GraphTraits +template <> struct GraphTraits : public GraphTraits { typedef clang::CFG::iterator nodes_iterator; - - static NodeType *getEntryNode(clang::CFG* F) { return &F->getEntry(); } + + static NodeType *getEntryNode(clang::CFG* F) { return &F->getEntry(); } static nodes_iterator nodes_begin(clang::CFG* F) { return F->begin(); } static nodes_iterator nodes_end(clang::CFG* F) { return F->end(); } }; -template <> struct GraphTraits< const clang::CFG* > +template <> struct GraphTraits< const clang::CFG* > : public GraphTraits< const clang::CFGBlock* > { - typedef clang::CFG::const_iterator nodes_iterator; + typedef clang::CFG::const_iterator nodes_iterator; static NodeType *getEntryNode( const clang::CFG* F) { return &F->getEntry(); } static nodes_iterator nodes_begin( const clang::CFG* F) { return F->begin(); } @@ -404,7 +404,7 @@ template <> struct GraphTraits > static nodes_iterator nodes_begin(const clang::CFG* F) { return F->begin();} static nodes_iterator nodes_end(const clang::CFG* F) { return F->end(); } }; - + } // end llvm namespace #endif diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowSolver.h b/clang/include/clang/Analysis/FlowSensitive/DataflowSolver.h index b0614e824f9afbeb16d7a62533d59f8ce84f348a..da4913206def27639b474f67f68c24a737450469 100644 --- a/clang/include/clang/Analysis/FlowSensitive/DataflowSolver.h +++ b/clang/include/clang/Analysis/FlowSensitive/DataflowSolver.h @@ -33,15 +33,15 @@ public: /// enqueue - Add a block to the worklist. Blocks already on the /// worklist are not added a second time. void enqueue(const CFGBlock* B) { wlist.insert(B); } - + /// dequeue - Remove a block from the worklist. const CFGBlock* dequeue() { assert (!wlist.empty()); const CFGBlock* B = *wlist.begin(); wlist.erase(B); - return B; + return B; } - + /// isEmpty - Return true if the worklist is empty. bool isEmpty() const { return wlist.empty(); } }; @@ -59,20 +59,20 @@ template <> struct ItrTraits { typedef CFGBlock::const_pred_iterator PrevBItr; typedef CFGBlock::const_succ_iterator NextBItr; typedef CFGBlock::const_iterator StmtItr; - + static PrevBItr PrevBegin(const CFGBlock* B) { return B->pred_begin(); } static PrevBItr PrevEnd(const CFGBlock* B) { return B->pred_end(); } - - static NextBItr NextBegin(const CFGBlock* B) { return B->succ_begin(); } + + static NextBItr NextBegin(const CFGBlock* B) { return B->succ_begin(); } static NextBItr NextEnd(const CFGBlock* B) { return B->succ_end(); } - + static StmtItr StmtBegin(const CFGBlock* B) { return B->begin(); } static StmtItr StmtEnd(const CFGBlock* B) { return B->end(); } - + static BlockEdge PrevEdge(const CFGBlock* B, const CFGBlock* Prev) { return BlockEdge(Prev, B, 0); } - + static BlockEdge NextEdge(const CFGBlock* B, const CFGBlock* Next) { return BlockEdge(B, Next, 0); } @@ -82,20 +82,20 @@ template <> struct ItrTraits { typedef CFGBlock::const_succ_iterator PrevBItr; typedef CFGBlock::const_pred_iterator NextBItr; typedef CFGBlock::const_reverse_iterator StmtItr; - - static PrevBItr PrevBegin(const CFGBlock* B) { return B->succ_begin(); } + + static PrevBItr PrevBegin(const CFGBlock* B) { return B->succ_begin(); } static PrevBItr PrevEnd(const CFGBlock* B) { return B->succ_end(); } - - static NextBItr NextBegin(const CFGBlock* B) { return B->pred_begin(); } + + static NextBItr NextBegin(const CFGBlock* B) { return B->pred_begin(); } static NextBItr NextEnd(const CFGBlock* B) { return B->pred_end(); } - + static StmtItr StmtBegin(const CFGBlock* B) { return B->rbegin(); } - static StmtItr StmtEnd(const CFGBlock* B) { return B->rend(); } - + static StmtItr StmtEnd(const CFGBlock* B) { return B->rend(); } + static BlockEdge PrevEdge(const CFGBlock* B, const CFGBlock* Prev) { return BlockEdge(B, Prev, 0); } - + static BlockEdge NextEdge(const CFGBlock* B, const CFGBlock* Next) { return BlockEdge(Next, B, 0); } @@ -105,7 +105,7 @@ template <> struct ItrTraits { //===----------------------------------------------------------------------===// /// DataflowSolverTy - Generic dataflow solver. //===----------------------------------------------------------------------===// - + template second); } } - + // Set the data for the block. D.getBlockDataMap()[B].copyValues(V); - } + } /// ProcessBlock - Process the transfer functions for a given block. void ProcessBlock(const CFGBlock* B, bool recordStmtValues, dataflow::forward_analysis_tag) { - + for (StmtItr I=ItrTraits::StmtBegin(B), E=ItrTraits::StmtEnd(B); I!=E;++I) ProcessStmt(*I, recordStmtValues, AnalysisDirTag()); - - TF.VisitTerminator(const_cast(B)); + + TF.VisitTerminator(const_cast(B)); } - + void ProcessBlock(const CFGBlock* B, bool recordStmtValues, dataflow::backward_analysis_tag) { - + TF.VisitTerminator(const_cast(B)); for (StmtItr I=ItrTraits::StmtBegin(B), E=ItrTraits::StmtEnd(B); I!=E;++I) ProcessStmt(*I, recordStmtValues, AnalysisDirTag()); } - + void ProcessStmt(const Stmt* S, bool record, dataflow::forward_analysis_tag) { if (record) D.getStmtDataMap()[S] = TF.getVal(); - TF.BlockStmt_Visit(const_cast(S)); + TF.BlockStmt_Visit(const_cast(S)); } - + void ProcessStmt(const Stmt* S, bool record, dataflow::backward_analysis_tag){ TF.BlockStmt_Visit(const_cast(S)); if (record) D.getStmtDataMap()[S] = TF.getVal(); @@ -272,12 +272,12 @@ private: if (CFGBlock *NextBlk = *I) UpdateEdgeValue(ItrTraits::NextEdge(B, NextBlk),V, NextBlk); } - + /// UpdateEdgeValue - Update the value associated with a given edge. void UpdateEdgeValue(BlockEdge E, ValTy& V, const CFGBlock* TargetBlock) { EdgeDataMapTy& M = D.getEdgeDataMap(); typename EdgeDataMapTy::iterator I = M.find(E); - + if (I == M.end()) { // First computed value for this edge? M[E].copyValues(V); WorkList.enqueue(TargetBlock); @@ -287,7 +287,7 @@ private: WorkList.enqueue(TargetBlock); } } - + private: DFValuesTy& D; DataflowWorkListTy WorkList; diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h index 8d7ba94b464268d8033300e9b8bc7edf863be7ea..648fe33ab0d49c06fbe1f1b722ba0344df72b771 100644 --- a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h +++ b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h @@ -24,7 +24,7 @@ /// Dataflow Directional Tag Classes. These are used for tag dispatching /// within the dataflow solver/transfer functions to determine what direction /// a dataflow analysis flows. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace clang { namespace dataflow { @@ -34,19 +34,19 @@ namespace dataflow { //===----------------------------------------------------------------------===// /// DataflowValues. Container class to store dataflow values for a CFG. -//===----------------------------------------------------------------------===// - +//===----------------------------------------------------------------------===// + template class DataflowValues { //===--------------------------------------------------------------------===// // Type declarations. - //===--------------------------------------------------------------------===// + //===--------------------------------------------------------------------===// public: typedef typename ValueTypes::ValTy ValTy; - typedef typename ValueTypes::AnalysisDataTy AnalysisDataTy; + typedef typename ValueTypes::AnalysisDataTy AnalysisDataTy; typedef _AnalysisDirTag AnalysisDirTag; typedef llvm::DenseMap EdgeDataMapTy; typedef llvm::DenseMap BlockDataMapTy; @@ -60,15 +60,15 @@ public: /// isForwardAnalysis - Returns true if the dataflow values are computed /// from a forward analysis. bool isForwardAnalysis() { return isForwardAnalysis(AnalysisDirTag()); } - + /// isBackwardAnalysis - Returns true if the dataflow values are computed /// from a backward analysis. bool isBackwardAnalysis() { return !isForwardAnalysis(); } - + private: bool isForwardAnalysis(dataflow::forward_analysis_tag) { return true; } - bool isForwardAnalysis(dataflow::backward_analysis_tag) { return false; } - + bool isForwardAnalysis(dataflow::backward_analysis_tag) { return false; } + //===--------------------------------------------------------------------===// // Initialization and accessors methods. //===--------------------------------------------------------------------===// @@ -76,10 +76,10 @@ private: public: DataflowValues() : StmtDataMap(NULL) {} ~DataflowValues() { delete StmtDataMap; } - + /// InitializeValues - Invoked by the solver to initialize state needed for /// dataflow analysis. This method is usually specialized by subclasses. - void InitializeValues(const CFG& cfg) {}; + void InitializeValues(const CFG& cfg) {}; /// getEdgeData - Retrieves the dataflow values associated with a @@ -89,28 +89,28 @@ public: assert (I != EdgeDataMap.end() && "No data associated with Edge."); return I->second; } - + const ValTy& getEdgeData(const BlockEdge& E) const { return reinterpret_cast(this)->getEdgeData(E); - } + } - /// getBlockData - Retrieves the dataflow values associated with a + /// getBlockData - Retrieves the dataflow values associated with a /// specified CFGBlock. If the dataflow analysis is a forward analysis, /// this data is associated with the END of the block. If the analysis - /// is a backwards analysis, it is associated with the ENTRY of the block. + /// is a backwards analysis, it is associated with the ENTRY of the block. ValTy& getBlockData(const CFGBlock* B) { typename BlockDataMapTy::iterator I = BlockDataMap.find(B); assert (I != BlockDataMap.end() && "No data associated with block."); return I->second; } - + const ValTy& getBlockData(const CFGBlock* B) const { return const_cast(this)->getBlockData(B); } - - /// getStmtData - Retrieves the dataflow values associated with a + + /// getStmtData - Retrieves the dataflow values associated with a /// specified Stmt. If the dataflow analysis is a forward analysis, - /// this data corresponds to the point immediately before a Stmt. + /// this data corresponds to the point immediately before a Stmt. /// If the analysis is a backwards analysis, it is associated with /// the point after a Stmt. This data is only computed for block-level /// expressions, and only when requested when the analysis is executed. @@ -120,11 +120,11 @@ public: assert (I != StmtDataMap->end() && "No data associated with statement."); return I->second; } - + const ValTy& getStmtData(const Stmt* S) const { return const_cast(this)->getStmtData(S); } - + /// getEdgeDataMap - Retrieves the internal map between CFG edges and /// dataflow values. Usually used by a dataflow solver to compute /// values for blocks. @@ -138,35 +138,35 @@ public: /// to the dataflow values at the end of the block. BlockDataMapTy& getBlockDataMap() { return BlockDataMap; } const BlockDataMapTy& getBlockDataMap() const { return BlockDataMap; } - + /// getStmtDataMap - Retrieves the internal map between Stmts and /// dataflow values. StmtDataMapTy& getStmtDataMap() { if (!StmtDataMap) StmtDataMap = new StmtDataMapTy(); return *StmtDataMap; } - + const StmtDataMapTy& getStmtDataMap() const { return const_cast(this)->getStmtDataMap(); } - /// getAnalysisData - Retrieves the meta data associated with a - /// dataflow analysis for analyzing a particular CFG. + /// getAnalysisData - Retrieves the meta data associated with a + /// dataflow analysis for analyzing a particular CFG. /// This is typically consumed by transfer function code (via the solver). /// This can also be used by subclasses to interpret the dataflow values. AnalysisDataTy& getAnalysisData() { return AnalysisData; } const AnalysisDataTy& getAnalysisData() const { return AnalysisData; } - + //===--------------------------------------------------------------------===// // Internal data. //===--------------------------------------------------------------------===// - + protected: EdgeDataMapTy EdgeDataMap; BlockDataMapTy BlockDataMap; StmtDataMapTy* StmtDataMap; AnalysisDataTy AnalysisData; -}; +}; } // end namespace clang #endif diff --git a/clang/include/clang/Analysis/LocalCheckers.h b/clang/include/clang/Analysis/LocalCheckers.h index c6d53e60ef62bed3e5ceaa97278514e3a0598843..ffcffe3305eecaaf2e5287fcdf1231440522e349 100644 --- a/clang/include/clang/Analysis/LocalCheckers.h +++ b/clang/include/clang/Analysis/LocalCheckers.h @@ -31,28 +31,28 @@ class BugReporter; class ObjCImplementationDecl; class LangOptions; class GRExprEngine; - -void CheckDeadStores(LiveVariables& L, BugReporter& BR); - + +void CheckDeadStores(LiveVariables& L, BugReporter& BR); + void CheckUninitializedValues(CFG& cfg, ASTContext& Ctx, Diagnostic& Diags, bool FullUninitTaint=false); - + GRTransferFuncs* MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled, - const LangOptions& lopts); - + const LangOptions& lopts); + void CheckObjCDealloc(const ObjCImplementationDecl* D, const LangOptions& L, BugReporter& BR); - + void CheckObjCInstMethSignature(const ObjCImplementationDecl *ID, BugReporter& BR); void CheckObjCUnusedIvar(const ObjCImplementationDecl *D, BugReporter& BR); - + void RegisterAppleChecks(GRExprEngine& Eng, const Decl &D); - + void CheckSecuritySyntaxOnly(const Decl *D, BugReporter &BR); - + } // end namespace clang #endif diff --git a/clang/include/clang/Analysis/PathDiagnostic.h b/clang/include/clang/Analysis/PathDiagnostic.h index 994b35e5efdac1f7a1238b30e4cd66f8ce221070..809c83161f3efae63a0312cd97b405ef88a8d969 100644 --- a/clang/include/clang/Analysis/PathDiagnostic.h +++ b/clang/include/clang/Analysis/PathDiagnostic.h @@ -38,21 +38,21 @@ class PathDiagnosticClient : public DiagnosticClient { public: PathDiagnosticClient() {} virtual ~PathDiagnosticClient() {} - + virtual void SetPreprocessor(Preprocessor *PP) {} - + virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info); - + virtual void HandlePathDiagnostic(const PathDiagnostic* D) = 0; - - enum PathGenerationScheme { Minimal, Extensive }; - virtual PathGenerationScheme getGenerationScheme() const { return Minimal; } + + enum PathGenerationScheme { Minimal, Extensive }; + virtual PathGenerationScheme getGenerationScheme() const { return Minimal; } virtual bool supportsLogicalOpControlFlow() const { return false; } virtual bool supportsAllBlockEdges() const { return false; } virtual bool useVerboseDescription() const { return true; } -}; - +}; + //===----------------------------------------------------------------------===// // Path-sensitive diagnostics. //===----------------------------------------------------------------------===// @@ -60,11 +60,11 @@ public: class PathDiagnosticRange : public SourceRange { public: const bool isPoint; - + PathDiagnosticRange(const SourceRange &R, bool isP = false) : SourceRange(R), isPoint(isP) {} }; - + class PathDiagnosticLocation { private: enum Kind { RangeK, SingleLocK, StmtK, DeclK } K; @@ -75,27 +75,27 @@ private: public: PathDiagnosticLocation() : K(SingleLocK), S(0), D(0), SM(0) {} - + PathDiagnosticLocation(FullSourceLoc L) : K(SingleLocK), R(L, L), S(0), D(0), SM(&L.getManager()) {} - + PathDiagnosticLocation(const Stmt *s, const SourceManager &sm) : K(StmtK), S(s), D(0), SM(&sm) {} - + PathDiagnosticLocation(SourceRange r, const SourceManager &sm) : K(RangeK), R(r), S(0), D(0), SM(&sm) {} - + PathDiagnosticLocation(const Decl *d, const SourceManager &sm) : K(DeclK), S(0), D(d), SM(&sm) {} - + bool operator==(const PathDiagnosticLocation &X) const { return K == X.K && R == X.R && S == X.S && D == X.D; } - + bool operator!=(const PathDiagnosticLocation &X) const { return K != X.K || R != X.R || S != X.S || D != X.D;; } - + PathDiagnosticLocation& operator=(const PathDiagnosticLocation &X) { K = X.K; R = X.R; @@ -104,26 +104,26 @@ public: SM = X.SM; return *this; } - + bool isValid() const { return SM != 0; } - + const SourceManager& getSourceManager() const { assert(isValid());return *SM;} - + FullSourceLoc asLocation() const; PathDiagnosticRange asRange() const; const Stmt *asStmt() const { assert(isValid()); return S; } const Decl *asDecl() const { assert(isValid()); return D; } - + bool hasRange() const { return K == StmtK || K == RangeK || K == DeclK; } - + void invalidate() { *this = PathDiagnosticLocation(); } - + void flatten(); - + const SourceManager& getManager() const { assert(isValid()); return *SM; } }; @@ -134,10 +134,10 @@ public: PathDiagnosticLocationPair(const PathDiagnosticLocation &start, const PathDiagnosticLocation &end) : Start(start), End(end) {} - + const PathDiagnosticLocation &getStart() const { return Start; } const PathDiagnosticLocation &getEnd() const { return End; } - + void flatten() { Start.flatten(); End.flatten(); @@ -146,7 +146,7 @@ public: //===----------------------------------------------------------------------===// // Path "pieces" for path-sensitive diagnostics. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// class PathDiagnosticPiece { public: @@ -159,7 +159,7 @@ private: const Kind kind; const DisplayHint Hint; std::vector ranges; - + // Do not implement: PathDiagnosticPiece(); PathDiagnosticPiece(const PathDiagnosticPiece &P); @@ -167,42 +167,42 @@ private: protected: PathDiagnosticPiece(const std::string& s, Kind k, DisplayHint hint = Below); - + PathDiagnosticPiece(const char* s, Kind k, DisplayHint hint = Below); PathDiagnosticPiece(Kind k, DisplayHint hint = Below); - + public: virtual ~PathDiagnosticPiece(); - + const std::string& getString() const { return str; } - + /// getDisplayHint - Return a hint indicating where the diagnostic should /// be displayed by the PathDiagnosticClient. DisplayHint getDisplayHint() const { return Hint; } - + virtual PathDiagnosticLocation getLocation() const = 0; virtual void flattenLocations() = 0; - + Kind getKind() const { return kind; } - + void addRange(SourceRange R) { ranges.push_back(R); } - + void addRange(SourceLocation B, SourceLocation E) { ranges.push_back(SourceRange(B,E)); } - + void addCodeModificationHint(const CodeModificationHint& Hint) { CodeModificationHints.push_back(Hint); } - + typedef const SourceRange* range_iterator; - + range_iterator ranges_begin() const { return ranges.empty() ? NULL : &ranges[0]; } - - range_iterator ranges_end() const { + + range_iterator ranges_end() const { return ranges_begin() + ranges.size(); } @@ -213,7 +213,7 @@ public: } code_modifications_iterator code_modifications_end() const { - return CodeModificationHints.empty()? 0 + return CodeModificationHints.empty()? 0 : &CodeModificationHints[0] + CodeModificationHints.size(); } @@ -221,7 +221,7 @@ public: return true; } }; - + class PathDiagnosticSpotPiece : public PathDiagnosticPiece { private: PathDiagnosticLocation Pos; @@ -234,30 +234,30 @@ public: assert(Pos.asLocation().isValid() && "PathDiagnosticSpotPiece's must have a valid location."); if (addPosRange && Pos.hasRange()) addRange(Pos.asRange()); - } + } PathDiagnosticLocation getLocation() const { return Pos; } virtual void flattenLocations() { Pos.flatten(); } }; - + class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece { public: PathDiagnosticEventPiece(const PathDiagnosticLocation &pos, const std::string& s, bool addPosRange = true) : PathDiagnosticSpotPiece(pos, s, Event, addPosRange) {} - + PathDiagnosticEventPiece(const PathDiagnosticLocation &pos, const char* s, bool addPosRange = true) : PathDiagnosticSpotPiece(pos, s, Event, addPosRange) {} - + ~PathDiagnosticEventPiece(); static inline bool classof(const PathDiagnosticPiece* P) { return P->getKind() == Event; } }; - + class PathDiagnosticControlFlowPiece : public PathDiagnosticPiece { std::vector LPairs; public: @@ -267,40 +267,40 @@ public: : PathDiagnosticPiece(s, ControlFlow) { LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos)); } - + PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos, const PathDiagnosticLocation &endPos, const char* s) : PathDiagnosticPiece(s, ControlFlow) { LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos)); } - + PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos, const PathDiagnosticLocation &endPos) : PathDiagnosticPiece(ControlFlow) { LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos)); } - + ~PathDiagnosticControlFlowPiece(); - + PathDiagnosticLocation getStartLocation() const { assert(!LPairs.empty() && "PathDiagnosticControlFlowPiece needs at least one location."); return LPairs[0].getStart(); } - + PathDiagnosticLocation getEndLocation() const { assert(!LPairs.empty() && "PathDiagnosticControlFlowPiece needs at least one location."); return LPairs[0].getEnd(); } - + void push_back(const PathDiagnosticLocationPair &X) { LPairs.push_back(X); } - + virtual PathDiagnosticLocation getLocation() const { return getStartLocation(); } - + typedef std::vector::iterator iterator; iterator begin() { return LPairs.begin(); } iterator end() { return LPairs.end(); } @@ -308,7 +308,7 @@ public: virtual void flattenLocations() { for (iterator I=begin(), E=end(); I!=E; ++I) I->flatten(); } - + typedef std::vector::const_iterator const_iterator; const_iterator begin() const { return LPairs.begin(); } @@ -318,32 +318,32 @@ public: return P->getKind() == ControlFlow; } }; - + class PathDiagnosticMacroPiece : public PathDiagnosticSpotPiece { std::vector SubPieces; public: PathDiagnosticMacroPiece(const PathDiagnosticLocation &pos) : PathDiagnosticSpotPiece(pos, "", Macro) {} - + ~PathDiagnosticMacroPiece(); - + bool containsEvent() const; void push_back(PathDiagnosticPiece* P) { SubPieces.push_back(P); } - + typedef std::vector::iterator iterator; iterator begin() { return SubPieces.begin(); } iterator end() { return SubPieces.end(); } - + virtual void flattenLocations() { PathDiagnosticSpotPiece::flattenLocations(); for (iterator I=begin(), E=end(); I!=E; ++I) (*I)->flattenLocations(); } - + typedef std::vector::const_iterator const_iterator; const_iterator begin() const { return SubPieces.begin(); } const_iterator end() const { return SubPieces.end(); } - + static inline bool classof(const PathDiagnosticPiece* P) { return P->getKind() == Macro; } @@ -359,129 +359,129 @@ class PathDiagnostic { std::string Desc; std::string Category; std::deque OtherDesc; - -public: + +public: PathDiagnostic(); - + PathDiagnostic(const char* bugtype, const char* desc, const char* category); - - PathDiagnostic(const std::string& bugtype, const std::string& desc, + + PathDiagnostic(const std::string& bugtype, const std::string& desc, const std::string& category); - + ~PathDiagnostic(); - + const std::string& getDescription() const { return Desc; } const std::string& getBugType() const { return BugType; } - const std::string& getCategory() const { return Category; } - + const std::string& getCategory() const { return Category; } + typedef std::deque::const_iterator meta_iterator; meta_iterator meta_begin() const { return OtherDesc.begin(); } meta_iterator meta_end() const { return OtherDesc.end(); } void addMeta(const std::string& s) { OtherDesc.push_back(s); } void addMeta(const char* s) { OtherDesc.push_back(s); } - + PathDiagnosticLocation getLocation() const { assert(Size > 0 && "getLocation() requires a non-empty PathDiagnostic."); return rbegin()->getLocation(); } - + void push_front(PathDiagnosticPiece* piece) { path.push_front(piece); ++Size; } - + void push_back(PathDiagnosticPiece* piece) { path.push_back(piece); ++Size; } - + PathDiagnosticPiece* back() { return path.back(); } - + const PathDiagnosticPiece* back() const { return path.back(); } - + unsigned size() const { return Size; } bool empty() const { return Size == 0; } - + void resetPath(bool deletePieces = true); - + class iterator { - public: + public: typedef std::deque::iterator ImplTy; - + typedef PathDiagnosticPiece value_type; typedef value_type& reference; typedef value_type* pointer; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; - + private: ImplTy I; - + public: iterator(const ImplTy& i) : I(i) {} - + bool operator==(const iterator& X) const { return I == X.I; } bool operator!=(const iterator& X) const { return I != X.I; } - + PathDiagnosticPiece& operator*() const { return **I; } PathDiagnosticPiece* operator->() const { return *I; } - + iterator& operator++() { ++I; return *this; } iterator& operator--() { --I; return *this; } }; - + class const_iterator { - public: + public: typedef std::deque::const_iterator ImplTy; - + typedef const PathDiagnosticPiece value_type; typedef value_type& reference; typedef value_type* pointer; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; - + private: ImplTy I; - + public: const_iterator(const ImplTy& i) : I(i) {} - + bool operator==(const const_iterator& X) const { return I == X.I; } bool operator!=(const const_iterator& X) const { return I != X.I; } - + reference operator*() const { return **I; } pointer operator->() const { return *I; } - + const_iterator& operator++() { ++I; return *this; } const_iterator& operator--() { --I; return *this; } }; - + typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; - + // forward iterator creation methods. - + iterator begin() { return path.begin(); } iterator end() { return path.end(); } - + const_iterator begin() const { return path.begin(); } const_iterator end() const { return path.end(); } - + // reverse iterator creation methods. reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin());} - + void flattenLocations() { for (iterator I = begin(), E = end(); I != E; ++I) I->flattenLocations(); } }; - - + + } //end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/AnalysisContext.h b/clang/include/clang/Analysis/PathSensitive/AnalysisContext.h index e69b4f529fe63ac56c7ea27bd07a10dde3b090a2..22f9902975d1599f9aa05e629a919487c0824ca9 100644 --- a/clang/include/clang/Analysis/PathSensitive/AnalysisContext.h +++ b/clang/include/clang/Analysis/PathSensitive/AnalysisContext.h @@ -27,7 +27,7 @@ class CFG; class LiveVariables; class ParentMap; class ImplicitParamDecl; - + /// AnalysisContext contains the context data for the function or method under /// analysis. class AnalysisContext { @@ -47,7 +47,7 @@ public: CFG *getCFG(); ParentMap &getParentMap(); LiveVariables *getLiveVariables(); - + /// Return the ImplicitParamDecl* associated with 'self' if this /// AnalysisContext wraps an ObjCMethodDecl. Returns NULL otherwise. const ImplicitParamDecl *getSelfDecl() const; @@ -58,7 +58,7 @@ class AnalysisContextManager { ContextMap Contexts; public: ~AnalysisContextManager(); - + AnalysisContext *getContext(const Decl *D); }; @@ -87,10 +87,10 @@ public: CFG *getCFG() const { return getAnalysisContext()->getCFG(); } - LiveVariables *getLiveVariables() const { + LiveVariables *getLiveVariables() const { return getAnalysisContext()->getLiveVariables(); } - + const ImplicitParamDecl *getSelfDecl() const { return Ctx->getSelfDecl(); } @@ -120,8 +120,8 @@ public: static void Profile(llvm::FoldingSetNodeID &ID, AnalysisContext *ctx, const LocationContext *parent, const Stmt *s); - static bool classof(const LocationContext* Ctx) { - return Ctx->getKind() == StackFrame; + static bool classof(const LocationContext* Ctx) { + return Ctx->getKind() == StackFrame; } }; @@ -140,8 +140,8 @@ public: static void Profile(llvm::FoldingSetNodeID &ID, AnalysisContext *ctx, const LocationContext *parent, const Stmt *s); - static bool classof(const LocationContext* Ctx) { - return Ctx->getKind() == Scope; + static bool classof(const LocationContext* Ctx) { + return Ctx->getKind() == Scope; } }; @@ -156,6 +156,6 @@ public: ScopeContext *getScope(AnalysisContext *ctx, const LocationContext *parent, const Stmt *s); }; - + } // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/AnalysisManager.h b/clang/include/clang/Analysis/PathSensitive/AnalysisManager.h index 97534c8716939f516215180117247d4e2f359c48..948bb1fe8a214b4fbf6b6c276ea77007220fee3d 100644 --- a/clang/include/clang/Analysis/PathSensitive/AnalysisManager.h +++ b/clang/include/clang/Analysis/PathSensitive/AnalysisManager.h @@ -38,7 +38,7 @@ class AnalysisManager : public BugReporterData { ConstraintManagerCreator CreateConstraintMgr; enum AnalysisScope { ScopeTU, ScopeDecl } AScope; - + bool DisplayedFunction; bool VisualizeEGDot; bool VisualizeEGUbi; @@ -55,13 +55,13 @@ class AnalysisManager : public BugReporterData { bool TrimGraph; public: - AnalysisManager(Decl *d, ASTContext &ctx, Diagnostic &diags, + AnalysisManager(Decl *d, ASTContext &ctx, Diagnostic &diags, const LangOptions &lang, PathDiagnosticClient *pd, StoreManagerCreator storemgr, ConstraintManagerCreator constraintmgr, - bool displayProgress, bool vizdot, bool vizubi, + bool displayProgress, bool vizdot, bool vizubi, bool purge, bool eager, bool trim) - : Ctx(ctx), Diags(diags), LangInfo(lang), PD(pd), + : Ctx(ctx), Diags(diags), LangInfo(lang), PD(pd), CreateStoreMgr(storemgr), CreateConstraintMgr(constraintmgr), AScope(ScopeDecl), DisplayedFunction(!displayProgress), VisualizeEGDot(vizdot), VisualizeEGUbi(vizubi), PurgeDead(purge), @@ -69,15 +69,15 @@ public: EntryContext = ContextMgr.getContext(d); } - - AnalysisManager(ASTContext &ctx, Diagnostic &diags, + + AnalysisManager(ASTContext &ctx, Diagnostic &diags, const LangOptions &lang, PathDiagnosticClient *pd, StoreManagerCreator storemgr, ConstraintManagerCreator constraintmgr, - bool displayProgress, bool vizdot, bool vizubi, + bool displayProgress, bool vizdot, bool vizubi, bool purge, bool eager, bool trim) - : Ctx(ctx), Diags(diags), LangInfo(lang), PD(pd), + : Ctx(ctx), Diags(diags), LangInfo(lang), PD(pd), CreateStoreMgr(storemgr), CreateConstraintMgr(constraintmgr), AScope(ScopeDecl), DisplayedFunction(!displayProgress), VisualizeEGDot(vizdot), VisualizeEGUbi(vizubi), PurgeDead(purge), @@ -90,17 +90,17 @@ public: EntryContext = ContextMgr.getContext(D); DisplayedFunction = false; } - - const Decl *getCodeDecl() const { + + const Decl *getCodeDecl() const { assert (AScope == ScopeDecl); return EntryContext->getDecl(); } - + Stmt *getBody() const { assert (AScope == ScopeDecl); return EntryContext->getBody(); } - + StoreManagerCreator getStoreManagerCreator() { return CreateStoreMgr; }; @@ -108,11 +108,11 @@ public: ConstraintManagerCreator getConstraintManagerCreator() { return CreateConstraintMgr; } - + virtual CFG *getCFG() { return EntryContext->getCFG(); } - + virtual ParentMap &getParentMap() { return EntryContext->getParentMap(); } @@ -120,31 +120,31 @@ public: virtual LiveVariables *getLiveVariables() { return EntryContext->getLiveVariables(); } - + virtual ASTContext &getASTContext() { return Ctx; } - + virtual SourceManager &getSourceManager() { return getASTContext().getSourceManager(); } - + virtual Diagnostic &getDiagnostic() { return Diags; } - + const LangOptions &getLangOptions() const { return LangInfo; } - + virtual PathDiagnosticClient *getPathDiagnosticClient() { - return PD.get(); + return PD.get(); } StackFrameContext *getEntryStackFrame() { return LocCtxMgr.getStackFrame(EntryContext, 0, 0); } - + bool shouldVisualizeGraphviz() const { return VisualizeEGDot; } bool shouldVisualizeUbigraph() const { return VisualizeEGUbi; } diff --git a/clang/include/clang/Analysis/PathSensitive/BasicValueFactory.h b/clang/include/clang/Analysis/PathSensitive/BasicValueFactory.h index 74d08e8410ee9c4bc022ab4050633e0d75d002cf..69cd9db77cb9dea5a301d1ed256d1470f357b7f0 100644 --- a/clang/include/clang/Analysis/PathSensitive/BasicValueFactory.h +++ b/clang/include/clang/Analysis/PathSensitive/BasicValueFactory.h @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// // // This file defines BasicValueFactory, a class that manages the lifetime -// of APSInt objects and symbolic constraints used by GRExprEngine +// of APSInt objects and symbolic constraints used by GRExprEngine // and related classes. // //===----------------------------------------------------------------------===// @@ -24,7 +24,7 @@ #include "llvm/ADT/ImmutableList.h" namespace clang { - + class GRState; class CompoundValData : public llvm::FoldingSetNode { @@ -32,13 +32,13 @@ class CompoundValData : public llvm::FoldingSetNode { llvm::ImmutableList L; public: - CompoundValData(QualType t, llvm::ImmutableList l) + CompoundValData(QualType t, llvm::ImmutableList l) : T(t), L(l) {} typedef llvm::ImmutableList::iterator iterator; iterator begin() const { return L.begin(); } - iterator end() const { return L.end(); } - + iterator end() const { return L.end(); } + static void Profile(llvm::FoldingSetNodeID& ID, QualType T, llvm::ImmutableList L); @@ -51,16 +51,16 @@ class LazyCompoundValData : public llvm::FoldingSetNode { public: LazyCompoundValData(const GRState *st, const TypedRegion *r) : state(st), region(r) {} - + const GRState *getState() const { return state; } const TypedRegion *getRegion() const { return region; } - + static void Profile(llvm::FoldingSetNodeID& ID, const GRState *state, const TypedRegion *region); - + void Profile(llvm::FoldingSetNodeID& ID) { Profile(ID, state, region); } }; - + class BasicValueFactory { typedef llvm::FoldingSet > APSIntSetTy; @@ -77,28 +77,28 @@ class BasicValueFactory { llvm::FoldingSet LazyCompoundValDataSet; public: - BasicValueFactory(ASTContext& ctx, llvm::BumpPtrAllocator& Alloc) + BasicValueFactory(ASTContext& ctx, llvm::BumpPtrAllocator& Alloc) : Ctx(ctx), BPAlloc(Alloc), PersistentSVals(0), PersistentSValPairs(0), SValListFactory(Alloc) {} ~BasicValueFactory(); - ASTContext& getContext() const { return Ctx; } + ASTContext& getContext() const { return Ctx; } const llvm::APSInt& getValue(const llvm::APSInt& X); const llvm::APSInt& getValue(const llvm::APInt& X, bool isUnsigned); const llvm::APSInt& getValue(uint64_t X, unsigned BitWidth, bool isUnsigned); const llvm::APSInt& getValue(uint64_t X, QualType T); - + /// Convert - Create a new persistent APSInt with the same value as 'From' /// but with the bitwidth and signedness of 'To'. const llvm::APSInt& Convert(const llvm::APSInt& To, const llvm::APSInt& From) { - + if (To.isUnsigned() == From.isUnsigned() && To.getBitWidth() == From.getBitWidth()) return From; - + return getValue(From.getSExtValue(), To.getBitWidth(), To.isUnsigned()); @@ -108,11 +108,11 @@ public: QualType T = isUnsigned ? Ctx.UnsignedIntTy : Ctx.IntTy; return getValue(X, T); } - + inline const llvm::APSInt& getMaxValue(const llvm::APSInt &v) { return getValue(llvm::APSInt::getMaxValue(v.getBitWidth(), v.isUnsigned())); } - + inline const llvm::APSInt& getMinValue(const llvm::APSInt &v) { return getValue(llvm::APSInt::getMinValue(v.getBitWidth(), v.isUnsigned())); } @@ -122,25 +122,25 @@ public: bool isUnsigned = T->isUnsignedIntegerType() || Loc::IsLocType(T); return getValue(llvm::APSInt::getMaxValue(Ctx.getTypeSize(T), isUnsigned)); } - + inline const llvm::APSInt& getMinValue(QualType T) { assert(T->isIntegerType() || Loc::IsLocType(T)); bool isUnsigned = T->isUnsignedIntegerType() || Loc::IsLocType(T); return getValue(llvm::APSInt::getMinValue(Ctx.getTypeSize(T), isUnsigned)); } - + inline const llvm::APSInt& Add1(const llvm::APSInt& V) { llvm::APSInt X = V; ++X; return getValue(X); } - + inline const llvm::APSInt& Sub1(const llvm::APSInt& V) { llvm::APSInt X = V; --X; return getValue(X); } - + inline const llvm::APSInt& getZeroWithPtrWidth(bool isUnsigned = true) { return getValue(0, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned); } @@ -152,21 +152,21 @@ public: inline const llvm::APSInt& getTruthValue(bool b, QualType T) { return getValue(b ? 1 : 0, Ctx.getTypeSize(T), false); } - + inline const llvm::APSInt& getTruthValue(bool b) { return getTruthValue(b, Ctx.IntTy); } - - const CompoundValData *getCompoundValData(QualType T, + + const CompoundValData *getCompoundValData(QualType T, llvm::ImmutableList Vals); - + const LazyCompoundValData *getLazyCompoundValData(const GRState *state, const TypedRegion *region); - + llvm::ImmutableList getEmptySValList() { return SValListFactory.GetEmptyList(); } - + llvm::ImmutableList consVals(SVal X, llvm::ImmutableList L) { return SValListFactory.Add(X, L); } @@ -174,13 +174,13 @@ public: const llvm::APSInt* EvaluateAPSInt(BinaryOperator::Opcode Op, const llvm::APSInt& V1, const llvm::APSInt& V2); - + const std::pair& getPersistentSValWithData(const SVal& V, uintptr_t Data); - + const std::pair& - getPersistentSValPair(const SVal& V1, const SVal& V2); - + getPersistentSValPair(const SVal& V1, const SVal& V2); + const SVal* getPersistentSVal(SVal X); }; diff --git a/clang/include/clang/Analysis/PathSensitive/BugReporter.h b/clang/include/clang/Analysis/PathSensitive/BugReporter.h index 0997edc6bb6dcc9dd5cebe5720d5e9d505889a09..55555c6df0c234543f69c114dfde7b5f8564aab1 100644 --- a/clang/include/clang/Analysis/PathSensitive/BugReporter.h +++ b/clang/include/clang/Analysis/PathSensitive/BugReporter.h @@ -27,7 +27,7 @@ #include namespace clang { - + class PathDiagnostic; class PathDiagnosticPiece; class PathDiagnosticClient; @@ -40,7 +40,7 @@ class GRState; class Stmt; class BugType; class ParentMap; - + //===----------------------------------------------------------------------===// // Interface for individual bug reports. //===----------------------------------------------------------------------===// @@ -51,10 +51,10 @@ public: virtual PathDiagnosticPiece* VisitNode(const ExplodedNode* N, const ExplodedNode* PrevN, BugReporterContext& BRC) = 0; - + virtual bool isOwnedByReporterContext() { return true; } }; - + // FIXME: Combine this with RangedBugReport and remove RangedBugReport. class BugReport : public BugReporterVisitor { protected: @@ -63,7 +63,7 @@ protected: std::string Description; const ExplodedNode *EndNode; SourceRange R; - + protected: friend class BugReporter; friend class BugReportEquivClass; @@ -71,7 +71,7 @@ protected: virtual void Profile(llvm::FoldingSetNodeID& hash) const { hash.AddInteger(getLocation().getRawEncoding()); } - + public: class NodeResolver { public: @@ -79,58 +79,58 @@ public: virtual const ExplodedNode* getOriginalNode(const ExplodedNode* N) = 0; }; - + BugReport(BugType& bt, const char* desc, const ExplodedNode *n) : BT(bt), Description(desc), EndNode(n) {} - + BugReport(BugType& bt, const char* shortDesc, const char* desc, const ExplodedNode *n) : BT(bt), ShortDescription(shortDesc), Description(desc), EndNode(n) {} virtual ~BugReport(); - + virtual bool isOwnedByReporterContext() { return false; } const BugType& getBugType() const { return BT; } BugType& getBugType() { return BT; } - + // FIXME: Perhaps this should be moved into a subclass? const ExplodedNode* getEndNode() const { return EndNode; } - + // FIXME: Do we need this? Maybe getLocation() should return a ProgramPoint // object. // FIXME: If we do need it, we can probably just make it private to // BugReporter. const Stmt* getStmt() const; - + const std::string& getDescription() const { return Description; } const std::string& getShortDescription() const { return ShortDescription.empty() ? Description : ShortDescription; } - + // FIXME: Is this needed? virtual std::pair getExtraDescriptiveText() { return std::make_pair((const char**)0,(const char**)0); } - + // FIXME: Perhaps move this into a subclass. virtual PathDiagnosticPiece* getEndPath(BugReporterContext& BRC, const ExplodedNode* N); - + /// getLocation - Return the "definitive" location of the reported bug. /// While a bug can span an entire path, usually there is a specific /// location that can be used to identify where the key issue occured. /// This location is used by clients rendering diagnostics. virtual SourceLocation getLocation() const; - + /// getRanges - Returns the source ranges associated with this bug. virtual void getRanges(const SourceRange*& beg, const SourceRange*& end); virtual PathDiagnosticPiece* VisitNode(const ExplodedNode* N, const ExplodedNode* PrevN, BugReporterContext& BR); - + virtual void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N) {} }; @@ -138,11 +138,11 @@ public: //===----------------------------------------------------------------------===// // BugTypes (collections of related reports). //===----------------------------------------------------------------------===// - + class BugReportEquivClass : public llvm::FoldingSetNode { // List of *owned* BugReport objects. std::list Reports; - + friend class BugReporter; void AddReport(BugReport* R) { Reports.push_back(R); } public: @@ -164,7 +164,7 @@ public: BugReport* operator*() const { return *impl; } BugReport* operator->() const { return *impl; } }; - + class const_iterator { std::list::const_iterator impl; public: @@ -175,14 +175,14 @@ public: const BugReport* operator*() const { return *impl; } const BugReport* operator->() const { return *impl; } }; - + iterator begin() { return iterator(Reports.begin()); } iterator end() { return iterator(Reports.end()); } - + const_iterator begin() const { return const_iterator(Reports.begin()); } const_iterator end() const { return const_iterator(Reports.end()); } }; - + class BugType { private: const std::string Name; @@ -192,45 +192,45 @@ private: public: BugType(const char *name, const char* cat) : Name(name), Category(cat) {} virtual ~BugType(); - + // FIXME: Should these be made strings as well? const std::string& getName() const { return Name; } const std::string& getCategory() const { return Category; } - virtual void FlushReports(BugReporter& BR); + virtual void FlushReports(BugReporter& BR); typedef llvm::FoldingSet::iterator iterator; iterator begin() { return EQClasses.begin(); } iterator end() { return EQClasses.end(); } - + typedef llvm::FoldingSet::const_iterator const_iterator; const_iterator begin() const { return EQClasses.begin(); } const_iterator end() const { return EQClasses.end(); } }; - + //===----------------------------------------------------------------------===// // Specialized subclasses of BugReport. //===----------------------------------------------------------------------===// - + // FIXME: Collapse this with the default BugReport class. class RangedBugReport : public BugReport { std::vector Ranges; public: RangedBugReport(BugType& D, const char* description, ExplodedNode *n) : BugReport(D, description, n) {} - + RangedBugReport(BugType& D, const char *shortDescription, const char *description, ExplodedNode *n) : BugReport(D, shortDescription, description, n) {} - + ~RangedBugReport(); // FIXME: Move this out of line. void addRange(SourceRange R) { Ranges.push_back(R); } - + // FIXME: Move this out of line. void getRanges(const SourceRange*& beg, const SourceRange*& end) { - + if (Ranges.empty()) { beg = NULL; end = NULL; @@ -241,36 +241,36 @@ public: } } }; - + class EnhancedBugReport : public RangedBugReport { public: typedef void (*VisitorCreator)(BugReporterContext &BRcC, const void *data, const ExplodedNode *N); - + private: typedef std::vector > Creators; Creators creators; - + public: EnhancedBugReport(BugType& D, const char* description, ExplodedNode *n) : RangedBugReport(D, description, n) {} - + EnhancedBugReport(BugType& D, const char *shortDescription, const char *description, ExplodedNode *n) : RangedBugReport(D, shortDescription, description, n) {} - + ~EnhancedBugReport() {} - - void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N) { + + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N) { for (Creators::iterator I = creators.begin(), E = creators.end(); I!=E; ++I) I->first(BRC, I->second, N); } - + void addVisitorCreator(VisitorCreator creator, const void *data) { creators.push_back(std::make_pair(creator, data)); } }; - + //===----------------------------------------------------------------------===// // BugReporter and friends. //===----------------------------------------------------------------------===// @@ -278,15 +278,15 @@ public: class BugReporterData { public: virtual ~BugReporterData(); - virtual Diagnostic& getDiagnostic() = 0; - virtual PathDiagnosticClient* getPathDiagnosticClient() = 0; + virtual Diagnostic& getDiagnostic() = 0; + virtual PathDiagnosticClient* getPathDiagnosticClient() = 0; virtual ASTContext& getASTContext() = 0; virtual SourceManager& getSourceManager() = 0; virtual CFG* getCFG() = 0; virtual ParentMap& getParentMap() = 0; virtual LiveVariables* getLiveVariables() = 0; }; - + class BugReporter { public: enum Kind { BaseBRKind, GRBugReporterKind }; @@ -296,9 +296,9 @@ private: BugTypesTy::Factory F; BugTypesTy BugTypes; - const Kind kind; + const Kind kind; BugReporterData& D; - + void FlushReport(BugReportEquivClass& EQ); protected: @@ -307,40 +307,40 @@ protected: public: BugReporter(BugReporterData& d) : BugTypes(F.GetEmptySet()), kind(BaseBRKind), D(d) {} virtual ~BugReporter(); - + void FlushReports(); - + Kind getKind() const { return kind; } - + Diagnostic& getDiagnostic() { return D.getDiagnostic(); } - + PathDiagnosticClient* getPathDiagnosticClient() { return D.getPathDiagnosticClient(); } - + typedef BugTypesTy::iterator iterator; iterator begin() { return BugTypes.begin(); } iterator end() { return BugTypes.end(); } - + ASTContext& getContext() { return D.getASTContext(); } - + SourceManager& getSourceManager() { return D.getSourceManager(); } - + CFG* getCFG() { return D.getCFG(); } - + ParentMap& getParentMap() { return D.getParentMap(); } - + LiveVariables* getLiveVariables() { return D.getLiveVariables(); } - + virtual void GeneratePathDiagnostic(PathDiagnostic& PD, BugReportEquivClass& EQ) {} void Register(BugType *BT); - + void EmitReport(BugReport *R); - + void EmitBasicReport(const char* BugName, const char* BugStr, SourceLocation Loc, SourceRange* RangeBeg, unsigned NumRanges); @@ -348,28 +348,28 @@ public: void EmitBasicReport(const char* BugName, const char* BugCategory, const char* BugStr, SourceLocation Loc, SourceRange* RangeBeg, unsigned NumRanges); - - + + void EmitBasicReport(const char* BugName, const char* BugStr, SourceLocation Loc) { EmitBasicReport(BugName, BugStr, Loc, 0, 0); } - + void EmitBasicReport(const char* BugName, const char* BugCategory, const char* BugStr, SourceLocation Loc) { EmitBasicReport(BugName, BugCategory, BugStr, Loc, 0, 0); } - + void EmitBasicReport(const char* BugName, const char* BugStr, SourceLocation Loc, SourceRange R) { EmitBasicReport(BugName, BugStr, Loc, &R, 1); } - + void EmitBasicReport(const char* BugName, const char* Category, const char* BugStr, SourceLocation Loc, SourceRange R) { EmitBasicReport(BugName, Category, BugStr, Loc, &R, 1); } - + static bool classof(const BugReporter* R) { return true; } }; @@ -377,12 +377,12 @@ public: class GRBugReporter : public BugReporter { GRExprEngine& Eng; llvm::SmallSet NotableSymbols; -public: +public: GRBugReporter(BugReporterData& d, GRExprEngine& eng) : BugReporter(d, GRBugReporterKind), Eng(eng) {} - + virtual ~GRBugReporter(); - + /// getEngine - Return the analysis engine used to analyze a given /// function or method. GRExprEngine &getEngine() { return Eng; } @@ -390,76 +390,76 @@ public: /// getGraph - Get the exploded graph created by the analysis engine /// for the analyzed method or function. ExplodedGraph &getGraph(); - + /// getStateManager - Return the state manager used by the analysis /// engine. GRStateManager &getStateManager(); - + virtual void GeneratePathDiagnostic(PathDiagnostic& PD, BugReportEquivClass& R); void addNotableSymbol(SymbolRef Sym) { NotableSymbols.insert(Sym); } - + bool isNotable(SymbolRef Sym) const { return (bool) NotableSymbols.count(Sym); } - + /// classof - Used by isa<>, cast<>, and dyn_cast<>. static bool classof(const BugReporter* R) { return R->getKind() == GRBugReporterKind; } }; - + class BugReporterContext { GRBugReporter &BR; std::vector Callbacks; public: BugReporterContext(GRBugReporter& br) : BR(br) {} virtual ~BugReporterContext(); - + void addVisitor(BugReporterVisitor* visitor) { if (visitor) Callbacks.push_back(visitor); } - + typedef std::vector::iterator visitor_iterator; visitor_iterator visitor_begin() { return Callbacks.begin(); } - visitor_iterator visitor_end() { return Callbacks.end(); } - - GRBugReporter& getBugReporter() { return BR; } - + visitor_iterator visitor_end() { return Callbacks.end(); } + + GRBugReporter& getBugReporter() { return BR; } + ExplodedGraph &getGraph() { return BR.getGraph(); } - + void addNotableSymbol(SymbolRef Sym) { // FIXME: For now forward to GRBugReporter. BR.addNotableSymbol(Sym); } - + bool isNotable(SymbolRef Sym) const { // FIXME: For now forward to GRBugReporter. return BR.isNotable(Sym); } - + GRStateManager& getStateManager() { return BR.getStateManager(); } - + ValueManager& getValueManager() { return getStateManager().getValueManager(); } - + ASTContext& getASTContext() { return BR.getContext(); } - + SourceManager& getSourceManager() { return BR.getSourceManager(); } - + const Decl &getCodeDecl(); const CFG &getCFG(); - virtual BugReport::NodeResolver& getNodeResolver() = 0; + virtual BugReport::NodeResolver& getNodeResolver() = 0; }; class DiagBugReport : public RangedBugReport { @@ -468,24 +468,24 @@ class DiagBugReport : public RangedBugReport { public: DiagBugReport(BugType& D, const char* desc, FullSourceLoc l) : RangedBugReport(D, desc, 0), L(l) {} - + virtual ~DiagBugReport() {} - + // FIXME: Move out-of-line (virtual function). SourceLocation getLocation() const { return L; } - - void addString(const std::string& s) { Strs.push_back(s); } - + + void addString(const std::string& s) { Strs.push_back(s); } + typedef std::list::const_iterator str_iterator; str_iterator str_begin() const { return Strs.begin(); } str_iterator str_end() const { return Strs.end(); } }; - + //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// - + namespace bugreporter { - + const Stmt *GetDerefExpr(const ExplodedNode *N); const Stmt *GetReceiverExpr(const ExplodedNode *N); const Stmt *GetDenomExpr(const ExplodedNode *N); @@ -496,7 +496,7 @@ void registerTrackNullOrUndefValue(BugReporterContext& BRC, const void *stmt, const ExplodedNode* N); } // end namespace clang::bugreporter - + //===----------------------------------------------------------------------===// } // end clang namespace diff --git a/clang/include/clang/Analysis/PathSensitive/Checker.h b/clang/include/clang/Analysis/PathSensitive/Checker.h index 3dc484569d54747c698aefeeebe7b0feb401ef7d..4e00d69cdba1c301a351b49f9abf928cff2e2c45 100644 --- a/clang/include/clang/Analysis/PathSensitive/Checker.h +++ b/clang/include/clang/Analysis/PathSensitive/Checker.h @@ -46,21 +46,21 @@ public: GRExprEngine &eng, ExplodedNode *pred, const void *tag, bool preVisit) - : Dst(dst), B(builder), Eng(eng), Pred(pred), + : Dst(dst), B(builder), Eng(eng), Pred(pred), OldSink(B.BuildSinks), OldTag(B.Tag), OldPointKind(B.PointKind), OldHasGen(B.HasGeneratedNode) { - //assert(Dst.empty()); // This is a fake assertion. + //assert(Dst.empty()); // This is a fake assertion. // See GRExprEngine::CheckerVisit(), CurrSet is repeatedly used. B.Tag = tag; if (preVisit) - B.PointKind = ProgramPoint::PreStmtKind; + B.PointKind = ProgramPoint::PreStmtKind; } - + ~CheckerContext() { if (!B.BuildSinks && !B.HasGeneratedNode) Dst.Add(Pred); } - + ConstraintManager &getConstraintManager() { return Eng.getConstraintManager(); } @@ -68,7 +68,7 @@ public: GRStmtNodeBuilder &getNodeBuilder() { return B; } ExplodedNode *&getPredecessor() { return Pred; } const GRState *getState() { return B.GetState(Pred); } - + ASTContext &getASTContext() { return Eng.getContext(); } @@ -76,26 +76,26 @@ public: ExplodedNode *GenerateNode(const Stmt *S, bool markAsSink = false) { return GenerateNode(S, getState(), markAsSink); } - + ExplodedNode *GenerateNode(const Stmt* S, const GRState *state, - bool markAsSink = false) { + bool markAsSink = false) { ExplodedNode *node = B.generateNode(S, state, Pred); - + if (markAsSink && node) node->markAsSink(); - + return node; } - + void addTransition(ExplodedNode *node) { Dst.Add(node); } - + void EmitReport(BugReport *R) { Eng.getBugReporter().EmitReport(R); } }; - + class Checker { private: friend class GRExprEngine; @@ -105,11 +105,11 @@ private: GRExprEngine &Eng, const Stmt *stmt, ExplodedNode *Pred, bool isPrevisit) { - CheckerContext C(Dst, Builder, Eng, Pred, getTag(), isPrevisit); + CheckerContext C(Dst, Builder, Eng, Pred, getTag(), isPrevisit); assert(isPrevisit && "Only previsit supported for now."); _PreVisit(C, stmt); } - + public: virtual ~Checker() {} virtual void _PreVisit(CheckerContext &C, const Stmt *stmt) = 0; @@ -119,4 +119,4 @@ public: } // end clang namespace #endif - + diff --git a/clang/include/clang/Analysis/PathSensitive/CheckerVisitor.h b/clang/include/clang/Analysis/PathSensitive/CheckerVisitor.h index 6ec192adee6046b28b9491bcff1c5766abef8161..e74f49c9a761fa63889ffaa2d08696400b6e10f2 100644 --- a/clang/include/clang/Analysis/PathSensitive/CheckerVisitor.h +++ b/clang/include/clang/Analysis/PathSensitive/CheckerVisitor.h @@ -14,14 +14,14 @@ #ifndef LLVM_CLANG_ANALYSIS_CHECKERVISITOR #define LLVM_CLANG_ANALYSIS_CHECKERVISITOR #include "clang/Analysis/PathSensitive/Checker.h" - + namespace clang { //===----------------------------------------------------------------------===// // Checker visitor interface. Used by subclasses of Checker to specify their // own checker visitor logic. //===----------------------------------------------------------------------===// - + /// CheckerVisitor - This class implements a simple visitor for Stmt subclasses. /// Since Expr derives from Stmt, this also includes support for visiting Exprs. template @@ -47,13 +47,13 @@ break; #include "clang/Analysis/PathSensitive/CheckerVisitor.def" } } - + #define PREVISIT(NAME) \ void PreVisit ## NAME(CheckerContext &C, const NAME* S) {} #include "clang/Analysis/PathSensitive/CheckerVisitor.def" }; - + } // end clang namespace #endif - + diff --git a/clang/include/clang/Analysis/PathSensitive/ConstraintManager.h b/clang/include/clang/Analysis/PathSensitive/ConstraintManager.h index e3b6489ad085ff7d5db42c06cab3a55e839a964a..1e758d8cb87ff6d9ad40cc9d187d9345db354dc7 100644 --- a/clang/include/clang/Analysis/PathSensitive/ConstraintManager.h +++ b/clang/include/clang/Analysis/PathSensitive/ConstraintManager.h @@ -30,32 +30,32 @@ class SVal; class ConstraintManager { public: virtual ~ConstraintManager(); - virtual const GRState *Assume(const GRState *state, SVal Cond, + virtual const GRState *Assume(const GRState *state, SVal Cond, bool Assumption) = 0; - virtual const GRState *AssumeInBound(const GRState *state, SVal Idx, + virtual const GRState *AssumeInBound(const GRState *state, SVal Idx, SVal UpperBound, bool Assumption) = 0; - + std::pair AssumeDual(const GRState *state, DefinedSVal Cond) { return std::make_pair(Assume(state, Cond, true), - Assume(state, Cond, false)); + Assume(state, Cond, false)); } virtual const llvm::APSInt* getSymVal(const GRState *state, SymbolRef sym) const = 0; - virtual bool isEqual(const GRState *state, SymbolRef sym, + virtual bool isEqual(const GRState *state, SymbolRef sym, const llvm::APSInt& V) const = 0; virtual const GRState *RemoveDeadBindings(const GRState *state, SymbolReaper& SymReaper) = 0; - virtual void print(const GRState *state, llvm::raw_ostream& Out, + virtual void print(const GRState *state, llvm::raw_ostream& Out, const char* nl, const char *sep) = 0; virtual void EndPath(const GRState *state) {} - + /// canReasonAbout - Not all ConstraintManagers can accurately reason about /// all SVal values. This method returns true if the ConstraintManager can /// reasonably handle a given SVal value. This is typically queried by diff --git a/clang/include/clang/Analysis/PathSensitive/Environment.h b/clang/include/clang/Analysis/PathSensitive/Environment.h index b96b1a77b605b6edee517f0ba5da45b504988839..6d5c5678e59b1a2d84c07cba82aaf0f621db6fbb 100644 --- a/clang/include/clang/Analysis/PathSensitive/Environment.h +++ b/clang/include/clang/Analysis/PathSensitive/Environment.h @@ -35,61 +35,61 @@ class LiveVariables; class Environment { private: friend class EnvironmentManager; - + // Type definitions. typedef llvm::ImmutableMap BindingsTy; // Data. BindingsTy ExprBindings; AnalysisContext *ACtx; - + Environment(BindingsTy eb, AnalysisContext *aCtx) : ExprBindings(eb), ACtx(aCtx) {} - -public: + +public: typedef BindingsTy::iterator iterator; iterator begin() const { return ExprBindings.begin(); } iterator end() const { return ExprBindings.end(); } - + SVal LookupExpr(const Stmt* E) const { const SVal* X = ExprBindings.lookup(E); return X ? *X : UnknownVal(); } - + SVal GetSVal(const Stmt* Ex, ValueManager& ValMgr) const; - + AnalysisContext &getAnalysisContext() const { return *ACtx; } - + /// Profile - Profile the contents of an Environment object for use /// in a FoldingSet. static void Profile(llvm::FoldingSetNodeID& ID, const Environment* E) { E->ExprBindings.Profile(ID); } - + /// Profile - Used to profile the contents of this object for inclusion /// in a FoldingSet. void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, this); } - + bool operator==(const Environment& RHS) const { return ExprBindings == RHS.ExprBindings; } }; - + class EnvironmentManager { private: typedef Environment::BindingsTy::Factory FactoryTy; FactoryTy F; - -public: + +public: EnvironmentManager(llvm::BumpPtrAllocator& Allocator) : F(Allocator) {} ~EnvironmentManager() {} - + Environment getInitialEnvironment(AnalysisContext *ACtx) { return Environment(F.GetEmptyMap(), ACtx); } - + Environment BindExpr(Environment Env, const Stmt *S, SVal V, bool Invalidate); @@ -97,7 +97,7 @@ public: SymbolReaper &SymReaper, const GRState *ST, llvm::SmallVectorImpl& RegionRoots); }; - + } // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/ExplodedGraph.h b/clang/include/clang/Analysis/PathSensitive/ExplodedGraph.h index 4ffed8950a6bb90860c2ef52eae3994f7632f382..fc41333f2759fba3e97197500a116f0de4152938 100644 --- a/clang/include/clang/Analysis/PathSensitive/ExplodedGraph.h +++ b/clang/include/clang/Analysis/PathSensitive/ExplodedGraph.h @@ -38,7 +38,7 @@ class ASTContext; // contain a specific kind of state. Typed-specialized versions are defined // on top of these classes. //===----------------------------------------------------------------------===// - + class ExplodedNode : public llvm::FoldingSetNode { friend class ExplodedGraph; friend class GRCoreEngine; @@ -46,16 +46,16 @@ class ExplodedNode : public llvm::FoldingSetNode { friend class GRBranchNodeBuilder; friend class GRIndirectGotoNodeBuilder; friend class GRSwitchNodeBuilder; - friend class GREndPathNodeBuilder; - + friend class GREndPathNodeBuilder; + class NodeGroup { enum { Size1 = 0x0, SizeOther = 0x1, AuxFlag = 0x2, Mask = 0x3 }; uintptr_t P; - + unsigned getKind() const { return P & 0x1; } - + void* getPtr() const { assert (!getFlag()); return reinterpret_cast(P & ~Mask); @@ -64,55 +64,55 @@ class ExplodedNode : public llvm::FoldingSetNode { ExplodedNode *getNode() const { return reinterpret_cast(getPtr()); } - + public: NodeGroup() : P(0) {} - + ~NodeGroup(); - + ExplodedNode** begin() const; - + ExplodedNode** end() const; - + unsigned size() const; - + bool empty() const { return size() == 0; } - + void addNode(ExplodedNode* N); - + void setFlag() { assert (P == 0); P = AuxFlag; } - + bool getFlag() const { return P & AuxFlag ? true : false; } - }; - + }; + /// Location - The program location (within a function body) associated /// with this node. const ProgramPoint Location; - + /// State - The state associated with this node. const GRState* State; - + /// Preds - The predecessors of this node. NodeGroup Preds; - + /// Succs - The successors of this node. NodeGroup Succs; public: - explicit ExplodedNode(const ProgramPoint& loc, const GRState* state) + explicit ExplodedNode(const ProgramPoint& loc, const GRState* state) : Location(loc), State(state) {} /// getLocation - Returns the edge associated with the given node. ProgramPoint getLocation() const { return Location; } - const LocationContext *getLocationContext() const { - return getLocation().getLocationContext(); + const LocationContext *getLocationContext() const { + return getLocation().getLocationContext(); } const Decl &getCodeDecl() const { return *getLocationContext()->getDecl(); } @@ -126,14 +126,14 @@ public: template const T* getLocationAs() const { return llvm::dyn_cast(&Location); } - static void Profile(llvm::FoldingSetNodeID &ID, + static void Profile(llvm::FoldingSetNodeID &ID, const ProgramPoint& Loc, const GRState* state); void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, getLocation(), getState()); } - /// addPredeccessor - Adds a predecessor to the current node, and + /// addPredeccessor - Adds a predecessor to the current node, and /// in tandem add this node as a successor of the other node. void addPredecessor(ExplodedNode* V); @@ -141,18 +141,18 @@ public: unsigned pred_size() const { return Preds.size(); } bool succ_empty() const { return Succs.empty(); } bool pred_empty() const { return Preds.empty(); } - + bool isSink() const { return Succs.getFlag(); } - void markAsSink() { Succs.setFlag(); } + void markAsSink() { Succs.setFlag(); } ExplodedNode* getFirstPred() { return pred_empty() ? NULL : *(pred_begin()); } - + const ExplodedNode* getFirstPred() const { return const_cast(this)->getFirstPred(); } - + // Iterators over successor and predecessor vertices. typedef ExplodedNode** succ_iterator; typedef const ExplodedNode* const * const_succ_iterator; @@ -164,7 +164,7 @@ public: const_pred_iterator pred_begin() const { return const_cast(this)->pred_begin(); - } + } const_pred_iterator pred_end() const { return const_cast(this)->pred_end(); } @@ -180,26 +180,26 @@ public: } // For debugging. - + public: - + class Auditor { public: virtual ~Auditor(); virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst) = 0; }; - + static void SetAuditor(Auditor* A); }; // FIXME: Is this class necessary? class InterExplodedGraphMap { llvm::DenseMap M; - friend class ExplodedGraph; + friend class ExplodedGraph; public: ExplodedNode* getMappedNode(const ExplodedNode* N) const; - + InterExplodedGraphMap() {}; virtual ~InterExplodedGraphMap() {} }; @@ -211,7 +211,7 @@ protected: // Type definitions. typedef llvm::SmallVector RootsTy; typedef llvm::SmallVector EndNodesTy; - + /// Roots - The roots of the simulation graph. Usually there will be only /// one, but clients are free to establish multiple subgraphs within a single /// SimulGraph. Moreover, these subgraphs can often merge when paths from @@ -227,10 +227,10 @@ protected: /// Allocator - BumpPtrAllocator to create nodes. llvm::BumpPtrAllocator Allocator; - + /// Ctx - The ASTContext used to "interpret" CodeDecl. ASTContext& Ctx; - + /// NumNodes - The number of nodes in the graph. unsigned NumNodes; @@ -242,7 +242,7 @@ public: ExplodedNode* getNode(const ProgramPoint& L, const GRState *State, bool* IsNew = 0); - + ExplodedGraph* MakeEmptyGraph() const { return new ExplodedGraph(Ctx); } @@ -265,7 +265,7 @@ public: unsigned num_roots() const { return Roots.size(); } unsigned num_eops() const { return EndNodes.size(); } - + bool empty() const { return NumNodes == 0; } unsigned size() const { return NumNodes; } @@ -278,29 +278,29 @@ public: typedef NodeTy* const * const_eop_iterator; typedef AllNodesTy::iterator node_iterator; typedef AllNodesTy::const_iterator const_node_iterator; - + node_iterator nodes_begin() { return Nodes.begin(); } node_iterator nodes_end() { return Nodes.end(); } - + const_node_iterator nodes_begin() const { return Nodes.begin(); } - + const_node_iterator nodes_end() const { return Nodes.end(); } - + roots_iterator roots_begin() { return Roots.begin(); } - + roots_iterator roots_end() { return Roots.end(); } - + const_roots_iterator roots_begin() const { return Roots.begin(); } - - const_roots_iterator roots_end() const { return Roots.end(); } + + const_roots_iterator roots_end() const { return Roots.end(); } eop_iterator eop_begin() { return EndNodes.begin(); } - + eop_iterator eop_end() { return EndNodes.end(); } - + const_eop_iterator eop_begin() const { return EndNodes.begin(); } - + const_eop_iterator eop_end() const { return EndNodes.end(); } llvm::BumpPtrAllocator& getAllocator() { return Allocator; } @@ -322,24 +322,24 @@ public: class ExplodedNodeSet { typedef llvm::SmallPtrSet ImplTy; ImplTy Impl; - + public: ExplodedNodeSet(ExplodedNode* N) { assert (N && !static_cast(N)->isSink()); Impl.insert(N); } - + ExplodedNodeSet() {} - + inline void Add(ExplodedNode* N) { if (N && !static_cast(N)->isSink()) Impl.insert(N); } - + ExplodedNodeSet& operator=(const ExplodedNodeSet &X) { Impl = X.Impl; return *this; } - + typedef ImplTy::iterator iterator; typedef ImplTy::const_iterator const_iterator; @@ -347,14 +347,14 @@ public: inline bool empty() const { return Impl.empty(); } inline void clear() { Impl.clear(); } - + inline iterator begin() { return Impl.begin(); } inline iterator end() { return Impl.end(); } - + inline const_iterator begin() const { return Impl.begin(); } inline const_iterator end() const { return Impl.end(); } -}; - +}; + } // end clang namespace // GraphTraits @@ -364,54 +364,54 @@ namespace llvm { typedef clang::ExplodedNode NodeType; typedef NodeType::succ_iterator ChildIteratorType; typedef llvm::df_iterator nodes_iterator; - + static inline NodeType* getEntryNode(NodeType* N) { return N; } - + static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } - + static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } - + static inline nodes_iterator nodes_begin(NodeType* N) { return df_begin(N); } - + static inline nodes_iterator nodes_end(NodeType* N) { return df_end(N); } }; - + template<> struct GraphTraits { typedef const clang::ExplodedNode NodeType; typedef NodeType::const_succ_iterator ChildIteratorType; typedef llvm::df_iterator nodes_iterator; - + static inline NodeType* getEntryNode(NodeType* N) { return N; } - + static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } - + static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } - + static inline nodes_iterator nodes_begin(NodeType* N) { return df_begin(N); } - + static inline nodes_iterator nodes_end(NodeType* N) { return df_end(N); } }; - + } // end llvm namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/GRAuditor.h b/clang/include/clang/Analysis/PathSensitive/GRAuditor.h index 6233ca890873e0d86a8fd81e0aad0b5f296bedf8..015c82e80bb59f8a9559c327d23d4227bfcd63e1 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRAuditor.h +++ b/clang/include/clang/Analysis/PathSensitive/GRAuditor.h @@ -1,5 +1,5 @@ //==- GRAuditor.h - Observers of the creation of ExplodedNodes------*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source @@ -22,14 +22,14 @@ namespace clang { class ExplodedNode; class GRStateManager; - + class GRAuditor { public: virtual ~GRAuditor() {} virtual bool Audit(ExplodedNode* N, GRStateManager& M) = 0; }; - - + + } // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/GRBlockCounter.h b/clang/include/clang/Analysis/PathSensitive/GRBlockCounter.h index b4fd2704b81a6e5e5e34e1b0e2437d1a4f2caff2..67ed9532db02b5deaa5ef2fcd27bf31b39317f1b 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRBlockCounter.h +++ b/clang/include/clang/Analysis/PathSensitive/GRBlockCounter.h @@ -1,5 +1,5 @@ //==- GRBlockCounter.h - ADT for counting block visits -------------*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source @@ -24,27 +24,27 @@ namespace clang { class GRBlockCounter { void* Data; - - GRBlockCounter(void* D) : Data(D) {} + + GRBlockCounter(void* D) : Data(D) {} public: GRBlockCounter() : Data(0) {} - + unsigned getNumVisited(unsigned BlockID) const; - + class Factory { void* F; public: Factory(llvm::BumpPtrAllocator& Alloc); ~Factory(); - + GRBlockCounter GetEmptyCounter(); GRBlockCounter IncrementCount(GRBlockCounter BC, unsigned BlockID); }; - + friend class Factory; }; } // end clang namespace - + #endif diff --git a/clang/include/clang/Analysis/PathSensitive/GRCoreEngine.h b/clang/include/clang/Analysis/PathSensitive/GRCoreEngine.h index 72aaf6ebb50f9ad495e73d6bf7f981b23fae11d5..48b86b9eaf0e56e1bc1c57772d8e217a4849cf97 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRCoreEngine.h +++ b/clang/include/clang/Analysis/PathSensitive/GRCoreEngine.h @@ -1,5 +1,5 @@ //==- GRCoreEngine.h - Path-Sensitive Dataflow Engine --------------*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source @@ -26,7 +26,7 @@ namespace clang { //===----------------------------------------------------------------------===// -/// GRCoreEngine - Implements the core logic of the graph-reachability +/// GRCoreEngine - Implements the core logic of the graph-reachability /// analysis. It traverses the CFG and generates the ExplodedGraph. /// Program "states" are treated as opaque void pointers. /// The template class GRCoreEngine (which subclasses GRCoreEngine) @@ -45,61 +45,61 @@ class GRCoreEngine { /// G - The simulation graph. Each node is a (location,state) pair. llvm::OwningPtr G; - + /// WList - A set of queued nodes that need to be processed by the /// worklist algorithm. It is up to the implementation of WList to decide /// the order that nodes are processed. GRWorkList* WList; - + /// BCounterFactory - A factory object for created GRBlockCounter objects. /// These are used to record for key nodes in the ExplodedGraph the /// number of times different CFGBlocks have been visited along a path. GRBlockCounter::Factory BCounterFactory; - + void GenerateNode(const ProgramPoint& Loc, const GRState* State, ExplodedNode* Pred); - + void HandleBlockEdge(const BlockEdge& E, ExplodedNode* Pred); void HandleBlockEntrance(const BlockEntrance& E, ExplodedNode* Pred); void HandleBlockExit(CFGBlock* B, ExplodedNode* Pred); void HandlePostStmt(const PostStmt& S, CFGBlock* B, unsigned StmtIdx, ExplodedNode *Pred); - + void HandleBranch(Stmt* Cond, Stmt* Term, CFGBlock* B, - ExplodedNode* Pred); + ExplodedNode* Pred); /// Get the initial state from the subengine. - const GRState* getInitialState(const LocationContext *InitLoc) { + const GRState* getInitialState(const LocationContext *InitLoc) { return SubEngine.getInitialState(InitLoc); } void ProcessEndPath(GREndPathNodeBuilder& Builder); - + void ProcessStmt(Stmt* S, GRStmtNodeBuilder& Builder); - + bool ProcessBlockEntrance(CFGBlock* Blk, const GRState* State, GRBlockCounter BC); - + void ProcessBranch(Stmt* Condition, Stmt* Terminator, GRBranchNodeBuilder& Builder); void ProcessIndirectGoto(GRIndirectGotoNodeBuilder& Builder); - + void ProcessSwitch(GRSwitchNodeBuilder& Builder); private: GRCoreEngine(const GRCoreEngine&); // Do not implement. GRCoreEngine& operator=(const GRCoreEngine&); - + public: /// Construct a GRCoreEngine object to analyze the provided CFG using /// a DFS exploration of the exploded graph. GRCoreEngine(ASTContext& ctx, GRSubEngine& subengine) - : SubEngine(subengine), G(new ExplodedGraph(ctx)), + : SubEngine(subengine), G(new ExplodedGraph(ctx)), WList(GRWorkList::MakeBFS()), BCounterFactory(G->getAllocator()) {} @@ -116,7 +116,7 @@ public: /// getGraph - Returns the exploded graph. ExplodedGraph& getGraph() { return *G.get(); } - + /// takeGraph - Returns the exploded graph. Ownership of the graph is /// transfered to the caller. ExplodedGraph* takeGraph() { return G.take(); } @@ -125,13 +125,13 @@ public: /// steps. Returns true if there is still simulation state on the worklist. bool ExecuteWorkList(const LocationContext *L, unsigned Steps); }; - + class GRStmtNodeBuilder { GRCoreEngine& Eng; CFGBlock& B; const unsigned Idx; ExplodedNode* Pred; - ExplodedNode* LastNode; + ExplodedNode* LastNode; GRStateManager& Mgr; GRAuditor* Auditor; @@ -141,23 +141,23 @@ public: bool HasGeneratedNode; ProgramPoint::Kind PointKind; const void *Tag; - - const GRState* CleanedState; - + + const GRState* CleanedState; + typedef llvm::SmallPtrSet DeferredTy; DeferredTy Deferred; - + void GenerateAutoTransition(ExplodedNode* N); - + public: - GRStmtNodeBuilder(CFGBlock* b, unsigned idx, ExplodedNode* N, - GRCoreEngine* e, GRStateManager &mgr); - + GRStmtNodeBuilder(CFGBlock* b, unsigned idx, ExplodedNode* N, + GRCoreEngine* e, GRStateManager &mgr); + ~GRStmtNodeBuilder(); - + ExplodedNode* getBasePredecessor() const { return Pred; } - + ExplodedNode* getLastNode() const { return LastNode ? (LastNode->isSink() ? NULL : LastNode) : NULL; } @@ -167,26 +167,26 @@ public: } GRBlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter();} - + unsigned getCurrentBlockCount() const { return getBlockCounter().getNumVisited(B.getBlockID()); - } + } ExplodedNode* generateNode(PostStmt PP,const GRState* St,ExplodedNode* Pred) { HasGeneratedNode = true; return generateNodeInternal(PP, St, Pred); } - + ExplodedNode* generateNode(const Stmt *S, const GRState *St, ExplodedNode *Pred, ProgramPoint::Kind K) { HasGeneratedNode = true; - if (PurgingDeadSymbols) - K = ProgramPoint::PostPurgeDeadSymbolsKind; + if (PurgingDeadSymbols) + K = ProgramPoint::PostPurgeDeadSymbolsKind; return generateNodeInternal(S, St, Pred, K, Tag); } - + ExplodedNode* generateNode(const Stmt *S, const GRState *St, ExplodedNode *Pred) { return generateNode(S, St, Pred, PointKind); @@ -195,16 +195,16 @@ public: ExplodedNode* generateNodeInternal(const ProgramPoint &PP, const GRState* State, ExplodedNode* Pred); - + ExplodedNode* generateNodeInternal(const Stmt* S, const GRState* State, ExplodedNode* Pred, ProgramPoint::Kind K = ProgramPoint::PostStmtKind, const void *tag = 0); - + /// getStmt - Return the current block-level expression associated with /// this builder. Stmt* getStmt() const { return B[Idx]; } - + /// getBlock - Return the CFGBlock associated with the block-level expression /// of this builder. CFGBlock* getBlock() const { return &B; } @@ -218,40 +218,40 @@ public: return Pred->getState(); } - ExplodedNode* MakeNode(ExplodedNodeSet& Dst, Stmt* S, ExplodedNode* Pred, + ExplodedNode* MakeNode(ExplodedNodeSet& Dst, Stmt* S, ExplodedNode* Pred, const GRState* St) { return MakeNode(Dst, S, Pred, St, PointKind); } - + ExplodedNode* MakeNode(ExplodedNodeSet& Dst, Stmt* S, ExplodedNode* Pred, - const GRState* St, ProgramPoint::Kind K) { - + const GRState* St, ProgramPoint::Kind K) { + const GRState* PredState = GetState(Pred); - + // If the state hasn't changed, don't generate a new node. if (!BuildSinks && St == PredState && Auditor == 0) { Dst.Add(Pred); return NULL; } - + ExplodedNode* N = generateNode(S, St, Pred, K); - - if (N) { + + if (N) { if (BuildSinks) N->markAsSink(); else { if (Auditor && Auditor->Audit(N, Mgr)) N->markAsSink(); - + Dst.Add(N); } } - + return N; } - + ExplodedNode* MakeSinkNode(ExplodedNodeSet& Dst, Stmt* S, - ExplodedNode* Pred, const GRState* St) { + ExplodedNode* Pred, const GRState* St) { bool Tmp = BuildSinks; BuildSinks = true; ExplodedNode* N = MakeNode(Dst, S, Pred, St); @@ -260,7 +260,7 @@ public: } }; - + class GRBranchNodeBuilder { GRCoreEngine& Eng; CFGBlock* Src; @@ -270,44 +270,44 @@ class GRBranchNodeBuilder { typedef llvm::SmallVector DeferredTy; DeferredTy Deferred; - + bool GeneratedTrue; bool GeneratedFalse; bool InFeasibleTrue; bool InFeasibleFalse; - + public: GRBranchNodeBuilder(CFGBlock* src, CFGBlock* dstT, CFGBlock* dstF, - ExplodedNode* pred, GRCoreEngine* e) + ExplodedNode* pred, GRCoreEngine* e) : Eng(*e), Src(src), DstT(dstT), DstF(dstF), Pred(pred), GeneratedTrue(false), GeneratedFalse(false), InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {} - + ~GRBranchNodeBuilder(); - + ExplodedNode* getPredecessor() const { return Pred; } const ExplodedGraph& getGraph() const { return *Eng.G; } GRBlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter();} - + ExplodedNode* generateNode(const GRState* State, bool branch); - + CFGBlock* getTargetBlock(bool branch) const { return branch ? DstT : DstF; - } - + } + void markInfeasible(bool branch) { if (branch) InFeasibleTrue = GeneratedTrue = true; else InFeasibleFalse = GeneratedFalse = true; } - + bool isFeasible(bool branch) { return branch ? !InFeasibleTrue : !InFeasibleFalse; } - + const GRState* getState() const { return getPredecessor()->getState(); } @@ -318,81 +318,81 @@ class GRIndirectGotoNodeBuilder { CFGBlock* Src; CFGBlock& DispatchBlock; Expr* E; - ExplodedNode* Pred; + ExplodedNode* Pred; public: - GRIndirectGotoNodeBuilder(ExplodedNode* pred, CFGBlock* src, Expr* e, + GRIndirectGotoNodeBuilder(ExplodedNode* pred, CFGBlock* src, Expr* e, CFGBlock* dispatch, GRCoreEngine* eng) : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} class iterator { CFGBlock::succ_iterator I; - - friend class GRIndirectGotoNodeBuilder; - iterator(CFGBlock::succ_iterator i) : I(i) {} + + friend class GRIndirectGotoNodeBuilder; + iterator(CFGBlock::succ_iterator i) : I(i) {} public: - + iterator& operator++() { ++I; return *this; } bool operator!=(const iterator& X) const { return I != X.I; } - + LabelStmt* getLabel() const { return llvm::cast((*I)->getLabel()); } - + CFGBlock* getBlock() const { return *I; } }; - + iterator begin() { return iterator(DispatchBlock.succ_begin()); } iterator end() { return iterator(DispatchBlock.succ_end()); } - + ExplodedNode* generateNode(const iterator& I, const GRState* State, bool isSink = false); - + Expr* getTarget() const { return E; } const GRState* getState() const { return Pred->State; } }; - + class GRSwitchNodeBuilder { GRCoreEngine& Eng; CFGBlock* Src; Expr* Condition; - ExplodedNode* Pred; + ExplodedNode* Pred; public: GRSwitchNodeBuilder(ExplodedNode* pred, CFGBlock* src, Expr* condition, GRCoreEngine* eng) : Eng(*eng), Src(src), Condition(condition), Pred(pred) {} - + class iterator { CFGBlock::succ_reverse_iterator I; - - friend class GRSwitchNodeBuilder; - iterator(CFGBlock::succ_reverse_iterator i) : I(i) {} + + friend class GRSwitchNodeBuilder; + iterator(CFGBlock::succ_reverse_iterator i) : I(i) {} public: iterator& operator++() { ++I; return *this; } bool operator!=(const iterator& X) const { return I != X.I; } - + CaseStmt* getCase() const { return llvm::cast((*I)->getLabel()); } - + CFGBlock* getBlock() const { return *I; } }; - + iterator begin() { return iterator(Src->succ_rbegin()+1); } iterator end() { return iterator(Src->succ_rend()); } - + ExplodedNode* generateCaseStmtNode(const iterator& I, const GRState* State); - + ExplodedNode* generateDefaultCaseNode(const GRState* State, bool isSink = false); - + Expr* getCondition() const { return Condition; } const GRState* getState() const { return Pred->State; } @@ -401,28 +401,28 @@ public: class GREndPathNodeBuilder { GRCoreEngine& Eng; CFGBlock& B; - ExplodedNode* Pred; + ExplodedNode* Pred; bool HasGeneratedNode; - + public: GREndPathNodeBuilder(CFGBlock* b, ExplodedNode* N, GRCoreEngine* e) - : Eng(*e), B(*b), Pred(N), HasGeneratedNode(false) {} - + : Eng(*e), B(*b), Pred(N), HasGeneratedNode(false) {} + ~GREndPathNodeBuilder(); - + ExplodedNode* getPredecessor() const { return Pred; } - - GRBlockCounter getBlockCounter() const { + + GRBlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter(); } - + unsigned getCurrentBlockCount() const { return getBlockCounter().getNumVisited(B.getBlockID()); - } - + } + ExplodedNode* generateNode(const GRState* State, const void *tag = 0, ExplodedNode *P = 0); - + CFGBlock* getBlock() const { return &B; } const GRState* getState() const { diff --git a/clang/include/clang/Analysis/PathSensitive/GRExprEngine.h b/clang/include/clang/Analysis/PathSensitive/GRExprEngine.h index 1410c011c798958f2d3a9b5fea9f0ab1cdd0b37c..bd8f714a6396eab2c91cbec36a64cbea6315a65c 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRExprEngine.h +++ b/clang/include/clang/Analysis/PathSensitive/GRExprEngine.h @@ -26,54 +26,54 @@ #include "clang/AST/Type.h" #include "clang/AST/ExprObjC.h" -namespace clang { - +namespace clang { + class PathDiagnosticClient; class Diagnostic; class ObjCForCollectionStmt; class Checker; -class GRExprEngine : public GRSubEngine { +class GRExprEngine : public GRSubEngine { AnalysisManager &AMgr; GRCoreEngine CoreEngine; - + /// G - the simulation graph. ExplodedGraph& G; - + /// Builder - The current GRStmtNodeBuilder which is used when building the /// nodes for a given statement. GRStmtNodeBuilder* Builder; - + /// StateMgr - Object that manages the data for all created states. GRStateManager StateMgr; /// SymMgr - Object that manages the symbol information. SymbolManager& SymMgr; - + /// ValMgr - Object that manages/creates SVals. ValueManager &ValMgr; - + /// SVator - SValuator object that creates SVals from expressions. SValuator &SVator; - + /// EntryNode - The immediate predecessor node. ExplodedNode* EntryNode; /// CleanedState - The state for EntryNode "cleaned" of all dead /// variables and symbols (as determined by a liveness analysis). - const GRState* CleanedState; - + const GRState* CleanedState; + /// CurrentStmt - The current block-level statement. Stmt* CurrentStmt; - + // Obj-C Class Identifiers. IdentifierInfo* NSExceptionII; - + // Obj-C Selectors. Selector* NSExceptionInstanceRaiseSelectors; Selector RaiseSel; - + llvm::OwningPtr BatchAuditor; std::vector Checkers; @@ -81,21 +81,21 @@ class GRExprEngine : public GRSubEngine { // this object be placed at the very end of member variables so that its // destructor is called before the rest of the GRExprEngine is destroyed. GRBugReporter BR; - + public: - typedef llvm::SmallPtrSet ErrorNodes; + typedef llvm::SmallPtrSet ErrorNodes; typedef llvm::DenseMap UndefArgsTy; - + /// NilReceiverStructRetExplicit - Nodes in the ExplodedGraph that resulted /// from [x ...] with 'x' definitely being nil and the result was a 'struct' // (an undefined value). ErrorNodes NilReceiverStructRetExplicit; - + /// NilReceiverStructRetImplicit - Nodes in the ExplodedGraph that resulted /// from [x ...] with 'x' possibly being nil and the result was a 'struct' // (an undefined value). ErrorNodes NilReceiverStructRetImplicit; - + /// NilReceiverLargerThanVoidPtrRetExplicit - Nodes in the ExplodedGraph that /// resulted from [x ...] with 'x' definitely being nil and the result's size // was larger than sizeof(void *) (an undefined value). @@ -105,7 +105,7 @@ public: /// resulted from [x ...] with 'x' possibly being nil and the result's size // was larger than sizeof(void *) (an undefined value). ErrorNodes NilReceiverLargerThanVoidPtrRetImplicit; - + /// RetsStackAddr - Nodes in the ExplodedGraph that result from returning /// the address of a stack variable. ErrorNodes RetsStackAddr; @@ -113,65 +113,65 @@ public: /// RetsUndef - Nodes in the ExplodedGraph that result from returning /// an undefined value. ErrorNodes RetsUndef; - + /// UndefBranches - Nodes in the ExplodedGraph that result from /// taking a branch based on an undefined value. ErrorNodes UndefBranches; - + /// UndefStores - Sinks in the ExplodedGraph that result from /// making a store to an undefined lvalue. ErrorNodes UndefStores; - + /// NoReturnCalls - Sinks in the ExplodedGraph that result from // calling a function with the attribute "noreturn". ErrorNodes NoReturnCalls; - + /// ImplicitNullDeref - Nodes in the ExplodedGraph that result from /// taking a dereference on a symbolic pointer that MAY be NULL. ErrorNodes ImplicitNullDeref; - + /// ExplicitNullDeref - Nodes in the ExplodedGraph that result from /// taking a dereference on a symbolic pointer that MUST be NULL. ErrorNodes ExplicitNullDeref; - + /// UnitDeref - Nodes in the ExplodedGraph that result from /// taking a dereference on an undefined value. ErrorNodes UndefDeref; - /// ImplicitBadDivides - Nodes in the ExplodedGraph that result from + /// ImplicitBadDivides - Nodes in the ExplodedGraph that result from /// evaluating a divide or modulo operation where the denominator /// MAY be zero. ErrorNodes ImplicitBadDivides; - - /// ExplicitBadDivides - Nodes in the ExplodedGraph that result from + + /// ExplicitBadDivides - Nodes in the ExplodedGraph that result from /// evaluating a divide or modulo operation where the denominator /// MUST be zero or undefined. ErrorNodes ExplicitBadDivides; - - /// ImplicitBadSizedVLA - Nodes in the ExplodedGraph that result from + + /// ImplicitBadSizedVLA - Nodes in the ExplodedGraph that result from /// constructing a zero-sized VLA where the size may be zero. ErrorNodes ImplicitBadSizedVLA; - - /// ExplicitBadSizedVLA - Nodes in the ExplodedGraph that result from + + /// ExplicitBadSizedVLA - Nodes in the ExplodedGraph that result from /// constructing a zero-sized VLA where the size must be zero. ErrorNodes ExplicitBadSizedVLA; - + /// UndefResults - Nodes in the ExplodedGraph where the operands are defined /// by the result is not. Excludes divide-by-zero errors. ErrorNodes UndefResults; - + /// BadCalls - Nodes in the ExplodedGraph resulting from calls to function /// pointers that are NULL (or other constants) or Undefined. ErrorNodes BadCalls; - + /// UndefReceiver - Nodes in the ExplodedGraph resulting from message /// ObjC message expressions where the receiver is undefined (uninitialized). ErrorNodes UndefReceivers; - + /// UndefArg - Nodes in the ExplodedGraph resulting from calls to functions /// where a pass-by-value argument has an undefined value. UndefArgsTy UndefArgs; - + /// MsgExprUndefArgs - Nodes in the ExplodedGraph resulting from /// message expressions where a pass-by-value argument has an undefined /// value. @@ -184,132 +184,132 @@ public: /// OutOfBoundMemAccesses - Nodes in the ExplodedGraph resulting from /// out-of-bound memory accesses where the index MUST be out-of-bound. ErrorNodes ExplicitOOBMemAccesses; - + public: GRExprEngine(AnalysisManager &mgr); ~GRExprEngine(); - + void ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) { CoreEngine.ExecuteWorkList(L, Steps); } - + /// getContext - Return the ASTContext associated with this analysis. ASTContext& getContext() const { return G.getContext(); } AnalysisManager &getAnalysisManager() const { return AMgr; } - + SValuator &getSValuator() { return SVator; } - + GRTransferFuncs& getTF() { return *StateMgr.TF; } - + BugReporter& getBugReporter() { return BR; } - + /// setTransferFunctions void setTransferFunctions(GRTransferFuncs* tf); void setTransferFunctions(GRTransferFuncs& tf) { setTransferFunctions(&tf); } - + /// ViewGraph - Visualize the ExplodedGraph created by executing the /// simulation. void ViewGraph(bool trim = false); - + void ViewGraph(ExplodedNode** Beg, ExplodedNode** End); - + /// getInitialState - Return the initial state used for the root vertex /// in the ExplodedGraph. const GRState* getInitialState(const LocationContext *InitLoc); - + ExplodedGraph& getGraph() { return G; } const ExplodedGraph& getGraph() const { return G; } void RegisterInternalChecks(); - + void registerCheck(Checker *check) { Checkers.push_back(check); } - + bool isRetStackAddr(const ExplodedNode* N) const { return N->isSink() && RetsStackAddr.count(const_cast(N)) != 0; } - + bool isUndefControlFlow(const ExplodedNode* N) const { return N->isSink() && UndefBranches.count(const_cast(N)) != 0; } - + bool isUndefStore(const ExplodedNode* N) const { return N->isSink() && UndefStores.count(const_cast(N)) != 0; } - + bool isImplicitNullDeref(const ExplodedNode* N) const { return N->isSink() && ImplicitNullDeref.count(const_cast(N)) != 0; } - + bool isExplicitNullDeref(const ExplodedNode* N) const { return N->isSink() && ExplicitNullDeref.count(const_cast(N)) != 0; } - + bool isUndefDeref(const ExplodedNode* N) const { return N->isSink() && UndefDeref.count(const_cast(N)) != 0; } - + bool isImplicitBadDivide(const ExplodedNode* N) const { return N->isSink() && ImplicitBadDivides.count(const_cast(N)) != 0; } - + bool isExplicitBadDivide(const ExplodedNode* N) const { return N->isSink() && ExplicitBadDivides.count(const_cast(N)) != 0; } - + bool isNoReturnCall(const ExplodedNode* N) const { return N->isSink() && NoReturnCalls.count(const_cast(N)) != 0; } - + bool isUndefResult(const ExplodedNode* N) const { return N->isSink() && UndefResults.count(const_cast(N)) != 0; } - + bool isBadCall(const ExplodedNode* N) const { return N->isSink() && BadCalls.count(const_cast(N)) != 0; } - + bool isUndefArg(const ExplodedNode* N) const { return N->isSink() && (UndefArgs.find(const_cast(N)) != UndefArgs.end() || MsgExprUndefArgs.find(const_cast(N)) != MsgExprUndefArgs.end()); } - + bool isUndefReceiver(const ExplodedNode* N) const { return N->isSink() && UndefReceivers.count(const_cast(N)) != 0; } - + typedef ErrorNodes::iterator ret_stackaddr_iterator; ret_stackaddr_iterator ret_stackaddr_begin() { return RetsStackAddr.begin(); } - ret_stackaddr_iterator ret_stackaddr_end() { return RetsStackAddr.end(); } - + ret_stackaddr_iterator ret_stackaddr_end() { return RetsStackAddr.end(); } + typedef ErrorNodes::iterator ret_undef_iterator; ret_undef_iterator ret_undef_begin() { return RetsUndef.begin(); } ret_undef_iterator ret_undef_end() { return RetsUndef.end(); } - + typedef ErrorNodes::iterator undef_branch_iterator; undef_branch_iterator undef_branches_begin() { return UndefBranches.begin(); } - undef_branch_iterator undef_branches_end() { return UndefBranches.end(); } - + undef_branch_iterator undef_branches_end() { return UndefBranches.end(); } + typedef ErrorNodes::iterator null_deref_iterator; null_deref_iterator null_derefs_begin() { return ExplicitNullDeref.begin(); } null_deref_iterator null_derefs_end() { return ExplicitNullDeref.end(); } - + null_deref_iterator implicit_null_derefs_begin() { return ImplicitNullDeref.begin(); } null_deref_iterator implicit_null_derefs_end() { return ImplicitNullDeref.end(); } - + typedef ErrorNodes::iterator nil_receiver_struct_ret_iterator; - + nil_receiver_struct_ret_iterator nil_receiver_struct_ret_begin() { return NilReceiverStructRetExplicit.begin(); } @@ -317,9 +317,9 @@ public: nil_receiver_struct_ret_iterator nil_receiver_struct_ret_end() { return NilReceiverStructRetExplicit.end(); } - + typedef ErrorNodes::iterator nil_receiver_larger_than_voidptr_ret_iterator; - + nil_receiver_larger_than_voidptr_ret_iterator nil_receiver_larger_than_voidptr_ret_begin() { return NilReceiverLargerThanVoidPtrRetExplicit.begin(); @@ -329,60 +329,60 @@ public: nil_receiver_larger_than_voidptr_ret_end() { return NilReceiverLargerThanVoidPtrRetExplicit.end(); } - + typedef ErrorNodes::iterator undef_deref_iterator; undef_deref_iterator undef_derefs_begin() { return UndefDeref.begin(); } undef_deref_iterator undef_derefs_end() { return UndefDeref.end(); } - + typedef ErrorNodes::iterator bad_divide_iterator; bad_divide_iterator explicit_bad_divides_begin() { return ExplicitBadDivides.begin(); } - + bad_divide_iterator explicit_bad_divides_end() { return ExplicitBadDivides.end(); } - + bad_divide_iterator implicit_bad_divides_begin() { return ImplicitBadDivides.begin(); } - + bad_divide_iterator implicit_bad_divides_end() { return ImplicitBadDivides.end(); } - + typedef ErrorNodes::iterator undef_result_iterator; undef_result_iterator undef_results_begin() { return UndefResults.begin(); } undef_result_iterator undef_results_end() { return UndefResults.end(); } typedef ErrorNodes::iterator bad_calls_iterator; bad_calls_iterator bad_calls_begin() { return BadCalls.begin(); } - bad_calls_iterator bad_calls_end() { return BadCalls.end(); } - + bad_calls_iterator bad_calls_end() { return BadCalls.end(); } + typedef UndefArgsTy::iterator undef_arg_iterator; undef_arg_iterator undef_arg_begin() { return UndefArgs.begin(); } - undef_arg_iterator undef_arg_end() { return UndefArgs.end(); } - + undef_arg_iterator undef_arg_end() { return UndefArgs.end(); } + undef_arg_iterator msg_expr_undef_arg_begin() { return MsgExprUndefArgs.begin(); } undef_arg_iterator msg_expr_undef_arg_end() { return MsgExprUndefArgs.end(); - } - + } + typedef ErrorNodes::iterator undef_receivers_iterator; undef_receivers_iterator undef_receivers_begin() { return UndefReceivers.begin(); } - + undef_receivers_iterator undef_receivers_end() { return UndefReceivers.end(); } typedef ErrorNodes::iterator oob_memacc_iterator; - oob_memacc_iterator implicit_oob_memacc_begin() { + oob_memacc_iterator implicit_oob_memacc_begin() { return ImplicitOOBMemAccesses.begin(); } oob_memacc_iterator implicit_oob_memacc_end() { @@ -397,45 +397,45 @@ public: void AddCheck(GRSimpleAPICheck* A, Stmt::StmtClass C); void AddCheck(GRSimpleAPICheck* A); - + /// ProcessStmt - Called by GRCoreEngine. Used to generate new successor - /// nodes by processing the 'effects' of a block-level statement. - void ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder); - + /// nodes by processing the 'effects' of a block-level statement. + void ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder); + /// ProcessBlockEntrance - Called by GRCoreEngine when start processing /// a CFGBlock. This method returns true if the analysis should continue /// exploring the given path, and false otherwise. bool ProcessBlockEntrance(CFGBlock* B, const GRState* St, GRBlockCounter BC); - + /// ProcessBranch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a branch condition. void ProcessBranch(Stmt* Condition, Stmt* Term, GRBranchNodeBuilder& builder); - + /// ProcessIndirectGoto - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a computed goto jump. void ProcessIndirectGoto(GRIndirectGotoNodeBuilder& builder); - + /// ProcessSwitch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. void ProcessSwitch(GRSwitchNodeBuilder& builder); - + /// ProcessEndPath - Called by GRCoreEngine. Used to generate end-of-path /// nodes when the control reaches the end of a function. void ProcessEndPath(GREndPathNodeBuilder& builder) { getTF().EvalEndPath(*this, builder); StateMgr.EndPath(builder.getState()); } - + GRStateManager& getStateManager() { return StateMgr; } const GRStateManager& getStateManager() const { return StateMgr; } StoreManager& getStoreManager() { return StateMgr.getStoreManager(); } - + ConstraintManager& getConstraintManager() { return StateMgr.getConstraintManager(); } - + // FIXME: Remove when we migrate over to just using ValueManager. BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); @@ -443,19 +443,19 @@ public: const BasicValueFactory& getBasicVals() const { return StateMgr.getBasicVals(); } - - ValueManager &getValueManager() { return ValMgr; } + + ValueManager &getValueManager() { return ValMgr; } const ValueManager &getValueManager() const { return ValMgr; } - + // FIXME: Remove when we migrate over to just using ValueManager. SymbolManager& getSymbolManager() { return SymMgr; } const SymbolManager& getSymbolManager() const { return SymMgr; } - + protected: const GRState* GetState(ExplodedNode* N) { return N == EntryNode ? CleanedState : N->getState(); } - + public: ExplodedNode* MakeNode(ExplodedNodeSet& Dst, Stmt* S, ExplodedNode* Pred, const GRState* St, ProgramPoint::Kind K = ProgramPoint::PostStmtKind, @@ -464,60 +464,60 @@ protected: /// CheckerVisit - Dispatcher for performing checker-specific logic /// at specific statements. void CheckerVisit(Stmt *S, ExplodedNodeSet &Dst, ExplodedNodeSet &Src, bool isPrevisit); - + /// Visit - Transfer function logic for all statements. Dispatches to /// other functions that handle specific kinds of statements. void Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitLValue - Evaluate the lvalue of the expression. For example, if Ex is /// a DeclRefExpr, it evaluates to the MemRegionVal which represents its /// storage location. Note that not all kinds of expressions has lvalue. void VisitLValue(Expr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitArraySubscriptExpr - Transfer function for array accesses. void VisitArraySubscriptExpr(ArraySubscriptExpr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue); - + /// VisitAsmStmt - Transfer function logic for inline asm. void VisitAsmStmt(AsmStmt* A, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + void VisitAsmStmtHelperOutputs(AsmStmt* A, AsmStmt::outputs_iterator I, AsmStmt::outputs_iterator E, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + void VisitAsmStmtHelperInputs(AsmStmt* A, AsmStmt::inputs_iterator I, AsmStmt::inputs_iterator E, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitBinaryOperator - Transfer function logic for binary operators. void VisitBinaryOperator(BinaryOperator* B, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitCall - Transfer function for function calls. void VisitCall(CallExpr* CE, ExplodedNode* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, ExplodedNodeSet& Dst); void VisitCallRec(CallExpr* CE, ExplodedNode* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, - ExplodedNodeSet& Dst, const FunctionProtoType *, + ExplodedNodeSet& Dst, const FunctionProtoType *, unsigned ParamIdx = 0); - + /// VisitCast - Transfer function logic for all casts (implicit and explicit). void VisitCast(Expr* CastE, Expr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst); /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. void VisitCompoundLiteralExpr(CompoundLiteralExpr* CL, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue); - + /// VisitDeclRefExpr - Transfer function logic for DeclRefExprs. void VisitDeclRefExpr(DeclRefExpr* DR, ExplodedNode* Pred, ExplodedNodeSet& Dst, - bool asLValue); - + bool asLValue); + /// VisitDeclStmt - Transfer function logic for DeclStmts. - void VisitDeclStmt(DeclStmt* DS, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + void VisitDeclStmt(DeclStmt* DS, ExplodedNode* Pred, ExplodedNodeSet& Dst); + /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose void VisitGuardedExpr(Expr* Ex, Expr* L, Expr* R, ExplodedNode* Pred, ExplodedNodeSet& Dst); @@ -525,65 +525,65 @@ protected: /// VisitLogicalExpr - Transfer function logic for '&&', '||' void VisitLogicalExpr(BinaryOperator* B, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitMemberExpr - Transfer function for member expressions. void VisitMemberExpr(MemberExpr* M, ExplodedNode* Pred, ExplodedNodeSet& Dst,bool asLValue); - + /// VisitObjCIvarRefExpr - Transfer function logic for ObjCIvarRefExprs. void VisitObjCIvarRefExpr(ObjCIvarRefExpr* DR, ExplodedNode* Pred, ExplodedNodeSet& Dst, - bool asLValue); + bool asLValue); /// VisitObjCForCollectionStmt - Transfer function logic for /// ObjCForCollectionStmt. void VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + void VisitObjCForCollectionStmtAux(ObjCForCollectionStmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst, SVal ElementV); - + /// VisitObjCMessageExpr - Transfer function for ObjC message expressions. void VisitObjCMessageExpr(ObjCMessageExpr* ME, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + void VisitObjCMessageExprArgHelper(ObjCMessageExpr* ME, ObjCMessageExpr::arg_iterator I, ObjCMessageExpr::arg_iterator E, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + void VisitObjCMessageExprDispatchHelper(ObjCMessageExpr* ME, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitReturnStmt - Transfer function logic for return statements. void VisitReturnStmt(ReturnStmt* R, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitSizeOfAlignOfExpr - Transfer function for sizeof. void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst); - + /// VisitUnaryOperator - Transfer function logic for unary operators. void VisitUnaryOperator(UnaryOperator* B, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue); - + const GRState* CheckDivideZero(Expr* Ex, const GRState* St, ExplodedNode* Pred, - SVal Denom); - + SVal Denom); + /// EvalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) /// with those assumptions. void EvalEagerlyAssume(ExplodedNodeSet& Dst, ExplodedNodeSet& Src, Expr *Ex); - + SVal EvalMinus(SVal X) { return X.isValid() ? SVator.EvalMinus(cast(X)) : X; } - + SVal EvalComplement(SVal X) { return X.isValid() ? SVator.EvalComplement(cast(X)) : X; } bool EvalBuiltinFunction(const FunctionDecl *FD, CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst); - + public: - + SVal EvalBinOp(BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T) { return SVator.EvalBinOpNN(op, L, R, T); } @@ -591,49 +591,49 @@ public: SVal EvalBinOp(BinaryOperator::Opcode op, NonLoc L, SVal R, QualType T) { return R.isValid() ? SVator.EvalBinOpNN(op, L, cast(R), T) : R; } - + SVal EvalBinOp(const GRState *ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T) { return SVator.EvalBinOp(ST, Op, LHS, RHS, T); } protected: - + void EvalCall(ExplodedNodeSet& Dst, CallExpr* CE, SVal L, ExplodedNode* Pred); - + void EvalObjCMessageExpr(ExplodedNodeSet& Dst, ObjCMessageExpr* ME, ExplodedNode* Pred) { assert (Builder && "GRStmtNodeBuilder must be defined."); getTF().EvalObjCMessageExpr(Dst, *this, *Builder, ME, Pred); } void EvalReturn(ExplodedNodeSet& Dst, ReturnStmt* s, ExplodedNode* Pred); - - const GRState* MarkBranch(const GRState* St, Stmt* Terminator, + + const GRState* MarkBranch(const GRState* St, Stmt* Terminator, bool branchTaken); - + /// EvalBind - Handle the semantics of binding a value to a specific location. /// This method is used by EvalStore, VisitDeclStmt, and others. void EvalBind(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, const GRState* St, SVal location, SVal Val); - + public: void EvalLoad(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, const GRState* St, SVal location, const void *tag = 0); - + ExplodedNode* EvalLocation(Stmt* Ex, ExplodedNode* Pred, const GRState* St, SVal location, const void *tag = 0); - + void EvalStore(ExplodedNodeSet& Dst, Expr* E, ExplodedNode* Pred, const GRState* St, SVal TargetLV, SVal Val, const void *tag = 0); - + void EvalStore(ExplodedNodeSet& Dst, Expr* E, Expr* StoreE, ExplodedNode* Pred, const GRState* St, SVal TargetLV, SVal Val, const void *tag = 0); - + }; - + } // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/GRExprEngineBuilders.h b/clang/include/clang/Analysis/PathSensitive/GRExprEngineBuilders.h index 0c3181885751417a202e164d61d17e6e123caac6..60db406cd13dfad47f5145dbbcf387573b23d58a 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRExprEngineBuilders.h +++ b/clang/include/clang/Analysis/PathSensitive/GRExprEngineBuilders.h @@ -34,10 +34,10 @@ class GRStmtNodeBuilderRef { private: friend class GRExprEngine; - + GRStmtNodeBuilderRef(); // do not implement void operator=(const GRStmtNodeBuilderRef&); // do not implement - + GRStmtNodeBuilderRef(ExplodedNodeSet &dst, GRStmtNodeBuilder &builder, GRExprEngine& eng, @@ -47,12 +47,12 @@ private: : Dst(dst), B(builder), Eng(eng), Pred(pred), state(st), stmt(s), OldSize(Dst.size()), AutoCreateNode(auto_create_node), OldSink(B.BuildSinks), OldTag(B.Tag), OldHasGen(B.HasGeneratedNode) {} - + public: ~GRStmtNodeBuilderRef() { // Handle the case where no nodes where generated. Auto-generate that - // contains the updated state if we aren't generating sinks. + // contains the updated state if we aren't generating sinks. if (!B.BuildSinks && Dst.size() == OldSize && !B.HasGeneratedNode) { if (AutoCreateNode) B.MakeNode(Dst, const_cast(stmt), Pred, state); @@ -62,14 +62,14 @@ public: } const GRState *getState() { return state; } - + GRStateManager& getStateManager() { return Eng.getStateManager(); } - + ExplodedNode* MakeNode(const GRState* state) { - return B.MakeNode(Dst, const_cast(stmt), Pred, state); - } + return B.MakeNode(Dst, const_cast(stmt), Pred, state); + } }; } // end clang namespace diff --git a/clang/include/clang/Analysis/PathSensitive/GRSimpleAPICheck.h b/clang/include/clang/Analysis/PathSensitive/GRSimpleAPICheck.h index c0593a375c35d3619d852bc4e94e0e8f06a78330..978ff0889e64c54540856bcb7193bb664cb84c07 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRSimpleAPICheck.h +++ b/clang/include/clang/Analysis/PathSensitive/GRSimpleAPICheck.h @@ -20,15 +20,15 @@ #include "clang/Analysis/PathSensitive/GRState.h" namespace clang { - + class Diagnostic; class BugReporter; class ASTContext; class GRExprEngine; class PathDiagnosticClient; class ExplodedGraph; - - + + class GRSimpleAPICheck : public GRAuditor { public: GRSimpleAPICheck() {} diff --git a/clang/include/clang/Analysis/PathSensitive/GRState.h b/clang/include/clang/Analysis/PathSensitive/GRState.h index 54a86af1f734c6e8cd5e2b0ed79650b6fe7e26b4..3924084015cdc328bea94256f18815b6b42ee3c5 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRState.h +++ b/clang/include/clang/Analysis/PathSensitive/GRState.h @@ -49,12 +49,12 @@ typedef StoreManager* (*StoreManagerCreator)(GRStateManager&); //===----------------------------------------------------------------------===// // GRStateTrait - Traits used by the Generic Data Map of a GRState. //===----------------------------------------------------------------------===// - + template struct GRStatePartialTrait; template struct GRStateTrait { typedef typename T::data_type data_type; - static inline void* GDMIndex() { return &T::TagInt; } + static inline void* GDMIndex() { return &T::TagInt; } static inline void* MakeVoidPtr(data_type D) { return (void*) D; } static inline data_type MakeData(void* const* P) { return P ? (data_type) *P : (data_type) 0; @@ -66,19 +66,19 @@ template struct GRStateTrait { //===----------------------------------------------------------------------===// class GRStateManager; - + /// GRState - This class encapsulates the actual data values for /// for a "state" in our symbolic value tracking. It is intended to be /// used as a functional object; that is once it is created and made /// "persistent" in a FoldingSet its values will never change. class GRState : public llvm::FoldingSetNode { -public: +public: typedef llvm::ImmutableSet IntSetTy; - typedef llvm::ImmutableMap GenericDataMap; - + typedef llvm::ImmutableMap GenericDataMap; + private: void operator=(const GRState& R) const; - + friend class GRStateManager; GRStateManager *StateMgr; @@ -88,9 +88,9 @@ private: // FIXME: Make these private. public: GenericDataMap GDM; - + public: - + /// This ctor is used when creating the first GRState object. GRState(GRStateManager *mgr, const Environment& env, Store st, GenericDataMap gdm) @@ -98,7 +98,7 @@ public: Env(env), St(st), GDM(gdm) {} - + /// Copy ctor - We must explicitly define this or else the "Next" ptr /// in FoldingSetNode will also get copied. GRState(const GRState& RHS) @@ -107,33 +107,33 @@ public: Env(RHS.Env), St(RHS.St), GDM(RHS.GDM) {} - + /// getStateManager - Return the GRStateManager associated with this state. GRStateManager &getStateManager() const { return *StateMgr; } - + /// getAnalysisContext - Return the AnalysisContext associated with this /// state. AnalysisContext &getAnalysisContext() const { return Env.getAnalysisContext(); } - + /// getEnvironment - Return the environment associated with this state. /// The environment is the mapping from expressions to values. const Environment& getEnvironment() const { return Env; } - + /// getStore - Return the store associated with this state. The store /// is a mapping from locations to values. Store getStore() const { return St; } - + void setStore(Store s) { St = s; } - + /// getGDM - Return the generic data map associated with this state. GenericDataMap getGDM() const { return GDM; } - + void setGDM(GenericDataMap gdm) { GDM = gdm; } - + /// Profile - Profile the contents of a GRState object for use /// in a FoldingSet. static void Profile(llvm::FoldingSetNodeID& ID, const GRState* V) { @@ -148,19 +148,19 @@ public: void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, this); } - + SVal LookupExpr(Expr* E) const { return Env.LookupExpr(E); } - + /// makeWithStore - Return a GRState with the same values as the current /// state with the exception of using the specified Store. const GRState *makeWithStore(Store store) const; - + BasicValueFactory &getBasicVals() const; SymbolManager &getSymbolManager() const; GRTransferFuncs &getTransferFuncs() const; - + //==---------------------------------------------------------------------==// // Constraints on values. //==---------------------------------------------------------------------==// @@ -193,12 +193,12 @@ public: // FIXME: (a) should probably disappear since it is redundant with (b). // (i.e., (b) could just be set to NULL). // - + const GRState *assume(SVal condition, bool assumption) const; - - const GRState *assumeInBound(SVal idx, SVal upperBound, + + const GRState *assumeInBound(SVal idx, SVal upperBound, bool assumption) const; - + //==---------------------------------------------------------------------==// // Utility methods for getting regions. //==---------------------------------------------------------------------==// @@ -208,67 +208,67 @@ public: //==---------------------------------------------------------------------==// // Binding and retrieving values to/from the environment and symbolic store. //==---------------------------------------------------------------------==// - + /// BindCompoundLiteral - Return the state that has the bindings currently /// in 'state' plus the bindings for the CompoundLiteral. 'R' is the region /// for the compound literal and 'BegInit' and 'EndInit' represent an /// array of initializer values. const GRState* bindCompoundLiteral(const CompoundLiteralExpr* CL, SVal V) const; - + const GRState *BindExpr(const Stmt *S, SVal V, bool Invalidate = true) const; - + const GRState *bindDecl(const VarDecl *VD, const LocationContext *LC, SVal V) const; - + const GRState *bindDeclWithNoInit(const VarDecl *VD, - const LocationContext *LC) const; - + const LocationContext *LC) const; + const GRState *bindLoc(Loc location, SVal V) const; - + const GRState *bindLoc(SVal location, SVal V) const; - + const GRState *unbindLoc(Loc LV) const; /// Get the lvalue for a variable reference. SVal getLValue(const VarDecl *D, const LocationContext *LC) const; - + /// Get the lvalue for a StringLiteral. SVal getLValue(const StringLiteral *literal) const; - + SVal getLValue(const CompoundLiteralExpr *literal) const; - + /// Get the lvalue for an ivar reference. SVal getLValue(const ObjCIvarDecl *decl, SVal base) const; - + /// Get the lvalue for a field reference. SVal getLValue(SVal Base, const FieldDecl *decl) const; - + /// Get the lvalue for an array index. SVal getLValue(QualType ElementType, SVal Base, SVal Idx) const; - + const llvm::APSInt *getSymVal(SymbolRef sym) const; SVal getSVal(const Stmt* Ex) const; - + SVal getSValAsScalarOrLoc(const Stmt *Ex) const; - + SVal getSVal(Loc LV, QualType T = QualType()) const; - + SVal getSVal(const MemRegion* R) const; - + SVal getSValAsScalarOrLoc(const MemRegion *R) const; - + bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const; template CB scanReachableSymbols(SVal val) const; - + //==---------------------------------------------------------------------==// // Accessing the Generic Data Map (GDM). //==---------------------------------------------------------------------==// void* const* FindGDM(void* K) const; - + template const GRState *add(typename GRStateTrait::key_type K) const; @@ -277,31 +277,31 @@ public: get() const { return GRStateTrait::MakeData(FindGDM(GRStateTrait::GDMIndex())); } - + template typename GRStateTrait::lookup_type get(typename GRStateTrait::key_type key) const { void* const* d = FindGDM(GRStateTrait::GDMIndex()); return GRStateTrait::Lookup(GRStateTrait::MakeData(d), key); } - + template typename GRStateTrait::context_type get_context() const; - - + + template const GRState *remove(typename GRStateTrait::key_type K) const; template const GRState *remove(typename GRStateTrait::key_type K, typename GRStateTrait::context_type C) const; - + template const GRState *set(typename GRStateTrait::data_type D) const; - + template const GRState *set(typename GRStateTrait::key_type K, - typename GRStateTrait::value_type E) const; + typename GRStateTrait::value_type E) const; template const GRState *set(typename GRStateTrait::key_type K, @@ -313,7 +313,7 @@ public: void* const* d = FindGDM(GRStateTrait::GDMIndex()); return GRStateTrait::Contains(GRStateTrait::MakeData(d), key); } - + // State pretty-printing. class Printer { public: @@ -321,55 +321,55 @@ public: virtual void Print(llvm::raw_ostream& Out, const GRState* state, const char* nl, const char* sep) = 0; }; - + // Pretty-printing. void print(llvm::raw_ostream& Out, const char *nl = "\n", - const char *sep = "") const; + const char *sep = "") const; + + void printStdErr() const; + + void printDOT(llvm::raw_ostream& Out) const; - void printStdErr() const; - - void printDOT(llvm::raw_ostream& Out) const; - // Tags used for the Generic Data Map. struct NullDerefTag { static int TagInt; typedef const SVal* data_type; }; }; - + class GRStateSet { typedef llvm::SmallPtrSet ImplTy; - ImplTy Impl; + ImplTy Impl; public: GRStateSet() {} inline void Add(const GRState* St) { Impl.insert(St); } - + typedef ImplTy::const_iterator iterator; - + inline unsigned size() const { return Impl.size(); } inline bool empty() const { return Impl.empty(); } - + inline iterator begin() const { return Impl.begin(); } inline iterator end() const { return Impl.end(); } - + class AutoPopulate { GRStateSet& S; unsigned StartSize; const GRState* St; public: - AutoPopulate(GRStateSet& s, const GRState* st) + AutoPopulate(GRStateSet& s, const GRState* st) : S(s), StartSize(S.size()), St(st) {} - + ~AutoPopulate() { if (StartSize == S.size()) S.Add(St); } }; -}; - +}; + //===----------------------------------------------------------------------===// // GRStateManager - Factory object for GRStates. //===----------------------------------------------------------------------===// @@ -377,21 +377,21 @@ public: class GRStateManager { friend class GRExprEngine; friend class GRState; - + private: EnvironmentManager EnvMgr; llvm::OwningPtr StoreMgr; llvm::OwningPtr ConstraintMgr; - + GRState::GenericDataMap::Factory GDMFactory; - + typedef llvm::DenseMap > GDMContextsTy; GDMContextsTy GDMContexts; - + /// Printers - A set of printer objects used for pretty-printing a GRState. /// GRStateManager owns these objects. std::vector Printers; - + /// StateSet - FoldingSet containing all the states created for analyzing /// a particular function. This is used to unique states. llvm::FoldingSet StateSet; @@ -401,36 +401,36 @@ private: /// Alloc - A BumpPtrAllocator to allocate states. llvm::BumpPtrAllocator& Alloc; - + /// CurrentStmt - The block-level statement currently being visited. This /// is set by GRExprEngine. Stmt* CurrentStmt; - + /// TF - Object that represents a bundle of transfer functions /// for manipulating and creating SVals. GRTransferFuncs* TF; public: - + GRStateManager(ASTContext& Ctx, StoreManagerCreator CreateStoreManager, ConstraintManagerCreator CreateConstraintManager, llvm::BumpPtrAllocator& alloc) - : EnvMgr(alloc), - GDMFactory(alloc), - ValueMgr(alloc, Ctx, *this), + : EnvMgr(alloc), + GDMFactory(alloc), + ValueMgr(alloc, Ctx, *this), Alloc(alloc) { StoreMgr.reset((*CreateStoreManager)(*this)); ConstraintMgr.reset((*CreateConstraintManager)(*this)); } - + ~GRStateManager(); const GRState *getInitialState(const LocationContext *InitLoc); - + ASTContext &getContext() { return ValueMgr.getContext(); } const ASTContext &getContext() const { return ValueMgr.getContext(); } - + GRTransferFuncs& getTransferFuncs() { return *TF; } BasicValueFactory &getBasicVals() { @@ -439,17 +439,17 @@ public: const BasicValueFactory& getBasicVals() const { return ValueMgr.getBasicValueFactory(); } - + SymbolManager &getSymbolManager() { return ValueMgr.getSymbolManager(); } const SymbolManager &getSymbolManager() const { return ValueMgr.getSymbolManager(); } - + ValueManager &getValueManager() { return ValueMgr; } const ValueManager &getValueManager() const { return ValueMgr; } - + llvm::BumpPtrAllocator& getAllocator() { return Alloc; } MemRegionManager& getRegionManager() { @@ -458,11 +458,11 @@ public: const MemRegionManager& getRegionManager() const { return ValueMgr.getRegionManager(); } - + StoreManager& getStoreManager() { return *StoreMgr; } ConstraintManager& getConstraintManager() { return *ConstraintMgr; } - const GRState* RemoveDeadBindings(const GRState* St, Stmt* Loc, + const GRState* RemoveDeadBindings(const GRState* St, Stmt* Loc, SymbolReaper& SymReaper); public: @@ -470,10 +470,10 @@ public: SVal ArrayToPointer(Loc Array) { return StoreMgr->ArrayToPointer(Array); } - + // Methods that manipulate the GDM. const GRState* addGDM(const GRState* St, void* Key, void* Data); - + // Methods that query & manipulate the Store. void iterBindings(const GRState* state, StoreManager::BindingsHandler& F) { @@ -484,7 +484,7 @@ public: bool isEqual(const GRState* state, const Expr* Ex, const llvm::APSInt& V); bool isEqual(const GRState* state, const Expr* Ex, uint64_t); - + //==---------------------------------------------------------------------==// // Generic Data Map methods. //==---------------------------------------------------------------------==// @@ -502,21 +502,21 @@ public: // The templated methods below use the GRStateTrait class // to resolve keys into the GDM and to return data values to clients. // - - // Trait based GDM dispatch. + + // Trait based GDM dispatch. template const GRState* set(const GRState* st, typename GRStateTrait::data_type D) { return addGDM(st, GRStateTrait::GDMIndex(), GRStateTrait::MakeVoidPtr(D)); } - + template const GRState* set(const GRState* st, typename GRStateTrait::key_type K, typename GRStateTrait::value_type V, typename GRStateTrait::context_type C) { - - return addGDM(st, GRStateTrait::GDMIndex(), + + return addGDM(st, GRStateTrait::GDMIndex(), GRStateTrait::MakeVoidPtr(GRStateTrait::Set(st->get(), K, V, C))); } @@ -532,22 +532,22 @@ public: const GRState* remove(const GRState* st, typename GRStateTrait::key_type K, typename GRStateTrait::context_type C) { - - return addGDM(st, GRStateTrait::GDMIndex(), + + return addGDM(st, GRStateTrait::GDMIndex(), GRStateTrait::MakeVoidPtr(GRStateTrait::Remove(st->get(), K, C))); } - + void* FindGDMContext(void* index, void* (*CreateContext)(llvm::BumpPtrAllocator&), void (*DeleteContext)(void*)); - + template typename GRStateTrait::context_type get_context() { void* p = FindGDMContext(GRStateTrait::GDMIndex(), GRStateTrait::CreateContext, GRStateTrait::DeleteContext); - + return GRStateTrait::MakeContext(p); } @@ -559,7 +559,7 @@ public: ConstraintMgr->EndPath(St); } }; - + //===----------------------------------------------------------------------===// // Out-of-line method definitions for GRState. @@ -577,13 +577,13 @@ inline const GRState *GRState::assume(SVal Cond, bool Assumption) const { inline const GRState *GRState::assumeInBound(SVal Idx, SVal UpperBound, bool Assumption) const { return getStateManager().ConstraintMgr->AssumeInBound(this, Idx, UpperBound, Assumption); -} +} inline const GRState *GRState::bindCompoundLiteral(const CompoundLiteralExpr* CL, SVal V) const { return getStateManager().StoreMgr->BindCompoundLiteral(this, CL, V); } - + inline const GRState *GRState::bindDecl(const VarDecl* VD, const LocationContext *LC, SVal IVal) const { @@ -594,7 +594,7 @@ inline const GRState *GRState::bindDeclWithNoInit(const VarDecl* VD, const LocationContext *LC) const { return getStateManager().StoreMgr->BindDeclWithNoInit(this, VD, LC); } - + inline const GRState *GRState::bindLoc(Loc LV, SVal V) const { return getStateManager().StoreMgr->Bind(this, LV, V); } @@ -602,7 +602,7 @@ inline const GRState *GRState::bindLoc(Loc LV, SVal V) const { inline const GRState *GRState::bindLoc(SVal LV, SVal V) const { return !isa(LV) ? this : bindLoc(cast(LV), V); } - + inline SVal GRState::getLValue(const VarDecl* VD, const LocationContext *LC) const { return getStateManager().StoreMgr->getLValueVar(this, VD, LC); @@ -611,7 +611,7 @@ inline SVal GRState::getLValue(const VarDecl* VD, inline SVal GRState::getLValue(const StringLiteral *literal) const { return getStateManager().StoreMgr->getLValueString(this, literal); } - + inline SVal GRState::getLValue(const CompoundLiteralExpr *literal) const { return getStateManager().StoreMgr->getLValueCompoundLiteral(this, literal); } @@ -619,19 +619,19 @@ inline SVal GRState::getLValue(const CompoundLiteralExpr *literal) const { inline SVal GRState::getLValue(const ObjCIvarDecl *D, SVal Base) const { return getStateManager().StoreMgr->getLValueIvar(this, D, Base); } - + inline SVal GRState::getLValue(SVal Base, const FieldDecl* D) const { return getStateManager().StoreMgr->getLValueField(this, Base, D); } - + inline SVal GRState::getLValue(QualType ElementType, SVal Base, SVal Idx) const{ return getStateManager().StoreMgr->getLValueElement(this, ElementType, Base, Idx); } - + inline const llvm::APSInt *GRState::getSymVal(SymbolRef sym) const { return getStateManager().getSymVal(this, sym); } - + inline SVal GRState::getSVal(const Stmt* Ex) const { return Env.GetSVal(Ex, getStateManager().ValueMgr); } @@ -642,7 +642,7 @@ inline SVal GRState::getSValAsScalarOrLoc(const Stmt *S) const { if (Loc::IsLocType(T) || T->isIntegerType()) return getSVal(S); } - + return UnknownVal(); } @@ -653,7 +653,7 @@ inline SVal GRState::getSVal(Loc LV, QualType T) const { inline SVal GRState::getSVal(const MemRegion* R) const { return getStateManager().StoreMgr->Retrieve(this, loc::MemRegionVal(R)).getSVal(); } - + inline BasicValueFactory &GRState::getBasicVals() const { return getStateManager().getBasicVals(); } @@ -661,7 +661,7 @@ inline BasicValueFactory &GRState::getBasicVals() const { inline SymbolManager &GRState::getSymbolManager() const { return getStateManager().getSymbolManager(); } - + inline GRTransferFuncs &GRState::getTransferFuncs() const { return getStateManager().getTransferFuncs(); } @@ -670,12 +670,12 @@ template const GRState *GRState::add(typename GRStateTrait::key_type K) const { return getStateManager().add(this, K, get_context()); } - + template typename GRStateTrait::context_type GRState::get_context() const { return getStateManager().get_context(); } - + template const GRState *GRState::remove(typename GRStateTrait::key_type K) const { return getStateManager().remove(this, K, get_context()); @@ -686,25 +686,25 @@ const GRState *GRState::remove(typename GRStateTrait::key_type K, typename GRStateTrait::context_type C) const { return getStateManager().remove(this, K, C); } - + template const GRState *GRState::set(typename GRStateTrait::data_type D) const { return getStateManager().set(this, D); } - + template const GRState *GRState::set(typename GRStateTrait::key_type K, typename GRStateTrait::value_type E) const { return getStateManager().set(this, K, E, get_context()); } - + template const GRState *GRState::set(typename GRStateTrait::key_type K, typename GRStateTrait::value_type E, typename GRStateTrait::context_type C) const { return getStateManager().set(this, K, E, C); } - + template CB GRState::scanReachableSymbols(SVal val) const { CB cb(this); diff --git a/clang/include/clang/Analysis/PathSensitive/GRStateTrait.h b/clang/include/clang/Analysis/PathSensitive/GRStateTrait.h index ce43cda31e9e54a44ea26ddcc2c731a0170a7318..5189a1f5aa7e84faf937dd981b703ef924d590c2 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRStateTrait.h +++ b/clang/include/clang/Analysis/PathSensitive/GRStateTrait.h @@ -1,5 +1,5 @@ //==- GRStateTrait.h - Partial implementations of GRStateTrait -----*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source @@ -27,59 +27,59 @@ namespace llvm { namespace clang { template struct GRStatePartialTrait; - + // Partial-specialization for ImmutableMap. - + template struct GRStatePartialTrait< llvm::ImmutableMap > { typedef llvm::ImmutableMap data_type; - typedef typename data_type::Factory& context_type; + typedef typename data_type::Factory& context_type; typedef Key key_type; typedef Data value_type; typedef const value_type* lookup_type; - + static inline data_type MakeData(void* const* p) { return p ? data_type((typename data_type::TreeTy*) *p) : data_type(0); - } + } static inline void* MakeVoidPtr(data_type B) { return B.getRoot(); - } + } static lookup_type Lookup(data_type B, key_type K) { return B.lookup(K); - } + } static data_type Set(data_type B, key_type K, value_type E,context_type F){ return F.Add(B, K, E); } - + static data_type Remove(data_type B, key_type K, context_type F) { return F.Remove(B, K); } - + static inline context_type MakeContext(void* p) { return *((typename data_type::Factory*) p); } - + static void* CreateContext(llvm::BumpPtrAllocator& Alloc) { - return new typename data_type::Factory(Alloc); + return new typename data_type::Factory(Alloc); } - + static void DeleteContext(void* Ctx) { delete (typename data_type::Factory*) Ctx; - } + } }; - - + + // Partial-specialization for ImmutableSet. - + template struct GRStatePartialTrait< llvm::ImmutableSet > { typedef llvm::ImmutableSet data_type; - typedef typename data_type::Factory& context_type; + typedef typename data_type::Factory& context_type; typedef Key key_type; - + static inline data_type MakeData(void* const* p) { return p ? data_type((typename data_type::TreeTy*) *p) : data_type(0); - } + } static inline void* MakeVoidPtr(data_type B) { return B.getRoot(); @@ -88,60 +88,60 @@ namespace clang { static data_type Add(data_type B, key_type K, context_type F) { return F.Add(B, K); } - + static data_type Remove(data_type B, key_type K, context_type F) { return F.Remove(B, K); } - + static bool Contains(data_type B, key_type K) { return B.contains(K); } - + static inline context_type MakeContext(void* p) { return *((typename data_type::Factory*) p); } - + static void* CreateContext(llvm::BumpPtrAllocator& Alloc) { - return new typename data_type::Factory(Alloc); + return new typename data_type::Factory(Alloc); } - + static void DeleteContext(void* Ctx) { delete (typename data_type::Factory*) Ctx; - } + } }; - + // Partial-specialization for ImmutableList. - + template struct GRStatePartialTrait< llvm::ImmutableList > { typedef llvm::ImmutableList data_type; typedef T key_type; - typedef typename data_type::Factory& context_type; - + typedef typename data_type::Factory& context_type; + static data_type Add(data_type L, key_type K, context_type F) { return F.Add(K, L); } - + static inline data_type MakeData(void* const* p) { - return p ? data_type((const llvm::ImmutableListImpl*) *p) + return p ? data_type((const llvm::ImmutableListImpl*) *p) : data_type(0); - } - + } + static inline void* MakeVoidPtr(data_type D) { return (void*) D.getInternalPointer(); - } - + } + static inline context_type MakeContext(void* p) { return *((typename data_type::Factory*) p); } - + static void* CreateContext(llvm::BumpPtrAllocator& Alloc) { - return new typename data_type::Factory(Alloc); + return new typename data_type::Factory(Alloc); } - + static void DeleteContext(void* Ctx) { delete (typename data_type::Factory*) Ctx; - } + } }; } // end clang namespace diff --git a/clang/include/clang/Analysis/PathSensitive/GRSubEngine.h b/clang/include/clang/Analysis/PathSensitive/GRSubEngine.h index f4636095adaed8010edd72cc89f4ed7e8d6e5776..62e36f9e641e44814d773acf77aeac54819d4a81 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRSubEngine.h +++ b/clang/include/clang/Analysis/PathSensitive/GRSubEngine.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines the interface of a subengine of the GRCoreEngine. +// This file defines the interface of a subengine of the GRCoreEngine. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GRSUBENGINE_H @@ -36,28 +36,28 @@ public: virtual GRStateManager& getStateManager() = 0; /// ProcessStmt - Called by GRCoreEngine. Used to generate new successor - /// nodes by processing the 'effects' of a block-level statement. - virtual void ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder) = 0; - + /// nodes by processing the 'effects' of a block-level statement. + virtual void ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder) = 0; + /// ProcessBlockEntrance - Called by GRCoreEngine when start processing /// a CFGBlock. This method returns true if the analysis should continue /// exploring the given path, and false otherwise. virtual bool ProcessBlockEntrance(CFGBlock* B, const GRState* St, GRBlockCounter BC) = 0; - + /// ProcessBranch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a branch condition. - virtual void ProcessBranch(Stmt* Condition, Stmt* Term, + virtual void ProcessBranch(Stmt* Condition, Stmt* Term, GRBranchNodeBuilder& builder) = 0; - + /// ProcessIndirectGoto - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a computed goto jump. virtual void ProcessIndirectGoto(GRIndirectGotoNodeBuilder& builder) = 0; - + /// ProcessSwitch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. virtual void ProcessSwitch(GRSwitchNodeBuilder& builder) = 0; - + /// ProcessEndPath - Called by GRCoreEngine. Used to generate end-of-path /// nodes when the control reaches the end of a function. virtual void ProcessEndPath(GREndPathNodeBuilder& builder) = 0; diff --git a/clang/include/clang/Analysis/PathSensitive/GRTransferFuncs.h b/clang/include/clang/Analysis/PathSensitive/GRTransferFuncs.h index 87caf8e054738f433e25327453c9ebadedf93a9c..a3bb8bad842649a4f63d32c6d73b7cf046cad747 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRTransferFuncs.h +++ b/clang/include/clang/Analysis/PathSensitive/GRTransferFuncs.h @@ -21,66 +21,66 @@ #include namespace clang { - + class GRExprEngine; class BugReporter; class ObjCMessageExpr; class GRStmtNodeBuilderRef; - + class GRTransferFuncs { public: GRTransferFuncs() {} virtual ~GRTransferFuncs() {} - + virtual void RegisterPrinters(std::vector& Printers) {} virtual void RegisterChecks(BugReporter& BR) {} - + // Calls. - + virtual void EvalCall(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, CallExpr* CE, SVal L, ExplodedNode* Pred) {} - + virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ObjCMessageExpr* ME, ExplodedNode* Pred) {} - + // Stores. - + virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {} - + // End-of-path and dead symbol notification. - + virtual void EvalEndPath(GRExprEngine& Engine, GREndPathNodeBuilder& Builder) {} - - + + virtual void EvalDeadSymbols(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ExplodedNode* Pred, Stmt* S, const GRState* state, SymbolReaper& SymReaper) {} - - // Return statements. + + // Return statements. virtual void EvalReturn(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ReturnStmt* S, ExplodedNode* Pred) {} - // Assumptions. + // Assumptions. virtual const GRState* EvalAssume(const GRState *state, SVal Cond, bool Assumption) { return state; } }; - + } // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/GRWorkList.h b/clang/include/clang/Analysis/PathSensitive/GRWorkList.h index b423e88072e55508d11e1d3552178573b88fe7ed..17b83fdf9fdc3d362a8eb3e224afd753bdadf4c1 100644 --- a/clang/include/clang/Analysis/PathSensitive/GRWorkList.h +++ b/clang/include/clang/Analysis/PathSensitive/GRWorkList.h @@ -1,5 +1,5 @@ //==- GRWorkList.h - Worklist class used by GRCoreEngine -----------*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source @@ -17,16 +17,16 @@ #include "clang/Analysis/PathSensitive/GRBlockCounter.h" -namespace clang { +namespace clang { class ExplodedNodeImpl; - + class GRWorkListUnit { ExplodedNode* Node; GRBlockCounter Counter; CFGBlock* Block; unsigned BlockIdx; - + public: GRWorkListUnit(ExplodedNode* N, GRBlockCounter C, CFGBlock* B, unsigned idx) @@ -34,13 +34,13 @@ public: Counter(C), Block(B), BlockIdx(idx) {} - + explicit GRWorkListUnit(ExplodedNode* N, GRBlockCounter C) : Node(N), Counter(C), Block(NULL), BlockIdx(0) {} - + ExplodedNode* getNode() const { return Node; } GRBlockCounter getBlockCounter() const { return Counter; } CFGBlock* getBlock() const { return Block; } @@ -52,25 +52,25 @@ class GRWorkList { public: virtual ~GRWorkList(); virtual bool hasWork() const = 0; - + virtual void Enqueue(const GRWorkListUnit& U) = 0; - void Enqueue(ExplodedNode* N, CFGBlock& B, unsigned idx) { + void Enqueue(ExplodedNode* N, CFGBlock& B, unsigned idx) { Enqueue(GRWorkListUnit(N, CurrentCounter, &B, idx)); } - + void Enqueue(ExplodedNode* N) { Enqueue(GRWorkListUnit(N, CurrentCounter)); } - + virtual GRWorkListUnit Dequeue() = 0; - + void setBlockCounter(GRBlockCounter C) { CurrentCounter = C; } GRBlockCounter getBlockCounter() const { return CurrentCounter; } - + static GRWorkList *MakeDFS(); static GRWorkList *MakeBFS(); static GRWorkList *MakeBFSBlockDFSContents(); }; -} // end clang namespace +} // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/MemRegion.h b/clang/include/clang/Analysis/PathSensitive/MemRegion.h index 54cb872368acd5e27a0cfbbd0aa8d6e2a595d617..ae0580afa458b94cf27cf4dcabf5f58b7d3b77bd 100644 --- a/clang/include/clang/Analysis/PathSensitive/MemRegion.h +++ b/clang/include/clang/Analysis/PathSensitive/MemRegion.h @@ -31,15 +31,15 @@ namespace llvm { class raw_ostream; } namespace clang { - + class MemRegionManager; class MemSpaceRegion; class LocationContext; - + //===----------------------------------------------------------------------===// // Base region classes. //===----------------------------------------------------------------------===// - + /// MemRegion - The root abstract class for all memory regions. class MemRegion : public llvm::FoldingSetNode { public: @@ -56,52 +56,52 @@ public: VarRegionKind, FieldRegionKind, ObjCIvarRegionKind, ObjCObjectRegionKind, END_DECL_REGIONS, - END_TYPED_REGIONS }; + END_TYPED_REGIONS }; private: const Kind kind; - + protected: MemRegion(Kind k) : kind(k) {} virtual ~MemRegion(); public: ASTContext &getContext() const; - + virtual void Profile(llvm::FoldingSetNodeID& ID) const = 0; virtual MemRegionManager* getMemRegionManager() const = 0; std::string getString() const; - + const MemSpaceRegion *getMemorySpace() const; - + const MemRegion *getBaseRegion() const; - + bool hasStackStorage() const; - + bool hasParametersStorage() const; - + bool hasGlobalsStorage() const; - + bool hasGlobalsOrParametersStorage() const; - + bool hasHeapStorage() const; - + bool hasHeapOrStackStorage() const; virtual void dumpToStream(llvm::raw_ostream& os) const; void dump() const; - - Kind getKind() const { return kind; } - + + Kind getKind() const { return kind; } + template const RegionTy* getAs() const; - + virtual bool isBoundable() const { return false; } static bool classof(const MemRegion*) { return true; } }; - + /// MemSpaceRegion - A memory region that represents and "memory space"; /// for example, the set of global variables, the stack frame, etc. class MemSpaceRegion : public MemRegion { @@ -112,7 +112,7 @@ protected: MemSpaceRegion(MemRegionManager *mgr) : MemRegion(MemSpaceRegionKind), Mgr(mgr) {} - + MemRegionManager* getMemRegionManager() const { return Mgr; } @@ -131,28 +131,28 @@ public: /// are subclasses of SubRegion. class SubRegion : public MemRegion { protected: - const MemRegion* superRegion; + const MemRegion* superRegion; SubRegion(const MemRegion* sReg, Kind k) : MemRegion(k), superRegion(sReg) {} public: const MemRegion* getSuperRegion() const { return superRegion; } - + MemRegionManager* getMemRegionManager() const; - + bool isSubRegionOf(const MemRegion* R) const; - + static bool classof(const MemRegion* R) { return R->getKind() > MemSpaceRegionKind; } }; - + //===----------------------------------------------------------------------===// // Auxillary data classes for use with MemRegions. //===----------------------------------------------------------------------===// class ElementRegion; - + class RegionRawOffset : public std::pair { private: friend class ElementRegion; @@ -160,7 +160,7 @@ private: RegionRawOffset(const MemRegion* reg, int64_t offset = 0) : std::pair(reg, offset) {} -public: +public: // FIXME: Eventually support symbolic offsets. int64_t getByteOffset() const { return second; } const MemRegion *getRegion() const { return first; } @@ -171,7 +171,7 @@ public: //===----------------------------------------------------------------------===// // MemRegion subclasses. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// /// AllocaRegion - A region that represents an untyped blob of bytes created /// by a call to 'alloca'. @@ -184,9 +184,9 @@ protected: AllocaRegion(const Expr* ex, unsigned cnt, const MemRegion *superRegion) : SubRegion(superRegion, AllocaRegionKind), Cnt(cnt), Ex(ex) {} - + public: - + const Expr* getExpr() const { return Ex; } bool isBoundable() const { return true; } @@ -195,32 +195,32 @@ public: static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Expr* Ex, unsigned Cnt, const MemRegion *superRegion); - + void dumpToStream(llvm::raw_ostream& os) const; - + static bool classof(const MemRegion* R) { return R->getKind() == AllocaRegionKind; } -}; - +}; + /// TypedRegion - An abstract class representing regions that are typed. class TypedRegion : public SubRegion { protected: TypedRegion(const MemRegion* sReg, Kind k) : SubRegion(sReg, k) {} - + public: virtual QualType getValueType(ASTContext &C) const = 0; - + virtual QualType getLocationType(ASTContext& C) const { // FIXME: We can possibly optimize this later to cache this value. return C.getPointerType(getValueType(C)); } - + QualType getDesugaredValueType(ASTContext& C) const { QualType T = getValueType(C); return T.getTypePtr() ? T->getDesugaredType() : T; } - + QualType getDesugaredLocationType(ASTContext& C) const { return getLocationType(C)->getDesugaredType(); } @@ -260,9 +260,9 @@ public: const FunctionDecl *getDecl() const { return FD; } - + bool isBoundable() const { return false; } - + virtual void dumpToStream(llvm::raw_ostream& os) const; void Profile(llvm::FoldingSetNodeID& ID) const; @@ -285,9 +285,9 @@ protected: const SymbolRef sym; public: - SymbolicRegion(const SymbolRef s, const MemRegion* sreg) + SymbolicRegion(const SymbolRef s, const MemRegion* sreg) : SubRegion(sreg, SymbolicRegionKind), sym(s) {} - + SymbolRef getSymbol() const { return sym; } @@ -299,13 +299,13 @@ public: static void ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym, const MemRegion* superRegion); - + void dumpToStream(llvm::raw_ostream& os) const; - + static bool classof(const MemRegion* R) { return R->getKind() == SymbolicRegionKind; } -}; +}; /// StringRegion - Region associated with a StringLiteral. class StringRegion : public TypedRegion { @@ -323,7 +323,7 @@ protected: public: const StringLiteral* getStringLiteral() const { return Str; } - + QualType getValueType(ASTContext& C) const { return Str->getType(); } @@ -351,7 +351,7 @@ private: CompoundLiteralRegion(const CompoundLiteralExpr* cl, const MemRegion* sReg) : TypedRegion(sReg, CompoundLiteralRegionKind), CL(cl) {} - + static void ProfileRegion(llvm::FoldingSetNodeID& ID, const CompoundLiteralExpr* CL, const MemRegion* superRegion); @@ -363,11 +363,11 @@ public: bool isBoundable() const { return !CL->isFileScope(); } void Profile(llvm::FoldingSetNodeID& ID) const; - + void dumpToStream(llvm::raw_ostream& os) const; const CompoundLiteralExpr* getLiteralExpr() const { return CL; } - + static bool classof(const MemRegion* R) { return R->getKind() == CompoundLiteralRegionKind; } @@ -382,23 +382,23 @@ protected: static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl* D, const MemRegion* superRegion, Kind k); - + public: const Decl* getDecl() const { return D; } void Profile(llvm::FoldingSetNodeID& ID) const; - + static bool classof(const MemRegion* R) { unsigned k = R->getKind(); return k > BEG_DECL_REGIONS && k < END_DECL_REGIONS; } }; - + class VarRegion : public DeclRegion { friend class MemRegionManager; // Data. const LocationContext *LC; - + // Constructors and private methods. VarRegion(const VarDecl* vd, const LocationContext *lC, const MemRegion* sReg) : DeclRegion(vd, sReg, VarRegionKind), LC(lC) {} @@ -409,24 +409,24 @@ class VarRegion : public DeclRegion { DeclRegion::ProfileRegion(ID, VD, superRegion, VarRegionKind); ID.AddPointer(LC); } - + void Profile(llvm::FoldingSetNodeID& ID) const; - -public: + +public: const VarDecl *getDecl() const { return cast(D); } - + const LocationContext *getLocationContext() const { return LC; } - - QualType getValueType(ASTContext& C) const { + + QualType getValueType(ASTContext& C) const { // FIXME: We can cache this if needed. return C.getCanonicalType(getDecl()->getType()); - } - + } + void dumpToStream(llvm::raw_ostream& os) const; - + static bool classof(const MemRegion* R) { return R->getKind() == VarRegionKind; - } + } }; class FieldRegion : public DeclRegion { @@ -436,57 +436,57 @@ class FieldRegion : public DeclRegion { : DeclRegion(fd, sReg, FieldRegionKind) {} public: - + void dumpToStream(llvm::raw_ostream& os) const; - + const FieldDecl* getDecl() const { return cast(D); } - - QualType getValueType(ASTContext& C) const { + + QualType getValueType(ASTContext& C) const { // FIXME: We can cache this if needed. return C.getCanonicalType(getDecl()->getType()); - } + } static void ProfileRegion(llvm::FoldingSetNodeID& ID, const FieldDecl* FD, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, FD, superRegion, FieldRegionKind); } - + static bool classof(const MemRegion* R) { return R->getKind() == FieldRegionKind; } }; - + class ObjCObjectRegion : public DeclRegion { - + friend class MemRegionManager; - + ObjCObjectRegion(const ObjCInterfaceDecl* ivd, const MemRegion* sReg) : DeclRegion(ivd, sReg, ObjCObjectRegionKind) {} - + static void ProfileRegion(llvm::FoldingSetNodeID& ID, const ObjCInterfaceDecl* ivd, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCObjectRegionKind); } - + public: const ObjCInterfaceDecl* getInterface() const { return cast(D); } - + QualType getValueType(ASTContext& C) const { return C.getObjCInterfaceType(getInterface()); } - + static bool classof(const MemRegion* R) { return R->getKind() == ObjCObjectRegionKind; } -}; - +}; + class ObjCIvarRegion : public DeclRegion { - + friend class MemRegionManager; - + ObjCIvarRegion(const ObjCIvarDecl* ivd, const MemRegion* sReg) : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {} @@ -494,13 +494,13 @@ class ObjCIvarRegion : public DeclRegion { const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind); } - + public: const ObjCIvarDecl* getDecl() const { return cast(D); } QualType getValueType(ASTContext&) const { return getDecl()->getType(); } - + void dumpToStream(llvm::raw_ostream& os) const; - + static bool classof(const MemRegion* R) { return R->getKind() == ObjCIvarRegionKind; } @@ -519,7 +519,7 @@ class ElementRegion : public TypedRegion { cast(&Idx)->getValue().isSigned()) && "The index must be signed"); } - + static void ProfileRegion(llvm::FoldingSetNodeID& ID, QualType elementType, SVal Idx, const MemRegion* superRegion); @@ -530,13 +530,13 @@ public: QualType getValueType(ASTContext&) const { return ElementType; } - + QualType getElementType() const { return ElementType; } - + RegionRawOffset getAsRawOffset() const; - + void dumpToStream(llvm::raw_ostream& os) const; void Profile(llvm::FoldingSetNodeID& ID) const; @@ -550,7 +550,7 @@ template const RegionTy* MemRegion::getAs() const { if (const RegionTy* RT = dyn_cast(this)) return RT; - + return NULL; } @@ -562,7 +562,7 @@ class MemRegionManager { ASTContext &C; llvm::BumpPtrAllocator& A; llvm::FoldingSet Regions; - + MemSpaceRegion *globals; MemSpaceRegion *stack; MemSpaceRegion *stackArguments; @@ -574,11 +574,11 @@ public: MemRegionManager(ASTContext &c, llvm::BumpPtrAllocator& a) : C(c), A(a), globals(0), stack(0), stackArguments(0), heap(0), unknown(0), code(0) {} - + ~MemRegionManager() {} - + ASTContext &getContext() { return C; } - + /// getStackRegion - Retrieve the memory region associated with the /// current stack frame. MemSpaceRegion *getStackRegion(); @@ -586,11 +586,11 @@ public: /// getStackArgumentsRegion - Retrieve the memory region associated with /// function/method arguments of the current stack frame. MemSpaceRegion *getStackArgumentsRegion(); - + /// getGlobalsRegion - Retrieve the memory region associated with /// all global variables. MemSpaceRegion *getGlobalsRegion(); - + /// getHeapRegion - Retrieve the memory region associated with the /// generic "heap". MemSpaceRegion *getHeapRegion(); @@ -603,12 +603,12 @@ public: /// getAllocaRegion - Retrieve a region associated with a call to alloca(). AllocaRegion *getAllocaRegion(const Expr* Ex, unsigned Cnt); - + /// getCompoundLiteralRegion - Retrieve the region associated with a /// given CompoundLiteral. CompoundLiteralRegion* - getCompoundLiteralRegion(const CompoundLiteralExpr* CL); - + getCompoundLiteralRegion(const CompoundLiteralExpr* CL); + /// getSymbolicRegion - Retrieve or create a "symbolic" memory region. SymbolicRegion* getSymbolicRegion(SymbolRef sym); @@ -617,13 +617,13 @@ public: /// getVarRegion - Retrieve or create the memory region associated with /// a specified VarDecl and LocationContext. VarRegion* getVarRegion(const VarDecl *D, const LocationContext *LC); - + /// getElementRegion - Retrieve the memory region associated with the /// associated element type, index, and super region. ElementRegion *getElementRegion(QualType elementType, SVal Idx, const MemRegion *superRegion, ASTContext &Ctx); - + ElementRegion *getElementRegionWithSuper(const ElementRegion *ER, const MemRegion *superRegion) { return getElementRegion(ER->getElementType(), ER->getIndex(), @@ -636,44 +636,44 @@ public: /// a structure or class). FieldRegion *getFieldRegion(const FieldDecl* fd, const MemRegion* superRegion); - + FieldRegion *getFieldRegionWithSuper(const FieldRegion *FR, const MemRegion *superRegion) { return getFieldRegion(FR->getDecl(), superRegion); } - + /// getObjCObjectRegion - Retrieve or create the memory region associated with /// the instance of a specified Objective-C class. ObjCObjectRegion* getObjCObjectRegion(const ObjCInterfaceDecl* ID, const MemRegion* superRegion); - + /// getObjCIvarRegion - Retrieve or create the memory region associated with /// a specified Objective-c instance variable. 'superRegion' corresponds /// to the containing region (which typically represents the Objective-C /// object). ObjCIvarRegion *getObjCIvarRegion(const ObjCIvarDecl* ivd, const MemRegion* superRegion); - + CodeTextRegion *getCodeTextRegion(const FunctionDecl *FD); - + template RegionTy* getRegion(const A1 a1); - + template RegionTy* getSubRegion(const A1 a1, const MemRegion* superRegion); - + template RegionTy* getRegion(const A1 a1, const A2 a2); - bool isGlobalsRegion(const MemRegion* R) { + bool isGlobalsRegion(const MemRegion* R) { assert(R); - return R == globals; + return R == globals; } - + private: MemSpaceRegion* LazyAllocate(MemSpaceRegion*& region); }; - + //===----------------------------------------------------------------------===// // Out-of-line member definitions. //===----------------------------------------------------------------------===// @@ -681,69 +681,69 @@ private: inline ASTContext& MemRegion::getContext() const { return getMemRegionManager()->getContext(); } - + template struct MemRegionManagerTrait; - + template RegionTy* MemRegionManager::getRegion(const A1 a1) { const typename MemRegionManagerTrait::SuperRegionTy *superRegion = MemRegionManagerTrait::getSuperRegion(*this, a1); - - llvm::FoldingSetNodeID ID; - RegionTy::ProfileRegion(ID, a1, superRegion); + + llvm::FoldingSetNodeID ID; + RegionTy::ProfileRegion(ID, a1, superRegion); void* InsertPos; RegionTy* R = cast_or_null(Regions.FindNodeOrInsertPos(ID, InsertPos)); - + if (!R) { R = (RegionTy*) A.Allocate(); new (R) RegionTy(a1, superRegion); Regions.InsertNode(R, InsertPos); } - + return R; } template RegionTy* MemRegionManager::getSubRegion(const A1 a1, const MemRegion *superRegion) { - llvm::FoldingSetNodeID ID; - RegionTy::ProfileRegion(ID, a1, superRegion); + llvm::FoldingSetNodeID ID; + RegionTy::ProfileRegion(ID, a1, superRegion); void* InsertPos; RegionTy* R = cast_or_null(Regions.FindNodeOrInsertPos(ID, InsertPos)); - + if (!R) { R = (RegionTy*) A.Allocate(); new (R) RegionTy(a1, superRegion); Regions.InsertNode(R, InsertPos); } - + return R; } - + template RegionTy* MemRegionManager::getRegion(const A1 a1, const A2 a2) { - + const typename MemRegionManagerTrait::SuperRegionTy *superRegion = MemRegionManagerTrait::getSuperRegion(*this, a1, a2); - - llvm::FoldingSetNodeID ID; - RegionTy::ProfileRegion(ID, a1, a2, superRegion); + + llvm::FoldingSetNodeID ID; + RegionTy::ProfileRegion(ID, a1, a2, superRegion); void* InsertPos; RegionTy* R = cast_or_null(Regions.FindNodeOrInsertPos(ID, InsertPos)); - + if (!R) { R = (RegionTy*) A.Allocate(); new (R) RegionTy(a1, a2, superRegion); Regions.InsertNode(R, InsertPos); } - + return R; } - + //===----------------------------------------------------------------------===// // Traits for constructing regions. //===----------------------------------------------------------------------===// @@ -754,18 +754,18 @@ template <> struct MemRegionManagerTrait { const Expr *, unsigned) { return MRMgr.getStackRegion(); } -}; - +}; + template <> struct MemRegionManagerTrait { typedef MemRegion SuperRegionTy; static const SuperRegionTy* getSuperRegion(MemRegionManager& MRMgr, const CompoundLiteralExpr *CL) { - - return CL->isFileScope() ? MRMgr.getGlobalsRegion() + + return CL->isFileScope() ? MRMgr.getGlobalsRegion() : MRMgr.getStackRegion(); } }; - + template <> struct MemRegionManagerTrait { typedef MemSpaceRegion SuperRegionTy; static const SuperRegionTy* getSuperRegion(MemRegionManager& MRMgr, @@ -773,24 +773,24 @@ template <> struct MemRegionManagerTrait { return MRMgr.getGlobalsRegion(); } }; - + template <> struct MemRegionManagerTrait { typedef MemRegion SuperRegionTy; static const SuperRegionTy* getSuperRegion(MemRegionManager &MRMgr, const VarDecl *D, const LocationContext *LC) { - + // FIXME: Make stack regions have a location context? - + if (D->hasLocalStorage()) { return isa(D) || isa(D) ? MRMgr.getStackArgumentsRegion() : MRMgr.getStackRegion(); } - + return MRMgr.getGlobalsRegion(); } }; - + template <> struct MemRegionManagerTrait { typedef MemRegion SuperRegionTy; static const SuperRegionTy* getSuperRegion(MemRegionManager& MRMgr, @@ -810,7 +810,7 @@ template<> struct MemRegionManagerTrait { return MRMgr.getCodeRegion(); } }; - + } // end clang namespace //===----------------------------------------------------------------------===// @@ -819,7 +819,7 @@ template<> struct MemRegionManagerTrait { namespace llvm { static inline raw_ostream& operator<<(raw_ostream& os, - const clang::MemRegion* R) { + const clang::MemRegion* R) { R->dumpToStream(os); return os; } diff --git a/clang/include/clang/Analysis/PathSensitive/SVals.h b/clang/include/clang/Analysis/PathSensitive/SVals.h index 1dd690695e90d060e488de6ef3f250c7cefdb5d2..608364af5ec8382197f886fcf2f7bd1e8076a295 100644 --- a/clang/include/clang/Analysis/PathSensitive/SVals.h +++ b/clang/include/clang/Analysis/PathSensitive/SVals.h @@ -38,35 +38,35 @@ class TypedRegion; class MemRegionManager; class GRStateManager; class ValueManager; - + class SVal { public: enum BaseKind { UndefinedKind, UnknownKind, LocKind, NonLocKind }; enum { BaseBits = 2, BaseMask = 0x3 }; - + protected: void* Data; unsigned Kind; - + protected: SVal(const void* d, bool isLoc, unsigned ValKind) : Data(const_cast(d)), Kind((isLoc ? LocKind : NonLocKind) | (ValKind << BaseBits)) {} - + explicit SVal(BaseKind k, void* D = NULL) : Data(D), Kind(k) {} - + public: SVal() : Data(0), Kind(0) {} ~SVal() {}; - + /// BufferTy - A temporary buffer to hold a set of SVals. typedef llvm::SmallVector BufferTy; - + inline unsigned getRawKind() const { return Kind; } inline BaseKind getBaseKind() const { return (BaseKind) (Kind & BaseMask); } inline unsigned getSubKind() const { return (Kind & ~BaseMask) >> BaseBits; } - + inline void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned) getRawKind()); ID.AddPointer(reinterpret_cast(Data)); @@ -75,7 +75,7 @@ public: inline bool operator==(const SVal& R) const { return getRawKind() == R.getRawKind() && Data == R.Data; } - + inline bool operator!=(const SVal& R) const { return !(*this == R); } @@ -91,25 +91,25 @@ public: inline bool isUnknownOrUndef() const { return getRawKind() <= UnknownKind; } - + inline bool isValid() const { return getRawKind() > UnknownKind; } - + bool isZeroConstant() const; /// hasConjuredSymbol - If this SVal wraps a conjured symbol, return true; bool hasConjuredSymbol() const; /// getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a - /// CodeTextRegion wrapping a FunctionDecl, return that FunctionDecl. + /// CodeTextRegion wrapping a FunctionDecl, return that FunctionDecl. /// Otherwise return 0. const FunctionDecl* getAsFunctionDecl() const; - - /// getAsLocSymbol - If this SVal is a location (subclasses Loc) and + + /// getAsLocSymbol - If this SVal is a location (subclasses Loc) and /// wraps a symbol, return that SymbolRef. Otherwise return a SymbolData* SymbolRef getAsLocSymbol() const; - + /// getAsSymbol - If this Sval wraps a symbol return that SymbolRef. /// Otherwise return a SymbolRef where 'isValid()' returns false. SymbolRef getAsSymbol() const; @@ -119,7 +119,7 @@ public: const SymExpr *getAsSymbolicExpression() const; const MemRegion *getAsRegion() const; - + void dumpToStream(llvm::raw_ostream& OS) const; void dump() const; @@ -130,14 +130,14 @@ public: public: symbol_iterator() {} symbol_iterator(const SymExpr* SE); - + symbol_iterator& operator++(); SymbolRef operator*(); - + bool operator==(const symbol_iterator& X) const; bool operator!=(const symbol_iterator& X) const; }; - + symbol_iterator symbol_begin() const { const SymExpr *SE = getAsSymbolicExpression(); if (SE) @@ -145,9 +145,9 @@ public: else return symbol_iterator(); } - + symbol_iterator symbol_end() const { return symbol_iterator(); } - + // Implement isa support. static inline bool classof(const SVal*) { return true; } }; @@ -155,24 +155,24 @@ public: class UnknownVal : public SVal { public: UnknownVal() : SVal(UnknownKind) {} - + static inline bool classof(const SVal* V) { return V->getBaseKind() == UnknownKind; - } + } }; class UndefinedVal : public SVal { public: UndefinedVal() : SVal(UndefinedKind) {} UndefinedVal(void* D) : SVal(UndefinedKind, D) {} - + static inline bool classof(const SVal* V) { return V->getBaseKind() == UndefinedKind; } - - void* getData() const { return Data; } + + void* getData() const { return Data; } }; - + class DefinedSVal : public SVal { protected: DefinedSVal(const void* d, bool isLoc, unsigned ValKind) @@ -181,16 +181,16 @@ public: // Implement isa support. static inline bool classof(const SVal *V) { return !V->isUnknownOrUndef(); - } + } }; class NonLoc : public DefinedSVal { protected: NonLoc(unsigned SubKind, const void* d) : DefinedSVal(d, false, SubKind) {} - + public: void dumpToStream(llvm::raw_ostream& Out) const; - + // Implement isa support. static inline bool classof(const SVal* V) { return V->getBaseKind() == NonLocKind; @@ -207,45 +207,45 @@ public: Loc(const Loc& X) : DefinedSVal(X.Data, true, X.getSubKind()) {} Loc& operator=(const Loc& X) { memcpy(this, &X, sizeof(Loc)); return *this; } - + // Implement isa support. static inline bool classof(const SVal* V) { return V->getBaseKind() == LocKind; } - + static inline bool IsLocType(QualType T) { return T->isAnyPointerType() || T->isBlockPointerType(); } }; - + //==------------------------------------------------------------------------==// // Subclasses of NonLoc. //==------------------------------------------------------------------------==// namespace nonloc { - + enum Kind { ConcreteIntKind, SymbolValKind, SymExprValKind, LocAsIntegerKind, CompoundValKind, LazyCompoundValKind }; class SymbolVal : public NonLoc { public: SymbolVal(SymbolRef sym) : NonLoc(SymbolValKind, sym) {} - + SymbolRef getSymbol() const { return (const SymbolData*) Data; } - + static inline bool classof(const SVal* V) { - return V->getBaseKind() == NonLocKind && + return V->getBaseKind() == NonLocKind && V->getSubKind() == SymbolValKind; } - + static inline bool classof(const NonLoc* V) { return V->getSubKind() == SymbolValKind; } }; -class SymExprVal : public NonLoc { +class SymExprVal : public NonLoc { public: SymExprVal(const SymExpr *SE) : NonLoc(SymExprValKind, reinterpret_cast(SE)) {} @@ -253,12 +253,12 @@ public: const SymExpr *getSymbolicExpression() const { return reinterpret_cast(Data); } - + static inline bool classof(const SVal* V) { return V->getBaseKind() == NonLocKind && V->getSubKind() == SymExprValKind; } - + static inline bool classof(const NonLoc* V) { return V->getSubKind() == SymExprValKind; } @@ -267,30 +267,30 @@ public: class ConcreteInt : public NonLoc { public: ConcreteInt(const llvm::APSInt& V) : NonLoc(ConcreteIntKind, &V) {} - + const llvm::APSInt& getValue() const { return *static_cast(Data); } - + // Transfer functions for binary/unary operations on ConcreteInts. SVal evalBinOp(ValueManager &ValMgr, BinaryOperator::Opcode Op, const ConcreteInt& R) const; - + ConcreteInt evalComplement(ValueManager &ValMgr) const; - + ConcreteInt evalMinus(ValueManager &ValMgr) const; - + // Implement isa support. static inline bool classof(const SVal* V) { return V->getBaseKind() == NonLocKind && V->getSubKind() == ConcreteIntKind; } - + static inline bool classof(const NonLoc* V) { return V->getSubKind() == ConcreteIntKind; } }; - + class LocAsInteger : public NonLoc { friend class clang::ValueManager; @@ -298,28 +298,28 @@ class LocAsInteger : public NonLoc { NonLoc(LocAsIntegerKind, &data) { assert (isa(data.first)); } - + public: - + Loc getLoc() const { return cast(((std::pair*) Data)->first); } - + const Loc& getPersistentLoc() const { const SVal& V = ((std::pair*) Data)->first; return cast(V); - } - + } + unsigned getNumBits() const { return ((std::pair*) Data)->second; } - + // Implement isa support. static inline bool classof(const SVal* V) { return V->getBaseKind() == NonLocKind && V->getSubKind() == LocAsIntegerKind; } - + static inline bool classof(const NonLoc* V) { return V->getSubKind() == LocAsIntegerKind; } @@ -334,10 +334,10 @@ public: const CompoundValData* getValue() const { return static_cast(Data); } - + typedef llvm::ImmutableList::iterator iterator; iterator begin() const; - iterator end() const; + iterator end() const; static bool classof(const SVal* V) { return V->getBaseKind() == NonLocKind && V->getSubKind() == CompoundValKind; @@ -347,7 +347,7 @@ public: return V->getSubKind() == CompoundValKind; } }; - + class LazyCompoundVal : public NonLoc { friend class clang::ValueManager; @@ -359,16 +359,16 @@ public: } const GRState *getState() const; const TypedRegion *getRegion() const; - + static bool classof(const SVal *V) { - return V->getBaseKind() == NonLocKind && + return V->getBaseKind() == NonLocKind && V->getSubKind() == LazyCompoundValKind; } static bool classof(const NonLoc *V) { return V->getSubKind() == LazyCompoundValKind; } }; - + } // end namespace clang::nonloc //==------------------------------------------------------------------------==// @@ -376,27 +376,27 @@ public: //==------------------------------------------------------------------------==// namespace loc { - + enum Kind { GotoLabelKind, MemRegionKind, ConcreteIntKind }; class GotoLabel : public Loc { public: GotoLabel(LabelStmt* Label) : Loc(GotoLabelKind, Label) {} - + LabelStmt* getLabel() const { return static_cast(Data); } - + static inline bool classof(const SVal* V) { return V->getBaseKind() == LocKind && V->getSubKind() == GotoLabelKind; } - + static inline bool classof(const Loc* V) { return V->getSubKind() == GotoLabelKind; - } + } }; - + class MemRegionVal : public Loc { public: @@ -405,37 +405,37 @@ public: const MemRegion* getRegion() const { return static_cast(Data); } - + const MemRegion* getBaseRegion() const; - + template const REGION* getRegionAs() const { return llvm::dyn_cast(getRegion()); - } - + } + inline bool operator==(const MemRegionVal& R) const { return getRegion() == R.getRegion(); } - + inline bool operator!=(const MemRegionVal& R) const { return getRegion() != R.getRegion(); } - + // Implement isa support. static inline bool classof(const SVal* V) { return V->getBaseKind() == LocKind && V->getSubKind() == MemRegionKind; } - + static inline bool classof(const Loc* V) { return V->getSubKind() == MemRegionKind; - } + } }; class ConcreteInt : public Loc { public: ConcreteInt(const llvm::APSInt& V) : Loc(ConcreteIntKind, &V) {} - + const llvm::APSInt& getValue() const { return *static_cast(Data); } @@ -443,20 +443,20 @@ public: // Transfer functions for binary/unary operations on ConcreteInts. SVal EvalBinOp(BasicValueFactory& BasicVals, BinaryOperator::Opcode Op, const ConcreteInt& R) const; - + // Implement isa support. static inline bool classof(const SVal* V) { return V->getBaseKind() == LocKind && V->getSubKind() == ConcreteIntKind; } - + static inline bool classof(const Loc* V) { return V->getSubKind() == ConcreteIntKind; } }; - + } // end clang::loc namespace -} // end clang namespace +} // end clang namespace namespace llvm { static inline llvm::raw_ostream& operator<<(llvm::raw_ostream& os, diff --git a/clang/include/clang/Analysis/PathSensitive/SValuator.h b/clang/include/clang/Analysis/PathSensitive/SValuator.h index 4635a9cd2a0d6c574cd36f216ab81249fc96ac58..b08d7ca64234025c52c8b29e12d80e1b60169fb9 100644 --- a/clang/include/clang/Analysis/PathSensitive/SValuator.h +++ b/clang/include/clang/Analysis/PathSensitive/SValuator.h @@ -9,7 +9,7 @@ // // This file defines SValuator, a class that defines the interface for // "symbolical evaluators" which construct an SVal from an expression. -// +// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_SVALUATOR @@ -28,14 +28,14 @@ class SValuator { protected: ValueManager &ValMgr; - virtual SVal EvalCastNL(NonLoc val, QualType castTy) = 0; - + virtual SVal EvalCastNL(NonLoc val, QualType castTy) = 0; + virtual SVal EvalCastL(Loc val, QualType castTy) = 0; public: SValuator(ValueManager &valMgr) : ValMgr(valMgr) {} virtual ~SValuator() {} - + class CastResult : public std::pair { public: const GRState *getState() const { return first; } @@ -43,12 +43,12 @@ public: CastResult(const GRState *s, SVal v) : std::pair(s, v) {} }; - + CastResult EvalCast(SVal val, const GRState *state, QualType castTy, QualType originalType); - + virtual SVal EvalMinus(NonLoc val) = 0; - + virtual SVal EvalComplement(NonLoc val) = 0; virtual SVal EvalBinOpNN(BinaryOperator::Opcode Op, NonLoc lhs, @@ -58,13 +58,13 @@ public: QualType resultTy) = 0; virtual SVal EvalBinOpLN(const GRState *state, BinaryOperator::Opcode Op, - Loc lhs, NonLoc rhs, QualType resultTy) = 0; - + Loc lhs, NonLoc rhs, QualType resultTy) = 0; + SVal EvalBinOp(const GRState *ST, BinaryOperator::Opcode Op, SVal L, SVal R, QualType T); }; - + SValuator* CreateSimpleSValuator(ValueManager &valMgr); - + } // end clang namespace #endif diff --git a/clang/include/clang/Analysis/PathSensitive/Store.h b/clang/include/clang/Analysis/PathSensitive/Store.h index 51143ec84b957eb17c9c5b038b47215dc81f8656..047bc6c68021d23f3beee868f5e0a92d250f6514 100644 --- a/clang/include/clang/Analysis/PathSensitive/Store.h +++ b/clang/include/clang/Analysis/PathSensitive/Store.h @@ -23,16 +23,16 @@ #include "llvm/ADT/SmallVector.h" namespace clang { - + typedef const void* Store; -class GRState; +class GRState; class GRStateManager; class Stmt; class Expr; class ObjCIvarDecl; class SubRegionMap; - + class StoreManager { protected: ValueManager &ValMgr; @@ -43,13 +43,13 @@ protected: StoreManager(GRStateManager &stateMgr); -public: +public: virtual ~StoreManager() {} - + /// Return the value bound to specified location in a given state. /// \param[in] state The analysis state. /// \param[in] loc The symbolic memory location. - /// \param[in] T An optional type that provides a hint indicating the + /// \param[in] T An optional type that provides a hint indicating the /// expected type of the returned value. This is used if the value is /// lazily computed. /// \return The value bound to the location \c loc. @@ -60,13 +60,13 @@ public: /// \param[in] state The analysis state. /// \param[in] loc The symbolic memory location. /// \param[in] val The value to bind to location \c loc. - /// \return A pointer to a GRState object that contains the same bindings as + /// \return A pointer to a GRState object that contains the same bindings as /// \c state with the addition of having the value specified by \c val bound /// to the location given for \c loc. virtual const GRState *Bind(const GRState *state, Loc loc, SVal val) = 0; virtual Store Remove(Store St, Loc L) = 0; - + /// BindCompoundLiteral - Return the store that has the bindings currently /// in 'store' plus the bindings for the CompoundLiteral. 'R' is the region /// for the compound literal and 'BegInit' and 'EndInit' represent an @@ -74,15 +74,15 @@ public: virtual const GRState *BindCompoundLiteral(const GRState *state, const CompoundLiteralExpr* cl, SVal v) = 0; - + /// getInitialStore - Returns the initial "empty" store representing the /// value bindings upon entry to an analyzed function. virtual Store getInitialStore(const LocationContext *InitLoc) = 0; - + /// getRegionManager - Returns the internal RegionManager object that is /// used to query and manipulate MemRegion objects. MemRegionManager& getRegionManager() { return MRMgr; } - + /// getSubRegionMap - Returns an opaque map object that clients can query /// to get the subregions of a given MemRegion object. It is the // caller's responsibility to 'delete' the returned map. @@ -96,13 +96,13 @@ public: virtual SVal getLValueCompoundLiteral(const GRState *state, const CompoundLiteralExpr* cl) = 0; - + virtual SVal getLValueIvar(const GRState *state, const ObjCIvarDecl* decl, SVal base) = 0; - + virtual SVal getLValueField(const GRState *state, SVal base, const FieldDecl* D) = 0; - + virtual SVal getLValueElement(const GRState *state, QualType elementType, SVal base, SVal offset) = 0; @@ -114,7 +114,7 @@ public: /// ArrayToPointer - Used by GRExprEngine::VistCast to handle implicit /// conversions between arrays and pointers. virtual SVal ArrayToPointer(Loc Array) = 0; - + class CastResult { const GRState *state; const MemRegion *region; @@ -123,19 +123,19 @@ public: const MemRegion* getRegion() const { return region; } CastResult(const GRState *s, const MemRegion* r = 0) : state(s), region(r){} }; - + /// CastRegion - Used by GRExprEngine::VisitCast to handle casts from /// a MemRegion* to a specific location type. 'R' is the region being /// casted and 'CastToTy' the result type of the cast. CastResult CastRegion(const GRState *state, const MemRegion *region, - QualType CastToTy); + QualType CastToTy); /// EvalBinOp - Perform pointer arithmetic. virtual SVal EvalBinOp(const GRState *state, BinaryOperator::Opcode Op, Loc lhs, NonLoc rhs, QualType resultTy) { return UnknownVal(); } - + virtual void RemoveDeadBindings(GRState &state, Stmt* Loc, SymbolReaper& SymReaper, llvm::SmallVectorImpl& RegionRoots) = 0; @@ -166,14 +166,14 @@ public: virtual void print(Store store, llvm::raw_ostream& Out, const char* nl, const char *sep) = 0; - + class BindingsHandler { - public: + public: virtual ~BindingsHandler(); virtual bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion *region, SVal val) = 0; }; - + /// iterBindings - Iterate over the bindings in the Store. virtual void iterBindings(Store store, BindingsHandler& f) = 0; @@ -181,12 +181,12 @@ protected: CastResult MakeElementRegion(const GRState *state, const MemRegion *region, QualType pointeeTy, QualType castToTy, uint64_t index = 0); - + /// CastRetrievedVal - Used by subclasses of StoreManager to implement /// implicit casts that arise from loads from regions that are reinterpreted /// as another region. SValuator::CastResult CastRetrievedVal(SVal val, const GRState *state, - const TypedRegion *R, QualType castTy); + const TypedRegion *R, QualType castTy); }; // FIXME: Do we still need this? @@ -195,14 +195,14 @@ protected: class SubRegionMap { public: virtual ~SubRegionMap() {} - + class Visitor { public: virtual ~Visitor() {}; virtual bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) = 0; }; - - virtual bool iterSubRegions(const MemRegion *region, Visitor& V) const = 0; + + virtual bool iterSubRegions(const MemRegion *region, Visitor& V) const = 0; }; // FIXME: Do we need to pass GRStateManager anymore? diff --git a/clang/include/clang/Analysis/PathSensitive/SymbolManager.h b/clang/include/clang/Analysis/PathSensitive/SymbolManager.h index 1a46e90b4194610edb36754b79b242c9fd2ccc34..d3996c6330a2a435a9a0882bc8e314a03f141ddd 100644 --- a/clang/include/clang/Analysis/PathSensitive/SymbolManager.h +++ b/clang/include/clang/Analysis/PathSensitive/SymbolManager.h @@ -27,7 +27,7 @@ namespace llvm { class raw_ostream; } -namespace clang { +namespace clang { class MemRegion; class TypedRegion; class ASTContext; @@ -35,7 +35,7 @@ namespace clang { } namespace clang { - + class SymExpr : public llvm::FoldingSetNode { public: enum Kind { BEGIN_SYMBOLS, @@ -46,47 +46,47 @@ private: Kind K; protected: - SymExpr(Kind k) : K(k) {} - + SymExpr(Kind k) : K(k) {} + public: virtual ~SymExpr() {} - - Kind getKind() const { return K; } - + + Kind getKind() const { return K; } + void dump() const; - + virtual void dumpToStream(llvm::raw_ostream &os) const = 0; - - virtual QualType getType(ASTContext&) const = 0; + + virtual QualType getType(ASTContext&) const = 0; virtual void Profile(llvm::FoldingSetNodeID& profile) = 0; - + // Implement isa support. static inline bool classof(const SymExpr*) { return true; } }; - + typedef unsigned SymbolID; - + class SymbolData : public SymExpr { private: const SymbolID Sym; - + protected: - SymbolData(Kind k, SymbolID sym) : SymExpr(k), Sym(sym) {} + SymbolData(Kind k, SymbolID sym) : SymExpr(k), Sym(sym) {} public: virtual ~SymbolData() {} - + SymbolID getSymbolID() const { return Sym; } // Implement isa support. - static inline bool classof(const SymExpr* SE) { + static inline bool classof(const SymExpr* SE) { Kind k = SE->getKind(); return k > BEGIN_SYMBOLS && k < END_SYMBOLS; } }; typedef const SymbolData* SymbolRef; - + class SymbolRegionValue : public SymbolData { const MemRegion *R; // We may cast the region to another type, so the expected type of the symbol @@ -96,7 +96,7 @@ class SymbolRegionValue : public SymbolData { public: SymbolRegionValue(SymbolID sym, const MemRegion *r, QualType t = QualType()) : SymbolData(RegionValueKind, sym), R(r), T(t) {} - + const MemRegion* getRegion() const { return R; } static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion* R, @@ -105,13 +105,13 @@ public: profile.AddPointer(R); T.Profile(profile); } - + virtual void Profile(llvm::FoldingSetNodeID& profile) { Profile(profile, R, T); } - + void dumpToStream(llvm::raw_ostream &os) const; - + QualType getType(ASTContext&) const; // Implement isa support. @@ -131,17 +131,17 @@ public: const void* symbolTag) : SymbolData(ConjuredKind, sym), S(s), T(t), Count(count), SymbolTag(symbolTag) {} - + const Stmt* getStmt() const { return S; } unsigned getCount() const { return Count; } const void* getTag() const { return SymbolTag; } - + QualType getType(ASTContext&) const; - + void dumpToStream(llvm::raw_ostream &os) const; - + static void Profile(llvm::FoldingSetNodeID& profile, const Stmt* S, - QualType T, unsigned Count, const void* SymbolTag) { + QualType T, unsigned Count, const void* SymbolTag) { profile.AddInteger((unsigned) ConjuredKind); profile.AddPointer(S); profile.Add(T); @@ -156,39 +156,39 @@ public: // Implement isa support. static inline bool classof(const SymExpr* SE) { return SE->getKind() == ConjuredKind; - } + } }; - + class SymbolDerived : public SymbolData { SymbolRef parentSymbol; const TypedRegion *R; - + public: SymbolDerived(SymbolID sym, SymbolRef parent, const TypedRegion *r) : SymbolData(DerivedKind, sym), parentSymbol(parent), R(r) {} SymbolRef getParentSymbol() const { return parentSymbol; } const TypedRegion *getRegion() const { return R; } - + QualType getType(ASTContext&) const; - + void dumpToStream(llvm::raw_ostream &os) const; - + static void Profile(llvm::FoldingSetNodeID& profile, SymbolRef parent, const TypedRegion *r) { profile.AddInteger((unsigned) DerivedKind); profile.AddPointer(r); profile.AddPointer(parent); } - + virtual void Profile(llvm::FoldingSetNodeID& profile) { Profile(profile, parentSymbol, R); } - + // Implement isa support. static inline bool classof(const SymExpr* SE) { return SE->getKind() == DerivedKind; - } + } }; // SymIntExpr - Represents symbolic expression like 'x' + 3. @@ -205,16 +205,16 @@ public: // FIXME: We probably need to make this out-of-line to avoid redundant // generation of virtual functions. - QualType getType(ASTContext& C) const { return T; } - + QualType getType(ASTContext& C) const { return T; } + BinaryOperator::Opcode getOpcode() const { return Op; } - - void dumpToStream(llvm::raw_ostream &os) const; - + + void dumpToStream(llvm::raw_ostream &os) const; + const SymExpr *getLHS() const { return LHS; } const llvm::APSInt &getRHS() const { return RHS; } - static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs, + static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t) { ID.AddInteger((unsigned) SymIntKind); @@ -227,11 +227,11 @@ public: void Profile(llvm::FoldingSetNodeID& ID) { Profile(ID, LHS, Op, RHS, T); } - + // Implement isa support. static inline bool classof(const SymExpr* SE) { return SE->getKind() == SymIntKind; - } + } }; // SymSymExpr - Represents symbolic expression like 'x' + 'y'. @@ -248,13 +248,13 @@ public: const SymExpr *getLHS() const { return LHS; } const SymExpr *getRHS() const { return RHS; } - + // FIXME: We probably need to make this out-of-line to avoid redundant // generation of virtual functions. QualType getType(ASTContext& C) const { return T; } - + void dumpToStream(llvm::raw_ostream &os) const; - + static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) { ID.AddInteger((unsigned) SymSymKind); @@ -267,48 +267,48 @@ public: void Profile(llvm::FoldingSetNodeID& ID) { Profile(ID, LHS, Op, RHS, T); } - + // Implement isa support. static inline bool classof(const SymExpr* SE) { return SE->getKind() == SymSymKind; - } + } }; class SymbolManager { typedef llvm::FoldingSet DataSetTy; - DataSetTy DataSet; + DataSetTy DataSet; unsigned SymbolCounter; llvm::BumpPtrAllocator& BPAlloc; BasicValueFactory &BV; ASTContext& Ctx; - + public: - SymbolManager(ASTContext& ctx, BasicValueFactory &bv, + SymbolManager(ASTContext& ctx, BasicValueFactory &bv, llvm::BumpPtrAllocator& bpalloc) : SymbolCounter(0), BPAlloc(bpalloc), BV(bv), Ctx(ctx) {} - + ~SymbolManager(); - + static bool canSymbolicate(QualType T); /// Make a unique symbol for MemRegion R according to its kind. - const SymbolRegionValue* getRegionValueSymbol(const MemRegion* R, + const SymbolRegionValue* getRegionValueSymbol(const MemRegion* R, QualType T = QualType()); const SymbolConjured* getConjuredSymbol(const Stmt* E, QualType T, unsigned VisitCount, const void* SymbolTag = 0); const SymbolConjured* getConjuredSymbol(const Expr* E, unsigned VisitCount, - const void* SymbolTag = 0) { + const void* SymbolTag = 0) { return getConjuredSymbol(E, E->getType(), VisitCount, SymbolTag); } - + const SymbolDerived *getDerivedSymbol(SymbolRef parentSymbol, const TypedRegion *R); const SymIntExpr *getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t); - + const SymIntExpr *getSymIntExpr(const SymExpr &lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t) { return getSymIntExpr(&lhs, op, rhs, t); @@ -316,27 +316,27 @@ public: const SymSymExpr *getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t); - + QualType getType(const SymExpr *SE) const { return SE->getType(Ctx); } - + ASTContext &getContext() { return Ctx; } BasicValueFactory &getBasicVals() { return BV; } }; - + class SymbolReaper { typedef llvm::DenseSet SetTy; - + SetTy TheLiving; SetTy TheDead; LiveVariables& Liveness; SymbolManager& SymMgr; - + public: SymbolReaper(LiveVariables& liveness, SymbolManager& symmgr) : Liveness(liveness), SymMgr(symmgr) {} - + ~SymbolReaper() {} bool isLive(SymbolRef sym); @@ -348,19 +348,19 @@ public: bool isLive(const Stmt* Loc, const VarDecl* VD) const { return Liveness.isLive(Loc, VD); } - + void markLive(SymbolRef sym); bool maybeDead(SymbolRef sym); - + typedef SetTy::const_iterator dead_iterator; dead_iterator dead_begin() const { return TheDead.begin(); } dead_iterator dead_end() const { return TheDead.end(); } - + bool hasDeadSymbols() const { return !TheDead.empty(); } }; - + class SymbolVisitor { public: // VisitSymbol - A visitor method invoked by @@ -369,7 +369,7 @@ public: virtual bool VisitSymbol(SymbolRef sym) = 0; virtual ~SymbolVisitor(); }; - + } // end clang namespace namespace llvm { diff --git a/clang/include/clang/Analysis/PathSensitive/ValueManager.h b/clang/include/clang/Analysis/PathSensitive/ValueManager.h index 8aa7a7711bdbc71234d77fd2cc19f7e8d301a5fb..0d9c5f7811606c28128c343062018fa4088ac013 100644 --- a/clang/include/clang/Analysis/PathSensitive/ValueManager.h +++ b/clang/include/clang/Analysis/PathSensitive/ValueManager.h @@ -25,15 +25,15 @@ namespace llvm { class BumpPtrAllocator; } -namespace clang { +namespace clang { class GRStateManager; - + class ValueManager { - ASTContext &Context; + ASTContext &Context; BasicValueFactory BasicVals; - + /// SymMgr - Object that manages the symbol information. SymbolManager SymMgr; @@ -41,12 +41,12 @@ class ValueManager { llvm::OwningPtr SVator; MemRegionManager MemMgr; - + GRStateManager &StateMgr; - + const QualType ArrayIndexTy; const unsigned ArrayIndexWidth; - + public: ValueManager(llvm::BumpPtrAllocator &alloc, ASTContext &context, GRStateManager &stateMgr) @@ -54,40 +54,39 @@ public: SymMgr(context, BasicVals, alloc), MemMgr(context, alloc), StateMgr(stateMgr), ArrayIndexTy(context.IntTy), - ArrayIndexWidth(context.getTypeSize(ArrayIndexTy)) - { + ArrayIndexWidth(context.getTypeSize(ArrayIndexTy)) { // FIXME: Generalize later. SVator.reset(clang::CreateSimpleSValuator(*this)); } // Accessors to submanagers. - + ASTContext &getContext() { return Context; } const ASTContext &getContext() const { return Context; } - + GRStateManager &getStateManager() { return StateMgr; } - + BasicValueFactory &getBasicValueFactory() { return BasicVals; } const BasicValueFactory &getBasicValueFactory() const { return BasicVals; } - + SymbolManager &getSymbolManager() { return SymMgr; } const SymbolManager &getSymbolManager() const { return SymMgr; } - + SValuator &getSValuator() { return *SVator.get(); } MemRegionManager &getRegionManager() { return MemMgr; } const MemRegionManager &getRegionManager() const { return MemMgr; } - + // Forwarding methods to SymbolManager. - + const SymbolConjured* getConjuredSymbol(const Stmt* E, QualType T, unsigned VisitCount, const void* SymbolTag = 0) { return SymMgr.getConjuredSymbol(E, T, VisitCount, SymbolTag); } - + const SymbolConjured* getConjuredSymbol(const Expr* E, unsigned VisitCount, - const void* SymbolTag = 0) { + const void* SymbolTag = 0) { return SymMgr.getConjuredSymbol(E, VisitCount, SymbolTag); } @@ -96,24 +95,24 @@ public: /// getRegionValueSymbolVal - make a unique symbol for value of R. SVal getRegionValueSymbolVal(const MemRegion *R, QualType T = QualType()); - + SVal getRegionValueSymbolValOrUnknown(const MemRegion *R, QualType T) { - return SymMgr.canSymbolicate(T) ? getRegionValueSymbolVal(R, T) - : UnknownVal(); + return SymMgr.canSymbolicate(T) ? getRegionValueSymbolVal(R, T) + : UnknownVal(); } - - SVal getConjuredSymbolVal(const Expr *E, unsigned Count); + + SVal getConjuredSymbolVal(const Expr *E, unsigned Count); SVal getConjuredSymbolVal(const Expr* E, QualType T, unsigned Count); SVal getDerivedRegionValueSymbolVal(SymbolRef parentSymbol, const TypedRegion *R); - + SVal getFunctionPointer(const FunctionDecl* FD); NonLoc makeCompoundVal(QualType T, llvm::ImmutableList Vals) { return nonloc::CompoundVal(BasicVals.getCompoundValData(T, Vals)); } - + NonLoc makeLazyCompoundVal(const GRState *state, const TypedRegion *R) { return nonloc::LazyCompoundVal(BasicVals.getLazyCompoundValData(state, R)); } @@ -121,11 +120,11 @@ public: NonLoc makeZeroArrayIndex() { return nonloc::ConcreteInt(BasicVals.getValue(0, ArrayIndexTy)); } - + NonLoc makeArrayIndex(uint64_t idx) { return nonloc::ConcreteInt(BasicVals.getValue(idx, ArrayIndexTy)); } - + SVal convertToArrayIndex(SVal V); nonloc::ConcreteInt makeIntVal(const IntegerLiteral* I) { @@ -136,7 +135,7 @@ public: nonloc::ConcreteInt makeIntVal(const llvm::APSInt& V) { return nonloc::ConcreteInt(BasicVals.getValue(V)); } - + loc::ConcreteInt makeIntLocVal(const llvm::APSInt &v) { return loc::ConcreteInt(BasicVals.getValue(v)); } @@ -170,10 +169,10 @@ public: NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType T); - + NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType T); - + NonLoc makeTruthVal(bool b, QualType T) { return nonloc::ConcreteInt(BasicVals.getTruthValue(b, T)); } diff --git a/clang/include/clang/Analysis/ProgramPoint.h b/clang/include/clang/Analysis/ProgramPoint.h index f2ff998fd86182fccba0990e90703f510fd4f3d7..666e45b847cf020bf6c71c3e50bf83cfa17b57ac 100644 --- a/clang/include/clang/Analysis/ProgramPoint.h +++ b/clang/include/clang/Analysis/ProgramPoint.h @@ -26,7 +26,7 @@ namespace clang { class LocationContext; - + class ProgramPoint { public: enum Kind { BlockEdgeKind, @@ -55,12 +55,12 @@ private: // context insensitive analysis. const LocationContext *L; const void *Tag; - + protected: - ProgramPoint(const void* P, Kind k, const LocationContext *l, + ProgramPoint(const void* P, Kind k, const LocationContext *l, const void *tag = 0) : Data(P, NULL), K(k), L(l), Tag(tag) {} - + ProgramPoint(const void* P1, const void* P2, Kind k, const LocationContext *l, const void *tag = 0) : Data(P1, P2), K(k), L(l), Tag(tag) {} @@ -69,8 +69,8 @@ protected: const void* getData1() const { return Data.first; } const void* getData2() const { return Data.second; } const void *getTag() const { return Tag; } - -public: + +public: Kind getKind() const { return K; } const LocationContext *getLocationContext() const { return L; } @@ -81,7 +81,7 @@ public: Profile(ID); return ID.ComputeHash(); } - + static bool classof(const ProgramPoint*) { return true; } bool operator==(const ProgramPoint & RHS) const { @@ -91,7 +91,7 @@ public: bool operator!=(const ProgramPoint& RHS) const { return K != RHS.K || Data != RHS.Data || L != RHS.L || Tag != RHS.Tag; } - + void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned) K); ID.AddPointer(Data.first); @@ -100,17 +100,17 @@ public: ID.AddPointer(Tag); } }; - + class BlockEntrance : public ProgramPoint { public: - BlockEntrance(const CFGBlock* B, const LocationContext *L, + BlockEntrance(const CFGBlock* B, const LocationContext *L, const void *tag = 0) : ProgramPoint(B, BlockEntranceKind, L, tag) {} - + CFGBlock* getBlock() const { return const_cast(reinterpret_cast(getData1())); } - + Stmt* getFirstStmt() const { const CFGBlock* B = getBlock(); return B->empty() ? NULL : B->front(); @@ -123,9 +123,9 @@ public: class BlockExit : public ProgramPoint { public: - BlockExit(const CFGBlock* B, const LocationContext *L) + BlockExit(const CFGBlock* B, const LocationContext *L) : ProgramPoint(B, BlockExitKind, L) {} - + CFGBlock* getBlock() const { return const_cast(reinterpret_cast(getData1())); } @@ -134,41 +134,41 @@ public: const CFGBlock* B = getBlock(); return B->empty() ? NULL : B->back(); } - + Stmt* getTerminator() const { return getBlock()->getTerminator(); } - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == BlockExitKind; } }; - + class StmtPoint : public ProgramPoint { public: - StmtPoint(const Stmt *S, const void *p2, Kind k, const LocationContext *L, + StmtPoint(const Stmt *S, const void *p2, Kind k, const LocationContext *L, const void *tag) : ProgramPoint(S, p2, k, L, tag) {} - + const Stmt *getStmt() const { return (const Stmt*) getData1(); } - + template const T* getStmtAs() const { return llvm::dyn_cast(getStmt()); } - + static bool classof(const ProgramPoint* Location) { unsigned k = Location->getKind(); return k >= PreStmtKind && k <= MaxPostStmtKind; } -}; +}; + - class PreStmt : public StmtPoint { public: - PreStmt(const Stmt *S, const LocationContext *L, const void *tag, + PreStmt(const Stmt *S, const LocationContext *L, const void *tag, const Stmt *SubStmt = 0) : StmtPoint(S, SubStmt, PreStmtKind, L, tag) {} - const Stmt *getSubStmt() const { return (const Stmt*) getData2(); } + const Stmt *getSubStmt() const { return (const Stmt*) getData2(); } static bool classof(const ProgramPoint* Location) { return Location->getKind() == PreStmtKind; @@ -183,7 +183,7 @@ protected: PostStmt(const Stmt* S, const void* data, Kind k, const LocationContext *L, const void *tag =0) : StmtPoint(S, data, k, L, tag) {} - + public: explicit PostStmt(const Stmt* S, const LocationContext *L,const void *tag = 0) : StmtPoint(S, NULL, PostStmtKind, L, tag) {} @@ -196,15 +196,15 @@ public: class PostLocationChecksSucceed : public PostStmt { public: - PostLocationChecksSucceed(const Stmt* S, const LocationContext *L, + PostLocationChecksSucceed(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostLocationChecksSucceedKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostLocationChecksSucceedKind; } }; - + class PostStmtCustom : public PostStmt { public: PostStmtCustom(const Stmt* S, @@ -216,22 +216,22 @@ public: return *reinterpret_cast*>(getData2()); } - + const void* getTag() const { return getTaggedPair().first; } - + const void* getTaggedData() const { return getTaggedPair().second; } - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostStmtCustomKind; } }; - + class PostOutOfBoundsCheckFailed : public PostStmt { public: - PostOutOfBoundsCheckFailed(const Stmt* S, const LocationContext *L, + PostOutOfBoundsCheckFailed(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostOutOfBoundsCheckFailedKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostOutOfBoundsCheckFailedKind; } @@ -242,38 +242,38 @@ public: PostUndefLocationCheckFailed(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostUndefLocationCheckFailedKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostUndefLocationCheckFailedKind; } }; - + class PostNullCheckFailed : public PostStmt { public: PostNullCheckFailed(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostNullCheckFailedKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostNullCheckFailedKind; } }; - + class PostLoad : public PostStmt { public: PostLoad(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostLoadKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostLoadKind; } }; - + class PostStore : public PostStmt { public: PostStore(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostStoreKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostStoreKind; } @@ -283,52 +283,52 @@ class PostLValue : public PostStmt { public: PostLValue(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostLValueKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostLValueKind; } -}; - +}; + class PostPurgeDeadSymbols : public PostStmt { public: - PostPurgeDeadSymbols(const Stmt* S, const LocationContext *L, + PostPurgeDeadSymbols(const Stmt* S, const LocationContext *L, const void *tag = 0) : PostStmt(S, PostPurgeDeadSymbolsKind, L, tag) {} - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostPurgeDeadSymbolsKind; } }; - + class BlockEdge : public ProgramPoint { public: BlockEdge(const CFGBlock* B1, const CFGBlock* B2, const LocationContext *L) : ProgramPoint(B1, B2, BlockEdgeKind, L) {} - + CFGBlock* getSrc() const { return const_cast(static_cast(getData1())); } - + CFGBlock* getDst() const { return const_cast(static_cast(getData2())); } - + static bool classof(const ProgramPoint* Location) { return Location->getKind() == BlockEdgeKind; } }; - + } // end namespace clang -namespace llvm { // Traits specialization for DenseMap - +namespace llvm { // Traits specialization for DenseMap + template <> struct DenseMapInfo { static inline clang::ProgramPoint getEmptyKey() { uintptr_t x = - reinterpret_cast(DenseMapInfo::getEmptyKey()) & ~0x7; + reinterpret_cast(DenseMapInfo::getEmptyKey()) & ~0x7; return clang::BlockEntrance(reinterpret_cast(x), 0); } diff --git a/clang/include/clang/Analysis/Support/BlkExprDeclBitVector.h b/clang/include/clang/Analysis/Support/BlkExprDeclBitVector.h index 7944c8e682f1b60ac6ed406b45958cd6dfb8d37c..27ecc66e66e3bd313e2cabcda795048cd3682f84 100644 --- a/clang/include/clang/Analysis/Support/BlkExprDeclBitVector.h +++ b/clang/include/clang/Analysis/Support/BlkExprDeclBitVector.h @@ -23,18 +23,18 @@ #include "llvm/ADT/DenseMap.h" namespace clang { - + class Stmt; class ASTContext; struct DeclBitVector_Types { - + class Idx { unsigned I; public: explicit Idx(unsigned i) : I(i) {} Idx() : I(~0U) {} - + bool isValid() const { return I != ~0U; } @@ -42,35 +42,35 @@ struct DeclBitVector_Types { assert (isValid()); return I; } - }; - + }; + //===--------------------------------------------------------------------===// // AnalysisDataTy - Whole-function meta data. //===--------------------------------------------------------------------===// - + class AnalysisDataTy { public: typedef llvm::DenseMap DMapTy; typedef DMapTy::const_iterator decl_iterator; - + protected: - DMapTy DMap; + DMapTy DMap; unsigned NDecls; - + public: - + AnalysisDataTy() : NDecls(0) {} virtual ~AnalysisDataTy() {} - + bool isTracked(const NamedDecl* SD) { return DMap.find(SD) != DMap.end(); } - + Idx getIdx(const NamedDecl* SD) const { DMapTy::const_iterator I = DMap.find(SD); return I == DMap.end() ? Idx() : Idx(I->second); } unsigned getNumDecls() const { return NDecls; } - + void Register(const NamedDecl* SD) { if (!isTracked(SD)) DMap[SD] = NDecls++; } @@ -78,44 +78,44 @@ struct DeclBitVector_Types { decl_iterator begin_decl() const { return DMap.begin(); } decl_iterator end_decl() const { return DMap.end(); } }; - + //===--------------------------------------------------------------------===// // ValTy - Dataflow value. //===--------------------------------------------------------------------===// - + class ValTy { llvm::BitVector DeclBV; public: - + void resetDeclValues(AnalysisDataTy& AD) { - DeclBV.resize(AD.getNumDecls()); + DeclBV.resize(AD.getNumDecls()); DeclBV.reset(); } void setDeclValues(AnalysisDataTy& AD) { - DeclBV.resize(AD.getNumDecls()); + DeclBV.resize(AD.getNumDecls()); DeclBV.set(); } - + void resetValues(AnalysisDataTy& AD) { resetDeclValues(AD); - } - - bool operator==(const ValTy& RHS) const { + } + + bool operator==(const ValTy& RHS) const { assert (sizesEqual(RHS)); return DeclBV == RHS.DeclBV; } - + void copyValues(const ValTy& RHS) { DeclBV = RHS.DeclBV; } - + llvm::BitVector::reference getBit(unsigned i) { return DeclBV[i]; } - + bool getBit(unsigned i) const { return DeclBV[i]; } - + llvm::BitVector::reference operator()(const NamedDecl* ND, const AnalysisDataTy& AD) { return getBit(AD.getIdx(ND)); @@ -124,48 +124,48 @@ struct DeclBitVector_Types { bool operator()(const NamedDecl* ND, const AnalysisDataTy& AD) const { return getBit(AD.getIdx(ND)); } - - llvm::BitVector::reference getDeclBit(unsigned i) { return DeclBV[i]; } + + llvm::BitVector::reference getDeclBit(unsigned i) { return DeclBV[i]; } const llvm::BitVector::reference getDeclBit(unsigned i) const { return const_cast(DeclBV)[i]; } - + ValTy& operator|=(const ValTy& RHS) { assert (sizesEqual(RHS)); DeclBV |= RHS.DeclBV; return *this; } - + ValTy& operator&=(const ValTy& RHS) { assert (sizesEqual(RHS)); DeclBV &= RHS.DeclBV; return *this; } - + ValTy& OrDeclBits(const ValTy& RHS) { return operator|=(RHS); } - + ValTy& AndDeclBits(const ValTy& RHS) { return operator&=(RHS); } - + bool sizesEqual(const ValTy& RHS) const { return DeclBV.size() == RHS.DeclBV.size(); } }; - + //===--------------------------------------------------------------------===// // Some useful merge operations. //===--------------------------------------------------------------------===// - + struct Union { void operator()(ValTy& Dst, ValTy& Src) { Dst |= Src; } }; struct Intersect { void operator()(ValTy& Dst, ValTy& Src) { Dst &= Src; } }; }; struct StmtDeclBitVector_Types { - + //===--------------------------------------------------------------------===// // AnalysisDataTy - Whole-function meta data. //===--------------------------------------------------------------------===// @@ -179,13 +179,13 @@ struct StmtDeclBitVector_Types { void setContext(ASTContext& c) { ctx = &c; } ASTContext& getContext() { - assert(ctx && "ASTContext should not be NULL."); + assert(ctx && "ASTContext should not be NULL."); return *ctx; } void setCFG(CFG& c) { cfg = &c; } CFG& getCFG() { assert(cfg && "CFG should not be NULL."); return *cfg; } - + bool isTracked(const Stmt* S) { return cfg->isBlkExpr(S); } using DeclBitVector_Types::AnalysisDataTy::isTracked; @@ -195,7 +195,7 @@ struct StmtDeclBitVector_Types { return I; } using DeclBitVector_Types::AnalysisDataTy::getIdx; - + unsigned getNumBlkExprs() const { return cfg->getNumBlkExprs(); } }; @@ -206,101 +206,101 @@ struct StmtDeclBitVector_Types { class ValTy : public DeclBitVector_Types::ValTy { llvm::BitVector BlkExprBV; typedef DeclBitVector_Types::ValTy ParentTy; - + static inline ParentTy& ParentRef(ValTy& X) { return static_cast(X); } - + static inline const ParentTy& ParentRef(const ValTy& X) { return static_cast(X); } - + public: void resetBlkExprValues(AnalysisDataTy& AD) { BlkExprBV.resize(AD.getNumBlkExprs()); BlkExprBV.reset(); } - + void setBlkExprValues(AnalysisDataTy& AD) { BlkExprBV.resize(AD.getNumBlkExprs()); BlkExprBV.set(); } - + void resetValues(AnalysisDataTy& AD) { resetDeclValues(AD); resetBlkExprValues(AD); } - + void setValues(AnalysisDataTy& AD) { setDeclValues(AD); setBlkExprValues(AD); } - - bool operator==(const ValTy& RHS) const { - return ParentRef(*this) == ParentRef(RHS) + + bool operator==(const ValTy& RHS) const { + return ParentRef(*this) == ParentRef(RHS) && BlkExprBV == RHS.BlkExprBV; } - + void copyValues(const ValTy& RHS) { ParentRef(*this).copyValues(ParentRef(RHS)); BlkExprBV = RHS.BlkExprBV; } - + llvm::BitVector::reference operator()(const Stmt* S, const AnalysisDataTy& AD) { - return BlkExprBV[AD.getIdx(S)]; - } + return BlkExprBV[AD.getIdx(S)]; + } const llvm::BitVector::reference operator()(const Stmt* S, const AnalysisDataTy& AD) const { return const_cast(*this)(S,AD); } - + using DeclBitVector_Types::ValTy::operator(); - - llvm::BitVector::reference getStmtBit(unsigned i) { return BlkExprBV[i]; } + + llvm::BitVector::reference getStmtBit(unsigned i) { return BlkExprBV[i]; } const llvm::BitVector::reference getStmtBit(unsigned i) const { return const_cast(BlkExprBV)[i]; } - + ValTy& OrBlkExprBits(const ValTy& RHS) { BlkExprBV |= RHS.BlkExprBV; return *this; } - + ValTy& AndBlkExprBits(const ValTy& RHS) { BlkExprBV &= RHS.BlkExprBV; return *this; } - + ValTy& operator|=(const ValTy& RHS) { assert (sizesEqual(RHS)); ParentRef(*this) |= ParentRef(RHS); BlkExprBV |= RHS.BlkExprBV; return *this; } - + ValTy& operator&=(const ValTy& RHS) { assert (sizesEqual(RHS)); ParentRef(*this) &= ParentRef(RHS); BlkExprBV &= RHS.BlkExprBV; return *this; } - + bool sizesEqual(const ValTy& RHS) const { return ParentRef(*this).sizesEqual(ParentRef(RHS)) && BlkExprBV.size() == RHS.BlkExprBV.size(); } }; - + //===--------------------------------------------------------------------===// // Some useful merge operations. //===--------------------------------------------------------------------===// - + struct Union { void operator()(ValTy& Dst, ValTy& Src) { Dst |= Src; } }; struct Intersect { void operator()(ValTy& Dst, ValTy& Src) { Dst &= Src; } }; - + }; } // end namespace clang diff --git a/clang/include/clang/Analysis/Support/Optional.h b/clang/include/clang/Analysis/Support/Optional.h index 5fb5078f7652ca6938337291b26d41b878fe881b..3940007bb574f33f4143f5c329c256ccc7e32a85 100644 --- a/clang/include/clang/Analysis/Support/Optional.h +++ b/clang/include/clang/Analysis/Support/Optional.h @@ -17,7 +17,7 @@ #define LLVM_CLANG_ANALYSIS_OPTIONAL namespace clang { - + template class Optional { const T x; @@ -25,15 +25,15 @@ class Optional { public: explicit Optional() : hasVal(false) {} Optional(const T &y) : x(y), hasVal(true) {} - + static inline Optional create(const T* y) { return y ? Optional(*y) : Optional(); } - + const T* getPointer() const { assert(hasVal); return &x; } - + operator bool() const { return hasVal; } - const T* operator->() const { return getPointer(); } + const T* operator->() const { return getPointer(); } const T& operator*() const { assert(hasVal); return x; } }; } //end clang namespace @@ -46,7 +46,7 @@ struct simplify_type > { return Val.getPointer(); } }; - + template struct simplify_type< ::clang::Optional > : public simplify_type > {}; diff --git a/clang/include/clang/Analysis/Support/SaveAndRestore.h b/clang/include/clang/Analysis/Support/SaveAndRestore.h index f597fcba57b3c2536e312c23f1fc7bb04b948a01..4720c22d990efa83a47bdd0f6ddce52ffc725105 100644 --- a/clang/include/clang/Analysis/Support/SaveAndRestore.h +++ b/clang/include/clang/Analysis/Support/SaveAndRestore.h @@ -16,7 +16,7 @@ #define LLVM_CLANG_ANALYSIS_SAVERESTORE namespace clang { - + // SaveAndRestore - A utility class that uses RAII to save and restore // the value of a variable. template @@ -24,7 +24,7 @@ struct SaveAndRestore { SaveAndRestore(T& x) : X(x), old_value(x) {} ~SaveAndRestore() { X = old_value; } T get() { return old_value; } -private: +private: T& X; T old_value; }; @@ -39,6 +39,6 @@ private: bool& X; const bool old_value; }; - + } #endif diff --git a/clang/include/clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h b/clang/include/clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h index ee79c517030f94bda11083d742bd5bae3e38daa8..3826d3a3acd6e4c0a189ff99ca3597ad46ef16e1 100644 --- a/clang/include/clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h +++ b/clang/include/clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h @@ -30,28 +30,28 @@ break; #define DEFAULT_DISPATCH_VARDECL(CLASS) void Visit##CLASS(CLASS* D)\ { static_cast(this)->VisitVarDecl(D); } - + namespace clang { template class CFGRecStmtDeclVisitor : public CFGRecStmtVisitor { -public: +public: void VisitDeclRefExpr(DeclRefExpr* DR) { - static_cast(this)->VisitDecl(DR->getDecl()); + static_cast(this)->VisitDecl(DR->getDecl()); } - + void VisitDeclStmt(DeclStmt* DS) { for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { Decl* D = *DI; - static_cast(this)->VisitDecl(D); + static_cast(this)->VisitDecl(D); // Visit the initializer. if (VarDecl* VD = dyn_cast(D)) if (Expr* I = VD->getInit()) static_cast(this)->Visit(I); } } - + void VisitDecl(Decl* D) { switch (D->getKind()) { DISPATCH_CASE(Function,FunctionDecl) @@ -67,7 +67,7 @@ public: assert(false && "Subtype of ScopedDecl not handled."); } } - + DEFAULT_DISPATCH(VarDecl) DEFAULT_DISPATCH(FunctionDecl) DEFAULT_DISPATCH_VARDECL(OriginalParmVarDecl) diff --git a/clang/include/clang/Analysis/Visitors/CFGRecStmtVisitor.h b/clang/include/clang/Analysis/Visitors/CFGRecStmtVisitor.h index 4d3201962250d35e0038a46d980088e29526f17c..83700a3a346d9e420ccdb313dd34adc119db538a 100644 --- a/clang/include/clang/Analysis/Visitors/CFGRecStmtVisitor.h +++ b/clang/include/clang/Analysis/Visitors/CFGRecStmtVisitor.h @@ -20,12 +20,12 @@ namespace clang { template class CFGRecStmtVisitor : public CFGStmtVisitor { -public: +public: void VisitStmt(Stmt* S) { static_cast< ImplClass* >(this)->VisitChildren(S); } - + // Defining operator() allows the visitor to be used as a C++ style functor. void operator()(Stmt* S) { static_cast(this)->BlockStmt_Visit(S);} }; diff --git a/clang/include/clang/Analysis/Visitors/CFGStmtVisitor.h b/clang/include/clang/Analysis/Visitors/CFGStmtVisitor.h index 7456831a6a0787202f9337ed8530fac1492f31e8..426b9ccd8a23a0db03ccd4db4e2452aafe65d34e 100644 --- a/clang/include/clang/Analysis/Visitors/CFGStmtVisitor.h +++ b/clang/include/clang/Analysis/Visitors/CFGStmtVisitor.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines the CFGStmtVisitor interface, which extends +// This file defines the CFGStmtVisitor interface, which extends // StmtVisitor. This interface is useful for visiting statements in a CFG // where some statements have implicit control-flow and thus should // be treated specially. @@ -24,7 +24,7 @@ namespace clang { #define DISPATCH_CASE(CLASS) \ case Stmt::CLASS ## Class: return \ -static_cast(this)->BlockStmt_Visit ## CLASS(static_cast(S)); +static_cast(this)->BlockStmt_Visit ## CLASS(static_cast(S)); #define DEFAULT_BLOCKSTMT_VISIT(CLASS) RetTy BlockStmt_Visit ## CLASS(CLASS *S)\ { return\ @@ -36,40 +36,40 @@ class CFGStmtVisitor : public StmtVisitor { Stmt* CurrentBlkStmt; struct NullifyStmt { - Stmt*& S; - + Stmt*& S; + NullifyStmt(Stmt*& s) : S(s) {} ~NullifyStmt() { S = NULL; } }; - + public: - CFGStmtVisitor() : CurrentBlkStmt(NULL) {} - + CFGStmtVisitor() : CurrentBlkStmt(NULL) {} + Stmt* getCurrentBlkStmt() const { return CurrentBlkStmt; } - + RetTy Visit(Stmt* S) { - if (S == CurrentBlkStmt || + if (S == CurrentBlkStmt || !static_cast(this)->getCFG().isBlkExpr(S)) return StmtVisitor::Visit(S); else return RetTy(); } - + /// BlockVisit_XXX - Visitor methods for visiting the "root" statements in - /// CFGBlocks. Root statements are the statements that appear explicitly in + /// CFGBlocks. Root statements are the statements that appear explicitly in /// the list of statements in a CFGBlock. For substatements, or when there /// is no implementation provided for a BlockStmt_XXX method, we default /// to using StmtVisitor's Visit method. RetTy BlockStmt_Visit(Stmt* S) { CurrentBlkStmt = S; NullifyStmt cleanup(CurrentBlkStmt); - + switch (S->getStmtClass()) { DISPATCH_CASE(StmtExpr) DISPATCH_CASE(ConditionalOperator) DISPATCH_CASE(ObjCForCollectionStmt) - + case Stmt::BinaryOperatorClass: { BinaryOperator* B = cast(S); if (B->isLogicalOp()) @@ -78,40 +78,40 @@ public: return static_cast(this)->BlockStmt_VisitComma(B); // Fall through. } - + default: if (isa(S)) - return + return static_cast(this)->BlockStmt_VisitExpr(cast(S)); else - return static_cast(this)->BlockStmt_VisitStmt(S); + return static_cast(this)->BlockStmt_VisitStmt(S); } } DEFAULT_BLOCKSTMT_VISIT(StmtExpr) DEFAULT_BLOCKSTMT_VISIT(ConditionalOperator) - + RetTy BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { return static_cast(this)->BlockStmt_VisitStmt(S); } - + RetTy BlockStmt_VisitImplicitControlFlowExpr(Expr* E) { return static_cast(this)->BlockStmt_VisitExpr(E); } - + RetTy BlockStmt_VisitExpr(Expr* E) { return static_cast(this)->BlockStmt_VisitStmt(E); } - + RetTy BlockStmt_VisitStmt(Stmt* S) { return static_cast(this)->Visit(S); } RetTy BlockStmt_VisitLogicalOp(BinaryOperator* B) { - return + return static_cast(this)->BlockStmt_VisitImplicitControlFlowExpr(B); } - + RetTy BlockStmt_VisitComma(BinaryOperator* B) { return static_cast(this)->BlockStmt_VisitImplicitControlFlowExpr(B); @@ -120,21 +120,21 @@ public: //===--------------------------------------------------------------------===// // Utility methods. Not called by default (but subclasses may use them). //===--------------------------------------------------------------------===// - + /// VisitChildren: Call "Visit" on each child of S. void VisitChildren(Stmt* S) { - + switch (S->getStmtClass()) { default: break; - + case Stmt::StmtExprClass: { CompoundStmt* CS = cast(S)->getSubStmt(); if (CS->body_empty()) return; static_cast(this)->Visit(CS->body_back()); return; } - + case Stmt::BinaryOperatorClass: { BinaryOperator* B = cast(S); if (B->getOpcode() != BinaryOperator::Comma) break; @@ -142,12 +142,12 @@ public: return; } } - + for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I != E;++I) - if (*I) static_cast(this)->Visit(*I); + if (*I) static_cast(this)->Visit(*I); } -}; - +}; + #undef DEFAULT_BLOCKSTMT_VISIT #undef DISPATCH_CASE diff --git a/clang/include/clang/Analysis/Visitors/CFGVarDeclVisitor.h b/clang/include/clang/Analysis/Visitors/CFGVarDeclVisitor.h index 8c5cf0b0b60955f1efa29fb4aa366b898769b672..1bc798f4e79e1ac176ecbd8b2fc0ab4bd5fef47e 100644 --- a/clang/include/clang/Analysis/Visitors/CFGVarDeclVisitor.h +++ b/clang/include/clang/Analysis/Visitors/CFGVarDeclVisitor.h @@ -24,37 +24,37 @@ namespace clang { template class CFGVarDeclVisitor : public CFGStmtVisitor { const CFG& cfg; -public: +public: CFGVarDeclVisitor(const CFG& c) : cfg(c) {} - + void VisitStmt(Stmt* S) { static_cast(this)->VisitChildren(S); } - + void VisitDeclRefExpr(DeclRefExpr* DR) { static_cast(this)->VisitDeclChain(DR->getDecl()); } - + void VisitDeclStmt(DeclStmt* DS) { static_cast(this)->VisitDeclChain(DS->getDecl()); } - - void VisitDeclChain(ScopedDecl* D) { + + void VisitDeclChain(ScopedDecl* D) { for (; D != NULL ; D = D->getNextDeclarator()) static_cast(this)->VisitScopedDecl(D); } - + void VisitScopedDecl(ScopedDecl* D) { if (VarDecl* V = dyn_cast(D)) static_cast(this)->VisitVarDecl(V); } - + void VisitVarDecl(VarDecl* D) {} - + void VisitAllDecls() { for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) for (CFGBlock::const_iterator SI=BI->begin(),SE = BI->end();SI != SE;++SI) - static_cast(this)->BlockStmt_Visit(const_cast(*SI)); + static_cast(this)->BlockStmt_Visit(const_cast(*SI)); } }; diff --git a/clang/include/clang/Basic/Builtins.h b/clang/include/clang/Basic/Builtins.h index cd05bccfb4c068e2f5b2dbf808bb931ec13f7e2a..07f091a58a4e26f297694f007fdbd7b44b829fe0 100644 --- a/clang/include/clang/Basic/Builtins.h +++ b/clang/include/clang/Basic/Builtins.h @@ -67,40 +67,40 @@ public: /// \brief Popular the vector with the names of all of the builtins. void GetBuiltinNames(llvm::SmallVectorImpl &Names, bool NoBuiltins); - + /// Builtin::GetName - Return the identifier name for the specified builtin, /// e.g. "__builtin_abs". const char *GetName(unsigned ID) const { return GetRecord(ID).Name; } - + /// GetTypeString - Get the type descriptor string for the specified builtin. const char *GetTypeString(unsigned ID) const { return GetRecord(ID).Type; } - + /// isConst - Return true if this function has no side effects and doesn't /// read memory. bool isConst(unsigned ID) const { return strchr(GetRecord(ID).Attributes, 'c') != 0; } - + /// isNoThrow - Return true if we know this builtin never throws an exception. bool isNoThrow(unsigned ID) const { return strchr(GetRecord(ID).Attributes, 'n') != 0; } - + /// isNoReturn - Return true if we know this builtin never returns. bool isNoReturn(unsigned ID) const { return strchr(GetRecord(ID).Attributes, 'r') != 0; } - + /// isLibFunction - Return true if this is a builtin for a libc/libm function, /// with a "__builtin_" prefix (e.g. __builtin_abs). bool isLibFunction(unsigned ID) const { return strchr(GetRecord(ID).Attributes, 'F') != 0; } - + /// \brief Determines whether this builtin is a predefined libc/libm /// function, such as "malloc", where we know the signature a /// priori. @@ -124,7 +124,7 @@ public: bool hasVAListUse(unsigned ID) const { return strpbrk(GetRecord(ID).Type, "Aa") != 0; } - + /// isConstWithoutErrno - Return true if this function has no side /// effects and doesn't read memory, except for possibly errno. Such /// functions can be const when the MathErrno lang option is diff --git a/clang/include/clang/Basic/ConvertUTF.h b/clang/include/clang/Basic/ConvertUTF.h index 823a7030c2dfe5e66467e29a987d12dd9103071a..4da2ad7572235fcff0d7d2e852512e098f77cac5 100644 --- a/clang/include/clang/Basic/ConvertUTF.h +++ b/clang/include/clang/Basic/ConvertUTF.h @@ -8,9 +8,9 @@ *==------------------------------------------------------------------------==*/ /* * Copyright 2001-2004 Unicode, Inc. - * + * * Disclaimer - * + * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine @@ -18,9 +18,9 @@ * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. - * + * * Limitations on Rights to Redistribute This Code - * + * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form @@ -41,7 +41,7 @@ Each routine converts the text between *sourceStart and sourceEnd, putting the result into the buffer between *targetStart and - targetEnd. Note: the end pointers are *after* the last item: e.g. + targetEnd. Note: the end pointers are *after* the last item: e.g. *(sourceEnd - 1) is the last item. The return result indicates whether the conversion was successful, @@ -79,7 +79,7 @@ sequence is malformed. When "sourceIllegal" is returned, the source value will point to the illegal value that caused the problem. E.g., in UTF-8 when a sequence is malformed, it points to the start of the - malformed sequence. + malformed sequence. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. @@ -125,28 +125,28 @@ extern "C" { #endif ConversionResult ConvertUTF8toUTF16 ( - const UTF8** sourceStart, const UTF8* sourceEnd, + const UTF8** sourceStart, const UTF8* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); #ifdef CLANG_NEEDS_THESE_ONE_DAY ConversionResult ConvertUTF16toUTF8 ( - const UTF16** sourceStart, const UTF16* sourceEnd, + const UTF16** sourceStart, const UTF16* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF8toUTF32 ( - const UTF8** sourceStart, const UTF8* sourceEnd, + const UTF8** sourceStart, const UTF8* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF8 ( - const UTF32** sourceStart, const UTF32* sourceEnd, + const UTF32** sourceStart, const UTF32* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF32 ( - const UTF16** sourceStart, const UTF16* sourceEnd, + const UTF16** sourceStart, const UTF16* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF16 ( - const UTF32** sourceStart, const UTF32* sourceEnd, + const UTF32** sourceStart, const UTF32* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); #endif diff --git a/clang/include/clang/Basic/Diagnostic.h b/clang/include/clang/Basic/Diagnostic.h index be52939c18e143be9d8f78dbd2efa0ed0586f163..dc854b18302e2f3fd299761270fdb985a2a27b23 100644 --- a/clang/include/clang/Basic/Diagnostic.h +++ b/clang/include/clang/Basic/Diagnostic.h @@ -30,7 +30,7 @@ namespace clang { class LangOptions; class PartialDiagnostic; class SourceRange; - + // Import the diagnostic enums themselves. namespace diag { // Start position for diagnostics. @@ -46,7 +46,7 @@ namespace clang { }; class CustomDiagInfo; - + /// diag::kind - All of the diagnostics that can be emitted by the frontend. typedef unsigned kind; @@ -57,7 +57,7 @@ namespace clang { NUM_BUILTIN_COMMON_DIAGNOSTICS #undef DIAG }; - + /// Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs /// to either MAP_IGNORE (nothing), MAP_WARNING (emit a warning), MAP_ERROR /// (emit as an error). It allows clients to map errors to @@ -69,13 +69,13 @@ namespace clang { MAP_WARNING = 2, //< Map this diagnostic to a warning. MAP_ERROR = 3, //< Map this diagnostic to an error. MAP_FATAL = 4, //< Map this diagnostic to a fatal error. - + /// Map this diagnostic to "warning", but make it immune to -Werror. This /// happens when you specify -Wno-error=foo. MAP_WARNING_NO_WERROR = 5 }; } - + /// \brief Annotates a diagnostic with some code that should be /// inserted, removed, or replaced to fix the problem. /// @@ -104,7 +104,7 @@ public: /// \brief Create a code modification hint that inserts the given /// code string at a specific location. - static CodeModificationHint CreateInsertion(SourceLocation InsertionLoc, + static CodeModificationHint CreateInsertion(SourceLocation InsertionLoc, const std::string &Code) { CodeModificationHint Hint; Hint.InsertionLoc = InsertionLoc; @@ -122,7 +122,7 @@ public: /// \brief Create a code modification hint that replaces the given /// source range with the given code string. - static CodeModificationHint CreateReplacement(SourceRange RemoveRange, + static CodeModificationHint CreateReplacement(SourceRange RemoveRange, const std::string &Code) { CodeModificationHint Hint; Hint.RemoveRange = RemoveRange; @@ -142,13 +142,13 @@ public: enum Level { Ignored, Note, Warning, Error, Fatal }; - + /// ExtensionHandling - How do we handle otherwise-unmapped extension? This /// is controlled by -pedantic and -pedantic-errors. enum ExtensionHandling { Ext_Ignore, Ext_Warn, Ext_Error }; - + enum ArgumentKind { ak_std_string, // std::string ak_c_string, // const char * @@ -161,10 +161,10 @@ public: ak_nestednamespec // NestedNameSpecifier * }; -private: +private: unsigned char AllExtensionsSilenced; // Used by __extension__ bool IgnoreAllWarnings; // Ignore all warnings: -w - bool WarningsAsErrors; // Treat warnings like errors: + bool WarningsAsErrors; // Treat warnings like errors: bool SuppressSystemWarnings; // Suppress warnings in system headers. ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors? DiagnosticClient *Client; @@ -183,7 +183,7 @@ private: /// fatal error is emitted, and is sticky. bool ErrorOccurred; bool FatalErrorOccurred; - + /// LastDiagLevel - This is the level of the last diagnostic emitted. This is /// used to emit continuation diagnostics with the same level as the /// diagnostic that they follow. @@ -209,16 +209,16 @@ private: public: explicit Diagnostic(DiagnosticClient *client = 0); ~Diagnostic(); - + //===--------------------------------------------------------------------===// // Diagnostic characterization methods, used by a client to customize how // - + DiagnosticClient *getClient() { return Client; }; const DiagnosticClient *getClient() const { return Client; }; - - /// pushMappings - Copies the current DiagMappings and pushes the new copy + + /// pushMappings - Copies the current DiagMappings and pushes the new copy /// onto the top of the stack. void pushMappings(); @@ -234,12 +234,12 @@ public: /// ignored. If this and WarningsAsErrors are both set, then this one wins. void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; } bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; } - + /// setWarningsAsErrors - When set to true, any warnings reported are issued /// as errors. void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; } bool getWarningsAsErrors() const { return WarningsAsErrors; } - + /// setSuppressSystemWarnings - When set to true mask warnings that /// come from system headers. void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; } @@ -251,14 +251,14 @@ public: void setExtensionHandlingBehavior(ExtensionHandling H) { ExtBehavior = H; } - + /// AllExtensionsSilenced - This is a counter bumped when an __extension__ /// block is encountered. When non-zero, all extension diagnostics are /// entirely silenced, no matter how they are mapped. void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; } void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; } bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; } - + /// setDiagnosticMapping - This allows the client to specify that certain /// warnings are ignored. Notes can never be mapped, errors can only be /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily. @@ -269,7 +269,7 @@ public: "Cannot map errors!"); setDiagnosticMappingInternal(Diag, Map, true); } - + /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g. /// "unknown-pragmas" to have the specified mapping. This returns true and /// ignores the request if "Group" was unknown, false otherwise. @@ -280,13 +280,13 @@ public: unsigned getNumErrors() const { return NumErrors; } unsigned getNumDiagnostics() const { return NumDiagnostics; } - + /// getCustomDiagID - Return an ID for a diagnostic with the specified message /// and level. If this is the first request for this diagnosic, it is /// registered and created, otherwise the existing ID is returned. unsigned getCustomDiagID(Level L, const char *Message); - - + + /// ConvertArgToString - This method converts a diagnostic argument (as an /// intptr_t) into the string that represents it. void ConvertArgToString(ArgumentKind Kind, intptr_t Val, @@ -296,12 +296,12 @@ public: ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen, Output, ArgToStringCookie); } - + void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) { ArgToStringFn = Fn; ArgToStringCookie = Cookie; } - + //===--------------------------------------------------------------------===// // Diagnostic classification and reporting interfaces. // @@ -309,7 +309,7 @@ public: /// getDescription - Given a diagnostic ID, return a description of the /// issue. const char *getDescription(unsigned DiagID) const; - + /// isNoteWarningOrExtension - Return true if the unmapped diagnostic /// level of the specified diagnostic ID is a Warning or Extension. /// This only works on builtin diagnostics, not custom ones, and is not legal to @@ -319,12 +319,12 @@ public: /// \brief Determine whether the given built-in diagnostic ID is a /// Note. static bool isBuiltinNote(unsigned DiagID); - + /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic /// ID is for an extension of some sort. /// static bool isBuiltinExtensionDiag(unsigned DiagID); - + /// getWarningOptionForDiag - Return the lowest-level warning option that /// enables the specified diagnostic. If there is no -Wfoo flag that controls /// the diagnostic, this returns null. @@ -343,8 +343,8 @@ public: /// getDiagnosticLevel - Based on the way the client configured the Diagnostic /// object, classify the specified diagnostic ID into a Level, consumable by /// the DiagnosticClient. - Level getDiagnosticLevel(unsigned DiagID) const; - + Level getDiagnosticLevel(unsigned DiagID) const; + /// Report - Issue the message to the client. @c DiagID is a member of the /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed. @@ -354,7 +354,7 @@ public: /// \brief Clear out the current diagnostic. void Clear() { CurDiagID = ~0U; } - + private: /// getDiagnosticMappingInfo - Return the mapping info currently set for the /// specified builtin diagnostic. This returns the high bit encoding, or zero @@ -363,7 +363,7 @@ private: const DiagMappings ¤tMappings = DiagMappingsStack.back(); return (diag::Mapping)((currentMappings[Diag/2] >> (Diag & 1)*4) & 15); } - + void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map, bool isUser) const { if (isUser) Map |= 8; // Set the high bit for user mappings. @@ -372,7 +372,7 @@ private: Slot &= ~(15 << Shift); Slot |= Map << Shift; } - + /// getDiagnosticLevel - This is an internal implementation helper used when /// DiagClass is already known. Level getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const; @@ -389,7 +389,7 @@ private: /// CurDiagLoc - This is the location of the current diagnostic that is in /// flight. FullSourceLoc CurDiagLoc; - + /// CurDiagID - This is the ID of the current diagnostic that is in flight. /// This is set to ~0U when there is no diagnostic in flight. unsigned CurDiagID; @@ -400,7 +400,7 @@ private: /// than that almost certainly has to be simplified anyway. MaxArguments = 10 }; - + /// NumDiagArgs - This contains the number of entries in Arguments. signed char NumDiagArgs; /// NumRanges - This is the number of ranges in the DiagRanges array. @@ -413,7 +413,7 @@ private: /// values, with one for each argument. This specifies whether the argument /// is in DiagArgumentsStr or in DiagArguments. unsigned char DiagArgumentsKind[MaxArguments]; - + /// DiagArgumentsStr - This holds the values of each string argument for the /// current diagnostic. This value is only used when the corresponding /// ArgumentKind is ak_std_string. @@ -424,11 +424,11 @@ private: /// mangled into an intptr_t and the intepretation depends on exactly what /// sort of argument kind it is. intptr_t DiagArgumentsVal[MaxArguments]; - + /// DiagRanges - The list of ranges added to this diagnostic. It currently /// only support 10 ranges, could easily be extended if needed. const SourceRange *DiagRanges[10]; - + enum { MaxCodeModificationHints = 3 }; /// CodeModificationHints - If valid, provides a hint with some code @@ -461,14 +461,14 @@ private: class DiagnosticBuilder { mutable Diagnostic *DiagObj; mutable unsigned NumArgs, NumRanges, NumCodeModificationHints; - + void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT friend class Diagnostic; explicit DiagnosticBuilder(Diagnostic *diagObj) - : DiagObj(diagObj), NumArgs(0), NumRanges(0), + : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumCodeModificationHints(0) {} -public: +public: /// Copy constructor. When copied, this "takes" the diagnostic info from the /// input and neuters it. DiagnosticBuilder(const DiagnosticBuilder &D) { @@ -485,7 +485,7 @@ public: /// \brief Create an empty DiagnosticBuilder object that represents /// no actual diagnostic. - explicit DiagnosticBuilder(SuppressKind) + explicit DiagnosticBuilder(SuppressKind) : DiagObj(0), NumArgs(0), NumRanges(0), NumCodeModificationHints(0) { } /// \brief Force the diagnostic builder to emit the diagnostic now. @@ -522,7 +522,7 @@ public: /// Destructor - The dtor emits the diagnostic if it hasn't already /// been emitted. ~DiagnosticBuilder() { Emit(); } - + /// Operator bool: conversion of DiagnosticBuilder to bool always returns /// true. This allows is to be used in boolean error contexts like: /// return Diag(...); @@ -536,7 +536,7 @@ public: DiagObj->DiagArgumentsStr[NumArgs++] = S; } } - + void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const { assert(NumArgs < Diagnostic::MaxArguments && "Too many arguments to diagnostic!"); @@ -545,14 +545,14 @@ public: DiagObj->DiagArgumentsVal[NumArgs++] = V; } } - + void AddSourceRange(const SourceRange &R) const { - assert(NumRanges < + assert(NumRanges < sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) && "Too many arguments to diagnostic!"); if (DiagObj) DiagObj->DiagRanges[NumRanges++] = &R; - } + } void AddCodeModificationHint(const CodeModificationHint &Hint) const { assert(NumCodeModificationHints < Diagnostic::MaxCodeModificationHints && @@ -597,7 +597,7 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, Diagnostic::ak_identifierinfo); return DB; } - + inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, const SourceRange &R) { DB.AddSourceRange(R); @@ -623,7 +623,7 @@ inline DiagnosticBuilder Diagnostic::Report(FullSourceLoc Loc, unsigned DiagID){ //===----------------------------------------------------------------------===// // DiagnosticInfo //===----------------------------------------------------------------------===// - + /// DiagnosticInfo - This is a little helper class (which is basically a smart /// pointer that forward info from Diagnostic) that allows clients to enquire /// about the currently in-flight diagnostic. @@ -631,74 +631,74 @@ class DiagnosticInfo { const Diagnostic *DiagObj; public: explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {} - + const Diagnostic *getDiags() const { return DiagObj; } unsigned getID() const { return DiagObj->CurDiagID; } const FullSourceLoc &getLocation() const { return DiagObj->CurDiagLoc; } - + unsigned getNumArgs() const { return DiagObj->NumDiagArgs; } - + /// getArgKind - Return the kind of the specified index. Based on the kind /// of argument, the accessors below can be used to get the value. Diagnostic::ArgumentKind getArgKind(unsigned Idx) const { assert(Idx < getNumArgs() && "Argument index out of range!"); return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx]; } - + /// getArgStdStr - Return the provided argument string specified by Idx. const std::string &getArgStdStr(unsigned Idx) const { assert(getArgKind(Idx) == Diagnostic::ak_std_string && "invalid argument accessor!"); return DiagObj->DiagArgumentsStr[Idx]; } - + /// getArgCStr - Return the specified C string argument. const char *getArgCStr(unsigned Idx) const { assert(getArgKind(Idx) == Diagnostic::ak_c_string && "invalid argument accessor!"); return reinterpret_cast(DiagObj->DiagArgumentsVal[Idx]); } - + /// getArgSInt - Return the specified signed integer argument. int getArgSInt(unsigned Idx) const { assert(getArgKind(Idx) == Diagnostic::ak_sint && "invalid argument accessor!"); return (int)DiagObj->DiagArgumentsVal[Idx]; } - + /// getArgUInt - Return the specified unsigned integer argument. unsigned getArgUInt(unsigned Idx) const { assert(getArgKind(Idx) == Diagnostic::ak_uint && "invalid argument accessor!"); return (unsigned)DiagObj->DiagArgumentsVal[Idx]; } - + /// getArgIdentifier - Return the specified IdentifierInfo argument. const IdentifierInfo *getArgIdentifier(unsigned Idx) const { assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo && "invalid argument accessor!"); return reinterpret_cast(DiagObj->DiagArgumentsVal[Idx]); } - + /// getRawArg - Return the specified non-string argument in an opaque form. intptr_t getRawArg(unsigned Idx) const { assert(getArgKind(Idx) != Diagnostic::ak_std_string && "invalid argument accessor!"); return DiagObj->DiagArgumentsVal[Idx]; } - - + + /// getNumRanges - Return the number of source ranges associated with this /// diagnostic. unsigned getNumRanges() const { return DiagObj->NumDiagRanges; } - + const SourceRange &getRange(unsigned Idx) const { assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!"); return *DiagObj->DiagRanges[Idx]; } - + unsigned getNumCodeModificationHints() const { return DiagObj->NumCodeModificationHints; } @@ -708,7 +708,7 @@ public: } const CodeModificationHint *getCodeModificationHints() const { - return DiagObj->NumCodeModificationHints? + return DiagObj->NumCodeModificationHints? &DiagObj->CodeModificationHints[0] : 0; } @@ -717,20 +717,20 @@ public: /// array. void FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const; }; - + /// DiagnosticClient - This is an abstract interface implemented by clients of /// the front-end, which formats and prints fully processed diagnostics. class DiagnosticClient { public: virtual ~DiagnosticClient(); - + /// setLangOptions - This is set by clients of diagnostics when they know the /// language parameters of the diagnostics that may be sent through. Note /// that this can change over time if a DiagClient has multiple languages sent /// through it. It may also be set to null (e.g. when processing command line /// options). virtual void setLangOptions(const LangOptions *LO) {} - + /// IncludeInDiagnosticCounts - This method (whose default implementation /// returns true) indicates whether the diagnostics handled by this /// DiagnosticClient should be included in the number of diagnostics diff --git a/clang/include/clang/Basic/FileManager.h b/clang/include/clang/Basic/FileManager.h index d684449c85087e3c1cc964aa827c95573e8bbdc5..7c9113c497ef16f766deca65d0b2d2c7fe9506e1 100644 --- a/clang/include/clang/Basic/FileManager.h +++ b/clang/include/clang/Basic/FileManager.h @@ -25,7 +25,7 @@ namespace clang { class FileManager; - + /// DirectoryEntry - Cached information about one directory on the disk. /// class DirectoryEntry { @@ -33,7 +33,7 @@ class DirectoryEntry { friend class FileManager; public: DirectoryEntry() : Name(0) {} - const char *getName() const { return Name; } + const char *getName() const { return Name; } }; /// FileEntry - Cached information about one file on the disk. @@ -53,7 +53,7 @@ public: : Name(0), Device(device), Inode(inode), FileMode(m) {} // Add a default constructor for use with llvm::StringMap FileEntry() : Name(0), Device(0), Inode(0), FileMode(0) {} - + const char *getName() const { return Name; } off_t getSize() const { return Size; } unsigned getUID() const { return UID; } @@ -61,11 +61,11 @@ public: dev_t getDevice() const { return Device; } time_t getModificationTime() const { return ModTime; } mode_t getFileMode() const { return FileMode; } - + /// getDir - Return the directory the file lives in. /// const DirectoryEntry *getDir() const { return Dir; } - + bool operator<(const FileEntry& RHS) const { return Device < RHS.Device || (Device == RHS.Device && Inode < RHS.Inode); } @@ -85,19 +85,19 @@ public: /// execution of the front end. class MemorizeStatCalls : public StatSysCallCache { public: - /// \brief The result of a stat() call. + /// \brief The result of a stat() call. /// /// The first member is the result of calling stat(). If stat() /// found something, the second member is a copy of the stat /// structure. typedef std::pair StatResult; - /// \brief The set of stat() calls that have been + /// \brief The set of stat() calls that have been llvm::StringMap StatCalls; typedef llvm::StringMap::const_iterator iterator; - + iterator begin() const { return StatCalls.begin(); } iterator end() const { return StatCalls.end(); } @@ -124,22 +124,22 @@ class FileManager { /// llvm::StringMap DirEntries; llvm::StringMap FileEntries; - + /// NextFileUID - Each FileEntry we create is assigned a unique ID #. /// unsigned NextFileUID; - + // Statistics. unsigned NumDirLookups, NumFileLookups; unsigned NumDirCacheMisses, NumFileCacheMisses; - + // Caching. llvm::OwningPtr StatCache; int stat_cached(const char* path, struct stat* buf) { return StatCache.get() ? StatCache->stat(path, buf) : stat(path, buf); } - + public: FileManager(); ~FileManager(); @@ -150,24 +150,24 @@ public: void setStatCache(StatSysCallCache *statCache) { StatCache.reset(statCache); } - + /// getDirectory - Lookup, cache, and verify the specified directory. This /// returns null if the directory doesn't exist. - /// + /// const DirectoryEntry *getDirectory(const llvm::StringRef &Filename) { return getDirectory(Filename.begin(), Filename.end()); } const DirectoryEntry *getDirectory(const char *FileStart,const char *FileEnd); - + /// getFile - Lookup, cache, and verify the specified file. This returns null /// if the file doesn't exist. - /// + /// const FileEntry *getFile(const llvm::StringRef &Filename) { return getFile(Filename.begin(), Filename.end()); } const FileEntry *getFile(const char *FilenameStart, const char *FilenameEnd); - + void PrintStats() const; }; diff --git a/clang/include/clang/Basic/IdentifierTable.h b/clang/include/clang/Basic/IdentifierTable.h index 57cd311631446489480fd481529d9f3337240a03..8512538e45cb51a9b131ce4f81371d8d65d7e783 100644 --- a/clang/include/clang/Basic/IdentifierTable.h +++ b/clang/include/clang/Basic/IdentifierTable.h @@ -21,8 +21,8 @@ #include "llvm/ADT/SmallString.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/PointerLikeTypeTraits.h" -#include -#include +#include +#include namespace llvm { template struct DenseMapInfo; @@ -38,21 +38,21 @@ namespace clang { /// IdentifierLocPair - A simple pair of identifier info and location. typedef std::pair IdentifierLocPair; - - + + /// IdentifierInfo - One of these records is kept for each identifier that /// is lexed. This contains information about whether the token was #define'd, /// is a language keyword, or if it is a front-end token of some sort (e.g. a /// variable or function name). The preprocessor keeps this information in a -/// set, and all tok::identifier tokens have a pointer to one of these. +/// set, and all tok::identifier tokens have a pointer to one of these. class IdentifierInfo { // Note: DON'T make TokenID a 'tok::TokenKind'; MSVC will treat it as a // signed char and TokenKinds > 127 won't be handled correctly. - unsigned TokenID : 8; // Front-end token ID or tok::identifier. + unsigned TokenID : 8; // Front-end token ID or tok::identifier. // Objective-C keyword ('protocol' in '@protocol') or builtin (__builtin_inf). // First NUM_OBJC_KEYWORDS values are for Objective-C, the remaining values // are for builtins. - unsigned ObjCOrBuiltinID :10; + unsigned ObjCOrBuiltinID :10; bool HasMacro : 1; // True if there is a #define for this. bool IsExtension : 1; // True if identifier is a lang extension. bool IsPoisoned : 1; // True if identifier is poisoned. @@ -61,50 +61,50 @@ class IdentifierInfo { // 9 bits left in 32-bit word. void *FETokenInfo; // Managed by the language front-end. llvm::StringMapEntry *Entry; - + IdentifierInfo(const IdentifierInfo&); // NONCOPYABLE. void operator=(const IdentifierInfo&); // NONASSIGNABLE. - friend class IdentifierTable; + friend class IdentifierTable; public: IdentifierInfo(); - + /// isStr - Return true if this is the identifier for the specified string. /// This is intended to be used for string literals only: II->isStr("foo"). template bool isStr(const char (&Str)[StrLen]) const { return getLength() == StrLen-1 && !memcmp(getName(), Str, StrLen-1); } - - /// getName - Return the actual string for this identifier. The returned + + /// getName - Return the actual string for this identifier. The returned /// string is properly null terminated. /// - const char *getName() const { + const char *getName() const { if (Entry) return Entry->getKeyData(); // FIXME: This is gross. It would be best not to embed specific details // of the PTH file format here. - // The 'this' pointer really points to a + // The 'this' pointer really points to a // std::pair, where internal pointer // points to the external string data. return ((std::pair*) this)->second; } - + /// getLength - Efficiently return the length of this identifier info. /// unsigned getLength() const { if (Entry) return Entry->getKeyLength(); // FIXME: This is gross. It would be best not to embed specific details // of the PTH file format here. - // The 'this' pointer really points to a + // The 'this' pointer really points to a // std::pair, where internal pointer // points to the external string data. const char* p = ((std::pair*) this)->second-2; return (((unsigned) p[0]) | (((unsigned) p[1]) << 8)) - 1; } - + /// hasMacroDefinition - Return true if this identifier is #defined to some /// other value. bool hasMacroDefinition() const { @@ -112,29 +112,29 @@ public: } void setHasMacroDefinition(bool Val) { if (HasMacro == Val) return; - + HasMacro = Val; if (Val) NeedsHandleIdentifier = 1; else RecomputeNeedsHandleIdentifier(); } - + /// get/setTokenID - If this is a source-language token (e.g. 'for'), this API /// can be used to cause the lexer to map identifiers to source-language /// tokens. tok::TokenKind getTokenID() const { return (tok::TokenKind)TokenID; } void setTokenID(tok::TokenKind ID) { TokenID = ID; } - + /// getPPKeywordID - Return the preprocessor keyword ID for this identifier. /// For example, "define" will return tok::pp_define. tok::PPKeywordKind getPPKeywordID() const; - + /// getObjCKeywordID - Return the Objective-C keyword ID for the this /// identifier. For example, 'class' will return tok::objc_class if ObjC is /// enabled. tok::ObjCKeywordKind getObjCKeywordID() const { - if (ObjCOrBuiltinID < tok::NUM_OBJC_KEYWORDS) + if (ObjCOrBuiltinID < tok::NUM_OBJC_KEYWORDS) return tok::ObjCKeywordKind(ObjCOrBuiltinID); else return tok::objc_not_keyword; @@ -144,15 +144,15 @@ public: /// getBuiltinID - Return a value indicating whether this is a builtin /// function. 0 is not-built-in. 1 is builtin-for-some-nonprimary-target. /// 2+ are specific builtin functions. - unsigned getBuiltinID() const { + unsigned getBuiltinID() const { if (ObjCOrBuiltinID >= tok::NUM_OBJC_KEYWORDS) - return ObjCOrBuiltinID - tok::NUM_OBJC_KEYWORDS; + return ObjCOrBuiltinID - tok::NUM_OBJC_KEYWORDS; else return 0; } void setBuiltinID(unsigned ID) { ObjCOrBuiltinID = ID + tok::NUM_OBJC_KEYWORDS; - assert(ObjCOrBuiltinID - unsigned(tok::NUM_OBJC_KEYWORDS) == ID + assert(ObjCOrBuiltinID - unsigned(tok::NUM_OBJC_KEYWORDS) == ID && "ID too large for field!"); } @@ -170,7 +170,7 @@ public: else RecomputeNeedsHandleIdentifier(); } - + /// setIsPoisoned - Mark this identifier as poisoned. After poisoning, the /// Preprocessor will emit an error every time this token is used. void setIsPoisoned(bool Value = true) { @@ -180,10 +180,10 @@ public: else RecomputeNeedsHandleIdentifier(); } - + /// isPoisoned - Return true if this token has been poisoned. bool isPoisoned() const { return IsPoisoned; } - + /// isCPlusPlusOperatorKeyword/setIsCPlusPlusOperatorKeyword controls whether /// this identifier is a C++ alternate representation of an operator. void setIsCPlusPlusOperatorKeyword(bool Val = true) { @@ -205,7 +205,7 @@ public: /// must be called on a token of this identifier. If this returns false, we /// know that HandleIdentifier will not affect the token. bool isHandleIdentifierCase() const { return NeedsHandleIdentifier; } - + private: /// RecomputeNeedsHandleIdentifier - The Preprocessor::HandleIdentifier does /// several special (but rare) things to identifiers of various sorts. For @@ -227,13 +227,13 @@ private: class IdentifierInfoLookup { public: virtual ~IdentifierInfoLookup(); - + /// get - Return the identifier token info for the specified named identifier. /// Unlike the version in IdentifierTable, this returns a pointer instead /// of a reference. If the pointer is NULL then the IdentifierInfo cannot /// be found. virtual IdentifierInfo* get(const char *NameStart, const char *NameEnd) = 0; -}; +}; /// \brief An abstract class used to resolve numerical identifier /// references (meaningful only to some external source) into @@ -257,7 +257,7 @@ class IdentifierTable { // BumpPtrAllocator! typedef llvm::StringMap HashTableTy; HashTableTy HashTable; - + IdentifierInfoLookup* ExternalLookup; public: @@ -265,7 +265,7 @@ public: /// info about the language keywords for the language specified by LangOpts. IdentifierTable(const LangOptions &LangOpts, IdentifierInfoLookup* externalLookup = 0); - + /// \brief Set the external identifier lookup mechanism. void setExternalIdentifierLookup(IdentifierInfoLookup *IILookup) { ExternalLookup = IILookup; @@ -274,16 +274,16 @@ public: llvm::BumpPtrAllocator& getAllocator() { return HashTable.getAllocator(); } - + /// get - Return the identifier token info for the specified named identifier. /// IdentifierInfo &get(const char *NameStart, const char *NameEnd) { llvm::StringMapEntry &Entry = HashTable.GetOrCreateValue(NameStart, NameEnd); - + IdentifierInfo *II = Entry.getValue(); if (II) return *II; - + // No entry; if we have an external lookup, look there first. if (ExternalLookup) { II = ExternalLookup->get(NameStart, NameEnd); @@ -305,7 +305,7 @@ public: return *II; } - + /// \brief Creates a new IdentifierInfo from the given string. /// /// This is a lower-level version of get() that requires that this @@ -314,14 +314,14 @@ public: /// identifier sources can use this routine to build IdentifierInfo /// nodes and then introduce additional information about those /// identifiers. - IdentifierInfo &CreateIdentifierInfo(const char *NameStart, + IdentifierInfo &CreateIdentifierInfo(const char *NameStart, const char *NameEnd) { llvm::StringMapEntry &Entry = HashTable.GetOrCreateValue(NameStart, NameEnd); - + IdentifierInfo *II = Entry.getValue(); assert(!II && "IdentifierInfo already exists"); - + // Lookups failed, make a new IdentifierInfo. void *Mem = getAllocator().Allocate(); II = new (Mem) IdentifierInfo(); @@ -345,26 +345,26 @@ public: typedef HashTableTy::const_iterator iterator; typedef HashTableTy::const_iterator const_iterator; - + iterator begin() const { return HashTable.begin(); } iterator end() const { return HashTable.end(); } unsigned size() const { return HashTable.size(); } - + /// PrintStats - Print some statistics to stderr that indicate how well the /// hashing is doing. void PrintStats() const; - + void AddKeywords(const LangOptions &LangOpts); }; /// Selector - This smart pointer class efficiently represents Objective-C /// method names. This class will either point to an IdentifierInfo or a /// MultiKeywordSelector (which is private). This enables us to optimize -/// selectors that take no arguments and selectors that take 1 argument, which +/// selectors that take no arguments and selectors that take 1 argument, which /// accounts for 78% of all selectors in Cocoa.h. class Selector { friend class DiagnosticInfo; - + enum IdentifierInfoFlag { // MultiKeywordSelector = 0. ZeroArg = 0x1, @@ -372,7 +372,7 @@ class Selector { ArgFlags = ZeroArg|OneArg }; uintptr_t InfoPtr; // a pointer to the MultiKeywordSelector or IdentifierInfo. - + Selector(IdentifierInfo *II, unsigned nArgs) { InfoPtr = reinterpret_cast(II); assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo"); @@ -383,7 +383,7 @@ class Selector { InfoPtr = reinterpret_cast(SI); assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo"); } - + IdentifierInfo *getAsIdentifierInfo() const { if (getIdentifierInfoFlag()) return reinterpret_cast(InfoPtr & ~ArgFlags); @@ -417,19 +417,19 @@ public: bool isNull() const { return InfoPtr == 0; } // Predicates to identify the selector type. - bool isKeywordSelector() const { - return getIdentifierInfoFlag() != ZeroArg; + bool isKeywordSelector() const { + return getIdentifierInfoFlag() != ZeroArg; } - bool isUnarySelector() const { + bool isUnarySelector() const { return getIdentifierInfoFlag() == ZeroArg; } unsigned getNumArgs() const; IdentifierInfo *getIdentifierInfoForSlot(unsigned argIndex) const; - + /// getAsString - Derive the full selector name (e.g. "foo:bar:") and return /// it as an std::string. std::string getAsString() const; - + static Selector getEmptyMarker() { return Selector(uintptr_t(-1)); } @@ -452,7 +452,7 @@ public: /// whether this is a no argument selector "foo", a single argument selector /// "foo:" or multi-argument "foo:bar:". Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV); - + Selector getUnarySelector(IdentifierInfo *ID) { return Selector(ID, 1); } @@ -519,15 +519,15 @@ struct DenseMapInfo { return clang::Selector::getEmptyMarker(); } static inline clang::Selector getTombstoneKey() { - return clang::Selector::getTombstoneMarker(); + return clang::Selector::getTombstoneMarker(); } - + static unsigned getHashValue(clang::Selector S); - + static bool isEqual(clang::Selector LHS, clang::Selector RHS) { return LHS == RHS; } - + static bool isPod() { return true; } }; @@ -537,7 +537,7 @@ template<> class PointerLikeTypeTraits { public: static inline void *getAsVoidPointer(clang::IdentifierInfo* P) { - return P; + return P; } static inline clang::IdentifierInfo *getFromVoidPointer(void *P) { return static_cast(P); @@ -549,7 +549,7 @@ template<> class PointerLikeTypeTraits { public: static inline const void *getAsVoidPointer(const clang::IdentifierInfo* P) { - return P; + return P; } static inline const clang::IdentifierInfo *getFromVoidPointer(const void *P) { return static_cast(P); diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h index da702a8ab36c69c480c9bf93967e972c11c6cdef..b5c813dc3c8eefd50a713a5ae569e454aacc83f7 100644 --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -34,13 +34,13 @@ public: unsigned CPlusPlus : 1; // C++ Support unsigned CPlusPlus0x : 1; // C++0x Support unsigned CXXOperatorNames : 1; // Treat C++ operator names as keywords. - + unsigned ObjC1 : 1; // Objective-C 1 support enabled. unsigned ObjC2 : 1; // Objective-C 2 support enabled. unsigned ObjCSenderDispatch: 1; // Objective-C 2 three-dimensional dispatch // enabled. unsigned ObjCNonFragileABI : 1; // Objective-C modern abi enabled - + unsigned PascalStrings : 1; // Allow Pascal strings unsigned WritableStrings : 1; // Allow writable strings unsigned LaxVectorConversions : 1; @@ -69,7 +69,7 @@ public: // may be ripped out at any time. unsigned Optimize : 1; // Whether __OPTIMIZE__ should be defined. - unsigned OptimizeSize : 1; // Whether __OPTIMIZE_SIZE__ should be + unsigned OptimizeSize : 1; // Whether __OPTIMIZE_SIZE__ should be // defined. unsigned Static : 1; // Should __STATIC__ be defined (as // opposed to __DYNAMIC__). @@ -82,7 +82,7 @@ public: unsigned ObjCGCBitmapPrint : 1; // Enable printing of gc's bitmap layout // for __weak/__strong ivars. - unsigned AccessControl : 1; // Whether C++ access control should + unsigned AccessControl : 1; // Whether C++ access control should // be enabled. unsigned CharIsSigned : 1; // Whether char is a signed or unsigned type @@ -106,19 +106,19 @@ private: /// the original input file, for example with -save-temps. const char *MainFileName; -public: +public: unsigned InstantiationDepth; // Maximum template instantiation depth. const char *ObjCConstantStringClass; enum GCMode { NonGC, GCOnly, HybridGC }; enum StackProtectorMode { SSPOff, SSPOn, SSPReq }; - enum VisibilityMode { - Default, - Protected, + enum VisibilityMode { + Default, + Protected, Hidden }; - + LangOptions() { Trigraphs = BCPLComment = Bool = DollarIdents = AsmPreprocessor = 0; GNUMode = ImplicitInt = Digraphs = 0; @@ -134,7 +134,7 @@ public: AltiVec = OpenCL = StackProtector = 0; SymbolVisibility = (unsigned) Default; - + // FIXME: The default should be 1. ThreadsafeStatics = 0; POSIXThreads = 0; @@ -145,13 +145,13 @@ public: // FIXME: The default should be 1. AccessControl = 0; ElideConstructors = 1; - + OverflowChecking = 0; ObjCGCBitmapPrint = 0; ObjCSenderDispatch = 0; InstantiationDepth = 99; - + Optimize = 0; OptimizeSize = 0; @@ -165,7 +165,7 @@ public: MainFileName = 0; } - + GCMode getGCMode() const { return (GCMode) GC; } void setGCMode(GCMode m) { GC = (unsigned) m; } @@ -179,8 +179,8 @@ public: const char *getMainFileName() const { return MainFileName; } void setMainFileName(const char *Name) { MainFileName = Name; } - VisibilityMode getVisibilityMode() const { - return (VisibilityMode) SymbolVisibility; + VisibilityMode getVisibilityMode() const { + return (VisibilityMode) SymbolVisibility; } void setVisibilityMode(VisibilityMode v) { SymbolVisibility = (unsigned) v; } }; diff --git a/clang/include/clang/Basic/OnDiskHashTable.h b/clang/include/clang/Basic/OnDiskHashTable.h index f54d67042c472a7f1c95afb73d0cc58e8d86e339..65245167d8d563f975e7e8c2cc14909ed1507d09 100644 --- a/clang/include/clang/Basic/OnDiskHashTable.h +++ b/clang/include/clang/Basic/OnDiskHashTable.h @@ -29,7 +29,7 @@ namespace clang { // This is basically copy-and-paste from StringMap. This likely won't // stay here, which is why I didn't both to expose this function from // String Map. -inline unsigned BernsteinHash(const char* x) { +inline unsigned BernsteinHash(const char* x) { unsigned int R = 0; for ( ; *x != '\0' ; ++x) R = R * 33 + *x; return R + (R >> 5); @@ -131,29 +131,29 @@ class OnDiskChainedHashTableGenerator { unsigned NumBuckets; unsigned NumEntries; llvm::BumpPtrAllocator BA; - + class Item { public: typename Info::key_type key; typename Info::data_type data; Item *next; const uint32_t hash; - + Item(typename Info::key_type_ref k, typename Info::data_type_ref d) : key(k), data(d), next(0), hash(Info::ComputeHash(k)) {} }; - - class Bucket { + + class Bucket { public: io::Offset off; Item* head; unsigned length; - + Bucket() {} }; - + Bucket* Buckets; - + private: void insert(Bucket* b, size_t size, Item* E) { unsigned idx = E->hash & (size - 1); @@ -162,7 +162,7 @@ private: ++B.length; B.head = E; } - + void resize(size_t newsize) { Bucket* newBuckets = (Bucket*) std::calloc(newsize, sizeof(Bucket)); // Populate newBuckets with the old entries. @@ -173,14 +173,14 @@ private: insert(newBuckets, newsize, E); E = N; } - + free(Buckets); NumBuckets = newsize; Buckets = newBuckets; - } - + } + public: - + void insert(typename Info::key_type_ref key, typename Info::data_type_ref data) { @@ -188,7 +188,7 @@ public: if (4*NumEntries >= 3*NumBuckets) resize(NumBuckets*2); insert(Buckets, NumBuckets, new (BA.Allocate()) Item(key, data)); } - + io::Offset Emit(llvm::raw_ostream &out) { Info InfoObj; return Emit(out, InfoObj); @@ -201,42 +201,42 @@ public: for (unsigned i = 0; i < NumBuckets; ++i) { Bucket& B = Buckets[i]; if (!B.head) continue; - + // Store the offset for the data of this bucket. B.off = out.tell(); assert(B.off && "Cannot write a bucket at offset 0. Please add padding."); // Write out the number of items in the bucket. Emit16(out, B.length); - + // Write out the entries in the bucket. for (Item *I = B.head; I ; I = I->next) { Emit32(out, I->hash); - const std::pair& Len = + const std::pair& Len = InfoObj.EmitKeyDataLength(out, I->key, I->data); InfoObj.EmitKey(out, I->key, Len.first); InfoObj.EmitData(out, I->key, I->data, Len.second); } } - + // Emit the hashtable itself. Pad(out, 4); io::Offset TableOff = out.tell(); Emit32(out, NumBuckets); Emit32(out, NumEntries); for (unsigned i = 0; i < NumBuckets; ++i) Emit32(out, Buckets[i].off); - + return TableOff; } - + OnDiskChainedHashTableGenerator() { NumEntries = 0; - NumBuckets = 64; + NumBuckets = 64; // Note that we do not need to run the constructors of the individual // Bucket objects since 'calloc' returns bytes that are all 0. Buckets = (Bucket*) std::calloc(NumBuckets, sizeof(Bucket)); } - + ~OnDiskChainedHashTableGenerator() { std::free(Buckets); } @@ -254,7 +254,7 @@ public: typedef typename Info::internal_key_type internal_key_type; typedef typename Info::external_key_type external_key_type; typedef typename Info::data_type data_type; - + OnDiskChainedHashTable(unsigned numBuckets, unsigned numEntries, const unsigned char* buckets, const unsigned char* base, @@ -271,7 +271,7 @@ public: const unsigned char* getBuckets() const { return Buckets; } bool isEmpty() const { return NumEntries == 0; } - + class iterator { internal_key_type key; const unsigned char* const data; @@ -282,12 +282,12 @@ public: iterator(const internal_key_type k, const unsigned char* d, unsigned l, Info *InfoObj) : key(k), data(d), len(l), InfoObj(InfoObj) {} - - data_type operator*() const { return InfoObj->ReadData(key, data, len); } - bool operator==(const iterator& X) const { return X.data == data; } + + data_type operator*() const { return InfoObj->ReadData(key, data, len); } + bool operator==(const iterator& X) const { return X.data == data; } bool operator!=(const iterator& X) const { return X.data != data; } - }; - + }; + iterator find(const external_key_type& eKey, Info *InfoPtr = 0) { if (!InfoPtr) InfoPtr = &InfoObj; @@ -295,25 +295,25 @@ public: using namespace io; const internal_key_type& iKey = Info::GetInternalKey(eKey); unsigned key_hash = Info::ComputeHash(iKey); - + // Each bucket is just a 32-bit offset into the hash table file. unsigned idx = key_hash & (NumBuckets - 1); const unsigned char* Bucket = Buckets + sizeof(uint32_t)*idx; - + unsigned offset = ReadLE32(Bucket); if (offset == 0) return iterator(); // Empty bucket. const unsigned char* Items = Base + offset; - + // 'Items' starts with a 16-bit unsigned integer representing the // number of items in this bucket. unsigned len = ReadUnalignedLE16(Items); - + for (unsigned i = 0; i < len; ++i) { // Read the hash. uint32_t item_hash = ReadUnalignedLE32(Items); - + // Determine the length of the key and the data. - const std::pair& L = Info::ReadKeyDataLength(Items); + const std::pair& L = Info::ReadKeyDataLength(Items); unsigned item_len = L.first + L.second; // Compare the hashes. If they are not the same, skip the entry entirely. @@ -321,7 +321,7 @@ public: Items += item_len; continue; } - + // Read the key. const internal_key_type& X = InfoPtr->ReadKey((const unsigned char* const) Items, L.first); @@ -331,17 +331,17 @@ public: Items += item_len; continue; } - + // The key matches! return iterator(X, Items + L.first, L.second, InfoPtr); } - + return iterator(); } - + iterator end() const { return iterator(); } - - + + static OnDiskChainedHashTable* Create(const unsigned char* buckets, const unsigned char* const base, const Info &InfoObj = Info()) { @@ -349,14 +349,14 @@ public: assert(buckets > base); assert((reinterpret_cast(buckets) & 0x3) == 0 && "buckets should be 4-byte aligned."); - + unsigned numBuckets = ReadLE32(buckets); unsigned numEntries = ReadLE32(buckets); return new OnDiskChainedHashTable(numBuckets, numEntries, buckets, base, InfoObj); - } + } }; } // end namespace clang -#endif +#endif diff --git a/clang/include/clang/Basic/SourceLocation.h b/clang/include/clang/Basic/SourceLocation.h index 2405c2fe7db72b61f7ef4f8e4fbdc4941281e379..28cf2db9bc25f0c438391676b153f7c20a445215 100644 --- a/clang/include/clang/Basic/SourceLocation.h +++ b/clang/include/clang/Basic/SourceLocation.h @@ -24,10 +24,10 @@ namespace llvm { } namespace clang { - + class SourceManager; class FileEntry; - + /// FileID - This is an opaque identifier used by SourceManager which refers to /// a source file (MemoryBuffer) along with its #include path and #line data. /// @@ -36,19 +36,19 @@ class FileID { unsigned ID; public: FileID() : ID(0) {} - + bool isInvalid() const { return ID == 0; } - + bool operator==(const FileID &RHS) const { return ID == RHS.ID; } bool operator<(const FileID &RHS) const { return ID < RHS.ID; } bool operator<=(const FileID &RHS) const { return ID <= RHS.ID; } bool operator!=(const FileID &RHS) const { return !(*this == RHS); } bool operator>(const FileID &RHS) const { return RHS < *this; } bool operator>=(const FileID &RHS) const { return RHS <= *this; } - + static FileID getSentinel() { return get(~0U); } unsigned getHashValue() const { return ID; } - + private: friend class SourceManager; static FileID get(unsigned V) { @@ -58,8 +58,8 @@ private: } unsigned getOpaqueValue() const { return ID; } }; - - + + /// SourceLocation - This is a carefully crafted 32-bit identifier that encodes /// a full include stack, line and column number information for a position in /// an input translation unit. @@ -72,17 +72,17 @@ class SourceLocation { public: SourceLocation() : ID(0) {} // 0 is an invalid FileID. - + bool isFileID() const { return (ID & MacroIDBit) == 0; } bool isMacroID() const { return (ID & MacroIDBit) != 0; } - + /// isValid - Return true if this is a valid SourceLocation object. Invalid /// SourceLocations are often used when events have no corresponding location /// in the source (e.g. a diagnostic is required for a command line option). /// bool isValid() const { return ID != 0; } bool isInvalid() const { return ID == 0; } - + private: /// getOffset - Return the index for SourceManager's SLocEntryTable table, /// note that this is not an index *into* it though. @@ -96,7 +96,7 @@ private: L.ID = ID; return L; } - + static SourceLocation getMacroLoc(unsigned ID) { assert((ID & MacroIDBit) == 0 && "Ran out of source locations!"); SourceLocation L; @@ -104,7 +104,7 @@ private: return L; } public: - + /// getFileLocWithOffset - Return a source location with the specified offset /// from this file SourceLocation. SourceLocation getFileLocWithOffset(int Offset) const { @@ -113,14 +113,14 @@ public: L.ID = ID+Offset; return L; } - + /// getRawEncoding - When a SourceLocation itself cannot be used, this returns /// an (opaque) 32-bit integer encoding for it. This should only be passed /// to SourceLocation::getFromRawEncoding, it should not be inspected /// directly. unsigned getRawEncoding() const { return ID; } - - + + /// getFromRawEncoding - Turn a raw encoding of a SourceLocation object into /// a real SourceLocation. static SourceLocation getFromRawEncoding(unsigned Encoding) { @@ -128,7 +128,7 @@ public: X.ID = Encoding; return X; } - + void print(llvm::raw_ostream &OS, const SourceManager &SM) const; void dump(const SourceManager &SM) const; }; @@ -140,7 +140,7 @@ inline bool operator==(const SourceLocation &LHS, const SourceLocation &RHS) { inline bool operator!=(const SourceLocation &LHS, const SourceLocation &RHS) { return !(LHS == RHS); } - + inline bool operator<(const SourceLocation &LHS, const SourceLocation &RHS) { return LHS.getRawEncoding() < RHS.getRawEncoding(); } @@ -153,24 +153,24 @@ public: SourceRange(): B(SourceLocation()), E(SourceLocation()) {} SourceRange(SourceLocation loc) : B(loc), E(loc) {} SourceRange(SourceLocation begin, SourceLocation end) : B(begin), E(end) {} - + SourceLocation getBegin() const { return B; } SourceLocation getEnd() const { return E; } - + void setBegin(SourceLocation b) { B = b; } void setEnd(SourceLocation e) { E = e; } - + bool isValid() const { return B.isValid() && E.isValid(); } - + bool operator==(const SourceRange &X) const { return B == X.B && E == X.E; } - + bool operator!=(const SourceRange &X) const { return B != X.B || E != X.E; } }; - + /// FullSourceLoc - A SourceLocation and its associated SourceManager. Useful /// for argument passing to functions that expect both objects. class FullSourceLoc : public SourceLocation { @@ -179,21 +179,21 @@ public: /// Creates a FullSourceLoc where isValid() returns false. explicit FullSourceLoc() : SrcMgr((SourceManager*) 0) {} - explicit FullSourceLoc(SourceLocation Loc, SourceManager &SM) + explicit FullSourceLoc(SourceLocation Loc, SourceManager &SM) : SourceLocation(Loc), SrcMgr(&SM) {} - + SourceManager &getManager() { assert(SrcMgr && "SourceManager is NULL."); return *SrcMgr; } - + const SourceManager &getManager() const { assert(SrcMgr && "SourceManager is NULL."); return *SrcMgr; } - + FileID getFileID() const; - + FullSourceLoc getInstantiationLoc() const; FullSourceLoc getSpellingLoc() const; @@ -204,37 +204,37 @@ public: unsigned getSpellingColumnNumber() const; const char *getCharacterData() const; - + const llvm::MemoryBuffer* getBuffer() const; - + /// getBufferData - Return a pointer to the start and end of the source buffer /// data for the specified FileID. std::pair getBufferData() const; - + /// getDecomposedLoc - Decompose the specified location into a raw FileID + /// Offset pair. The first element is the FileID, the second is the /// offset from the start of the buffer of the location. std::pair getDecomposedLoc() const; bool isInSystemHeader() const; - + /// Prints information about this FullSourceLoc to stderr. Useful for /// debugging. void dump() const { SourceLocation::dump(*SrcMgr); } - friend inline bool + friend inline bool operator==(const FullSourceLoc &LHS, const FullSourceLoc &RHS) { return LHS.getRawEncoding() == RHS.getRawEncoding() && LHS.SrcMgr == RHS.SrcMgr; } - friend inline bool + friend inline bool operator!=(const FullSourceLoc &LHS, const FullSourceLoc &RHS) { return !(LHS == RHS); } }; - + /// PresumedLoc - This class represents an unpacked "presumed" location which /// can be presented to the user. A 'presumed' location can be modified by /// #line and GNU line marker directives and is always the instantiation point @@ -250,13 +250,13 @@ public: PresumedLoc(const char *FN, unsigned Ln, unsigned Co, SourceLocation IL) : Filename(FN), Line(Ln), Col(Co), IncludeLoc(IL) { } - + /// isInvalid - Return true if this object is invalid or uninitialized. This /// occurs when created with invalid source locations or when walking off /// the top of a #include stack. bool isInvalid() const { return Filename == 0; } bool isValid() const { return Filename != 0; } - + /// getFilename - Return the presumed filename of this location. This can be /// affected by #line etc. const char *getFilename() const { return Filename; } @@ -264,7 +264,7 @@ public: /// getLine - Return the presumed line number of this location. This can be /// affected by #line etc. unsigned getLine() const { return Line; } - + /// getColumn - Return the presumed column number of this location. This can /// not be affected by #line, but is packaged here for convenience. unsigned getColumn() const { return Col; } @@ -274,7 +274,7 @@ public: SourceLocation getIncludeLoc() const { return IncludeLoc; } }; - + } // end namespace clang namespace llvm { @@ -286,20 +286,20 @@ namespace llvm { return clang::FileID(); } static inline clang::FileID getTombstoneKey() { - return clang::FileID::getSentinel(); + return clang::FileID::getSentinel(); } - + static unsigned getHashValue(clang::FileID S) { return S.getHashValue(); } - + static bool isEqual(clang::FileID LHS, clang::FileID RHS) { return LHS == RHS; } - + static bool isPod() { return true; } }; - + } // end namespace llvm #endif diff --git a/clang/include/clang/Basic/SourceManager.h b/clang/include/clang/Basic/SourceManager.h index 249ca89f717de87d0600acd10bfc4ff3c802edf0..e0eb2197ce06c4d653cf7983ef0d64e447b38915 100644 --- a/clang/include/clang/Basic/SourceManager.h +++ b/clang/include/clang/Basic/SourceManager.h @@ -24,9 +24,9 @@ namespace llvm { class MemoryBuffer; } - + namespace clang { - + class SourceManager; class FileManager; class FileEntry; @@ -46,7 +46,7 @@ namespace SrcMgr { enum CharacteristicKind { C_User, C_System, C_ExternCSystem }; - + /// ContentCache - Once instance of this struct is kept for every file /// loaded or used. This object owns the MemoryBuffer object. class ContentCache { @@ -59,12 +59,12 @@ namespace SrcMgr { /// the FileEntry object. It is possible for this to be NULL if /// the ContentCache encapsulates an imaginary text buffer. const FileEntry *Entry; - + /// SourceLineCache - A bump pointer allocated array of offsets for each /// source line. This is lazily computed. This is owned by the /// SourceManager BumpPointerAllocator object. unsigned *SourceLineCache; - + /// NumLines - The number of lines in this ContentCache. This is only valid /// if SourceLineCache is non-null. unsigned NumLines; @@ -76,28 +76,28 @@ namespace SrcMgr { /// getBuffer - Returns the memory buffer for the associated content. const llvm::MemoryBuffer *getBuffer() const; - + /// getSize - Returns the size of the content encapsulated by this /// ContentCache. This can be the size of the source file or the size of an /// arbitrary scratch buffer. If the ContentCache encapsulates a source /// file this size is retrieved from the file's FileEntry. unsigned getSize() const; - + /// getSizeBytesMapped - Returns the number of bytes actually mapped for /// this ContentCache. This can be 0 if the MemBuffer was not actually /// instantiated. unsigned getSizeBytesMapped() const; - + void setBuffer(const llvm::MemoryBuffer *B) { assert(!Buffer && "MemoryBuffer already set."); Buffer = B; } - + ContentCache(const FileEntry *Ent = 0) : Buffer(0), Entry(Ent), SourceLineCache(0), NumLines(0) {} ~ContentCache(); - + /// The copy ctor does not allow copies where source object has either /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory /// is not transfered, so this is a logical error. @@ -106,14 +106,14 @@ namespace SrcMgr { assert (RHS.Buffer == 0 && RHS.SourceLineCache == 0 && "Passed ContentCache object cannot own a buffer."); - - NumLines = RHS.NumLines; + + NumLines = RHS.NumLines; } - + private: // Disable assignments. - ContentCache &operator=(const ContentCache& RHS); - }; + ContentCache &operator=(const ContentCache& RHS); + }; /// FileInfo - Information about a FileID, basically just the logical file /// that it represents and include stack information. @@ -128,7 +128,7 @@ namespace SrcMgr { /// IncludeLoc - The location of the #include that brought in this file. /// This is an invalid SLOC for the main file (top of the #include chain). unsigned IncludeLoc; // Really a SourceLocation - + /// Data - This contains the ContentCache* and the bits indicating the /// characteristic of the file and whether it has #line info, all bitmangled /// together. @@ -145,39 +145,39 @@ namespace SrcMgr { X.Data |= (unsigned)FileCharacter; return X; } - + SourceLocation getIncludeLoc() const { return SourceLocation::getFromRawEncoding(IncludeLoc); } const ContentCache* getContentCache() const { return reinterpret_cast(Data & ~7UL); } - + /// getCharacteristic - Return whether this is a system header or not. - CharacteristicKind getFileCharacteristic() const { + CharacteristicKind getFileCharacteristic() const { return (CharacteristicKind)(Data & 3); } /// hasLineDirectives - Return true if this FileID has #line directives in /// it. bool hasLineDirectives() const { return (Data & 4) != 0; } - + /// setHasLineDirectives - Set the flag that indicates that this FileID has /// line table entries associated with it. void setHasLineDirectives() { Data |= 4; } }; - + /// InstantiationInfo - Each InstantiationInfo encodes the Instantiation /// location - where the token was ultimately instantiated, and the /// SpellingLoc - where the actual character data for the token came from. class InstantiationInfo { // Really these are all SourceLocations. - + /// SpellingLoc - Where the spelling for the token can be found. unsigned SpellingLoc; - + /// InstantiationLocStart/InstantiationLocEnd - In a macro expansion, these /// indicate the start and end of the instantiation. In object-like macros, /// these will be the same. In a function-like macro instantiation, the @@ -193,12 +193,12 @@ namespace SrcMgr { SourceLocation getInstantiationLocEnd() const { return SourceLocation::getFromRawEncoding(InstantiationLocEnd); } - + std::pair getInstantiationLocRange() const { return std::make_pair(getInstantiationLocStart(), getInstantiationLocEnd()); } - + /// get - Return a InstantiationInfo for an expansion. IL specifies /// the instantiation location (where the macro is expanded), and SL /// specifies the spelling location (where the characters from the token @@ -213,7 +213,7 @@ namespace SrcMgr { return X; } }; - + /// SLocEntry - This is a discriminated union of FileInfo and /// InstantiationInfo. SourceManager keeps an array of these objects, and /// they are uniquely identified by the FileID datatype. @@ -225,10 +225,10 @@ namespace SrcMgr { }; public: unsigned getOffset() const { return Offset >> 1; } - + bool isInstantiation() const { return Offset & 1; } bool isFile() const { return !isInstantiation(); } - + const FileInfo &getFile() const { assert(isFile() && "Not a file SLocEntry!"); return File; @@ -238,7 +238,7 @@ namespace SrcMgr { assert(isInstantiation() && "Not an instantiation SLocEntry!"); return Instantiation; } - + static SLocEntry get(unsigned Offset, const FileInfo &FI) { SLocEntry E; E.Offset = Offset << 1; @@ -277,18 +277,18 @@ public: /// location specifies where it was expanded. class SourceManager { mutable llvm::BumpPtrAllocator ContentCacheAlloc; - + /// FileInfos - Memoized information about all of the files tracked by this /// SourceManager. This set allows us to merge ContentCache entries based /// on their FileEntry*. All ContentCache objects will thus have unique, - /// non-null, FileEntry pointers. + /// non-null, FileEntry pointers. llvm::DenseMap FileInfos; - + /// MemBufferInfos - Information about various memory buffers that we have /// read in. All FileEntry* within the stored ContentCache objects are NULL, /// as they do not refer to a file. std::vector MemBufferInfos; - + /// SLocEntryTable - This is an array of SLocEntry's that we have created. /// FileID is an index into this vector. This array is sorted by the offset. std::vector SLocEntryTable; @@ -308,49 +308,49 @@ class SourceManager { /// LastFileIDLookup records the last FileID looked up or created, because it /// is very common to look up many tokens from the same file. mutable FileID LastFileIDLookup; - + /// LineTable - This holds information for #line directives. It is referenced /// by indices from SLocEntryTable. LineTableInfo *LineTable; - + /// LastLineNo - These ivars serve as a cache used in the getLineNumber /// method which is used to speedup getLineNumber calls to nearby locations. mutable FileID LastLineNoFileIDQuery; mutable SrcMgr::ContentCache *LastLineNoContentCache; mutable unsigned LastLineNoFilePos; mutable unsigned LastLineNoResult; - + /// MainFileID - The file ID for the main source file of the translation unit. FileID MainFileID; // Statistics for -print-stats. mutable unsigned NumLinearScans, NumBinaryProbes; - + // Cache results for the isBeforeInTranslationUnit method. mutable FileID LastLFIDForBeforeTUCheck; mutable FileID LastRFIDForBeforeTUCheck; mutable bool LastResForBeforeTUCheck; - + // SourceManager doesn't support copy construction. explicit SourceManager(const SourceManager&); - void operator=(const SourceManager&); + void operator=(const SourceManager&); public: - SourceManager() - : ExternalSLocEntries(0), LineTable(0), NumLinearScans(0), + SourceManager() + : ExternalSLocEntries(0), LineTable(0), NumLinearScans(0), NumBinaryProbes(0) { clearIDTables(); } ~SourceManager(); - + void clearIDTables(); - + //===--------------------------------------------------------------------===// // MainFileID creation and querying methods. //===--------------------------------------------------------------------===// /// getMainFileID - Returns the FileID of the main source file. FileID getMainFileID() const { return MainFileID; } - + /// createMainFileID - Create the FileID for the main source file. FileID createMainFileID(const FileEntry *SourceFile, SourceLocation IncludePos) { @@ -358,15 +358,15 @@ public: MainFileID = createFileID(SourceFile, IncludePos, SrcMgr::C_User); return MainFileID; } - + //===--------------------------------------------------------------------===// // Methods to create new FileID's and instantiations. //===--------------------------------------------------------------------===// - + /// createFileID - Create a new FileID that represents the specified file /// being #included from the specified IncludePosition. This returns 0 on /// error and translates NULL into standard input. - /// PreallocateID should be non-zero to specify which a pre-allocated, + /// PreallocateID should be non-zero to specify which a pre-allocated, /// lazily computed source location is being filled in by this operation. FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, @@ -376,7 +376,7 @@ public: if (IR == 0) return FileID(); // Error opening file? return createFileID(IR, IncludePos, FileCharacter, PreallocatedID, Offset); } - + /// createFileIDForMemBuffer - Create a new FileID that represents the /// specified memory buffer. This does no caching of the buffer and takes /// ownership of the MemoryBuffer, so only pass a MemoryBuffer to this once. @@ -386,7 +386,7 @@ public: return createFileID(createMemBufferContentCache(Buffer), SourceLocation(), SrcMgr::C_User, PreallocatedID, Offset); } - + /// createMainFileIDForMembuffer - Create the FileID for a memory buffer /// that will represent the FileID for the main source. One example /// of when this would be used is when the main source is read from STDIN. @@ -405,31 +405,31 @@ public: unsigned TokLength, unsigned PreallocatedID = 0, unsigned Offset = 0); - + //===--------------------------------------------------------------------===// // FileID manipulation methods. //===--------------------------------------------------------------------===// - + /// getBuffer - Return the buffer for the specified FileID. /// const llvm::MemoryBuffer *getBuffer(FileID FID) const { return getSLocEntry(FID).getFile().getContentCache()->getBuffer(); } - + /// getFileEntryForID - Returns the FileEntry record for the provided FileID. const FileEntry *getFileEntryForID(FileID FID) const { return getSLocEntry(FID).getFile().getContentCache()->Entry; } - + /// getBufferData - Return a pointer to the start and end of the source buffer /// data for the specified FileID. std::pair getBufferData(FileID FID) const; - - + + //===--------------------------------------------------------------------===// // SourceLocation manipulation methods. //===--------------------------------------------------------------------===// - + /// getFileID - Return the FileID for a SourceLocation. This is a very /// hot method that is used for all SourceManager queries that start with a /// SourceLocation object. It is responsible for finding the entry in @@ -437,14 +437,14 @@ public: /// FileID getFileID(SourceLocation SpellingLoc) const { unsigned SLocOffset = SpellingLoc.getOffset(); - + // If our one-entry cache covers this offset, just return it. if (isOffsetInFileID(LastFileIDLookup, SLocOffset)) return LastFileIDLookup; return getFileIDSlow(SLocOffset); } - + /// getLocForStartOfFile - Return the source location corresponding to the /// first byte of the specified file. SourceLocation getLocForStartOfFile(FileID FID) const { @@ -453,7 +453,7 @@ public: unsigned FileOffset = getSLocEntry(FID).getOffset(); return SourceLocation::getFileLoc(FileOffset); } - + /// getInstantiationLoc - Given a SourceLocation object, return the /// instantiation location referenced by the ID. SourceLocation getInstantiationLoc(SourceLocation Loc) const { @@ -462,18 +462,18 @@ public: if (Loc.isFileID()) return Loc; return getInstantiationLocSlowCase(Loc); } - + /// getImmediateInstantiationRange - Loc is required to be an instantiation /// location. Return the start/end of the instantiation information. std::pair getImmediateInstantiationRange(SourceLocation Loc) const; - + /// getInstantiationRange - Given a SourceLocation object, return the /// range of tokens covered by the instantiation in the ultimate file. std::pair getInstantiationRange(SourceLocation Loc) const; - - + + /// getSpellingLoc - Given a SourceLocation object, return the spelling /// location referenced by the ID. This is the place where the characters /// that make up the lexed token can be found. @@ -483,12 +483,12 @@ public: if (Loc.isFileID()) return Loc; return getSpellingLocSlowCase(Loc); } - + /// getImmediateSpellingLoc - Given a SourceLocation object, return the /// spelling location referenced by the ID. This is the first level down /// towards the place where the characters that make up the lexed token can be /// found. This should not generally be used by clients. - SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const; + SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const; /// getDecomposedLoc - Decompose the specified location into a raw FileID + /// Offset pair. The first element is the FileID, the second is the @@ -497,7 +497,7 @@ public: FileID FID = getFileID(Loc); return std::make_pair(FID, Loc.getOffset()-getSLocEntry(FID).getOffset()); } - + /// getDecomposedInstantiationLoc - Decompose the specified location into a /// raw FileID + Offset pair. If the location is an instantiation record, /// walk through it until we find the final location instantiated. @@ -505,11 +505,11 @@ public: getDecomposedInstantiationLoc(SourceLocation Loc) const { FileID FID = getFileID(Loc); const SrcMgr::SLocEntry *E = &getSLocEntry(FID); - + unsigned Offset = Loc.getOffset()-E->getOffset(); if (Loc.isFileID()) return std::make_pair(FID, Offset); - + return getDecomposedInstantiationLocSlowCase(E, Offset); } @@ -520,29 +520,29 @@ public: getDecomposedSpellingLoc(SourceLocation Loc) const { FileID FID = getFileID(Loc); const SrcMgr::SLocEntry *E = &getSLocEntry(FID); - + unsigned Offset = Loc.getOffset()-E->getOffset(); if (Loc.isFileID()) return std::make_pair(FID, Offset); return getDecomposedSpellingLocSlowCase(E, Offset); - } - + } + /// getFileOffset - This method returns the offset from the start /// of the file that the specified SourceLocation represents. This is not very /// meaningful for a macro ID. unsigned getFileOffset(SourceLocation SpellingLoc) const { return getDecomposedLoc(SpellingLoc).second; } - - + + //===--------------------------------------------------------------------===// // Queries about the code at a SourceLocation. //===--------------------------------------------------------------------===// - + /// getCharacterData - Return a pointer to the start of the specified location /// in the appropriate spelling MemoryBuffer. const char *getCharacterData(SourceLocation SL) const; - + /// getColumnNumber - Return the column # for the specified file position. /// This is significantly cheaper to compute than the line number. This /// returns zero if the column number isn't known. This may only be called on @@ -551,24 +551,24 @@ public: unsigned getColumnNumber(FileID FID, unsigned FilePos) const; unsigned getSpellingColumnNumber(SourceLocation Loc) const; unsigned getInstantiationColumnNumber(SourceLocation Loc) const; - - + + /// getLineNumber - Given a SourceLocation, return the spelling line number /// 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 getLineNumber(FileID FID, unsigned FilePos) const; - + unsigned getInstantiationLineNumber(SourceLocation Loc) const; unsigned getSpellingLineNumber(SourceLocation Loc) const; - + /// Return the filename or buffer identifier of the buffer the location is in. /// Note that this name does not respect #line directives. Use getPresumedLoc /// for normal clients. const char *getBufferName(SourceLocation Loc) const; - + /// getFileCharacteristic - return the file characteristic of the specified - /// source location, indicating whether this is a normal file, a system + /// source location, indicating whether this is a normal file, a system /// header, or an "implicit extern C" system header. /// /// This state can be modified with flags on GNU linemarker directives like: @@ -576,7 +576,7 @@ public: /// which changes all source locations in the current file after that to be /// considered to be from a system header. SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const; - + /// getPresumedLoc - This method returns the "presumed" location of a /// SourceLocation specifies. A "presumed location" can be modified by #line /// or GNU line marker directives. This provides a view on the data that a @@ -585,44 +585,44 @@ public: /// Note that a presumed location is always given as the instantiation point /// of an instantiation location, not at the spelling location. PresumedLoc getPresumedLoc(SourceLocation Loc) const; - + /// isFromSameFile - Returns true if both SourceLocations correspond to /// the same file. bool isFromSameFile(SourceLocation Loc1, SourceLocation Loc2) const { return getFileID(Loc1) == getFileID(Loc2); } - + /// isFromMainFile - Returns true if the file of provided SourceLocation is /// the main file. bool isFromMainFile(SourceLocation Loc) const { return getFileID(Loc) == getMainFileID(); - } - + } + /// isInSystemHeader - Returns if a SourceLocation is in a system header. bool isInSystemHeader(SourceLocation Loc) const { return getFileCharacteristic(Loc) != SrcMgr::C_User; } - + /// isInExternCSystemHeader - Returns if a SourceLocation is in an "extern C" /// system header. bool isInExternCSystemHeader(SourceLocation Loc) const { return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem; } - + //===--------------------------------------------------------------------===// // Line Table Manipulation Routines //===--------------------------------------------------------------------===// - + /// getLineTableFilenameID - Return the uniqued ID for the specified filename. - /// + /// unsigned getLineTableFilenameID(const char *Ptr, unsigned Len); - + /// AddLineNote - Add a line note to the line table for the FileID and offset /// specified by Loc. If FilenameID is -1, it is considered to be /// unspecified. void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID); void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID, - bool IsFileEntry, bool IsFileExit, + bool IsFileEntry, bool IsFileExit, bool IsSystemHeader, bool IsExternCHeader); /// \brief Determine if the source manager has a line table. @@ -641,7 +641,7 @@ public: /// be based upon the first inclusion. SourceLocation getLocation(const FileEntry *SourceFile, unsigned Line, unsigned Col) const; - + /// \brief Determines the order of 2 source locations in the translation unit. /// /// \returns true if LHS source location comes before RHS, false otherwise. @@ -657,22 +657,22 @@ public: /// void PrintStats() const; - // Iteration over the source location entry table. + // Iteration over the source location entry table. typedef std::vector::const_iterator sloc_entry_iterator; - sloc_entry_iterator sloc_entry_begin() const { - return SLocEntryTable.begin(); + sloc_entry_iterator sloc_entry_begin() const { + return SLocEntryTable.begin(); } - sloc_entry_iterator sloc_entry_end() const { - return SLocEntryTable.end(); + sloc_entry_iterator sloc_entry_end() const { + return SLocEntryTable.end(); } unsigned sloc_entry_size() const { return SLocEntryTable.size(); } const SrcMgr::SLocEntry &getSLocEntry(FileID FID) const { assert(FID.ID < SLocEntryTable.size() && "Invalid id"); - if (ExternalSLocEntries && + if (ExternalSLocEntries && FID.ID < SLocEntryLoaded.size() && !SLocEntryLoaded[FID.ID]) ExternalSLocEntries->ReadSLocEntry(FID.ID); @@ -698,14 +698,14 @@ private: const SrcMgr::SLocEntry &Entry = getSLocEntry(FID); // If the entry is after the offset, it can't contain it. if (SLocOffset < Entry.getOffset()) return false; - + // If this is the last entry than it does. Otherwise, the entry after it // has to not include it. if (FID.ID+1 == SLocEntryTable.size()) return true; return SLocOffset < getSLocEntry(FileID::get(FID.ID+1)).getOffset(); } - + /// createFileID - Create a new fileID for the specified ContentCache and /// include position. This works regardless of whether the ContentCache /// corresponds to a file or some other input source. @@ -714,15 +714,15 @@ private: SrcMgr::CharacteristicKind DirCharacter, unsigned PreallocatedID = 0, unsigned Offset = 0); - + const SrcMgr::ContentCache * getOrCreateContentCache(const FileEntry *SourceFile); /// createMemBufferContentCache - Create a new ContentCache for the specified /// memory buffer. - const SrcMgr::ContentCache* + const SrcMgr::ContentCache* createMemBufferContentCache(const llvm::MemoryBuffer *Buf); - + FileID getFileIDSlow(unsigned SLocOffset) const; SourceLocation getInstantiationLocSlowCase(SourceLocation Loc) const; @@ -730,7 +730,7 @@ private: std::pair getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E, - unsigned Offset) const; + unsigned Offset) const; std::pair getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, unsigned Offset) const; diff --git a/clang/include/clang/Basic/SourceManagerInternals.h b/clang/include/clang/Basic/SourceManagerInternals.h index 0bcb68e4601ddc5eae7cd66ab7030194a096d767..258989cb7787e0213adea6db57f7c40756be4723 100644 --- a/clang/include/clang/Basic/SourceManagerInternals.h +++ b/clang/include/clang/Basic/SourceManagerInternals.h @@ -28,22 +28,22 @@ namespace clang { struct LineEntry { /// FileOffset - The offset in this file that the line entry occurs at. unsigned FileOffset; - + /// LineNo - The presumed line number of this line entry: #line 4. unsigned LineNo; - + /// FilenameID - The ID of the filename identified by this line entry: /// #line 4 "foo.c". This is -1 if not specified. int FilenameID; - - /// Flags - Set the 0 if no flags, 1 if a system header, + + /// Flags - Set the 0 if no flags, 1 if a system header, SrcMgr::CharacteristicKind FileKind; - + /// IncludeOffset - This is the offset of the virtual include stack location, /// which is manipulated by GNU linemarker directives. If this is 0 then /// there is no virtual #includer. unsigned IncludeOffset; - + static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset) { @@ -70,7 +70,7 @@ inline bool operator<(const LineEntry &E, unsigned Offset) { inline bool operator<(unsigned Offset, const LineEntry &E) { return Offset < E.FileOffset; } - + /// LineTableInfo - This class is used to hold and unique data used to /// represent #line information. class LineTableInfo { @@ -81,22 +81,22 @@ class LineTableInfo { /// to string. llvm::StringMap FilenameIDs; std::vector*> FilenamesByID; - + /// LineEntries - This is a map from FileIDs to a list of line entries (sorted /// by the offset they occur in the file. std::map > LineEntries; public: LineTableInfo() { } - + void clear() { FilenameIDs.clear(); FilenamesByID.clear(); LineEntries.clear(); } - + ~LineTableInfo() {} - + unsigned getLineTableFilenameID(const char *Ptr, unsigned Len); const char *getFilename(unsigned ID) const { assert(ID < FilenamesByID.size() && "Invalid FilenameID"); @@ -110,7 +110,7 @@ public: unsigned LineNo, int FilenameID, unsigned EntryExit, SrcMgr::CharacteristicKind FileKind); - + /// FindNearestLineEntry - Find the line entry nearest to FID that is before /// it. If there is no line entry before Offset in FID, return null. const LineEntry *FindNearestLineEntry(unsigned FID, unsigned Offset); diff --git a/clang/include/clang/Basic/TargetInfo.h b/clang/include/clang/Basic/TargetInfo.h index f48d1a3a60e86d84c10fd12ffe8391f382d1174b..f8dca87a26056ea65018380c00ff9b7b5442d1bb 100644 --- a/clang/include/clang/Basic/TargetInfo.h +++ b/clang/include/clang/Basic/TargetInfo.h @@ -34,7 +34,7 @@ class SourceLocation; class SourceManager; class LangOptions; namespace Builtin { struct Info; } - + /// TargetInfo - This class exposes information about the current target. /// class TargetInfo { @@ -61,8 +61,8 @@ protected: // TargetInfo Constructor. Default initializes all fields. TargetInfo(const std::string &T); - -public: + +public: /// CreateTargetInfo - Return the target info object for the specified target /// triple. static TargetInfo* CreateTargetInfo(const std::string &Triple); @@ -105,35 +105,35 @@ public: uint64_t getPointerAlign(unsigned AddrSpace) const { return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace); } - + /// getBoolWidth/Align - Return the size of '_Bool' and C++ 'bool' for this /// target, in bits. unsigned getBoolWidth(bool isWide = false) const { return 8; } // FIXME unsigned getBoolAlign(bool isWide = false) const { return 8; } // FIXME - + unsigned getCharWidth() const { return 8; } // FIXME unsigned getCharAlign() const { return 8; } // FIXME - + /// getShortWidth/Align - Return the size of 'signed short' and - /// 'unsigned short' for this target, in bits. + /// 'unsigned short' for this target, in bits. unsigned getShortWidth() const { return 16; } // FIXME unsigned getShortAlign() const { return 16; } // FIXME - + /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for /// this target, in bits. unsigned getIntWidth() const { return IntWidth; } unsigned getIntAlign() const { return IntAlign; } - + /// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' /// for this target, in bits. unsigned getLongWidth() const { return LongWidth; } unsigned getLongAlign() const { return LongAlign; } - + /// getLongLongWidth/Align - Return the size of 'signed long long' and /// 'unsigned long long' for this target, in bits. unsigned getLongLongWidth() const { return LongLongWidth; } unsigned getLongLongAlign() const { return LongLongAlign; } - + /// getWCharWidth/Align - Return the size of 'wchar_t' for this target, in /// bits. unsigned getWCharWidth() const { return WCharWidth; } @@ -166,13 +166,13 @@ public: const llvm::fltSemantics &getLongDoubleFormat() const { return *LongDoubleFormat; } - + /// getIntMaxTWidth - Return the size of intmax_t and uintmax_t for this - /// target, in bits. + /// target, in bits. unsigned getIntMaxTWidth() const { return IntMaxTWidth; } - + /// getUserLabelPrefix - This returns the default value of the /// __USER_LABEL_PREFIX__ macro, which is the prefix given to user symbols by /// default. On most platforms this is "_", but it is "" on some, and "." on @@ -180,22 +180,22 @@ public: const char *getUserLabelPrefix() const { return UserLabelPrefix; } - + /// getTypeName - Return the user string for the specified integer type enum. /// For example, SignedShort -> "short". static const char *getTypeName(IntType T); - + ///===---- Other target property query methods --------------------------===// - + /// getTargetDefines - Appends the target-specific #define values for this /// target set to the specified buffer. virtual void getTargetDefines(const LangOptions &Opts, std::vector &DefineBuffer) const = 0; - + /// getTargetBuiltins - Return information about target-specific builtins for /// the current primary target, and info about which builtins are non-portable /// across the current set of primary and secondary targets. - virtual void getTargetBuiltins(const Builtin::Info *&Records, + virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const = 0; /// getVAListDeclaration - Return the declaration to use for @@ -210,7 +210,7 @@ public: // getNormalizedGCCRegisterName - Returns the "normalized" GCC register name. // For example, on x86 it will return "ax" when "eax" is passed in. const char *getNormalizedGCCRegisterName(const char *Name) const; - + struct ConstraintInfo { enum { CI_None = 0x00, @@ -221,7 +221,7 @@ public: }; unsigned Flags; int TiedOperand; - + std::string ConstraintStr; // constraint: "=rm" std::string Name; // Operand name: [foo] with no []'s. public: @@ -235,11 +235,11 @@ public: bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; } bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; } bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; } - + /// hasMatchingInput - Return true if this output operand has a matching /// (tied) input operand. bool hasMatchingInput() const { return (Flags & CI_HasMatchingInput) != 0; } - + /// hasTiedOperand() - Return true if this input operand is a matching /// constraint that ties it to an output operand. If this returns true, /// then getTiedOperand will indicate which output operand this is tied to. @@ -248,12 +248,12 @@ public: assert(hasTiedOperand() && "Has no tied operand!"); return (unsigned)TiedOperand; } - + void setIsReadWrite() { Flags |= CI_ReadWrite; } void setAllowsMemory() { Flags |= CI_AllowsMemory; } void setAllowsRegister() { Flags |= CI_AllowsRegister; } void setHasMatchingInput() { Flags |= CI_HasMatchingInput; } - + /// setTiedOperand - Indicate that this is an input operand that is tied to /// the specified output operand. Copy over the various constraint /// information from the output. @@ -275,20 +275,20 @@ public: bool resolveSymbolicName(const char *&Name, ConstraintInfo *OutputConstraints, unsigned NumOutputs, unsigned &Index) const; - + virtual std::string convertConstraint(const char Constraint) const { return std::string(1, Constraint); } - + // Returns a string of target-specific clobbers, in LLVM format. virtual const char *getClobbers() const = 0; - + /// getTriple - Return the target triple of the primary target. const llvm::Triple &getTriple() const { return Triple; } - + const char *getTargetDescription() const { return DescriptionString; } @@ -302,30 +302,30 @@ public: /// getUnicodeStringSymbolPrefix - Get the default symbol prefix to /// use for string literals. - virtual const char *getUnicodeStringSymbolPrefix() const { + virtual const char *getUnicodeStringSymbolPrefix() const { return ".str"; } /// getUnicodeStringSection - Return the section to use for unicode /// string literals, or 0 if no special section is used. - virtual const char *getUnicodeStringSection() const { + virtual const char *getUnicodeStringSection() const { return 0; } /// getCFStringSection - Return the section to use for CFString /// literals, or 0 if no special section is used. - virtual const char *getCFStringSection() const { + virtual const char *getCFStringSection() const { return "__DATA,__cfstring"; } /// getCFStringDataSection - Return the section to use for the /// constant string data associated with a CFString literal, or 0 if /// no special section is used. - virtual const char *getCFStringDataSection() const { + virtual const char *getCFStringDataSection() const { return "__TEXT,__cstring,cstring_literals"; } - - + + /// isValidSectionSpecifier - This is an optional hook that targets can /// implement to perform semantic checking on attribute((section("foo"))) /// specifiers. In this case, "foo" is passed in to be checked. If the @@ -342,13 +342,13 @@ public: /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line - /// options. + /// options. virtual void getDefaultLangOptions(LangOptions &Opts) {} /// getDefaultFeatures - Get the default set of target features for /// the \args CPU; this should include all legal feature strings on /// the target. - virtual void getDefaultFeatures(const std::string &CPU, + virtual void getDefaultFeatures(const std::string &CPU, llvm::StringMap &Features) const { } @@ -387,11 +387,11 @@ protected: virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const { return PtrDiffType; } - virtual void getGCCRegNames(const char * const *&Names, + virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const = 0; - virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, + virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const = 0; - virtual bool validateAsmConstraint(const char *&Name, + virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const= 0; }; diff --git a/clang/include/clang/Basic/TokenKinds.h b/clang/include/clang/Basic/TokenKinds.h index 62a9e428bf210eac2c4554e3a058ae0cc29eafa1..85dc0671de62974b0fbf2155eb831d69f16d8042 100644 --- a/clang/include/clang/Basic/TokenKinds.h +++ b/clang/include/clang/Basic/TokenKinds.h @@ -29,7 +29,7 @@ enum TokenKind { /// PPKeywordKind - This provides a namespace for preprocessor keywords which /// start with a '#' at the beginning of the line. enum PPKeywordKind { -#define PPKEYWORD(X) pp_##X, +#define PPKEYWORD(X) pp_##X, #include "clang/Basic/TokenKinds.def" NUM_PP_KEYWORDS }; diff --git a/clang/include/clang/CodeGen/ModuleBuilder.h b/clang/include/clang/CodeGen/ModuleBuilder.h index 12b74d51473e221bb43e58ecfa5098148f70fd80..1871c8f206f3d408e8b9b5457962e6f94fa52f8f 100644 --- a/clang/include/clang/CodeGen/ModuleBuilder.h +++ b/clang/include/clang/CodeGen/ModuleBuilder.h @@ -26,13 +26,13 @@ namespace clang { class Diagnostic; class LangOptions; class CompileOptions; - + class CodeGenerator : public ASTConsumer { public: virtual llvm::Module* GetModule() = 0; - virtual llvm::Module* ReleaseModule() = 0; + virtual llvm::Module* ReleaseModule() = 0; }; - + CodeGenerator *CreateLLVMCodeGen(Diagnostic &Diags, const std::string &ModuleName, const CompileOptions &CO, diff --git a/clang/include/clang/Driver/Action.h b/clang/include/clang/Driver/Action.h index ceef189f7b7ef0e4d090a0b1fac66f26d110854c..679704c3958725430821dc902e370a35b3b7c57b 100644 --- a/clang/include/clang/Driver/Action.h +++ b/clang/include/clang/Driver/Action.h @@ -26,7 +26,7 @@ namespace clang { namespace driver { class Arg; -/// Action - Represent an abstract compilation step to perform. +/// Action - Represent an abstract compilation step to perform. /// /// An action represents an edge in the compilation graph; typically /// it is a job to transform an input using some tool. @@ -63,15 +63,15 @@ private: /// The output type of this action. types::ID Type; - + ActionList Inputs; protected: Action(ActionClass _Kind, types::ID _Type) : Kind(_Kind), Type(_Type) {} - Action(ActionClass _Kind, Action *Input, types::ID _Type) + Action(ActionClass _Kind, Action *Input, types::ID _Type) : Kind(_Kind), Type(_Type), Inputs(&Input, &Input + 1) {} - Action(ActionClass _Kind, const ActionList &_Inputs, types::ID _Type) - : Kind(_Kind), Type(_Type), Inputs(_Inputs) {} + Action(ActionClass _Kind, const ActionList &_Inputs, types::ID _Type) + : Kind(_Kind), Type(_Type), Inputs(_Inputs) {} public: virtual ~Action(); @@ -90,7 +90,7 @@ public: const_iterator begin() const { return Inputs.begin(); } const_iterator end() const { return Inputs.end(); } - static bool classof(const Action *) { return true; } + static bool classof(const Action *) { return true; } }; class InputAction : public Action { @@ -100,8 +100,8 @@ public: const Arg &getInputArg() const { return Input; } - static bool classof(const Action *A) { - return A->getKind() == InputClass; + static bool classof(const Action *A) { + return A->getKind() == InputClass; } static bool classof(const InputAction *) { return true; } }; @@ -116,8 +116,8 @@ public: const char *getArchName() const { return ArchName; } - static bool classof(const Action *A) { - return A->getKind() == BindArchClass; + static bool classof(const Action *A) { + return A->getKind() == BindArchClass; } static bool classof(const BindArchAction *) { return true; } }; @@ -128,9 +128,9 @@ protected: JobAction(ActionClass Kind, const ActionList &Inputs, types::ID Type); public: - static bool classof(const Action *A) { + static bool classof(const Action *A) { return (A->getKind() >= JobClassFirst && - A->getKind() <= JobClassLast); + A->getKind() <= JobClassLast); } static bool classof(const JobAction *) { return true; } }; @@ -139,7 +139,7 @@ class PreprocessJobAction : public JobAction { public: PreprocessJobAction(Action *Input, types::ID OutputType); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == PreprocessJobClass; } static bool classof(const PreprocessJobAction *) { return true; } @@ -149,7 +149,7 @@ class PrecompileJobAction : public JobAction { public: PrecompileJobAction(Action *Input, types::ID OutputType); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == PrecompileJobClass; } static bool classof(const PrecompileJobAction *) { return true; } @@ -159,7 +159,7 @@ class AnalyzeJobAction : public JobAction { public: AnalyzeJobAction(Action *Input, types::ID OutputType); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == AnalyzeJobClass; } static bool classof(const AnalyzeJobAction *) { return true; } @@ -169,7 +169,7 @@ class CompileJobAction : public JobAction { public: CompileJobAction(Action *Input, types::ID OutputType); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == CompileJobClass; } static bool classof(const CompileJobAction *) { return true; } @@ -179,7 +179,7 @@ class AssembleJobAction : public JobAction { public: AssembleJobAction(Action *Input, types::ID OutputType); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == AssembleJobClass; } static bool classof(const AssembleJobAction *) { return true; } @@ -189,7 +189,7 @@ class LinkJobAction : public JobAction { public: LinkJobAction(ActionList &Inputs, types::ID Type); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == LinkJobClass; } static bool classof(const LinkJobAction *) { return true; } @@ -199,7 +199,7 @@ class LipoJobAction : public JobAction { public: LipoJobAction(ActionList &Inputs, types::ID Type); - static bool classof(const Action *A) { + static bool classof(const Action *A) { return A->getKind() == LipoJobClass; } static bool classof(const LipoJobAction *) { return true; } diff --git a/clang/include/clang/Driver/Arg.h b/clang/include/clang/Driver/Arg.h index 6bed2b8cbdef3b7e5e0137e5ff7ab7091d4e089b..ebf40d45de4cbb7730ed28071e37e4ff55a121e0 100644 --- a/clang/include/clang/Driver/Arg.h +++ b/clang/include/clang/Driver/Arg.h @@ -49,7 +49,7 @@ namespace driver { /// The option this argument is an instance of. const Option *Opt; - + /// The argument this argument was derived from (during tool chain /// argument translation), if any. const Arg *BaseArg; @@ -66,7 +66,7 @@ namespace driver { protected: Arg(ArgClass Kind, const Option *Opt, unsigned Index, const Arg *BaseArg = 0); - + public: Arg(const Arg &); virtual ~Arg(); @@ -74,12 +74,12 @@ namespace driver { ArgClass getKind() const { return Kind; } const Option &getOption() const { return *Opt; } unsigned getIndex() const { return Index; } - + /// getBaseArg - Return the base argument which generated this /// arg; this is either the argument itself or the argument it was /// derived from during tool chain specific argument translation. - const Arg &getBaseArg() const { - return BaseArg ? *BaseArg : *this; + const Arg &getBaseArg() const { + return BaseArg ? *BaseArg : *this; } void setBaseArg(const Arg *_BaseArg) { BaseArg = _BaseArg; @@ -88,14 +88,14 @@ namespace driver { bool isClaimed() const { return getBaseArg().Claimed; } /// claim - Set the Arg claimed bit. - + // FIXME: We need to deal with derived arguments and set the bit // in the original argument; not the derived one. void claim() const { getBaseArg().Claimed = true; } virtual unsigned getNumValues() const = 0; virtual const char *getValue(const ArgList &Args, unsigned N=0) const = 0; - + /// render - Append the argument onto the given array as strings. virtual void render(const ArgList &Args, ArgStringList &Output) const = 0; @@ -105,7 +105,7 @@ namespace driver { /// (e.g., Xlinker). void renderAsInput(const ArgList &Args, ArgStringList &Output) const; - static bool classof(const Arg *) { return true; } + static bool classof(const Arg *) { return true; } void dump() const; @@ -124,8 +124,8 @@ namespace driver { virtual unsigned getNumValues() const { return 0; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; - static bool classof(const Arg *A) { - return A->getKind() == Arg::FlagClass; + static bool classof(const Arg *A) { + return A->getKind() == Arg::FlagClass; } static bool classof(const FlagArg *) { return true; } }; @@ -140,8 +140,8 @@ namespace driver { virtual unsigned getNumValues() const { return 1; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; - static bool classof(const Arg *A) { - return A->getKind() == Arg::PositionalClass; + static bool classof(const Arg *A) { + return A->getKind() == Arg::PositionalClass; } static bool classof(const PositionalArg *) { return true; } }; @@ -157,8 +157,8 @@ namespace driver { virtual unsigned getNumValues() const { return 1; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; - static bool classof(const Arg *A) { - return A->getKind() == Arg::JoinedClass; + static bool classof(const Arg *A) { + return A->getKind() == Arg::JoinedClass; } static bool classof(const JoinedArg *) { return true; } }; @@ -169,7 +169,7 @@ namespace driver { unsigned NumValues; public: - SeparateArg(const Option *Opt, unsigned Index, unsigned NumValues, + SeparateArg(const Option *Opt, unsigned Index, unsigned NumValues, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; @@ -177,8 +177,8 @@ namespace driver { virtual unsigned getNumValues() const { return NumValues; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; - static bool classof(const Arg *A) { - return A->getKind() == Arg::SeparateClass; + static bool classof(const Arg *A) { + return A->getKind() == Arg::SeparateClass; } static bool classof(const SeparateArg *) { return true; } }; @@ -193,7 +193,7 @@ namespace driver { std::vector Values; public: - CommaJoinedArg(const Option *Opt, unsigned Index, const char *Str, + CommaJoinedArg(const Option *Opt, unsigned Index, const char *Str, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; @@ -201,8 +201,8 @@ namespace driver { virtual unsigned getNumValues() const { return Values.size(); } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; - static bool classof(const Arg *A) { - return A->getKind() == Arg::CommaJoinedClass; + static bool classof(const Arg *A) { + return A->getKind() == Arg::CommaJoinedClass; } static bool classof(const CommaJoinedArg *) { return true; } }; @@ -211,7 +211,7 @@ namespace driver { /// values. class JoinedAndSeparateArg : public Arg { public: - JoinedAndSeparateArg(const Option *Opt, unsigned Index, + JoinedAndSeparateArg(const Option *Opt, unsigned Index, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; @@ -219,8 +219,8 @@ namespace driver { virtual unsigned getNumValues() const { return 2; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; - static bool classof(const Arg *A) { - return A->getKind() == Arg::JoinedAndSeparateClass; + static bool classof(const Arg *A) { + return A->getKind() == Arg::JoinedAndSeparateClass; } static bool classof(const JoinedAndSeparateArg *) { return true; } }; diff --git a/clang/include/clang/Driver/ArgList.h b/clang/include/clang/Driver/ArgList.h index ea8846a6e9f056e5d95d4bae06a8051d97be0ec7..81588a599440129d9224c3a02a8d53e6800ad3ed 100644 --- a/clang/include/clang/Driver/ArgList.h +++ b/clang/include/clang/Driver/ArgList.h @@ -65,17 +65,17 @@ namespace driver { const_iterator begin() const { return Args.begin(); } const_iterator end() const { return Args.end(); } - + const_reverse_iterator rbegin() const { return Args.rbegin(); } const_reverse_iterator rend() const { return Args.rend(); } /// hasArg - Does the arg list contain any option matching \arg Id. /// /// \arg Claim Whether the argument should be claimed, if it exists. - bool hasArg(options::ID Id, bool Claim=true) const { + bool hasArg(options::ID Id, bool Claim=true) const { return getLastArg(Id, Claim) != 0; } - bool hasArg(options::ID Id0, options::ID Id1, bool Claim=true) const { + bool hasArg(options::ID Id0, options::ID Id1, bool Claim=true) const { return getLastArg(Id0, Id1, Claim) != 0; } @@ -105,15 +105,15 @@ namespace driver { /// AddAllArgs - Render all arguments matching the given ids. void AddAllArgs(ArgStringList &Output, options::ID Id0) const; - void AddAllArgs(ArgStringList &Output, options::ID Id0, + void AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1) const; - void AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1, + void AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1, options::ID Id2) const; /// AddAllArgValues - Render the argument values of all arguments /// matching the given ids. void AddAllArgValues(ArgStringList &Output, options::ID Id0) const; - void AddAllArgValues(ArgStringList &Output, options::ID Id0, + void AddAllArgValues(ArgStringList &Output, options::ID Id0, options::ID Id1) const; /// AddAllArgsTranslated - Render all the arguments matching the @@ -123,7 +123,7 @@ namespace driver { /// \param Joined - If true, render the argument as joined with /// the option specifier. void AddAllArgsTranslated(ArgStringList &Output, options::ID Id0, - const char *Translation, + const char *Translation, bool Joined = false) const; /// ClaimAllArgs - Claim all arguments which match the given @@ -168,8 +168,8 @@ namespace driver { InputArgList(const ArgList &); ~InputArgList(); - virtual const char *getArgString(unsigned Index) const { - return ArgStrings[Index]; + virtual const char *getArgString(unsigned Index) const { + return ArgStrings[Index]; } /// getNumInputArgStrings - Return the number of original input @@ -212,7 +212,7 @@ namespace driver { ~DerivedArgList(); virtual const char *getArgString(unsigned Index) const { - return BaseArgs.getArgString(Index); + return BaseArgs.getArgString(Index); } /// @name Arg Synthesis @@ -226,17 +226,17 @@ namespace driver { /// MakePositionalArg - Construct a new Positional arg for the /// given option \arg Id, with the provided \arg Value. - Arg *MakePositionalArg(const Arg *BaseArg, const Option *Opt, + Arg *MakePositionalArg(const Arg *BaseArg, const Option *Opt, const char *Value) const; /// MakeSeparateArg - Construct a new Positional arg for the /// given option \arg Id, with the provided \arg Value. - Arg *MakeSeparateArg(const Arg *BaseArg, const Option *Opt, + Arg *MakeSeparateArg(const Arg *BaseArg, const Option *Opt, const char *Value) const; /// MakeJoinedArg - Construct a new Positional arg for the /// given option \arg Id, with the provided \arg Value. - Arg *MakeJoinedArg(const Arg *BaseArg, const Option *Opt, + Arg *MakeJoinedArg(const Arg *BaseArg, const Option *Opt, const char *Value) const; /// @} diff --git a/clang/include/clang/Driver/Compilation.h b/clang/include/clang/Driver/Compilation.h index 6414ef13692b053362ce0011ee1588a1b1a5315e..9e026b91ef5660d5e09f839848bf98c6ab6714cd 100644 --- a/clang/include/clang/Driver/Compilation.h +++ b/clang/include/clang/Driver/Compilation.h @@ -56,7 +56,7 @@ class Compilation { ArgStringList ResultFiles; public: - Compilation(const Driver &D, const ToolChain &DefaultToolChain, + Compilation(const Driver &D, const ToolChain &DefaultToolChain, InputArgList *Args); ~Compilation(); @@ -83,8 +83,8 @@ public: /// addTempFile - Add a file to remove on exit, and returns its /// argument. - const char *addTempFile(const char *Name) { - TempFiles.push_back(Name); + const char *addTempFile(const char *Name) { + TempFiles.push_back(Name); return Name; } @@ -99,7 +99,7 @@ public: /// /// \param IssueErrors - Report failures as errors. /// \return Whether all files were removed successfully. - bool CleanupFileList(const ArgStringList &Files, + bool CleanupFileList(const ArgStringList &Files, bool IssueErrors=false) const; /// PrintJob - Print one job in -### format. @@ -108,7 +108,7 @@ public: /// \param J - The job to print. /// \param Terminator - A string to print at the end of the line. /// \param Quote - Should separate arguments be quoted. - void PrintJob(llvm::raw_ostream &OS, const Job &J, + void PrintJob(llvm::raw_ostream &OS, const Job &J, const char *Terminator, bool Quote) const; /// ExecuteCommand - Execute an actual command. diff --git a/clang/include/clang/Driver/Driver.h b/clang/include/clang/Driver/Driver.h index bdc6f3b18a6e104078986c59598a3031701235aa..c18d9e0c460b32442fc78562b476730d7cb03ee7 100644 --- a/clang/include/clang/Driver/Driver.h +++ b/clang/include/clang/Driver/Driver.h @@ -55,11 +55,11 @@ public: public: /// The name the driver was invoked as. std::string Name; - + /// The path the driver executable was in, as invoked from the /// command line. std::string Dir; - + /// Default host triple. std::string DefaultHostTriple; @@ -75,7 +75,7 @@ public: /// Whether the driver should follow g++ like behavior. bool CCCIsCXX : 1; - + /// Echo commands while executing (in -v style). bool CCCEcho : 1; @@ -107,7 +107,7 @@ private: /// Certain options suppress the 'no input files' warning. bool SuppressMissingInputWarning : 1; - + std::list TempFiles; std::list ResultFiles; @@ -243,7 +243,7 @@ public: /// \param BaseInput - The original input file that this action was /// triggered by. /// \param AtTopLevel - Whether this is a "top-level" action. - const char *GetNamedOutputPath(Compilation &C, + const char *GetNamedOutputPath(Compilation &C, const JobAction &JA, const char *BaseInput, bool AtTopLevel) const; @@ -253,14 +253,14 @@ public: /// /// GCC goes to extra lengths here to be a bit more robust. std::string GetTemporaryPath(const char *Suffix) const; - + /// GetHostInfo - Construct a new host info object for the given /// host triple. const HostInfo *GetHostInfo(const char *HostTriple) const; /// ShouldUseClangCompilar - Should the clang compiler be used to /// handle this action. - bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, + bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, const llvm::Triple &ArchName) const; /// @} @@ -272,7 +272,7 @@ public: /// \return True if the entire string was parsed (9.2), or all /// groups were parsed (10.3.5extrastuff). HadExtra is true if all /// groups were parsed but extra characters remain at the end. - static bool GetReleaseVersion(const char *Str, unsigned &Major, + static bool GetReleaseVersion(const char *Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra); }; diff --git a/clang/include/clang/Driver/DriverDiagnostic.h b/clang/include/clang/Driver/DriverDiagnostic.h index 705c3422cda3942691995b967e447404a85cb1b5..d4a9da7b6d8028115dcab7f059ab54e54c866baa 100644 --- a/clang/include/clang/Driver/DriverDiagnostic.h +++ b/clang/include/clang/Driver/DriverDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define DRIVERSTART diff --git a/clang/include/clang/Driver/HostInfo.h b/clang/include/clang/Driver/HostInfo.h index caffaeca36651f3f4c89fccff2abc2704f67f849..bf67c343f3266eb6cdc998cecccdfae7fa13a1c3 100644 --- a/clang/include/clang/Driver/HostInfo.h +++ b/clang/include/clang/Driver/HostInfo.h @@ -22,7 +22,7 @@ namespace driver { /// HostInfo - Config information about a particular host which may interact /// with driver behavior. -/// +/// /// The host information is used for controlling the parts of the driver which /// interact with the platform the driver is ostensibly being run from. For /// testing purposes, the HostInfo used by the driver may differ from the actual @@ -38,7 +38,7 @@ public: virtual ~HostInfo(); const Driver &getDriver() const { return TheDriver; } - + const llvm::Triple& getTriple() const { return Triple; } std::string getArchName() const { return Triple.getArchName(); } std::string getPlatformName() const { return Triple.getVendorName(); } @@ -64,23 +64,23 @@ public: // FIXME: Pin down exactly what the HostInfo is allowed to use Args // for here. Currently this is for -m32 / -m64 defaulting. - virtual ToolChain *CreateToolChain(const ArgList &Args, + virtual ToolChain *CreateToolChain(const ArgList &Args, const char *ArchName=0) const = 0; }; const HostInfo *createAuroraUXHostInfo(const Driver &D, const llvm::Triple& Triple); -const HostInfo *createDarwinHostInfo(const Driver &D, +const HostInfo *createDarwinHostInfo(const Driver &D, const llvm::Triple& Triple); -const HostInfo *createOpenBSDHostInfo(const Driver &D, +const HostInfo *createOpenBSDHostInfo(const Driver &D, const llvm::Triple& Triple); -const HostInfo *createFreeBSDHostInfo(const Driver &D, +const HostInfo *createFreeBSDHostInfo(const Driver &D, const llvm::Triple& Triple); -const HostInfo *createDragonFlyHostInfo(const Driver &D, +const HostInfo *createDragonFlyHostInfo(const Driver &D, const llvm::Triple& Triple); -const HostInfo *createLinuxHostInfo(const Driver &D, +const HostInfo *createLinuxHostInfo(const Driver &D, const llvm::Triple& Triple); -const HostInfo *createUnknownHostInfo(const Driver &D, +const HostInfo *createUnknownHostInfo(const Driver &D, const llvm::Triple& Triple); } // end namespace driver diff --git a/clang/include/clang/Driver/Job.h b/clang/include/clang/Driver/Job.h index a23babdbb31a5704e913af5e7c93199223d3c791..906d73128b7dc6bc90e3b947c4c7a9dbf464e6f0 100644 --- a/clang/include/clang/Driver/Job.h +++ b/clang/include/clang/Driver/Job.h @@ -46,7 +46,7 @@ public: /// either a piped job or a job list. void addCommand(Command *C); - static bool classof(const Job *) { return true; } + static bool classof(const Job *) { return true; } }; /// Command - An executable path/name and argument vector to @@ -63,7 +63,7 @@ class Command : public Job { ArgStringList Arguments; public: - Command(const Action &_Source, const char *_Executable, + Command(const Action &_Source, const char *_Executable, const ArgStringList &_Arguments); /// getSource - Return the Action which caused the creation of this job. @@ -73,8 +73,8 @@ public: const ArgStringList &getArguments() const { return Arguments; } - static bool classof(const Job *J) { - return J->getKind() == CommandClass; + static bool classof(const Job *J) { + return J->getKind() == CommandClass; } static bool classof(const Command *) { return true; } }; @@ -97,15 +97,15 @@ public: void addCommand(Command *C) { Commands.push_back(C); } const list_type &getCommands() const { return Commands; } - + size_type size() const { return Commands.size(); } iterator begin() { return Commands.begin(); } const_iterator begin() const { return Commands.begin(); } iterator end() { return Commands.end(); } const_iterator end() const { return Commands.end(); } - static bool classof(const Job *J) { - return J->getKind() == PipedJobClass; + static bool classof(const Job *J) { + return J->getKind() == PipedJobClass; } static bool classof(const PipedJob *) { return true; } }; @@ -133,13 +133,13 @@ public: const_iterator begin() const { return Jobs.begin(); } iterator end() { return Jobs.end(); } const_iterator end() const { return Jobs.end(); } - - static bool classof(const Job *J) { - return J->getKind() == JobListClass; + + static bool classof(const Job *J) { + return J->getKind() == JobListClass; } static bool classof(const JobList *) { return true; } }; - + } // end namespace driver } // end namespace clang diff --git a/clang/include/clang/Driver/Option.h b/clang/include/clang/Driver/Option.h index c59faef897aee7c4707be3738691c4241eb3d3b9..c70b6482167b14f5583c5f258552e28704b834e4 100644 --- a/clang/include/clang/Driver/Option.h +++ b/clang/include/clang/Driver/Option.h @@ -24,7 +24,7 @@ namespace driver { class Arg; class InputArgList; class OptionGroup; - + /// Option - Abstract representation for a single form of driver /// argument. /// @@ -57,10 +57,10 @@ namespace driver { options::ID ID; /// The option name. - const char *Name; + const char *Name; /// Group this option is a member of, if any. - const OptionGroup *Group; + const OptionGroup *Group; /// Option that this is an alias for, if any. const Option *Alias; @@ -70,7 +70,7 @@ namespace driver { /// Treat this option like a linker input? bool LinkerInput : 1; - + /// When rendering as an input, don't render the option. // FIXME: We should ditch the render/renderAsInput distinction. @@ -78,18 +78,18 @@ namespace driver { /// Always render this option as separate form its value. bool ForceSeparateRender : 1; - + /// Always render this option joined with its value. - bool ForceJoinedRender : 1; + bool ForceJoinedRender : 1; /// This option is only consumed by the driver. - bool DriverOption : 1; + bool DriverOption : 1; /// This option should not report argument unused errors. - bool NoArgumentUnused : 1; + bool NoArgumentUnused : 1; protected: - Option(OptionClass Kind, options::ID ID, const char *Name, + Option(OptionClass Kind, options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); public: virtual ~Option(); @@ -108,13 +108,13 @@ namespace driver { bool hasNoOptAsInput() const { return NoOptAsInput; } void setNoOptAsInput(bool Value) { NoOptAsInput = Value; } - + bool hasForceSeparateRender() const { return ForceSeparateRender; } void setForceSeparateRender(bool Value) { ForceSeparateRender = Value; } - + bool hasForceJoinedRender() const { return ForceJoinedRender; } void setForceJoinedRender(bool Value) { ForceJoinedRender = Value; } - + bool isDriverOption() const { return DriverOption; } void setDriverOption(bool Value) { DriverOption = Value; } @@ -125,7 +125,7 @@ namespace driver { /// getUnaliasedOption - Return the final option this option /// aliases (itself, if the option has no alias). - const Option *getUnaliasedOption() const { + const Option *getUnaliasedOption() const { if (Alias) return Alias->getUnaliasedOption(); return this; } @@ -149,12 +149,12 @@ namespace driver { /// Index to the position where argument parsing should resume /// (even if the argument is missing values). virtual Arg *accept(const InputArgList &Args, unsigned &Index) const = 0; - + void dump() const; static bool classof(const Option *) { return true; } }; - + /// OptionGroup - A set of options which are can be handled uniformly /// by the driver. class OptionGroup : public Option { @@ -163,14 +163,14 @@ namespace driver { virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::GroupClass; + static bool classof(const Option *O) { + return O->getKind() == Option::GroupClass; } static bool classof(const OptionGroup *) { return true; } }; - + // Dummy option classes. - + /// InputOption - Dummy option class for representing driver inputs. class InputOption : public Option { public: @@ -178,8 +178,8 @@ namespace driver { virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::InputClass; + static bool classof(const Option *O) { + return O->getKind() == Option::InputClass; } static bool classof(const InputOption *) { return true; } }; @@ -191,8 +191,8 @@ namespace driver { virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::UnknownClass; + static bool classof(const Option *O) { + return O->getKind() == Option::UnknownClass; } static bool classof(const UnknownOption *) { return true; } }; @@ -201,52 +201,52 @@ namespace driver { class FlagOption : public Option { public: - FlagOption(options::ID ID, const char *Name, const OptionGroup *Group, + FlagOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::FlagClass; + static bool classof(const Option *O) { + return O->getKind() == Option::FlagClass; } static bool classof(const FlagOption *) { return true; } }; class JoinedOption : public Option { public: - JoinedOption(options::ID ID, const char *Name, const OptionGroup *Group, + JoinedOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::JoinedClass; + static bool classof(const Option *O) { + return O->getKind() == Option::JoinedClass; } static bool classof(const JoinedOption *) { return true; } }; class SeparateOption : public Option { public: - SeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, + SeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::SeparateClass; + static bool classof(const Option *O) { + return O->getKind() == Option::SeparateClass; } static bool classof(const SeparateOption *) { return true; } }; class CommaJoinedOption : public Option { public: - CommaJoinedOption(options::ID ID, const char *Name, + CommaJoinedOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::CommaJoinedClass; + static bool classof(const Option *O) { + return O->getKind() == Option::CommaJoinedClass; } static bool classof(const CommaJoinedOption *) { return true; } }; @@ -259,15 +259,15 @@ namespace driver { unsigned NumArgs; public: - MultiArgOption(options::ID ID, const char *Name, const OptionGroup *Group, + MultiArgOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias, unsigned NumArgs); unsigned getNumArgs() const { return NumArgs; } virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::MultiArgClass; + static bool classof(const Option *O) { + return O->getKind() == Option::MultiArgClass; } static bool classof(const MultiArgOption *) { return true; } }; @@ -276,13 +276,13 @@ namespace driver { /// prefixes its (non-empty) value, or is follwed by a value. class JoinedOrSeparateOption : public Option { public: - JoinedOrSeparateOption(options::ID ID, const char *Name, + JoinedOrSeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::JoinedOrSeparateClass; + static bool classof(const Option *O) { + return O->getKind() == Option::JoinedOrSeparateClass; } static bool classof(const JoinedOrSeparateOption *) { return true; } }; @@ -291,13 +291,13 @@ namespace driver { /// value and is followed by another value. class JoinedAndSeparateOption : public Option { public: - JoinedAndSeparateOption(options::ID ID, const char *Name, + JoinedAndSeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias); virtual Arg *accept(const InputArgList &Args, unsigned &Index) const; - static bool classof(const Option *O) { - return O->getKind() == Option::JoinedAndSeparateClass; + static bool classof(const Option *O) { + return O->getKind() == Option::JoinedAndSeparateClass; } static bool classof(const JoinedAndSeparateOption *) { return true; } }; diff --git a/clang/include/clang/Driver/Options.h b/clang/include/clang/Driver/Options.h index 8b959d369c0e127a8aef6f482e9c02f3b34bdd0f..7fcaf3f497bef5d34c2ddf48f607590cec264b56 100644 --- a/clang/include/clang/Driver/Options.h +++ b/clang/include/clang/Driver/Options.h @@ -24,7 +24,7 @@ namespace options { #undef OPTION }; } - + class Arg; class InputArgList; class Option; @@ -36,7 +36,7 @@ namespace options { /// few options will be needed at runtime; the OptTable class /// maintains enough information to parse command lines without /// instantiating Options, while letting other parts of the driver - /// still use Option instances where convient. + /// still use Option instances where convient. class OptTable { /// The table of options which have been constructed, indexed by /// option::ID - 1. diff --git a/clang/include/clang/Driver/Tool.h b/clang/include/clang/Driver/Tool.h index d8b37e9ead88c51924943a75eab7fa925e341073..8a89f01e0f4b0e2b5822ad8165c951ed307990c8 100644 --- a/clang/include/clang/Driver/Tool.h +++ b/clang/include/clang/Driver/Tool.h @@ -22,7 +22,7 @@ namespace driver { class Job; class JobAction; class ToolChain; - + typedef llvm::SmallVector InputInfoList; /// Tool - Information on a specific compilation tool. @@ -57,9 +57,9 @@ public: /// linker, then this is the final output name of the linked image. virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const = 0; }; diff --git a/clang/include/clang/Frontend/ASTConsumers.h b/clang/include/clang/Frontend/ASTConsumers.h index d3d43c25881535470b71dfff10e6fdadc3958f21..fc89e95cd7cd21c50fa921d812f7ee393ac78058 100644 --- a/clang/include/clang/Frontend/ASTConsumers.h +++ b/clang/include/clang/Frontend/ASTConsumers.h @@ -38,9 +38,9 @@ class LangOptions; // implementation is still incomplete. ASTConsumer *CreateASTPrinter(llvm::raw_ostream *OS); -// AST XML-printer: prints out the AST in a XML format +// AST XML-printer: prints out the AST in a XML format // The output is intended to be in a format such that -// clang or any other tool could re-parse the output back into the same AST, +// clang or any other tool could re-parse the output back into the same AST, // but the implementation is still incomplete. ASTConsumer *CreateASTPrinterXML(llvm::raw_ostream *OS); diff --git a/clang/include/clang/Frontend/ASTUnit.h b/clang/include/clang/Frontend/ASTUnit.h index d41549ec3e5987438231ed7207f7af1b969c31e3..3b72c37bcd1e29275b6e745fde53ab8e95b73719 100644 --- a/clang/include/clang/Frontend/ASTUnit.h +++ b/clang/include/clang/Frontend/ASTUnit.h @@ -43,7 +43,7 @@ class ASTUnit { ASTUnit(const ASTUnit&); // do not implement ASTUnit &operator=(const ASTUnit &); // do not implement ASTUnit(); - + public: ~ASTUnit(); @@ -52,13 +52,13 @@ public: const Preprocessor &getPreprocessor() const { return *PP.get(); } Preprocessor &getPreprocessor() { return *PP.get(); } - + const ASTContext &getASTContext() const { return *Ctx.get(); } ASTContext &getASTContext() { return *Ctx.get(); } const Diagnostic &getDiagnostic() const { return *Diags.get(); } Diagnostic &getDiagnostic() { return *Diags.get(); } - + FileManager &getFileManager(); const std::string &getOriginalSourceFileName(); diff --git a/clang/include/clang/Frontend/CommandLineSourceLoc.h b/clang/include/clang/Frontend/CommandLineSourceLoc.h index 1eaa958995f545bbcfed45a28f9832efc6642f55..4092724372931bb25c5ea2f184e1d3902e20b9de 100644 --- a/clang/include/clang/Frontend/CommandLineSourceLoc.h +++ b/clang/include/clang/Frontend/CommandLineSourceLoc.h @@ -34,21 +34,21 @@ namespace llvm { /// /// Source locations are of the form filename:line:column. template<> - class parser + class parser : public basic_parser { public: - bool parse(Option &O, const char *ArgName, + bool parse(Option &O, const char *ArgName, const std::string &ArgValue, clang::ParsedSourceLocation &Val); }; - bool + bool parser:: - parse(Option &O, const char *ArgName, const std::string &ArgValue, + parse(Option &O, const char *ArgName, const std::string &ArgValue, clang::ParsedSourceLocation &Val) { using namespace clang; - const char *ExpectedFormat + const char *ExpectedFormat = "source location must be of the form filename:line:column"; std::string::size_type SecondColon = ArgValue.rfind(':'); if (SecondColon == std::string::npos) { @@ -56,7 +56,7 @@ namespace llvm { return true; } char *EndPtr; - long Column + long Column = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10); if (EndPtr != ArgValue.c_str() + ArgValue.size()) { std::fprintf(stderr, "%s\n", ExpectedFormat); @@ -73,7 +73,7 @@ namespace llvm { std::fprintf(stderr, "%s\n", ExpectedFormat); return true; } - + Val.FileName = ArgValue.substr(0, FirstColon); Val.Line = Line; Val.Column = Column; diff --git a/clang/include/clang/Frontend/CompileOptions.h b/clang/include/clang/Frontend/CompileOptions.h index 75dec00f747f3442be730caad4c810dbbd53e49b..508af537b1fa1b96ed316ceea182c8391d11ad3e 100644 --- a/clang/include/clang/Frontend/CompileOptions.h +++ b/clang/include/clang/Frontend/CompileOptions.h @@ -67,7 +67,7 @@ public: Inlining = NoInlining; DisableRedZone = 0; NoImplicitFloat = 0; - } + } }; } // end namespace clang diff --git a/clang/include/clang/Frontend/DocumentXML.h b/clang/include/clang/Frontend/DocumentXML.h index 4ed11e153ce365ab3707b864f1ac042578453134..31cffd0be9d8925c2a440e396f0edda9491186cf 100644 --- a/clang/include/clang/Frontend/DocumentXML.h +++ b/clang/include/clang/Frontend/DocumentXML.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements the XML document class, which provides the means to +// This file implements the XML document class, which provides the means to // dump out the AST in a XML form that exposes type details and other fields. // //===----------------------------------------------------------------------===// @@ -32,10 +32,9 @@ class NamedDecl; class FunctionDecl; class ASTContext; class LabelStmt; - -//--------------------------------------------------------- -namespace XML -{ + +//--------------------------------------------------------- +namespace XML { // id maps: template struct IdMap : llvm::DenseMap {}; @@ -47,9 +46,8 @@ namespace XML struct IdMap : std::map {}; } -//--------------------------------------------------------- -class DocumentXML -{ +//--------------------------------------------------------- +class DocumentXML { public: DocumentXML(const std::string& rootName, llvm::raw_ostream& out); @@ -62,24 +60,22 @@ public: DocumentXML& addSubNode(const std::string& name); // also enters the sub node, returns *this DocumentXML& toParent(); // returns *this - void addAttribute(const char* pName, const QualType& pType); + void addAttribute(const char* pName, const QualType& pType); void addAttribute(const char* pName, bool value); template - void addAttribute(const char* pName, const T* value) - { + void addAttribute(const char* pName, const T* value) { addPtrAttribute(pName, value); } template - void addAttribute(const char* pName, T* value) - { + void addAttribute(const char* pName, T* value) { addPtrAttribute(pName, value); } template void addAttribute(const char* pName, const T& value); - + template void addAttributeOptional(const char* pName, const T& value); @@ -114,7 +110,7 @@ private: void Indent(); // forced pointer dispatch: - void addPtrAttribute(const char* pName, const Type* pType); + void addPtrAttribute(const char* pName, const Type* pType); void addPtrAttribute(const char* pName, const NamedDecl* D); void addPtrAttribute(const char* pName, const DeclContext* D); void addPtrAttribute(const char* pName, const NamespaceDecl* D); // disambiguation @@ -141,42 +137,37 @@ private: //--------------------------------------------------------- inlines -inline void DocumentXML::initialize(ASTContext &Context) -{ - Ctx = &Context; +inline void DocumentXML::initialize(ASTContext &Context) { + Ctx = &Context; } -//--------------------------------------------------------- +//--------------------------------------------------------- template -inline void DocumentXML::addAttribute(const char* pName, const T& value) -{ +inline void DocumentXML::addAttribute(const char* pName, const T& value) { Out << ' ' << pName << "=\"" << value << "\""; } -//--------------------------------------------------------- -inline void DocumentXML::addPtrAttribute(const char* pName, const char* text) -{ +//--------------------------------------------------------- +inline void DocumentXML::addPtrAttribute(const char* pName, const char* text) { Out << ' ' << pName << "=\"" << text << "\""; } -//--------------------------------------------------------- -inline void DocumentXML::addAttribute(const char* pName, bool value) -{ +//--------------------------------------------------------- +inline void DocumentXML::addAttribute(const char* pName, bool value) { addPtrAttribute(pName, value ? "1" : "0"); } -//--------------------------------------------------------- +//--------------------------------------------------------- template -inline void DocumentXML::addAttributeOptional(const char* pName, const T& value) -{ - if (!isDefault(value)) - { +inline void DocumentXML::addAttributeOptional(const char* pName, + const T& value) { + if (!isDefault(value)) { addAttribute(pName, value); } } -//--------------------------------------------------------- +//--------------------------------------------------------- -} //namespace clang +} //namespace clang #endif //LLVM_CLANG_DOCUMENTXML_H diff --git a/clang/include/clang/Frontend/FixItRewriter.h b/clang/include/clang/Frontend/FixItRewriter.h index 7fcd682bf66c1e15bee5cad95a32051ceb68d484..fac87afadef24662dbbc85b3f2f4633261f04659 100644 --- a/clang/include/clang/Frontend/FixItRewriter.h +++ b/clang/include/clang/Frontend/FixItRewriter.h @@ -51,7 +51,7 @@ class FixItRewriter : public DiagnosticClient { unsigned NumFailures; /// \brief Locations at which we should perform fix-its. - /// + /// /// When empty, perform fix-it modifications everywhere. llvm::SmallVector FixItLocations; @@ -72,7 +72,7 @@ public: /// \brief Write the modified source file. /// /// \returns true if there was an error, false otherwise. - bool WriteFixedFile(const std::string &InFileName, + bool WriteFixedFile(const std::string &InFileName, const std::string &OutFileName = std::string()); /// IncludeInDiagnosticCounts - This method (whose default implementation diff --git a/clang/include/clang/Frontend/FrontendDiagnostic.h b/clang/include/clang/Frontend/FrontendDiagnostic.h index 079abae3eee1c14ccc8324c74ef624f14248840b..a044586a8c0a17994bb3f618e8c6e678cfa2b0d7 100644 --- a/clang/include/clang/Frontend/FrontendDiagnostic.h +++ b/clang/include/clang/Frontend/FrontendDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define FRONTENDSTART diff --git a/clang/include/clang/Frontend/ManagerRegistry.h b/clang/include/clang/Frontend/ManagerRegistry.h index ecab67a3b67691e00c8b0a313c169bf7396d2fe9..f05cfe6df6b8d8f1663889aef13936a04f63a662 100644 --- a/clang/include/clang/Frontend/ManagerRegistry.h +++ b/clang/include/clang/Frontend/ManagerRegistry.h @@ -43,7 +43,7 @@ public: class RegisterConstraintManager { public: RegisterConstraintManager(ConstraintManagerCreator CMC) { - assert(ManagerRegistry::ConstraintMgrCreator == 0 + assert(ManagerRegistry::ConstraintMgrCreator == 0 && "ConstraintMgrCreator already set!"); ManagerRegistry::ConstraintMgrCreator = CMC; } diff --git a/clang/include/clang/Frontend/PCHBitCodes.h b/clang/include/clang/Frontend/PCHBitCodes.h index 92a541ea19c9cc67a6e96708466e2df5b6698411..f6efccfe07343dc173dd37e6f13d6b9fe58a8306 100644 --- a/clang/include/clang/Frontend/PCHBitCodes.h +++ b/clang/include/clang/Frontend/PCHBitCodes.h @@ -65,7 +65,7 @@ namespace clang { typedef uint32_t IdentID; typedef uint32_t SelectorID; - + /// \brief Describes the various kinds of blocks that occur within /// a PCH file. enum BlockIDs { @@ -106,7 +106,7 @@ namespace clang { /// TYPE_OFFSET block to determine the offset of that type's /// corresponding record within the TYPES_BLOCK_ID block. TYPE_OFFSET = 1, - + /// \brief Record code for the offsets of each decl. /// /// The DECL_OFFSET constant describes the record that occurs @@ -182,7 +182,7 @@ namespace clang { /// \brief Record code for the array of locally-scoped external /// declarations. LOCALLY_SCOPED_EXTERNAL_DECLS = 11, - + /// \brief Record code for the table of offsets into the /// Objective-C method pool. SELECTOR_OFFSETS = 12, @@ -215,7 +215,7 @@ namespace clang { /// \brief Record code for the original file that was used to /// generate the precompiled header. ORIGINAL_FILE_NAME = 19, - + /// \brief Record code for the sorted array of source ranges where /// comments were encountered in the source code. COMMENT_RANGES = 20 @@ -243,7 +243,7 @@ namespace clang { /// ControllingMacro is optional. SM_HEADER_FILE_INFO = 6 }; - + /// \brief Record types used within a preprocessor block. enum PreprocessorRecordTypes { // The macros in the PP section are a PP_MACRO_* instance followed by a @@ -257,7 +257,7 @@ namespace clang { /// [PP_MACRO_FUNCTION_LIKE, , IsC99Varargs, IsGNUVarars, /// NumArgs, ArgIdentInfoID* ] PP_MACRO_FUNCTION_LIKE = 2, - + /// \brief Describes one token. /// [PP_TOKEN, SLoc, Length, IdentInfoID, Kind, Flags] PP_TOKEN = 3 @@ -333,7 +333,7 @@ namespace clang { /// \brief The ObjC 'id' type. PREDEF_TYPE_OBJC_ID = 26, /// \brief The ObjC 'Class' type. - PREDEF_TYPE_OBJC_CLASS = 27 + PREDEF_TYPE_OBJC_CLASS = 27 }; /// \brief The number of predefined type IDs that are reserved for @@ -627,9 +627,9 @@ namespace clang { EXPR_BLOCK, /// \brief A BlockDeclRef record. EXPR_BLOCK_DECL_REF, - + // Objective-C - + /// \brief An ObjCStringLiteral record. EXPR_OBJC_STRING_LITERAL, /// \brief An ObjCEncodeExpr record. @@ -650,23 +650,23 @@ namespace clang { EXPR_OBJC_SUPER_EXPR, /// \brief An ObjCIsa Expr record. EXPR_OBJC_ISA, - - /// \brief An ObjCForCollectionStmt record. + + /// \brief An ObjCForCollectionStmt record. STMT_OBJC_FOR_COLLECTION, - /// \brief An ObjCAtCatchStmt record. + /// \brief An ObjCAtCatchStmt record. STMT_OBJC_CATCH, - /// \brief An ObjCAtFinallyStmt record. + /// \brief An ObjCAtFinallyStmt record. STMT_OBJC_FINALLY, - /// \brief An ObjCAtTryStmt record. + /// \brief An ObjCAtTryStmt record. STMT_OBJC_AT_TRY, - /// \brief An ObjCAtSynchronizedStmt record. + /// \brief An ObjCAtSynchronizedStmt record. STMT_OBJC_AT_SYNCHRONIZED, - /// \brief An ObjCAtThrowStmt record. + /// \brief An ObjCAtThrowStmt record. STMT_OBJC_AT_THROW, // C++ - /// \brief An CXXOperatorCallExpr record. + /// \brief An CXXOperatorCallExpr record. EXPR_CXX_OPERATOR_CALL }; diff --git a/clang/include/clang/Frontend/PCHReader.h b/clang/include/clang/Frontend/PCHReader.h index 2ddf13fcf1ef605421bde93831ddaf48143979b1..6f28a25722da93d26a987f58416a6ed685728ac0 100644 --- a/clang/include/clang/Frontend/PCHReader.h +++ b/clang/include/clang/Frontend/PCHReader.h @@ -66,21 +66,21 @@ struct HeaderFileInfo; class PCHReaderListener { public: virtual ~PCHReaderListener(); - + /// \brief Receives the language options. /// /// \returns true to indicate the options are invalid or false otherwise. virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { return false; } - + /// \brief Receives the target triple. /// /// \returns true to indicate the target triple is invalid or false otherwise. virtual bool ReadTargetTriple(const std::string &Triple) { return false; } - + /// \brief Receives the contents of the predefines buffer. /// /// \param PCHPredef The start of the predefines buffer in the PCH @@ -95,16 +95,16 @@ public: /// here. /// /// \returns true to indicate the predefines are invalid or false otherwise. - virtual bool ReadPredefinesBuffer(const char *PCHPredef, + virtual bool ReadPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID, std::string &SuggestedPredefines) { return false; } - + /// \brief Receives a HeaderFileInfo entry. virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) {} - + /// \brief Receives __COUNTER__ value. virtual void ReadCounter(unsigned Value) {} }; @@ -114,16 +114,16 @@ public: class PCHValidator : public PCHReaderListener { Preprocessor &PP; PCHReader &Reader; - + unsigned NumHeaderInfos; - + public: PCHValidator(Preprocessor &PP, PCHReader &Reader) : PP(PP), Reader(Reader), NumHeaderInfos(0) {} - + virtual bool ReadLanguageOptions(const LangOptions &LangOpts); virtual bool ReadTargetTriple(const std::string &Triple); - virtual bool ReadPredefinesBuffer(const char *PCHPredef, + virtual bool ReadPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID, std::string &SuggestedPredefines); @@ -143,8 +143,8 @@ public: /// The PCH reader provides lazy de-serialization of declarations, as /// required when traversing the AST. Only those AST nodes that are /// actually required will be de-serialized. -class PCHReader - : public ExternalSemaSource, +class PCHReader + : public ExternalSemaSource, public IdentifierInfoLookup, public ExternalIdentifierLookup, public ExternalSLocEntrySource { @@ -154,11 +154,11 @@ public: private: /// \ brief The receiver of some callbacks invoked by PCHReader. llvm::OwningPtr Listener; - + SourceManager &SourceMgr; FileManager &FileMgr; Diagnostic &Diags; - + /// \brief The semantic analysis object that will be processing the /// PCH file and the translation unit that uses it. Sema *SemaObj; @@ -203,8 +203,8 @@ private: const uint32_t *TypeOffsets; /// \brief Types that have already been loaded from the PCH file. - /// - /// When the pointer at index I is non-NULL, the type with + /// + /// When the pointer at index I is non-NULL, the type with /// ID = (I + 1) << 3 has already been loaded from the PCH file. std::vector TypesLoaded; @@ -273,7 +273,7 @@ private: /// \brief The total number of selectors stored in the PCH file. unsigned TotalNumSelectors; - /// \brief A vector containing selectors that have already been loaded. + /// \brief A vector containing selectors that have already been loaded. /// /// This vector is indexed by the Selector ID (-1). NULL selector /// entries indicate that the particular selector ID has not yet @@ -282,10 +282,10 @@ private: /// \brief A sorted array of source ranges containing comments. SourceRange *Comments; - + /// \brief The number of source ranges in the Comments array. unsigned NumComments; - + /// \brief The set of external definitions stored in the the PCH /// file. llvm::SmallVector ExternalDefinitions; @@ -312,11 +312,11 @@ private: /// \brief Whether this precompiled header is a relocatable PCH file. bool RelocatablePCH; - - /// \brief The system include root to be used when loading the + + /// \brief The system include root to be used when loading the /// precompiled header. const char *isysroot; - + /// \brief Mapping from switch-case IDs in the PCH file to /// switch-case statements. std::map SwitchCaseStmts; @@ -369,41 +369,41 @@ private: /// Number of visible decl contexts read/total. unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts; - - /// \brief When a type or declaration is being loaded from the PCH file, an - /// instantance of this RAII object will be available on the stack to + + /// \brief When a type or declaration is being loaded from the PCH file, an + /// instantance of this RAII object will be available on the stack to /// indicate when we are in a recursive-loading situation. class LoadingTypeOrDecl { PCHReader &Reader; LoadingTypeOrDecl *Parent; - + LoadingTypeOrDecl(const LoadingTypeOrDecl&); // do not implement LoadingTypeOrDecl &operator=(const LoadingTypeOrDecl&); // do not implement - + public: explicit LoadingTypeOrDecl(PCHReader &Reader); ~LoadingTypeOrDecl(); }; friend class LoadingTypeOrDecl; - + /// \brief If we are currently loading a type or declaration, points to the /// most recent LoadingTypeOrDecl object on the stack. LoadingTypeOrDecl *CurrentlyLoadingTypeOrDecl; - - /// \brief An IdentifierInfo that has been loaded but whose top-level + + /// \brief An IdentifierInfo that has been loaded but whose top-level /// declarations of the same name have not (yet) been loaded. struct PendingIdentifierInfo { IdentifierInfo *II; llvm::SmallVector DeclIDs; }; - + /// \brief The set of identifiers that were read while the PCH reader was - /// (recursively) loading declarations. - /// + /// (recursively) loading declarations. + /// /// The declarations on the identifier chain for these identifiers will be /// loaded once the recursive loading has completed. std::deque PendingIdentifierInfos; - + /// \brief FIXME: document! llvm::SmallVector SpecialTypes; @@ -434,17 +434,17 @@ private: /// there are differences that the PCH reader can work around, this /// predefines buffer may contain additional definitions. std::string SuggestedPredefines; - + void MaybeAddSystemRootToFilename(std::string &Filename); - + PCHReadResult ReadPCHBlock(); - bool CheckPredefinesBuffer(const char *PCHPredef, + bool CheckPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID); bool ParseLineTable(llvm::SmallVectorImpl &Record); PCHReadResult ReadSourceManagerBlock(); PCHReadResult ReadSLocEntryRecord(unsigned ID); - + bool ParseLanguageOptions(const llvm::SmallVectorImpl &Record); QualType ReadTypeRecord(uint64_t Offset); void LoadedDecl(unsigned Index, Decl *D); @@ -474,7 +474,7 @@ public: /// user. This is only used with relocatable PCH files. If non-NULL, /// a relocatable PCH file will use the default path "/". PCHReader(Preprocessor &PP, ASTContext *Context, const char *isysroot = 0); - + /// \brief Load the PCH file without using any pre-initialized Preprocessor. /// /// The necessary information to initialize a Preprocessor later can be @@ -492,28 +492,28 @@ public: /// \param isysroot If non-NULL, the system include path specified by the /// user. This is only used with relocatable PCH files. If non-NULL, /// a relocatable PCH file will use the default path "/". - PCHReader(SourceManager &SourceMgr, FileManager &FileMgr, + PCHReader(SourceManager &SourceMgr, FileManager &FileMgr, Diagnostic &Diags, const char *isysroot = 0); ~PCHReader(); /// \brief Load the precompiled header designated by the given file /// name. PCHReadResult ReadPCH(const std::string &FileName); - + /// \brief Set the PCH callbacks listener. void setListener(PCHReaderListener *listener) { Listener.reset(listener); } - + /// \brief Set the Preprocessor to use. void setPreprocessor(Preprocessor &pp) { PP = &pp; } - + /// \brief Sets and initializes the given Context. void InitializeContext(ASTContext &Context); - /// \brief Retrieve the name of the original source file name + /// \brief Retrieve the name of the original source file name const std::string &getOriginalSourceFile() { return OriginalFileName; } /// \brief Retrieve the name of the original source file name @@ -533,7 +533,7 @@ public: /// replaced with the sorted set of source ranges corresponding to /// comments in the source code. virtual void ReadComments(std::vector &Comments); - + /// \brief Resolve a type ID into a type, potentially building a new /// type. virtual QualType GetType(pch::TypeID ID); @@ -619,14 +619,14 @@ public: /// /// \returns a pair of Objective-C methods lists containing the /// instance and factory methods, respectively, with this selector. - virtual std::pair + virtual std::pair ReadMethodPool(Selector Sel); void SetIdentifierInfo(unsigned ID, IdentifierInfo *II); - void SetGloballyVisibleDecls(IdentifierInfo *II, + void SetGloballyVisibleDecls(IdentifierInfo *II, const llvm::SmallVectorImpl &DeclIDs, bool Nonrecursive = false); - + /// \brief Report a diagnostic. DiagnosticBuilder Diag(unsigned DiagID); @@ -634,11 +634,11 @@ public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); IdentifierInfo *DecodeIdentifierInfo(unsigned Idx); - + IdentifierInfo *GetIdentifierInfo(const RecordData &Record, unsigned &Idx) { return DecodeIdentifierInfo(Record[Idx++]); } - + virtual IdentifierInfo *GetIdentifier(unsigned ID) { return DecodeIdentifierInfo(ID); } @@ -647,7 +647,7 @@ public: virtual void ReadSLocEntry(unsigned ID); Selector DecodeSelector(unsigned Idx); - + Selector GetSelector(const RecordData &Record, unsigned &Idx) { return DecodeSelector(Record[Idx++]); } @@ -670,13 +670,13 @@ public: /// \brief ReadDeclExpr - Reads an expression from the current decl cursor. Expr *ReadDeclExpr(); - + /// \brief ReadTypeExpr - Reads an expression from the current type cursor. Expr *ReadTypeExpr(); /// \brief Reads a statement from the specified cursor. Stmt *ReadStmt(llvm::BitstreamCursor &Cursor); - + /// \brief Read a statement from the current DeclCursor. Stmt *ReadDeclStmt() { return ReadStmt(DeclsCursor); @@ -741,16 +741,16 @@ public: struct SavedStreamPosition { explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor) : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { } - + ~SavedStreamPosition() { Cursor.JumpToBit(Offset); } - + private: llvm::BitstreamCursor &Cursor; uint64_t Offset; }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Frontend/PCHWriter.h b/clang/include/clang/Frontend/PCHWriter.h index 3bab9b998b097a949246762168f47b02d6fdf87c..22341fb9c5d632976b33529320e1cd9aa7e0e6c2 100644 --- a/clang/include/clang/Frontend/PCHWriter.h +++ b/clang/include/clang/Frontend/PCHWriter.h @@ -98,21 +98,21 @@ private: /// discovery), starting at 1. An ID of zero refers to a NULL /// IdentifierInfo. llvm::DenseMap IdentifierIDs; - + /// \brief Offsets of each of the identifier IDs into the identifier /// table. std::vector IdentifierOffsets; /// \brief Map that provides the ID numbers of each Selector. llvm::DenseMap SelectorIDs; - + /// \brief Offset of each selector within the method pool/selector /// table, indexed by the Selector ID (-1). std::vector SelectorOffsets; /// \brief A vector of all Selectors (ordered by ID). std::vector SelVector; - + /// \brief Offsets of each of the macro identifiers into the /// bitstream. /// @@ -141,7 +141,7 @@ private: /// \brief Mapping from SwitchCase statements to IDs. std::map SwitchCaseIDs; - + /// \brief Mapping from LabelStmt statements to IDs. std::map LabelIDs; @@ -163,7 +163,7 @@ private: void WriteMetadata(ASTContext &Context, const char *isysroot); void WriteLanguageOptions(const LangOptions &LangOpts); void WriteStatCache(MemorizeStatCalls &StatCalls, const char* isysroot); - void WriteSourceManagerBlock(SourceManager &SourceMgr, + void WriteSourceManagerBlock(SourceManager &SourceMgr, const Preprocessor &PP, const char* isysroot); void WritePreprocessor(const Preprocessor &PP); @@ -172,7 +172,7 @@ private: void WriteTypesBlock(ASTContext &Context); uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC); uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC); - + void WriteDeclsBlock(ASTContext &Context); void WriteMethodPool(Sema &SemaRef); void WriteIdentifierTable(Preprocessor &PP); @@ -180,12 +180,12 @@ private: unsigned ParmVarDeclAbbrev; void WriteDeclsBlockAbbrevs(); - + public: /// \brief Create a new precompiled header writer that outputs to /// the given bitstream. PCHWriter(llvm::BitstreamWriter &Stream); - + /// \brief Write a precompiled header for the given semantic analysis. /// /// \param SemaRef a reference to the semantic analysis object that processed @@ -194,9 +194,9 @@ public: /// \param StatCalls the object that cached all of the stat() calls made while /// searching for source files and headers. /// - /// \param isysroot if non-NULL, write a relocatable PCH file whose headers + /// \param isysroot if non-NULL, write a relocatable PCH file whose headers /// are relative to the given system root. - void WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, + void WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, const char* isysroot); /// \brief Emit a source location. @@ -216,7 +216,7 @@ public: /// \brief Emit a Selector (which is a smart pointer reference) void AddSelectorRef(const Selector, RecordData &Record); - + /// \brief Get the unique number used to refer to the given /// identifier. pch::IdentID getIdentifierRef(const IdentifierInfo *II); @@ -226,7 +226,7 @@ public: /// /// The identifier must refer to a macro. uint64_t getMacroOffset(const IdentifierInfo *II) { - assert(MacroOffsets.find(II) != MacroOffsets.end() && + assert(MacroOffsets.find(II) != MacroOffsets.end() && "Identifier does not name a macro"); return MacroOffsets[II]; } diff --git a/clang/include/clang/Frontend/PathDiagnosticClients.h b/clang/include/clang/Frontend/PathDiagnosticClients.h index 53dd32e93b8c1af9ca47db174b4762d3c19d4c35..8cb6898d75984cf20d7d5b3838c9a53766a90a08 100644 --- a/clang/include/clang/Frontend/PathDiagnosticClients.h +++ b/clang/include/clang/Frontend/PathDiagnosticClients.h @@ -23,12 +23,12 @@ namespace clang { class PathDiagnosticClient; class Preprocessor; class PreprocessorFactory; - + class PathDiagnosticClientFactory { public: PathDiagnosticClientFactory() {} virtual ~PathDiagnosticClientFactory() {} - + virtual const char *getName() const = 0; virtual PathDiagnosticClient* @@ -39,12 +39,12 @@ PathDiagnosticClient* CreateHTMLDiagnosticClient(const std::string& prefix, Preprocessor* PP = 0, PreprocessorFactory* PPF = 0, llvm::SmallVectorImpl* FilesMade = 0); - + PathDiagnosticClientFactory* CreateHTMLDiagnosticClientFactory(const std::string& prefix, Preprocessor* PP = 0, PreprocessorFactory* PPF = 0); - + PathDiagnosticClient* CreatePlistDiagnosticClient(const std::string& prefix, Preprocessor* PP, PreprocessorFactory* PPF, diff --git a/clang/include/clang/Frontend/TextDiagnosticPrinter.h b/clang/include/clang/Frontend/TextDiagnosticPrinter.h index f8408bdbd742ea580e4cc32c158aab29de50add7..0fd8d44f72bc13dc89305fdefa4e9fc85c12bd03 100644 --- a/clang/include/clang/Frontend/TextDiagnosticPrinter.h +++ b/clang/include/clang/Frontend/TextDiagnosticPrinter.h @@ -52,7 +52,7 @@ public: unsigned messageLength = 0, bool useColors = false) : OS(os), LangOpts(0), - LastCaretDiagnosticWasNote(false), ShowColumn(showColumn), + LastCaretDiagnosticWasNote(false), ShowColumn(showColumn), CaretDiagnostics(caretDiagnistics), ShowLocation(showLocation), PrintRangeInfo(printRangeInfo), PrintDiagnosticOption(printDiagnosticOption), @@ -63,7 +63,7 @@ public: void setLangOptions(const LangOptions *LO) { LangOpts = LO; } - + void PrintIncludeStack(SourceLocation Loc, const SourceManager &SM); void HighlightRange(const SourceRange &R, @@ -72,13 +72,13 @@ public: std::string &CaretLine, const std::string &SourceLine); - void EmitCaretDiagnostic(SourceLocation Loc, + void EmitCaretDiagnostic(SourceLocation Loc, SourceRange *Ranges, unsigned NumRanges, SourceManager &SM, const CodeModificationHint *Hints, unsigned NumHints, unsigned Columns); - + virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info); }; diff --git a/clang/include/clang/Frontend/Utils.h b/clang/include/clang/Frontend/Utils.h index 2ad44da999c1c43d9166bd45d869b4a80332b240..9cbcf8e3e93e88687a41721dd8952bd182d4a1ac 100644 --- a/clang/include/clang/Frontend/Utils.h +++ b/clang/include/clang/Frontend/Utils.h @@ -57,7 +57,7 @@ void RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream* OS); /// RewriteMacrosInInput - A simple test for the TokenRewriter class. void DoRewriteTest(Preprocessor &PP, llvm::raw_ostream* OS); - + /// CreatePrintParserActionsAction - Return the actions implementation that /// implements the -parse-print-callbacks option. MinimalAction *CreatePrintParserActionsAction(Preprocessor &PP, diff --git a/clang/include/clang/Index/ASTLocation.h b/clang/include/clang/Index/ASTLocation.h index 954792d0f9ee9db68f0af0a39b510b3f89621347..60af9e672c011b04a6d2ba521373d36a9c839f9b 100644 --- a/clang/include/clang/Index/ASTLocation.h +++ b/clang/include/clang/Index/ASTLocation.h @@ -75,13 +75,13 @@ public: static bool isImmediateParent(Decl *D, Stmt *Node); static Decl *FindImmediateParent(Decl *D, Stmt *Node); - friend bool operator==(const ASTLocation &L, const ASTLocation &R) { + friend bool operator==(const ASTLocation &L, const ASTLocation &R) { return L.D == R.D && L.Stm == R.Stm; } - friend bool operator!=(const ASTLocation &L, const ASTLocation &R) { + friend bool operator!=(const ASTLocation &L, const ASTLocation &R) { return !(L == R); } - + void print(llvm::raw_ostream &OS) const; }; @@ -89,13 +89,13 @@ public: /// ASTLocation originated from. class TULocation : public ASTLocation { TranslationUnit *TU; - + public: TULocation(TranslationUnit *tu, ASTLocation astLoc) : ASTLocation(astLoc), TU(tu) { assert(tu && "Passed null translation unit"); } - + TranslationUnit *getTU() const { return TU; } }; diff --git a/clang/include/clang/Index/DeclReferenceMap.h b/clang/include/clang/Index/DeclReferenceMap.h index 1ed64369fc302a1b91a3f9ccecd82d33521177ad..73f2fe50b3b64ca58bd105ae8b691758bf947967 100644 --- a/clang/include/clang/Index/DeclReferenceMap.h +++ b/clang/include/clang/Index/DeclReferenceMap.h @@ -24,27 +24,27 @@ namespace clang { class NamedDecl; namespace idx { - + /// \brief Maps NamedDecls with the ASTLocations that reference them. /// /// References are mapped and retrieved using the canonical decls. class DeclReferenceMap { public: explicit DeclReferenceMap(ASTContext &Ctx); - + typedef std::multimap MapTy; typedef pair_value_iterator astlocation_iterator; astlocation_iterator refs_begin(NamedDecl *D) const; astlocation_iterator refs_end(NamedDecl *D) const; bool refs_empty(NamedDecl *D) const; - + private: mutable MapTy Map; }; } // end idx namespace - + } // end clang namespace #endif diff --git a/clang/include/clang/Index/Entity.h b/clang/include/clang/Index/Entity.h index edbb329723426df6aa3fb816f0255acf4fc18114..4533a1a0ac082d763a46a3ec51d28db5ce072faa 100644 --- a/clang/include/clang/Index/Entity.h +++ b/clang/include/clang/Index/Entity.h @@ -50,7 +50,7 @@ class Entity { explicit Entity(Decl *D); explicit Entity(EntityImpl *impl) : Val(impl) { } friend class EntityGetter; - + public: Entity() { } @@ -79,7 +79,7 @@ public: bool isValid() const { return !Val.isNull(); } bool isInvalid() const { return !isValid(); } - + void *getAsOpaquePtr() const { return Val.getOpaqueValue(); } static Entity getFromOpaquePtr(void *Ptr) { Entity Ent; @@ -87,12 +87,12 @@ public: return Ent; } - friend bool operator==(const Entity &LHS, const Entity &RHS) { + friend bool operator==(const Entity &LHS, const Entity &RHS) { return LHS.getAsOpaquePtr() == RHS.getAsOpaquePtr(); } - + // For use in a std::map. - friend bool operator < (const Entity &LHS, const Entity &RHS) { + friend bool operator < (const Entity &LHS, const Entity &RHS) { return LHS.getAsOpaquePtr() < RHS.getAsOpaquePtr(); } @@ -110,7 +110,7 @@ public: return Ent; } }; - + } // namespace idx } // namespace clang @@ -130,7 +130,7 @@ struct DenseMapInfo { static unsigned getHashValue(clang::idx::Entity); - static inline bool + static inline bool isEqual(clang::idx::Entity LHS, clang::idx::Entity RHS) { return LHS == RHS; } diff --git a/clang/include/clang/Index/GlobalSelector.h b/clang/include/clang/Index/GlobalSelector.h index e24c419d1eec015bd34bf253707d941fc8c85285..51f98267f3562568054ec864501168566ad731cb 100644 --- a/clang/include/clang/Index/GlobalSelector.h +++ b/clang/include/clang/Index/GlobalSelector.h @@ -44,19 +44,19 @@ public: /// \brief Get a GlobalSelector for the ASTContext-specific selector. static GlobalSelector get(Selector Sel, Program &Prog); - + void *getAsOpaquePtr() const { return Val; } - + static GlobalSelector getFromOpaquePtr(void *Ptr) { return GlobalSelector(Ptr); } - friend bool operator==(const GlobalSelector &LHS, const GlobalSelector &RHS) { + friend bool operator==(const GlobalSelector &LHS, const GlobalSelector &RHS) { return LHS.getAsOpaquePtr() == RHS.getAsOpaquePtr(); } - + // For use in a std::map. - friend bool operator< (const GlobalSelector &LHS, const GlobalSelector &RHS) { + friend bool operator< (const GlobalSelector &LHS, const GlobalSelector &RHS) { return LHS.getAsOpaquePtr() < RHS.getAsOpaquePtr(); } @@ -66,7 +66,7 @@ public: return GlobalSelector((void*)-2); } }; - + } // namespace idx } // namespace clang @@ -86,7 +86,7 @@ struct DenseMapInfo { static unsigned getHashValue(clang::idx::GlobalSelector); - static inline bool + static inline bool isEqual(clang::idx::GlobalSelector LHS, clang::idx::GlobalSelector RHS) { return LHS == RHS; } diff --git a/clang/include/clang/Index/Handlers.h b/clang/include/clang/Index/Handlers.h index 2fe83c7f8b7799b2cb25bf0a8a7ef2ab682cd4ae..655aef901cd163c23f9c69c8927bca1e538c9a60 100644 --- a/clang/include/clang/Index/Handlers.h +++ b/clang/include/clang/Index/Handlers.h @@ -63,7 +63,7 @@ class Storing : public handler_type { typedef typename handler_type::receiving_type receiving_type; typedef llvm::SmallVector StoreTy; StoreTy Store; - + public: virtual void Handle(receiving_type Obj) { Store.push_back(Obj); diff --git a/clang/include/clang/Index/Indexer.h b/clang/include/clang/Index/Indexer.h index 0fcf31c6443719ef5ece0438f29ddcb10c1fd5fb..7bb48f2b757a959b579d24d8b8edbf36ed0b9342 100644 --- a/clang/include/clang/Index/Indexer.h +++ b/clang/include/clang/Index/Indexer.h @@ -37,13 +37,13 @@ public: typedef std::map MapTy; typedef std::map SelMapTy; - explicit Indexer(Program &prog, FileManager &FM) : + explicit Indexer(Program &prog, FileManager &FM) : Prog(prog), FileMgr(FM) { } Program &getProgram() const { return Prog; } FileManager &getFileManager() const { return FileMgr; } - + /// \brief Find all Entities and map them to the given translation unit. void IndexAST(TranslationUnit *TU); @@ -55,7 +55,7 @@ public: private: Program &Prog; FileManager &FileMgr; - + MapTy Map; CtxTUMapTy CtxTUMap; SelMapTy SelMap; diff --git a/clang/include/clang/Index/Program.h b/clang/include/clang/Index/Program.h index a9e0b878d7767a676c77c91714b982909ce1975a..8039192512d62fa574a81a78fd8391e6a3beb9cd 100644 --- a/clang/include/clang/Index/Program.h +++ b/clang/include/clang/Index/Program.h @@ -29,7 +29,7 @@ class Program { Program &operator=(const Program &); // do not implement friend class Entity; friend class GlobalSelector; - + public: Program(); ~Program(); diff --git a/clang/include/clang/Index/STLExtras.h b/clang/include/clang/Index/STLExtras.h index a9707204c5e10c2ae308e6804bf3b9a855f53427..a3693c6c79a62f3f4d0e9f2305fd65cac927a7a6 100644 --- a/clang/include/clang/Index/STLExtras.h +++ b/clang/include/clang/Index/STLExtras.h @@ -48,16 +48,16 @@ public: return tmp; } - friend bool operator==(pair_value_iterator L, pair_value_iterator R) { + friend bool operator==(pair_value_iterator L, pair_value_iterator R) { return L.I == R.I; } - friend bool operator!=(pair_value_iterator L, pair_value_iterator R) { + friend bool operator!=(pair_value_iterator L, pair_value_iterator R) { return L.I != R.I; } }; } // end idx namespace - + } // end clang namespace #endif diff --git a/clang/include/clang/Index/SelectorMap.h b/clang/include/clang/Index/SelectorMap.h index 0fb6afb7413e258020da2a8487af5e8c5741a168..be01702fcbdbea5fb46f38bcb067d9ff3e5bad0d 100644 --- a/clang/include/clang/Index/SelectorMap.h +++ b/clang/include/clang/Index/SelectorMap.h @@ -25,14 +25,14 @@ namespace clang { class ObjCMethodDecl; namespace idx { - + /// \brief Maps NamedDecls with the ASTLocations that reference them. /// /// References are mapped and retrieved using the canonical decls. class SelectorMap { public: explicit SelectorMap(ASTContext &Ctx); - + typedef std::multimap SelMethMapTy; typedef std::multimap SelRefMapTy; @@ -44,14 +44,14 @@ public: astlocation_iterator refs_begin(Selector Sel) const; astlocation_iterator refs_end(Selector Sel) const; - + private: mutable SelMethMapTy SelMethMap; mutable SelRefMapTy SelRefMap; }; } // end idx namespace - + } // end clang namespace #endif diff --git a/clang/include/clang/Lex/DirectoryLookup.h b/clang/include/clang/Lex/DirectoryLookup.h index 618de39233db7399ce3c13b34d2a79cf250b83dc..c94a9902241550b4a11eb386103427ac17d28ea2 100644 --- a/clang/include/clang/Lex/DirectoryLookup.h +++ b/clang/include/clang/Lex/DirectoryLookup.h @@ -38,20 +38,20 @@ private: /// Dir - This is the actual directory that we're referring to for a normal /// directory or a framework. const DirectoryEntry *Dir; - + /// Map - This is the HeaderMap if this is a headermap lookup. /// const HeaderMap *Map; } u; - + /// DirCharacteristic - The type of directory this is: this is an instance of /// SrcMgr::CharacteristicKind. unsigned DirCharacteristic : 2; - + /// UserSupplied - True if this is a user-supplied directory. /// bool UserSupplied : 1; - + /// LookupType - This indicates whether this DirectoryLookup object is a /// normal directory, a framework, or a headermap. unsigned LookupType : 2; @@ -62,25 +62,25 @@ public: bool isUser, bool isFramework) : DirCharacteristic(DT), UserSupplied(isUser), LookupType(isFramework ? LT_Framework : LT_NormalDir) { - u.Dir = dir; + u.Dir = dir; } - + /// DirectoryLookup ctor - Note that this ctor *does not take ownership* of /// 'map'. DirectoryLookup(const HeaderMap *map, SrcMgr::CharacteristicKind DT, bool isUser) : DirCharacteristic(DT), UserSupplied(isUser), LookupType(LT_HeaderMap) { - u.Map = map; + u.Map = map; } - + /// getLookupType - Return the kind of directory lookup that this is: either a /// normal directory, a framework path, or a HeaderMap. LookupType_t getLookupType() const { return (LookupType_t)LookupType; } - + /// getName - Return the directory or filename corresponding to this lookup /// object. const char *getName() const; - + /// getDir - Return the directory that this entry refers to. /// const DirectoryEntry *getDir() const { return isNormalDir() ? u.Dir : 0; } @@ -90,42 +90,42 @@ public: const DirectoryEntry *getFrameworkDir() const { return isFramework() ? u.Dir : 0; } - + /// getHeaderMap - Return the directory that this entry refers to. /// const HeaderMap *getHeaderMap() const { return isHeaderMap() ? u.Map : 0; } /// isNormalDir - Return true if this is a normal directory, not a header map. bool isNormalDir() const { return getLookupType() == LT_NormalDir; } - + /// isFramework - True if this is a framework directory. /// bool isFramework() const { return getLookupType() == LT_Framework; } - + /// isHeaderMap - Return true if this is a header map, not a normal directory. bool isHeaderMap() const { return getLookupType() == LT_HeaderMap; } - + /// DirCharacteristic - The type of directory this is, one of the DirType enum /// values. SrcMgr::CharacteristicKind getDirCharacteristic() const { return (SrcMgr::CharacteristicKind)DirCharacteristic; } - + /// isUserSupplied - True if this is a user-supplied directory. /// bool isUserSupplied() const { return UserSupplied; } - - + + /// LookupFile - Lookup the specified file in this search path, returning it /// if it exists or returning null if not. const FileEntry *LookupFile(const char *FilenameStart, const char *FilenameEnd, HeaderSearch &HS) const; - + private: const FileEntry *DoFrameworkLookup(const char *FilenameStart, - const char *FilenameEnd, + const char *FilenameEnd, HeaderSearch &HS) const; - + }; } // end namespace clang diff --git a/clang/include/clang/Lex/HeaderMap.h b/clang/include/clang/Lex/HeaderMap.h index d8033093bd8e78859e37e9e075d59a527ed8e937..6bb7c25947d7c95695168f53127a2197855a9a07 100644 --- a/clang/include/clang/Lex/HeaderMap.h +++ b/clang/include/clang/Lex/HeaderMap.h @@ -30,31 +30,31 @@ namespace clang { class HeaderMap { HeaderMap(const HeaderMap&); // DO NOT IMPLEMENT void operator=(const HeaderMap&); // DO NOT IMPLEMENT - + const llvm::MemoryBuffer *FileBuffer; bool NeedsBSwap; - + HeaderMap(const llvm::MemoryBuffer *File, bool BSwap) : FileBuffer(File), NeedsBSwap(BSwap) { } public: ~HeaderMap(); - + /// HeaderMap::Create - This attempts to load the specified file as a header /// map. If it doesn't look like a HeaderMap, it gives up and returns null. static const HeaderMap *Create(const FileEntry *FE); - + /// LookupFile - Check to see if the specified relative filename is located in /// this HeaderMap. If so, open it and return its FileEntry. const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, FileManager &FM) const; - + /// getFileName - Return the filename of the headermap. const char *getFileName() const; - + /// dump - Print the contents of this headermap to stderr. void dump() const; - + private: unsigned getEndianAdjustedWord(unsigned X) const; const HMapHeader &getHeader() const; diff --git a/clang/include/clang/Lex/HeaderSearch.h b/clang/include/clang/Lex/HeaderSearch.h index f21aab1b40152500278d639d45b1ce78924c1d78..7517440983b12fc46e23726336747ea7be40bd46 100644 --- a/clang/include/clang/Lex/HeaderSearch.h +++ b/clang/include/clang/Lex/HeaderSearch.h @@ -30,17 +30,17 @@ class IdentifierInfo; struct HeaderFileInfo { /// isImport - True if this is a #import'd or #pragma once file. bool isImport : 1; - + /// DirInfo - Keep track of whether this is a system header, and if so, /// whether it is C++ clean or not. This can be set by the include paths or /// by #pragma gcc system_header. This is an instance of /// SrcMgr::CharacteristicKind. unsigned DirInfo : 2; - + /// NumIncludes - This is the number of times the file has been included /// already. unsigned short NumIncludes; - + /// ControllingMacro - If this file has a #ifndef XXX (or equivalent) guard /// that protects the entire contents of the file, this is the identifier /// for the macro that controls whether or not it has any effect. @@ -51,14 +51,14 @@ struct HeaderFileInfo { /// external storage. const IdentifierInfo *ControllingMacro; - /// \brief The ID number of the controlling macro. + /// \brief The ID number of the controlling macro. /// /// This ID number will be non-zero when there is a controlling /// macro whose IdentifierInfo may not yet have been loaded from /// external storage. unsigned ControllingMacroID; - HeaderFileInfo() + HeaderFileInfo() : isImport(false), DirInfo(SrcMgr::C_User), NumIncludes(0), ControllingMacro(0), ControllingMacroID(0) {} @@ -71,7 +71,7 @@ struct HeaderFileInfo { /// file referenced by a #include or #include_next, (sub-)framework lookup, etc. class HeaderSearch { FileManager &FileMgr; - + /// #include search path information. Requests for #include "x" search the /// directory of the #including file first, then each directory in SearchDirs /// consequtively. Requests for search the current dir first, then each @@ -81,7 +81,7 @@ class HeaderSearch { std::vector SearchDirs; unsigned SystemDirIdx; bool NoCurDirSearch; - + /// FileInfo - This contains all of the preprocessor-specific data about files /// that are included. The vector is indexed by the FileEntry's UID. /// @@ -94,13 +94,13 @@ class HeaderSearch { /// ignored. The second value is the entry in SearchDirs that satisfied the /// query. llvm::StringMap > LookupFileCache; - - + + /// FrameworkMap - This is a collection mapping a framework or subframework /// name like "Carbon" to the Carbon.framework directory. llvm::StringMap FrameworkMap; - /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing + /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing /// headermaps. This vector owns the headermap. std::vector > HeaderMaps; @@ -114,7 +114,7 @@ class HeaderSearch { unsigned NumFrameworkLookups, NumSubFrameworkLookups; // HeaderSearch doesn't support default or copy construction. - explicit HeaderSearch(); + explicit HeaderSearch(); explicit HeaderSearch(const HeaderSearch&); void operator=(const HeaderSearch&); public: @@ -132,12 +132,12 @@ public: NoCurDirSearch = noCurDirSearch; //LookupFileCache.clear(); } - + /// ClearFileInfo - Forget everything we know about headers so far. void ClearFileInfo() { FileInfo.clear(); } - + void SetExternalLookup(ExternalIdentifierLookup *EIL) { ExternalLookup = EIL; } @@ -155,7 +155,7 @@ public: const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, const FileEntry *CurFileEnt); - + /// LookupSubframeworkHeader - Look up a subframework for the specified /// #include file. For example, if #include'ing from /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox @@ -164,7 +164,7 @@ public: const FileEntry *LookupSubframeworkHeader(const char *FilenameStart, const char *FilenameEnd, const FileEntry *RelativeFileEnt); - + /// LookupFrameworkCache - Look up the specified framework name in our /// framework cache, returning the DirectoryEntry it is in if we know, /// otherwise, return null. @@ -172,19 +172,19 @@ public: const char *FWNameEnd) { return FrameworkMap.GetOrCreateValue(FWNameStart, FWNameEnd).getValue(); } - + /// ShouldEnterIncludeFile - Mark the specified file as a target of of a /// #include, #include_next, or #import directive. Return false if #including /// the file will have no effect or true if we should include it. bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport); - - + + /// getFileDirFlavor - Return whether the specified file is a normal header, /// a system header, or a C++ friendly system header. SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) { return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo; } - + /// MarkFileIncludeOnce - Mark the specified file as a "once only" file, e.g. /// due to #pragma once. void MarkFileIncludeOnce(const FileEntry *File) { @@ -196,13 +196,13 @@ public: void MarkFileSystemHeader(const FileEntry *File) { getFileInfo(File).DirInfo = SrcMgr::C_System; } - + /// IncrementIncludeCount - Increment the count for the number of times the /// specified FileEntry has been entered. void IncrementIncludeCount(const FileEntry *File) { ++getFileInfo(File).NumIncludes; } - + /// SetFileControllingMacro - Mark the specified file as having a controlling /// macro. This is used by the multiple-include optimization to eliminate /// no-op #includes. @@ -210,11 +210,11 @@ public: const IdentifierInfo *ControllingMacro) { getFileInfo(File).ControllingMacro = ControllingMacro; } - + /// CreateHeaderMap - This method returns a HeaderMap for the specified /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure. const HeaderMap *CreateHeaderMap(const FileEntry *FE); - + void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; } typedef std::vector::iterator header_file_iterator; @@ -223,10 +223,10 @@ public: // Used by PCHReader. void setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID); - + void PrintStats(); private: - + /// getFileInfo - Return the HeaderFileInfo structure for the specified /// FileEntry. HeaderFileInfo &getFileInfo(const FileEntry *FE); diff --git a/clang/include/clang/Lex/LexDiagnostic.h b/clang/include/clang/Lex/LexDiagnostic.h index 03d9b7b3bbb84fd9ea4e5a03b254745d48a0919a..a470aa0924fbc18eccaf7363451edd443b6dd12e 100644 --- a/clang/include/clang/Lex/LexDiagnostic.h +++ b/clang/include/clang/Lex/LexDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define LEXSTART diff --git a/clang/include/clang/Lex/Lexer.h b/clang/include/clang/Lex/Lexer.h index 3a73147152afc2e2b0dc700732175670599cc4dc..1443ef11841b78081b1715b29088d538c035b474 100644 --- a/clang/include/clang/Lex/Lexer.h +++ b/clang/include/clang/Lex/Lexer.h @@ -39,11 +39,11 @@ class Lexer : public PreprocessorLexer { SourceLocation FileLoc; // Location for start of file. LangOptions Features; // Features enabled by this language (cache). bool Is_PragmaLexer; // True if lexer for _Pragma handling. - + //===--------------------------------------------------------------------===// // Context-specific lexing flags set by the preprocessor. // - + /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace /// and return them as tokens. This is used for -C and -CC modes, and /// whitespace preservation can be useful for some clients that want to lex @@ -52,7 +52,7 @@ class Lexer : public PreprocessorLexer { /// When this is set to 2 it returns comments and whitespace. When set to 1 /// it returns comments, when it is set to 0 it returns normal tokens only. unsigned char ExtendedTokenMode; - + //===--------------------------------------------------------------------===// // Context that changes as the file is lexed. // NOTE: any state that mutates when in raw mode must have save/restore code @@ -65,14 +65,14 @@ class Lexer : public PreprocessorLexer { // IsAtStartOfLine - True if the next lexed token should get the "start of // line" flag set on it. bool IsAtStartOfLine; - + Lexer(const Lexer&); // DO NOT IMPLEMENT void operator=(const Lexer&); // DO NOT IMPLEMENT friend class Preprocessor; - + void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd); public: - + /// Lexer constructor - Create a new lexer object for the specified buffer /// with the specified preprocessor managing the lexing process. This lexer /// assumes that the associated file buffer and Preprocessor objects will @@ -84,21 +84,21 @@ public: /// range will outlive it, so it doesn't take ownership of it. Lexer(SourceLocation FileLoc, const LangOptions &Features, const char *BufStart, const char *BufPtr, const char *BufEnd); - + /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexRawToken'. This lexer assumes that the text /// range will outlive it, so it doesn't take ownership of it. Lexer(FileID FID, const SourceManager &SM, const LangOptions &Features); - + /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for /// _Pragma expansion. This has a variety of magic semantics that this method /// sets up. It returns a new'd Lexer that must be delete'd when done. - static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc, + static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation InstantiationLocStart, SourceLocation InstantiationLocEnd, unsigned TokLen, Preprocessor &PP); - - + + /// getFeatures - Return the language features currently enabled. NOTE: this /// lexer modifies features as a file is parsed! const LangOptions &getFeatures() const { return Features; } @@ -108,7 +108,7 @@ public: /// the virtual location encodes where we should *claim* the characters came /// from. Currently this is only used by _Pragma handling. SourceLocation getFileLoc() const { return FileLoc; } - + /// Lex - Return the next token in the file. If this is the end of file, it /// return the tok::eof token. Return true if an error occurred and /// compilation should terminate, false if normal. This implicitly involves @@ -116,14 +116,14 @@ public: void Lex(Token &Result) { // Start a new token. Result.startToken(); - - // NOTE, any changes here should also change code after calls to + + // NOTE, any changes here should also change code after calls to // Preprocessor::HandleDirective if (IsAtStartOfLine) { Result.setFlag(Token::StartOfLine); IsAtStartOfLine = false; } - + // Get a token. Note that this may delete the current lexer if the end of // file is reached. LexTokenInternal(Result); @@ -131,11 +131,11 @@ public: /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma. bool isPragmaLexer() const { return Is_PragmaLexer; } - + /// IndirectLex - An indirect call to 'Lex' that can be invoked via /// the PreprocessorLexer interface. void IndirectLex(Token &Result) { Lex(Result); } - + /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no /// associated preprocessor object. Return true if the 'next character to /// read' pointer points at the end of the lexer buffer, false otherwise. @@ -144,7 +144,7 @@ public: Lex(Result); // Note that lexing to the end of the buffer doesn't implicitly delete the // lexer when in raw mode. - return BufferPtr == BufferEnd; + return BufferPtr == BufferEnd; } /// isKeepWhitespaceMode - Return true if the lexer should return tokens for @@ -168,23 +168,23 @@ public: bool inKeepCommentMode() const { return ExtendedTokenMode > 0; } - + /// SetCommentRetentionMode - Change the comment retention mode of the lexer /// to the specified mode. This is really only useful when lexing in raw /// mode, because otherwise the lexer needs to manage this. - void SetCommentRetentionState(bool Mode) { + void SetCommentRetentionState(bool Mode) { assert(!isKeepWhitespaceMode() && "Can't play with comment retention state when retaining whitespace"); ExtendedTokenMode = Mode ? 1 : 0; } - + const char *getBufferStart() const { return BufferStart; } - + /// ReadToEndOfLine - Read the rest of the current preprocessor line as an /// uninterpreted string. This switches the lexer out of directive mode. std::string ReadToEndOfLine(); - - + + /// Diag - Forwarding function for diagnostics. This translate a source /// position in the current buffer into a SourceLocation object for rendering. DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const; @@ -192,20 +192,20 @@ public: /// getSourceLocation - Return a source location identifier for the specified /// offset in the current file. SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const; - + /// getSourceLocation - Return a source location for the next character in /// the current file. SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); } - + /// Stringify - Convert the specified string into a C string by escaping '\' /// and " characters. This does not add surrounding ""'s to the string. /// If Charify is true, this escapes the ' character instead of ". static std::string Stringify(const std::string &Str, bool Charify = false); - + /// Stringify - Convert the specified string into a C string by escaping '\' /// and " characters. This does not add surrounding ""'s to the string. static void Stringify(llvm::SmallVectorImpl &Str); - + /// MeasureTokenLength - Relex the token at the specified location and return /// its length in bytes in the input file. If the token needs cleaning (e.g. /// includes a trigraph or an escaped newline) then this count includes bytes @@ -213,7 +213,7 @@ public: static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts); - + //===--------------------------------------------------------------------===// // Internal implementation interfaces. private: @@ -228,7 +228,7 @@ private: /// takes that range and assigns it to the token as its location and size. In /// addition, since tokens cannot overlap, this also updates BufferPtr to be /// TokEnd. - void FormTokenWithChars(Token &Result, const char *TokEnd, + void FormTokenWithChars(Token &Result, const char *TokEnd, tok::TokenKind Kind) { unsigned TokLen = TokEnd-BufferPtr; Result.setLength(TokLen); @@ -236,7 +236,7 @@ private: Result.setKind(Kind); BufferPtr = TokEnd; } - + /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a /// tok::l_paren token, 0 if it is something else and 2 if there are no more /// tokens in the buffer controlled by this lexer. @@ -245,7 +245,7 @@ private: //===--------------------------------------------------------------------===// // Lexer character reading interfaces. public: - + // This lexer is built on two interfaces for reading characters, both of which // automatically provide phase 1/2 translation. getAndAdvanceChar is used // when we know that we will be reading a character from the input buffer and @@ -260,7 +260,7 @@ public: // approach allows us to emit diagnostics for characters (e.g. warnings about // trigraphs), knowing that they only are emitted if the character is // consumed. - + /// isObviouslySimpleCharacter - Return true if the specified character is /// obviously the same in translation phase 1 and translation phase 3. This /// can return false for characters that end up being the same, but it will @@ -268,7 +268,7 @@ public: static bool isObviouslySimpleCharacter(char C) { return C != '?' && C != '\\'; } - + /// getAndAdvanceChar - Read a single 'character' from the specified buffer, /// advance over it, and return it. This is tricky in several cases. Here we /// just handle the trivial case and fall-back to the non-inlined @@ -277,13 +277,13 @@ public: // If this is not a trigraph and not a UCN or escaped newline, return // quickly. if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; - + unsigned Size = 0; char C = getCharAndSizeSlow(Ptr, Size, &Tok); Ptr += Size; return C; } - + private: /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed /// and added to a given token, check to see if there are diagnostics that @@ -300,7 +300,7 @@ private: getCharAndSizeSlow(Ptr, Size, &Tok); return Ptr+Size; } - + /// getCharAndSize - Peek a single 'character' from the specified buffer, /// get its size, and return it. This is tricky in several cases. Here we /// just handle the trivial case and fall-back to the non-inlined @@ -312,16 +312,16 @@ private: Size = 1; return *Ptr; } - + Size = 0; return getCharAndSizeSlow(Ptr, Size); } - + /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize /// method. char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0); public: - + /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever /// emit a warning. static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, @@ -332,30 +332,30 @@ public: Size = 1; return *Ptr; } - + Size = 0; return getCharAndSizeSlowNoWarn(Ptr, Size, Features); } - + /// getEscapedNewLineSize - Return the size of the specified escaped newline, /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry /// to this function. static unsigned getEscapedNewLineSize(const char *P); - + /// SkipEscapedNewLines - If P points to an escaped newline (or a series of /// them), skip over them and return the first non-escaped-newline found, /// otherwise return P. static const char *SkipEscapedNewLines(const char *P); private: - + /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a /// diagnostic. static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, const LangOptions &Features); - + //===--------------------------------------------------------------------===// // Other lexer functions. - + // Helper functions to lex the remainder of a token of the specific type. void LexIdentifier (Token &Result, const char *CurPtr); void LexNumericConstant (Token &Result, const char *CurPtr); @@ -363,7 +363,7 @@ private: void LexAngledStringLiteral(Token &Result, const char *CurPtr); void LexCharConstant (Token &Result, const char *CurPtr); bool LexEndOfFile (Token &Result, const char *CurPtr); - + bool SkipWhitespace (Token &Result, const char *CurPtr); bool SkipBCPLComment (Token &Result, const char *CurPtr); bool SkipBlockComment (Token &Result, const char *CurPtr); diff --git a/clang/include/clang/Lex/LiteralSupport.h b/clang/include/clang/Lex/LiteralSupport.h index 29b82c1807d17354a1486a4c1f9999d4ff3ab04d..1c1cc8031f83f9229db6ce28e7767d3f6b800c99 100644 --- a/clang/include/clang/Lex/LiteralSupport.h +++ b/clang/include/clang/Lex/LiteralSupport.h @@ -32,22 +32,22 @@ class Preprocessor; class Token; class SourceLocation; class TargetInfo; - + /// NumericLiteralParser - This performs strict semantic analysis of the content /// of a ppnumber, classifying it as either integer, floating, or erroneous, /// determines the radix of the value and can convert it to a useful value. class NumericLiteralParser { Preprocessor &PP; // needed for diagnostics - + const char *const ThisTokBegin; const char *const ThisTokEnd; const char *DigitsBegin, *SuffixBegin; // markers const char *s; // cursor - + unsigned radix; - + bool saw_exponent, saw_period; - + public: NumericLiteralParser(const char *begin, const char *end, SourceLocation Loc, Preprocessor &PP); @@ -57,8 +57,8 @@ public: bool isLongLong; bool isFloat; // 1.0f bool isImaginary; // 1.0i - - bool isIntegerLiteral() const { + + bool isIntegerLiteral() const { return !saw_period && !saw_exponent; } bool isFloatingLiteral() const { @@ -67,27 +67,27 @@ public: bool hasSuffix() const { return SuffixBegin != ThisTokEnd; } - + unsigned getRadix() const { return radix; } - + /// GetIntegerValue - Convert this numeric literal value to an APInt that /// matches Val's input width. If there is an overflow (i.e., if the unsigned /// value read is larger than the APInt's bits will hold), set Val to the low /// bits of the result and return true. Otherwise, return false. bool GetIntegerValue(llvm::APInt &Val); - + /// GetFloatValue - Convert this numeric literal to a floating value, using /// the specified APFloat fltSemantics (specifying float, double, etc). /// The optional bool isExact (passed-by-reference) has its value /// set to true if the returned APFloat can represent the number in the /// literal exactly, and false otherwise. - llvm::APFloat GetFloatValue(const llvm::fltSemantics &Format, + llvm::APFloat GetFloatValue(const llvm::fltSemantics &Format, bool* isExact = NULL); -private: - +private: + void ParseNumberStartingWithZero(SourceLocation TokLoc); - + /// SkipHexDigits - Read and skip over any hex digits, up to End. /// Return a pointer to the first non-hex digit or End. const char *SkipHexDigits(const char *ptr) { @@ -95,7 +95,7 @@ private: ptr++; return ptr; } - + /// SkipOctalDigits - Read and skip over any octal digits, up to End. /// Return a pointer to the first non-hex digit or End. const char *SkipOctalDigits(const char *ptr) { @@ -103,7 +103,7 @@ private: ptr++; return ptr; } - + /// SkipDigits - Read and skip over any digits, up to End. /// Return a pointer to the first non-hex digit or End. const char *SkipDigits(const char *ptr) { @@ -111,7 +111,7 @@ private: ptr++; return ptr; } - + /// SkipBinaryDigits - Read and skip over any binary digits, up to End. /// Return a pointer to the first non-binary digit or End. const char *SkipBinaryDigits(const char *ptr) { @@ -119,7 +119,7 @@ private: ptr++; return ptr; } - + }; /// CharLiteralParser - Perform interpretation and semantic analysis of a @@ -144,7 +144,7 @@ public: /// literals) (C99 5.1.1.2p1). class StringLiteralParser { Preprocessor &PP; - + unsigned MaxTokenLength; unsigned SizeBound; unsigned wchar_tByteWidth; @@ -156,7 +156,7 @@ public: bool hadError; bool AnyWide; bool Pascal; - + const char *GetString() { return &ResultBuf[0]; } unsigned GetStringLength() const { return ResultPtr-&ResultBuf[0]; } @@ -164,14 +164,14 @@ public: if (AnyWide) return GetStringLength() / wchar_tByteWidth; return GetStringLength(); - } + } /// getOffsetOfStringByte - This function returns the offset of the /// specified byte of the string data represented by Token. This handles /// advancing over escape sequences in the string. static unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo, Preprocessor &PP); }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Lex/MacroInfo.h b/clang/include/clang/Lex/MacroInfo.h index ccd13c80d354699a8f444ba4851285caea0f4118..5887041c46b9fa487069bfc1edced6408780f212 100644 --- a/clang/include/clang/Lex/MacroInfo.h +++ b/clang/include/clang/Lex/MacroInfo.h @@ -22,7 +22,7 @@ namespace clang { class Preprocessor; - + /// MacroInfo - Each identifier that is #define'd has an instance of this class /// associated with it, used to implement macro expansion. class MacroInfo { @@ -39,7 +39,7 @@ class MacroInfo { /// includes the __VA_ARGS__ identifier on the list. IdentifierInfo **ArgumentList; unsigned NumArguments; - + /// ReplacementTokens - This is the list of tokens that the macro is defined /// to. llvm::SmallVector ReplacementTokens; @@ -47,21 +47,21 @@ class MacroInfo { /// IsFunctionLike - True if this macro is a function-like macro, false if it /// is an object-like macro. bool IsFunctionLike : 1; - + /// IsC99Varargs - True if this macro is of the form "#define X(...)" or /// "#define X(Y,Z,...)". The __VA_ARGS__ token should be replaced with the /// contents of "..." in an invocation. bool IsC99Varargs : 1; - + /// IsGNUVarargs - True if this macro is of the form "#define X(a...)". The /// "a" identifier in the replacement list will be replaced with all arguments /// of the macro starting with the specified one. bool IsGNUVarargs : 1; - + /// IsBuiltinMacro - True if this is a builtin macro, such as __LINE__, and if /// it has not yet been redefined or undefined. bool IsBuiltinMacro : 1; - + private: //===--------------------------------------------------------------------===// // State that changes as the macro is used. @@ -70,19 +70,19 @@ private: /// This disbles recursive expansion, which would be quite bad for things like /// #define A A. bool IsDisabled : 1; - + /// IsUsed - True if this macro is either defined in the main file and has - /// been used, or if it is not defined in the main file. This is used to + /// been used, or if it is not defined in the main file. This is used to /// emit -Wunused-macros diagnostics. bool IsUsed : 1; - + ~MacroInfo() { assert(ArgumentList == 0 && "Didn't call destroy before dtor!"); } - + public: MacroInfo(SourceLocation DefLoc); - + /// FreeArgumentList - Free the argument list of the macro, restoring it to a /// state where it can be reused for other devious purposes. void FreeArgumentList(llvm::BumpPtrAllocator &PPAllocator) { @@ -90,13 +90,13 @@ public: ArgumentList = 0; NumArguments = 0; } - + /// Destroy - destroy this MacroInfo object. void Destroy(llvm::BumpPtrAllocator &PPAllocator) { FreeArgumentList(PPAllocator); this->~MacroInfo(); } - + /// getDefinitionLoc - Return the location that the macro was defined at. /// SourceLocation getDefinitionLoc() const { return Location; } @@ -112,13 +112,13 @@ public: /// this macro in spelling, arguments, and whitespace. This is used to emit /// duplicate definition warnings. This implements the rules in C99 6.10.3. bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP) const; - + /// setIsBuiltinMacro - Set or clear the isBuiltinMacro flag. /// void setIsBuiltinMacro(bool Val = true) { IsBuiltinMacro = Val; } - + /// setIsUsed - Set the value of the IsUsed flag. /// void setIsUsed(bool Val) { @@ -132,13 +132,13 @@ public: assert(ArgumentList == 0 && NumArguments == 0 && "Argument list already set!"); if (NumArgs == 0) return; - + NumArguments = NumArgs; ArgumentList = PPAllocator.Allocate(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) ArgumentList[i] = List[i]; } - + /// Arguments - The list of arguments for a function-like macro. This can be /// empty, for, e.g. "#define X()". typedef IdentifierInfo* const *arg_iterator; @@ -146,7 +146,7 @@ public: arg_iterator arg_begin() const { return ArgumentList; } arg_iterator arg_end() const { return ArgumentList+NumArguments; } unsigned getNumArgs() const { return NumArguments; } - + /// getArgumentNum - Return the argument number of the specified identifier, /// or -1 if the identifier is not a formal argument identifier. int getArgumentNum(IdentifierInfo *Arg) const { @@ -154,20 +154,20 @@ public: if (*I == Arg) return I-arg_begin(); return -1; } - + /// Function/Object-likeness. Keep track of whether this macro has formal /// parameters. void setIsFunctionLike() { IsFunctionLike = true; } bool isFunctionLike() const { return IsFunctionLike; } bool isObjectLike() const { return !IsFunctionLike; } - + /// Varargs querying methods. This can only be set for function-like macros. void setIsC99Varargs() { IsC99Varargs = true; } void setIsGNUVarargs() { IsGNUVarargs = true; } bool isC99Varargs() const { return IsC99Varargs; } bool isGNUVarargs() const { return IsGNUVarargs; } bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; } - + /// isBuiltinMacro - Return true if this macro is a builtin macro, such as /// __LINE__, which requires processing before expansion. bool isBuiltinMacro() const { return IsBuiltinMacro; } @@ -175,7 +175,7 @@ public: /// isUsed - Return false if this macro is defined in the main file and has /// not yet been used. bool isUsed() const { return IsUsed; } - + /// getNumTokens - Return the number of tokens that this macro expands to. /// unsigned getNumTokens() const { @@ -186,22 +186,22 @@ public: assert(Tok < ReplacementTokens.size() && "Invalid token #"); return ReplacementTokens[Tok]; } - + typedef llvm::SmallVector::const_iterator tokens_iterator; tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); } tokens_iterator tokens_end() const { return ReplacementTokens.end(); } bool tokens_empty() const { return ReplacementTokens.empty(); } - + /// AddTokenToBody - Add the specified token to the replacement text for the /// macro. void AddTokenToBody(const Token &Tok) { ReplacementTokens.push_back(Tok); } - + /// isEnabled - Return true if this macro is enabled: in other words, that we /// are not currently in an expansion of this macro. bool isEnabled() const { return !IsDisabled; } - + void EnableMacro() { assert(IsDisabled && "Cannot enable an already-enabled macro!"); IsDisabled = false; @@ -212,7 +212,7 @@ public: IsDisabled = true; } }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Lex/MultipleIncludeOpt.h b/clang/include/clang/Lex/MultipleIncludeOpt.h index 94d4677f9d29cba7829b161a50eff5752c17f874..5d5d6732905960aaf44a0638bbe2f19fa85a0b7f 100644 --- a/clang/include/clang/Lex/MultipleIncludeOpt.h +++ b/clang/include/clang/Lex/MultipleIncludeOpt.h @@ -36,7 +36,7 @@ class MultipleIncludeOpt { /// to false, that way any tokens before the first #ifdef or after the last /// #endif can be easily detected. bool DidMacroExpansion; - + /// TheMacro - The controlling macro for a file, if valid. /// const IdentifierInfo *TheMacro; @@ -46,7 +46,7 @@ public: DidMacroExpansion = false; TheMacro = 0; } - + /// Invalidate - Permenantly mark this file as not being suitable for the /// include-file optimization. void Invalidate() { @@ -55,19 +55,19 @@ public: ReadAnyTokens = true; TheMacro = 0; } - + /// getHasReadAnyTokensVal - This is used for the #ifndef hande-shake at the /// top of the file when reading preprocessor directives. Otherwise, reading /// the "ifndef x" would count as reading tokens. bool getHasReadAnyTokensVal() const { return ReadAnyTokens; } - + // If a token is read, remember that we have seen a side-effect in this file. void ReadToken() { ReadAnyTokens = true; } - + /// ExpandedMacro - When a macro is expanded with this lexer as the current /// buffer, this method is called to disable the MIOpt if needed. void ExpandedMacro() { DidMacroExpansion = true; } - + /// EnterTopLevelIFNDEF - When entering a top-level #ifndef directive (or the /// "#if !defined" equivalent) without any preceding tokens, this method is /// called. @@ -80,14 +80,14 @@ public: // If the macro is already set, this is after the top-level #endif. if (TheMacro) return Invalidate(); - + // If we have already expanded a macro by the end of the #ifndef line, then // there is a macro expansion *in* the #ifndef line. This means that the // condition could evaluate differently when subsequently #included. Reject // this. if (DidMacroExpansion) return Invalidate(); - + // Remember that we're in the #if and that we have the macro. ReadAnyTokens = true; TheMacro = M; @@ -100,7 +100,7 @@ public: /// there is a chunk of the file not guarded by the controlling macro. Invalidate(); } - + /// ExitTopLevelConditional - This method is called when the lexer exits the /// top-level conditional. void ExitTopLevelConditional() { @@ -108,12 +108,12 @@ public: // back to "not having read any tokens" so we can detect anything after the // #endif. if (!TheMacro) return Invalidate(); - + // At this point, we haven't "read any tokens" but we do have a controlling // macro. ReadAnyTokens = false; } - + /// GetControllingMacroAtEndOfFile - Once the entire file has been lexed, if /// there is a controlling macro, return it. const IdentifierInfo *GetControllingMacroAtEndOfFile() const { diff --git a/clang/include/clang/Lex/PPCallbacks.h b/clang/include/clang/Lex/PPCallbacks.h index e5cbeebd22aa02a5e4142df407e17fef03d0abba..dd24fb7d7ba25fb0d806d731114097d5adc4a690 100644 --- a/clang/include/clang/Lex/PPCallbacks.h +++ b/clang/include/clang/Lex/PPCallbacks.h @@ -23,18 +23,18 @@ namespace clang { class Token; class IdentifierInfo; class MacroInfo; - + /// PPCallbacks - This interface provides a way to observe the actions of the /// preprocessor as it does its thing. Clients can define their hooks here to /// implement preprocessor level tools. class PPCallbacks { public: virtual ~PPCallbacks(); - + enum FileChangeReason { EnterFile, ExitFile, SystemHeaderPragma, RenameFile }; - + /// FileChanged - This callback is invoked whenever a source file is /// entered or exited. The SourceLocation indicates the new location, and /// EnteringFile indicates whether this is because we are entering a new @@ -43,25 +43,25 @@ public: virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType) { } - + /// Ident - This callback is invoked when a #ident or #sccs directive is read. /// virtual void Ident(SourceLocation Loc, const std::string &str) { } - + /// PragmaComment - This callback is invoked when a #pragma comment directive /// is read. /// - virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, + virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, const std::string &Str) { } - + /// MacroExpands - This is called by /// Preprocessor::HandleMacroExpandedIdentifier when a macro invocation is /// found. virtual void MacroExpands(const Token &Id, const MacroInfo* MI) { } - + /// MacroDefined - This hook is called whenever a macro definition is seen. virtual void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI) { } @@ -76,7 +76,7 @@ public: class PPChainedCallbacks : public PPCallbacks { PPCallbacks *First, *Second; -public: +public: PPChainedCallbacks(PPCallbacks *_First, PPCallbacks *_Second) : First(_First), Second(_Second) {} ~PPChainedCallbacks() { @@ -89,23 +89,23 @@ public: First->FileChanged(Loc, Reason, FileType); Second->FileChanged(Loc, Reason, FileType); } - + virtual void Ident(SourceLocation Loc, const std::string &str) { First->Ident(Loc, str); Second->Ident(Loc, str); } - - virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, + + virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, const std::string &Str) { First->PragmaComment(Loc, Kind, Str); Second->PragmaComment(Loc, Kind, Str); } - + virtual void MacroExpands(const Token &Id, const MacroInfo* MI) { First->MacroExpands(Id, MI); Second->MacroExpands(Id, MI); } - + virtual void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI) { First->MacroDefined(II, MI); Second->MacroDefined(II, MI); diff --git a/clang/include/clang/Lex/PTHLexer.h b/clang/include/clang/Lex/PTHLexer.h index 369b818a1fc9ea117e5e1eb1b81e938e78a7fe98..e96a8c514e6eb14a8cf39cca1bea9b5ba69b2482 100644 --- a/clang/include/clang/Lex/PTHLexer.h +++ b/clang/include/clang/Lex/PTHLexer.h @@ -18,42 +18,42 @@ #include namespace clang { - + class PTHManager; class PTHSpellingSearch; - + class PTHLexer : public PreprocessorLexer { SourceLocation FileStartLoc; - + /// TokBuf - Buffer from PTH file containing raw token data. const unsigned char* TokBuf; - + /// CurPtr - Pointer into current offset of the token buffer where /// the next token will be read. const unsigned char* CurPtr; - + /// LastHashTokPtr - Pointer into TokBuf of the last processed '#' /// token that appears at the start of a line. const unsigned char* LastHashTokPtr; - + /// PPCond - Pointer to a side table in the PTH file that provides a /// a consise summary of the preproccessor conditional block structure. /// This is used to perform quick skipping of conditional blocks. const unsigned char* PPCond; - + /// CurPPCondPtr - Pointer inside PPCond that refers to the next entry /// to process when doing quick skipping of preprocessor blocks. const unsigned char* CurPPCondPtr; PTHLexer(const PTHLexer&); // DO NOT IMPLEMENT void operator=(const PTHLexer&); // DO NOT IMPLEMENT - + /// ReadToken - Used by PTHLexer to read tokens TokBuf. void ReadToken(Token& T); /// PTHMgr - The PTHManager object that created this PTHLexer. PTHManager& PTHMgr; - + Token EofToken; protected: @@ -62,19 +62,19 @@ protected: /// Create a PTHLexer for the specified token stream. PTHLexer(Preprocessor& pp, FileID FID, const unsigned char *D, const unsigned char* ppcond, PTHManager &PM); -public: +public: ~PTHLexer() {} - + /// Lex - Return the next token. void Lex(Token &Tok); - + void getEOF(Token &Tok); - + /// DiscardToEndOfLine - Read the rest of the current preprocessor line as an /// uninterpreted string. This switches the lexer out of directive mode. void DiscardToEndOfLine(); - + /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a /// tok::l_paren token, 0 if it is something else and 2 if there are no more /// tokens controlled by this lexer. @@ -85,12 +85,12 @@ public: // its kind. tok::TokenKind x = (tok::TokenKind)*CurPtr; return x == tok::eof ? 2 : x == tok::l_paren; - } + } /// IndirectLex - An indirect call to 'Lex' that can be invoked via /// the PreprocessorLexer interface. void IndirectLex(Token &Result) { Lex(Result); } - + /// getSourceLocation - Return a source location for the token in /// the current file. SourceLocation getSourceLocation(); diff --git a/clang/include/clang/Lex/PTHManager.h b/clang/include/clang/Lex/PTHManager.h index 507576473f60eba47e6bd6d5a62afad9d24ffa1a..ff1a17259e8a6aa6dbd48a1419684f6c726b26ad 100644 --- a/clang/include/clang/Lex/PTHManager.h +++ b/clang/include/clang/Lex/PTHManager.h @@ -32,29 +32,29 @@ class FileEntry; class PTHLexer; class Diagnostic; class StatSysCallCache; - + class PTHManager : public IdentifierInfoLookup { friend class PTHLexer; - + /// The memory mapped PTH file. const llvm::MemoryBuffer* Buf; /// Alloc - Allocator used for IdentifierInfo objects. llvm::BumpPtrAllocator Alloc; - + /// IdMap - A lazily generated cache mapping from persistent identifiers to /// IdentifierInfo*. IdentifierInfo** PerIDCache; - + /// FileLookup - Abstract data structure used for mapping between files /// and token data in the PTH file. void* FileLookup; - + /// IdDataTable - Array representing the mapping from persistent IDs to the /// data offset within the PTH file containing the information to /// reconsitute an IdentifierInfo. const unsigned char* const IdDataTable; - + /// SortedIdTable - Abstract data structure mapping from strings to /// persistent IDs. This is used by get(). void* StringIdLookup; @@ -65,15 +65,15 @@ class PTHManager : public IdentifierInfoLookup { /// PP - The Preprocessor object that will use this PTHManager to create /// PTHLexer objects. Preprocessor* PP; - - /// SpellingBase - The base offset within the PTH memory buffer that + + /// SpellingBase - The base offset within the PTH memory buffer that /// contains the cached spellings for literals. const unsigned char* const SpellingBase; - + /// OriginalSourceFile - A null-terminated C-string that specifies the name /// if the file (if any) that was to used to generate the PTH cache. const char* OriginalSourceFile; - + /// This constructor is intended to only be called by the static 'Create' /// method. PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup, @@ -84,11 +84,11 @@ class PTHManager : public IdentifierInfoLookup { // Do not implement. PTHManager(); void operator=(const PTHManager&); - - /// getSpellingAtPTHOffset - Used by PTHLexer classes to get the cached + + /// getSpellingAtPTHOffset - Used by PTHLexer classes to get the cached /// spelling for a token. unsigned getSpellingAtPTHOffset(unsigned PTHOffset, const char*& Buffer); - + /// GetIdentifierInfo - Used to reconstruct IdentifierInfo objects from the /// PTH file. inline IdentifierInfo* GetIdentifierInfo(unsigned PersistentID) { @@ -98,44 +98,44 @@ class PTHManager : public IdentifierInfoLookup { return LazilyCreateIdentifierInfo(PersistentID); } IdentifierInfo* LazilyCreateIdentifierInfo(unsigned PersistentID); - + public: // The current PTH version. enum { Version = 9 }; ~PTHManager(); - + /// getOriginalSourceFile - Return the full path to the original header /// file name that was used to generate the PTH cache. const char* getOriginalSourceFile() const { return OriginalSourceFile; } - + /// get - Return the identifier token info for the specified named identifier. /// Unlike the version in IdentifierTable, this returns a pointer instead /// of a reference. If the pointer is NULL then the IdentifierInfo cannot /// be found. IdentifierInfo *get(const char *NameStart, const char *NameEnd); - + /// Create - This method creates PTHManager objects. The 'file' argument /// is the name of the PTH file. This method returns NULL upon failure. static PTHManager *Create(const std::string& file, Diagnostic* Diags = 0, Diagnostic::Level failureLevel=Diagnostic::Warning); - void setPreprocessor(Preprocessor *pp) { PP = pp; } - + void setPreprocessor(Preprocessor *pp) { PP = pp; } + /// CreateLexer - Return a PTHLexer that "lexes" the cached tokens for the /// specified file. This method returns NULL if no cached tokens exist. /// It is the responsibility of the caller to 'delete' the returned object. - PTHLexer *CreateLexer(FileID FID); - + PTHLexer *CreateLexer(FileID FID); + /// createStatCache - Returns a StatSysCallCache object for use with /// FileManager objects. These objects use the PTH data to speed up /// calls to stat by memoizing their results from when the PTH file /// was generated. StatSysCallCache *createStatCache(); }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Lex/Pragma.h b/clang/include/clang/Lex/Pragma.h index 136dc6fabfb673eeb0b6ac084475005dc0a9e344..ef367feb84db963da6aecb6fdd27f7c94d852aea 100644 --- a/clang/include/clang/Lex/Pragma.h +++ b/clang/include/clang/Lex/Pragma.h @@ -37,10 +37,10 @@ class PragmaHandler { public: PragmaHandler(const IdentifierInfo *name) : Name(name) {} virtual ~PragmaHandler(); - + const IdentifierInfo *getName() const { return Name; } virtual void HandlePragma(Preprocessor &PP, Token &FirstToken) = 0; - + /// getIfNamespace - If this is a namespace, return it. This is equivalent to /// using a dynamic_cast, but doesn't require RTTI. virtual PragmaNamespace *getIfNamespace() { return 0; } @@ -57,14 +57,14 @@ class PragmaNamespace : public PragmaHandler { public: PragmaNamespace(const IdentifierInfo *Name) : PragmaHandler(Name) {} virtual ~PragmaNamespace(); - + /// FindHandler - Check to see if there is already a handler for the /// specified name. If not, return the handler for the null identifier if it /// exists, otherwise return null. If IgnoreNull is true (the default) then /// the null handler isn't returned on failure to match. PragmaHandler *FindHandler(const IdentifierInfo *Name, bool IgnoreNull = true) const; - + /// AddPragma - Add a pragma to this namespace. /// void AddPragma(PragmaHandler *Handler) { @@ -75,12 +75,12 @@ public: /// namespace. void RemovePragmaHandler(PragmaHandler *Handler); - bool IsEmpty() { - return Handlers.empty(); + bool IsEmpty() { + return Handlers.empty(); } virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); - + virtual PragmaNamespace *getIfNamespace() { return this; } }; diff --git a/clang/include/clang/Lex/Preprocessor.h b/clang/include/clang/Lex/Preprocessor.h index f1647afaa3a77c25b034274326d6df1fa8eb3a23..d1c508a542aa9f745ff04f83feb20dd608fbcc46 100644 --- a/clang/include/clang/Lex/Preprocessor.h +++ b/clang/include/clang/Lex/Preprocessor.h @@ -29,7 +29,7 @@ #include namespace clang { - + class SourceManager; class FileManager; class FileEntry; @@ -41,7 +41,7 @@ class ScratchBuffer; class TargetInfo; class PPCallbacks; class DirectoryLookup; - + /// Preprocessor - This object engages in a tight little dance with the lexer to /// efficiently preprocess tokens. Lexers know only about tokens within a /// single source file, and don't know anything about preprocessor-level issues @@ -55,15 +55,15 @@ class Preprocessor { SourceManager &SourceMgr; ScratchBuffer *ScratchBuf; HeaderSearch &HeaderInfo; - + /// PTH - An optional PTHManager object used for getting tokens from /// a token cache rather than lexing the original source file. llvm::OwningPtr PTH; - + /// BP - A BumpPtrAllocator object used to quickly allocate and release /// objects internal to the Preprocessor. llvm::BumpPtrAllocator BP; - + /// Identifiers for builtin macros and other builtins. IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__ IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__ @@ -74,7 +74,7 @@ class Preprocessor { IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__ IdentifierInfo *Ident__has_feature; // __has_feature IdentifierInfo *Ident__has_builtin; // __has_builtin - + SourceLocation DATELoc, TIMELoc; unsigned CounterValue; // Next __COUNTER__ value. @@ -86,7 +86,7 @@ class Preprocessor { // State that is set before the preprocessor begins. bool KeepComments : 1; bool KeepMacroComments : 1; - + // State that changes while the preprocessor runs: bool DisableMacroExpansion : 1; // True if macro expansion is disabled. bool InMacroArgs : 1; // True if parsing fn macro invocation args. @@ -94,42 +94,42 @@ class Preprocessor { /// Identifiers - This is mapping/lookup information for all identifiers in /// the program, including program keywords. IdentifierTable Identifiers; - + /// Selectors - This table contains all the selectors in the program. Unlike /// IdentifierTable above, this table *isn't* populated by the preprocessor. - /// It is declared/instantiated here because it's role/lifetime is + /// It is declared/instantiated here because it's role/lifetime is /// conceptually similar the IdentifierTable. In addition, the current control - /// flow (in clang::ParseAST()), make it convenient to put here. + /// flow (in clang::ParseAST()), make it convenient to put here. /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to /// the lifetime fo the preprocessor. SelectorTable Selectors; /// BuiltinInfo - Information about builtins. Builtin::Context BuiltinInfo; - + /// PragmaHandlers - This tracks all of the pragmas that the client registered /// with this preprocessor. PragmaNamespace *PragmaHandlers; - - /// \brief Tracks all of the comment handlers that the client registered + + /// \brief Tracks all of the comment handlers that the client registered /// with this preprocessor. std::vector CommentHandlers; - + /// CurLexer - This is the current top of the stack that we're lexing from if /// not expanding a macro and we are lexing directly from source code. /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. llvm::OwningPtr CurLexer; - + /// CurPTHLexer - This is the current top of stack that we're lexing from if /// not expanding from a macro and we are lexing from a PTH cache. /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. llvm::OwningPtr CurPTHLexer; - + /// CurPPLexer - This is the current top of the stack what we're lexing from /// if not expanding a macro. This is an alias for either CurLexer or /// CurPTHLexer. PreprocessorLexer* CurPPLexer; - + /// CurLookup - The DirectoryLookup structure used to find the current /// FileEntry, if CurLexer is non-null and if applicable. This allows us to /// implement #include_next and find directory-specific properties. @@ -138,7 +138,7 @@ class Preprocessor { /// CurTokenLexer - This is the current macro we are expanding, if we are /// expanding a macro. One of CurLexer and CurTokenLexer must be null. llvm::OwningPtr CurTokenLexer; - + /// IncludeMacroStack - This keeps track of the stack of files currently /// #included, and macros currently being expanded from, not counting /// CurLexer/CurTokenLexer. @@ -146,7 +146,7 @@ class Preprocessor { Lexer *TheLexer; PTHLexer *ThePTHLexer; PreprocessorLexer *ThePPLexer; - TokenLexer *TheTokenLexer; + TokenLexer *TheTokenLexer; const DirectoryLookup *TheDirLookup; IncludeStackInfo(Lexer *L, PTHLexer* P, PreprocessorLexer* PPL, @@ -155,19 +155,19 @@ class Preprocessor { TheDirLookup(D) {} }; std::vector IncludeMacroStack; - + /// Callbacks - These are actions invoked when some preprocessor activity is /// encountered (e.g. a file is #included, etc). PPCallbacks *Callbacks; - + /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping /// to the actual definition of the macro. llvm::DenseMap Macros; - + /// MICache - A "freelist" of MacroInfo objects that can be reused for quick /// allocation. std::vector MICache; - + // Various statistics we track for performance analysis. unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma; unsigned NumIf, NumElse, NumEndif; @@ -175,11 +175,11 @@ class Preprocessor { unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded; unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste; unsigned NumSkipped; - + /// Predefines - This string is the predefined macros that preprocessor /// should use from the command line etc. std::string Predefines; - + /// TokenLexerCache - Cache macro expanders to reduce malloc traffic. enum { TokenLexerCacheSize = 8 }; unsigned NumCachedTokenLexers; @@ -223,9 +223,9 @@ public: SelectorTable &getSelectorTable() { return Selectors; } Builtin::Context &getBuiltinInfo() { return BuiltinInfo; } llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; } - + void setPTHManager(PTHManager* pm); - + PTHManager *getPTHManager() { return PTH.get(); } /// SetCommentRetentionState - Control whether or not the preprocessor retains @@ -234,20 +234,20 @@ public: this->KeepComments = KeepComments | KeepMacroComments; this->KeepMacroComments = KeepMacroComments; } - + bool getCommentRetentionState() const { return KeepComments; } - + /// isCurrentLexer - Return true if we are lexing directly from the specified /// lexer. bool isCurrentLexer(const PreprocessorLexer *L) const { return CurPPLexer == L; } - + /// getCurrentLexer - Return the current file lexer being lexed from. Note /// that this ignores any potentially active macro expansions and _Pragma /// expansions going on at the time. PreprocessorLexer *getCurrentFileLexer() const; - + /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks. /// Note that this class takes ownership of any PPCallbacks object given to /// it. @@ -257,32 +257,32 @@ public: C = new PPChainedCallbacks(C, Callbacks); Callbacks = C; } - + /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to /// or null if it isn't #define'd. MacroInfo *getMacroInfo(IdentifierInfo *II) const { return II->hasMacroDefinition() ? Macros.find(II)->second : 0; } - + /// setMacroInfo - Specify a macro for this identifier. /// void setMacroInfo(IdentifierInfo *II, MacroInfo *MI); - + /// macro_iterator/macro_begin/macro_end - This allows you to walk the current /// state of the macro table. This visits every currently-defined macro. - typedef llvm::DenseMap::const_iterator macro_iterator; macro_iterator macro_begin() const { return Macros.begin(); } macro_iterator macro_end() const { return Macros.end(); } - - - + + + const std::string &getPredefines() const { return Predefines; } /// setPredefines - Set the predefines for this Preprocessor. These /// predefines are automatically injected when parsing the main file. void setPredefines(const char *P) { Predefines = P; } void setPredefines(const std::string &P) { Predefines = P; } - + /// getIdentifierInfo - Return information about the specified preprocessor /// identifier token. The version of this method that takes two character /// pointers is preferred unless the identifier is already available as a @@ -295,7 +295,7 @@ public: IdentifierInfo *getIdentifierInfo(const char *NameStr) { return getIdentifierInfo(NameStr, NameStr+strlen(NameStr)); } - + /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. /// If 'Namespace' is non-null, then it is a token required to exist on the /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". @@ -309,16 +309,16 @@ public: /// \brief Add the specified comment handler to the preprocessor. void AddCommentHandler(CommentHandler *Handler); - + /// \brief Remove the specified comment handler. /// /// It is an error to remove a handler that has not been registered. void RemoveCommentHandler(CommentHandler *Handler); - + /// EnterMainSourceFile - Enter the specified FileID as the main source file, /// which implicitly adds the builtin defines etc. - void EnterMainSourceFile(); - + void EnterMainSourceFile(); + /// EnterSourceFile - Add a source file to the top of the include stack and /// start lexing tokens from it instead of the current buffer. If isMainFile /// is true, this is the main file for the translation unit. @@ -331,7 +331,7 @@ public: /// ILEnd specifies the location of the ')' for a function-like macro or the /// identifier for an object-like macro. void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroArgs *Args); - + /// EnterTokenStream - Add a "macro" context to the top of the include stack, /// which will cause the lexer to start returning the specified tokens. /// @@ -346,7 +346,7 @@ public: /// void EnterTokenStream(const Token *Toks, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens); - + /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the /// lexer stack. This should only be used in situations where the current /// state of the top-of-stack lexer is known. @@ -371,7 +371,7 @@ public: void CommitBacktrackedTokens(); /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since - /// EnableBacktrackAtThisPos() was previously called. + /// EnableBacktrackAtThisPos() was previously called. void Backtrack(); /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and @@ -390,7 +390,7 @@ public: else CachingLex(Result); } - + /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get /// something not a comment. This is useful in -E -C mode where comments /// would foul up preprocessor directive handling. @@ -408,11 +408,11 @@ public: DisableMacroExpansion = true; // Lex the token. Lex(Result); - + // Reenable it. DisableMacroExpansion = OldVal; } - + /// LookAhead - This peeks ahead N tokens and returns that token without /// consuming any tokens. LookAhead(0) returns the next token that would be /// returned by Lex(), LookAhead(1) returns the token after it, etc. This @@ -461,7 +461,7 @@ public: AnnotatePreviousCachedTokens(Tok); } - /// \brief Replace the last token with an annotation token. + /// \brief Replace the last token with an annotation token. /// /// Like AnnotateCachedTokens(), this routine replaces an /// already-parsed (and resolved) token with an annotation @@ -481,19 +481,19 @@ public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags->Report(FullSourceLoc(Loc, getSourceManager()), DiagID); } - + DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) { return Diags->Report(FullSourceLoc(Tok.getLocation(), getSourceManager()), DiagID); } - + /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a /// token is the characters used to represent the token in the source file /// after trigraph expansion and escaped-newline folding. In particular, this /// wants to get the true, uncanonicalized, spelling of things like digraphs /// UCNs, etc. std::string getSpelling(const Token &Tok) const; - + /// getSpelling - This method is used to get the spelling of a token into a /// preallocated buffer, instead of as an std::string. The caller is required /// to allocate enough space for the token, which is guaranteed to be at least @@ -521,7 +521,7 @@ public: // works. return *SourceMgr.getCharacterData(Tok.getLocation()); } - + /// CreateString - Plop the specified string into a scratch buffer and set the /// specified token's location and length to it. If specified, the source /// location provides a location of the instantiation point of the token. @@ -539,35 +539,35 @@ public: /// it points into a macro), this routine returns an invalid /// source location. SourceLocation getLocForEndOfToken(SourceLocation Loc); - + /// DumpToken - Print the token to stderr, used for debugging. /// void DumpToken(const Token &Tok, bool DumpFlags = false) const; void DumpLocation(SourceLocation Loc) const; void DumpMacro(const MacroInfo &MI) const; - + /// AdvanceToTokenCharacter - Given a location that specifies the start of a /// token, return a new location that specifies a character within the token. SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); - + /// IncrementPasteCounter - Increment the counters for the number of token /// paste operations performed. If fast was specified, this is a 'fast paste' /// case we handled. - /// + /// void IncrementPasteCounter(bool isFast) { if (isFast) ++NumFastTokenPaste; else ++NumTokenPaste; } - + void PrintStats(); /// HandleMicrosoftCommentPaste - When the macro expander pastes together a /// comment (/##/) in microsoft mode, this method handles updating the current /// state, returning the token on the next source line. void HandleMicrosoftCommentPaste(Token &Tok); - + //===--------------------------------------------------------------------===// // Preprocessor callback methods. These are invoked by a lexer as various // directives and events are found. @@ -576,26 +576,26 @@ public: /// identifier information for the token and install it into the token. IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, const char *BufPtr = 0); - + /// HandleIdentifier - This callback is invoked when the lexer reads an /// identifier and has filled in the tokens IdentifierInfo member. This /// callback potentially macro expands it or turns it into a named token (like /// 'for'). void HandleIdentifier(Token &Identifier); - + /// HandleEndOfFile - This callback is invoked when the lexer hits the end of /// the current file. This either returns the EOF token and returns true, or /// pops a level off the include stack and returns false, at which point the /// client should call lex again. bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); - + /// HandleEndOfTokenLexer - This callback is invoked when the current /// TokenLexer hits the end of its token stream. bool HandleEndOfTokenLexer(Token &Result); - + /// HandleDirective - This callback is invoked when the lexer sees a # token - /// at the start of a line. This consumes the directive, modifies the + /// at the start of a line. This consumes the directive, modifies the /// lexer/preprocessor state, and advances the lexer(s) so that the next token /// read is the correct one. void HandleDirective(Token &Result); @@ -604,11 +604,11 @@ public: /// not, emit a diagnostic and consume up until the eom. If EnableMacros is /// true, then we consider macros that expand to zero tokens as being ok. void CheckEndOfDirective(const char *Directive, bool EnableMacros = false); - + /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the /// current line until the tok::eom token is found. void DiscardUntilEndOfDirective(); - + /// SawDateOrTime - This returns true if the preprocessor has seen a use of /// __DATE__ or __TIME__ in the file so far. bool SawDateOrTime() const { @@ -616,13 +616,13 @@ public: } unsigned getCounterValue() const { return CounterValue; } void setCounterValue(unsigned V) { CounterValue = V; } - + /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide /// SourceLocation. MacroInfo* AllocateMacroInfo(SourceLocation L); - + private: - + void PushIncludeMacroStack() { IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), CurPTHLexer.take(), @@ -631,7 +631,7 @@ private: CurDirLookup)); CurPPLexer = 0; } - + void PopIncludeMacroStack() { CurLexer.reset(IncludeMacroStack.back().TheLexer); CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); @@ -640,11 +640,11 @@ private: CurDirLookup = IncludeMacroStack.back().TheDirLookup; IncludeMacroStack.pop_back(); } - + /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will /// be reused for allocating new MacroInfo objects. void ReleaseMacroInfo(MacroInfo* MI); - + /// isInPrimaryFile - Return true if we're in the top-level file, not in a /// #include. bool isInPrimaryFile() const; @@ -653,13 +653,13 @@ private: /// #define or #undef. This emits a diagnostic, sets the token kind to eom, /// and discards the rest of the macro line if the macro name is invalid. void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); - + /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro /// definition has just been read. Lex the rest of the arguments and the /// closing ), updating MI with what we learn. Return true if an error occurs /// parsing the arg list. bool ReadMacroDefinitionArgList(MacroInfo *MI); - + /// SkipExcludedConditionalBlock - We just read a #if or related directive and /// decided that the subsequent tokens are in the #if'd out portion of the /// file. Lex the rest of the file, until we see an #endif. If @@ -670,34 +670,34 @@ private: /// the caller can lex the first valid token. void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse); - + /// PTHSkipExcludedConditionalBlock - A fast PTH version of /// SkipExcludedConditionalBlock. void PTHSkipExcludedConditionalBlock(); - + /// EvaluateDirectiveExpression - Evaluate an integer constant expression that /// may occur after a #if or #elif directive and return it as a bool. If the /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); - + /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: /// #pragma GCC poison/system_header/dependency and #pragma once. void RegisterBuiltinPragmas(); - + /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the /// identifier table. void RegisterBuiltinMacros(); - + /// HandleMacroExpandedIdentifier - If an identifier token is read that is to /// be expanded as a macro, handle it and return the next token as 'Tok'. If /// the macro should not be expanded return true, otherwise return false. bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); - + /// isNextPPTokenLParen - Determine whether the next preprocessor token to be /// lexed is a '('. If so, consume the token and return true, if not, this /// method should have no observable side-effect on the lexed tokens. bool isNextPPTokenLParen(); - + /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is /// invoked to read all of the formal arguments specified for the macro /// invocation. This returns null on error. @@ -707,12 +707,12 @@ private: /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded /// as a builtin macro, handle it and return the next token as 'Tok'. void ExpandBuiltinMacro(Token &Tok); - + /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then /// return the first token after the directive. The _Pragma token has just /// been read into 'Tok'. void Handle_Pragma(Token &Tok); - + /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and /// start lexing tokens from it instead of the current buffer. void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); @@ -720,7 +720,7 @@ private: /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and /// start getting tokens from it using the PTH cache. void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir); - + /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully /// checked and spelled filename, e.g. as an operand of #include. This returns /// true if the input filename was in <>'s or false if it were in ""'s. The @@ -729,7 +729,7 @@ private: /// this method decides to use a different buffer. bool GetIncludeFilenameSpelling(SourceLocation Loc, const char *&BufStart, const char *&BufEnd); - + /// LookupFile - Given a "foo" or reference, look up the indicated file, /// return null on failure. isAngled indicates whether the file reference is /// for system #include's or not (i.e. using <> instead of ""). @@ -737,7 +737,7 @@ private: bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir); - + /// IsFileLexer - Returns true if we are lexing from a file and not a /// pragma or a macro. @@ -752,7 +752,7 @@ private: bool IsFileLexer() const { return IsFileLexer(CurLexer.get(), CurPPLexer); } - + //===--------------------------------------------------------------------===// // Caching stuff. void CachingLex(Token &Result); @@ -773,7 +773,7 @@ private: void HandleDigitDirective(Token &Tok); void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); void HandleIdentSCCSDirective(Token &Tok); - + // File inclusion. void HandleIncludeDirective(Token &Tok, const DirectoryLookup *LookupFrom = 0, @@ -781,13 +781,13 @@ private: void HandleIncludeNextDirective(Token &Tok); void HandleIncludeMacrosDirective(Token &Tok); void HandleImportDirective(Token &Tok); - + // Macro handling. void HandleDefineDirective(Token &Tok); void HandleUndefDirective(Token &Tok); // HandleAssertDirective(Token &Tok); // HandleUnassertDirective(Token &Tok); - + // Conditional Inclusion. void HandleIfdefDirective(Token &Tok, bool isIfndef, bool ReadAnyTokensBeforeDirective); @@ -795,7 +795,7 @@ private: void HandleEndifDirective(Token &Tok); void HandleElseDirective(Token &Tok); void HandleElifDirective(Token &Tok); - + // Pragmas. void HandlePragmaDirective(); public: @@ -813,18 +813,18 @@ public: class PreprocessorFactory { public: virtual ~PreprocessorFactory(); - virtual Preprocessor* CreatePreprocessor() = 0; + virtual Preprocessor* CreatePreprocessor() = 0; }; - -/// \brief Abstract base class that describes a handler that will receive + +/// \brief Abstract base class that describes a handler that will receive /// source ranges for each of the comments encountered in the source file. class CommentHandler { public: virtual ~CommentHandler(); - + virtual void HandleComment(Preprocessor &PP, SourceRange Comment) = 0; }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Lex/PreprocessorLexer.h b/clang/include/clang/Lex/PreprocessorLexer.h index 6a3c2bd43fa771587a548b71df00817168cc8f0d..85c44c5a0b808509f33f8746063b8b6a89372da7 100644 --- a/clang/include/clang/Lex/PreprocessorLexer.h +++ b/clang/include/clang/Lex/PreprocessorLexer.h @@ -29,19 +29,19 @@ protected: /// The SourceManager FileID corresponding to the file being lexed. const FileID FID; - + //===--------------------------------------------------------------------===// // Context-specific lexing flags set by the preprocessor. //===--------------------------------------------------------------------===// - + /// ParsingPreprocessorDirective - This is true when parsing #XXX. This turns /// '\n' into a tok::eom token. bool ParsingPreprocessorDirective; - + /// ParsingFilename - True after #include: this turns into a /// tok::angle_string_literal token. bool ParsingFilename; - + /// LexingRawMode - True if in raw mode: This flag disables interpretation of /// tokens and is a far faster mode to lex in than non-raw-mode. This flag: /// 1. If EOF of the current lexer is found, the include stack isn't popped. @@ -54,40 +54,40 @@ protected: /// /// Note that in raw mode that the PP pointer may be null. bool LexingRawMode; - - /// MIOpt - This is a state machine that detects the #ifndef-wrapping a file + + /// MIOpt - This is a state machine that detects the #ifndef-wrapping a file /// idiom for the multiple-include optimization. MultipleIncludeOpt MIOpt; - + /// ConditionalStack - Information about the set of #if/#ifdef/#ifndef blocks /// we are currently in. llvm::SmallVector ConditionalStack; - + PreprocessorLexer(const PreprocessorLexer&); // DO NOT IMPLEMENT void operator=(const PreprocessorLexer&); // DO NOT IMPLEMENT friend class Preprocessor; - + PreprocessorLexer(Preprocessor *pp, FileID fid) : PP(pp), FID(fid), ParsingPreprocessorDirective(false), ParsingFilename(false), LexingRawMode(false) {} - + PreprocessorLexer() - : PP(0), + : PP(0), ParsingPreprocessorDirective(false), ParsingFilename(false), LexingRawMode(false) {} - + virtual ~PreprocessorLexer() {} - + virtual void IndirectLex(Token& Result) = 0; - + /// getSourceLocation - Return the source location for the next observable /// location. virtual SourceLocation getSourceLocation() = 0; - + //===--------------------------------------------------------------------===// // #if directive handling. - + /// pushConditionalLevel - When we enter a #if directive, this keeps track of /// what we are currently in for diagnostic emission (e.g. #if with missing /// #endif). @@ -102,8 +102,8 @@ protected: } void pushConditionalLevel(const PPConditionalInfo &CI) { ConditionalStack.push_back(CI); - } - + } + /// popConditionalLevel - Remove an entry off the top of the conditional /// stack, returning information about it. If the conditional stack is empty, /// this returns true and does not fill in the arguments. @@ -113,44 +113,44 @@ protected: ConditionalStack.pop_back(); return false; } - + /// peekConditionalLevel - Return the top of the conditional stack. This /// requires that there be a conditional active. PPConditionalInfo &peekConditionalLevel() { assert(!ConditionalStack.empty() && "No conditionals active!"); return ConditionalStack.back(); } - - unsigned getConditionalStackDepth() const { return ConditionalStack.size(); } + + unsigned getConditionalStackDepth() const { return ConditionalStack.size(); } public: - + //===--------------------------------------------------------------------===// // Misc. lexing methods. - + /// LexIncludeFilename - After the preprocessor has parsed a #include, lex and /// (potentially) macro expand the filename. If the sequence parsed is not /// lexically legal, emit a diagnostic and return a result EOM token. void LexIncludeFilename(Token &Result); - + /// setParsingPreprocessorDirective - Inform the lexer whether or not /// we are currently lexing a preprocessor directive. void setParsingPreprocessorDirective(bool f) { ParsingPreprocessorDirective = f; } - + /// isLexingRawMode - Return true if this lexer is in raw mode or not. bool isLexingRawMode() const { return LexingRawMode; } /// getPP - Return the preprocessor object for this lexer. Preprocessor *getPP() const { return PP; } - - FileID getFileID() const { + + FileID getFileID() const { assert(PP && "PreprocessorLexer::getFileID() should only be used with a Preprocessor"); return FID; } - + /// getFileEntry - Return the FileEntry corresponding to this FileID. Like /// getFileID(), this only works for lexers with attached preprocessors. const FileEntry *getFileEntry() const; diff --git a/clang/include/clang/Lex/ScratchBuffer.h b/clang/include/clang/Lex/ScratchBuffer.h index 6506f9262947cc3a06fdbc38b752249882784dae..f03515ffc14289547d00ba5ee425a167cdf4e168 100644 --- a/clang/include/clang/Lex/ScratchBuffer.h +++ b/clang/include/clang/Lex/ScratchBuffer.h @@ -29,13 +29,13 @@ class ScratchBuffer { unsigned BytesUsed; public: ScratchBuffer(SourceManager &SM); - + /// getToken - Splat the specified text into a temporary MemoryBuffer and /// return a SourceLocation that refers to the token. This is just like the /// previous method, but returns a location that indicates the physloc of the /// token. SourceLocation getToken(const char *Buf, unsigned Len, const char *&DestPtr); - + private: void AllocScratchBuffer(unsigned RequestLen); }; diff --git a/clang/include/clang/Lex/Token.h b/clang/include/clang/Lex/Token.h index 2c8f2ad3f2b622ed876ad6063fa19a3b124d02ca..8acdb30cc705a1e2099653300cb535caa5a1adbe 100644 --- a/clang/include/clang/Lex/Token.h +++ b/clang/include/clang/Lex/Token.h @@ -62,14 +62,14 @@ class Token { /// Kind - The actual flavor of token this is. /// - unsigned Kind : 8; // DON'T make Kind a 'tok::TokenKind'; + unsigned Kind : 8; // DON'T make Kind a 'tok::TokenKind'; // MSVC will treat it as a signed char and // TokenKinds > 127 won't be handled correctly. - + /// Flags - Bits we track about this token, members of the TokenFlags enum. unsigned Flags : 8; public: - + // Various flags set per token: enum TokenFlags { StartOfLine = 0x01, // At start of line or only after whitespace. @@ -80,7 +80,7 @@ public: tok::TokenKind getKind() const { return (tok::TokenKind)Kind; } void setKind(tok::TokenKind K) { Kind = K; } - + /// is/isNot - Predicates to check if this token is a specific kind, as in /// "if (Tok.is(tok::l_brace)) {...}". bool is(tok::TokenKind K) const { return Kind == (unsigned) K; } @@ -94,12 +94,12 @@ public: is(tok::angle_string_literal); } - bool isAnnotation() const { - return is(tok::annot_typename) || + bool isAnnotation() const { + return is(tok::annot_typename) || is(tok::annot_cxxscope) || is(tok::annot_template_id); } - + /// getLocation - Return a source location identifier for the specified /// offset in the current file. SourceLocation getLocation() const { return Loc; } @@ -132,11 +132,11 @@ public: setLocation(R.getBegin()); setAnnotationEndLoc(R.getEnd()); } - + const char *getName() const { return tok::getTokenName( (tok::TokenKind) Kind); } - + /// startToken - Reset all flags to cleared. /// void startToken() { @@ -145,7 +145,7 @@ public: PtrData = 0; Loc = SourceLocation(); } - + IdentifierInfo *getIdentifierInfo() const { assert(!isAnnotation() && "Used IdentInfo on annotation token!"); if (isLiteral()) return 0; @@ -154,7 +154,7 @@ public: void setIdentifierInfo(IdentifierInfo *II) { PtrData = (void*) II; } - + /// getLiteralData - For a literal token (numeric constant, string, etc), this /// returns a pointer to the start of it in the text buffer if known, null /// otherwise. @@ -166,7 +166,7 @@ public: assert(isLiteral() && "Cannot set literal data of non-literal"); PtrData = (void*)Ptr; } - + void *getAnnotationValue() const { assert(isAnnotation() && "Used AnnotVal on non-annotation token"); return PtrData; @@ -175,17 +175,17 @@ public: assert(isAnnotation() && "Used AnnotVal on non-annotation token"); PtrData = val; } - + /// setFlag - Set the specified flag. void setFlag(TokenFlags Flag) { Flags |= Flag; } - + /// clearFlag - Unset the specified flag. void clearFlag(TokenFlags Flag) { Flags &= ~Flag; } - + /// getFlags - Return the internal represtation of the flags. /// Only intended for low-level operations such as writing tokens to // disk. @@ -195,32 +195,32 @@ public: /// setFlagValue - Set a flag to either true or false. void setFlagValue(TokenFlags Flag, bool Val) { - if (Val) + if (Val) setFlag(Flag); else clearFlag(Flag); } - + /// isAtStartOfLine - Return true if this token is at the start of a line. /// bool isAtStartOfLine() const { return (Flags & StartOfLine) ? true : false; } - + /// hasLeadingSpace - Return true if this token has whitespace before it. /// bool hasLeadingSpace() const { return (Flags & LeadingSpace) ? true : false; } - + /// isExpandDisabled - Return true if this identifier token should never /// be expanded in the future, due to C99 6.10.3.4p2. bool isExpandDisabled() const { return (Flags & DisableExpand) ? true : false; } - - /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. + + /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const; - + /// getObjCKeywordID - Return the ObjC keyword kind. tok::ObjCKeywordKind getObjCKeywordID() const; - + /// needsCleaning - Return true if this token has trigraphs or escaped /// newlines in it. /// @@ -233,15 +233,15 @@ struct PPConditionalInfo { /// IfLoc - Location where the conditional started. /// SourceLocation IfLoc; - + /// WasSkipping - True if this was contained in a skipping directive, e.g. /// in a "#if 0" block. bool WasSkipping; - + /// FoundNonSkip - True if we have emitted tokens already, and now we're in /// an #else block or something. Only useful in Skipping blocks. bool FoundNonSkip; - + /// FoundElse - True if we've seen a #else in this block. If so, /// #elif/#else directives are not allowed. bool FoundElse; @@ -263,41 +263,41 @@ struct TemplateIdAnnotation { /// The declaration of the template corresponding to the /// template-name. This is an Action::DeclTy*. - void *Template; + void *Template; /// The kind of template that Template refers to. TemplateNameKind Kind; /// The location of the '<' before the template argument - /// list. + /// list. SourceLocation LAngleLoc; /// The location of the '>' after the template argument - /// list. + /// list. SourceLocation RAngleLoc; /// NumArgs - The number of template arguments. - unsigned NumArgs; + unsigned NumArgs; /// \brief Retrieves a pointer to the template arguments void **getTemplateArgs() { return (void **)(this + 1); } /// \brief Retrieves a pointer to the array of template argument /// locations. - SourceLocation *getTemplateArgLocations() { + SourceLocation *getTemplateArgLocations() { return (SourceLocation *)(getTemplateArgs() + NumArgs); } /// \brief Retrieves a pointer to the array of flags that states /// whether the template arguments are types. - bool *getTemplateArgIsType() { + bool *getTemplateArgIsType() { return (bool *)(getTemplateArgLocations() + NumArgs); } static TemplateIdAnnotation* Allocate(unsigned NumArgs) { - TemplateIdAnnotation *TemplateId - = (TemplateIdAnnotation *)std::malloc(sizeof(TemplateIdAnnotation) + - sizeof(void*) * NumArgs + + TemplateIdAnnotation *TemplateId + = (TemplateIdAnnotation *)std::malloc(sizeof(TemplateIdAnnotation) + + sizeof(void*) * NumArgs + sizeof(SourceLocation) * NumArgs + sizeof(bool) * NumArgs); TemplateId->NumArgs = NumArgs; diff --git a/clang/include/clang/Lex/TokenConcatenation.h b/clang/include/clang/Lex/TokenConcatenation.h index dfc05f4074e0abfbb66a733275694898e542abca..d759e47e57fcd4017738ece4cb919283a5e1d5ad 100644 --- a/clang/include/clang/Lex/TokenConcatenation.h +++ b/clang/include/clang/Lex/TokenConcatenation.h @@ -19,7 +19,7 @@ namespace clang { class Preprocessor; class Token; - + /// TokenConcatenation class, which answers the question of /// "Is it safe to emit two tokens without a whitespace between them, or /// would that cause implicit concatenation of the tokens?" @@ -30,40 +30,40 @@ namespace clang { /// class TokenConcatenation { Preprocessor &PP; - + enum AvoidConcatInfo { /// By default, a token never needs to avoid concatenation. Most tokens /// (e.g. ',', ')', etc) don't cause a problem when concatenated. aci_never_avoid_concat = 0, - + /// aci_custom_firstchar - AvoidConcat contains custom code to handle this /// token's requirements, and it needs to know the first character of the /// token. aci_custom_firstchar = 1, - + /// aci_custom - AvoidConcat contains custom code to handle this token's /// requirements, but it doesn't need to know the first character of the /// token. aci_custom = 2, - + /// aci_avoid_equal - Many tokens cannot be safely followed by an '=' /// character. For example, "<<" turns into "<<=" when followed by an =. aci_avoid_equal = 4 }; - + /// TokenInfo - This array contains information for each token on what /// action to take when avoiding concatenation of tokens in the AvoidConcat /// method. char TokenInfo[tok::NUM_TOKENS]; public: TokenConcatenation(Preprocessor &PP); - + bool AvoidConcat(const Token &PrevTok, const Token &Tok) const; private: /// StartsWithL - Return true if the spelling of this token starts with 'L'. bool StartsWithL(const Token &Tok) const; - + /// IsIdentifierL - Return true if the spelling of this token is literally /// 'L'. bool IsIdentifierL(const Token &Tok) const; diff --git a/clang/include/clang/Lex/TokenLexer.h b/clang/include/clang/Lex/TokenLexer.h index c0a61cf93ee55c84641aa9616382d7ce2179582c..3f13e9cc1268eeab78bdbf327c493f56750fc810 100644 --- a/clang/include/clang/Lex/TokenLexer.h +++ b/clang/include/clang/Lex/TokenLexer.h @@ -21,7 +21,7 @@ namespace clang { class Preprocessor; class Token; class MacroArgs; - + /// TokenLexer - This implements a lexer that returns token from a macro body /// or token stream instead of lexing from a character buffer. This is used for /// macro expansion and _Pragma handling, for example. @@ -47,34 +47,34 @@ class TokenLexer { /// the preprocessor's bump pointer allocator, or some other buffer that we /// may or may not own (depending on OwnsTokens). const Token *Tokens; - + /// NumTokens - This is the length of the Tokens array. /// unsigned NumTokens; - + /// CurToken - This is the next token that Lex will return. /// unsigned CurToken; - + /// InstantiateLocStart/End - The source location range where this macro was /// instantiated. SourceLocation InstantiateLocStart, InstantiateLocEnd; - + /// Lexical information about the expansion point of the macro: the identifier /// that the macro expanded from had these properties. bool AtStartOfLine : 1; bool HasLeadingSpace : 1; - + /// OwnsTokens - This is true if this TokenLexer allocated the Tokens /// array, and thus needs to free it when destroyed. For simple object-like /// macros (for example) we just point into the token buffer of the macro /// definition, we don't make a copy of it. bool OwnsTokens : 1; - + /// DisableMacroExpansion - This is true when tokens lexed from the TokenLexer /// should not be subject to further macro expansion. bool DisableMacroExpansion : 1; - + TokenLexer(const TokenLexer&); // DO NOT IMPLEMENT void operator=(const TokenLexer&); // DO NOT IMPLEMENT public: @@ -87,13 +87,13 @@ public: : Macro(0), ActualArgs(0), PP(pp), OwnsTokens(false) { Init(Tok, ILEnd, ActualArgs); } - + /// Init - Initialize this TokenLexer to expand from the specified macro /// with the specified argument information. Note that this ctor takes /// ownership of the ActualArgs pointer. ILEnd specifies the location of the /// ')' for a function-like macro or the identifier for an object-like macro. void Init(Token &Tok, SourceLocation ILEnd, MacroArgs *ActualArgs); - + /// Create a TokenLexer for the specified token stream. If 'OwnsTokens' is /// specified, this takes ownership of the tokens and delete[]'s them when /// the token lexer is empty. @@ -102,45 +102,45 @@ public: : Macro(0), ActualArgs(0), PP(pp), OwnsTokens(false) { Init(TokArray, NumToks, DisableExpansion, ownsTokens); } - + /// Init - Initialize this TokenLexer with the specified token stream. /// This does not take ownership of the specified token vector. /// - /// DisableExpansion is true when macro expansion of tokens lexed from this + /// DisableExpansion is true when macro expansion of tokens lexed from this /// stream should be disabled. void Init(const Token *TokArray, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens); - + ~TokenLexer() { destroy(); } - + /// isNextTokenLParen - If the next token lexed will pop this macro off the /// expansion stack, return 2. If the next unexpanded token is a '(', return /// 1, otherwise return 0. unsigned isNextTokenLParen() const; - + /// Lex - Lex and return a token from this macro stream. void Lex(Token &Tok); - + private: void destroy(); - + /// isAtEnd - Return true if the next lex call will pop this macro off the /// include stack. bool isAtEnd() const { return CurToken == NumTokens; } - + /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ## /// operator. Read the ## and RHS, and paste the LHS/RHS together. If there /// are is another ## after it, chomp it iteratively. Return the result as /// Tok. If this returns true, the caller should immediately return the /// token. bool PasteTokens(Token &Tok); - + /// Expand the arguments of a function-like macro so that we can quickly /// return preexpanded tokens from Tokens. void ExpandFunctionArguments(); - + /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes /// together to form a comment that comments out everything in the current /// macro, other active macros, and anything left on the current physical diff --git a/clang/include/clang/Parse/Action.h b/clang/include/clang/Parse/Action.h index feecfdfbc70cb41ca5a43c9d37025ae8114c9b33..27f690b6b363e2ce0f8a3e3299401132aa238833 100644 --- a/clang/include/clang/Parse/Action.h +++ b/clang/include/clang/Parse/Action.h @@ -50,7 +50,7 @@ namespace clang { template<> struct IsResultPtrLowBitFree<3> { static const bool value = true;}; template<> struct IsResultPtrLowBitFree<4> { static const bool value = true;}; template<> struct IsResultPtrLowBitFree<5> { static const bool value = true;}; - + /// Action - As the parser reads the input file and recognizes the productions /// of the grammar, it invokes methods on this class to turn the parsed input /// into something useful: e.g. a parse tree. @@ -103,22 +103,22 @@ public: typedef ASTMultiPtr<&ActionBase::DeleteStmt> MultiStmtArg; typedef ASTMultiPtr<&ActionBase::DeleteTemplateParams> MultiTemplateParamsArg; - class FullExprArg { + class FullExprArg { public: // FIXME: The const_cast here is ugly. RValue references would make this - // much nicer (or we could duplicate a bunch of the move semantics + // much nicer (or we could duplicate a bunch of the move semantics // emulation code from Ownership.h). FullExprArg(const FullExprArg& Other) : Expr(move(const_cast(Other).Expr)) {} - + OwningExprResult release() { return move(Expr); } - + ExprArg* operator->() { return &Expr; } - + private: // FIXME: No need to make the entire Action class a friend when it's just // Action::FullExpr that needs access to the constructor below. @@ -129,7 +129,7 @@ public: ExprArg Expr; }; - + template FullExprArg FullExpr(T &Arg) { return FullExprArg(ActOnFinishFullExpr(move(Arg))); @@ -150,24 +150,24 @@ public: virtual void PrintStats() const {} /// getDeclName - Return a pretty name for the specified decl if possible, or - /// an empty string if not. This is used for pretty crash reporting. + /// an empty string if not. This is used for pretty crash reporting. virtual std::string getDeclName(DeclPtrTy D) { return ""; } - + /// \brief Invoked for each comment in the source code, providing the source /// range that contains the comment. virtual void ActOnComment(SourceRange Comment) { } - + //===--------------------------------------------------------------------===// // Declaration Tracking Callbacks. //===--------------------------------------------------------------------===// - + /// ConvertDeclToDeclGroup - If the parser has one decl in a context where it /// needs a decl group, it calls this to convert between the two /// representations. virtual DeclGroupPtrTy ConvertDeclToDeclGroup(DeclPtrTy Ptr) { return DeclGroupPtrTy(); } - + /// getTypeName - Return non-null if the specified identifier is a type name /// in the current scope. /// @@ -177,13 +177,13 @@ public: /// /// \param S the scope in which this name lookup occurs /// - /// \param SS if non-NULL, the C++ scope specifier that precedes the + /// \param SS if non-NULL, the C++ scope specifier that precedes the /// identifier /// - /// \param isClassName whether this is a C++ class-name production, in - /// which we can end up referring to a member of an unknown specialization + /// \param isClassName whether this is a C++ class-name production, in + /// which we can end up referring to a member of an unknown specialization /// that we know (from the grammar) is supposed to be a type. For example, - /// this occurs when deriving from "std::vector::allocator_type", where T + /// this occurs when deriving from "std::vector::allocator_type", where T /// is a template parameter. /// /// \returns the type referred to by this identifier, or NULL if the type @@ -200,7 +200,7 @@ public: virtual DeclSpec::TST isTagName(IdentifierInfo &II, Scope *S) { return DeclSpec::TST_unspecified; } - + /// isCurrentClassName - Return true if the specified name is the /// name of the innermost C++ class type currently being defined. virtual bool isCurrentClassName(const IdentifierInfo &II, Scope *S, @@ -227,7 +227,7 @@ public: /// /// \returns the kind of template that this name refers to. virtual TemplateNameKind isTemplateName(Scope *S, - const IdentifierInfo &II, + const IdentifierInfo &II, SourceLocation IdLoc, const CXXScopeSpec *SS, TypeTy *ObjectType, @@ -253,18 +253,18 @@ public: /// \param IdLoc the location of the identifier we have just parsed (e.g., /// the "bar" in "foo::bar::". /// - /// \param CCLoc the location of the '::' at the end of the + /// \param CCLoc the location of the '::' at the end of the /// nested-name-specifier. /// - /// \param II the identifier that represents the scope that this + /// \param II the identifier that represents the scope that this /// nested-name-specifier refers to, e.g., the "bar" in "foo::bar::". /// - /// \param ObjectType if this nested-name-specifier occurs as part of a + /// \param ObjectType if this nested-name-specifier occurs as part of a /// C++ member access expression such as "x->Base::f", the type of the base /// object (e.g., *x in the example, if "x" were a pointer). - /// + /// /// \param EnteringContext if true, then we intend to immediately enter the - /// context of this nested-name-specifier, e.g., for an out-of-line + /// context of this nested-name-specifier, e.g., for an out-of-line /// definition of a class member. /// /// \returns a CXXScopeTy* object representing the C++ scope. @@ -291,7 +291,7 @@ public: TypeTy *Type, SourceRange TypeRange, SourceLocation CCLoc) { - return 0; + return 0; } /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global @@ -340,12 +340,12 @@ public: return DeclPtrTy(); } - /// AddInitializerToDecl - This action is called immediately after - /// ActOnDeclarator (when an initializer is present). The code is factored + /// AddInitializerToDecl - This action is called immediately after + /// ActOnDeclarator (when an initializer is present). The code is factored /// this way to make sure we are able to handle the following: /// void func() { int xx = xx; } /// This allows ActOnDeclarator to register "xx" prior to parsing the - /// initializer. The declaration above should still result in a warning, + /// initializer. The declaration above should still result in a warning, /// since the reference to "xx" is uninitialized. virtual void AddInitializerToDecl(DeclPtrTy Dcl, ExprArg Init) { return; @@ -363,7 +363,7 @@ public: /// ActOnDeclarator (when an initializer is *not* present). /// If TypeContainsUndeducedAuto is true, then the type of the declarator /// has an undeduced 'auto' type somewhere. - virtual void ActOnUninitializedDecl(DeclPtrTy Dcl, + virtual void ActOnUninitializedDecl(DeclPtrTy Dcl, bool TypeContainsUndeducedAuto) { return; } @@ -376,7 +376,7 @@ public: return DeclGroupPtrTy(); } - + /// @brief Indicates that all K&R-style parameter declarations have /// been parsed prior to a function definition. /// @param S The function prototype scope. @@ -414,7 +414,7 @@ public: ExprArg AsmString) { return DeclPtrTy(); } - + /// ActOnPopScope - This callback is called immediately before the specified /// scope is popped and deleted. virtual void ActOnPopScope(SourceLocation Loc, Scope *S) {} @@ -422,7 +422,7 @@ public: /// ActOnTranslationUnitScope - This callback is called once, immediately /// after creating the translation unit scope (in Parser::Initialize). virtual void ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {} - + /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with /// no declarator (e.g. "struct foo;") is parsed. virtual DeclPtrTy ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { @@ -459,7 +459,7 @@ public: /// translation unit when EOF is reached and all but the top-level scope is /// popped. virtual void ActOnEndOfTranslationUnit() {} - + //===--------------------------------------------------------------------===// // Type Parsing Callbacks. //===--------------------------------------------------------------------===// @@ -468,7 +468,7 @@ public: virtual TypeResult ActOnTypeName(Scope *S, Declarator &D) { return TypeResult(); } - + enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' @@ -481,7 +481,7 @@ public: /// /// \param S the scope in which this tag occurs. /// - /// \param TagSpec an instance of DeclSpec::TST, indicating what kind of tag + /// \param TagSpec an instance of DeclSpec::TST, indicating what kind of tag /// this is (struct/union/enum/class). /// /// \param TUK how the tag we have encountered is being used, which @@ -489,7 +489,7 @@ public: /// declaration of that tag, or the beginning of a definition of /// that tag. /// - /// \param KWLoc the location of the "struct", "class", "union", or "enum" + /// \param KWLoc the location of the "struct", "class", "union", or "enum" /// keyword. /// /// \param SS C++ scope specifier that precedes the name of the tag, e.g., @@ -502,12 +502,12 @@ public: /// /// \param Attr the set of attributes that appertain to the tag. /// - /// \param AS when this tag occurs within a C++ class, provides the - /// current access specifier (AS_public, AS_private, AS_protected). + /// \param AS when this tag occurs within a C++ class, provides the + /// current access specifier (AS_public, AS_private, AS_protected). /// Otherwise, it will be AS_none. /// - /// \param TemplateParameterLists the set of C++ template parameter lists - /// that apply to this tag, if the tag is a declaration or definition (see + /// \param TemplateParameterLists the set of C++ template parameter lists + /// that apply to this tag, if the tag is a declaration or definition (see /// the \p TK parameter). The action module is responsible for determining, /// based on the template parameter lists and the scope specifier, whether /// the declared tag is a class template or not. @@ -525,9 +525,9 @@ public: bool &OwnedDecl) { return DeclPtrTy(); } - + /// Act on @defs() element found when parsing a structure. ClassName is the - /// name of the referenced class. + /// name of the referenced class. virtual void ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, llvm::SmallVectorImpl &Decls) {} @@ -536,19 +536,19 @@ public: Declarator &D, ExprTy *BitfieldWidth) { return DeclPtrTy(); } - + virtual DeclPtrTy ActOnIvar(Scope *S, SourceLocation DeclStart, DeclPtrTy IntfDecl, Declarator &D, ExprTy *BitfieldWidth, tok::ObjCKeywordKind visibility) { return DeclPtrTy(); } - + virtual void ActOnFields(Scope* S, SourceLocation RecLoc, DeclPtrTy TagDecl, - DeclPtrTy *Fields, unsigned NumFields, + DeclPtrTy *Fields, unsigned NumFields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList) {} - + /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). @@ -602,10 +602,10 @@ public: SourceLocation ColonLoc) { return StmtEmpty(); } - + /// ActOnCaseStmtBody - This installs a statement as the body of a case. virtual void ActOnCaseStmtBody(StmtTy *CaseStmt, StmtArg SubStmt) {} - + virtual OwningStmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, StmtArg SubStmt, Scope *CurScope){ @@ -619,8 +619,8 @@ public: return StmtEmpty(); } - virtual OwningStmtResult ActOnIfStmt(SourceLocation IfLoc, - FullExprArg CondVal, StmtArg ThenVal, + virtual OwningStmtResult ActOnIfStmt(SourceLocation IfLoc, + FullExprArg CondVal, StmtArg ThenVal, SourceLocation ElseLoc, StmtArg ElseVal) { return StmtEmpty(); @@ -635,12 +635,12 @@ public: return StmtEmpty(); } - virtual OwningStmtResult ActOnWhileStmt(SourceLocation WhileLoc, + virtual OwningStmtResult ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, StmtArg Body) { return StmtEmpty(); } virtual OwningStmtResult ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, - SourceLocation WhileLoc, + SourceLocation WhileLoc, SourceLocation CondLParen, ExprArg Cond, SourceLocation CondRParen) { @@ -682,7 +682,7 @@ public: return StmtEmpty(); } virtual OwningStmtResult ActOnAsmStmt(SourceLocation AsmLoc, - bool IsSimple, + bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, @@ -753,15 +753,15 @@ public: /// \brief The current expression and its subexpressions occur within an /// unevaluated operand (C++0x [expr]p8), such as a constant expression /// or the subexpression of \c sizeof, where the type or the value of the - /// expression may be significant but no code will be generated to evaluate + /// expression may be significant but no code will be generated to evaluate /// the value of the expression at run time. Unevaluated, - - /// \brief The current expression is potentially evaluated at run time, - /// which means that code may be generated to evaluate the value of the + + /// \brief The current expression is potentially evaluated at run time, + /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, - + /// \brief The current expression may be potentially evaluated or it may /// be unevaluated, but it is impossible to tell from the lexical context. /// This evaluation context is used primary for the operand of the C++ @@ -769,17 +769,17 @@ public: /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2). PotentiallyPotentiallyEvaluated }; - + /// \brief The parser is entering a new expression evaluation context. /// /// \param NewContext is the new expression evaluation context. /// /// \returns the previous expression evaluation context. - virtual ExpressionEvaluationContext + virtual ExpressionEvaluationContext PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { return PotentiallyEvaluated; } - + /// \brief The parser is existing an expression evaluation context. /// /// \param OldContext the expression evaluation context that the parser is @@ -787,10 +787,10 @@ public: /// /// \param NewContext the expression evaluation context that the parser is /// returning to. - virtual void + virtual void PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext, ExpressionEvaluationContext NewContext) { } - + // Primary Expressions. /// \brief Retrieve the source range that corresponds to the given @@ -862,12 +862,12 @@ public: return move(Val); // Default impl returns operand. } - virtual OwningExprResult ActOnParenListExpr(SourceLocation L, - SourceLocation R, + virtual OwningExprResult ActOnParenListExpr(SourceLocation L, + SourceLocation R, MultiExprArg Val) { return ExprEmpty(); } - + // Postfix Expressions. virtual OwningExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, @@ -924,8 +924,8 @@ public: SourceLocation RParenLoc) { return ExprEmpty(); } - /// @brief Parsed a C99 designated initializer. - /// + /// @brief Parsed a C99 designated initializer. + /// /// @param Desig Contains the designation with one or more designators. /// /// @param Loc The location of the '=' or ':' prior to the @@ -945,11 +945,11 @@ public: } virtual OwningExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, - TypeTy *Ty, SourceLocation RParenLoc, + TypeTy *Ty, SourceLocation RParenLoc, ExprArg Op) { return ExprEmpty(); } - + virtual OwningExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, ExprArg LHS, ExprArg RHS) { @@ -999,13 +999,13 @@ public: } // __builtin_types_compatible_p(type1, type2) - virtual OwningExprResult ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, + virtual OwningExprResult ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, TypeTy *arg1, TypeTy *arg2, SourceLocation RPLoc) { return ExprEmpty(); } // __builtin_choose_expr(constExpr, expr1, expr2) - virtual OwningExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, + virtual OwningExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, ExprArg cond, ExprArg expr1, ExprArg expr2, SourceLocation RPLoc){ return ExprEmpty(); @@ -1093,7 +1093,7 @@ public: OverloadedOperatorKind Op, AttributeList *AttrList, bool IsTypeName); - + /// ActOnParamDefaultArgument - Parse default argument for function parameter virtual void ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, @@ -1104,7 +1104,7 @@ public: /// argument for a function parameter, but we can't parse it yet /// because we're inside a class definition. Note that this default /// argument will be parsed later. - virtual void ActOnParamUnparsedDefaultArgument(DeclPtrTy param, + virtual void ActOnParamUnparsedDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, SourceLocation ArgLoc) { } @@ -1112,7 +1112,7 @@ public: /// the default argument for the parameter param failed. virtual void ActOnParamDefaultArgumentError(DeclPtrTy param) { } - /// AddCXXDirectInitializerToDecl - This action is called immediately after + /// AddCXXDirectInitializerToDecl - This action is called immediately after /// ActOnDeclarator, when a C++ direct initializer is present. /// e.g: "int x(1);" virtual void AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, @@ -1286,7 +1286,7 @@ public: return ExprEmpty(); } - /// \brief Invoked when the parser is starting to parse a C++ member access + /// \brief Invoked when the parser is starting to parse a C++ member access /// expression such as x.f or x->f. /// /// \param S the scope in which the member access expression occurs. @@ -1299,7 +1299,7 @@ public: /// \param OpKind the kind of member access operator ("." or "->") /// /// \param ObjectType originally NULL. The action should fill in this type - /// with the type into which name lookup should look to find the member in + /// with the type into which name lookup should look to find the member in /// the member access expression. /// /// \returns the (possibly modified) \p Base expression @@ -1310,7 +1310,7 @@ public: TypeTy *&ObjectType) { return ExprEmpty(); } - + /// ActOnDestructorReferenceExpr - Parsed a destructor reference, for example: /// /// t->~T(); @@ -1352,10 +1352,10 @@ public: const CXXScopeSpec *SS = 0) { return ExprEmpty(); } - + /// \brief Parsed a reference to a member template-id. /// - /// This callback will occur instead of ActOnMemberReferenceExpr() when the + /// This callback will occur instead of ActOnMemberReferenceExpr() when the /// member in question is a template for which the code provides an /// explicitly-specified template argument list, e.g., /// @@ -1371,7 +1371,7 @@ public: /// /// \param OpKind the kind of operator, which will be "." or "->". /// - /// \param SS the scope specifier that precedes the template-id in, e.g., + /// \param SS the scope specifier that precedes the template-id in, e.g., /// \c x.Base::f(). /// /// \param Template the declaration of the template that is being referenced. @@ -1399,7 +1399,7 @@ public: SourceLocation RAngleLoc) { return ExprEmpty(); } - + /// ActOnFinishFullExpr - Called whenever a full expression has been parsed. /// (C++ [intro.execution]p12). virtual OwningExprResult ActOnFinishFullExpr(ExprArg Expr) { @@ -1408,18 +1408,18 @@ public: //===---------------------------- C++ Classes ---------------------------===// /// ActOnBaseSpecifier - Parsed a base specifier - virtual BaseResult ActOnBaseSpecifier(DeclPtrTy classdecl, + virtual BaseResult ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, - TypeTy *basetype, + TypeTy *basetype, SourceLocation BaseLoc) { return BaseResult(); } - virtual void ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, + virtual void ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, unsigned NumBases) { } - + /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member /// declarator is parsed. 'AS' is the access specifier, 'BitfieldWidth' /// specifies the bitfield width if there is one and 'Init' specifies the @@ -1452,12 +1452,12 @@ public: /// is the function declaration (which will be a C++ constructor in /// a well-formed program), ColonLoc is the location of the ':' that /// starts the constructor initializer, and MemInit/NumMemInits - /// contains the individual member (and base) initializers. - virtual void ActOnMemInitializers(DeclPtrTy ConstructorDecl, + /// contains the individual member (and base) initializers. + virtual void ActOnMemInitializers(DeclPtrTy ConstructorDecl, SourceLocation ColonLoc, MemInitTy **MemInits, unsigned NumMemInits){ } - + virtual void ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {} /// ActOnFinishCXXMemberSpecification - Invoked after all member declarators @@ -1473,17 +1473,17 @@ public: /// ActOnTypeParameter - Called when a C++ template type parameter /// (e.g., "typename T") has been parsed. Typename specifies whether /// the keyword "typename" was used to declare the type parameter - /// (otherwise, "class" was used), ellipsis specifies whether this is a + /// (otherwise, "class" was used), ellipsis specifies whether this is a /// C++0x parameter pack, EllipsisLoc specifies the start of the ellipsis, - /// and KeyLoc is the location of the "class" or "typename" keyword. - // ParamName is the name of the parameter (NULL indicates an unnamed template + /// and KeyLoc is the location of the "class" or "typename" keyword. + // ParamName is the name of the parameter (NULL indicates an unnamed template // parameter) and ParamNameLoc is the location of the parameter name (if any) /// If the type parameter has a default argument, it will be added /// later via ActOnTypeParameterDefault. Depth and Position provide /// the number of enclosing templates (see /// ActOnTemplateParameterList) and the number of previous /// parameters within this template parameter list. - virtual DeclPtrTy ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, + virtual DeclPtrTy ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, @@ -1493,8 +1493,8 @@ public: } /// ActOnTypeParameterDefault - Adds a default argument (the type - /// Default) to the given template type parameter (TypeParam). - virtual void ActOnTypeParameterDefault(DeclPtrTy TypeParam, + /// Default) to the given template type parameter (TypeParam). + virtual void ActOnTypeParameterDefault(DeclPtrTy TypeParam, SourceLocation EqualLoc, SourceLocation DefaultLoc, TypeTy *Default) { @@ -1508,7 +1508,7 @@ public: /// ActOnTemplateParameterList) and the number of previous /// parameters within this template parameter list. virtual DeclPtrTy ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, - unsigned Depth, + unsigned Depth, unsigned Position) { return DeclPtrTy(); } @@ -1566,7 +1566,7 @@ public: /// @endcode /// /// ExportLoc, if valid, is the position of the "export" - /// keyword. Otherwise, "export" was not specified. + /// keyword. Otherwise, "export" was not specified. /// TemplateLoc is the position of the template keyword, LAngleLoc /// is the position of the left angle bracket, and RAngleLoc is the /// position of the corresponding right angle bracket. @@ -1575,7 +1575,7 @@ public: virtual TemplateParamsTy * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, - SourceLocation TemplateLoc, + SourceLocation TemplateLoc, SourceLocation LAngleLoc, DeclPtrTy *Params, unsigned NumParams, SourceLocation RAngleLoc) { @@ -1607,7 +1607,7 @@ public: /// \param TUK Either TUK_Reference or TUK_Friend. Declarations and /// definitions are interpreted as explicit instantiations or /// specializations. - /// + /// /// \param TagSpec The tag keyword that was provided as part of the /// elaborated-type-specifier; either class, struct, union, or enum. /// @@ -1636,7 +1636,7 @@ public: SourceLocation RAngleLoc) { return ExprError(); } - + /// \brief Form a dependent template name. /// /// This action forms a dependent template name given the template @@ -1653,10 +1653,10 @@ public: /// /// \param SS the nested-name-specifier that precedes the "template" keyword /// or the template name. FIXME: If the dependent template name occurs in - /// a member access expression, e.g., "x.template f", this + /// a member access expression, e.g., "x.template f", this /// nested-name-specifier will be empty. /// - /// \param ObjectType if this dependent template name occurs in the + /// \param ObjectType if this dependent template name occurs in the /// context of a member access expression, the type of the object being /// accessed. virtual TemplateTy ActOnDependentTemplateName(SourceLocation TemplateKWLoc, @@ -1695,7 +1695,7 @@ public: /// (template) /// /// \param TUK whether this is a declaration or a definition - /// + /// /// \param KWLoc the location of the 'class', 'struct', or 'union' /// keyword. /// @@ -1715,7 +1715,7 @@ public: /// specialization); the parser does not check this condition. virtual DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, - SourceLocation KWLoc, + SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, @@ -1732,22 +1732,22 @@ public: /// lists has been parsed. /// /// This action is similar to ActOnDeclarator(), except that the declaration - /// being created somehow involves a template, e.g., it is a template + /// being created somehow involves a template, e.g., it is a template /// declaration or specialization. - virtual DeclPtrTy ActOnTemplateDeclarator(Scope *S, + virtual DeclPtrTy ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D) { return DeclPtrTy(); } - + /// \brief Invoked when the parser is beginning to parse a function template /// or function template specialization definition. - virtual DeclPtrTy ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, + virtual DeclPtrTy ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, MultiTemplateParamsArg TemplateParameterLists, Declarator &D) { return DeclPtrTy(); } - + /// \brief Process the explicit instantiation of a class template /// specialization. /// @@ -1791,10 +1791,10 @@ public: /// /// \param Attr attributes that apply to this instantiation. virtual DeclResult - ActOnExplicitInstantiation(Scope *S, + ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, - unsigned TagSpec, + unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, @@ -1806,7 +1806,7 @@ public: AttributeList *Attr) { return DeclResult(); } - + /// \brief Process the explicit instantiation of a member class of a /// class template specialization. /// @@ -1851,10 +1851,10 @@ public: /// /// \param Attr attributes that apply to this instantiation. virtual DeclResult - ActOnExplicitInstantiation(Scope *S, + ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, - unsigned TagSpec, + unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, IdentifierInfo *Name, @@ -1877,7 +1877,7 @@ public: } /// \brief Called when the parser has parsed a C++ typename - /// specifier that ends in a template-id, e.g., + /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply". /// /// \param TypenameLoc the location of the 'typename' keyword @@ -1891,22 +1891,22 @@ public: } //===----------------------- Obj-C Declarations -------------------------===// - + // ActOnStartClassInterface - this action is called immediately after parsing - // the prologue for a class interface (before parsing the instance + // the prologue for a class interface (before parsing the instance // variables). Instance variables are processed by ActOnFields(). virtual DeclPtrTy ActOnStartClassInterface(SourceLocation AtInterfaceLoc, - IdentifierInfo *ClassName, + IdentifierInfo *ClassName, SourceLocation ClassLoc, - IdentifierInfo *SuperName, + IdentifierInfo *SuperName, SourceLocation SuperLoc, - const DeclPtrTy *ProtoRefs, + const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList) { return DeclPtrTy(); } - + /// ActOnCompatiblityAlias - this action is called after complete parsing of /// @compaatibility_alias declaration. It sets up the alias relationships. virtual DeclPtrTy ActOnCompatiblityAlias( @@ -1915,11 +1915,11 @@ public: IdentifierInfo *ClassName, SourceLocation ClassLocation) { return DeclPtrTy(); } - + // ActOnStartProtocolInterface - this action is called immdiately after // parsing the prologue for a protocol interface. virtual DeclPtrTy ActOnStartProtocolInterface(SourceLocation AtProtoLoc, - IdentifierInfo *ProtocolName, + IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, @@ -1930,9 +1930,9 @@ public: // ActOnStartCategoryInterface - this action is called immdiately after // parsing the prologue for a category interface. virtual DeclPtrTy ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, - IdentifierInfo *ClassName, + IdentifierInfo *ClassName, SourceLocation ClassLoc, - IdentifierInfo *CategoryName, + IdentifierInfo *CategoryName, SourceLocation CategoryLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, @@ -1940,13 +1940,13 @@ public: return DeclPtrTy(); } // ActOnStartClassImplementation - this action is called immdiately after - // parsing the prologue for a class implementation. Instance variables are + // parsing the prologue for a class implementation. Instance variables are // processed by ActOnFields(). virtual DeclPtrTy ActOnStartClassImplementation( SourceLocation AtClassImplLoc, - IdentifierInfo *ClassName, + IdentifierInfo *ClassName, SourceLocation ClassLoc, - IdentifierInfo *SuperClassname, + IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc) { return DeclPtrTy(); } @@ -1954,12 +1954,12 @@ public: // parsing the prologue for a category implementation. virtual DeclPtrTy ActOnStartCategoryImplementation( SourceLocation AtCatImplLoc, - IdentifierInfo *ClassName, + IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc) { return DeclPtrTy(); - } + } // ActOnPropertyImplDecl - called for every property implementation virtual DeclPtrTy ActOnPropertyImplDecl( SourceLocation AtLoc, // location of the @synthesize/@dynamic @@ -1971,7 +1971,7 @@ public: IdentifierInfo *propertyIvar) { // name of the ivar return DeclPtrTy(); } - + struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; @@ -1979,12 +1979,12 @@ public: // in this case. TypeTy *Type; ObjCDeclSpec DeclSpec; - + /// ArgAttrs - Attribute list for this argument. AttributeList *ArgAttrs; }; - // ActOnMethodDeclaration - called for all method declarations. + // ActOnMethodDeclaration - called for all method declarations. virtual DeclPtrTy ActOnMethodDeclaration( SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. @@ -1996,20 +1996,20 @@ public: ObjCArgInfo *ArgInfo, // ArgInfo: Has 'Sel.getNumArgs()' entries. llvm::SmallVectorImpl &Cdecls, // c-style args AttributeList *MethodAttrList, // optional - // tok::objc_not_keyword, tok::objc_optional, tok::objc_required + // tok::objc_not_keyword, tok::objc_optional, tok::objc_required tok::ObjCKeywordKind impKind, bool isVariadic = false) { return DeclPtrTy(); } // ActOnAtEnd - called to mark the @end. For declarations (interfaces, - // protocols, categories), the parser passes all methods/properties. + // protocols, categories), the parser passes all methods/properties. // For class implementations, these values default to 0. For implementations, // methods are processed incrementally (by ActOnMethodDeclaration above). - virtual void ActOnAtEnd(SourceLocation AtEndLoc, + virtual void ActOnAtEnd(SourceLocation AtEndLoc, DeclPtrTy classDecl, - DeclPtrTy *allMethods = 0, + DeclPtrTy *allMethods = 0, unsigned allNum = 0, - DeclPtrTy *allProperties = 0, + DeclPtrTy *allProperties = 0, unsigned pNum = 0, DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0) { @@ -2023,7 +2023,7 @@ public: tok::ObjCKeywordKind MethodImplKind) { return DeclPtrTy(); } - + virtual OwningExprResult ActOnClassPropertyRefExpr( IdentifierInfo &receiverName, IdentifierInfo &propertyName, @@ -2031,17 +2031,17 @@ public: SourceLocation &propertyNameLoc) { return ExprEmpty(); } - + // ActOnClassMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from NumArgs. virtual ExprResult ActOnClassMessage( Scope *S, - IdentifierInfo *receivingClassName, + IdentifierInfo *receivingClassName, Selector Sel, SourceLocation lbrac, SourceLocation receiverLoc, SourceLocation selectorLoc, - SourceLocation rbrac, + SourceLocation rbrac, ExprTy **ArgExprs, unsigned NumArgs) { return ExprResult(); } @@ -2050,7 +2050,7 @@ public: // is obtained from NumArgs. virtual ExprResult ActOnInstanceMessage( ExprTy *receiver, Selector Sel, - SourceLocation lbrac, SourceLocation selectorLoc, SourceLocation rbrac, + SourceLocation lbrac, SourceLocation selectorLoc, SourceLocation rbrac, ExprTy **ArgExprs, unsigned NumArgs) { return ExprResult(); } @@ -2067,7 +2067,7 @@ public: AttributeList *AttrList) { return DeclPtrTy(); } - + /// FindProtocolDeclaration - This routine looks up protocols and /// issues error if they are not declared. It returns list of valid /// protocols found. @@ -2079,7 +2079,7 @@ public: //===----------------------- Obj-C Expressions --------------------------===// - virtual ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, + virtual ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ExprTy **Strings, unsigned NumStrings) { return ExprResult(); @@ -2092,7 +2092,7 @@ public: SourceLocation RParenLoc) { return ExprResult(); } - + virtual ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, @@ -2100,38 +2100,38 @@ public: SourceLocation RParenLoc) { return ExprResult(); } - + virtual ExprResult ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return ExprResult(); - } + } //===---------------------------- Pragmas -------------------------------===// enum PragmaPackKind { - PPK_Default, // #pragma pack([n]) + PPK_Default, // #pragma pack([n]) PPK_Show, // #pragma pack(show), only supported by MSVC. PPK_Push, // #pragma pack(push, [identifier], [n]) PPK_Pop // #pragma pack(pop, [identifier], [n]) }; - + /// ActOnPragmaPack - Called on well formed #pragma pack(...). virtual void ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, ExprTy *Alignment, - SourceLocation PragmaLoc, + SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return; } - + /// ActOnPragmaUnused - Called on well formed #pragma unused(...). virtual void ActOnPragmaUnused(const Token *Identifiers, unsigned NumIdentifiers, Scope *CurScope, - SourceLocation PragmaLoc, + SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return; @@ -2181,13 +2181,13 @@ public: /// /// \param S the scope in which this name lookup occurs /// - /// \param SS if non-NULL, the C++ scope specifier that precedes the + /// \param SS if non-NULL, the C++ scope specifier that precedes the /// identifier /// - /// \param isClassName whether this is a C++ class-name production, in - /// which we can end up referring to a member of an unknown specialization + /// \param isClassName whether this is a C++ class-name production, in + /// which we can end up referring to a member of an unknown specialization /// that we know (from the grammar) is supposed to be a type. For example, - /// this occurs when deriving from "std::vector::allocator_type", where T + /// this occurs when deriving from "std::vector::allocator_type", where T /// is a template parameter. /// /// \returns the type referred to by this identifier, or NULL if the type @@ -2202,10 +2202,10 @@ public: const CXXScopeSpec *SS); virtual TemplateNameKind isTemplateName(Scope *S, - const IdentifierInfo &II, + const IdentifierInfo &II, SourceLocation IdLoc, const CXXScopeSpec *SS, - TypeTy *ObjectType, + TypeTy *ObjectType, bool EnteringContext, TemplateTy &Template); @@ -2213,22 +2213,22 @@ public: /// IdentifierInfo::FETokenInfo field to keep track of this fact, until S is /// popped. virtual DeclPtrTy ActOnDeclarator(Scope *S, Declarator &D); - - /// ActOnPopScope - When a scope is popped, if any typedefs are now + + /// ActOnPopScope - When a scope is popped, if any typedefs are now /// out-of-scope, they are removed from the IdentifierInfo::FETokenInfo field. virtual void ActOnPopScope(SourceLocation Loc, Scope *S); virtual void ActOnTranslationUnitScope(SourceLocation Loc, Scope *S); - + virtual DeclPtrTy ActOnForwardClassDeclaration(SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts); - + virtual DeclPtrTy ActOnStartClassInterface(SourceLocation interLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, - const DeclPtrTy *ProtoRefs, + const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList); @@ -2248,15 +2248,15 @@ public: Action &actions, SourceManager &sm, const char *Msg) : TheDecl(Decl), Loc(L), Actions(actions), SM(sm), Message(Msg) {} - + virtual void print(llvm::raw_ostream &OS) const; -}; - +}; + /// \brief RAII object that enters a new expression evaluation context. -class EnterExpressionEvaluationContext { +class EnterExpressionEvaluationContext { /// \brief The action object. Action &Actions; - + /// \brief The previous expression evaluation context. Action::ExpressionEvaluationContext PrevContext; @@ -2265,16 +2265,16 @@ class EnterExpressionEvaluationContext { public: EnterExpressionEvaluationContext(Action &Actions, - Action::ExpressionEvaluationContext NewContext) - : Actions(Actions), CurContext(NewContext) { + Action::ExpressionEvaluationContext NewContext) + : Actions(Actions), CurContext(NewContext) { PrevContext = Actions.PushExpressionEvaluationContext(NewContext); } - + ~EnterExpressionEvaluationContext() { Actions.PopExpressionEvaluationContext(CurContext, PrevContext); } }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Parse/AttributeList.h b/clang/include/clang/Parse/AttributeList.h index 6f987eefd06b410b299478b56effe19176208577..9fcc845cb00640d3a5e66c3ae985ee8ee43a6ef9 100644 --- a/clang/include/clang/Parse/AttributeList.h +++ b/clang/include/clang/Parse/AttributeList.h @@ -21,7 +21,7 @@ namespace clang { class IdentifierInfo; class Action; - + /// AttributeList - Represents GCC's __attribute__ declaration. There are /// 4 forms of this construct...they are: /// @@ -47,7 +47,7 @@ public: ActionBase::ExprTy **args, unsigned numargs, AttributeList *Next, bool declspec = false); ~AttributeList(); - + enum Kind { // Please keep this list alphabetized. AT_IBOutlet, // Clang-specific. AT_address_space, @@ -102,57 +102,57 @@ public: IgnoredAttribute, UnknownAttribute }; - + IdentifierInfo *getName() const { return AttrName; } SourceLocation getLoc() const { return AttrLoc; } IdentifierInfo *getParameterName() const { return ParmName; } bool isDeclspecAttribute() const { return DeclspecAttribute; } - + Kind getKind() const { return getKind(getName()); } static Kind getKind(const IdentifierInfo *Name); - + AttributeList *getNext() const { return Next; } void setNext(AttributeList *N) { Next = N; } /// getNumArgs - Return the number of actual arguments to this attribute. unsigned getNumArgs() const { return NumArgs; } - + /// getArg - Return the specified argument. ActionBase::ExprTy *getArg(unsigned Arg) const { assert(Arg < NumArgs && "Arg access out of range!"); return Args[Arg]; } - + class arg_iterator { ActionBase::ExprTy** X; unsigned Idx; public: - arg_iterator(ActionBase::ExprTy** x, unsigned idx) : X(x), Idx(idx) {} + arg_iterator(ActionBase::ExprTy** x, unsigned idx) : X(x), Idx(idx) {} arg_iterator& operator++() { ++Idx; return *this; } - + bool operator==(const arg_iterator& I) const { assert (X == I.X && "compared arg_iterators are for different argument lists"); return Idx == I.Idx; } - + bool operator!=(const arg_iterator& I) const { return !operator==(I); } - + ActionBase::ExprTy* operator*() const { return X[Idx]; } - + unsigned getArgNum() const { return Idx+1; } }; - + arg_iterator arg_begin() const { return arg_iterator(Args, 0); } diff --git a/clang/include/clang/Parse/DeclSpec.h b/clang/include/clang/Parse/DeclSpec.h index 3bedec4e4dbd8c0c23a7437f192b7c7fcd3c38e0..8f0441a8fe1e1efdde83e8f2104e99fd49fbf57e 100644 --- a/clang/include/clang/Parse/DeclSpec.h +++ b/clang/include/clang/Parse/DeclSpec.h @@ -25,7 +25,7 @@ namespace clang { class IdentifierInfo; class Preprocessor; class Declarator; - + /// DeclSpec - This class captures information about "declaration specifiers", /// which encompasses storage-class-specifiers, type-specifiers, /// type-qualifiers, and function-specifiers. @@ -42,7 +42,7 @@ public: SCS_private_extern, SCS_mutable }; - + // type-specifier enum TSW { TSW_unspecified, @@ -50,19 +50,19 @@ public: TSW_long, TSW_longlong }; - + enum TSC { TSC_unspecified, TSC_imaginary, TSC_complex }; - + enum TSS { TSS_unspecified, TSS_signed, TSS_unsigned }; - + enum TST { TST_unspecified, TST_void, @@ -88,7 +88,7 @@ public: TST_auto, // C++0x auto TST_error // erroneous type }; - + // type-qualifiers enum TQ { // NOTE: These flags must be kept in sync with QualType::TQ. TQ_unspecified = 0, @@ -106,9 +106,9 @@ public: PQ_TypeQualifier = 4, PQ_FunctionSpecifier = 8 }; - + private: - + // storage-class-specifier /*SCS*/unsigned StorageClassSpec : 3; bool SCS_thread_specified : 1; @@ -122,43 +122,43 @@ private: // type-qualifiers unsigned TypeQualifiers : 3; // Bitwise OR of TQ. - + // function-specifier bool FS_inline_specified : 1; bool FS_virtual_specified : 1; bool FS_explicit_specified : 1; - + // friend-specifier bool Friend_specified : 1; - + /// TypeRep - This contains action-specific information about a specific TST. /// For example, for a typedef or struct, it might contain the declaration for /// these. - void *TypeRep; - + void *TypeRep; + // attributes. AttributeList *AttrList; - - // List of protocol qualifiers for objective-c classes. Used for + + // List of protocol qualifiers for objective-c classes. Used for // protocol-qualified interfaces "NString" and protocol-qualified id // "id". const ActionBase::DeclPtrTy *ProtocolQualifiers; unsigned NumProtocolQualifiers; - + // SourceLocation info. These are null if the item wasn't specified or if // the setting was synthesized. SourceRange Range; - + SourceLocation StorageClassSpecLoc, SCS_threadLoc; SourceLocation TSWLoc, TSCLoc, TSSLoc, TSTLoc; SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc; SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc; SourceLocation FriendLoc; - + DeclSpec(const DeclSpec&); // DO NOT IMPLEMENT void operator=(const DeclSpec&); // DO NOT IMPLEMENT -public: - +public: + DeclSpec() : StorageClassSpec(SCS_unspecified), SCS_thread_specified(false), @@ -184,17 +184,17 @@ public: // storage-class-specifier SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; } bool isThreadSpecified() const { return SCS_thread_specified; } - + SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; } SourceLocation getThreadSpecLoc() const { return SCS_threadLoc; } - + void ClearStorageClassSpecs() { StorageClassSpec = DeclSpec::SCS_unspecified; SCS_thread_specified = false; StorageClassSpecLoc = SourceLocation(); SCS_threadLoc = SourceLocation(); } - + // type-specifier TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; } TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; } @@ -202,13 +202,13 @@ public: TST getTypeSpecType() const { return (TST)TypeSpecType; } bool isTypeSpecOwned() const { return TypeSpecOwned; } void *getTypeRep() const { return TypeRep; } - + const SourceRange &getSourceRange() const { return Range; } SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; } SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; } SourceLocation getTypeSpecSignLoc() const { return TSSLoc; } SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; } - + /// getSpecifierName - Turn a type-specifier-type into a string like "_Bool" /// or "union". static const char *getSpecifierName(DeclSpec::TST T); @@ -217,7 +217,7 @@ public: static const char *getSpecifierName(DeclSpec::TSC C); static const char *getSpecifierName(DeclSpec::TSW W); static const char *getSpecifierName(DeclSpec::SCS S); - + // type-qualifiers /// getTypeQualifiers - Return a set of TQs. @@ -225,7 +225,7 @@ public: SourceLocation getConstSpecLoc() const { return TQ_constLoc; } SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; } SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; } - + // function-specifier bool isInlineSpecified() const { return FS_inline_specified; } SourceLocation getInlineSpecLoc() const { return FS_inlineLoc; } @@ -244,7 +244,7 @@ public: FS_explicit_specified = false; FS_explicitLoc = SourceLocation(); } - + /// hasTypeSpecifier - Return true if any type-specifier has been found. bool hasTypeSpecifier() const { return getTypeSpecType() != DeclSpec::TST_unspecified || @@ -252,21 +252,21 @@ public: getTypeSpecComplex() != DeclSpec::TSC_unspecified || getTypeSpecSign() != DeclSpec::TSS_unspecified; } - + /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this /// DeclSpec includes. /// unsigned getParsedSpecifiers() const; - + /// isEmpty - Return true if this declaration specifier is completely empty: /// no tokens were parsed in the production of it. bool isEmpty() const { return getParsedSpecifiers() == DeclSpec::PQ_None; } - + void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); } void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); } - + /// These methods set the specified attribute of the DeclSpec and /// return false if there was no error. If an error occurs (for /// example, if we tried to set "auto" on a spec with "extern" @@ -291,42 +291,42 @@ public: unsigned &DiagID, void *Rep = 0, bool Owned = false); bool SetTypeSpecError(); void UpdateTypeRep(void *Rep) { TypeRep = Rep; } - + bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const LangOptions &Lang); - + bool SetFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID); bool SetFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID); bool SetFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID); - + bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID); bool isFriendSpecified() const { return Friend_specified; } SourceLocation getFriendSpecLoc() const { return FriendLoc; } - /// AddAttributes - contatenates two attribute lists. + /// AddAttributes - contatenates two attribute lists. /// The GCC attribute syntax allows for the following: /// - /// short __attribute__(( unused, deprecated )) + /// short __attribute__(( unused, deprecated )) /// int __attribute__(( may_alias, aligned(16) )) var; /// /// This declares 4 attributes using 2 lists. The following syntax is /// also allowed and equivalent to the previous declaration. /// - /// short __attribute__((unused)) __attribute__((deprecated)) + /// short __attribute__((unused)) __attribute__((deprecated)) /// int __attribute__((may_alias)) __attribute__((aligned(16))) var; - /// + /// void AddAttributes(AttributeList *alist) { AttrList = addAttributeLists(AttrList, alist); } void SetAttributes(AttributeList *AL) { AttrList = AL; } const AttributeList *getAttributes() const { return AttrList; } AttributeList *getAttributes() { return AttrList; } - + /// TakeAttributes - Return the current attribute list and remove them from /// the DeclSpec so that it doesn't own them. AttributeList *TakeAttributes() { @@ -334,7 +334,7 @@ public: AttrList = 0; return AL; } - + typedef const ActionBase::DeclPtrTy *ProtocolQualifierListTy; ProtocolQualifierListTy getProtocolQualifiers() const { return ProtocolQualifiers; @@ -348,7 +348,7 @@ public: memcpy((void*)ProtocolQualifiers, Protos, sizeof(ActionBase::DeclPtrTy)*NP); NumProtocolQualifiers = NP; } - + /// Finish - This does final analysis of the declspec, issuing diagnostics for /// things like "_Imaginary" (lacking an FP type). After calling this method, /// DeclSpec is guaranteed self-consistent, even if an error occurred. @@ -359,7 +359,7 @@ public: bool isMissingDeclaratorOk(); }; -/// ObjCDeclSpec - This class captures information about +/// ObjCDeclSpec - This class captures information about /// "declaration specifiers" specific to objective-c class ObjCDeclSpec { public: @@ -373,47 +373,46 @@ public: DQ_Byref = 0x10, DQ_Oneway = 0x20 }; - + /// PropertyAttributeKind - list of property attributes. - enum ObjCPropertyAttributeKind { DQ_PR_noattr = 0x0, - DQ_PR_readonly = 0x01, - DQ_PR_getter = 0x02, - DQ_PR_assign = 0x04, - DQ_PR_readwrite = 0x08, + enum ObjCPropertyAttributeKind { DQ_PR_noattr = 0x0, + DQ_PR_readonly = 0x01, + DQ_PR_getter = 0x02, + DQ_PR_assign = 0x04, + DQ_PR_readwrite = 0x08, DQ_PR_retain = 0x10, - DQ_PR_copy = 0x20, + DQ_PR_copy = 0x20, DQ_PR_nonatomic = 0x40, DQ_PR_setter = 0x80 }; - - + + ObjCDeclSpec() : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr), - GetterName(0), SetterName(0) - {} + GetterName(0), SetterName(0) { } ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; } - void setObjCDeclQualifier(ObjCDeclQualifier DQVal) + void setObjCDeclQualifier(ObjCDeclQualifier DQVal) { objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal); } - - ObjCPropertyAttributeKind getPropertyAttributes() const + + ObjCPropertyAttributeKind getPropertyAttributes() const { return ObjCPropertyAttributeKind(PropertyAttributes); } - void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) { - PropertyAttributes = + void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) { + PropertyAttributes = (ObjCPropertyAttributeKind) (PropertyAttributes | PRVal); } - + const IdentifierInfo *getGetterName() const { return GetterName; } IdentifierInfo *getGetterName() { return GetterName; } void setGetterName(IdentifierInfo *name) { GetterName = name; } - + const IdentifierInfo *getSetterName() const { return SetterName; } IdentifierInfo *getSetterName() { return SetterName; } void setSetterName(IdentifierInfo *name) { SetterName = name; } private: - // FIXME: These two are unrelated and mutially exclusive. So perhaps + // FIXME: These two are unrelated and mutially exclusive. So perhaps // we can put them in a union to reflect their mutual exclusiveness // (space saving is negligible). ObjCDeclQualifier objcDeclQualifier : 6; - + // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind unsigned PropertyAttributes : 8; IdentifierInfo *GetterName; // getter name of NULL if no getter @@ -453,7 +452,7 @@ public: ScopeRep = 0; } }; - + /// CachedTokens - A set of tokens that has been cached for later /// parsing. typedef llvm::SmallVector CachedTokens; @@ -471,7 +470,7 @@ struct DeclaratorChunk { SourceLocation Loc; /// EndLoc - If valid, the place where this chunck ends. SourceLocation EndLoc; - + struct PointerTypeInfo { /// The type qualifiers: const/volatile/restrict. unsigned TypeQuals : 3; @@ -495,20 +494,20 @@ struct DeclaratorChunk { struct ArrayTypeInfo { /// The type qualifiers for the array: const/volatile/restrict. unsigned TypeQuals : 3; - + /// True if this dimension included the 'static' keyword. bool hasStatic : 1; - + /// True if this dimension was [*]. In this case, NumElts is null. bool isStar : 1; - + /// This is the size of the array, or null if [] or [*] was specified. /// Since the parser is multi-purpose, and we don't want to impose a root /// expression class on all clients, NumElts is untyped. ActionBase::ExprTy *NumElts; void destroy() {} }; - + /// ParamInfo - An array of paraminfo objects is allocated whenever a function /// declarator is parsed. There are two interesting styles of arguments here: /// K&R-style identifier lists and parameter type lists. K&R-style identifier @@ -531,7 +530,7 @@ struct DeclaratorChunk { ParamInfo(IdentifierInfo *ident, SourceLocation iloc, ActionBase::DeclPtrTy param, CachedTokens *DefArgTokens = 0) - : Ident(ident), IdentLoc(iloc), Param(param), + : Ident(ident), IdentLoc(iloc), Param(param), DefaultArgTokens(DefArgTokens) {} }; @@ -552,7 +551,7 @@ struct DeclaratorChunk { bool isVariadic : 1; /// The type qualifiers: const/volatile/restrict. - /// The qualifier bitmask values are the same as in QualType. + /// The qualifier bitmask values are the same as in QualType. unsigned TypeQuals : 3; /// hasExceptionSpec - True if the function has an exception specification. @@ -692,7 +691,7 @@ struct DeclaratorChunk { I.Ptr.AttrList = AL; return I; } - + /// getReference - Return a DeclaratorChunk for a reference. /// static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, @@ -705,7 +704,7 @@ struct DeclaratorChunk { I.Ref.AttrList = AL; return I; } - + /// getArray - Return a DeclaratorChunk for an array. /// static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, @@ -721,7 +720,7 @@ struct DeclaratorChunk { I.Arr.NumElts = NumElts; return I; } - + /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function. /// "TheDeclarator" is the declarator that this will be added to. static DeclaratorChunk getFunction(bool hasProto, bool isVariadic, @@ -735,7 +734,7 @@ struct DeclaratorChunk { unsigned NumExceptions, SourceLocation LPLoc, SourceLocation RPLoc, Declarator &TheDeclarator); - + /// getBlockPointer - Return a DeclaratorChunk for a block. /// static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc, @@ -791,11 +790,11 @@ public: /// DeclaratorKind - The kind of declarator this represents. enum DeclaratorKind { DK_Abstract, // An abstract declarator (has no identifier) - DK_Normal, // A normal declarator (has an identifier). + DK_Normal, // A normal declarator (has an identifier). DK_Constructor, // A C++ constructor (identifier is the class name) DK_Destructor, // A C++ destructor (identifier is ~class name) DK_Operator, // A C++ overloaded operator name - DK_Conversion // A C++ conversion function (identifier is + DK_Conversion // A C++ conversion function (identifier is // "operator " then the type name) }; @@ -810,7 +809,7 @@ private: /// TheContext Context; - /// Kind - What kind of declarator this is. + /// Kind - What kind of declarator this is. DeclaratorKind Kind; /// DeclTypeInfo - This holds each type that the declarator includes as it is @@ -827,7 +826,7 @@ private: /// AttrList - Attributes. AttributeList *AttrList; - + /// AsmLabel - The asm label, if specified. ActionBase::ExprTy *AsmLabel; @@ -861,7 +860,7 @@ public: GroupingParens(false), AttrList(0), AsmLabel(0), Type(0), InlineParamsUsed(false), Extension(false) { } - + ~Declarator() { clear(); } @@ -869,7 +868,7 @@ public: /// getDeclSpec - Return the declaration-specifier that this declarator was /// declared with. const DeclSpec &getDeclSpec() const { return DS; } - + /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This /// should be used with extreme care: declspecs can often be shared between /// multiple declarators, so mutating the DeclSpec affects all of the @@ -928,9 +927,9 @@ public: Type = 0; InlineParamsUsed = false; } - + /// mayOmitIdentifier - Return true if the identifier is either optional or - /// not allowed. This is true for typenames, prototypes, and template + /// not allowed. This is true for typenames, prototypes, and template /// parameter lists. bool mayOmitIdentifier() const { return Context == TypeNameContext || Context == PrototypeContext || @@ -953,7 +952,7 @@ public: Context == BlockContext || Context == ForContext); } - + /// isPastIdentifier - Return true if we have parsed beyond the point where /// the bool isPastIdentifier() const { return IdentifierLoc.isValid(); } @@ -965,7 +964,7 @@ public: IdentifierInfo *getIdentifier() const { return Identifier; } SourceLocation getIdentifierLoc() const { return IdentifierLoc; } - + void SetIdentifier(IdentifierInfo *ID, SourceLocation Loc) { Identifier = ID; IdentifierLoc = Loc; @@ -975,7 +974,7 @@ public: Kind = DK_Abstract; SetRangeEnd(Loc); } - + /// setConstructor - Set this declarator to be a C++ constructor /// declarator. Also extends the range. void setConstructor(ActionBase::TypeTy *Ty, SourceLocation Loc) { @@ -1035,7 +1034,7 @@ public: /// getNumTypeObjects() - Return the number of types applied to this /// declarator. unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); } - + /// Return the specified TypeInfo from this declarator. TypeInfo #0 is /// closest to the identifier. const DeclaratorChunk &getTypeObject(unsigned i) const { @@ -1046,14 +1045,14 @@ public: assert(i < DeclTypeInfo.size() && "Invalid type chunk"); return DeclTypeInfo[i]; } - + /// isFunctionDeclarator - Once this declarator is fully parsed and formed, /// this method returns true if the identifier is a function declarator. bool isFunctionDeclarator() const { return !DeclTypeInfo.empty() && DeclTypeInfo[0].Kind == DeclaratorChunk::Function; } - + /// AddAttributes - simply adds the attribute list to the Declarator. /// These examples both add 3 attributes to "var": /// short int var __attribute__((aligned(16),common,deprecated)); @@ -1061,13 +1060,13 @@ public: /// __attribute__((common,deprecated)); /// /// Also extends the range of the declarator. - void AddAttributes(AttributeList *alist, SourceLocation LastLoc) { + void AddAttributes(AttributeList *alist, SourceLocation LastLoc) { AttrList = addAttributeLists(AttrList, alist); if (!LastLoc.isInvalid()) SetRangeEnd(LastLoc); } - + const AttributeList *getAttributes() const { return AttrList; } AttributeList *getAttributes() { return AttrList; } @@ -1091,8 +1090,8 @@ public: OverloadedOperatorKind getOverloadedOperator() const { return OperatorKind; } void setInvalidType(bool Val = true) { InvalidType = Val; } - bool isInvalidType() const { - return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error; + bool isInvalidType() const { + return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error; } void setGroupingParens(bool flag) { GroupingParens = flag; } diff --git a/clang/include/clang/Parse/Designator.h b/clang/include/clang/Parse/Designator.h index 026286d318fb817bb48caf29843c417fcc000928..255af5901819243eec3e98c2fd7726be92cf0a4d 100644 --- a/clang/include/clang/Parse/Designator.h +++ b/clang/include/clang/Parse/Designator.h @@ -18,7 +18,7 @@ #include "clang/Parse/Action.h" namespace clang { - + /// Designator - This class is a discriminated union which holds the various /// different sorts of designators possible. A Designation is an array of /// these. An example of a designator are things like this: @@ -34,7 +34,7 @@ public: }; private: DesignatorKind Kind; - + struct FieldDesignatorInfo { const IdentifierInfo *II; unsigned DotLoc; @@ -50,15 +50,15 @@ private: unsigned LBracketLoc, EllipsisLoc; mutable unsigned RBracketLoc; }; - + union { FieldDesignatorInfo FieldInfo; ArrayDesignatorInfo ArrayInfo; ArrayRangeDesignatorInfo ArrayRangeInfo; }; - + public: - + DesignatorKind getKind() const { return Kind; } bool isFieldDesignator() const { return Kind == FieldDesignator; } bool isArrayDesignator() const { return Kind == ArrayDesignator; } @@ -78,7 +78,7 @@ public: assert(isFieldDesignator() && "Invalid accessor"); return SourceLocation::getFromRawEncoding(FieldInfo.NameLoc); } - + ActionBase::ExprTy *getArrayIndex() const { assert(isArrayDesignator() && "Invalid accessor"); return ArrayInfo.Index; @@ -92,22 +92,22 @@ public: assert(isArrayRangeDesignator() && "Invalid accessor"); return ArrayRangeInfo.End; } - + SourceLocation getLBracketLoc() const { - assert((isArrayDesignator() || isArrayRangeDesignator()) && + assert((isArrayDesignator() || isArrayRangeDesignator()) && "Invalid accessor"); if (isArrayDesignator()) return SourceLocation::getFromRawEncoding(ArrayInfo.LBracketLoc); - else + else return SourceLocation::getFromRawEncoding(ArrayRangeInfo.LBracketLoc); } SourceLocation getRBracketLoc() const { - assert((isArrayDesignator() || isArrayRangeDesignator()) && + assert((isArrayDesignator() || isArrayRangeDesignator()) && "Invalid accessor"); if (isArrayDesignator()) return SourceLocation::getFromRawEncoding(ArrayInfo.RBracketLoc); - else + else return SourceLocation::getFromRawEncoding(ArrayRangeInfo.RBracketLoc); } @@ -135,10 +135,10 @@ public: D.ArrayInfo.RBracketLoc = 0; return D; } - + static Designator getArrayRange(ActionBase::ExprTy *Start, ActionBase::ExprTy *End, - SourceLocation LBracketLoc, + SourceLocation LBracketLoc, SourceLocation EllipsisLoc) { Designator D; D.Kind = ArrayRangeDesignator; @@ -151,14 +151,14 @@ public: } void setRBracketLoc(SourceLocation RBracketLoc) const { - assert((isArrayDesignator() || isArrayRangeDesignator()) && + assert((isArrayDesignator() || isArrayRangeDesignator()) && "Invalid accessor"); if (isArrayDesignator()) ArrayInfo.RBracketLoc = RBracketLoc.getRawEncoding(); else ArrayRangeInfo.RBracketLoc = RBracketLoc.getRawEncoding(); } - + /// ClearExprs - Null out any expression references, which prevents them from /// being 'delete'd later. void ClearExprs(Action &Actions) { @@ -173,7 +173,7 @@ public: return; } } - + /// FreeExprs - Release any unclaimed memory for the expressions in this /// designator. void FreeExprs(Action &Actions) { @@ -190,7 +190,7 @@ public: } }; - + /// Designation - Represent a full designation, which is a sequence of /// designators. This class is mostly a helper for InitListDesignations. class Designation { @@ -198,10 +198,10 @@ class Designation { /// example, if the initializer were "{ A, .foo=B, C }" a Designation would /// exist with InitIndex=1, because element #1 has a designation. unsigned InitIndex; - + /// Designators - The actual designators for this initializer. llvm::SmallVector Designators; - + Designation(unsigned Idx) : InitIndex(Idx) {} public: Designation() : InitIndex(4000) {} @@ -218,14 +218,14 @@ public: assert(Idx < Designators.size()); return Designators[Idx]; } - + /// ClearExprs - Null out any expression references, which prevents them from /// being 'delete'd later. void ClearExprs(Action &Actions) { for (unsigned i = 0, e = Designators.size(); i != e; ++i) Designators[i].ClearExprs(Actions); } - + /// FreeExprs - Release any unclaimed memory for the expressions in this /// designation. void FreeExprs(Action &Actions) { @@ -233,7 +233,7 @@ public: Designators[i].FreeExprs(Actions); } }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Parse/Ownership.h b/clang/include/clang/Parse/Ownership.h index 8840adb25ff88544cc7fb06c5dbbbae269c85628..9bd69c5fdb6879c3772b99b7909cc53f2a152622 100644 --- a/clang/include/clang/Parse/Ownership.h +++ b/clang/include/clang/Parse/Ownership.h @@ -23,7 +23,7 @@ namespace clang { class ActionBase; - + /// OpaquePtr - This is a very simple POD type that wraps a pointer that the /// Parser doesn't know about but that Sema or another client does. The UID /// template argument is used to make sure that "Decl" pointers are not @@ -33,29 +33,29 @@ namespace clang { void *Ptr; public: OpaquePtr() : Ptr(0) {} - + template T* getAs() const { return llvm::PointerLikeTypeTraits::getFromVoidPointer(Ptr); } - + template T getAsVal() const { return llvm::PointerLikeTypeTraits::getFromVoidPointer(Ptr); } - + void *get() const { return Ptr; } - + template static OpaquePtr make(T P) { OpaquePtr R; R.set(P); return R; } - + template void set(T P) { Ptr = llvm::PointerLikeTypeTraits::getAsVoidPointer(P); } - + operator bool() const { return Ptr != 0; } }; } @@ -218,7 +218,7 @@ namespace clang { /// expressions, stmts, etc. It encapsulates both the object returned by /// the action, plus a sense of whether or not it is valid. /// When CompressInvalid is true, the "invalid" flag will be - /// stored in the low bit of the Val pointer. + /// stored in the low bit of the Val pointer. template::value> @@ -252,7 +252,7 @@ namespace clang { uintptr_t PtrWithInvalid; typedef llvm::PointerLikeTypeTraits PtrTraits; public: - ActionResult(bool Invalid = false) + ActionResult(bool Invalid = false) : PtrWithInvalid(static_cast(Invalid)) { } template @@ -262,17 +262,17 @@ namespace clang { PtrWithInvalid = reinterpret_cast(VP); assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"); } - + ActionResult(PtrTy V) { void *VP = PtrTraits::getAsVoidPointer(V); PtrWithInvalid = reinterpret_cast(VP); assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"); } - + ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) { } PtrTy get() const { - void *VP = reinterpret_cast(PtrWithInvalid & ~0x01); + void *VP = reinterpret_cast(PtrWithInvalid & ~0x01); return PtrTraits::getFromVoidPointer(VP); } @@ -326,8 +326,7 @@ namespace clang { /// Move emulation helper for ASTOwningResult. NEVER EVER use this class /// directly if you don't know what you're doing. template - class ASTResultMover - { + class ASTResultMover { ASTOwningResult &Moved; public: @@ -339,8 +338,7 @@ namespace clang { /// Move emulation helper for ASTMultiPtr. NEVER EVER use this class /// directly if you don't know what you're doing. template - class ASTMultiMover - { + class ASTMultiMover { ASTMultiPtr &Moved; public: @@ -357,8 +355,7 @@ namespace clang { /// Kept only as a type-safe wrapper for a void pointer, when smart pointers /// are disabled. When they are enabled, ASTOwningResult takes over. template - class ASTOwningPtr - { + class ASTOwningPtr { void *Node; public: @@ -400,8 +397,7 @@ namespace clang { #if !defined(DISABLE_SMART_POINTERS) template - class ASTOwningResult - { + class ASTOwningResult { llvm::PointerIntPair ActionInv; void *Ptr; @@ -505,8 +501,7 @@ namespace clang { }; #else template - class ASTOwningResult - { + class ASTOwningResult { public: typedef ActionBase::ActionResult::UID> DumbResult; @@ -522,8 +517,7 @@ namespace clang { ASTOwningResult(const ASTOwningPtr &o) : Result(o.get()) { } /// Assignment from a raw pointer. Takes ownership - beware! - ASTOwningResult & operator =(void *raw) - { + ASTOwningResult & operator =(void *raw) { Result = raw; return *this; } @@ -563,8 +557,7 @@ namespace clang { #endif template - class ASTMultiPtr - { + class ASTMultiPtr { #if !defined(DISABLE_SMART_POINTERS) ActionBase &Actions; #endif @@ -608,7 +601,7 @@ namespace clang { /// Move constructor ASTMultiPtr(moving::ASTMultiMover mover) #if defined(_MSC_VER) - // Apply the visual C++ hack supplied above. + // Apply the visual C++ hack supplied above. // Last tested with Visual Studio 2008. : Actions(hack(mover)->Actions), Nodes(hack(mover)->Nodes), Count(hack(mover)->Count) { #else @@ -660,7 +653,7 @@ namespace clang { } #endif }; - + class ASTTemplateArgsPtr { #if !defined(DISABLE_SMART_POINTERS) ActionBase &Actions; @@ -668,7 +661,7 @@ namespace clang { void **Args; bool *ArgIsType; mutable unsigned Count; - + #if !defined(DISABLE_SMART_POINTERS) void destroy() { if (!Count) @@ -684,16 +677,16 @@ namespace clang { public: ASTTemplateArgsPtr(ActionBase &actions, void **args, bool *argIsType, - unsigned count) : + unsigned count) : #if !defined(DISABLE_SMART_POINTERS) - Actions(actions), + Actions(actions), #endif Args(args), ArgIsType(argIsType), Count(count) { } // FIXME: Lame, not-fully-type-safe emulation of 'move semantics'. - ASTTemplateArgsPtr(ASTTemplateArgsPtr &Other) : + ASTTemplateArgsPtr(ASTTemplateArgsPtr &Other) : #if !defined(DISABLE_SMART_POINTERS) - Actions(Other.Actions), + Actions(Other.Actions), #endif Args(Other.Args), ArgIsType(Other.ArgIsType), Count(Other.Count) { #if !defined(DISABLE_SMART_POINTERS) @@ -734,7 +727,7 @@ namespace clang { void *operator[](unsigned Arg) const { return Args[Arg]; } - void **release() const { + void **release() const { #if !defined(DISABLE_SMART_POINTERS) Count = 0; #endif @@ -754,7 +747,7 @@ namespace clang { ASTOwningVector &operator=(ASTOwningVector &); // do not implement public: - explicit ASTOwningVector(ActionBase &Actions) + explicit ASTOwningVector(ActionBase &Actions) #if !defined(DISABLE_SMART_POINTERS) : Actions(Actions), Owned(true) #endif @@ -825,8 +818,7 @@ namespace clang { template inline ASTOwningPtr::ASTOwningPtr(const ASTOwningResult &o) - : Node(o.get()) - {} + : Node(o.get()) { } // These versions are hopefully no-ops. template inline diff --git a/clang/include/clang/Parse/ParseDiagnostic.h b/clang/include/clang/Parse/ParseDiagnostic.h index fa600ddadfab4c5e6ea039844b7ee6168eeb6a5d..c702e2fe65b86006fb8f23077190b296fce4062f 100644 --- a/clang/include/clang/Parse/ParseDiagnostic.h +++ b/clang/include/clang/Parse/ParseDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define PARSESTART diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index dd1036e861097a91bb865c2150acb66f659da9e3..e1a6e7ad397ebc71fa21c72b3fb6b0a46da0f1ea 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -38,8 +38,8 @@ public: PrettyStackTraceParserEntry(const Parser &p) : P(p) {} virtual void print(llvm::raw_ostream &OS) const; }; - - + + /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. @@ -47,13 +47,13 @@ public: class Parser { friend class PragmaUnusedHandler; PrettyStackTraceParserEntry CrashInfo; - + Preprocessor &PP; - + /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; - + // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of @@ -66,10 +66,10 @@ class Parser { /// in the file. This refers to the common base class between MinimalActions /// and SemaActions for those uses that don't matter. Action &Actions; - + Scope *CurScope; Diagnostic &Diags; - + /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; @@ -83,7 +83,7 @@ class Parser { llvm::OwningPtr UnusedHandler; llvm::OwningPtr WeakHandler; llvm::OwningPtr CommentHandler; - + /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template @@ -92,15 +92,15 @@ class Parser { /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; - + /// \brief RAII object that makes '>' behave either as an operator /// or as the closing angle bracket for a template argument list. struct GreaterThanIsOperatorScope { bool &GreaterThanIsOperator; bool OldGreaterThanIsOperator; - + GreaterThanIsOperatorScope(bool >IO, bool Val) - : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { + : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { GreaterThanIsOperator = Val; } @@ -108,7 +108,7 @@ class Parser { GreaterThanIsOperator = OldGreaterThanIsOperator; } }; - + public: Parser(Preprocessor &PP, Action &Actions); ~Parser(); @@ -117,9 +117,9 @@ public: TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Action &getActions() const { return Actions; } - + const Token &getCurToken() const { return Tok; } - + // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef Action::ExprTy ExprTy; @@ -166,24 +166,24 @@ public: OwningExprResult ExprEmpty() { return OwningExprResult(Actions, false); } // Parsing methods. - + /// ParseTranslationUnit - All in one method that initializes parses, and /// shuts down the parser. void ParseTranslationUnit(); - + /// Initialize - Warm up the parser. /// void Initialize(); - - /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if + + /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result); - + private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // - + /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; @@ -196,7 +196,7 @@ private: bool isTokenBrace() const { return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace; } - + /// isTokenStringLiteral - True if this token is a string-literal. /// bool isTokenStringLiteral() const { @@ -216,7 +216,7 @@ private: PP.Lex(Tok); return PrevTokLocation; } - + /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. @@ -232,7 +232,7 @@ private: else return ConsumeToken(); } - + /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { @@ -245,7 +245,7 @@ private: PP.Lex(Tok); return PrevTokLocation; } - + /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { @@ -254,12 +254,12 @@ private: ++BracketCount; else if (BracketCount) --BracketCount; // Don't let unbalanced ]'s drive the count negative. - + PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } - + /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { @@ -268,12 +268,12 @@ private: ++BraceCount; else if (BraceCount) --BraceCount; // Don't let unbalanced }'s drive the count negative. - + PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } - + /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation @@ -285,7 +285,7 @@ private: PP.Lex(Tok); return PrevTokLocation; } - + /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. @@ -362,8 +362,8 @@ private: assert(!isActive && "Forgot to call Commit or Revert!"); } }; - - + + /// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'), /// this helper function matches and consumes the specified RHS token if /// present. If not present, it emits the specified diagnostic indicating @@ -372,7 +372,7 @@ private: /// of the consumed token. SourceLocation MatchRHSPunctuation(tok::TokenKind RHSTok, SourceLocation LHSLoc); - + /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// @@ -385,7 +385,7 @@ private: //===--------------------------------------------------------------------===// // Scope manipulation - + /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the @@ -402,7 +402,7 @@ private: // parser Self where the new Scope is created with the flags // ScopeFlags, but only when ManageScope is true (the default). If // ManageScope is false, this object does nothing. - ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true) + ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true) : Self(Self) { if (ManageScope) Self->EnterScope(ScopeFlags); @@ -426,7 +426,7 @@ private: /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); - + /// ExitScope - Pop a scope off the scope stack. void ExitScope(); @@ -436,7 +436,7 @@ private: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); - void SuggestParentheses(SourceLocation Loc, unsigned DK, + void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); /// SkipUntil - Read tokens until we get to the specified token, then consume @@ -444,9 +444,9 @@ private: /// token will ever occur, this skips to the next token, or to some likely /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' /// character. - /// + /// /// If SkipUntil finds the specified token, it returns true, otherwise it - /// returns false. + /// returns false. bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true, bool DontConsume = false) { return SkipUntil(&T, 1, StopAtSemi, DontConsume); @@ -479,7 +479,7 @@ private: /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { - explicit LateParsedDefaultArgument(Action::DeclPtrTy P, + explicit LateParsedDefaultArgument(Action::DeclPtrTy P, CachedTokens *Toks = 0) : Param(P), Toks(Toks) { } @@ -492,13 +492,13 @@ private: /// default argument. CachedTokens *Toks; }; - + /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration { - explicit LateParsedMethodDeclaration(Action::DeclPtrTy M) + explicit LateParsedMethodDeclaration(Action::DeclPtrTy M) : Method(M), TemplateScope(false) { } /// Method - The method declaration. @@ -508,12 +508,12 @@ private: /// scope. When true, D is a template declaration. /// othewise, it is a member function declaration. bool TemplateScope; - + /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into - /// scope at the appropriate times. + /// scope at the appropriate times. llvm::SmallVector DefaultArgs; }; @@ -533,8 +533,8 @@ private: /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { - ParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass) - : TopLevelClass(TopLevelClass), TemplateScope(false), + ParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass) + : TopLevelClass(TopLevelClass), TemplateScope(false), TagOrTemplate(TagOrTemplate) { } /// \brief Whether this is a "top-level" class, meaning that it is @@ -571,27 +571,27 @@ private: return *ClassStack.top(); } - /// \brief RAII object used to + /// \brief RAII object used to class ParsingClassDefinition { Parser &P; bool Popped; public: - ParsingClassDefinition(Parser &P, DeclPtrTy TagOrTemplate, bool TopLevelClass) - : P(P), Popped(false) { + ParsingClassDefinition(Parser &P, DeclPtrTy TagOrTemplate, bool TopLevelClass) + : P(P), Popped(false) { P.PushParsingClass(TagOrTemplate, TopLevelClass); } /// \brief Pop this class of the stack. - void Pop() { + void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(); } - ~ParsingClassDefinition() { + ~ParsingClassDefinition() { if (!Popped) - P.PopParsingClass(); + P.PopParsingClass(); } }; @@ -599,7 +599,7 @@ private: /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { - ParsedTemplateInfo() + ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, @@ -609,7 +609,7 @@ private: explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) - : Kind(ExplicitInstantiation), TemplateParams(0), + : Kind(ExplicitInstantiation), TemplateParams(0), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc) { } /// \brief The kind of template we are parsing. @@ -631,12 +631,12 @@ private: /// \brief The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; - + /// \brief The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; }; - + void PushParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(); @@ -645,7 +645,7 @@ private: const ParsedTemplateInfo &TemplateInfo); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDefs(ParsingClass &Class); - bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, + bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, tok::TokenKind EarlyAbortIf = tok::unknown, bool ConsumeFinalToken = true); @@ -657,7 +657,7 @@ private: bool isStartOfFunctionDefinition(); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( AccessSpecifier AS = AS_none); - + DeclPtrTy ParseFunctionDefinition(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); void ParseKNRParamDeclarations(Declarator &D); @@ -667,20 +667,20 @@ private: OwningExprResult ParseAsmStringLiteral(); // Objective-C External Declarations - DeclPtrTy ParseObjCAtDirectives(); + DeclPtrTy ParseObjCAtDirectives(); DeclPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); - DeclPtrTy ParseObjCAtInterfaceDeclaration(SourceLocation atLoc, + DeclPtrTy ParseObjCAtInterfaceDeclaration(SourceLocation atLoc, AttributeList *prefixAttrs = 0); - void ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, + void ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, SourceLocation atLoc); bool ParseObjCProtocolReferences(llvm::SmallVectorImpl &P, - bool WarnOnDeclarations, + bool WarnOnDeclarations, SourceLocation &EndProtoLoc); void ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, tok::ObjCKeywordKind contextKey); DeclPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, AttributeList *prefixAttrs = 0); - + DeclPtrTy ObjCImpDecl; DeclPtrTy ParseObjCAtImplementationDeclaration(SourceLocation atLoc); @@ -688,7 +688,7 @@ private: DeclPtrTy ParseObjCAtAliasDeclaration(SourceLocation atLoc); DeclPtrTy ParseObjCPropertySynthesize(SourceLocation atLoc); DeclPtrTy ParseObjCPropertyDynamic(SourceLocation atLoc); - + IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { @@ -696,7 +696,7 @@ private: objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; - + bool isTokIdentifier_in() const; TypeTy *ParseObjCTypeName(ObjCDeclSpec &DS); @@ -707,9 +707,9 @@ private: DeclPtrTy classDecl, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); - + DeclPtrTy ParseObjCMethodDefinition(); - + //===--------------------------------------------------------------------===// // C99 6.5: Expressions. @@ -734,7 +734,7 @@ private: OwningExprResult ParsePostfixExpressionSuffix(OwningExprResult LHS); OwningExprResult ParseSizeofAlignofExpression(); OwningExprResult ParseBuiltinPrimaryExpression(); - + OwningExprResult ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, bool &isCastExpr, TypeTy *&CastTy, @@ -759,26 +759,26 @@ private: bool parseAsExprList, TypeTy *&CastTy, SourceLocation &RParenLoc); - + OwningExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, TypeTy *&CastTy, SourceLocation LParenLoc, SourceLocation &RParenLoc); - + OwningExprResult ParseCompoundLiteralExpression(TypeTy *Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); - + OwningExprResult ParseStringLiteralExpression(); //===--------------------------------------------------------------------===// // C++ Expressions OwningExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); - bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, + bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, TypeTy *ObjectType, bool EnteringContext); - + //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts OwningExprResult ParseCXXCasts(); @@ -832,7 +832,7 @@ private: //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. - + /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression @@ -852,15 +852,15 @@ private: //===--------------------------------------------------------------------===// // Objective-C Expressions - + bool isTokObjCMessageIdentifierReceiver() const { if (!Tok.is(tok::identifier)) return false; - + IdentifierInfo *II = Tok.getIdentifierInfo(); if (Actions.getTypeName(*II, Tok.getLocation(), CurScope)) return true; - + return II == Ident_super; } @@ -935,7 +935,7 @@ private: DSC_normal, // normal context DSC_class // class context, enables 'friend' }; - + DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd); DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context, SourceLocation &DeclEnd, @@ -949,17 +949,17 @@ private: bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS); - void ParseDeclarationSpecifiers(DeclSpec &DS, + void ParseDeclarationSpecifiers(DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DSC_normal); - bool ParseOptionalTypeSpecifier(DeclSpec &DS, bool &isInvalid, + bool ParseOptionalTypeSpecifier(DeclSpec &DS, bool &isInvalid, const char *&PrevSpec, unsigned &DiagID, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); void ParseSpecifierQualifierList(DeclSpec &DS); - + void ParseObjCTypeQualifierList(ObjCDeclSpec &DS); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, @@ -969,7 +969,7 @@ private: DeclPtrTy TagDecl); void ParseStructDeclaration(DeclSpec &DS, llvm::SmallVectorImpl &Fields); - + bool isDeclarationSpecifier(); bool isTypeSpecifierQualifier(); bool isTypeQualifier() const; @@ -1131,7 +1131,7 @@ private: } } }; - + /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. @@ -1147,10 +1147,10 @@ private: void ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, Declarator &D); void ParseBracketDeclarator(Declarator &D); - + //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] - + DeclPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd); DeclPtrTy ParseLinkage(unsigned Context); DeclPtrTy ParseUsingDirectiveOrDeclaration(unsigned Context, @@ -1164,14 +1164,14 @@ private: DeclPtrTy ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); - + //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. - TypeResult ParseClassName(SourceLocation &EndLocation, + TypeResult ParseClassName(SourceLocation &EndLocation, const CXXScopeSpec *SS = 0, bool DestrExpected = false); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, - DeclSpec &DS, + DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none); void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType, @@ -1212,9 +1212,9 @@ private: const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, AccessSpecifier AS=AS_none); - bool ParseTemplateParameters(unsigned Depth, + bool ParseTemplateParameters(unsigned Depth, TemplateParameterList &TemplateParams, - SourceLocation &LAngleLoc, + SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, TemplateParameterList &TemplateParams); @@ -1228,7 +1228,7 @@ private: typedef llvm::SmallVector TemplateArgLocationList; bool ParseTemplateIdAfterTemplateName(TemplateTy Template, - SourceLocation TemplateNameLoc, + SourceLocation TemplateNameLoc, const CXXScopeSpec *SS, bool ConsumeLastToken, SourceLocation &LAngleLoc, @@ -1247,7 +1247,7 @@ private: TemplateArgLocationList &TemplateArgLocations); void *ParseTemplateArgument(bool &ArgIsType); DeclPtrTy ParseExplicitInstantiation(SourceLocation ExternLoc, - SourceLocation TemplateLoc, + SourceLocation TemplateLoc, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// diff --git a/clang/include/clang/Parse/Scope.h b/clang/include/clang/Parse/Scope.h index 84cc5d5c3461a17ef508ac04f9d31df0bdebbac3..480b94f73f6218f813870b3482b7faa5e5129a1d 100644 --- a/clang/include/clang/Parse/Scope.h +++ b/clang/include/clang/Parse/Scope.h @@ -31,15 +31,15 @@ public: /// FnScope - This indicates that the scope corresponds to a function, which /// means that labels are set here. FnScope = 0x01, - + /// BreakScope - This is a while,do,switch,for, etc that can have break /// stmts embedded into it. BreakScope = 0x02, - + /// ContinueScope - This is a while,do,for, which can have continue /// stmt embedded into it. ContinueScope = 0x04, - + /// DeclScope - This is a scope that can contain a declaration. Some scopes /// just contain loop constructs but don't contain decls. DeclScope = 0x08, @@ -49,7 +49,7 @@ public: /// ClassScope - The scope of a struct/union/class definition. ClassScope = 0x20, - + /// BlockScope - This is a scope that corresponds to a block object. /// Blocks serve as top-level scopes for some objects like labels, they /// also prevent things like break and continue. BlockScopes have the @@ -65,7 +65,7 @@ public: /// FunctionPrototypeScope - This is a scope that corresponds to the /// parameters within a function prototype. FunctionPrototypeScope = 0x100, - + /// AtCatchScope - This is a scope that corresponds to the Objective-C /// @catch statement. AtCatchScope = 0x200 @@ -74,15 +74,15 @@ private: /// The parent scope for this scope. This is null for the translation-unit /// scope. Scope *AnyParent; - + /// Depth - This is the depth of this scope. The translation-unit scope has /// depth 0. unsigned Depth : 16; - + /// Flags - This contains a set of ScopeFlags, which indicates how the scope /// interrelates with other control flow statements. unsigned Flags : 10; - + /// WithinElse - Whether this scope is part of the "else" branch in /// its parent ControlScope. bool WithinElse : 1; @@ -90,7 +90,7 @@ private: /// FnParent - If this scope has a parent scope that is a function body, this /// pointer is non-null and points to it. This is used for label processing. Scope *FnParent; - + /// BreakParent/ContinueParent - This is a direct link to the immediately /// preceeding BreakParent/ContinueParent if this scope is not one, or null if /// there is no containing break/continue scope. @@ -119,7 +119,7 @@ private: /// implement these semantics. typedef llvm::SmallPtrSet DeclSetTy; DeclSetTy DeclsInScope; - + /// Entity - The entity with which this scope is associated. For /// example, the entity of a class scope is the class itself, the /// entity of a function scope is a function, etc. This field is @@ -151,9 +151,9 @@ public: /// const Scope *getFnParent() const { return FnParent; } Scope *getFnParent() { return FnParent; } - + /// getContinueParent - Return the closest scope that a continue statement - /// would be affected by. If the closest scope is a closure scope, we know + /// would be affected by. If the closest scope is a closure scope, we know /// that there is no loop *inside* the closure. Scope *getContinueParent() { if (ContinueParent && !ContinueParent->isBlockScope()) @@ -164,9 +164,9 @@ public: const Scope *getContinueParent() const { return const_cast(this)->getContinueParent(); } - + /// getBreakParent - Return the closest scope that a break statement - /// would be affected by. If the closest scope is a block scope, we know + /// would be affected by. If the closest scope is a block scope, we know /// that there is no loop *inside* the block. Scope *getBreakParent() { if (BreakParent && !BreakParent->isBlockScope()) @@ -176,16 +176,16 @@ public: const Scope *getBreakParent() const { return const_cast(this)->getBreakParent(); } - + Scope *getControlParent() { return ControlParent; } const Scope *getControlParent() const { return ControlParent; } - + Scope *getBlockParent() { return BlockParent; } - const Scope *getBlockParent() const { return BlockParent; } + const Scope *getBlockParent() const { return BlockParent; } Scope *getTemplateParamParent() { return TemplateParamParent; } - const Scope *getTemplateParamParent() const { return TemplateParamParent; } - + const Scope *getTemplateParamParent() const { return TemplateParamParent; } + typedef DeclSetTy::iterator decl_iterator; decl_iterator decl_begin() const { return DeclsInScope.begin(); } decl_iterator decl_end() const { return DeclsInScope.end(); } @@ -222,7 +222,7 @@ public: } return false; } - + /// isTemplateParamScope - Return true if this scope is a C++ /// template parameter scope. bool isTemplateParamScope() const { @@ -275,7 +275,7 @@ public: AnyParent = Parent; Depth = AnyParent ? AnyParent->Depth+1 : 0; Flags = ScopeFlags; - + if (AnyParent) { FnParent = AnyParent->FnParent; BreakParent = AnyParent->BreakParent; @@ -291,7 +291,7 @@ public: TemplateParamParent = 0; WithinElse = false; } - + // If this scope is a function or contains breaks/continues, remember it. if (Flags & FnScope) FnParent = this; if (Flags & BreakScope) BreakParent = this; @@ -304,7 +304,7 @@ public: Entity = 0; } }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Rewrite/DeltaTree.h b/clang/include/clang/Rewrite/DeltaTree.h index 7bf9305e287755cfaaddc13e2fee467ba98b74dc..7e0796524c6d9011775aa478224ff086b75cb7dc 100644 --- a/clang/include/clang/Rewrite/DeltaTree.h +++ b/clang/include/clang/Rewrite/DeltaTree.h @@ -15,7 +15,7 @@ #define CLANG_REWRITE_DELTATREE_H namespace clang { - + /// DeltaTree - a multiway search tree (BTree) structure with some fancy /// features. B-Trees are are generally more memory and cache efficient than /// binary trees, because they store multiple keys/values in each node. This @@ -32,16 +32,16 @@ namespace clang { // Note: Currently we only support copying when the RHS is empty. DeltaTree(const DeltaTree &RHS); ~DeltaTree(); - + /// getDeltaAt - Return the accumulated delta at the specified file offset. /// This includes all insertions or delections that occurred *before* the /// specified file index. - int getDeltaAt(unsigned FileIndex) const; + int getDeltaAt(unsigned FileIndex) const; /// AddDelta - When a change is made that shifts around the text buffer, /// this method is used to record that info. It inserts a delta of 'Delta' /// into the current DeltaTree at offset FileIndex. - void AddDelta(unsigned FileIndex, int Delta); + void AddDelta(unsigned FileIndex, int Delta); }; } // end namespace clang diff --git a/clang/include/clang/Rewrite/HTMLRewrite.h b/clang/include/clang/Rewrite/HTMLRewrite.h index f49d49e710c9a7b9d9ab99b63f2027e725710fbd..f77e0c61c54ce4a3db39d885efbbae63f3ad4e10 100644 --- a/clang/include/clang/Rewrite/HTMLRewrite.h +++ b/clang/include/clang/Rewrite/HTMLRewrite.h @@ -19,36 +19,36 @@ #include namespace clang { - + class Rewriter; class RewriteBuffer; class Preprocessor; class PreprocessorFactory; - + namespace html { - + /// HighlightRange - Highlight a range in the source code with the specified /// start/end tags. B/E must be in the same file. This ensures that /// start/end tags are placed at the start/end of each line if the range is /// multiline. void HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E, const char *StartTag, const char *EndTag); - + /// HighlightRange - Highlight a range in the source code with the specified - /// start/end tags. The Start/end of the range must be in the same file. + /// start/end tags. The Start/end of the range must be in the same file. /// This ensures that start/end tags are placed at the start/end of each line /// if the range is multiline. inline void HighlightRange(Rewriter &R, SourceRange Range, const char *StartTag, const char *EndTag) { HighlightRange(R, Range.getBegin(), Range.getEnd(), StartTag, EndTag); } - + /// HighlightRange - This is the same as the above method, but takes /// decomposed file locations. void HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E, const char *BufferStart, const char *StartTag, const char *EndTag); - + /// EscapeText - HTMLize a specified file so that special characters are /// are translated so that they are not interpreted as HTML tags. void EscapeText(Rewriter& R, FileID FID, @@ -61,9 +61,9 @@ namespace html { std::string EscapeText(const std::string& s, bool EscapeSpaces = false, bool ReplaceTabs = false); - void AddLineNumbers(Rewriter& R, FileID FID); - - void AddHeaderFooterInternalBuiltinCSS(Rewriter& R, FileID FID, + void AddLineNumbers(Rewriter& R, FileID FID); + + void AddHeaderFooterInternalBuiltinCSS(Rewriter& R, FileID FID, const char *title = NULL); /// SyntaxHighlight - Relex the specified FileID and annotate the HTML with diff --git a/clang/include/clang/Rewrite/RewriteRope.h b/clang/include/clang/Rewrite/RewriteRope.h index 3b8eeb2b6b58caf245aa7e072a452d366caaa40c..c0bd741d554656e15e4b55b5870edb7edc627e95 100644 --- a/clang/include/clang/Rewrite/RewriteRope.h +++ b/clang/include/clang/Rewrite/RewriteRope.h @@ -22,7 +22,7 @@ namespace clang { //===--------------------------------------------------------------------===// // RopeRefCountString Class //===--------------------------------------------------------------------===// - + /// RopeRefCountString - This struct is allocated with 'new char[]' from the /// heap, and represents a reference counted chunk of string data. When its /// ref count drops to zero, it is delete[]'d. This is primarily managed @@ -30,21 +30,21 @@ namespace clang { struct RopeRefCountString { unsigned RefCount; char Data[1]; // Variable sized. - + void addRef() { if (this) ++RefCount; } - + void dropRef() { if (this && --RefCount == 0) delete [] (char*)this; } }; - + //===--------------------------------------------------------------------===// // RopePiece Class //===--------------------------------------------------------------------===// - + /// RopePiece - This class represents a view into a RopeRefCountString object. /// This allows references to string data to be efficiently chopped up and /// moved around without having to push around the string data itself. @@ -57,9 +57,9 @@ namespace clang { RopeRefCountString *StrData; unsigned StartOffs; unsigned EndOffs; - + RopePiece() : StrData(0), StartOffs(0), EndOffs(0) {} - + RopePiece(RopeRefCountString *Str, unsigned Start, unsigned End) : StrData(Str), StartOffs(Start), EndOffs(End) { StrData->addRef(); @@ -68,11 +68,11 @@ namespace clang { : StrData(RP.StrData), StartOffs(RP.StartOffs), EndOffs(RP.EndOffs) { StrData->addRef(); } - + ~RopePiece() { StrData->dropRef(); } - + void operator=(const RopePiece &RHS) { if (StrData != RHS.StrData) { StrData->dropRef(); @@ -82,21 +82,21 @@ namespace clang { StartOffs = RHS.StartOffs; EndOffs = RHS.EndOffs; } - + const char &operator[](unsigned Offset) const { return StrData->Data[Offset+StartOffs]; } char &operator[](unsigned Offset) { return StrData->Data[Offset+StartOffs]; } - + unsigned size() const { return EndOffs-StartOffs; } }; - + //===--------------------------------------------------------------------===// // RopePieceBTreeIterator Class //===--------------------------------------------------------------------===// - + /// RopePieceBTreeIterator - This class provides read-only forward iteration /// over bytes that are in a RopePieceBTree. This first iterates over bytes /// in a RopePiece, then iterates over RopePiece's in a RopePieceBTreeLeaf, @@ -115,18 +115,18 @@ namespace clang { RopePieceBTreeIterator(const void /*RopePieceBTreeNode*/ *N); // end iterator RopePieceBTreeIterator() : CurNode(0), CurPiece(0), CurChar(0) {} - + char operator*() const { return (*CurPiece)[CurChar]; } - + bool operator==(const RopePieceBTreeIterator &RHS) const { return CurPiece == RHS.CurPiece && CurChar == RHS.CurChar; } bool operator!=(const RopePieceBTreeIterator &RHS) const { return !operator==(RHS); } - + RopePieceBTreeIterator& operator++() { // Preincrement if (CurChar+1 < CurPiece->size()) ++CurChar; @@ -140,11 +140,11 @@ namespace clang { private: void MoveToNextPiece(); }; - + //===--------------------------------------------------------------------===// // RopePieceBTree Class //===--------------------------------------------------------------------===// - + class RopePieceBTree { void /*RopePieceBTreeNode*/ *Root; void operator=(const RopePieceBTree &); // DO NOT IMPLEMENT @@ -152,15 +152,15 @@ namespace clang { RopePieceBTree(); RopePieceBTree(const RopePieceBTree &RHS); ~RopePieceBTree(); - + typedef RopePieceBTreeIterator iterator; iterator begin() const { return iterator(Root); } iterator end() const { return iterator(); } unsigned size() const; unsigned empty() const { return size() == 0; } - + void clear(); - + void insert(unsigned Offset, const RopePiece &R); void erase(unsigned Offset, unsigned NumBytes); @@ -169,13 +169,13 @@ namespace clang { //===--------------------------------------------------------------------===// // RewriteRope Class //===--------------------------------------------------------------------===// - + /// RewriteRope - A powerful string class. This class supports extremely /// efficient insertions and deletions into the middle of it, even for /// ridiculously long strings. class RewriteRope { RopePieceBTree Chunks; - + /// We allocate space for string data out of a buffer of size AllocChunkSize. /// This keeps track of how much space is left. RopeRefCountString *AllocBuffer; @@ -184,7 +184,7 @@ class RewriteRope { public: RewriteRope() : AllocBuffer(0), AllocOffs(AllocChunkSize) {} - RewriteRope(const RewriteRope &RHS) + RewriteRope(const RewriteRope &RHS) : Chunks(RHS.Chunks), AllocBuffer(0), AllocOffs(AllocChunkSize) { } @@ -192,23 +192,23 @@ public: // If we had an allocation buffer, drop our reference to it. AllocBuffer->dropRef(); } - + typedef RopePieceBTree::iterator iterator; typedef RopePieceBTree::iterator const_iterator; iterator begin() const { return Chunks.begin(); } iterator end() const { return Chunks.end(); } unsigned size() const { return Chunks.size(); } - + void clear() { Chunks.clear(); } - + void assign(const char *Start, const char *End) { clear(); if (Start != End) Chunks.insert(0, MakeRopeString(Start, End)); } - + void insert(unsigned Offset, const char *Start, const char *End) { assert(Offset <= size() && "Invalid position to insert!"); if (Start == End) return; @@ -224,7 +224,7 @@ public: private: RopePiece MakeRopeString(const char *Start, const char *End); }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Rewrite/Rewriter.h b/clang/include/clang/Rewrite/Rewriter.h index ea4b08e71b13d6ccdd13b0840f85192b8c269f73..29e78fa27958b6639843e5a64619cb4e02b49d69 100644 --- a/clang/include/clang/Rewrite/Rewriter.h +++ b/clang/include/clang/Rewrite/Rewriter.h @@ -29,7 +29,7 @@ namespace clang { class LangOptions; class Rewriter; class Stmt; - + /// RewriteBuffer - As code is rewritten, SourceBuffer's from the original /// input with modifications get a new RewriteBuffer associated with them. The /// RewriteBuffer captures the modified text itself as well as information used @@ -41,7 +41,7 @@ class RewriteBuffer { /// Deltas - Keep track of all the deltas in the source code due to insertions /// and deletions. DeltaTree Deltas; - + /// Buffer - This is the actual buffer itself. Note that using a vector or /// string is a horribly inefficient way to do this, we should use a rope /// instead. @@ -52,17 +52,17 @@ public: iterator begin() const { return Buffer.begin(); } iterator end() const { return Buffer.end(); } unsigned size() const { return Buffer.size(); } - + /// RemoveText - Remove the specified text. void RemoveText(unsigned OrigOffset, unsigned Size); - + /// InsertText - Insert some text at the specified point, where the offset in /// the buffer is specified relative to the original SourceBuffer. The /// text is inserted after the specified location. /// void InsertText(unsigned OrigOffset, const llvm::StringRef &Str, bool InsertAfter = true); - + /// InsertTextBefore - Insert some text before the specified point, where the /// offset in the buffer is specified relative to the original @@ -71,28 +71,28 @@ public: void InsertTextBefore(unsigned OrigOffset, const llvm::StringRef &Str) { InsertText(OrigOffset, Str, false); } - + /// InsertTextAfter - Insert some text at the specified point, where the /// offset in the buffer is specified relative to the original SourceBuffer. /// The text is inserted after the specified location. void InsertTextAfter(unsigned OrigOffset, const llvm::StringRef &Str) { InsertText(OrigOffset, Str); } - + /// ReplaceText - This method replaces a range of characters in the input /// buffer with a new string. This is effectively a combined "remove/insert" /// operation. void ReplaceText(unsigned OrigOffset, unsigned OrigLength, const llvm::StringRef &NewStr); - + private: // Methods only usable by Rewriter. - + /// Initialize - Start this rewrite buffer out with a copy of the unmodified /// input buffer. void Initialize(const char *BufStart, const char *BufEnd) { Buffer.assign(BufStart, BufEnd); } - + /// getMappedOffset - Given an offset into the original SourceBuffer that this /// RewriteBuffer is based on, map it into the offset space of the /// RewriteBuffer. If AfterInserts is true and if the OrigOffset indicates a @@ -102,7 +102,7 @@ private: // Methods only usable by Rewriter. bool AfterInserts = false) const{ return Deltas.getDeltaAt(2*OrigOffset+AfterInserts)+OrigOffset; } - + /// AddInsertDelta - When an insertion is made at a position, this /// method is used to record that information. void AddInsertDelta(unsigned OrigOffset, int Change) { @@ -115,7 +115,7 @@ private: // Methods only usable by Rewriter. return Deltas.AddDelta(2*OrigOffset+1, Change); } }; - + /// Rewriter - This is the main interface to the rewrite buffers. Its primary /// job is to dispatch high-level requests to the low-level RewriteBuffers that @@ -128,14 +128,14 @@ public: explicit Rewriter(SourceManager &SM, const LangOptions &LO) : SourceMgr(&SM), LangOpts(&LO) {} explicit Rewriter() : SourceMgr(0), LangOpts(0) {} - + void setSourceMgr(SourceManager &SM, const LangOptions &LO) { SourceMgr = &SM; LangOpts = &LO; } SourceManager &getSourceMgr() { return *SourceMgr; } const LangOptions &getLangOpts() { return *LangOpts; } - + /// isRewritable - Return true if this location is a raw file location, which /// is rewritable. Locations from macros, etc are not rewritable. static bool isRewritable(SourceLocation Loc) { @@ -145,7 +145,7 @@ public: /// getRangeSize - Return the size in bytes of the specified range if they /// are in the same file. If not, this returns -1. int getRangeSize(SourceRange Range) const; - + /// getRewritenText - Return the rewritten form of the text in the specified /// range. If the start or end of the range was unrewritable or if they are /// in different buffers, this returns an empty string. @@ -153,22 +153,22 @@ public: /// Note that this method is not particularly efficient. /// std::string getRewritenText(SourceRange Range) const; - + /// InsertText - Insert the specified string at the specified location in the /// original buffer. This method returns true (and does nothing) if the input /// location was not rewritable, false otherwise. bool InsertText(SourceLocation Loc, const llvm::StringRef &Str, bool InsertAfter = true); - + /// InsertTextAfter - Insert the specified string at the specified location in - /// the original buffer. This method returns true (and does nothing) if + /// the original buffer. This method returns true (and does nothing) if /// the input location was not rewritable, false otherwise. Text is /// inserted after any other text that has been previously inserted /// at the some point (the default behavior for InsertText). bool InsertTextAfter(SourceLocation Loc, const llvm::StringRef &Str) { return InsertText(Loc, Str); - } - + } + /// InsertText - Insert the specified string at the specified location in the /// original buffer. This method returns true (and does nothing) if the input /// location was not rewritable, false otherwise. Text is @@ -177,21 +177,21 @@ public: bool InsertTextBefore(SourceLocation Loc, const llvm::StringRef &Str) { return InsertText(Loc, Str, false); } - + /// RemoveText - Remove the specified text region. bool RemoveText(SourceLocation Start, unsigned Length); - + /// ReplaceText - This method replaces a range of characters in the input /// buffer with a new string. This is effectively a combined "remove/insert" /// operation. bool ReplaceText(SourceLocation Start, unsigned OrigLength, const llvm::StringRef &NewStr); - + /// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty /// printer to generate the replacement code. This returns true if the input /// could not be rewritten, or false if successful. bool ReplaceStmt(Stmt *From, Stmt *To); - + /// getRewriteBufferFor - Return the rewrite buffer for the specified FileID. /// If no modification has been made to it, return null. const RewriteBuffer *getRewriteBufferFor(FileID FID) const { @@ -209,7 +209,7 @@ public: private: unsigned getLocationOffsetAndFileID(SourceLocation Loc, FileID &FID) const; }; - + } // end namespace clang #endif diff --git a/clang/include/clang/Rewrite/TokenRewriter.h b/clang/include/clang/Rewrite/TokenRewriter.h index c8fd0f532c25a288ed923a60143c414dfce2033f..62ea12af1f17c87843fba8b4c0730756d2f8f28f 100644 --- a/clang/include/clang/Rewrite/TokenRewriter.h +++ b/clang/include/clang/Rewrite/TokenRewriter.h @@ -24,7 +24,7 @@ namespace clang { class Token; class LangOptions; class ScratchBuffer; - + class TokenRewriter { /// TokenList - This is the list of raw tokens that make up this file. Each /// of these tokens has a unique SourceLocation, which is a FileID. @@ -32,17 +32,17 @@ namespace clang { /// TokenRefTy - This is the type used to refer to a token in the TokenList. typedef std::list::iterator TokenRefTy; - + /// TokenAtLoc - This map indicates which token exists at a specific /// SourceLocation. Since each token has a unique SourceLocation, this is a /// one to one map. The token can return its own location directly, to map /// backwards. std::map TokenAtLoc; - + /// ScratchBuf - This is the buffer that we create scratch tokens from. /// llvm::OwningPtr ScratchBuf; - + TokenRewriter(const TokenRewriter&); // DO NOT IMPLEMENT void operator=(const TokenRewriter&); // DO NOT IMPLEMENT. public: @@ -50,30 +50,30 @@ namespace clang { /// specified FileID. TokenRewriter(FileID FID, SourceManager &SM, const LangOptions &LO); ~TokenRewriter(); - + typedef std::list::const_iterator token_iterator; token_iterator token_begin() const { return TokenList.begin(); } token_iterator token_end() const { return TokenList.end(); } - - + + token_iterator AddTokenBefore(token_iterator I, const char *Val); token_iterator AddTokenAfter(token_iterator I, const char *Val) { assert(I != token_end() && "Cannot insert after token_end()!"); return AddTokenBefore(++I, Val); } - + private: /// RemapIterator - Convert from token_iterator (a const iterator) to /// TokenRefTy (a non-const iterator). TokenRefTy RemapIterator(token_iterator I); - + /// AddToken - Add the specified token into the Rewriter before the other /// position. TokenRefTy AddToken(const Token &T, TokenRefTy Where); }; - - - + + + } // end namespace clang #endif diff --git a/clang/include/clang/Sema/ExternalSemaSource.h b/clang/include/clang/Sema/ExternalSemaSource.h index 0f0d375e9c30a729a3ea168837d9ba0c33d63d89..05c56451b21884bc70e51c00cfe39fccfcf7af12 100644 --- a/clang/include/clang/Sema/ExternalSemaSource.h +++ b/clang/include/clang/Sema/ExternalSemaSource.h @@ -39,13 +39,13 @@ public: /// /// \returns a pair of Objective-C methods lists containing the /// instance and factory methods, respectively, with this selector. - virtual std::pair - ReadMethodPool(Selector Sel) { + virtual std::pair + ReadMethodPool(Selector Sel) { return std::pair(); } - + // isa/cast/dyn_cast support - static bool classof(const ExternalASTSource *Source) { + static bool classof(const ExternalASTSource *Source) { return Source->SemaSource; } static bool classof(const ExternalSemaSource *) { return true; } diff --git a/clang/include/clang/Sema/ParseAST.h b/clang/include/clang/Sema/ParseAST.h index bdce5e95effb5e1a5be174b5bfc1fcbc9170f718..debe75bb85dd661202edd12b5d3cddbda069caac 100644 --- a/clang/include/clang/Sema/ParseAST.h +++ b/clang/include/clang/Sema/ParseAST.h @@ -28,7 +28,7 @@ namespace clang { /// \param CompleteTranslationUnit When true, the parsed file is /// considered to be a complete translation unit, and any /// end-of-translation-unit wrapup will be performed. - void ParseAST(Preprocessor &pp, ASTConsumer *C, + void ParseAST(Preprocessor &pp, ASTConsumer *C, ASTContext &Ctx, bool PrintStats = false, bool CompleteTranslationUnit = true); diff --git a/clang/include/clang/Sema/SemaConsumer.h b/clang/include/clang/Sema/SemaConsumer.h index e821947035c4c74bff954a8506f57958daa926ba..b213daf8a39ea0f85897f00f65eaafb19d899ee3 100644 --- a/clang/include/clang/Sema/SemaConsumer.h +++ b/clang/include/clang/Sema/SemaConsumer.h @@ -35,8 +35,8 @@ namespace clang { virtual void InitializeSema(Sema &S) {} // isa/cast/dyn_cast support - static bool classof(const ASTConsumer *Consumer) { - return Consumer->SemaConsumer; + static bool classof(const ASTConsumer *Consumer) { + return Consumer->SemaConsumer; } static bool classof(const SemaConsumer *) { return true; } }; diff --git a/clang/include/clang/Sema/SemaDiagnostic.h b/clang/include/clang/Sema/SemaDiagnostic.h index de92844f4d6adf78c554cc2341a3fa12718c05b2..d026339b5caf98acff9a96861adcf303d644a11f 100644 --- a/clang/include/clang/Sema/SemaDiagnostic.h +++ b/clang/include/clang/Sema/SemaDiagnostic.h @@ -13,7 +13,7 @@ #include "clang/Basic/Diagnostic.h" namespace clang { - namespace diag { + namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM, #define SEMASTART diff --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp index 489dac7970646e03cba3ff385323edd541c3c455..772a884c90d361502bf0b0313bd9d21671d066f9 100644 --- a/clang/lib/AST/APValue.cpp +++ b/clang/lib/AST/APValue.cpp @@ -91,7 +91,7 @@ void APValue::print(llvm::raw_ostream &OS) const { return; case Vector: OS << "Vector: " << getVectorElt(0); - for (unsigned i = 1; i != getVectorLength(); ++i) + for (unsigned i = 1; i != getVectorLength(); ++i) OS << ", " << getVectorElt(i); return; case ComplexInt: diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp index 30e42349564df0b3f38756b55c65067ee3310439..bf1fac9eec11a77a73f94b63fec44cb33d5278a5 100644 --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -37,16 +37,16 @@ ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, - bool FreeMem, unsigned size_reserve) : - GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), + bool FreeMem, unsigned size_reserve) : + GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0), - sigjmp_bufDecl(0), SourceMgr(SM), LangOpts(LOpts), - LoadedExternalComments(false), FreeMemory(FreeMem), Target(t), + sigjmp_bufDecl(0), SourceMgr(SM), LangOpts(LOpts), + LoadedExternalComments(false), FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels), - BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) { + BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) { ObjCIdRedefinitionType = QualType(); ObjCClassRedefinitionType = QualType(); - if (size_reserve > 0) Types.reserve(size_reserve); + if (size_reserve > 0) Types.reserve(size_reserve); TUDecl = TranslationUnitDecl::Create(*this); InitBuiltinTypes(); } @@ -79,8 +79,8 @@ ASTContext::~ASTContext() { // Destroy nested-name-specifiers. for (llvm::FoldingSet::iterator NNS = NestedNameSpecifiers.begin(), - NNSEnd = NestedNameSpecifiers.end(); - NNS != NNSEnd; + NNSEnd = NestedNameSpecifiers.end(); + NNS != NNSEnd; /* Increment in loop */) (*NNS++).Destroy(*this); @@ -90,7 +90,7 @@ ASTContext::~ASTContext() { TUDecl->Destroy(*this); } -void +void ASTContext::setExternalSource(llvm::OwningPtr &Source) { ExternalSource.reset(Source.take()); } @@ -100,7 +100,7 @@ void ASTContext::PrintStats() const { fprintf(stderr, " %d types total.\n", (int)Types.size()); unsigned counts[] = { -#define TYPE(Name, Parent) 0, +#define TYPE(Name, Parent) 0, #define ABSTRACT_TYPE(Name, Parent) #include "clang/AST/TypeNodes.def" 0 // Extra @@ -120,7 +120,7 @@ void ASTContext::PrintStats() const { ++Idx; #define ABSTRACT_TYPE(Name, Parent) #include "clang/AST/TypeNodes.def" - + fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); if (ExternalSource.get()) { @@ -136,10 +136,10 @@ void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) { void ASTContext::InitBuiltinTypes() { assert(VoidTy.isNull() && "Context reinitialized?"); - + // C99 6.2.5p19. InitBuiltinType(VoidTy, BuiltinType::Void); - + // C99 6.2.5p2. InitBuiltinType(BoolTy, BuiltinType::Bool); // C99 6.2.5p3. @@ -153,14 +153,14 @@ void ASTContext::InitBuiltinTypes() { InitBuiltinType(IntTy, BuiltinType::Int); InitBuiltinType(LongTy, BuiltinType::Long); InitBuiltinType(LongLongTy, BuiltinType::LongLong); - + // C99 6.2.5p6. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); - + // C99 6.2.5p10. InitBuiltinType(FloatTy, BuiltinType::Float); InitBuiltinType(DoubleTy, BuiltinType::Double); @@ -195,27 +195,27 @@ void ASTContext::InitBuiltinTypes() { // expressions. InitBuiltinType(DependentTy, BuiltinType::Dependent); - // Placeholder type for C++0x auto declarations whose real type has + // Placeholder type for C++0x auto declarations whose real type has // not yet been deduced. InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto); - + // C99 6.2.5p11. FloatComplexTy = getComplexType(FloatTy); DoubleComplexTy = getComplexType(DoubleTy); LongDoubleComplexTy = getComplexType(LongDoubleTy); BuiltinVaListType = QualType(); - + // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope(). ObjCIdTypedefType = QualType(); ObjCClassTypedefType = QualType(); - + // Builtin types for 'id' and 'Class'. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); ObjCConstantStringType = QualType(); - + // void * type VoidPtrTy = getPointerType(VoidTy); @@ -229,11 +229,11 @@ VarDecl *ASTContext::getInstantiatedFromStaticDataMember(VarDecl *Var) { = InstantiatedFromStaticDataMember.find(Var); if (Pos == InstantiatedFromStaticDataMember.end()) return 0; - + return Pos->second; } -void +void ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) { assert(Inst->isStaticDataMember() && "Not a static data member"); assert(Tmpl->isStaticDataMember() && "Not a static data member"); @@ -244,11 +244,11 @@ ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) { UnresolvedUsingDecl * ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) { - llvm::DenseMap::iterator Pos + llvm::DenseMap::iterator Pos = InstantiatedFromUnresolvedUsingDecl.find(UUD); if (Pos == InstantiatedFromUnresolvedUsingDecl.end()) return 0; - + return Pos->second; } @@ -265,7 +265,7 @@ FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { = InstantiatedFromUnnamedFieldDecl.find(Field); if (Pos == InstantiatedFromUnnamedFieldDecl.end()) return 0; - + return Pos->second; } @@ -275,18 +275,18 @@ void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); assert(!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"); - + InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; } namespace { - class BeforeInTranslationUnit + class BeforeInTranslationUnit : std::binary_function { SourceManager *SourceMgr; - + public: explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { } - + bool operator()(SourceRange X, SourceRange Y) { return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin()); } @@ -302,14 +302,14 @@ namespace { /// \param Member whether we want to check whether this is a member comment /// (which requires a < after the Doxygen-comment delimiter). Otherwise, /// we only return true when we find a non-member comment. -static bool -isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment, +static bool +isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment, bool Member = false) { - const char *BufferStart + const char *BufferStart = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first; const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin()); const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd()); - + if (End - Start < 4) return false; @@ -323,32 +323,32 @@ isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment, } /// \brief Retrieve the comment associated with the given declaration, if -/// it has one. +/// it has one. const char *ASTContext::getCommentForDecl(const Decl *D) { if (!D) return 0; - + // Check whether we have cached a comment string for this declaration // already. - llvm::DenseMap::iterator Pos + llvm::DenseMap::iterator Pos = DeclComments.find(D); if (Pos != DeclComments.end()) return Pos->second.c_str(); - // If we have an external AST source and have not yet loaded comments from + // If we have an external AST source and have not yet loaded comments from // that source, do so now. if (ExternalSource && !LoadedExternalComments) { std::vector LoadedComments; ExternalSource->ReadComments(LoadedComments); - + if (!LoadedComments.empty()) Comments.insert(Comments.begin(), LoadedComments.begin(), LoadedComments.end()); - + LoadedExternalComments = true; } - - // If there are no comments anywhere, we won't find anything. + + // If there are no comments anywhere, we won't find anything. if (Comments.empty()) return 0; @@ -360,17 +360,17 @@ const char *ASTContext::getCommentForDecl(const Decl *D) { // Find the comment that occurs just before this declaration. std::vector::iterator LastComment - = std::lower_bound(Comments.begin(), Comments.end(), + = std::lower_bound(Comments.begin(), Comments.end(), SourceRange(DeclStartLoc), BeforeInTranslationUnit(&SourceMgr)); - + // Decompose the location for the start of the declaration and find the // beginning of the file buffer. - std::pair DeclStartDecomp + std::pair DeclStartDecomp = SourceMgr.getDecomposedLoc(DeclStartLoc); - const char *FileBufferStart + const char *FileBufferStart = SourceMgr.getBufferData(DeclStartDecomp.first).first; - + // First check whether we have a comment for a member. if (LastComment != Comments.end() && !isa(D) && !isa(D) && @@ -379,19 +379,19 @@ const char *ASTContext::getCommentForDecl(const Decl *D) { = SourceMgr.getDecomposedLoc(LastComment->getEnd()); if (DeclStartDecomp.first == LastCommentEndDecomp.first && SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second) - == SourceMgr.getLineNumber(LastCommentEndDecomp.first, + == SourceMgr.getLineNumber(LastCommentEndDecomp.first, LastCommentEndDecomp.second)) { // The Doxygen member comment comes after the declaration starts and // is on the same line and in the same file as the declaration. This // is the comment we want. std::string &Result = DeclComments[D]; - Result.append(FileBufferStart + - SourceMgr.getFileOffset(LastComment->getBegin()), + Result.append(FileBufferStart + + SourceMgr.getFileOffset(LastComment->getBegin()), FileBufferStart + LastCommentEndDecomp.second + 1); return Result.c_str(); } } - + if (LastComment == Comments.begin()) return 0; --LastComment; @@ -399,33 +399,33 @@ const char *ASTContext::getCommentForDecl(const Decl *D) { // Decompose the end of the comment. std::pair LastCommentEndDecomp = SourceMgr.getDecomposedLoc(LastComment->getEnd()); - + // If the comment and the declaration aren't in the same file, then they // aren't related. if (DeclStartDecomp.first != LastCommentEndDecomp.first) return 0; - + // Check that we actually have a Doxygen comment. if (!isDoxygenComment(SourceMgr, *LastComment)) return 0; - + // Compute the starting line for the declaration and for the end of the // comment (this is expensive). - unsigned DeclStartLine + unsigned DeclStartLine = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second); unsigned CommentEndLine - = SourceMgr.getLineNumber(LastCommentEndDecomp.first, + = SourceMgr.getLineNumber(LastCommentEndDecomp.first, LastCommentEndDecomp.second); - + // If the comment does not end on the line prior to the declaration, then // the comment is not associated with the declaration at all. if (CommentEndLine + 1 != DeclStartLine) return 0; - + // We have a comment, but there may be more comments on the previous lines. // Keep looking so long as the comments are still Doxygen comments and are // still adjacent. - unsigned ExpectedLine + unsigned ExpectedLine = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1; std::vector::iterator FirstComment = LastComment; while (FirstComment != Comments.begin()) { @@ -433,31 +433,31 @@ const char *ASTContext::getCommentForDecl(const Decl *D) { --FirstComment; std::pair Decomp = SourceMgr.getDecomposedLoc(FirstComment->getEnd()); - + // If this previous comment is in a different file, we're done. if (Decomp.first != DeclStartDecomp.first) { ++FirstComment; break; } - + // If this comment is not a Doxygen comment, we're done. if (!isDoxygenComment(SourceMgr, *FirstComment)) { ++FirstComment; break; } - + // If the line number is not what we expected, we're done. unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second); if (Line != ExpectedLine) { ++FirstComment; break; } - + // Set the next expected line number. - ExpectedLine + ExpectedLine = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1; } - + // The iterator range [FirstComment, LastComment] contains all of the // BCPL comments that, together, are associated with this declaration. // Form a single comment block string for this declaration that concatenates @@ -472,10 +472,10 @@ const char *ASTContext::getCommentForDecl(const Decl *D) { FileBufferStart + DecompEnd.second + 1); ++FirstComment; } - + // Append the last comment line. - Result.append(FileBufferStart + - SourceMgr.getFileOffset(LastComment->getBegin()), + Result.append(FileBufferStart + + SourceMgr.getFileOffset(LastComment->getBegin()), FileBufferStart + LastCommentEndDecomp.second + 1); return Result.c_str(); } @@ -555,7 +555,7 @@ ASTContext::getTypeInfo(const Type *T) { case Type::ConstantArrayWithoutExpr: case Type::ConstantArray: { const ConstantArrayType *CAT = cast(T); - + std::pair EltInfo = getTypeInfo(CAT->getElementType()); Width = EltInfo.first*CAT->getSize().getZExtValue(); Align = EltInfo.second; @@ -563,7 +563,7 @@ ASTContext::getTypeInfo(const Type *T) { } case Type::ExtVector: case Type::Vector: { - std::pair EltInfo = + std::pair EltInfo = getTypeInfo(cast(T)->getElementType()); Width = EltInfo.first*cast(T)->getNumElements(); Align = Width; @@ -689,7 +689,7 @@ ASTContext::getTypeInfo(const Type *T) { // If we ever want to support other ABIs this needs to be abstracted. QualType Pointee = cast(T)->getPointeeType(); - std::pair PtrDiffInfo = + std::pair PtrDiffInfo = getTypeInfo(getPointerDiffType()); Width = PtrDiffInfo.first; if (Pointee->isFunctionType()) @@ -700,7 +700,7 @@ ASTContext::getTypeInfo(const Type *T) { case Type::Complex: { // Complex types have the same alignment as their elements, but twice the // size. - std::pair EltInfo = + std::pair EltInfo = getTypeInfo(cast(T)->getElementType()); Width = EltInfo.first*2; Align = EltInfo.second; @@ -722,7 +722,7 @@ ASTContext::getTypeInfo(const Type *T) { Align = 1; break; } - + if (const EnumType *ET = dyn_cast(TT)) return getTypeInfo(ET->getDecl()->getIntegerType()); @@ -760,16 +760,16 @@ ASTContext::getTypeInfo(const Type *T) { case Type::QualifiedName: return getTypeInfo(cast(T)->getNamedType().getTypePtr()); - + case Type::TemplateSpecialization: - assert(getCanonicalType(T) != T && + assert(getCanonicalType(T) != T && "Cannot request the size of a dependent type"); // FIXME: this is likely to be wrong once we support template // aliases, since a template alias could refer to a typedef that // has an __aligned__ attribute on it. return getTypeInfo(getCanonicalType(T)); } - + assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); return std::make_pair(Width, Align); } @@ -829,7 +829,7 @@ void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD, E = PD->prop_end(); I != E; ++I) if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) Ivars.push_back(Ivar); - + // Also look into nested protocols. for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(), E = PD->protocol_end(); P != E; ++P) @@ -869,8 +869,7 @@ unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) { return count; } -unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) -{ +unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) { unsigned count = 0; for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(), E = OI->prop_end(); I != E; ++I) { @@ -944,7 +943,7 @@ ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, assert(!D->isForwardDecl() && "Invalid interface decl!"); // Look up this layout, if already laid out, return what we have. - ObjCContainerDecl *Key = + ObjCContainerDecl *Key = Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) return *Entry; @@ -962,10 +961,10 @@ ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, return getObjCLayout(D, 0); } - const ASTRecordLayout *NewEntry = + const ASTRecordLayout *NewEntry = ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl); ObjCLayouts[Key] = NewEntry; - + return *NewEntry; } @@ -992,10 +991,10 @@ const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { const ASTRecordLayout *Entry = ASTRecordLayouts[D]; if (Entry) return *Entry; - const ASTRecordLayout *NewEntry = + const ASTRecordLayout *NewEntry = ASTRecordLayoutBuilder::ComputeLayout(*this, D); ASTRecordLayouts[D] = NewEntry; - + return *NewEntry; } @@ -1013,7 +1012,7 @@ QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { unsigned CVRQuals = T.getCVRQualifiers(); QualType::GCAttrTypes GCAttr = QualType::GCNone; Type *TypeNode = T.getTypePtr(); - + if (ExtQualType *EQT = dyn_cast(TypeNode)) { // If this type already has an address space specified, it cannot get // another one. @@ -1022,7 +1021,7 @@ QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { GCAttr = EQT->getObjCGCAttr(); TypeNode = EQT->getBaseType(); } - + // Check if we've already instantiated this type. llvm::FoldingSetNodeID ID; ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); @@ -1035,7 +1034,7 @@ QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { QualType Canonical; if (!TypeNode->isCanonical()) { Canonical = getAddrSpaceQualType(CanT, AddressSpace); - + // Update InsertPos, the previous call could have invalidated it. ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; @@ -1052,7 +1051,7 @@ QualType ASTContext::getObjCGCQualType(QualType T, QualType CanT = getCanonicalType(T); if (CanT.getObjCGCAttr() == GCAttr) return T; - + if (T->isPointerType()) { QualType Pointee = T->getAs()->getPointeeType(); if (Pointee->isAnyPointerType()) { @@ -1065,7 +1064,7 @@ QualType ASTContext::getObjCGCQualType(QualType T, unsigned CVRQuals = T.getCVRQualifiers(); Type *TypeNode = T.getTypePtr(); unsigned AddressSpace = 0; - + if (ExtQualType *EQT = dyn_cast(TypeNode)) { // If this type already has an ObjCGC specified, it cannot get // another one. @@ -1074,14 +1073,14 @@ QualType ASTContext::getObjCGCQualType(QualType T, AddressSpace = EQT->getAddressSpace(); TypeNode = EQT->getBaseType(); } - + // Check if we've already instantiated an gc qual'd type of this type. llvm::FoldingSetNodeID ID; ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); void *InsertPos = 0; if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(EXTQy, CVRQuals); - + // If the base type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. // FIXME: Isn't this also not canonical if the base type is a array @@ -1089,7 +1088,7 @@ QualType ASTContext::getObjCGCQualType(QualType T, QualType Canonical; if (!T->isCanonical()) { Canonical = getObjCGCQualType(CanT, GCAttr); - + // Update InsertPos, the previous call could have invalidated it. ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; @@ -1117,10 +1116,10 @@ QualType ASTContext::getNoReturnType(QualType T) { ResultType = getBlockPointerType(ResultType); ResultType.setCVRQualifiers(T.getCVRQualifiers()); return qs.apply(ResultType, *this); - } + } if (!T->isFunctionType()) assert(0 && "can't noreturn qualify non-pointer to function or block type"); - + if (const FunctionNoProtoType *F = T->getAsFunctionNoProtoType()) { return getFunctionNoProtoType(F->getResultType(), true); } @@ -1138,17 +1137,17 @@ QualType ASTContext::getComplexType(QualType T) { // structure. llvm::FoldingSetNodeID ID; ComplexType::Profile(ID, T); - + void *InsertPos = 0; if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(CT, 0); - + // If the pointee type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!T->isCanonical()) { Canonical = getComplexType(getCanonicalType(T)); - + // Get the new insert position for the node we care about. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; @@ -1175,17 +1174,17 @@ QualType ASTContext::getPointerType(QualType T) { // structure. llvm::FoldingSetNodeID ID; PointerType::Profile(ID, T); - + void *InsertPos = 0; if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); - + // If the pointee type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!T->isCanonical()) { Canonical = getPointerType(getCanonicalType(T)); - + // Get the new insert position for the node we care about. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; @@ -1196,7 +1195,7 @@ QualType ASTContext::getPointerType(QualType T) { return QualType(New, 0); } -/// getBlockPointerType - Return the uniqued reference to the type for +/// getBlockPointerType - Return the uniqued reference to the type for /// a pointer to the specified block. QualType ASTContext::getBlockPointerType(QualType T) { assert(T->isFunctionType() && "block of function types only"); @@ -1204,18 +1203,18 @@ QualType ASTContext::getBlockPointerType(QualType T) { // structure. llvm::FoldingSetNodeID ID; BlockPointerType::Profile(ID, T); - + void *InsertPos = 0; if (BlockPointerType *PT = BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); - - // If the block pointee type isn't canonical, this won't be a canonical + + // If the block pointee type isn't canonical, this won't be a canonical // type either so fill in the canonical type field. QualType Canonical; if (!T->isCanonical()) { Canonical = getBlockPointerType(getCanonicalType(T)); - + // Get the new insert position for the node we care about. BlockPointerType *NewIP = BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); @@ -1291,8 +1290,7 @@ QualType ASTContext::getRValueReferenceType(QualType T) { /// getMemberPointerType - Return the uniqued reference to the type for a /// member pointer to the specified type, in the specified class. -QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) -{ +QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; @@ -1320,9 +1318,9 @@ QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) return QualType(New, 0); } -/// getConstantArrayType - Return the unique reference to the type for an +/// getConstantArrayType - Return the unique reference to the type for an /// array of the specified element type. -QualType ASTContext::getConstantArrayType(QualType EltTy, +QualType ASTContext::getConstantArrayType(QualType EltTy, const llvm::APInt &ArySizeIn, ArrayType::ArraySizeModifier ASM, unsigned EltTypeQuals) { @@ -1333,27 +1331,27 @@ QualType ASTContext::getConstantArrayType(QualType EltTy, // the target. llvm::APInt ArySize(ArySizeIn); ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); - + llvm::FoldingSetNodeID ID; ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); - + void *InsertPos = 0; - if (ConstantArrayType *ATP = + if (ConstantArrayType *ATP = ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(ATP, 0); - + // If the element type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!EltTy->isCanonical()) { - Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, + Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, ASM, EltTypeQuals); // Get the new insert position for the node we care about. - ConstantArrayType *NewIP = + ConstantArrayType *NewIP = ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; } - + ConstantArrayType *New = new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); ConstantArrayTypes.InsertNode(New, InsertPos); @@ -1437,11 +1435,11 @@ QualType ASTContext::getDependentSizedArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned EltTypeQuals, SourceRange Brackets) { - assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) && + assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) && "Size must be type- or value-dependent!"); llvm::FoldingSetNodeID ID; - DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM, + DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM, EltTypeQuals, NumElts); void *InsertPos = 0; @@ -1451,7 +1449,7 @@ QualType ASTContext::getDependentSizedArrayType(QualType EltTy, if (Canon) { // We already have a canonical version of this array type; use it as // the canonical type for a newly-built type. - New = new (*this,8) DependentSizedArrayType(*this, EltTy, + New = new (*this,8) DependentSizedArrayType(*this, EltTy, QualType(Canon, 0), NumElts, ASM, EltTypeQuals, Brackets); @@ -1468,10 +1466,10 @@ QualType ASTContext::getDependentSizedArrayType(QualType EltTy, SourceRange()); New = new (*this,8) DependentSizedArrayType(*this, EltTy, Canon, NumElts, ASM, EltTypeQuals, - Brackets); + Brackets); } } - + Types.push_back(New); return QualType(New, 0); } @@ -1483,7 +1481,7 @@ QualType ASTContext::getIncompleteArrayType(QualType EltTy, IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); void *InsertPos = 0; - if (IncompleteArrayType *ATP = + if (IncompleteArrayType *ATP = IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(ATP, 0); @@ -1514,13 +1512,13 @@ QualType ASTContext::getIncompleteArrayType(QualType EltTy, /// the specified element type and size. VectorType must be a built-in type. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { BuiltinType *baseType; - + baseType = dyn_cast(getCanonicalType(vecType).getTypePtr()); assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); - + // Check if we've already instantiated a vector of this type. llvm::FoldingSetNodeID ID; - VectorType::Profile(ID, vecType, NumElts, Type::Vector); + VectorType::Profile(ID, vecType, NumElts, Type::Vector); void *InsertPos = 0; if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(VTP, 0); @@ -1530,7 +1528,7 @@ QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { QualType Canonical; if (!vecType->isCanonical()) { Canonical = getVectorType(getCanonicalType(vecType), NumElts); - + // Get the new insert position for the node we care about. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; @@ -1545,13 +1543,13 @@ QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { /// the specified element type and size. VectorType must be a built-in type. QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { BuiltinType *baseType; - + baseType = dyn_cast(getCanonicalType(vecType).getTypePtr()); assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); - + // Check if we've already instantiated a vector of this type. llvm::FoldingSetNodeID ID; - VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); + VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); void *InsertPos = 0; if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(VTP, 0); @@ -1561,7 +1559,7 @@ QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { QualType Canonical; if (!vecType->isCanonical()) { Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); - + // Get the new insert position for the node we care about. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; @@ -1572,13 +1570,13 @@ QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { return QualType(New, 0); } -QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, +QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, Expr *SizeExpr, SourceLocation AttrLoc) { llvm::FoldingSetNodeID ID; - DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), + DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), SizeExpr); - + void *InsertPos = 0; DependentSizedExtVectorType *Canon = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); @@ -1592,8 +1590,8 @@ QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, } else { QualType CanonVecTy = getCanonicalType(vecType); if (CanonVecTy == vecType) { - New = new (*this,8) DependentSizedExtVectorType(*this, vecType, - QualType(), SizeExpr, + New = new (*this,8) DependentSizedExtVectorType(*this, vecType, + QualType(), SizeExpr, AttrLoc); DependentSizedExtVectorTypes.InsertNode(New, InsertPos); } else { @@ -1603,7 +1601,7 @@ QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, SizeExpr, AttrLoc); } } - + Types.push_back(New); return QualType(New, 0); } @@ -1615,22 +1613,22 @@ QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) { // structure. llvm::FoldingSetNodeID ID; FunctionNoProtoType::Profile(ID, ResultTy, NoReturn); - + void *InsertPos = 0; - if (FunctionNoProtoType *FT = + if (FunctionNoProtoType *FT = FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(FT, 0); - + QualType Canonical; if (!ResultTy->isCanonical()) { Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn); - + // Get the new insert position for the node we care about. FunctionNoProtoType *NewIP = FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; } - + FunctionNoProtoType *New = new (*this,8) FunctionNoProtoType(ResultTy, Canonical, NoReturn); Types.push_back(New); @@ -1653,7 +1651,7 @@ QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, NumExs, ExArray, NoReturn); void *InsertPos = 0; - if (FunctionProtoType *FTP = + if (FunctionProtoType *FTP = FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(FTP, 0); @@ -1688,7 +1686,7 @@ QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, // FunctionProtoType objects are allocated with extra bytes after them // for two variable size arrays (for parameter and exception types) at the // end of them. - FunctionProtoType *FTP = + FunctionProtoType *FTP = (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + NumArgs*sizeof(QualType) + NumExs*sizeof(QualType), 8); @@ -1705,7 +1703,7 @@ QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) { assert(Decl && "Passed null for Decl param"); if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); - + if (TypedefDecl *Typedef = dyn_cast(Decl)) return getTypedefType(Typedef); else if (isa(Decl)) { @@ -1735,7 +1733,7 @@ QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) { /// specified typename decl. QualType ASTContext::getTypedefType(TypedefDecl *Decl) { if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); - + QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical); Types.push_back(Decl->TypeForDecl); @@ -1743,20 +1741,20 @@ QualType ASTContext::getTypedefType(TypedefDecl *Decl) { } /// \brief Retrieve the template type parameter type for a template -/// parameter or parameter pack with the given depth, index, and (optionally) +/// parameter or parameter pack with the given depth, index, and (optionally) /// name. -QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, +QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, IdentifierInfo *Name) { llvm::FoldingSetNodeID ID; TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name); void *InsertPos = 0; - TemplateTypeParmType *TypeParm + TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); if (TypeParm) return QualType(TypeParm, 0); - + if (Name) { QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack, @@ -1770,7 +1768,7 @@ QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, return QualType(TypeParm, 0); } -QualType +QualType ASTContext::getTemplateSpecializationType(TemplateName Template, const TemplateArgument *Args, unsigned NumArgs, @@ -1788,65 +1786,65 @@ ASTContext::getTemplateSpecializationType(TemplateName Template, // Determine whether this canonical template specialization type already // exists. llvm::FoldingSetNodeID ID; - TemplateSpecializationType::Profile(ID, CanonTemplate, + TemplateSpecializationType::Profile(ID, CanonTemplate, CanonArgs.data(), NumArgs, *this); void *InsertPos = 0; TemplateSpecializationType *Spec = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); - + if (!Spec) { // Allocate a new canonical template specialization type. - void *Mem = Allocate((sizeof(TemplateSpecializationType) + + void *Mem = Allocate((sizeof(TemplateSpecializationType) + sizeof(TemplateArgument) * NumArgs), 8); - Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, + Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, CanonArgs.data(), NumArgs, Canon); Types.push_back(Spec); - TemplateSpecializationTypes.InsertNode(Spec, InsertPos); + TemplateSpecializationTypes.InsertNode(Spec, InsertPos); } - + if (Canon.isNull()) Canon = QualType(Spec, 0); - assert(Canon->isDependentType() && + assert(Canon->isDependentType() && "Non-dependent template-id type must have a canonical type"); } // Allocate the (non-canonical) template specialization type, but don't // try to unique it: these types typically have location information that // we don't unique and don't want to lose. - void *Mem = Allocate((sizeof(TemplateSpecializationType) + + void *Mem = Allocate((sizeof(TemplateSpecializationType) + sizeof(TemplateArgument) * NumArgs), 8); - TemplateSpecializationType *Spec - = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs, + TemplateSpecializationType *Spec + = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs, Canon); - + Types.push_back(Spec); - return QualType(Spec, 0); + return QualType(Spec, 0); } -QualType +QualType ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType) { llvm::FoldingSetNodeID ID; QualifiedNameType::Profile(ID, NNS, NamedType); void *InsertPos = 0; - QualifiedNameType *T + QualifiedNameType *T = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); - T = new (*this) QualifiedNameType(NNS, NamedType, + T = new (*this) QualifiedNameType(NNS, NamedType, getCanonicalType(NamedType)); Types.push_back(T); QualifiedNameTypes.InsertNode(T, InsertPos); return QualType(T, 0); } -QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, +QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon) { assert(NNS->isDependent() && "nested-name-specifier must be dependent"); @@ -1861,7 +1859,7 @@ QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, TypenameType::Profile(ID, NNS, Name); void *InsertPos = 0; - TypenameType *T + TypenameType *T = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); @@ -1869,11 +1867,11 @@ QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, T = new (*this) TypenameType(NNS, Name, Canon); Types.push_back(T); TypenameTypes.InsertNode(T, InsertPos); - return QualType(T, 0); + return QualType(T, 0); } -QualType -ASTContext::getTypenameType(NestedNameSpecifier *NNS, +QualType +ASTContext::getTypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *TemplateId, QualType Canon) { assert(NNS->isDependent() && "nested-name-specifier must be dependent"); @@ -1894,7 +1892,7 @@ ASTContext::getTypenameType(NestedNameSpecifier *NNS, TypenameType::Profile(ID, NNS, TemplateId); void *InsertPos = 0; - TypenameType *T + TypenameType *T = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); @@ -1902,7 +1900,7 @@ ASTContext::getTypenameType(NestedNameSpecifier *NNS, T = new (*this) TypenameType(NNS, TemplateId, Canon); Types.push_back(T); TypenameTypes.InsertNode(T, InsertPos); - return QualType(T, 0); + return QualType(T, 0); } QualType @@ -1910,7 +1908,7 @@ ASTContext::getElaboratedType(QualType UnderlyingType, ElaboratedType::TagKind Tag) { llvm::FoldingSetNodeID ID; ElaboratedType::Profile(ID, UnderlyingType, Tag); - + void *InsertPos = 0; ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) @@ -1934,7 +1932,7 @@ static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, unsigned &NumProtocols) { ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; - + // Sort protocols, keyed by name. std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); @@ -1946,7 +1944,7 @@ static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for /// the given interface decl and the conforming protocol list. QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT, - ObjCProtocolDecl **Protocols, + ObjCProtocolDecl **Protocols, unsigned NumProtocols) { // Sort the protocol list alphabetically to canonicalize it. if (NumProtocols) @@ -1963,7 +1961,7 @@ QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT, // No Match; ObjCObjectPointerType *QType = new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols); - + Types.push_back(QType); ObjCObjectPointerTypes.InsertNode(QType, InsertPos); return QualType(QType, 0); @@ -1973,21 +1971,21 @@ QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT, /// specified ObjC interface decl. The list of protocols is optional. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCProtocolDecl **Protocols, unsigned NumProtocols) { - if (NumProtocols) + if (NumProtocols) // Sort the protocol list alphabetically to canonicalize it. SortAndUniqueProtocols(Protocols, NumProtocols); - + llvm::FoldingSetNodeID ID; ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); - + void *InsertPos = 0; if (ObjCInterfaceType *QT = ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(QT, 0); - + // No Match; ObjCInterfaceType *QType = - new (*this,8) ObjCInterfaceType(const_cast(Decl), + new (*this,8) ObjCInterfaceType(const_cast(Decl), Protocols, NumProtocols); Types.push_back(QType); ObjCInterfaceTypes.InsertNode(QType, InsertPos); @@ -1997,21 +1995,21 @@ QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, /// getTypeOfExprType - Unlike many "get" functions, we can't unique /// TypeOfExprType AST's (since expression's are never shared). For example, /// multiple declarations that refer to "typeof(x)" all contain different -/// DeclRefExpr's. This doesn't effect the type checker, since it operates +/// DeclRefExpr's. This doesn't effect the type checker, since it operates /// on canonical type's (which are always unique). QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { TypeOfExprType *toe; if (tofExpr->isTypeDependent()) { llvm::FoldingSetNodeID ID; DependentTypeOfExprType::Profile(ID, *this, tofExpr); - + void *InsertPos = 0; DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); if (Canon) { // We already have a "canonical" version of an identical, dependent // typeof(expr) type. Use that as our canonical type. - toe = new (*this, 8) TypeOfExprType(tofExpr, + toe = new (*this, 8) TypeOfExprType(tofExpr, QualType((TypeOfExprType*)Canon, 0)); } else { @@ -2031,7 +2029,7 @@ QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { /// getTypeOfType - Unlike many "get" functions, we don't unique /// TypeOfType AST's. The only motivation to unique these nodes would be /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be -/// an issue. This doesn't effect the type checker, since it operates +/// an issue. This doesn't effect the type checker, since it operates /// on canonical type's (which are always unique). QualType ASTContext::getTypeOfType(QualType tofType) { QualType Canonical = getCanonicalType(tofType); @@ -2045,7 +2043,7 @@ QualType ASTContext::getTypeOfType(QualType tofType) { static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { if (e->isTypeDependent()) return Context.DependentTy; - + // If e is an id expression or a class member access, decltype(e) is defined // as the type of the entity named by e. if (const DeclRefExpr *DRE = dyn_cast(e)) { @@ -2061,28 +2059,28 @@ static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { // return type of that function. if (const CallExpr *CE = dyn_cast(e->IgnoreParens())) return CE->getCallReturnType(); - + QualType T = e->getType(); - - // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is + + // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is // defined as T&, otherwise decltype(e) is defined as T. if (e->isLvalue(Context) == Expr::LV_Valid) T = Context.getLValueReferenceType(T); - + return T; } /// getDecltypeType - Unlike many "get" functions, we don't unique /// DecltypeType AST's. The only motivation to unique these nodes would be /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be -/// an issue. This doesn't effect the type checker, since it operates +/// an issue. This doesn't effect the type checker, since it operates /// on canonical type's (which are always unique). QualType ASTContext::getDecltypeType(Expr *e) { DecltypeType *dt; if (e->isTypeDependent()) { llvm::FoldingSetNodeID ID; DependentDecltypeType::Profile(ID, *this, e); - + void *InsertPos = 0; DependentDecltypeType *Canon = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); @@ -2100,7 +2098,7 @@ QualType ASTContext::getDecltypeType(Expr *e) { } } else { QualType T = getDecltypeForExpr(e, *this); - dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T)); + dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T)); } Types.push_back(dt); return QualType(dt, 0); @@ -2115,9 +2113,9 @@ QualType ASTContext::getTagDeclType(const TagDecl *Decl) { return getTypeDeclType(const_cast(Decl)); } -/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result -/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and -/// needs to agree with the definition in . +/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result +/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and +/// needs to agree with the definition in . QualType ASTContext::getSizeType() const { return getFromTargetType(Target.getSizeType()); } @@ -2154,10 +2152,10 @@ QualType ASTContext::getPointerDiffType() const { /// for exact equality with a simple pointer comparison. CanQualType ASTContext::getCanonicalType(QualType T) { QualType CanType = T.getTypePtr()->getCanonicalTypeInternal(); - + // If the result has type qualifiers, make sure to canonicalize them as well. unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers(); - if (TypeQuals == 0) + if (TypeQuals == 0) return CanQualType::CreateUnsafe(CanType); // If the type qualifiers are on an array type, get the canonical type of the @@ -2165,12 +2163,12 @@ CanQualType ASTContext::getCanonicalType(QualType T) { ArrayType *AT = dyn_cast(CanType); if (!AT) return CanQualType::CreateUnsafe(CanType.getQualifiedType(TypeQuals)); - + // Get the canonical version of the element with the extra qualifiers on it. // This can recursively sink qualifiers through multiple levels of arrays. QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals); NewEltTy = getCanonicalType(NewEltTy); - + if (ConstantArrayType *CAT = dyn_cast(AT)) return CanQualType::CreateUnsafe( getConstantArrayType(NewEltTy, CAT->getSize(), @@ -2180,7 +2178,7 @@ CanQualType ASTContext::getCanonicalType(QualType T) { return CanQualType::CreateUnsafe( getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), IAT->getIndexTypeQualifier())); - + if (DependentSizedArrayType *DSAT = dyn_cast(AT)) return CanQualType::CreateUnsafe( getDependentSizedArrayType(NewEltTy, @@ -2205,7 +2203,7 @@ TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { if (TemplateDecl *Template = Name.getAsTemplateDecl()) return TemplateName(cast(Template->getCanonicalDecl())); - // If this template name refers to a set of overloaded function templates, + // If this template name refers to a set of overloaded function templates, /// the canonical template name merely stores the set of function templates. if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) { OverloadedFunctionDecl *CanonOvl = 0; @@ -2215,55 +2213,55 @@ TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { Decl *Canon = F->get()->getCanonicalDecl(); if (CanonOvl || Canon != F->get()) { if (!CanonOvl) - CanonOvl = OverloadedFunctionDecl::Create(*this, - Ovl->getDeclContext(), + CanonOvl = OverloadedFunctionDecl::Create(*this, + Ovl->getDeclContext(), Ovl->getDeclName()); - + CanonOvl->addOverload( AnyFunctionDecl::getFromNamedDecl(cast(Canon))); } } - + return TemplateName(CanonOvl? CanonOvl : Ovl); } - + DependentTemplateName *DTN = Name.getAsDependentTemplateName(); assert(DTN && "Non-dependent template names must refer to template decls."); return DTN->CanonicalTemplateName; } -TemplateArgument +TemplateArgument ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) { switch (Arg.getKind()) { case TemplateArgument::Null: return Arg; - + case TemplateArgument::Expression: // FIXME: Build canonical expression? return Arg; - + case TemplateArgument::Declaration: return TemplateArgument(SourceLocation(), Arg.getAsDecl()->getCanonicalDecl()); - + case TemplateArgument::Integral: return TemplateArgument(SourceLocation(), *Arg.getAsIntegral(), getCanonicalType(Arg.getIntegralType())); - + case TemplateArgument::Type: return TemplateArgument(SourceLocation(), getCanonicalType(Arg.getAsType())); - + case TemplateArgument::Pack: { // FIXME: Allocate in ASTContext TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()]; unsigned Idx = 0; - for (TemplateArgument::pack_iterator A = Arg.pack_begin(), + for (TemplateArgument::pack_iterator A = Arg.pack_begin(), AEnd = Arg.pack_end(); A != AEnd; (void)++A, ++Idx) CanonArgs[Idx] = getCanonicalTemplateArgument(*A); - + TemplateArgument Result; Result.setArgumentPack(CanonArgs, Arg.pack_size(), false); return Result; @@ -2277,13 +2275,13 @@ ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) { NestedNameSpecifier * ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { - if (!NNS) + if (!NNS) return 0; switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: // Canonicalize the prefix but keep the identifier the same. - return NestedNameSpecifier::Create(*this, + return NestedNameSpecifier::Create(*this, getCanonicalNestedNameSpecifier(NNS->getPrefix()), NNS->getAsIdentifier()); @@ -2295,8 +2293,8 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); - return NestedNameSpecifier::Create(*this, 0, - NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, + return NestedNameSpecifier::Create(*this, 0, + NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, T.getTypePtr()); } @@ -2317,27 +2315,27 @@ const ArrayType *ASTContext::getAsArrayType(QualType T) { if (const ArrayType *AT = dyn_cast(T)) return AT; } - + // Handle the common negative case fast, ignoring CVR qualifiers. QualType CType = T->getCanonicalTypeInternal(); - + // Make sure to look through type qualifiers (like ExtQuals) for the negative // test. if (!isa(CType) && !isa(CType.getUnqualifiedType())) return 0; - + // Apply any CVR qualifiers from the array type to the element type. This // implements C99 6.7.3p8: "If the specification of an array type includes // any type qualifiers, the element type is so qualified, not the array type." - + // If we get here, we either have type qualifiers on the type, or we have // sugar such as a typedef in the way. If we have type qualifiers on the type // we must propagate them down into the element type. unsigned CVRQuals = T.getCVRQualifiers(); unsigned AddrSpace = 0; Type *Ty = T.getTypePtr(); - + // Rip through ExtQualType's and typedefs to get to a concrete type. while (1) { if (const ExtQualType *EXTQT = dyn_cast(Ty)) { @@ -2351,12 +2349,12 @@ const ArrayType *ASTContext::getAsArrayType(QualType T) { Ty = T.getTypePtr(); } } - + // If we have a simple case, just return now. const ArrayType *ATy = dyn_cast(Ty); if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0)) return ATy; - + // Otherwise, we have an array and we have qualifiers on it. Push the // qualifiers into the array element type and return a new array type. // Get the canonical version of the element with the extra qualifiers on it. @@ -2365,7 +2363,7 @@ const ArrayType *ASTContext::getAsArrayType(QualType T) { if (AddrSpace) NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace); NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals); - + if (const ConstantArrayType *CAT = dyn_cast(ATy)) return cast(getConstantArrayType(NewEltTy, CAT->getSize(), CAT->getSizeModifier(), @@ -2375,16 +2373,16 @@ const ArrayType *ASTContext::getAsArrayType(QualType T) { IAT->getSizeModifier(), IAT->getIndexTypeQualifier())); - if (const DependentSizedArrayType *DSAT + if (const DependentSizedArrayType *DSAT = dyn_cast(ATy)) return cast( - getDependentSizedArrayType(NewEltTy, + getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr() ? DSAT->getSizeExpr()->Retain() : 0, DSAT->getSizeModifier(), DSAT->getIndexTypeQualifier(), DSAT->getBracketsRange())); - + const VariableArrayType *VAT = cast(ATy); return cast(getVariableArrayType(NewEltTy, VAT->getSizeExpr() ? @@ -2408,7 +2406,7 @@ QualType ASTContext::getArrayDecayedType(QualType Ty) { // (C99 6.7.3p8). const ArrayType *PrettyArrayType = getAsArrayType(Ty); assert(PrettyArrayType && "Not an array type!"); - + QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); // int x[restrict 4] -> int *restrict @@ -2429,15 +2427,15 @@ QualType ASTContext::getBaseElementType(QualType QT) { QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) { QualType ElemTy = VAT->getElementType(); - + if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy)) return getBaseElementType(VAT); - + return ElemTy; } /// getConstantArrayElementCount - Returns number of constant array elements. -uint64_t +uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { uint64_t ElementCount = 1; do { @@ -2462,8 +2460,8 @@ static FloatingRank getFloatingRank(QualType T) { } } -/// getFloatingTypeOfSizeWithinDomain - Returns a real floating -/// point or a complex type (based on typeDomain/typeSize). +/// getFloatingTypeOfSizeWithinDomain - Returns a real floating +/// point or a complex type (based on typeDomain/typeSize). /// 'typeDomain' is a real floating point or complex type. /// 'typeSize' is a real floating point or complex type. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, @@ -2490,11 +2488,11 @@ QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, /// getFloatingTypeOrder - Compare the rank of the two specified floating /// point types, ignoring the domain of the type (i.e. 'double' == /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If -/// LHS < RHS, return -1. +/// LHS < RHS, return -1. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { FloatingRank LHSR = getFloatingRank(LHS); FloatingRank RHSR = getFloatingRank(RHS); - + if (LHSR == RHSR) return 0; if (LHSR > RHSR) @@ -2597,77 +2595,77 @@ QualType ASTContext::getPromotedIntegerType(QualType Promotable) { return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; } -/// getIntegerTypeOrder - Returns the highest ranked integer type: +/// getIntegerTypeOrder - Returns the highest ranked integer type: /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If -/// LHS < RHS, return -1. +/// LHS < RHS, return -1. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { Type *LHSC = getCanonicalType(LHS).getTypePtr(); Type *RHSC = getCanonicalType(RHS).getTypePtr(); if (LHSC == RHSC) return 0; - + bool LHSUnsigned = LHSC->isUnsignedIntegerType(); bool RHSUnsigned = RHSC->isUnsignedIntegerType(); - + unsigned LHSRank = getIntegerRank(LHSC); unsigned RHSRank = getIntegerRank(RHSC); - + if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. if (LHSRank == RHSRank) return 0; return LHSRank > RHSRank ? 1 : -1; } - + // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. if (LHSUnsigned) { // If the unsigned [LHS] type is larger, return it. if (LHSRank >= RHSRank) return 1; - + // If the signed type can represent all values of the unsigned type, it // wins. Because we are dealing with 2's complement and types that are - // powers of two larger than each other, this is always safe. + // powers of two larger than each other, this is always safe. return -1; } // If the unsigned [RHS] type is larger, return it. if (RHSRank >= LHSRank) return -1; - + // If the signed type can represent all values of the unsigned type, it // wins. Because we are dealing with 2's complement and types that are - // powers of two larger than each other, this is always safe. + // powers of two larger than each other, this is always safe. return 1; } -// getCFConstantStringType - Return the type used for constant CFStrings. +// getCFConstantStringType - Return the type used for constant CFStrings. QualType ASTContext::getCFConstantStringType() { if (!CFConstantStringTypeDecl) { - CFConstantStringTypeDecl = - RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), + CFConstantStringTypeDecl = + RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), &Idents.get("NSConstantString")); QualType FieldTypes[4]; - + // const int *isa; - FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); + FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); // int flags; FieldTypes[1] = IntTy; // const char *str; - FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); + FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); // long length; - FieldTypes[3] = LongTy; - + FieldTypes[3] = LongTy; + // Create fields for (unsigned i = 0; i < 4; ++i) { - FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, + FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, SourceLocation(), 0, FieldTypes[i], /*DInfo=*/0, - /*BitWidth=*/0, + /*BitWidth=*/0, /*Mutable=*/false); CFConstantStringTypeDecl->addDecl(Field); } CFConstantStringTypeDecl->completeDefinition(*this); } - + return getTagDeclType(CFConstantStringTypeDecl); } @@ -2677,13 +2675,12 @@ void ASTContext::setCFConstantStringType(QualType T) { CFConstantStringTypeDecl = Rec->getDecl(); } -QualType ASTContext::getObjCFastEnumerationStateType() -{ +QualType ASTContext::getObjCFastEnumerationStateType() { if (!ObjCFastEnumerationStateTypeDecl) { ObjCFastEnumerationStateTypeDecl = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), &Idents.get("__objcFastEnumerationState")); - + QualType FieldTypes[] = { UnsignedLongTy, getPointerType(ObjCIdTypedefType), @@ -2691,20 +2688,20 @@ QualType ASTContext::getObjCFastEnumerationStateType() getConstantArrayType(UnsignedLongTy, llvm::APInt(32, 5), ArrayType::Normal, 0) }; - + for (size_t i = 0; i < 4; ++i) { - FieldDecl *Field = FieldDecl::Create(*this, - ObjCFastEnumerationStateTypeDecl, - SourceLocation(), 0, + FieldDecl *Field = FieldDecl::Create(*this, + ObjCFastEnumerationStateTypeDecl, + SourceLocation(), 0, FieldTypes[i], /*DInfo=*/0, - /*BitWidth=*/0, + /*BitWidth=*/0, /*Mutable=*/false); ObjCFastEnumerationStateTypeDecl->addDecl(Field); } - + ObjCFastEnumerationStateTypeDecl->completeDefinition(*this); } - + return getTagDeclType(ObjCFastEnumerationStateTypeDecl); } @@ -2720,7 +2717,7 @@ static bool isTypeTypedefedAsBOOL(QualType T) { if (const TypedefType *TT = dyn_cast(T)) if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) return II->isStr("BOOL"); - + return false; } @@ -2728,7 +2725,7 @@ static bool isTypeTypedefedAsBOOL(QualType T) { /// purpose. int ASTContext::getObjCEncodingTypeSize(QualType type) { uint64_t sz = getTypeSize(type); - + // Make all integer and enum types at least as large as an int if (sz > 0 && type->isIntegralType()) sz = std::max(sz, getTypeSize(IntTy)); @@ -2740,7 +2737,7 @@ int ASTContext::getObjCEncodingTypeSize(QualType type) { /// getObjCEncodingForMethodDecl - Return the encoded type for this method /// declaration. -void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, +void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string& S) { // FIXME: This is not very efficient. // Encode type qualifer, 'in', 'inout', etc. for the return type. @@ -2765,13 +2762,13 @@ void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, S += llvm::utostr(ParmOffset); S += "@0:"; S += llvm::utostr(PtrSize); - + // Argument types. ParmOffset = 2 * PtrSize; for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), E = Decl->param_end(); PI != E; ++PI) { ParmVarDecl *PVDecl = *PI; - QualType PType = PVDecl->getOriginalType(); + QualType PType = PVDecl->getOriginalType(); if (const ArrayType *AT = dyn_cast(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of @@ -2793,11 +2790,11 @@ void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, /// property declaration. If non-NULL, Container must be either an /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be /// NULL when getting encodings for protocol properties. -/// Property attributes are stored as a comma-delimited C string. The simple -/// attributes readonly and bycopy are encoded as single characters. The -/// parametrized attributes, getter=name, setter=name, and ivar=name, are -/// encoded as single characters, followed by an identifier. Property types -/// are also encoded as a parametrized attribute. The characters used to encode +/// Property attributes are stored as a comma-delimited C string. The simple +/// attributes readonly and bycopy are encoded as single characters. The +/// parametrized attributes, getter=name, setter=name, and ivar=name, are +/// encoded as single characters, followed by an identifier. Property types +/// are also encoded as a parametrized attribute. The characters used to encode /// these attributes are defined by the following enumeration: /// @code /// enum PropertyAttributes { @@ -2814,7 +2811,7 @@ void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, /// kPropertyNonAtomic = 'N' // property non-atomic /// }; /// @endcode -void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, +void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container, std::string& S) { // Collect information from the property implementation decl(s). @@ -2823,7 +2820,7 @@ void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, // FIXME: Duplicated code due to poor abstraction. if (Container) { - if (const ObjCCategoryImplDecl *CID = + if (const ObjCCategoryImplDecl *CID = dyn_cast(Container)) { for (ObjCCategoryImplDecl::propimpl_iterator i = CID->propimpl_begin(), e = CID->propimpl_end(); @@ -2850,7 +2847,7 @@ void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, SynthesizePID = PID; } } - } + } } } @@ -2860,7 +2857,7 @@ void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, // Encode result type. // GCC has some special rules regarding encoding of properties which // closely resembles encoding of ivars. - getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, + getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, true /* outermost type */, true /* encoding for property */); @@ -2870,7 +2867,7 @@ void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, switch (PD->getSetterKind()) { case ObjCPropertyDecl::Assign: break; case ObjCPropertyDecl::Copy: S += ",C"; break; - case ObjCPropertyDecl::Retain: S += ",&"; break; + case ObjCPropertyDecl::Retain: S += ",&"; break; } } @@ -2881,7 +2878,7 @@ void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) S += ",N"; - + if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { S += ",G"; S += PD->getGetterName().getAsString(); @@ -2902,8 +2899,8 @@ void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, } /// getLegacyIntegralTypeEncoding - -/// Another legacy compatibility encoding: 32-bit longs are encoded as -/// 'l' or 'L' , but not always. For typedefs, we need to use +/// Another legacy compatibility encoding: 32-bit longs are encoded as +/// 'l' or 'L' , but not always. For typedefs, we need to use /// 'i' or 'I' instead if encoding a struct field, or a pointer! /// void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { @@ -2912,7 +2909,7 @@ void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { if (BT->getKind() == BuiltinType::ULong && ((const_cast(this))->getIntWidth(PointeeTy) == 32)) PointeeTy = UnsignedIntTy; - else + else if (BT->getKind() == BuiltinType::Long && ((const_cast(this))->getIntWidth(PointeeTy) == 32)) PointeeTy = IntTy; @@ -2926,11 +2923,11 @@ void ASTContext::getObjCEncodingForType(QualType T, std::string& S, // directly pointed to, and expanding embedded structures. Note that // these rules are sufficient to prevent recursive encoding of the // same type. - getObjCEncodingForTypeImpl(T, S, true, true, Field, + getObjCEncodingForTypeImpl(T, S, true, true, Field, true /* outermost type */); } -static void EncodeBitField(const ASTContext *Context, std::string& S, +static void EncodeBitField(const ASTContext *Context, std::string& S, const FieldDecl *FD) { const Expr *E = FD->getBitWidth(); assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); @@ -2951,16 +2948,16 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, return EncodeBitField(this, S, FD); char encoding; switch (BT->getKind()) { - default: assert(0 && "Unhandled builtin type kind"); + default: assert(0 && "Unhandled builtin type kind"); case BuiltinType::Void: encoding = 'v'; break; case BuiltinType::Bool: encoding = 'B'; break; case BuiltinType::Char_U: case BuiltinType::UChar: encoding = 'C'; break; case BuiltinType::UShort: encoding = 'S'; break; case BuiltinType::UInt: encoding = 'I'; break; - case BuiltinType::ULong: - encoding = - (const_cast(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; + case BuiltinType::ULong: + encoding = + (const_cast(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; break; case BuiltinType::UInt128: encoding = 'T'; break; case BuiltinType::ULongLong: encoding = 'Q'; break; @@ -2968,9 +2965,9 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, case BuiltinType::SChar: encoding = 'c'; break; case BuiltinType::Short: encoding = 's'; break; case BuiltinType::Int: encoding = 'i'; break; - case BuiltinType::Long: - encoding = - (const_cast(this))->getIntWidth(T) == 32 ? 'l' : 'q'; + case BuiltinType::Long: + encoding = + (const_cast(this))->getIntWidth(T) == 32 ? 'l' : 'q'; break; case BuiltinType::LongLong: encoding = 'q'; break; case BuiltinType::Int128: encoding = 't'; break; @@ -2978,25 +2975,25 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, case BuiltinType::Double: encoding = 'd'; break; case BuiltinType::LongDouble: encoding = 'd'; break; } - + S += encoding; return; } - + if (const ComplexType *CT = T->getAsComplexType()) { S += 'j'; - getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, + getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, false); return; } - + if (const PointerType *PT = T->getAs()) { QualType PointeeTy = PT->getPointeeType(); bool isReadOnly = false; // For historical/compatibility reasons, the read-only qualifier of the // pointee gets emitted _before_ the '^'. The read-only qualifier of // the pointer itself gets ignored, _unless_ we are looking at a typedef! - // Also, do not emit the 'r' for anything but the outermost type! + // Also, do not emit the 'r' for anything but the outermost type! if (isa(T.getTypePtr())) { if (OutermostType && T.isConstQualified()) { isReadOnly = true; @@ -3026,7 +3023,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += ':'; return; } - + if (PointeeTy->isCharType()) { // char pointer types should be encoded as '*' unless it is a // type that has been typedef'd to 'BOOL'. @@ -3050,11 +3047,11 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += '^'; getLegacyIntegralTypeEncoding(PointeeTy); - getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, + getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, NULL); return; } - + if (const ArrayType *AT = // Ignore type qualifiers etc. dyn_cast(T->getCanonicalTypeInternal())) { @@ -3062,11 +3059,11 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, // Incomplete arrays are encoded as a pointer to the array element. S += '^'; - getObjCEncodingForTypeImpl(AT->getElementType(), S, + getObjCEncodingForTypeImpl(AT->getElementType(), S, false, ExpandStructures, FD); } else { S += '['; - + if (const ConstantArrayType *CAT = dyn_cast(AT)) S += llvm::utostr(CAT->getSize().getZExtValue()); else { @@ -3074,19 +3071,19 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, assert(isa(AT) && "Unknown array type!"); S += '0'; } - - getObjCEncodingForTypeImpl(AT->getElementType(), S, + + getObjCEncodingForTypeImpl(AT->getElementType(), S, false, ExpandStructures, FD); S += ']'; } return; } - + if (T->getAsFunctionType()) { S += '?'; return; } - + if (const RecordType *RTy = T->getAs()) { RecordDecl *RDecl = RTy->getDecl(); S += RDecl->isUnion() ? '(' : '{'; @@ -3106,15 +3103,15 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += Field->getNameAsString(); S += '"'; } - + // Special case bit-fields. if (Field->isBitField()) { - getObjCEncodingForTypeImpl(Field->getType(), S, false, true, + getObjCEncodingForTypeImpl(Field->getType(), S, false, true, (*Field)); } else { QualType qt = Field->getType(); getLegacyIntegralTypeEncoding(qt); - getObjCEncodingForTypeImpl(qt, S, false, true, + getObjCEncodingForTypeImpl(qt, S, false, true, FD); } } @@ -3122,7 +3119,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += RDecl->isUnion() ? ')' : '}'; return; } - + if (T->isEnumeralType()) { if (FD && FD->isBitField()) EncodeBitField(this, S, FD); @@ -3130,12 +3127,12 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += 'i'; return; } - + if (T->isBlockPointerType()) { S += "@?"; // Unlike a pointer-to-function, which is "^?". return; } - + if (T->isObjCInterfaceType()) { // @encode(class_name) ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl(); @@ -3147,29 +3144,29 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, CollectObjCIvars(OI, RecFields); for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { if (RecFields[i]->isBitField()) - getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, + getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, RecFields[i]); else - getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, + getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, FD); } S += '}'; return; } - + if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) { if (OPT->isObjCIdType()) { S += '@'; return; } - + if (OPT->isObjCClassType()) { S += '#'; return; } - + if (OPT->isObjCQualifiedIdType()) { - getObjCEncodingForTypeImpl(getObjCIdType(), S, + getObjCEncodingForTypeImpl(getObjCIdType(), S, ExpandPointedToStructures, ExpandStructures, FD); if (FD || EncodingProperty) { @@ -3186,16 +3183,16 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, } return; } - + QualType PointeeTy = OPT->getPointeeType(); if (!EncodingProperty && isa(PointeeTy.getTypePtr())) { // Another historical/compatibility reason. - // We encode the underlying type which comes out as + // We encode the underlying type which comes out as // {...}; S += '^'; - getObjCEncodingForTypeImpl(PointeeTy, S, - false, ExpandPointedToStructures, + getObjCEncodingForTypeImpl(PointeeTy, S, + false, ExpandPointedToStructures, NULL); return; } @@ -3209,16 +3206,16 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += '<'; S += (*I)->getNameAsString(); S += '>'; - } + } S += '"'; } return; } - + assert(0 && "@encode for type not implemented!"); } -void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, +void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string& S) const { if (QT & Decl::OBJC_TQ_In) S += 'n'; @@ -3236,7 +3233,7 @@ void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, void ASTContext::setBuiltinVaListType(QualType T) { assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); - + BuiltinVaListType = T; } @@ -3271,15 +3268,15 @@ void ASTContext::setObjCClassType(QualType T) { } void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { - assert(ObjCConstantStringType.isNull() && + assert(ObjCConstantStringType.isNull() && "'NSConstantString' type already set!"); - + ObjCConstantStringType = getObjCInterfaceType(Decl); } /// \brief Retrieve the template name that represents a qualified /// template name such as \c std::vector. -TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, +TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) { llvm::FoldingSetNodeID ID; @@ -3298,12 +3295,12 @@ TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, /// \brief Retrieve the template name that represents a qualified /// template name such as \c std::vector. -TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, +TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, OverloadedFunctionDecl *Template) { llvm::FoldingSetNodeID ID; QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); - + void *InsertPos = 0; QualifiedTemplateName *QTN = QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); @@ -3311,15 +3308,15 @@ TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); QualifiedTemplateNames.InsertNode(QTN, InsertPos); } - + return TemplateName(QTN); } /// \brief Retrieve the template name that represents a dependent /// template name such as \c MetaFun::template apply. -TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, +TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) { - assert((!NNS || NNS->isDependent()) && + assert((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"); llvm::FoldingSetNodeID ID; @@ -3349,7 +3346,7 @@ TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, /// is actually a value of type @c TargetInfo::IntType. QualType ASTContext::getFromTargetType(unsigned Type) const { switch (Type) { - case TargetInfo::NoInt: return QualType(); + case TargetInfo::NoInt: return QualType(); case TargetInfo::SignedShort: return ShortTy; case TargetInfo::UnsignedShort: return UnsignedShortTy; case TargetInfo::SignedInt: return IntTy; @@ -3379,7 +3376,7 @@ bool ASTContext::isObjCNSObjectType(QualType Ty) const { if (TD->getAttr()) return true; } - return false; + return false; } /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's @@ -3391,7 +3388,7 @@ QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const { getLangOptions().getGCMode() != LangOptions::NonGC) { GCAttrs = Ty.getObjCGCAttr(); // Default behavious under objective-c's gc is for objective-c pointers - // (or pointers to them) be treated as though they were declared + // (or pointers to them) be treated as though they were declared // as __strong. if (GCAttrs == QualType::GCNone) { if (Ty->isObjCObjectPointerType()) @@ -3411,7 +3408,7 @@ QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const { // Type Compatibility Testing //===----------------------------------------------------------------------===// -/// areCompatVectorTypes - Return true if the two specified vector types are +/// areCompatVectorTypes - Return true if the two specified vector types are /// compatible. static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS) { @@ -3451,20 +3448,20 @@ bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, bool compare) { // Allow id and an 'id' or void* type in all cases. - if (lhs->isVoidPointerType() || + if (lhs->isVoidPointerType() || lhs->isObjCIdType() || lhs->isObjCClassType()) return true; - else if (rhs->isVoidPointerType() || + else if (rhs->isVoidPointerType() || rhs->isObjCIdType() || rhs->isObjCClassType()) return true; if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType(); - + if (!rhsOPT) return false; - + if (rhsOPT->qual_empty()) { - // If the RHS is a unqualified interface pointer "NSString*", + // If the RHS is a unqualified interface pointer "NSString*", // make sure we check the class hierarchy. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), @@ -3479,7 +3476,7 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, // If there are no qualifiers and no interface, we have an 'id'. return true; } - // Both the right and left sides have qualifiers. + // Both the right and left sides have qualifiers. for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), E = lhsQID->qual_end(); I != E; ++I) { ObjCProtocolDecl *lhsProto = *I; @@ -3497,7 +3494,7 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, break; } } - // If the RHS is a qualified interface pointer "NSString

*", + // If the RHS is a qualified interface pointer "NSString

*", // make sure we check the class hierarchy. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), @@ -3514,14 +3511,14 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, if (!match) return false; } - + return true; } - + const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); assert(rhsQID && "One of the LHS/RHS should be id"); - if (const ObjCObjectPointerType *lhsOPT = + if (const ObjCObjectPointerType *lhsOPT = lhs->getAsObjCInterfacePointerType()) { if (lhsOPT->qual_empty()) { bool match = false; @@ -3541,7 +3538,7 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, } return true; } - // Both the right and left sides have qualifiers. + // Both the right and left sides have qualifiers. for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), E = lhsOPT->qual_end(); I != E; ++I) { ObjCProtocolDecl *lhsProto = *I; @@ -3578,15 +3575,15 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, return true; if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) - return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), - QualType(RHSOPT,0), + return 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. return canAssignObjCInterfaces(LHS, RHS); - + return false; } @@ -3596,17 +3593,17 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, // the LHS. if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) return false; - + // RHS must have a superset of the protocols in the LHS. If the LHS is not // protocol qualified at all, then we are good. if (LHS->getNumProtocols() == 0) return true; - + // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it // isn't a superset. if (RHS->getNumProtocols() == 0) return true; // FIXME: should return false! - + for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(), LHSPE = LHS->qual_end(); LHSPI != LHSPE; LHSPI++) { @@ -3634,7 +3631,7 @@ bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { // get the "pointed to" types const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType(); const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType(); - + if (!LHSOPT || !RHSOPT) return false; @@ -3642,9 +3639,9 @@ bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { canAssignObjCInterfaces(RHSOPT, LHSOPT); } -/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, +/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, /// both shall have the identically qualified version of a compatible type. -/// C99 6.2.7p1: Two types have compatible types if their types are the +/// C99 6.2.7p1: Two types have compatible types if their types are the /// same. See 6.7.[2,3,5] for additional rules. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { return !mergeTypes(LHS, RHS).isNull(); @@ -3671,7 +3668,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) { allLTypes = false; if (NoReturn != rbase->getNoReturnAttr()) allRTypes = false; - + if (lproto && rproto) { // two C99 style function prototypes assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && "C++ shouldn't be here"); @@ -3783,15 +3780,15 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr(); if (GCAttr != QualType::GCNone) { QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr(); - // __weak attribute must appear on both declarations. - // __strong attribue is redundant if other decl is an objective-c + // __weak attribute must appear on both declarations. + // __strong attribue is redundant if other decl is an objective-c // object pointer (or decorated with __strong attribute); otherwise // issue error. if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) || (GCAttr == QualType::Strong && GCLHSAttr != GCAttr && !LHSCan->isObjCObjectPointerType())) return QualType(); - + RHS = QualType(cast(RHS.getDesugaredType())->getBaseType(), RHS.getCVRQualifiers()); QualType Result = mergeTypes(LHS, RHS); @@ -3809,14 +3806,14 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { if (GCAttr != QualType::GCNone) { QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr(); // __weak attribute must appear on both declarations. __strong - // __strong attribue is redundant if other decl is an objective-c + // __strong attribue is redundant if other decl is an objective-c // object pointer (or decorated with __strong attribute); otherwise // issue error. if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) || (GCAttr == QualType::Strong && GCRHSAttr != GCAttr && !RHSCan->isObjCObjectPointerType())) return QualType(); - + LHS = QualType(cast(LHS.getDesugaredType())->getBaseType(), LHS.getCVRQualifiers()); QualType Result = mergeTypes(LHS, RHS); @@ -3835,15 +3832,15 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { LHSClass = Type::ConstantArray; if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) RHSClass = Type::ConstantArray; - + // Canonicalize ExtVector -> Vector. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; - + // If the canonical type classes don't match. if (LHSClass != RHSClass) { // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, - // a signed integer type, or an unsigned integer type. + // a signed integer type, or an unsigned integer type. if (const EnumType* ETy = LHS->getAsEnumType()) { if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) return RHS; @@ -3976,7 +3973,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { return QualType(); } case Type::ObjCObjectPointer: { - if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(), + if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(), RHS->getAsObjCObjectPointerType())) return LHS; @@ -4072,18 +4069,18 @@ void ExternalASTSource::PrintStats() { } /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the /// pointer over the consumed characters. This returns the resultant type. -static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, +static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool AllowTypeModifiers = true) { // Modifiers. int HowLong = 0; bool Signed = false, Unsigned = false; - + // Read the modifiers first. bool Done = false; while (!Done) { switch (*Str++) { - default: Done = true; --Str; break; + default: Done = true; --Str; break; case 'S': assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); assert(!Signed && "Can't use 'S' modifier multiple times!"); @@ -4102,7 +4099,7 @@ static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, } QualType Type; - + // Read the base type. switch (*Str++) { default: assert(0 && "Unknown builtin type letter!"); @@ -4186,9 +4183,9 @@ static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, char *End; unsigned NumElements = strtoul(Str, &End, 10); assert(End != Str && "Missing vector size"); - + Str = End; - + QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); Type = Context.getVectorType(ElementType, NumElements); break; @@ -4212,10 +4209,10 @@ static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, } break; } - + if (!AllowTypeModifiers) return Type; - + Done = false; while (!Done) { switch (*Str++) { @@ -4232,7 +4229,7 @@ static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, break; } } - + return Type; } @@ -4240,9 +4237,9 @@ static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, QualType ASTContext::GetBuiltinType(unsigned id, GetBuiltinTypeError &Error) { const char *TypeStr = BuiltinInfo.GetTypeString(id); - + llvm::SmallVector ArgTypes; - + Error = GE_None; QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error); if (Error != GE_None) @@ -4255,7 +4252,7 @@ QualType ASTContext::GetBuiltinType(unsigned id, // Do array -> pointer decay. The builtin should use the decayed type. if (Ty->isArrayType()) Ty = getArrayDecayedType(Ty); - + ArgTypes.push_back(Ty); } @@ -4288,42 +4285,42 @@ ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { // If both types are identical, no conversion is needed. if (lhs == rhs) return lhs; - + // If either side is a non-arithmetic type (e.g. a pointer), we are done. // The caller can deal with this (e.g. pointer + int). if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) return lhs; - - // At this point, we have two different arithmetic types. - + + // At this point, we have two different arithmetic types. + // Handle complex types first (C99 6.3.1.8p1). if (lhs->isComplexType() || rhs->isComplexType()) { // if we have an integer operand, the result is the complex type. - if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { + if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { // convert the rhs to the lhs complex type. return lhs; } - if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { + if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { // convert the lhs to the rhs complex type. return rhs; } // This handles complex/complex, complex/float, or float/complex. - // When both operands are complex, the shorter operand is converted to the - // type of the longer, and that is the type of the result. This corresponds - // to what is done when combining two real floating-point operands. - // The fun begins when size promotion occur across type domains. + // When both operands are complex, the shorter operand is converted to the + // type of the longer, and that is the type of the result. This corresponds + // to what is done when combining two real floating-point operands. + // The fun begins when size promotion occur across type domains. // From H&S 6.3.4: When one operand is complex and the other is a real - // floating-point type, the less precise type is converted, within it's + // floating-point type, the less precise type is converted, within it's // real or complex domain, to the precision of the other type. For example, - // when combining a "long double" with a "double _Complex", the + // when combining a "long double" with a "double _Complex", the // "double _Complex" is promoted to "long double _Complex". int result = getFloatingTypeOrder(lhs, rhs); - - if (result > 0) { // The left side is bigger, convert rhs. + + if (result > 0) { // The left side is bigger, convert rhs. rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs); - } else if (result < 0) { // The right side is bigger, convert lhs. + } else if (result < 0) { // The right side is bigger, convert lhs. lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs); - } + } // At this point, lhs and rhs have the same rank/size. Now, make sure the // domains match. This is a requirement for our implementation, C99 // does not require this promotion. @@ -4351,7 +4348,7 @@ ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { // convert lhs to the rhs floating point type. return rhs; } - if (lhs->isComplexIntegerType()) { + if (lhs->isComplexIntegerType()) { // convert lhs to the complex floating point type. return getComplexType(rhs); } @@ -4369,7 +4366,7 @@ ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); if (lhsComplexInt && rhsComplexInt) { - if (getIntegerTypeOrder(lhsComplexInt->getElementType(), + if (getIntegerTypeOrder(lhsComplexInt->getElementType(), rhsComplexInt->getElementType()) >= 0) return lhs; // convert the rhs return rhs; diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp index 4e07b957a7d05f180fe254a0629bd5fece069303..776a26595b03fadabeb9abb1c1385c3dc4d1bbdb 100644 --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -45,7 +45,7 @@ TypeLoc DeclaratorInfo::getTypeLoc() const { //===----------------------------------------------------------------------===// // Decl Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// - + TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { return new (C) TranslationUnitDecl(C); @@ -59,7 +59,7 @@ NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, void NamespaceDecl::Destroy(ASTContext& C) { // NamespaceDecl uses "NextDeclarator" to chain namespace declarations // together. They are all top-level Decls. - + this->~NamespaceDecl(); C.Deallocate((void *)this); } @@ -75,9 +75,9 @@ const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { case VarDecl::None: break; case VarDecl::Auto: return "auto"; break; case VarDecl::Extern: return "extern"; break; - case VarDecl::PrivateExtern: return "__private_extern__"; break; + case VarDecl::PrivateExtern: return "__private_extern__"; break; case VarDecl::Register: return "register"; break; - case VarDecl::Static: return "static"; break; + case VarDecl::Static: return "static"; break; } assert(0 && "Invalid storage class"); @@ -92,13 +92,13 @@ ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, } QualType ParmVarDecl::getOriginalType() const { - if (const OriginalParmVarDecl *PVD = + if (const OriginalParmVarDecl *PVD = dyn_cast(this)) return PVD->OriginalType; return getType(); } -void VarDecl::setInit(ASTContext &C, Expr *I) { +void VarDecl::setInit(ASTContext &C, Expr *I) { if (EvaluatedStmt *Eval = Init.dyn_cast()) { Eval->~EvaluatedStmt(); C.Deallocate(Eval); @@ -109,11 +109,11 @@ void VarDecl::setInit(ASTContext &C, Expr *I) { bool VarDecl::isExternC(ASTContext &Context) const { if (!Context.getLangOptions().CPlusPlus) - return (getDeclContext()->isTranslationUnit() && + return (getDeclContext()->isTranslationUnit() && getStorageClass() != Static) || (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); - for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); + for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { if (const LinkageSpecDecl *Linkage = dyn_cast(DC)) { if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) @@ -138,12 +138,12 @@ OriginalParmVarDecl *OriginalParmVarDecl::Create( } FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, + SourceLocation L, DeclarationName N, QualType T, DeclaratorInfo *DInfo, - StorageClass S, bool isInline, + StorageClass S, bool isInline, bool hasWrittenPrototype) { - FunctionDecl *New + FunctionDecl *New = new (C) FunctionDecl(Function, DC, L, N, T, DInfo, S, isInline); New->HasWrittenPrototype = hasWrittenPrototype; return New; @@ -162,7 +162,7 @@ FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, bool FieldDecl::isAnonymousStructOrUnion() const { if (!isImplicit() || getDeclName()) return false; - + if (const RecordType *Record = getType()->getAs()) return Record->getDecl()->isAnonymousStructOrUnion(); @@ -233,7 +233,7 @@ std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { // scope class/struct/union. How do we handle this case? break; - if (const ClassTemplateSpecializationDecl *Spec + if (const ClassTemplateSpecializationDecl *Spec = dyn_cast(Ctx)) { const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); std::string TemplateArgsStr @@ -271,7 +271,7 @@ bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { return cast(this)->getNominatedNamespace() == cast(OldD)->getNominatedNamespace(); } - + if (const FunctionDecl *FD = dyn_cast(this)) // For function declarations, we keep track of redeclarations. return FD->getPreviousDeclaration() == OldD; @@ -283,11 +283,11 @@ bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { = dyn_cast(OldD)) return FunctionTemplate->getTemplatedDecl() ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); - + // For method declarations, we keep track of redeclarations. if (isa(this)) return false; - + // For non-function declarations, if the declarations are of the // same kind then this must be a redeclaration, or semantic analysis // would not have given us the new declaration. @@ -444,11 +444,11 @@ bool FunctionDecl::isExternC(ASTContext &Context) const { if (!Context.getLangOptions().CPlusPlus) return getStorageClass() != Static && !getAttr(); - for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); + for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { if (const LinkageSpecDecl *Linkage = dyn_cast(DC)) { if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) - return getStorageClass() != Static && + return getStorageClass() != Static && !getAttr(); break; @@ -465,7 +465,7 @@ bool FunctionDecl::isGlobal() const { if (getStorageClass() == Static) return false; - for (const DeclContext *DC = getDeclContext(); + for (const DeclContext *DC = getDeclContext(); DC->isNamespace(); DC = DC->getParent()) { if (const NamespaceDecl *Namespace = cast(DC)) { @@ -485,7 +485,7 @@ bool FunctionDecl::isGlobal() const { /// declared at translation scope or within an extern "C" block and /// its name matches with the name of a builtin. The returned value /// will be 0 for functions that do not correspond to a builtin, a -/// value of type \c Builtin::ID if in the target-independent range +/// value of type \c Builtin::ID if in the target-independent range /// \c [1,Builtin::First), or a target-specific builtin value. unsigned FunctionDecl::getBuiltinID(ASTContext &Context) const { if (!getIdentifier() || !getIdentifier()->getBuiltinID()) @@ -512,7 +512,7 @@ unsigned FunctionDecl::getBuiltinID(ASTContext &Context) const { // If the function is in an extern "C" linkage specification and is // not marked "overloadable", it's the real function. if (isa(getDeclContext()) && - cast(getDeclContext())->getLanguage() + cast(getDeclContext())->getLanguage() == LinkageSpecDecl::lang_c && !getAttr()) return BuiltinID; @@ -530,14 +530,14 @@ unsigned FunctionDecl::getNumParams() const { if (isa(FT)) return 0; return cast(FT)->getNumArgs(); - + } void FunctionDecl::setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NumParams) { assert(ParamInfo == 0 && "Already has param info!"); assert(NumParams == getNumParams() && "Parameter count mismatch!"); - + // Zero params -> null pointer. if (NumParams) { void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); @@ -586,12 +586,12 @@ bool FunctionDecl::isExternGNUInline(ASTContext &Context) const { return false; } -void +void FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { redeclarable_base::setPreviousDeclaration(PrevDecl); if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { - FunctionTemplateDecl *PrevFunTmpl + FunctionTemplateDecl *PrevFunTmpl = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); FunTmpl->setPreviousDeclaration(PrevFunTmpl); @@ -612,7 +612,7 @@ OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { } FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { - if (FunctionTemplateSpecializationInfo *Info + if (FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization .dyn_cast()) { return Info->Template.getPointer(); @@ -622,7 +622,7 @@ FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { const TemplateArgumentList * FunctionDecl::getTemplateSpecializationArgs() const { - if (FunctionTemplateSpecializationInfo *Info + if (FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization .dyn_cast()) { return Info->TemplateArguments; @@ -630,53 +630,53 @@ FunctionDecl::getTemplateSpecializationArgs() const { return 0; } -void +void FunctionDecl::setFunctionTemplateSpecialization(ASTContext &Context, FunctionTemplateDecl *Template, const TemplateArgumentList *TemplateArgs, void *InsertPos) { - FunctionTemplateSpecializationInfo *Info + FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization.dyn_cast(); if (!Info) Info = new (Context) FunctionTemplateSpecializationInfo; - + Info->Function = this; Info->Template.setPointer(Template); Info->Template.setInt(TSK_ImplicitInstantiation - 1); Info->TemplateArguments = TemplateArgs; TemplateOrSpecialization = Info; - + // Insert this function template specialization into the set of known // function template specialiations. Template->getSpecializations().InsertNode(Info, InsertPos); } TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { - // For a function template specialization, query the specialization + // For a function template specialization, query the specialization // information object. - FunctionTemplateSpecializationInfo *Info + FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization.dyn_cast(); if (Info) return Info->getTemplateSpecializationKind(); - + if (!getInstantiatedFromMemberFunction()) return TSK_Undeclared; - + // Find the class template specialization corresponding to this instantiation // of a member function. const DeclContext *Parent = getDeclContext(); while (Parent && !isa(Parent)) Parent = Parent->getParent(); - + if (!Parent) return TSK_Undeclared; return cast(Parent)->getSpecializationKind(); } -void +void FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { - FunctionTemplateSpecializationInfo *Info + FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization.dyn_cast(); assert(Info && "Not a function template specialization"); Info->setTemplateSpecializationKind(TSK); @@ -714,12 +714,12 @@ void TagDecl::completeDefinition() { TagDecl* TagDecl::getDefinition(ASTContext& C) const { if (isDefinition()) return const_cast(this); - - for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); + + for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); R != REnd; ++R) if (R->isDefinition()) return *R; - + return 0; } @@ -750,7 +750,7 @@ RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, SourceLocation TKL, RecordDecl* PrevDecl) { - + RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL); C.getTypeDeclType(R, PrevDecl); return R; @@ -764,7 +764,7 @@ void RecordDecl::Destroy(ASTContext& C) { } bool RecordDecl::isInjectedClassName() const { - return isImplicit() && getDeclName() && getDeclContext()->isRecord() && + return isImplicit() && getDeclName() && getDeclContext()->isRecord() && cast(getDeclContext())->getDeclName() == getDeclName(); } @@ -788,15 +788,15 @@ void BlockDecl::Destroy(ASTContext& C) { for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) (*I)->Destroy(C); - - C.Deallocate(ParamInfo); + + C.Deallocate(ParamInfo); Decl::Destroy(C); } void BlockDecl::setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NParms) { assert(ParamInfo == 0 && "Already has param info!"); - + // Zero params -> null pointer. if (NParms) { NumParams = NParms; diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp index acdbdbe4223b01809ded1990d8ed390854d2ac33..34bc2b97e3fd9dcffe712d4f975486bf7f6aa24e 100644 --- a/clang/lib/AST/DeclBase.cpp +++ b/clang/lib/AST/DeclBase.cpp @@ -62,12 +62,12 @@ bool Decl::CollectingStats(bool Enable) { void Decl::PrintStats() { fprintf(stderr, "*** Decl Stats:\n"); - + int totalDecls = 0; #define DECL(Derived, Base) totalDecls += n##Derived##s; #include "clang/AST/DeclNodes.def" fprintf(stderr, " %d decls total.\n", totalDecls); - + int totalBytes = 0; #define DECL(Derived, Base) \ if (n##Derived##s > 0) { \ @@ -77,7 +77,7 @@ void Decl::PrintStats() { (int)(n##Derived##s * sizeof(Derived##Decl))); \ } #include "clang/AST/DeclNodes.def" - + fprintf(stderr, "Total bytes = %d\n", totalBytes); } @@ -92,26 +92,26 @@ void Decl::addDeclKind(Kind k) { bool Decl::isTemplateParameterPack() const { if (const TemplateTypeParmDecl *TTP = dyn_cast(this)) return TTP->isParameterPack(); - + return false; } bool Decl::isFunctionOrFunctionTemplate() const { if (const UsingDecl *UD = dyn_cast(this)) return UD->getTargetDecl()->isFunctionOrFunctionTemplate(); - + return isa(this) || isa(this); } //===----------------------------------------------------------------------===// // PrettyStackTraceDecl Implementation //===----------------------------------------------------------------------===// - + void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const { SourceLocation TheLoc = Loc; if (TheLoc.isInvalid() && TheDecl) TheLoc = TheDecl->getLocation(); - + if (TheLoc.isValid()) { TheLoc.print(OS, SM); OS << ": "; @@ -123,7 +123,7 @@ void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const { OS << " '" << DN->getQualifiedNameAsString() << '\''; OS << '\n'; } - + //===----------------------------------------------------------------------===// // Decl Implementation //===----------------------------------------------------------------------===// @@ -132,14 +132,14 @@ void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const { Decl::~Decl() { if (isOutOfSemaDC()) delete getMultipleDC(); - + assert(!HasAttrs && "attributes should have been freed by Destroy"); } void Decl::setDeclContext(DeclContext *DC) { if (isOutOfSemaDC()) delete getMultipleDC(); - + DeclCtx = DC; } @@ -163,22 +163,22 @@ TranslationUnitDecl *Decl::getTranslationUnitDecl() { DeclContext *DC = getDeclContext(); assert(DC && "This decl is not contained in a translation unit!"); - + while (!DC->isTranslationUnit()) { DC = DC->getParent(); assert(DC && "This decl is not contained in a translation unit!"); } - + return cast(DC); } ASTContext &Decl::getASTContext() const { - return getTranslationUnitDecl()->getASTContext(); + return getTranslationUnitDecl()->getASTContext(); } unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { switch (DeclKind) { - default: + default: if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast) return IDNS_Ordinary; assert(0 && "Unknown decl kind!"); @@ -202,7 +202,7 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { case ObjCProtocol: return IDNS_ObjCProtocol; - + case ObjCImplementation: return IDNS_ObjCImplementation; @@ -213,13 +213,13 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { case ObjCAtDefsField: case ObjCIvar: return IDNS_Member; - + case Record: case CXXRecord: case Enum: case TemplateTypeParm: return IDNS_Tag; - + case Namespace: case Template: case FunctionTemplate: @@ -227,7 +227,7 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { case TemplateTemplateParm: case NamespaceAlias: return IDNS_Tag | IDNS_Ordinary; - + // Never have names. case Friend: case LinkageSpec: @@ -252,41 +252,41 @@ void Decl::addAttr(Attr *NewAttr) { NewAttr->setNext(ExistingAttr); ExistingAttr = NewAttr; - + HasAttrs = true; } void Decl::invalidateAttrs() { if (!HasAttrs) return; - + HasAttrs = false; getASTContext().eraseDeclAttrs(this); } const Attr *Decl::getAttrsImpl() const { - assert(HasAttrs && "getAttrs() should verify this!"); + assert(HasAttrs && "getAttrs() should verify this!"); return getASTContext().getDeclAttrs(this); } void Decl::swapAttrs(Decl *RHS) { bool HasLHSAttr = this->HasAttrs; bool HasRHSAttr = RHS->HasAttrs; - + // Usually, neither decl has attrs, nothing to do. if (!HasLHSAttr && !HasRHSAttr) return; - + // If 'this' has no attrs, swap the other way. if (!HasLHSAttr) return RHS->swapAttrs(this); - + ASTContext &Context = getASTContext(); - + // Handle the case when both decls have attrs. if (HasRHSAttr) { std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS)); return; } - + // Otherwise, LHS has an attr and RHS doesn't. Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this); Context.eraseDeclAttrs(this); @@ -302,7 +302,7 @@ void Decl::Destroy(ASTContext &C) { invalidateAttrs(); HasAttrs = false; } - + #if 0 // FIXME: Once ownership is fully understood, we can enable this code if (DeclContext *DC = dyn_cast(this)) @@ -311,15 +311,15 @@ void Decl::Destroy(ASTContext &C) { // Observe the unrolled recursion. By setting N->NextDeclInContext = 0x0 // within the loop, only the Destroy method for the first Decl // will deallocate all of the Decls in a chain. - + Decl* N = getNextDeclInContext(); - + while (N) { Decl* Tmp = N->getNextDeclInContext(); N->NextDeclInContext = 0; N->Destroy(C); N = Tmp; - } + } this->~Decl(); C.Deallocate((void *)this); @@ -384,8 +384,8 @@ void Decl::CheckAccessDeclContext() const { if (isa(this) || !isa(getDeclContext())) return; - - assert(Access != AS_none && + + assert(Access != AS_none && "Access specifier is AS_none inside a record decl"); } @@ -434,7 +434,7 @@ bool DeclContext::isDependentContext() const { if (const FunctionDecl *Function = dyn_cast(this)) if (Function->getDescribedFunctionTemplate()) return true; - + return getParent() && getParent()->isDependentContext(); } @@ -454,18 +454,18 @@ bool DeclContext::isTransparentContext() const { bool DeclContext::Encloses(DeclContext *DC) { if (getPrimaryContext() != this) return getPrimaryContext()->Encloses(DC); - + for (; DC; DC = DC->getParent()) if (DC->getPrimaryContext() == this) return true; - return false; + return false; } DeclContext *DeclContext::getPrimaryContext() { switch (DeclKind) { case Decl::TranslationUnit: case Decl::LinkageSpec: - case Decl::Block: + case Decl::Block: // There is only one DeclContext for these entities. return this; @@ -491,7 +491,7 @@ DeclContext *DeclContext::getPrimaryContext() { // If this is a tag type that has a definition or is currently // being defined, that definition is our primary context. if (const TagType *TagT =cast(this)->TypeForDecl->getAs()) - if (TagT->isBeingDefined() || + if (TagT->isBeingDefined() || (TagT->getDecl() && TagT->getDecl()->isDefinition())) return TagT->getDecl(); return this; @@ -516,13 +516,13 @@ DeclContext *DeclContext::getNextContext() { /// \brief Load the declarations within this lexical storage from an /// external source. -void +void DeclContext::LoadLexicalDeclsFromExternalStorage() const { ExternalASTSource *Source = getParentASTContext().getExternalSource(); assert(hasExternalLexicalStorage() && Source && "No external storage?"); llvm::SmallVector Decls; - if (Source->ReadDeclsLexicallyInContext(const_cast(this), + if (Source->ReadDeclsLexicallyInContext(const_cast(this), Decls)) return; @@ -554,7 +554,7 @@ DeclContext::LoadLexicalDeclsFromExternalStorage() const { LastDecl = PrevDecl; } -void +void DeclContext::LoadVisibleDeclsFromExternalStorage() const { DeclContext *This = const_cast(this); ExternalASTSource *Source = getParentASTContext().getExternalSource(); @@ -583,14 +583,14 @@ DeclContext::decl_iterator DeclContext::decls_begin() const { // FIXME: Check whether we need to load some declarations from // external storage. - return decl_iterator(FirstDecl); + return decl_iterator(FirstDecl); } DeclContext::decl_iterator DeclContext::decls_end() const { if (hasExternalLexicalStorage()) LoadLexicalDeclsFromExternalStorage(); - return decl_iterator(); + return decl_iterator(); } bool DeclContext::decls_empty() const { @@ -603,7 +603,7 @@ bool DeclContext::decls_empty() const { void DeclContext::addHiddenDecl(Decl *D) { assert(D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context"); - assert(!D->getNextDeclInContext() && D != LastDecl && + assert(!D->getNextDeclInContext() && D != LastDecl && "Decl already inserted into a DeclContext"); if (FirstDecl) { @@ -626,8 +626,8 @@ void DeclContext::addDecl(Decl *D) { /// transparent contexts nested within it). void DeclContext::buildLookup(DeclContext *DCtx) { for (; DCtx; DCtx = DCtx->getNextContext()) { - for (decl_iterator D = DCtx->decls_begin(), - DEnd = DCtx->decls_end(); + for (decl_iterator D = DCtx->decls_begin(), + DEnd = DCtx->decls_end(); D != DEnd; ++D) { // Insert this declaration into the lookup structure, but only // if it's semantically in its decl context. During non-lazy @@ -645,7 +645,7 @@ void DeclContext::buildLookup(DeclContext *DCtx) { } } -DeclContext::lookup_result +DeclContext::lookup_result DeclContext::lookup(DeclarationName Name) { DeclContext *PrimaryContext = getPrimaryContext(); if (PrimaryContext != this) @@ -671,7 +671,7 @@ DeclContext::lookup(DeclarationName Name) { return Pos->second.getLookupResult(getParentASTContext()); } -DeclContext::lookup_const_result +DeclContext::lookup_const_result DeclContext::lookup(DeclarationName Name) const { return const_cast(this)->lookup(Name); } @@ -744,14 +744,14 @@ void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) { // one, just replace it and return. if (DeclNameEntries.HandleRedeclaration(getParentASTContext(), D)) return; - + // Put this declaration into the appropriate slot. DeclNameEntries.AddSubsequentDecl(D); } /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within /// this context. -DeclContext::udir_iterator_range +DeclContext::udir_iterator_range DeclContext::getUsingDirectives() const { lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); return udir_iterator_range(reinterpret_cast(Result.first), diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp index 155005a10035533c159d4fb2f582797f1ad2dae5..e8f97a383d02f6f41e1f2fcda7535608a516c84d 100644 --- a/clang/lib/AST/DeclCXX.cpp +++ b/clang/lib/AST/DeclCXX.cpp @@ -26,7 +26,7 @@ using namespace clang; CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, CXXRecordDecl *PrevDecl, - SourceLocation TKL) + SourceLocation TKL) : RecordDecl(K, TK, DC, L, Id, PrevDecl, TKL), UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false), UserDeclaredCopyAssignment(false), UserDeclaredDestructor(false), @@ -42,12 +42,12 @@ CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation TKL, CXXRecordDecl* PrevDecl, bool DelayTypeCreation) { - CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id, + CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id, PrevDecl, TKL); - + // FIXME: DelayTypeCreation seems like such a hack if (!DelayTypeCreation) - C.getTypeDeclType(R, PrevDecl); + C.getTypeDeclType(R, PrevDecl); return R; } @@ -60,22 +60,22 @@ void CXXRecordDecl::Destroy(ASTContext &C) { this->RecordDecl::Destroy(C); } -void +void CXXRecordDecl::setBases(ASTContext &C, - CXXBaseSpecifier const * const *Bases, + CXXBaseSpecifier const * const *Bases, unsigned NumBases) { - // C++ [dcl.init.aggr]p1: + // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class (clause 9) with [...] // no base classes [...]. Aggregate = false; if (this->Bases) C.Deallocate(this->Bases); - + int vbaseCount = 0; llvm::SmallVector UniqueVbases; bool hasDirectVirtualBase = false; - + this->Bases = new(C) CXXBaseSpecifier [NumBases]; this->NumBases = NumBases; for (unsigned i = 0; i < NumBases; ++i) { @@ -83,7 +83,7 @@ CXXRecordDecl::setBases(ASTContext &C, // Keep track of inherited vbases for this base class. const CXXBaseSpecifier *Base = Bases[i]; QualType BaseType = Base->getType(); - // Skip template types. + // Skip template types. // FIXME. This means that this list must be rebuilt during template // instantiation. if (BaseType->isDependentType()) @@ -92,10 +92,10 @@ CXXRecordDecl::setBases(ASTContext &C, = cast(BaseType->getAs()->getDecl()); if (Base->isVirtual()) hasDirectVirtualBase = true; - for (CXXRecordDecl::base_class_iterator VBase = + for (CXXRecordDecl::base_class_iterator VBase = BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) { - // Add this vbase to the array of vbases for current class if it is + // Add this vbase to the array of vbases for current class if it is // not already in the list. // FIXME. Note that we do a linear search as number of such classes are // very few. @@ -134,7 +134,7 @@ CXXRecordDecl::setBases(ASTContext &C, QualType QT = UniqueVbases[i]->getType(); CXXRecordDecl *VBaseClassDecl = cast(QT->getAs()->getDecl()); - this->VBases[i] = + this->VBases[i] = CXXBaseSpecifier(VBaseClassDecl->getSourceRange(), true, VBaseClassDecl->getTagKind() == RecordDecl::TK_class, UniqueVbases[i]->getAccessSpecifier(), QT); @@ -146,11 +146,11 @@ bool CXXRecordDecl::hasConstCopyConstructor(ASTContext &Context) const { return getCopyConstructor(Context, QualType::Const) != 0; } -CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context, +CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context, unsigned TypeQuals) const{ QualType ClassType = Context.getTypeDeclType(const_cast(this)); - DeclarationName ConstructorName + DeclarationName ConstructorName = Context.DeclarationNames.getCXXConstructorName( Context.getCanonicalType(ClassType)); unsigned FoundTQs; @@ -162,12 +162,12 @@ CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context, if (isa(*Con)) continue; - if (cast(*Con)->isCopyConstructor(Context, + if (cast(*Con)->isCopyConstructor(Context, FoundTQs)) { if (((TypeQuals & QualType::Const) == (FoundTQs & QualType::Const)) || (!(TypeQuals & QualType::Const) && (FoundTQs & QualType::Const))) return cast(*Con); - + } } return 0; @@ -217,13 +217,13 @@ bool CXXRecordDecl::hasConstCopyAssignment(ASTContext &Context, } void -CXXRecordDecl::addedConstructor(ASTContext &Context, +CXXRecordDecl::addedConstructor(ASTContext &Context, CXXConstructorDecl *ConDecl) { assert(!ConDecl->isImplicit() && "addedConstructor - not for implicit decl"); // Note that we have a user-declared constructor. UserDeclaredConstructor = true; - // C++ [dcl.init.aggr]p1: + // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class (clause 9) with no // user-declared constructors (12.1) [...]. Aggregate = false; @@ -237,7 +237,7 @@ CXXRecordDecl::addedConstructor(ASTContext &Context, // constructor. // FIXME: C++0x: don't do this for "= default" default constructors. HasTrivialConstructor = false; - + // Note when we have a user-declared copy constructor, which will // suppress the implicit declaration of a copy constructor. if (ConDecl->isCopyConstructor(Context)) { @@ -282,14 +282,14 @@ void CXXRecordDecl::addedAssignmentOperator(ASTContext &Context, PlainOldData = false; } -void CXXRecordDecl::addConversionFunction(ASTContext &Context, +void CXXRecordDecl::addConversionFunction(ASTContext &Context, CXXConversionDecl *ConvDecl) { assert(!ConvDecl->getDescribedFunctionTemplate() && "Conversion function templates should cast to FunctionTemplateDecl."); Conversions.addOverload(ConvDecl); } -void CXXRecordDecl::addConversionFunction(ASTContext &Context, +void CXXRecordDecl::addConversionFunction(ASTContext &Context, FunctionTemplateDecl *ConvDecl) { assert(isa(ConvDecl->getTemplatedDecl()) && "Function template is not a conversion function template"); @@ -302,7 +302,7 @@ CXXRecordDecl::getDefaultConstructor(ASTContext &Context) { DeclarationName ConstructorName = Context.DeclarationNames.getCXXConstructorName( Context.getCanonicalType(ClassType.getUnqualifiedType())); - + DeclContext::lookup_const_iterator Con, ConEnd; for (llvm::tie(Con, ConEnd) = lookup(ConstructorName); Con != ConEnd; ++Con) { @@ -320,18 +320,18 @@ CXXRecordDecl::getDefaultConstructor(ASTContext &Context) { const CXXDestructorDecl * CXXRecordDecl::getDestructor(ASTContext &Context) { QualType ClassType = Context.getTypeDeclType(this); - - DeclarationName Name + + DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( Context.getCanonicalType(ClassType)); DeclContext::lookup_iterator I, E; - llvm::tie(I, E) = lookup(Name); + llvm::tie(I, E) = lookup(Name); assert(I != E && "Did not find a destructor!"); - + const CXXDestructorDecl *Dtor = cast(*I); assert(++I == E && "Found more than one destructor!"); - + return Dtor; } @@ -345,8 +345,8 @@ CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, } -typedef llvm::DenseMap *> +typedef llvm::DenseMap *> OverriddenMethodsMapTy; // FIXME: We hate static data. This doesn't survive PCH saving/loading, and @@ -355,21 +355,21 @@ static OverriddenMethodsMapTy *OverriddenMethods = 0; void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) { // FIXME: The CXXMethodDecl dtor needs to remove and free the entry. - + if (!OverriddenMethods) OverriddenMethods = new OverriddenMethodsMapTy(); - + std::vector *&Methods = (*OverriddenMethods)[this]; if (!Methods) Methods = new std::vector; - + Methods->push_back(MD); } CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { if (!OverriddenMethods) return 0; - + OverriddenMethodsMapTy::iterator it = OverriddenMethods->find(this); if (it == OverriddenMethods->end() || it->second->empty()) return 0; @@ -380,7 +380,7 @@ CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const { if (!OverriddenMethods) return 0; - + OverriddenMethodsMapTy::iterator it = OverriddenMethods->find(this); if (it == OverriddenMethods->end() || it->second->empty()) return 0; @@ -409,12 +409,12 @@ QualType CXXMethodDecl::getThisType(ASTContext &C) const { CXXBaseOrMemberInitializer:: CXXBaseOrMemberInitializer(QualType BaseType, Expr **Args, unsigned NumArgs, CXXConstructorDecl *C, - SourceLocation L, SourceLocation R) + SourceLocation L, SourceLocation R) : Args(0), NumArgs(0), CtorOrAnonUnion(), IdLoc(L), RParenLoc(R) { BaseOrMember = reinterpret_cast(BaseType.getTypePtr()); assert((BaseOrMember & 0x01) == 0 && "Invalid base class type pointer"); BaseOrMember |= 0x01; - + if (NumArgs > 0) { this->NumArgs = NumArgs; // FIXME. Allocation via Context @@ -431,7 +431,7 @@ CXXBaseOrMemberInitializer(FieldDecl *Member, Expr **Args, unsigned NumArgs, SourceLocation L, SourceLocation R) : Args(0), NumArgs(0), CtorOrAnonUnion(), IdLoc(L), RParenLoc(R) { BaseOrMember = reinterpret_cast(Member); - assert((BaseOrMember & 0x01) == 0 && "Invalid member pointer"); + assert((BaseOrMember & 0x01) == 0 && "Invalid member pointer"); if (NumArgs > 0) { this->NumArgs = NumArgs; @@ -466,8 +466,8 @@ bool CXXConstructorDecl::isDefaultConstructor() const { (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg()); } -bool -CXXConstructorDecl::isCopyConstructor(ASTContext &Context, +bool +CXXConstructorDecl::isCopyConstructor(ASTContext &Context, unsigned &TypeQuals) const { // C++ [class.copy]p2: // A non-template constructor for class X is a copy constructor @@ -508,7 +508,7 @@ bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { if (isExplicit() && !AllowExplicit) return false; - return (getNumParams() == 0 && + return (getNumParams() == 0 && getType()->getAsFunctionProtoType()->isVariadic()) || (getNumParams() == 1) || (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg()); @@ -517,11 +517,11 @@ bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { CXXDestructorDecl * CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, - QualType T, bool isInline, + QualType T, bool isInline, bool isImplicitlyDeclared) { assert(N.getNameKind() == DeclarationName::CXXDestructorName && "Name must refer to a destructor"); - return new (C) CXXDestructorDecl(RD, L, N, T, isInline, + return new (C) CXXDestructorDecl(RD, L, N, T, isInline, isImplicitlyDeclared); } @@ -556,7 +556,7 @@ OverloadedFunctionDecl::Create(ASTContext &C, DeclContext *DC, OverloadIterator::OverloadIterator(NamedDecl *ND) : D(0) { if (!ND) return; - + if (isa(ND) || isa(ND)) D = ND; else if (OverloadedFunctionDecl *Ovl = dyn_cast(ND)) { @@ -575,10 +575,10 @@ void OverloadedFunctionDecl::addOverload(AnyFunctionDecl F) { OverloadIterator::reference OverloadIterator::operator*() const { if (FunctionDecl *FD = dyn_cast(D)) return FD; - + if (FunctionTemplateDecl *FTD = dyn_cast(D)) return FTD; - + assert(isa(D)); return *Iter; } @@ -588,20 +588,20 @@ OverloadIterator &OverloadIterator::operator++() { D = 0; return *this; } - + if (++Iter == cast(D)->function_end()) D = 0; - + return *this; } bool OverloadIterator::Equals(const OverloadIterator &Other) const { if (!D || !Other.D) return D == Other.D; - + if (D != Other.D) return false; - + return !isa(D) || Iter == Other.Iter; } @@ -621,10 +621,10 @@ FriendDecl *FriendDecl::Create(ASTContext &C, DeclContext *DC, #endif return new (C) FriendDecl(DC, L, Friend, FriendL); -} +} LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, - DeclContext *DC, + DeclContext *DC, SourceLocation L, LanguageIDs Lang, bool Braces) { return new (C) LinkageSpecDecl(DC, L, Lang, Braces); @@ -638,19 +638,19 @@ UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation IdentLoc, NamespaceDecl *Used, DeclContext *CommonAncestor) { - return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierRange, + return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierRange, Qualifier, IdentLoc, Used, CommonAncestor); } -NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, - SourceLocation AliasLoc, - IdentifierInfo *Alias, +NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, + SourceLocation L, + SourceLocation AliasLoc, + IdentifierInfo *Alias, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, - SourceLocation IdentLoc, + SourceLocation IdentLoc, NamedDecl *Namespace) { - return new (C) NamespaceAliasDecl(DC, L, AliasLoc, Alias, QualifierRange, + return new (C) NamespaceAliasDecl(DC, L, AliasLoc, Alias, QualifierRange, Qualifier, IdentLoc, Namespace); } diff --git a/clang/lib/AST/DeclObjC.cpp b/clang/lib/AST/DeclObjC.cpp index ee2b81560d76ee1d834c936524d0e62abae061c0..d6e4b2c44bba7529ae45eaf779aa05206bae49ee 100644 --- a/clang/lib/AST/DeclObjC.cpp +++ b/clang/lib/AST/DeclObjC.cpp @@ -30,8 +30,8 @@ void ObjCListBase::Destroy(ASTContext &Ctx) { void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { assert(List == 0 && "Elements already set!"); if (Elts == 0) return; // Setting to an empty list is a noop. - - + + List = new (Ctx) void*[Elts]; NumElts = Elts; memcpy(List, InList, sizeof(void*)*Elts); @@ -83,15 +83,15 @@ ObjCContainerDecl::FindPropertyDeclaration(IdentifierInfo *PropertyId) const { for (prop_iterator I = prop_begin(), E = prop_end(); I != E; ++I) if ((*I)->getIdentifier() == PropertyId) return *I; - + const ObjCProtocolDecl *PID = dyn_cast(this); if (PID) { - for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), + for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), E = PID->protocol_end(); I != E; ++I) if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId)) return P; } - + if (const ObjCInterfaceDecl *OID = dyn_cast(this)) { // Look through categories. for (ObjCCategoryDecl *Category = OID->getCategoryList(); @@ -151,11 +151,11 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, bool isInstance) const { const ObjCInterfaceDecl* ClassDecl = this; ObjCMethodDecl *MethodDecl = 0; - + while (ClassDecl != NULL) { if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance))) return MethodDecl; - + // Didn't find one yet - look through protocols. const ObjCList &Protocols = ClassDecl->getReferencedProtocols(); @@ -163,13 +163,13 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, E = Protocols.end(); I != E; ++I) if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance))) return MethodDecl; - + // Didn't find one yet - now look through categories. ObjCCategoryDecl *CatDecl = ClassDecl->getCategoryList(); while (CatDecl) { if ((MethodDecl = CatDecl->getMethod(Sel, isInstance))) return MethodDecl; - + // Didn't find one yet - look through protocols. const ObjCList &Protocols = CatDecl->getReferencedProtocols(); @@ -191,7 +191,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, //===----------------------------------------------------------------------===// ObjCMethodDecl *ObjCMethodDecl::Create(ASTContext &C, - SourceLocation beginLoc, + SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, DeclContext *contextDecl, @@ -201,14 +201,14 @@ ObjCMethodDecl *ObjCMethodDecl::Create(ASTContext &C, ImplementationControl impControl) { return new (C) ObjCMethodDecl(beginLoc, endLoc, SelInfo, T, contextDecl, - isInstance, + isInstance, isVariadic, isSynthesized, impControl); } void ObjCMethodDecl::Destroy(ASTContext &C) { if (Body) Body->Destroy(C); if (SelfDecl) SelfDecl->Destroy(C); - + for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) if (*I) (*I)->Destroy(C); @@ -267,7 +267,7 @@ ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() { return this; } -void ObjCMethodDecl::createImplicitParams(ASTContext &Context, +void ObjCMethodDecl::createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *OID) { QualType selfTy; if (isInstanceMethod()) { @@ -282,11 +282,11 @@ void ObjCMethodDecl::createImplicitParams(ASTContext &Context, } else // we have a factory method. selfTy = Context.getObjCClassType(); - setSelfDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(), + setSelfDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(), &Context.Idents.get("self"), selfTy)); - setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(), - &Context.Idents.get("_cmd"), + setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(), + &Context.Idents.get("_cmd"), Context.getObjCSelType())); } @@ -310,7 +310,7 @@ ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() { ObjCInterfaceDecl *ObjCInterfaceDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation atLoc, - IdentifierInfo *Id, + IdentifierInfo *Id, SourceLocation ClassLoc, bool ForwardDecl, bool isInternal){ return new (C) ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc, ForwardDecl, @@ -326,13 +326,13 @@ ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, ClassLoc(CLoc) { } -void ObjCInterfaceDecl::Destroy(ASTContext &C) { +void ObjCInterfaceDecl::Destroy(ASTContext &C) { for (ivar_iterator I = ivar_begin(), E = ivar_end(); I != E; ++I) if (*I) (*I)->Destroy(C); - + IVars.Destroy(C); // FIXME: CategoryList? - + // FIXME: Because there is no clear ownership // role between ObjCInterfaceDecls and the ObjCPropertyDecls that they // reference, we destroy ObjCPropertyDecls in ~TranslationUnit. @@ -391,7 +391,7 @@ bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, // 1st, look up the class. const ObjCList &Protocols = IDecl->getReferencedProtocols(); - + for (ObjCList::iterator PI = Protocols.begin(), E = Protocols.end(); PI != E; ++PI) { if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI)) @@ -402,11 +402,11 @@ bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, // object. This IMO, should be a bug. // FIXME: Treat this as an extension, and flag this as an error when GCC // extensions are not enabled. - if (RHSIsQualifiedID && + if (RHSIsQualifiedID && getASTContext().ProtocolCompatibleWithProtocol(*PI, lProto)) return true; } - + // 2nd, look up the category. if (lookupCategory) for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl; @@ -416,13 +416,13 @@ bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI)) return true; } - + // 3rd, look up the super class(s) if (IDecl->getSuperClass()) return IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory, RHSIsQualifiedID); - + return false; } @@ -451,7 +451,7 @@ ObjCAtDefsFieldDecl void ObjCAtDefsFieldDecl::Destroy(ASTContext& C) { this->~ObjCAtDefsFieldDecl(); - C.Deallocate((void *)this); + C.Deallocate((void *)this); } //===----------------------------------------------------------------------===// @@ -459,7 +459,7 @@ void ObjCAtDefsFieldDecl::Destroy(ASTContext& C) { //===----------------------------------------------------------------------===// ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, + SourceLocation L, IdentifierInfo *Id) { return new (C) ObjCProtocolDecl(DC, L, Id); } @@ -478,7 +478,7 @@ ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I) if ((PDecl = (*I)->lookupProtocolNamed(Name))) return PDecl; - + return NULL; } @@ -487,10 +487,10 @@ ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel, bool isInstance) const { ObjCMethodDecl *MethodDecl = NULL; - + if ((MethodDecl = getMethod(Sel, isInstance))) return MethodDecl; - + for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I) if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance))) return MethodDecl; @@ -501,7 +501,7 @@ ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel, // ObjCClassDecl //===----------------------------------------------------------------------===// -ObjCClassDecl::ObjCClassDecl(DeclContext *DC, SourceLocation L, +ObjCClassDecl::ObjCClassDecl(DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *const *Elts, unsigned nElts, ASTContext &C) : Decl(ObjCClass, DC, L) { @@ -517,7 +517,7 @@ ObjCClassDecl *ObjCClassDecl::Create(ASTContext &C, DeclContext *DC, } void ObjCClassDecl::Destroy(ASTContext &C) { - + // FIXME: There is no clear ownership policy now for referenced // ObjCInterfaceDecls. Some of them can be forward declarations that // are never later defined (in which case the ObjCClassDecl owns them) @@ -525,7 +525,7 @@ void ObjCClassDecl::Destroy(ASTContext &C) { // we should have separate objects for forward declarations and definitions, // obviating this problem. Because of this situation, referenced // ObjCInterfaceDecls are destroyed in ~TranslationUnit. - + ForwardDecls.Destroy(C); Decl::Destroy(C); } @@ -538,14 +538,14 @@ ObjCForwardProtocolDecl:: ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L, ObjCProtocolDecl *const *Elts, unsigned nElts, ASTContext &C) -: Decl(ObjCForwardProtocol, DC, L) { +: Decl(ObjCForwardProtocol, DC, L) { ReferencedProtocols.set(Elts, nElts, C); } ObjCForwardProtocolDecl * ObjCForwardProtocolDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, + SourceLocation L, ObjCProtocolDecl *const *Elts, unsigned NumElts) { return new (C) ObjCForwardProtocolDecl(DC, L, Elts, NumElts, C); @@ -649,7 +649,7 @@ FindPropertyImplDecl(IdentifierInfo *Id) const { //===----------------------------------------------------------------------===// ObjCImplementationDecl * -ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, +ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *ClassInterface, ObjCInterfaceDecl *SuperDecl) { @@ -663,7 +663,7 @@ ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, ObjCCompatibleAliasDecl * ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, - IdentifierInfo *Id, + IdentifierInfo *Id, ObjCInterfaceDecl* AliasedClass) { return new (C) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); } diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp index 275fa6972376275aebbf9b971924e063e06db63b..8aae742ef1a778b2e47a8930f588e40805de547e 100644 --- a/clang/lib/AST/DeclPrinter.cpp +++ b/clang/lib/AST/DeclPrinter.cpp @@ -34,9 +34,9 @@ namespace { void ProcessDeclGroup(llvm::SmallVectorImpl& Decls); void Print(AccessSpecifier AS); - + public: - DeclPrinter(llvm::raw_ostream &Out, ASTContext &Context, + DeclPrinter(llvm::raw_ostream &Out, ASTContext &Context, const PrintingPolicy &Policy, unsigned Indentation = 0) : Out(Out), Context(Context), Policy(Policy), Indentation(Indentation) { } @@ -186,7 +186,7 @@ void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) { bool PrintAccess = isa(DC); AccessSpecifier CurAS = AS_none; - + llvm::SmallVector Decls; for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); D != DEnd; ++D) { @@ -209,7 +209,7 @@ void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) { CurAS = AS; } } - + // The next bits of code handles stuff like "struct {int x;} a,b"; we're // forced to merge the declarations because there's no other way to // refer to the struct in question. This limited merging is safe without @@ -240,16 +240,16 @@ void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) { } this->Indent(); Visit(*D); - - // FIXME: Need to be able to tell the DeclPrinter when + + // FIXME: Need to be able to tell the DeclPrinter when const char *Terminator = 0; - if (isa(*D) && + if (isa(*D) && cast(*D)->isThisDeclarationADefinition()) Terminator = 0; else if (isa(*D) && cast(*D)->getBody()) Terminator = 0; else if (isa(*D) || isa(*D) || - isa(*D) || + isa(*D) || isa(*D) || isa(*D) || isa(*D) || @@ -299,7 +299,7 @@ void DeclPrinter::VisitRecordDecl(RecordDecl *D) { Out << " "; Out << D->getNameAsString(); } - + if (D->isDefinition()) { Out << " {\n"; VisitDeclContext(D); @@ -315,7 +315,7 @@ void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) { } } -void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { +void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { if (!Policy.SuppressSpecifiers) { switch (D->getStorageClass()) { case FunctionDecl::None: break; @@ -346,7 +346,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { if (i) POut << ", "; ParamPrinter.VisitParmVarDecl(D->getParamDecl(i)); } - + if (FT->isVariadic()) { if (D->getNumParams()) POut << ", "; POut << "..."; @@ -367,29 +367,29 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { Proto += " : "; Out << Proto; Proto.clear(); - for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(), + for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(), E = CDecl->init_end(); B != E; ++B) { CXXBaseOrMemberInitializer * BMInitializer = (*B); if (B != CDecl->init_begin()) Out << ", "; - bool hasArguments = (BMInitializer->arg_begin() != + bool hasArguments = (BMInitializer->arg_begin() != BMInitializer->arg_end()); if (BMInitializer->isMemberInitializer()) { FieldDecl *FD = BMInitializer->getMember(); Out << FD->getNameAsString(); } else // FIXME. skip dependent types for now. - if (const RecordType *RT = + if (const RecordType *RT = BMInitializer->getBaseClass()->getAs()) { - const CXXRecordDecl *BaseDecl = + const CXXRecordDecl *BaseDecl = cast(RT->getDecl()); Out << BaseDecl->getNameAsString(); } if (hasArguments) { Out << "("; - for (CXXBaseOrMemberInitializer::const_arg_iterator BE = - BMInitializer->const_arg_begin(), + for (CXXBaseOrMemberInitializer::const_arg_iterator BE = + BMInitializer->const_arg_begin(), EE = BMInitializer->const_arg_end(); BE != EE; ++BE) { if (BE != BMInitializer->const_arg_begin()) Out<< ", "; @@ -407,7 +407,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { // List order of base/member destruction for visualization purposes. assert (D->isThisDeclarationADefinition() && "Destructor with dtor-list"); Proto += "/* : "; - for (CXXDestructorDecl::destr_const_iterator *B = DDecl->destr_begin(), + for (CXXDestructorDecl::destr_const_iterator *B = DDecl->destr_begin(), *E = DDecl->destr_end(); B != E; ++B) { uintptr_t BaseOrMember = (*B); @@ -420,10 +420,10 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { Proto += FD->getNameAsString(); } else // FIXME. skip dependent types for now. - if (const RecordType *RT = + if (const RecordType *RT = DDecl->getAnyBaseClassToDestroy(BaseOrMember) ->getAs()) { - const CXXRecordDecl *BaseDecl = + const CXXRecordDecl *BaseDecl = cast(RT->getDecl()); Proto += "~"; Proto += BaseDecl->getNameAsString(); @@ -522,7 +522,7 @@ void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) { // C++ declarations //---------------------------------------------------------------------------- void DeclPrinter::VisitOverloadedFunctionDecl(OverloadedFunctionDecl *D) { - assert(false && + assert(false && "OverloadedFunctionDecls aren't really decls and are never printed"); } @@ -552,14 +552,13 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { Out << " "; Out << D->getNameAsString(); } - + if (D->isDefinition()) { // Print the base classes if (D->getNumBases()) { Out << " : "; - for(CXXRecordDecl::base_class_iterator Base = D->bases_begin(), - BaseEnd = D->bases_end(); - Base != BaseEnd; ++Base) { + for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), + BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { if (Base != D->bases_begin()) Out << ", "; @@ -578,7 +577,7 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { Out << " {\n"; VisitDeclContext(D); Indent() << "}"; - } + } } void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { @@ -602,17 +601,17 @@ void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { void DeclPrinter::VisitTemplateDecl(TemplateDecl *D) { Out << "template <"; - + TemplateParameterList *Params = D->getTemplateParameters(); for (unsigned i = 0, e = Params->size(); i != e; ++i) { if (i != 0) Out << ", "; - + const Decl *Param = Params->getParam(i); - if (const TemplateTypeParmDecl *TTP = + if (const TemplateTypeParmDecl *TTP = dyn_cast(Param)) { - - QualType ParamType = + + QualType ParamType = Context.getTypeDeclType(const_cast(TTP)); if (TTP->wasDeclaredWithTypename()) @@ -622,14 +621,14 @@ void DeclPrinter::VisitTemplateDecl(TemplateDecl *D) { if (TTP->isParameterPack()) Out << "... "; - + Out << ParamType.getAsString(Policy); if (TTP->hasDefaultArgument()) { Out << " = "; Out << TTP->getDefaultArgument().getAsString(Policy); }; - } else if (const NonTypeTemplateParmDecl *NTTP = + } else if (const NonTypeTemplateParmDecl *NTTP = dyn_cast(Param)) { Out << NTTP->getType().getAsString(Policy); @@ -637,15 +636,15 @@ void DeclPrinter::VisitTemplateDecl(TemplateDecl *D) { Out << ' '; Out << Name->getName(); } - + if (NTTP->hasDefaultArgument()) { Out << " = "; - NTTP->getDefaultArgument()->printPretty(Out, Context, 0, Policy, + NTTP->getDefaultArgument()->printPretty(Out, Context, 0, Policy, Indentation); } } } - + Out << "> "; Visit(D->getTemplatedDecl()); @@ -667,29 +666,29 @@ void DeclPrinter::VisitObjCClassDecl(ObjCClassDecl *D) { void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { if (OMD->isInstanceMethod()) Out << "- "; - else + else Out << "+ "; if (!OMD->getResultType().isNull()) Out << '(' << OMD->getResultType().getAsString(Policy) << ")"; - + std::string name = OMD->getSelector().getAsString(); std::string::size_type pos, lastPos = 0; for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), E = OMD->param_end(); PI != E; ++PI) { - // FIXME: selector is missing here! + // FIXME: selector is missing here! pos = name.find_first_of(":", lastPos); Out << " " << name.substr(lastPos, pos - lastPos); Out << ":(" << (*PI)->getType().getAsString(Policy) << ")" - << (*PI)->getNameAsString(); + << (*PI)->getNameAsString(); lastPos = pos + 1; } - + if (OMD->param_begin() == OMD->param_end()) Out << " " << name; - + if (OMD->isVariadic()) Out << ", ..."; - + if (OMD->getBody()) { Out << ' '; OMD->getBody()->printPretty(Out, Context, 0, Policy); @@ -718,7 +717,7 @@ void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { Out << "@interface " << I << " : " << SID->getNameAsString(); else Out << "@interface " << I; - + // Protocols? const ObjCList &Protocols = OID->getReferencedProtocols(); if (!Protocols.empty()) { @@ -726,22 +725,22 @@ void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { E = Protocols.end(); I != E; ++I) Out << (I == Protocols.begin() ? '<' : ',') << (*I)->getNameAsString(); } - + if (!Protocols.empty()) Out << "> "; - + if (OID->ivar_size() > 0) { Out << "{\n"; Indentation += Policy.Indentation; for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(), E = OID->ivar_end(); I != E; ++I) { Indent() << (*I)->getType().getAsString(Policy) - << ' ' << (*I)->getNameAsString() << ";\n"; + << ' ' << (*I)->getNameAsString() << ";\n"; } Indentation -= Policy.Indentation; Out << "}\n"; } - + VisitDeclContext(OID, false); Out << "@end"; // FIXME: implement the rest... @@ -749,7 +748,7 @@ void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { void DeclPrinter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { Out << "@protocol "; - for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(), + for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(), E = D->protocol_end(); I != E; ++I) { if (I != D->protocol_begin()) Out << ", "; @@ -766,7 +765,7 @@ void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) { Out << "@implementation " << PID->getClassInterface()->getNameAsString() - << '(' << PID->getNameAsString() << ")\n"; + << '(' << PID->getNameAsString() << ")\n"; VisitDeclContext(PID, false); Out << "@end"; @@ -774,18 +773,18 @@ void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) { } void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) { - Out << "@interface " + Out << "@interface " << PID->getClassInterface()->getNameAsString() << '(' << PID->getNameAsString() << ")\n"; VisitDeclContext(PID, false); Out << "@end"; - + // FIXME: implement the rest... } void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) { - Out << "@compatibility_alias " << AID->getNameAsString() - << ' ' << AID->getClassInterface()->getNameAsString() << ";\n"; + Out << "@compatibility_alias " << AID->getNameAsString() + << ' ' << AID->getClassInterface()->getNameAsString() << ";\n"; } /// PrintObjCPropertyDecl - print a property declaration. @@ -795,17 +794,17 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { Out << "@required\n"; else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional) Out << "@optional\n"; - + Out << "@property"; if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) { bool first = true; Out << " ("; - if (PDecl->getPropertyAttributes() & + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly) { Out << (first ? ' ' : ',') << "readonly"; first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { Out << (first ? ' ' : ',') << "getter = " << PDecl->getGetterName().getAsString(); @@ -816,29 +815,29 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { << PDecl->getSetterName().getAsString(); first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) { Out << (first ? ' ' : ',') << "assign"; first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) { Out << (first ? ' ' : ',') << "readwrite"; first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) { Out << (first ? ' ' : ',') << "retain"; first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) { Out << (first ? ' ' : ',') << "copy"; first = false; } - - if (PDecl->getPropertyAttributes() & + + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) { Out << (first ? ' ' : ',') << "nonatomic"; first = false; diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp index 08e53eb0889ea1098bf2bfc8054260d17976d7b7..b46f6275d33c2b3602f15afd11470b9c73b5a590 100644 --- a/clang/lib/AST/DeclTemplate.cpp +++ b/clang/lib/AST/DeclTemplate.cpp @@ -40,26 +40,26 @@ TemplateParameterList::Create(ASTContext &C, SourceLocation TemplateLoc, unsigned Size = sizeof(TemplateParameterList) + sizeof(Decl *) * NumParams; unsigned Align = llvm::AlignOf::Alignment; void *Mem = C.Allocate(Size, Align); - return new (Mem) TemplateParameterList(TemplateLoc, LAngleLoc, Params, + return new (Mem) TemplateParameterList(TemplateLoc, LAngleLoc, Params, NumParams, RAngleLoc); } unsigned TemplateParameterList::getMinRequiredArguments() const { unsigned NumRequiredArgs = size(); - iterator Param = const_cast(this)->end(), + iterator Param = const_cast(this)->end(), ParamBegin = const_cast(this)->begin(); while (Param != ParamBegin) { --Param; - + if (!(*Param)->isTemplateParameterPack() && - !(isa(*Param) && + !(isa(*Param) && cast(*Param)->hasDefaultArgument()) && !(isa(*Param) && cast(*Param)->hasDefaultArgument()) && !(isa(*Param) && cast(*Param)->hasDefaultArgument())) break; - + --NumRequiredArgs; } @@ -94,7 +94,7 @@ void FunctionTemplateDecl::Destroy(ASTContext &C) { Spec != SpecEnd; ++Spec) C.Deallocate(&*Spec); } - + Decl::Destroy(C); } @@ -110,7 +110,7 @@ FunctionTemplateDecl::Common *FunctionTemplateDecl::getCommonPtr() { FunctionTemplateDecl *First = this; while (First->getPreviousDeclaration()) First = First->getPreviousDeclaration(); - + if (First->CommonOrPrev.isNull()) { // FIXME: Allocate with the ASTContext First->CommonOrPrev = new Common; @@ -142,7 +142,7 @@ ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext &C, else CommonPtr = new (C) Common; - return new (C) ClassTemplateDecl(DC, L, Name, Params, Decl, PrevDecl, + return new (C) ClassTemplateDecl(DC, L, Name, Params, Decl, PrevDecl, CommonPtr); } @@ -172,7 +172,7 @@ ClassTemplateDecl::findPartialSpecialization(QualType T) { if (Context.hasSameType(Context.getTypeDeclType(&*P), T)) return &*P; } - + return 0; } @@ -188,21 +188,21 @@ QualType ClassTemplateDecl::getInjectedClassNameType(ASTContext &Context) { TemplateParameterList *Params = getTemplateParameters(); llvm::SmallVector TemplateArgs; TemplateArgs.reserve(Params->size()); - for (TemplateParameterList::iterator Param = Params->begin(), - ParamEnd = Params->end(); + for (TemplateParameterList::iterator Param = Params->begin(), + ParamEnd = Params->end(); Param != ParamEnd; ++Param) { if (isa(*Param)) { QualType ParamType = Context.getTypeDeclType(cast(*Param)); - TemplateArgs.push_back(TemplateArgument((*Param)->getLocation(), + TemplateArgs.push_back(TemplateArgument((*Param)->getLocation(), ParamType)); - } else if (NonTypeTemplateParmDecl *NTTP = + } else if (NonTypeTemplateParmDecl *NTTP = dyn_cast(*Param)) { Expr *E = new (Context) DeclRefExpr(NTTP, NTTP->getType(), NTTP->getLocation(), NTTP->getType()->isDependentType(), /*Value-dependent=*/true); TemplateArgs.push_back(TemplateArgument(E)); - } else { + } else { TemplateTemplateParmDecl *TTP = cast(*Param); TemplateArgs.push_back(TemplateArgument(TTP->getLocation(), TTP)); } @@ -242,7 +242,7 @@ NonTypeTemplateParmDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation NonTypeTemplateParmDecl::getDefaultArgumentLoc() const { return DefaultArgument? DefaultArgument->getSourceRange().getBegin() - : SourceLocation(); + : SourceLocation(); } //===----------------------------------------------------------------------===// @@ -259,7 +259,7 @@ TemplateTemplateParmDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation TemplateTemplateParmDecl::getDefaultArgumentLoc() const { return DefaultArgument? DefaultArgument->getSourceRange().getBegin() - : SourceLocation(); + : SourceLocation(); } //===----------------------------------------------------------------------===// @@ -272,10 +272,10 @@ TemplateArgument::TemplateArgument(Expr *E) : Kind(Expression) { } /// \brief Construct a template argument pack. -void TemplateArgument::setArgumentPack(TemplateArgument *args, unsigned NumArgs, +void TemplateArgument::setArgumentPack(TemplateArgument *args, unsigned NumArgs, bool CopyArgs) { assert(isNull() && "Must call setArgumentPack on a null argument"); - + Kind = Pack; Args.NumArgs = NumArgs; Args.CopyArgs = CopyArgs; @@ -283,7 +283,7 @@ void TemplateArgument::setArgumentPack(TemplateArgument *args, unsigned NumArgs, Args.Args = args; return; } - + // FIXME: Allocate in ASTContext Args.Args = new TemplateArgument[NumArgs]; for (unsigned I = 0; I != Args.NumArgs; ++I) @@ -301,21 +301,21 @@ void TemplateArgumentListBuilder::Append(const TemplateArgument& Arg) { assert(Arg.getAsType()->isCanonical() && "Type must be canonical!"); break; } - + assert(NumFlatArgs < MaxFlatArgs && "Argument list builder is full!"); - assert(!StructuredArgs && + assert(!StructuredArgs && "Can't append arguments when an argument pack has been added!"); - + if (!FlatArgs) FlatArgs = new TemplateArgument[MaxFlatArgs]; - + FlatArgs[NumFlatArgs++] = Arg; } void TemplateArgumentListBuilder::BeginPack() { assert(!AddingToPack && "Already adding to pack!"); assert(!StructuredArgs && "Argument list already contains a pack!"); - + AddingToPack = true; PackBeginIndex = NumFlatArgs; } @@ -323,24 +323,24 @@ void TemplateArgumentListBuilder::BeginPack() { void TemplateArgumentListBuilder::EndPack() { assert(AddingToPack && "Not adding to pack!"); assert(!StructuredArgs && "Argument list already contains a pack!"); - + AddingToPack = false; StructuredArgs = new TemplateArgument[MaxStructuredArgs]; - + // First copy the flat entries over to the list (if any) for (unsigned I = 0; I != PackBeginIndex; ++I) { NumStructuredArgs++; StructuredArgs[I] = FlatArgs[I]; } - + // Next, set the pack. TemplateArgument *PackArgs = 0; unsigned NumPackArgs = NumFlatArgs - PackBeginIndex; if (NumPackArgs) PackArgs = &FlatArgs[PackBeginIndex]; - - StructuredArgs[NumStructuredArgs++].setArgumentPack(PackArgs, NumPackArgs, + + StructuredArgs[NumStructuredArgs++].setArgumentPack(PackArgs, NumPackArgs, /*CopyArgs=*/false); } @@ -359,14 +359,14 @@ void TemplateArgumentListBuilder::ReleaseArgs() { TemplateArgumentList::TemplateArgumentList(ASTContext &Context, TemplateArgumentListBuilder &Builder, bool TakeArgs) - : FlatArguments(Builder.getFlatArguments(), TakeArgs), - NumFlatArguments(Builder.flatSize()), + : FlatArguments(Builder.getFlatArguments(), TakeArgs), + NumFlatArguments(Builder.flatSize()), StructuredArguments(Builder.getStructuredArguments(), TakeArgs), NumStructuredArguments(Builder.structuredSize()) { - + if (!TakeArgs) return; - + if (Builder.getStructuredArguments() == Builder.getFlatArguments()) StructuredArguments.setInt(0); Builder.ReleaseArgs(); @@ -385,8 +385,8 @@ ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, ClassTemplateDecl *SpecializedTemplate, TemplateArgumentListBuilder &Builder, ClassTemplateSpecializationDecl *PrevDecl) - : CXXRecordDecl(DK, - SpecializedTemplate->getTemplatedDecl()->getTagKind(), + : CXXRecordDecl(DK, + SpecializedTemplate->getTemplatedDecl()->getTagKind(), DC, L, // FIXME: Should we use DeclarationName for the name of // class template specializations? @@ -396,17 +396,17 @@ ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TemplateArgs(Context, Builder, /*TakeArgs=*/true), SpecializationKind(TSK_Undeclared) { } - + ClassTemplateSpecializationDecl * -ClassTemplateSpecializationDecl::Create(ASTContext &Context, +ClassTemplateSpecializationDecl::Create(ASTContext &Context, DeclContext *DC, SourceLocation L, ClassTemplateDecl *SpecializedTemplate, TemplateArgumentListBuilder &Builder, ClassTemplateSpecializationDecl *PrevDecl) { ClassTemplateSpecializationDecl *Result - = new (Context)ClassTemplateSpecializationDecl(Context, + = new (Context)ClassTemplateSpecializationDecl(Context, ClassTemplateSpecialization, - DC, L, + DC, L, SpecializedTemplate, Builder, PrevDecl); @@ -415,16 +415,16 @@ ClassTemplateSpecializationDecl::Create(ASTContext &Context, } void ClassTemplateSpecializationDecl::Destroy(ASTContext &C) { - if (SpecializedPartialSpecialization *PartialSpec + if (SpecializedPartialSpecialization *PartialSpec = SpecializedTemplate.dyn_cast()) C.Deallocate(PartialSpec); - + CXXRecordDecl::Destroy(C); } ClassTemplateDecl * -ClassTemplateSpecializationDecl::getSpecializedTemplate() const { - if (SpecializedPartialSpecialization *PartialSpec +ClassTemplateSpecializationDecl::getSpecializedTemplate() const { + if (SpecializedPartialSpecialization *PartialSpec = SpecializedTemplate.dyn_cast()) return PartialSpec->PartialSpecialization->getSpecializedTemplate(); return SpecializedTemplate.get(); @@ -441,7 +441,7 @@ Create(ASTContext &Context, DeclContext *DC, SourceLocation L, TemplateArgumentListBuilder &Builder, ClassTemplatePartialSpecializationDecl *PrevDecl) { ClassTemplatePartialSpecializationDecl *Result - = new (Context)ClassTemplatePartialSpecializationDecl(Context, + = new (Context)ClassTemplatePartialSpecializationDecl(Context, DC, L, Params, SpecializedTemplate, Builder, PrevDecl); diff --git a/clang/lib/AST/DeclarationName.cpp b/clang/lib/AST/DeclarationName.cpp index da9f01a9aa8b636101472806b783a019b8bbe01a..a01a89201ae4fef1f404fc9b90e4460485fdb2ee 100644 --- a/clang/lib/AST/DeclarationName.cpp +++ b/clang/lib/AST/DeclarationName.cpp @@ -23,7 +23,7 @@ namespace clang { /// CXXSpecialName - Records the type associated with one of the /// "special" kinds of declaration names in C++, e.g., constructors, /// destructors, and conversion functions. -class CXXSpecialName +class CXXSpecialName : public DeclarationNameExtra, public llvm::FoldingSetNode { public: /// Type - The type associated with this declaration name. @@ -40,7 +40,7 @@ public: }; /// CXXOperatorIdName - Contains extra information for the name of an -/// overloaded operator in C++, such as "operator+. +/// overloaded operator in C++, such as "operator+. class CXXOperatorIdName : public DeclarationNameExtra { public: /// FETokenInfo - Extra information associated with this operator @@ -93,13 +93,13 @@ DeclarationName::NameKind DeclarationName::getNameKind() const { case StoredDeclarationNameExtra: switch (getExtra()->ExtraKindOrNumArgs) { - case DeclarationNameExtra::CXXConstructor: + case DeclarationNameExtra::CXXConstructor: return CXXConstructorName; - case DeclarationNameExtra::CXXDestructor: + case DeclarationNameExtra::CXXDestructor: return CXXDestructorName; - case DeclarationNameExtra::CXXConversionFunction: + case DeclarationNameExtra::CXXConversionFunction: return CXXConversionFunctionName; case DeclarationNameExtra::CXXUsingDirective: @@ -107,7 +107,7 @@ DeclarationName::NameKind DeclarationName::getNameKind() const { default: // Check if we have one of the CXXOperator* enumeration values. - if (getExtra()->ExtraKindOrNumArgs < + if (getExtra()->ExtraKindOrNumArgs < DeclarationNameExtra::CXXUsingDirective) return CXXOperatorName; @@ -159,7 +159,7 @@ std::string DeclarationName::getAsString() const { }; const char *OpName = OperatorNames[getCXXOverloadedOperator()]; assert(OpName && "not an overloaded operator"); - + std::string Result = "operator"; if (OpName[0] >= 'a' && OpName[0] <= 'z') Result += ' '; @@ -193,7 +193,7 @@ QualType DeclarationName::getCXXNameType() const { OverloadedOperatorKind DeclarationName::getCXXOverloadedOperator() const { if (CXXOperatorIdName *CXXOp = getAsCXXOperatorIdName()) { - unsigned value + unsigned value = CXXOp->ExtraKindOrNumArgs - DeclarationNameExtra::CXXConversionFunction; return static_cast(value); } else { @@ -276,7 +276,7 @@ DeclarationNameTable::DeclarationNameTable() { // Initialize the overloaded operator names. CXXOperatorNames = new CXXOperatorIdName[NUM_OVERLOADED_OPERATORS]; for (unsigned Op = 0; Op < NUM_OVERLOADED_OPERATORS; ++Op) { - CXXOperatorNames[Op].ExtraKindOrNumArgs + CXXOperatorNames[Op].ExtraKindOrNumArgs = Op + DeclarationNameExtra::CXXConversionFunction; CXXOperatorNames[Op].FETokenInfo = 0; } @@ -296,18 +296,18 @@ DeclarationNameTable::~DeclarationNameTable() { delete [] CXXOperatorNames; } -DeclarationName -DeclarationNameTable::getCXXSpecialName(DeclarationName::NameKind Kind, +DeclarationName +DeclarationNameTable::getCXXSpecialName(DeclarationName::NameKind Kind, CanQualType Ty) { assert(Kind >= DeclarationName::CXXConstructorName && Kind <= DeclarationName::CXXConversionFunctionName && "Kind must be a C++ special name kind"); - llvm::FoldingSet *SpecialNames + llvm::FoldingSet *SpecialNames = static_cast*>(CXXSpecialNamesImpl); DeclarationNameExtra::ExtraKind EKind; switch (Kind) { - case DeclarationName::CXXConstructorName: + case DeclarationName::CXXConstructorName: EKind = DeclarationNameExtra::CXXConstructor; assert(Ty.getCVRQualifiers() == 0 &&"Constructor type must be unqualified"); break; @@ -340,12 +340,12 @@ DeclarationNameTable::getCXXSpecialName(DeclarationName::NameKind Kind, return DeclarationName(SpecialName); } -DeclarationName +DeclarationName DeclarationNameTable::getCXXOperatorName(OverloadedOperatorKind Op) { return DeclarationName(&CXXOperatorNames[(unsigned)Op]); } -unsigned +unsigned llvm::DenseMapInfo:: getHashValue(clang::DeclarationName N) { return DenseMapInfo::getHashValue(N.getAsOpaquePtr()); diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp index 013a9418f1f7c8d2db9b6fa75a99d066b40debc0..a90b9984d4b867e5e81a52a8c69ab91e909d954e 100644 --- a/clang/lib/AST/Expr.cpp +++ b/clang/lib/AST/Expr.cpp @@ -120,7 +120,7 @@ double FloatingLiteral::getValueAsApproximateDouble() const { StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData, unsigned ByteLength, bool Wide, QualType Ty, - const SourceLocation *Loc, + const SourceLocation *Loc, unsigned NumStrs) { // Allocate enough space for the StringLiteral plus an array of locations for // any concatenated string tokens. @@ -128,7 +128,7 @@ StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData, sizeof(SourceLocation)*(NumStrs-1), llvm::alignof()); StringLiteral *SL = new (Mem) StringLiteral(Ty); - + // OPTIMIZE: could allocate this appended to the StringLiteral. char *AStrData = new (C, 1) char[ByteLength]; memcpy(AStrData, StrData, ByteLength); @@ -191,7 +191,7 @@ const char *UnaryOperator::getOpcodeStr(Opcode Op) { } } -UnaryOperator::Opcode +UnaryOperator::Opcode UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { switch (OO) { default: assert(false && "No unary operator for overloaded function"); @@ -227,11 +227,11 @@ OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation rparenloc) - : Expr(SC, t, + : Expr(SC, t, fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs), fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)), NumArgs(numargs) { - + SubExprs = new (C) Stmt*[numargs+1]; SubExprs[FN] = fn; for (unsigned i = 0; i != numargs; ++i) @@ -255,8 +255,8 @@ CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, RParenLoc = rparenloc; } -CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty) - : Expr(SC, Empty), SubExprs(0), NumArgs(0) { +CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty) + : Expr(SC, Empty), SubExprs(0), NumArgs(0) { SubExprs = new (C) Stmt*[1]; } @@ -281,7 +281,7 @@ FunctionDecl *CallExpr::getDirectCallee() { void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { // No change, just return. if (NumArgs == getNumArgs()) return; - + // If shrinking # arguments, just delete the extras and forgot them. if (NumArgs < getNumArgs()) { for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i) @@ -298,7 +298,7 @@ void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { // Null out new args. for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i) NewSubExprs[i] = 0; - + if (SubExprs) C.Deallocate(SubExprs); SubExprs = NewSubExprs; this->NumArgs = NumArgs; @@ -308,20 +308,20 @@ void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { /// not, return 0. unsigned CallExpr::isBuiltinCall(ASTContext &Context) const { // All simple function calls (e.g. func()) are implicitly cast to pointer to - // function. As a result, we try and obtain the DeclRefExpr from the + // function. As a result, we try and obtain the DeclRefExpr from the // ImplicitCastExpr. const ImplicitCastExpr *ICE = dyn_cast(getCallee()); if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()). return 0; - + const DeclRefExpr *DRE = dyn_cast(ICE->getSubExpr()); if (!DRE) return 0; - + const FunctionDecl *FDecl = dyn_cast(DRE->getDecl()); if (!FDecl) return 0; - + if (!FDecl->getIdentifier()) return 0; @@ -334,18 +334,18 @@ QualType CallExpr::getCallReturnType() const { CalleeType = FnTypePtr->getPointeeType(); else if (const BlockPointerType *BPT = CalleeType->getAs()) CalleeType = BPT->getPointeeType(); - + const FunctionType *FnType = CalleeType->getAsFunctionType(); return FnType->getResultType(); } -MemberExpr::MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual, - SourceRange qualrange, NamedDecl *memberdecl, +MemberExpr::MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual, + SourceRange qualrange, NamedDecl *memberdecl, SourceLocation l, bool has_explicit, SourceLocation langle, const TemplateArgument *targs, unsigned numtargs, SourceLocation rangle, QualType ty) - : Expr(MemberExprClass, ty, + : Expr(MemberExprClass, ty, base->isTypeDependent() || (qual && qual->isDependent()), base->isValueDependent() || (qual && qual->isDependent())), Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow), @@ -356,26 +356,26 @@ MemberExpr::MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual, NQ->NNS = qual; NQ->Range = qualrange; } - + // Initialize the explicit template argument list, if any. if (HasExplicitTemplateArgumentList) { - ExplicitTemplateArgumentList *ETemplateArgs + ExplicitTemplateArgumentList *ETemplateArgs = getExplicitTemplateArgumentList(); ETemplateArgs->LAngleLoc = langle; ETemplateArgs->RAngleLoc = rangle; ETemplateArgs->NumTemplateArgs = numtargs; - + TemplateArgument *TemplateArgs = ETemplateArgs->getTemplateArgs(); for (unsigned I = 0; I < numtargs; ++I) - new (TemplateArgs + I) TemplateArgument(targs[I]); + new (TemplateArgs + I) TemplateArgument(targs[I]); } } -MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow, - NestedNameSpecifier *qual, +MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow, + NestedNameSpecifier *qual, SourceRange qualrange, - NamedDecl *memberdecl, - SourceLocation l, + NamedDecl *memberdecl, + SourceLocation l, bool has_explicit, SourceLocation langle, const TemplateArgument *targs, @@ -385,11 +385,11 @@ MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow, std::size_t Size = sizeof(MemberExpr); if (qual != 0) Size += sizeof(NameQualifier); - + if (has_explicit) - Size += sizeof(ExplicitTemplateArgumentList) + + Size += sizeof(ExplicitTemplateArgumentList) + sizeof(TemplateArgument) * numtargs; - + void *Mem = C.Allocate(Size, llvm::alignof()); return new (Mem) MemberExpr(base, isarrow, qual, qualrange, memberdecl, l, has_explicit, langle, targs, numtargs, rangle, @@ -423,7 +423,7 @@ const char *CastExpr::getCastKindName() const { case CastExpr::CK_ConstructorConversion: return "ConstructorConversion"; } - + assert(0 && "Unhandled cast kind!"); return 0; } @@ -469,7 +469,7 @@ const char *BinaryOperator::getOpcodeStr(Opcode Op) { return ""; } -BinaryOperator::Opcode +BinaryOperator::Opcode BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { switch (OO) { default: assert(false && "Not an overloadable binary operator"); @@ -531,13 +531,13 @@ OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { return OverOps[Opc]; } -InitListExpr::InitListExpr(SourceLocation lbraceloc, +InitListExpr::InitListExpr(SourceLocation lbraceloc, Expr **initExprs, unsigned numInits, SourceLocation rbraceloc) : Expr(InitListExprClass, QualType(), hasAnyTypeDependentArguments(initExprs, numInits), hasAnyValueDependentArguments(initExprs, numInits)), - LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0), + LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0), UnionFieldInit(0), HadArrayRangeDesignator(false) { InitExprs.insert(InitExprs.end(), initExprs, initExprs+numInits); @@ -561,7 +561,7 @@ Expr *InitListExpr::updateInit(unsigned Init, Expr *expr) { InitExprs.back() = expr; return 0; } - + Expr *Result = cast_or_null(InitExprs[Init]); InitExprs[Init] = expr; return Result; @@ -574,14 +574,14 @@ const FunctionType *BlockExpr::getFunctionType() const { getPointeeType()->getAsFunctionType(); } -SourceLocation BlockExpr::getCaretLocation() const { - return TheBlock->getCaretLocation(); +SourceLocation BlockExpr::getCaretLocation() const { + return TheBlock->getCaretLocation(); } -const Stmt *BlockExpr::getBody() const { +const Stmt *BlockExpr::getBody() const { return TheBlock->getBody(); } -Stmt *BlockExpr::getBody() { - return TheBlock->getBody(); +Stmt *BlockExpr::getBody() { + return TheBlock->getBody(); } @@ -599,7 +599,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, // instantiating to void. if (isTypeDependent()) return false; - + switch (getStmtClass()) { default: Loc = getExprLoc(); @@ -610,7 +610,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, isUnusedResultAWarning(Loc, R1, R2); case UnaryOperatorClass: { const UnaryOperator *UO = cast(this); - + switch (UO->getOpcode()) { default: break; case UnaryOperator::PostInc: @@ -642,7 +642,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, if (BO->getOpcode() == BinaryOperator::Comma) return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2) || BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2); - + if (BO->isAssignmentOp()) return false; Loc = BO->getOperatorLoc(); @@ -657,7 +657,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, // The condition must be evaluated, but if either the LHS or RHS is a // warning, warn about them. const ConditionalOperator *Exp = cast(this); - if (Exp->getLHS() && + if (Exp->getLHS() && Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2)) return true; return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2); @@ -672,7 +672,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, R1 = SourceRange(Loc, Loc); R2 = cast(this)->getBase()->getSourceRange(); return true; - + case ArraySubscriptExprClass: // If the base pointer or element is to a volatile pointer/field, accessing // it is a side effect. @@ -697,7 +697,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, FD->getAttr() || FD->getAttr()) { Loc = CE->getCallee()->getLocStart(); R1 = CE->getCallee()->getSourceRange(); - + if (unsigned NumArgs = CE->getNumArgs()) R2 = SourceRange(CE->getArg(0)->getLocStart(), CE->getArg(NumArgs-1)->getLocEnd()); @@ -708,10 +708,10 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, } case ObjCMessageExprClass: return false; - + case ObjCImplicitSetterGetterRefExprClass: { // Dot syntax for message send. #if 0 - const ObjCImplicitSetterGetterRefExpr *Ref = + const ObjCImplicitSetterGetterRefExpr *Ref = cast(this); // FIXME: We really want the location of the '.' here. Loc = Ref->getLocation(); @@ -734,7 +734,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, if (!CS->body_empty()) if (const Expr *E = dyn_cast(CS->body_back())) return E->isUnusedResultAWarning(Loc, R1, R2); - + Loc = cast(this)->getLParenLoc(); R1 = getSourceRange(); return true; @@ -756,7 +756,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, Loc = cast(this)->getTypeBeginLoc(); R1 = cast(this)->getSubExpr()->getSourceRange(); return true; - + case ImplicitCastExprClass: // Check the operand, since implicit casts are inserted by Sema return cast(this) @@ -785,7 +785,7 @@ bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, static bool DeclCanBeLvalue(const NamedDecl *Decl, ASTContext &Ctx) { // C++ [temp.param]p6: // A non-type non-reference template-parameter is not an lvalue. - if (const NonTypeTemplateParmDecl *NTTParm + if (const NonTypeTemplateParmDecl *NTTParm = dyn_cast(Decl)) return NTTParm->getType()->isReferenceType(); @@ -838,7 +838,7 @@ Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { if (cast(this)->getBase()->getType()->isVectorType()) return cast(this)->getBase()->isLvalue(Ctx); return LV_Valid; - case DeclRefExprClass: + case DeclRefExprClass: case QualifiedDeclRefExprClass: { // C99 6.5.1p2 const NamedDecl *RefdDecl = cast(this)->getDecl(); if (DeclCanBeLvalue(RefdDecl, Ctx)) @@ -885,7 +885,7 @@ Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { // Not an lvalue. return LV_InvalidExpression; - } + } // C99 6.5.2.3p4 return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx); @@ -905,7 +905,7 @@ Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { return LV_Valid; break; case ImplicitCastExprClass: - return cast(this)->isLvalueCast()? LV_Valid + return cast(this)->isLvalueCast()? LV_Valid : LV_InvalidExpression; case ParenExprClass: // C99 6.5.1p5 return cast(this)->getSubExpr()->isLvalue(Ctx); @@ -927,7 +927,7 @@ Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { return LV_InvalidExpression; if (Ctx.getLangOptions().CPlusPlus) - // C++ [expr.ass]p1: + // C++ [expr.ass]p1: // The result of an assignment operation [...] is an lvalue. return LV_Valid; @@ -936,7 +936,7 @@ Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { // An assignment expression [...] is not an lvalue. return LV_InvalidExpression; } - case CallExprClass: + case CallExprClass: case CXXOperatorCallExprClass: case CXXMemberCallExprClass: { // C++0x [expr.call]p10 @@ -1023,15 +1023,15 @@ Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const { /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, /// does not have an incomplete type, does not have a const-qualified type, and -/// if it is a structure or union, does not have any member (including, +/// if it is a structure or union, does not have any member (including, /// recursively, any member or element of all contained aggregates or unions) /// with a const-qualified type. -Expr::isModifiableLvalueResult +Expr::isModifiableLvalueResult Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const { isLvalueResult lvalResult = isLvalue(Ctx); - + switch (lvalResult) { - case LV_Valid: + case LV_Valid: // C++ 3.10p11: Functions cannot be modified, but pointers to // functions can be modifiable. if (Ctx.getLangOptions().CPlusPlus && TR->isFunctionType()) @@ -1068,27 +1068,27 @@ Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const { } QualType CT = Ctx.getCanonicalType(getType()); - + if (CT.isConstQualified()) return MLV_ConstQualified; if (CT->isArrayType()) return MLV_ArrayType; if (CT->isIncompleteType()) return MLV_IncompleteType; - + if (const RecordType *r = CT->getAs()) { - if (r->hasConstFields()) + if (r->hasConstFields()) return MLV_ConstQualified; } - + // Assigning to an 'implicit' property? else if (isa(this)) { - const ObjCImplicitSetterGetterRefExpr* Expr = + const ObjCImplicitSetterGetterRefExpr* Expr = cast(this); if (Expr->getSetterMethod() == 0) return MLV_NoSetterProperty; } - return MLV_Valid; + return MLV_Valid; } /// isOBJCGCCandidate - Check if an expression is objc gc'able. @@ -1131,7 +1131,7 @@ Expr* Expr::IgnoreParens() { Expr* E = this; while (ParenExpr* P = dyn_cast(E)) E = P->getSubExpr(); - + return E; } @@ -1159,17 +1159,17 @@ Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { E = P->getSubExpr(); continue; } - + if (CastExpr *P = dyn_cast(E)) { // We ignore integer <-> casts that are of the same width, ptr<->ptr and // ptr<->int casts of the same width. We also ignore all identify casts. Expr *SE = P->getSubExpr(); - + if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { E = SE; continue; } - + if ((E->getType()->isPointerType() || E->getType()->isIntegralType()) && (SE->getType()->isPointerType() || SE->getType()->isIntegralType()) && Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { @@ -1177,7 +1177,7 @@ Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { continue; } } - + return E; } } @@ -1233,7 +1233,7 @@ bool Expr::isConstantInitializer(ASTContext &Ctx) const { const InitListExpr *Exp = cast(this); unsigned numInits = Exp->getNumInits(); for (unsigned i = 0; i < numInits; i++) { - if (!Exp->getInit(i)->isConstantInitializer(Ctx)) + if (!Exp->getInit(i)->isConstantInitializer(Ctx)) return false; } return true; @@ -1274,9 +1274,9 @@ bool Expr::isConstantInitializer(ASTContext &Ctx) const { // CheckICE - This function does the fundamental ICE checking: the returned // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. // Note that to reduce code duplication, this helper does no evaluation -// itself; the caller checks whether the expression is evaluatable, and +// itself; the caller checks whether the expression is evaluatable, and // in the rare cases where CheckICE actually cares about the evaluated -// value, it calls into Evalute. +// value, it calls into Evalute. // // Meanings of Val: // 0: This expression is an ICE if it can be evaluated by Evaluate. @@ -1323,7 +1323,7 @@ static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { case Expr::TypesCompatibleExprClass: case Expr::UnaryTypeTraitExprClass: return NoDiag(); - case Expr::CallExprClass: + case Expr::CallExprClass: case Expr::CXXOperatorCallExprClass: { const CallExpr *CE = cast(E); if (CE->isBuiltinCall(Ctx)) @@ -1474,7 +1474,7 @@ static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { } case Expr::ConditionalOperatorClass: { const ConditionalOperator *Exp = cast(E); - // If the condition (ignoring parens) is a __builtin_constant_p call, + // If the condition (ignoring parens) is a __builtin_constant_p call, // then only the true side is actually considered in an integer constant // expression, and it is fully evaluated. This is an important GNU // extension. See GCC PR38377 for discussion. @@ -1535,15 +1535,14 @@ bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, /// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an /// integer constant expression with the value zero, or if this is one that is /// cast to void*. -bool Expr::isNullPointerConstant(ASTContext &Ctx) const -{ +bool Expr::isNullPointerConstant(ASTContext &Ctx) const { // Strip off a cast to void*, if it exists. Except in C++. if (const ExplicitCastExpr *CE = dyn_cast(this)) { if (!Ctx.getLangOptions().CPlusPlus) { // Check that it is a cast to void*. if (const PointerType *PT = CE->getType()->getAs()) { QualType Pointee = PT->getPointeeType(); - if (Pointee.getCVRQualifiers() == 0 && + if (Pointee.getCVRQualifiers() == 0 && Pointee->isVoidType() && // to void* CE->getSubExpr()->getType()->isIntegerType()) // from int. return CE->getSubExpr()->isNullPointerConstant(Ctx); @@ -1556,7 +1555,7 @@ bool Expr::isNullPointerConstant(ASTContext &Ctx) const // Accept ((void*)0) as a null pointer constant, as many other // implementations do. return PE->getSubExpr()->isNullPointerConstant(Ctx); - } else if (const CXXDefaultArgExpr *DefaultArg + } else if (const CXXDefaultArgExpr *DefaultArg = dyn_cast(this)) { // See through default argument expressions return DefaultArg->getExpr()->isNullPointerConstant(Ctx); @@ -1572,7 +1571,7 @@ bool Expr::isNullPointerConstant(ASTContext &Ctx) const // This expression must be an integer type. if (!getType()->isIntegerType()) return false; - + // If we have an integer constant expression, we need to *evaluate* it and // test for the value 0. llvm::APSInt Result; @@ -1612,20 +1611,20 @@ bool ExtVectorElementExpr::containsDuplicateElements() const { unsigned length = Accessor->getLength(); // Halving swizzles do not contain duplicate elements. - if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || + if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || !strcmp(compStr, "even") || !strcmp(compStr, "odd")) return false; - + // Advance past s-char prefix on hex swizzles. if (*compStr == 's' || *compStr == 'S') { compStr++; length--; } - + for (unsigned i = 0; i != length-1; i++) { const char *s = compStr+i; for (const char c = *s++; *s; s++) - if (c == *s) + if (c == *s) return true; } return false; @@ -1637,15 +1636,15 @@ void ExtVectorElementExpr::getEncodedElementAccess( const char *compStr = Accessor->getName(); if (*compStr == 's' || *compStr == 'S') compStr++; - + bool isHi = !strcmp(compStr, "hi"); bool isLo = !strcmp(compStr, "lo"); bool isEven = !strcmp(compStr, "even"); bool isOdd = !strcmp(compStr, "odd"); - + for (unsigned i = 0, e = getNumElements(); i != e; ++i) { uint64_t Index; - + if (isHi) Index = e + i; else if (isLo) @@ -1666,7 +1665,7 @@ ObjCMessageExpr::ObjCMessageExpr(Expr *receiver, Selector selInfo, QualType retType, ObjCMethodDecl *mproto, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned nargs) - : Expr(ObjCMessageExprClass, retType), SelName(selInfo), + : Expr(ObjCMessageExprClass, retType), SelName(selInfo), MethodProto(mproto) { NumArgs = nargs; SubExprs = new Stmt*[NumArgs+1]; @@ -1679,13 +1678,13 @@ ObjCMessageExpr::ObjCMessageExpr(Expr *receiver, Selector selInfo, RBracloc = RBrac; } -// constructor for class messages. +// constructor for class messages. // FIXME: clsName should be typed to ObjCInterfaceType ObjCMessageExpr::ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo, QualType retType, ObjCMethodDecl *mproto, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned nargs) - : Expr(ObjCMessageExprClass, retType), SelName(selInfo), + : Expr(ObjCMessageExprClass, retType), SelName(selInfo), MethodProto(mproto) { NumArgs = nargs; SubExprs = new Stmt*[NumArgs+1]; @@ -1698,12 +1697,12 @@ ObjCMessageExpr::ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo, RBracloc = RBrac; } -// constructor for class messages. +// constructor for class messages. ObjCMessageExpr::ObjCMessageExpr(ObjCInterfaceDecl *cls, Selector selInfo, QualType retType, ObjCMethodDecl *mproto, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned nargs) -: Expr(ObjCMessageExprClass, retType), SelName(selInfo), +: Expr(ObjCMessageExprClass, retType), SelName(selInfo), MethodProto(mproto) { NumArgs = nargs; SubExprs = new Stmt*[NumArgs+1]; @@ -1753,7 +1752,7 @@ void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs, SubExprs = new (C) Stmt* [NumExprs]; this->NumExprs = NumExprs; memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs); -} +} void ShuffleVectorExpr::DoDestroy(ASTContext& C) { DestroyChildren(C); @@ -1788,17 +1787,17 @@ IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() { return getField()->getIdentifier(); } -DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators, +DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators, const Designator *Designators, - SourceLocation EqualOrColonLoc, + SourceLocation EqualOrColonLoc, bool GNUSyntax, - Expr **IndexExprs, + Expr **IndexExprs, unsigned NumIndexExprs, Expr *Init) - : Expr(DesignatedInitExprClass, Ty, + : Expr(DesignatedInitExprClass, Ty, Init->isTypeDependent(), Init->isValueDependent()), - EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), - NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) { + EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), + NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) { this->Designators = new Designator[NumDesignators]; // Record the initializer itself. @@ -1814,7 +1813,7 @@ DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators, if (this->Designators[I].isArrayDesignator()) { // Compute type- and value-dependence. Expr *Index = IndexExprs[IndexIdx]; - ValueDependent = ValueDependent || + ValueDependent = ValueDependent || Index->isTypeDependent() || Index->isValueDependent(); // Copy the index expressions into permanent storage. @@ -1823,7 +1822,7 @@ DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators, // Compute type- and value-dependence. Expr *Start = IndexExprs[IndexIdx]; Expr *End = IndexExprs[IndexIdx + 1]; - ValueDependent = ValueDependent || + ValueDependent = ValueDependent || Start->isTypeDependent() || Start->isValueDependent() || End->isTypeDependent() || End->isValueDependent(); @@ -1837,7 +1836,7 @@ DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators, } DesignatedInitExpr * -DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, +DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, unsigned NumDesignators, Expr **IndexExprs, unsigned NumIndexExprs, SourceLocation ColonOrEqualLoc, @@ -1849,14 +1848,14 @@ DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, IndexExprs, NumIndexExprs, Init); } -DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, +DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, unsigned NumIndexExprs) { void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + sizeof(Stmt *) * (NumIndexExprs + 1), 8); return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); } -void DesignatedInitExpr::setDesignators(const Designator *Desigs, +void DesignatedInitExpr::setDesignators(const Designator *Desigs, unsigned NumDesigs) { if (Designators) delete [] Designators; @@ -1891,7 +1890,7 @@ Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) { } Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) { - assert(D.Kind == Designator::ArrayRangeDesignator && + assert(D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"); char* Ptr = static_cast(static_cast(this)); Ptr += sizeof(DesignatedInitExpr); @@ -1900,7 +1899,7 @@ Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) { } Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) { - assert(D.Kind == Designator::ArrayRangeDesignator && + assert(D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"); char* Ptr = static_cast(static_cast(this)); Ptr += sizeof(DesignatedInitExpr); @@ -1910,8 +1909,8 @@ Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) { /// \brief Replaces the designator at index @p Idx with the series /// of designators in [First, Last). -void DesignatedInitExpr::ExpandDesignator(unsigned Idx, - const Designator *First, +void DesignatedInitExpr::ExpandDesignator(unsigned Idx, + const Designator *First, const Designator *Last) { unsigned NumNewDesignators = Last - First; if (NumNewDesignators == 0) { @@ -1925,7 +1924,7 @@ void DesignatedInitExpr::ExpandDesignator(unsigned Idx, return; } - Designator *NewDesignators + Designator *NewDesignators = new Designator[NumDesignators - 1 + NumNewDesignators]; std::copy(Designators, Designators + Idx, NewDesignators); std::copy(First, Last, NewDesignators + Idx); @@ -1941,14 +1940,14 @@ void DesignatedInitExpr::DoDestroy(ASTContext &C) { Expr::DoDestroy(C); } -ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc, +ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs, unsigned nexprs, SourceLocation rparenloc) : Expr(ParenListExprClass, QualType(), hasAnyTypeDependentArguments(exprs, nexprs), - hasAnyValueDependentArguments(exprs, nexprs)), + hasAnyValueDependentArguments(exprs, nexprs)), NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) { - + Exprs = new (C) Stmt*[nexprs]; for (unsigned i = 0; i != nexprs; ++i) Exprs[i] = exprs[i]; @@ -1991,11 +1990,11 @@ Stmt::child_iterator ObjCPropertyRefExpr::child_begin() { return &Base; } Stmt::child_iterator ObjCPropertyRefExpr::child_end() { return &Base+1; } // ObjCImplicitSetterGetterRefExpr -Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_begin() { - return &Base; +Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_begin() { + return &Base; } -Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_end() { - return &Base+1; +Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_end() { + return &Base+1; } // ObjCSuperExpr @@ -2039,7 +2038,7 @@ Stmt::child_iterator UnaryOperator::child_begin() { return &Val; } Stmt::child_iterator UnaryOperator::child_end() { return &Val+1; } // SizeOfAlignOfExpr -Stmt::child_iterator SizeOfAlignOfExpr::child_begin() { +Stmt::child_iterator SizeOfAlignOfExpr::child_begin() { // If this is of a type and the type is a VLA type (and not a typedef), the // size expression of the VLA needs to be treated as an executable expression. // Why isn't this weirdness documented better in StmtIterator? @@ -2161,12 +2160,12 @@ Stmt::child_iterator DesignatedInitExpr::child_end() { } // ImplicitValueInitExpr -Stmt::child_iterator ImplicitValueInitExpr::child_begin() { - return child_iterator(); +Stmt::child_iterator ImplicitValueInitExpr::child_begin() { + return child_iterator(); } -Stmt::child_iterator ImplicitValueInitExpr::child_end() { - return child_iterator(); +Stmt::child_iterator ImplicitValueInitExpr::child_end() { + return child_iterator(); } // ParenListExpr @@ -2178,7 +2177,7 @@ Stmt::child_iterator ParenListExpr::child_end() { } // ObjCStringLiteral -Stmt::child_iterator ObjCStringLiteral::child_begin() { +Stmt::child_iterator ObjCStringLiteral::child_begin() { return &String; } Stmt::child_iterator ObjCStringLiteral::child_end() { @@ -2190,7 +2189,7 @@ Stmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); } Stmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); } // ObjCSelectorExpr -Stmt::child_iterator ObjCSelectorExpr::child_begin() { +Stmt::child_iterator ObjCSelectorExpr::child_begin() { return child_iterator(); } Stmt::child_iterator ObjCSelectorExpr::child_end() { @@ -2206,7 +2205,7 @@ Stmt::child_iterator ObjCProtocolExpr::child_end() { } // ObjCMessageExpr -Stmt::child_iterator ObjCMessageExpr::child_begin() { +Stmt::child_iterator ObjCMessageExpr::child_begin() { return getReceiver() ? &SubExprs[0] : &SubExprs[0] + ARGS_START; } Stmt::child_iterator ObjCMessageExpr::child_end() { diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp index 7c36caad5851a873a6b6be940a53f7f064eb3d6e..7f39793c04d42818365c1176d1a1c1c3cd2e4bec 100644 --- a/clang/lib/AST/ExprCXX.cpp +++ b/clang/lib/AST/ExprCXX.cpp @@ -30,7 +30,7 @@ Stmt::child_iterator CXXTypeidExpr::child_end() { } // CXXBoolLiteralExpr -Stmt::child_iterator CXXBoolLiteralExpr::child_begin() { +Stmt::child_iterator CXXBoolLiteralExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXBoolLiteralExpr::child_end() { @@ -38,7 +38,7 @@ Stmt::child_iterator CXXBoolLiteralExpr::child_end() { } // CXXNullPtrLiteralExpr -Stmt::child_iterator CXXNullPtrLiteralExpr::child_begin() { +Stmt::child_iterator CXXNullPtrLiteralExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXNullPtrLiteralExpr::child_end() { @@ -65,7 +65,7 @@ Stmt::child_iterator CXXDefaultArgExpr::child_end() { } // CXXZeroInitValueExpr -Stmt::child_iterator CXXZeroInitValueExpr::child_begin() { +Stmt::child_iterator CXXZeroInitValueExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXZeroInitValueExpr::child_end() { @@ -93,8 +93,7 @@ CXXNewExpr::CXXNewExpr(bool globalNew, FunctionDecl *operatorNew, Initializer(initializer), Array(arraySize), NumPlacementArgs(numPlaceArgs), NumConstructorArgs(numConsArgs), OperatorNew(operatorNew), OperatorDelete(operatorDelete), Constructor(constructor), - StartLoc(startLoc), EndLoc(endLoc) -{ + StartLoc(startLoc), EndLoc(endLoc) { unsigned TotalSize = Array + NumPlacementArgs + NumConstructorArgs; SubExprs = new Stmt*[TotalSize]; unsigned i = 0; @@ -123,8 +122,8 @@ Stmt::child_iterator CXXPseudoDestructorExpr::child_end() { } // UnresolvedFunctionNameExpr -Stmt::child_iterator UnresolvedFunctionNameExpr::child_begin() { - return child_iterator(); +Stmt::child_iterator UnresolvedFunctionNameExpr::child_begin() { + return child_iterator(); } Stmt::child_iterator UnresolvedFunctionNameExpr::child_end() { return child_iterator(); @@ -147,16 +146,16 @@ StmtIterator UnresolvedDeclRefExpr::child_end() { } TemplateIdRefExpr::TemplateIdRefExpr(QualType T, - NestedNameSpecifier *Qualifier, + NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - TemplateName Template, + TemplateName Template, SourceLocation TemplateNameLoc, - SourceLocation LAngleLoc, + SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc) : Expr(TemplateIdRefExprClass, T, - (Template.isDependent() || + (Template.isDependent() || TemplateSpecializationType::anyDependentTemplateArguments( TemplateArgs, NumTemplateArgs)), (Template.isDependent() || @@ -164,10 +163,8 @@ TemplateIdRefExpr::TemplateIdRefExpr(QualType T, TemplateArgs, NumTemplateArgs))), Qualifier(Qualifier), QualifierRange(QualifierRange), Template(Template), TemplateNameLoc(TemplateNameLoc), LAngleLoc(LAngleLoc), - RAngleLoc(RAngleLoc), NumTemplateArgs(NumTemplateArgs) - -{ - TemplateArgument *StoredTemplateArgs + RAngleLoc(RAngleLoc), NumTemplateArgs(NumTemplateArgs) { + TemplateArgument *StoredTemplateArgs = reinterpret_cast (this+1); for (unsigned I = 0; I != NumTemplateArgs; ++I) new (StoredTemplateArgs + I) TemplateArgument(TemplateArgs[I]); @@ -175,10 +172,10 @@ TemplateIdRefExpr::TemplateIdRefExpr(QualType T, TemplateIdRefExpr * TemplateIdRefExpr::Create(ASTContext &Context, QualType T, - NestedNameSpecifier *Qualifier, + NestedNameSpecifier *Qualifier, SourceRange QualifierRange, TemplateName Template, SourceLocation TemplateNameLoc, - SourceLocation LAngleLoc, + SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc) { void *Mem = Context.Allocate(sizeof(TemplateIdRefExpr) + @@ -298,7 +295,7 @@ SourceRange CXXOperatorCallExpr::getSourceRange() const { if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) { if (getNumArgs() == 1) // Prefix operator - return SourceRange(getOperatorLoc(), + return SourceRange(getOperatorLoc(), getArg(0)->getSourceRange().getEnd()); else // Postfix operator @@ -343,7 +340,7 @@ const char *CXXNamedCastExpr::getCastName() const { } } -CXXTemporary *CXXTemporary::Create(ASTContext &C, +CXXTemporary *CXXTemporary::Create(ASTContext &C, const CXXDestructorDecl *Destructor) { return new (C) CXXTemporary(Destructor); } @@ -353,10 +350,10 @@ void CXXTemporary::Destroy(ASTContext &Ctx) { Ctx.Deallocate(this); } -CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(ASTContext &C, +CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(ASTContext &C, CXXTemporary *Temp, Expr* SubExpr) { - assert(SubExpr->getType()->isRecordType() && + assert(SubExpr->getType()->isRecordType() && "Expression bound to a temporary must have record type!"); return new (C) CXXBindTemporaryExpr(Temp, SubExpr); @@ -371,46 +368,46 @@ void CXXBindTemporaryExpr::DoDestroy(ASTContext &C) { CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(ASTContext &C, CXXConstructorDecl *Cons, QualType writtenTy, - SourceLocation tyBeginLoc, + SourceLocation tyBeginLoc, Expr **Args, - unsigned NumArgs, + unsigned NumArgs, SourceLocation rParenLoc) - : CXXConstructExpr(C, CXXTemporaryObjectExprClass, writtenTy, Cons, - false, Args, NumArgs), + : CXXConstructExpr(C, CXXTemporaryObjectExprClass, writtenTy, Cons, + false, Args, NumArgs), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) { } -CXXConstructExpr *CXXConstructExpr::Create(ASTContext &C, QualType T, +CXXConstructExpr *CXXConstructExpr::Create(ASTContext &C, QualType T, CXXConstructorDecl *D, bool Elidable, Expr **Args, unsigned NumArgs) { - return new (C) CXXConstructExpr(C, CXXConstructExprClass, T, D, Elidable, + return new (C) CXXConstructExpr(C, CXXConstructExprClass, T, D, Elidable, Args, NumArgs); } -CXXConstructExpr::CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T, +CXXConstructExpr::CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T, CXXConstructorDecl *D, bool elidable, - Expr **args, unsigned numargs) + Expr **args, unsigned numargs) : Expr(SC, T, T->isDependentType(), (T->isDependentType() || CallExpr::hasAnyValueDependentArguments(args, numargs))), Constructor(D), Elidable(elidable), Args(0), NumArgs(numargs) { // leave room for default arguments; - const FunctionProtoType *FTy = + const FunctionProtoType *FTy = cast(D)->getType()->getAsFunctionProtoType(); - + unsigned NumArgsInProto = FTy->getNumArgs(); unsigned NumArgsToAllocate = FTy->isVariadic() ? NumArgs : NumArgsInProto; if (NumArgsToAllocate) { Args = new (C) Stmt*[NumArgsToAllocate]; - + for (unsigned i = 0; i != NumArgs; ++i) Args[i] = args[i]; - + // Set default arguments to 0. for (unsigned i = NumArgs; i != NumArgsToAllocate; ++i) Args[i] = 0; - + NumArgs = NumArgsToAllocate; } } @@ -423,13 +420,13 @@ void CXXConstructExpr::DoDestroy(ASTContext &C) { C.Deallocate(this); } -CXXExprWithTemporaries::CXXExprWithTemporaries(Expr *subexpr, - CXXTemporary **temps, +CXXExprWithTemporaries::CXXExprWithTemporaries(Expr *subexpr, + CXXTemporary **temps, unsigned numtemps, bool shoulddestroytemps) : Expr(CXXExprWithTemporariesClass, subexpr->getType(), - subexpr->isTypeDependent(), subexpr->isValueDependent()), - SubExpr(subexpr), Temps(0), NumTemps(numtemps), + subexpr->isTypeDependent(), subexpr->isValueDependent()), + SubExpr(subexpr), Temps(0), NumTemps(numtemps), ShouldDestroyTemps(shoulddestroytemps) { if (NumTemps > 0) { Temps = new CXXTemporary*[NumTemps]; @@ -438,12 +435,12 @@ CXXExprWithTemporaries::CXXExprWithTemporaries(Expr *subexpr, } } -CXXExprWithTemporaries *CXXExprWithTemporaries::Create(ASTContext &C, +CXXExprWithTemporaries *CXXExprWithTemporaries::Create(ASTContext &C, Expr *SubExpr, - CXXTemporary **Temps, + CXXTemporary **Temps, unsigned NumTemps, bool ShouldDestroyTemps){ - return new (C) CXXExprWithTemporaries(SubExpr, Temps, NumTemps, + return new (C) CXXExprWithTemporaries(SubExpr, Temps, NumTemps, ShouldDestroyTemps); } @@ -462,7 +459,7 @@ Stmt::child_iterator CXXBindTemporaryExpr::child_begin() { return &SubExpr; } -Stmt::child_iterator CXXBindTemporaryExpr::child_end() { +Stmt::child_iterator CXXBindTemporaryExpr::child_end() { return &SubExpr + 1; } @@ -479,7 +476,7 @@ Stmt::child_iterator CXXExprWithTemporaries::child_begin() { return &SubExpr; } -Stmt::child_iterator CXXExprWithTemporaries::child_end() { +Stmt::child_iterator CXXExprWithTemporaries::child_end() { return &SubExpr + 1; } @@ -502,7 +499,7 @@ CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr( } CXXUnresolvedConstructExpr * -CXXUnresolvedConstructExpr::Create(ASTContext &C, +CXXUnresolvedConstructExpr::Create(ASTContext &C, SourceLocation TyBegin, QualType T, SourceLocation LParenLoc, @@ -523,8 +520,8 @@ Stmt::child_iterator CXXUnresolvedConstructExpr::child_end() { return child_iterator(reinterpret_cast(this + 1) + NumArgs); } -CXXUnresolvedMemberExpr::CXXUnresolvedMemberExpr(ASTContext &C, - Expr *Base, bool IsArrow, +CXXUnresolvedMemberExpr::CXXUnresolvedMemberExpr(ASTContext &C, + Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, @@ -537,29 +534,28 @@ CXXUnresolvedMemberExpr::CXXUnresolvedMemberExpr(ASTContext &C, unsigned NumTemplateArgs, SourceLocation RAngleLoc) : Expr(CXXUnresolvedMemberExprClass, C.DependentTy, true, true), - Base(Base), IsArrow(IsArrow), + Base(Base), IsArrow(IsArrow), HasExplicitTemplateArgumentList(HasExplicitTemplateArgs), OperatorLoc(OperatorLoc), Qualifier(Qualifier), QualifierRange(QualifierRange), FirstQualifierFoundInScope(FirstQualifierFoundInScope), - Member(Member), MemberLoc(MemberLoc) -{ + Member(Member), MemberLoc(MemberLoc) { if (HasExplicitTemplateArgumentList) { - ExplicitTemplateArgumentList *ETemplateArgs + ExplicitTemplateArgumentList *ETemplateArgs = getExplicitTemplateArgumentList(); ETemplateArgs->LAngleLoc = LAngleLoc; ETemplateArgs->RAngleLoc = RAngleLoc; ETemplateArgs->NumTemplateArgs = NumTemplateArgs; - + TemplateArgument *SavedTemplateArgs = ETemplateArgs->getTemplateArgs(); for (unsigned I = 0; I < NumTemplateArgs; ++I) - new (SavedTemplateArgs + I) TemplateArgument(TemplateArgs[I]); + new (SavedTemplateArgs + I) TemplateArgument(TemplateArgs[I]); } } CXXUnresolvedMemberExpr * -CXXUnresolvedMemberExpr::Create(ASTContext &C, - Expr *Base, bool IsArrow, +CXXUnresolvedMemberExpr::Create(ASTContext &C, + Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, @@ -570,16 +566,15 @@ CXXUnresolvedMemberExpr::Create(ASTContext &C, SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, - SourceLocation RAngleLoc) -{ + SourceLocation RAngleLoc) { if (!HasExplicitTemplateArgs) return new (C) CXXUnresolvedMemberExpr(C, Base, IsArrow, OperatorLoc, Qualifier, QualifierRange, FirstQualifierFoundInScope, Member, MemberLoc); - + void *Mem = C.Allocate(sizeof(CXXUnresolvedMemberExpr) + - sizeof(ExplicitTemplateArgumentList) + + sizeof(ExplicitTemplateArgumentList) + sizeof(TemplateArgument) * NumTemplateArgs, llvm::alignof()); return new (Mem) CXXUnresolvedMemberExpr(C, Base, IsArrow, OperatorLoc, diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 7d281494d6966f2ae675ce41dbc7c703b882a170..4494896d2c450e98ef48a1da70cdd80bb8ec2a10 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -42,11 +42,11 @@ using llvm::APFloat; /// certain things in certain situations. struct EvalInfo { ASTContext &Ctx; - + /// EvalResult - Contains information about the evaluation. Expr::EvalResult &EvalResult; - EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx), + EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx), EvalResult(evalresult) {} }; @@ -104,12 +104,12 @@ static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) { return false; } -static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, +static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, APFloat &Value, ASTContext &Ctx) { unsigned DestWidth = Ctx.getIntWidth(DestType); // Determine whether we are converting to unsigned or signed. bool DestSigned = DestType->isSignedIntegerType(); - + // FIXME: Warning for overflow. uint64_t Space[4]; bool ignored; @@ -118,16 +118,16 @@ static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned); } -static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType, +static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType, APFloat &Value, ASTContext &Ctx) { bool ignored; APFloat Result = Value; - Result.convert(Ctx.getFloatTypeSemantics(DestType), + Result.convert(Ctx.getFloatTypeSemantics(DestType), APFloat::rmNearestTiesToEven, &ignored); return Result; } -static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, +static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, APSInt &Value, ASTContext &Ctx) { unsigned DestWidth = Ctx.getIntWidth(DestType); APSInt Result = Value; @@ -138,7 +138,7 @@ static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, return Result; } -static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType, +static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType, APSInt &Value, ASTContext &Ctx) { APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1); @@ -155,7 +155,7 @@ class VISIBILITY_HIDDEN LValueExprEvaluator : public StmtVisitor { EvalInfo &Info; public: - + LValueExprEvaluator(EvalInfo &info) : Info(info) {} APValue VisitStmt(Stmt *S) { @@ -185,8 +185,7 @@ static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) { return Result.isLValue(); } -APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) -{ +APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) { if (isa(E->getDecl())) { return APValue(E, 0); } else if (VarDecl* VD = dyn_cast(E->getDecl())) { @@ -202,11 +201,10 @@ APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) return APValue(); } -APValue LValueExprEvaluator::VisitBlockExpr(BlockExpr *E) -{ +APValue LValueExprEvaluator::VisitBlockExpr(BlockExpr *E) { if (E->hasBlockDeclRefExprs()) return APValue(); - + return APValue(E, 0); } @@ -255,13 +253,12 @@ APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) { return result; } -APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) -{ +APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { APValue Result; - + if (!EvaluatePointer(E->getBase(), Result, Info)) return APValue(); - + APSInt Index; if (!EvaluateInteger(E->getIdx(), Index, Info)) return APValue(); @@ -269,13 +266,12 @@ APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8; uint64_t Offset = Index.getSExtValue() * ElementSize; - Result.setLValue(Result.getLValueBase(), + Result.setLValue(Result.getLValueBase(), Result.getLValueOffset() + Offset); return Result; } -APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) -{ +APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) { APValue Result; if (!EvaluatePointer(E->getSubExpr(), Result, Info)) return APValue(); @@ -291,7 +287,7 @@ class VISIBILITY_HIDDEN PointerExprEvaluator : public StmtVisitor { EvalInfo &Info; public: - + PointerExprEvaluator(EvalInfo &info) : Info(info) {} APValue VisitStmt(Stmt *S) { @@ -337,23 +333,23 @@ APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { if (E->getOpcode() != BinaryOperator::Add && E->getOpcode() != BinaryOperator::Sub) return APValue(); - + const Expr *PExp = E->getLHS(); const Expr *IExp = E->getRHS(); if (IExp->getType()->isPointerType()) std::swap(PExp, IExp); - + APValue ResultLValue; if (!EvaluatePointer(PExp, ResultLValue, Info)) return APValue(); - + llvm::APSInt AdditionalOffset(32); if (!EvaluateInteger(IExp, AdditionalOffset, Info)) return APValue(); QualType PointeeType = PExp->getType()->getAs()->getPointeeType(); uint64_t SizeOfPointee; - + // Explicitly handle GNU void* and function pointer arithmetic extensions. if (PointeeType->isVoidType() || PointeeType->isFunctionType()) SizeOfPointee = 1; @@ -376,7 +372,7 @@ APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { return result; return APValue(); } - + APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { const Expr* SubExpr = E->getSubExpr(); @@ -389,7 +385,7 @@ APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { return Result; return APValue(); } - + if (SubExpr->getType()->isIntegralType()) { APValue Result; if (!EvaluateIntegerOrLValue(SubExpr, Result, Info)) @@ -399,7 +395,7 @@ APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType())); return APValue(0, Result.getInt().getZExtValue()); } - + // Cast is of an lvalue, no need to change value. return Result; } @@ -414,10 +410,10 @@ APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { } return APValue(); -} +} APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) { - if (E->isBuiltinCall(Info.Ctx) == + if (E->isBuiltinCall(Info.Ctx) == Builtin::BI__builtin___CFStringMakeConstantString) return APValue(E, 0); return APValue(); @@ -446,13 +442,13 @@ namespace { EvalInfo &Info; APValue GetZeroVector(QualType VecType); public: - + VectorExprEvaluator(EvalInfo &info) : Info(info) {} - + APValue VisitStmt(Stmt *S) { return APValue(); } - + APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } APValue VisitUnaryExtension(const UnaryOperator *E) @@ -490,7 +486,7 @@ APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { QualType EltTy = VTy->getElementType(); unsigned NElts = VTy->getNumElements(); unsigned EltWidth = Info.Ctx.getTypeSize(EltTy); - + const Expr* SE = E->getSubExpr(); QualType SETy = SE->getType(); APValue Result = APValue(); @@ -540,12 +536,12 @@ APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { // element. APSInt Init; Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt(); - + llvm::SmallVector Elts; for (unsigned i = 0; i != NElts; ++i) { APSInt Tmp = Init; Tmp.extOrTrunc(EltWidth); - + if (EltTy->isIntegerType()) Elts.push_back(APValue(Tmp)); else if (EltTy->isRealFloatingType()) @@ -558,17 +554,17 @@ APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { return APValue(&Elts[0], Elts.size()); } -APValue +APValue VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { return this->Visit(const_cast(E->getInitializer())); } -APValue +APValue VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { const VectorType *VT = E->getType()->getAsVectorType(); unsigned NumInits = E->getNumInits(); unsigned NumElements = VT->getNumElements(); - + QualType EltTy = VT->getElementType(); llvm::SmallVector Elements; @@ -596,7 +592,7 @@ VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { return APValue(&Elements[0], Elements.size()); } -APValue +APValue VectorExprEvaluator::GetZeroVector(QualType T) { const VectorType *VT = T->getAsVectorType(); QualType EltTy = VT->getElementType(); @@ -677,20 +673,20 @@ public: } return false; } - + //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// - + bool VisitStmt(Stmt *) { assert(0 && "This should be called on integers, stmts are not integers"); return false; } - + bool VisitExpr(Expr *E) { return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); } - + bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } bool VisitIntegerLiteral(const IntegerLiteral *E) { @@ -705,7 +701,7 @@ public: // be able to strip CRV qualifiers from the type. QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1()); QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2()); - return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(), + return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(), T1.getUnqualifiedType()), E); } @@ -721,11 +717,11 @@ public: bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return Success(E->getValue(), E); } - + bool VisitGNUNullExpr(const GNUNullExpr *E) { return Success(0, E); } - + bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { return Success(0, E); } @@ -755,7 +751,7 @@ private: static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) { if (!E->getType()->isIntegralType()) return false; - + return IntExprEvaluator(Info, Result).Visit(const_cast(E)); } @@ -818,12 +814,12 @@ static int EvaluateBuiltinClassifyType(const CallExpr *E) { array_type_class, string_type_class, lang_type_class }; - - // If no argument was supplied, default to "no_type_class". This isn't + + // If no argument was supplied, default to "no_type_class". This isn't // ideal, however it is what gcc does. if (E->getNumArgs() == 0) return no_type_class; - + QualType ArgTy = E->getArg(0)->getType(); if (ArgTy->isVoidType()) return void_type_class; @@ -864,7 +860,7 @@ bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); case Builtin::BI__builtin_classify_type: return Success(EvaluateBuiltinClassifyType(E), E); - + case Builtin::BI__builtin_constant_p: // __builtin_constant_p always has one operand: it returns true if that // operand can be folded, false otherwise. @@ -889,7 +885,7 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { // These need to be handled specially because the operands aren't // necessarily integral bool lhsResult, rhsResult; - + if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) { // We were able to evaluate the LHS, see if we can get away with not // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 @@ -906,7 +902,7 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { // We can't evaluate the LHS; however, sometimes the result // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. - if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) || + if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) || !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) { // Since we weren't able to evaluate the left hand side, it // must have had side effects. @@ -934,9 +930,9 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { return false; if (LHS.isComplexFloat()) { - APFloat::cmpResult CR_r = + APFloat::cmpResult CR_r = LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); - APFloat::cmpResult CR_i = + APFloat::cmpResult CR_i = LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); if (E->getOpcode() == BinaryOperator::EQ) @@ -945,9 +941,9 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { else { assert(E->getOpcode() == BinaryOperator::NE && "Invalid complex comparison."); - return Success(((CR_r == APFloat::cmpGreaterThan || + return Success(((CR_r == APFloat::cmpGreaterThan || CR_r == APFloat::cmpLessThan) && - (CR_i == APFloat::cmpGreaterThan || + (CR_i == APFloat::cmpGreaterThan || CR_i == APFloat::cmpLessThan)), E); } } else { @@ -962,17 +958,17 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { } } } - + if (LHSTy->isRealFloatingType() && RHSTy->isRealFloatingType()) { APFloat RHS(0.0), LHS(0.0); - + if (!EvaluateFloat(E->getRHS(), RHS, Info)) return false; - + if (!EvaluateFloat(E->getLHS(), LHS, Info)) return false; - + APFloat::cmpResult CR = LHS.compare(RHS); switch (E->getOpcode()) { @@ -985,16 +981,16 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { case BinaryOperator::LE: return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); case BinaryOperator::GE: - return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, + return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, E); case BinaryOperator::EQ: return Success(CR == APFloat::cmpEqual, E); case BinaryOperator::NE: - return Success(CR == APFloat::cmpGreaterThan + return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan, E); } } - + if (LHSTy->isPointerType() && RHSTy->isPointerType()) { if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) { APValue LHSValue; @@ -1106,16 +1102,16 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { return Success(Result.getInt() % RHS, E); case BinaryOperator::Shl: { // FIXME: Warn about out of range shift amounts! - unsigned SA = + unsigned SA = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1); return Success(Result.getInt() << SA, E); } case BinaryOperator::Shr: { - unsigned SA = + unsigned SA = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1); return Success(Result.getInt() >> SA, E); } - + case BinaryOperator::LT: return Success(Result.getInt() < RHS, E); case BinaryOperator::GT: return Success(Result.getInt() > RHS, E); case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E); @@ -1145,7 +1141,7 @@ unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) { E = E->IgnoreParens(); // alignof decl is always accepted, even if it doesn't make sense: we default - // to 1 in those cases. + // to 1 in those cases. if (const DeclRefExpr *DRE = dyn_cast(E)) return Info.Ctx.getDeclAlignInBytes(DRE->getDecl()); @@ -1225,7 +1221,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { // If so, we could clear the diagnostic ID. return true; case UnaryOperator::Plus: - // The result is always just the subexpr. + // The result is always just the subexpr. return true; case UnaryOperator::Minus: if (!Result.isInt()) return false; @@ -1235,7 +1231,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { return Success(~Result.getInt(), E); } } - + /// HandleCast - This is used to evaluate implicit or explicit casts where the /// result type is integer. bool IntExprEvaluator::VisitCastExpr(CastExpr *E) { @@ -1263,7 +1259,7 @@ bool IntExprEvaluator::VisitCastExpr(CastExpr *E) { return Success(HandleIntToIntCast(DestType, SrcType, Result.getInt(), Info.Ctx), E); } - + // FIXME: Clean this up! if (SrcType->isPointerType()) { APValue LV; @@ -1317,7 +1313,7 @@ bool IntExprEvaluator::VisitCastExpr(CastExpr *E) { APFloat F(0.0); if (!EvaluateFloat(SubExpr, F, Info)) return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); - + return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E); } @@ -1400,13 +1396,13 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { Result = llvm::APFloat::getInf(Sem); return true; } - + case Builtin::BI__builtin_nan: case Builtin::BI__builtin_nanf: case Builtin::BI__builtin_nanl: // If this is __builtin_nan() turn this into a nan, otherwise we // can't constant fold it. - if (const StringLiteral *S = + if (const StringLiteral *S = dyn_cast(E->getArg(0)->IgnoreParenCasts())) { if (!S->isWide()) { const llvm::fltSemantics &Sem = @@ -1431,13 +1427,13 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { case Builtin::BI__builtin_fabsl: if (!EvaluateFloat(E->getArg(0), Result, Info)) return false; - + if (Result.isNegative()) Result.changeSign(); return true; - case Builtin::BI__builtin_copysign: - case Builtin::BI__builtin_copysignf: + case Builtin::BI__builtin_copysign: + case Builtin::BI__builtin_copysignf: case Builtin::BI__builtin_copysignl: { APFloat RHS(0.); if (!EvaluateFloat(E->getArg(0), Result, Info) || @@ -1458,7 +1454,7 @@ bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { switch (E->getOpcode()) { default: return false; - case UnaryOperator::Plus: + case UnaryOperator::Plus: return true; case UnaryOperator::Minus: Result.changeSign(); @@ -1499,12 +1495,12 @@ bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) { Expr* SubExpr = E->getSubExpr(); - + if (SubExpr->getType()->isIntegralType()) { APSInt IntResult; if (!EvaluateInteger(SubExpr, IntResult, Info)) return false; - Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(), + Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(), IntResult, Info.Ctx); return true; } @@ -1533,10 +1529,10 @@ namespace { class VISIBILITY_HIDDEN ComplexExprEvaluator : public StmtVisitor { EvalInfo &Info; - + public: ComplexExprEvaluator(EvalInfo &info) : Info(info) {} - + //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// @@ -1544,7 +1540,7 @@ public: APValue VisitStmt(Stmt *S) { return APValue(); } - + APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } APValue VisitImaginaryLiteral(ImaginaryLiteral *E) { @@ -1555,17 +1551,17 @@ public: if (!EvaluateFloat(SubExpr, Result, Info)) return APValue(); - - return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false), + + return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false), Result); } else { - assert(SubExpr->getType()->isIntegerType() && + assert(SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal."); llvm::APSInt Result; if (!EvaluateInteger(SubExpr, Result, Info)) return APValue(); - + llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned()); Zero = 0; return APValue(Zero, Result); @@ -1585,7 +1581,7 @@ public: if (EltType->isRealFloatingType()) { Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx); - return APValue(Result, + return APValue(Result, APFloat(Result.getSemantics(), APFloat::fcZero, false)); } else { llvm::APSInt IResult; @@ -1603,7 +1599,7 @@ public: if (EltType->isRealFloatingType()) { APFloat FResult = HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx); - return APValue(FResult, + return APValue(FResult, APFloat(FResult.getSemantics(), APFloat::fcZero, false)); } else { Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx); @@ -1621,36 +1617,36 @@ public: if (Src.isComplexFloat()) { if (EltType->isRealFloatingType()) { - return APValue(HandleFloatToFloatCast(EltType, SrcType, + return APValue(HandleFloatToFloatCast(EltType, SrcType, Src.getComplexFloatReal(), Info.Ctx), - HandleFloatToFloatCast(EltType, SrcType, + HandleFloatToFloatCast(EltType, SrcType, Src.getComplexFloatImag(), Info.Ctx)); } else { return APValue(HandleFloatToIntCast(EltType, SrcType, Src.getComplexFloatReal(), Info.Ctx), - HandleFloatToIntCast(EltType, SrcType, + HandleFloatToIntCast(EltType, SrcType, Src.getComplexFloatImag(), - Info.Ctx)); + Info.Ctx)); } } else { assert(Src.isComplexInt() && "Invalid evaluate result."); if (EltType->isRealFloatingType()) { - return APValue(HandleIntToFloatCast(EltType, SrcType, + return APValue(HandleIntToFloatCast(EltType, SrcType, Src.getComplexIntReal(), Info.Ctx), - HandleIntToFloatCast(EltType, SrcType, + HandleIntToFloatCast(EltType, SrcType, Src.getComplexIntImag(), Info.Ctx)); } else { return APValue(HandleIntToIntCast(EltType, SrcType, Src.getComplexIntReal(), Info.Ctx), - HandleIntToIntCast(EltType, SrcType, + HandleIntToIntCast(EltType, SrcType, Src.getComplexIntImag(), - Info.Ctx)); + Info.Ctx)); } } } @@ -1658,7 +1654,7 @@ public: // FIXME: Handle more casts. return APValue(); } - + APValue VisitBinaryOperator(const BinaryOperator *E); APValue VisitChooseExpr(const ChooseExpr *E) { return Visit(E->getChosenSubExpr(Info.Ctx)); } @@ -1669,23 +1665,21 @@ public: }; } // end anonymous namespace -static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) -{ +static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) { Result = ComplexExprEvaluator(Info).Visit(const_cast(E)); assert((!Result.isComplexFloat() || - (&Result.getComplexFloatReal().getSemantics() == - &Result.getComplexFloatImag().getSemantics())) && + (&Result.getComplexFloatReal().getSemantics() == + &Result.getComplexFloatImag().getSemantics())) && "Invalid complex evaluation."); return Result.isComplexFloat() || Result.isComplexInt(); } -APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) -{ +APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { APValue Result, RHS; - + if (!EvaluateComplex(E->getLHS(), Result, Info)) return APValue(); - + if (!EvaluateComplex(E->getRHS(), RHS, Info)) return APValue(); @@ -1722,7 +1716,7 @@ APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) APFloat &LHS_i = LHS.getComplexFloatImag(); APFloat &RHS_r = RHS.getComplexFloatReal(); APFloat &RHS_i = RHS.getComplexFloatImag(); - + APFloat Tmp = LHS_r; Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); Result.getComplexFloatReal() = Tmp; @@ -1738,10 +1732,10 @@ APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); } else { APValue LHS = Result; - Result.getComplexIntReal() = + Result.getComplexIntReal() = (LHS.getComplexIntReal() * RHS.getComplexIntReal() - LHS.getComplexIntImag() * RHS.getComplexIntImag()); - Result.getComplexIntImag() = + Result.getComplexIntImag() = (LHS.getComplexIntReal() * RHS.getComplexIntImag() + LHS.getComplexIntImag() * RHS.getComplexIntReal()); } @@ -1775,7 +1769,7 @@ bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const { llvm::APFloat f(0.0); if (!EvaluateFloat(this, f, Info)) return false; - + Result.Val = APValue(f); } else if (getType()->isAnyComplexType()) { if (!EvaluateComplex(this, Result.Val, Info)) diff --git a/clang/lib/AST/InheritViz.cpp b/clang/lib/AST/InheritViz.cpp index 323048c88b1525d6046e610a30619991081cc563..c47a9dadbadd02707164295040d649fd05f88b2d 100644 --- a/clang/lib/AST/InheritViz.cpp +++ b/clang/lib/AST/InheritViz.cpp @@ -89,7 +89,7 @@ void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) { Out << " \"];\n"; // Display the base classes. - const CXXRecordDecl *Decl + const CXXRecordDecl *Decl = static_cast(Type->getAs()->getDecl()); for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin(); Base != Decl->bases_end(); ++Base) { @@ -120,8 +120,8 @@ void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) { /// WriteNodeReference - Write out a reference to the given node, /// using a unique identifier for each direct base and for the /// (only) virtual base. -llvm::raw_ostream& -InheritanceHierarchyWriter::WriteNodeReference(QualType Type, +llvm::raw_ostream& +InheritanceHierarchyWriter::WriteNodeReference(QualType Type, bool FromVirtual) { QualType CanonType = Context.getCanonicalType(Type); diff --git a/clang/lib/AST/NestedNameSpecifier.cpp b/clang/lib/AST/NestedNameSpecifier.cpp index 2ed8eb00993d4b38efed9a4f84d733118f28ad4f..d969776aa0ee78e06cc1fd4741df96f07524ec1b 100644 --- a/clang/lib/AST/NestedNameSpecifier.cpp +++ b/clang/lib/AST/NestedNameSpecifier.cpp @@ -22,13 +22,13 @@ using namespace clang; NestedNameSpecifier * -NestedNameSpecifier::FindOrInsert(ASTContext &Context, +NestedNameSpecifier::FindOrInsert(ASTContext &Context, const NestedNameSpecifier &Mockup) { llvm::FoldingSetNodeID ID; Mockup.Profile(ID); void *InsertPos = 0; - NestedNameSpecifier *NNS + NestedNameSpecifier *NNS = Context.NestedNameSpecifiers.FindNodeOrInsertPos(ID, InsertPos); if (!NNS) { NNS = new (Context, 4) NestedNameSpecifier(Mockup); @@ -39,7 +39,7 @@ NestedNameSpecifier::FindOrInsert(ASTContext &Context, } NestedNameSpecifier * -NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, +NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II) { assert(II && "Identifier cannot be NULL"); assert((!Prefix || Prefix->isDependent()) && "Prefix must be dependent"); @@ -52,10 +52,10 @@ NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, } NestedNameSpecifier * -NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, +NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, NamespaceDecl *NS) { assert(NS && "Namespace cannot be NULL"); - assert((!Prefix || + assert((!Prefix || (Prefix->getAsType() == 0 && Prefix->getAsIdentifier() == 0)) && "Broken nested name specifier"); NestedNameSpecifier Mockup; @@ -115,8 +115,8 @@ bool NestedNameSpecifier::isDependent() const { /// \brief Print this nested name specifier to the given output /// stream. -void -NestedNameSpecifier::print(llvm::raw_ostream &OS, +void +NestedNameSpecifier::print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const { if (getPrefix()) getPrefix()->print(OS, Policy); @@ -144,26 +144,26 @@ NestedNameSpecifier::print(llvm::raw_ostream &OS, PrintingPolicy InnerPolicy(Policy); InnerPolicy.SuppressTagKind = true; InnerPolicy.SuppressScope = true; - + // Nested-name-specifiers are intended to contain minimally-qualified // types. An actual QualifiedNameType will not occur, since we'll store // just the type that is referred to in the nested-name-specifier (e.g., // a TypedefType, TagType, etc.). However, when we are dealing with - // dependent template-id types (e.g., Outer::template Inner), + // dependent template-id types (e.g., Outer::template Inner), // the type requires its own nested-name-specifier for uniqueness, so we // suppress that nested-name-specifier during printing. - assert(!isa(T) && + assert(!isa(T) && "Qualified name type in nested-name-specifier"); if (const TemplateSpecializationType *SpecType = dyn_cast(T)) { - // Print the template name without its corresponding + // Print the template name without its corresponding // nested-name-specifier. SpecType->getTemplateName().print(OS, InnerPolicy, true); - + // Print the template argument list. TypeStr = TemplateSpecializationType::PrintTemplateArgumentList( - SpecType->getArgs(), - SpecType->getNumArgs(), + SpecType->getArgs(), + SpecType->getNumArgs(), InnerPolicy); } else { // Print the type normally diff --git a/clang/lib/AST/ParentMap.cpp b/clang/lib/AST/ParentMap.cpp index 9d87daa0bfd8613e149136dcd90040c5c3122d06..48251d52fd2a84dafe4cc497847c131133913174 100644 --- a/clang/lib/AST/ParentMap.cpp +++ b/clang/lib/AST/ParentMap.cpp @@ -32,7 +32,7 @@ ParentMap::ParentMap(Stmt* S) : Impl(0) { if (S) { MapTy *M = new MapTy(); BuildParentMap(*M, S); - Impl = M; + Impl = M; } } @@ -54,16 +54,16 @@ Stmt *ParentMap::getParentIgnoreParens(Stmt *S) const { bool ParentMap::isConsumedExpr(Expr* E) const { Stmt *P = getParent(E); Stmt *DirectChild = E; - + // Ignore parents that are parentheses or casts. while (P && (isa(P) || isa(P))) { DirectChild = P; P = getParent(P); } - + if (!P) return false; - + switch (P->getStmtClass()) { default: return isa(P); @@ -78,7 +78,7 @@ bool ParentMap::isConsumedExpr(Expr* E) const { case Stmt::ForStmtClass: return DirectChild == cast(P)->getCond(); case Stmt::WhileStmtClass: - return DirectChild == cast(P)->getCond(); + return DirectChild == cast(P)->getCond(); case Stmt::DoStmtClass: return DirectChild == cast(P)->getCond(); case Stmt::IfStmtClass: diff --git a/clang/lib/AST/RecordLayoutBuilder.cpp b/clang/lib/AST/RecordLayoutBuilder.cpp index 071e3e89550b6d6b980df6b656c86bdf95afc327..05b5ee977cc9ac87882638c0a1222267600a60f1 100644 --- a/clang/lib/AST/RecordLayoutBuilder.cpp +++ b/clang/lib/AST/RecordLayoutBuilder.cpp @@ -21,8 +21,8 @@ using namespace clang; -ASTRecordLayoutBuilder::ASTRecordLayoutBuilder(ASTContext &Ctx) - : Ctx(Ctx), Size(0), Alignment(8), Packed(false), MaxFieldAlignment(0), +ASTRecordLayoutBuilder::ASTRecordLayoutBuilder(ASTContext &Ctx) + : Ctx(Ctx), Size(0), Alignment(8), Packed(false), MaxFieldAlignment(0), NextOffset(0), IsUnion(false), NonVirtualSize(0), NonVirtualAlignment(8) {} /// LayoutVtable - Lay out the vtable and set PrimaryBase. @@ -43,12 +43,12 @@ void ASTRecordLayoutBuilder::LayoutVtable(const CXXRecordDecl *RD, } } -void +void ASTRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) { for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { if (!i->isVirtual()) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); // Skip the PrimaryBase here, as it is laid down first. if (Base != PrimaryBase || PrimaryBaseWasVirtual) @@ -83,7 +83,7 @@ void ASTRecordLayoutBuilder::SelectPrimaryForBase(const CXXRecordDecl *RD, for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); // Only bases with virtual bases participate in computing the // indirect primary virtual base classes. @@ -97,7 +97,7 @@ void ASTRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD, llvm::SmallSet &IndirectPrimary) { for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (!i->isVirtual()) { SelectPrimaryVBase(Base, FirstPrimary, IndirectPrimary); @@ -125,7 +125,7 @@ void ASTRecordLayoutBuilder::SelectPrimaryBase(const CXXRecordDecl *RD, const CXXRecordDecl *FirstPrimary = 0; for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); SelectPrimaryForBase(Base, IndirectPrimary); } @@ -135,7 +135,7 @@ void ASTRecordLayoutBuilder::SelectPrimaryBase(const CXXRecordDecl *RD, for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { if (!i->isVirtual()) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (Base->isDynamicClass()) { setPrimaryBase(Base, false); @@ -174,7 +174,7 @@ void ASTRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD, llvm::SmallSet &IndirectPrimary) { for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); #if 0 const ASTRecordLayout &L = Ctx.getASTRecordLayout(Base); @@ -224,12 +224,12 @@ void ASTRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD, void ASTRecordLayoutBuilder::LayoutBaseNonVirtually(const CXXRecordDecl *RD, bool IsVirtualBase) { const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD); - assert(BaseInfo.getDataSize() > 0 && + assert(BaseInfo.getDataSize() > 0 && "FIXME: Handle empty classes."); - + unsigned BaseAlign = BaseInfo.getNonVirtualAlign(); uint64_t BaseSize = BaseInfo.getNonVirtualSize(); - + // Round up the current record size to the base's alignment boundary. Size = (Size + (BaseAlign-1)) & ~(BaseAlign-1); @@ -260,10 +260,10 @@ void ASTRecordLayoutBuilder::LayoutBaseNonVirtually(const CXXRecordDecl *RD, // Reserve space for this base. Size += BaseSize; - + // Remember the next available offset. NextOffset = Size; - + // Remember max struct/class alignment. UpdateAlignment(BaseAlign); } @@ -276,7 +276,7 @@ void ASTRecordLayoutBuilder::Layout(const RecordDecl *D) { // The #pragma pack attribute specifies the maximum field alignment. if (const PragmaPackAttr *PPA = D->getAttr()) MaxFieldAlignment = PPA->getAlignment(); - + if (const AlignedAttr *AA = D->getAttr()) UpdateAlignment(AA->getAlignment()); @@ -296,7 +296,7 @@ void ASTRecordLayoutBuilder::Layout(const RecordDecl *D) { } LayoutFields(D); - + NonVirtualSize = Size; NonVirtualAlignment = Alignment; @@ -316,28 +316,28 @@ void ASTRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D, const ASTRecordLayout &SL = Ctx.getASTObjCInterfaceLayout(SD); UpdateAlignment(SL.getAlignment()); - + // We start laying out ivars not at the end of the superclass // structure, but at the next byte following the last field. Size = llvm::RoundUpToAlignment(SL.getDataSize(), 8); NextOffset = Size; } - + Packed = D->hasAttr(); - + // The #pragma pack attribute specifies the maximum field alignment. if (const PragmaPackAttr *PPA = D->getAttr()) MaxFieldAlignment = PPA->getAlignment(); - + if (const AlignedAttr *AA = D->getAttr()) UpdateAlignment(AA->getAlignment()); - + // Layout each ivar sequentially. llvm::SmallVector Ivars; Ctx.ShallowCollectObjCIvars(D, Ivars, Impl); for (unsigned i = 0, e = Ivars.size(); i != e; ++i) LayoutField(Ivars[i]); - + // Finally, round the size of the total struct up to the alignment of the // struct itself. FinishLayout(); @@ -346,7 +346,7 @@ void ASTRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D, void ASTRecordLayoutBuilder::LayoutFields(const RecordDecl *D) { // Layout each field, for now, just sequentially, respecting alignment. In // the future, this will need to be tweakable by targets. - for (RecordDecl::field_iterator Field = D->field_begin(), + for (RecordDecl::field_iterator Field = D->field_begin(), FieldEnd = D->field_end(); Field != FieldEnd; ++Field) LayoutField(*Field); } @@ -356,19 +356,19 @@ void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) { uint64_t FieldOffset = IsUnion ? 0 : Size; uint64_t FieldSize; unsigned FieldAlign; - - FieldPacked |= D->hasAttr(); - + + FieldPacked |= D->hasAttr(); + if (const Expr *BitWidthExpr = D->getBitWidth()) { // TODO: Need to check this algorithm on other targets! // (tested on Linux-X86) FieldSize = BitWidthExpr->EvaluateAsInt(Ctx).getZExtValue(); - + std::pair FieldInfo = Ctx.getTypeInfo(D->getType()); uint64_t TypeSize = FieldInfo.first; FieldAlign = FieldInfo.second; - + if (FieldPacked) FieldAlign = 1; if (const AlignedAttr *AA = D->getAttr()) @@ -381,7 +381,7 @@ void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) { // alignment. if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); - + // Padding members don't affect overall alignment if (!D->getIdentifier()) FieldAlign = 1; @@ -403,7 +403,7 @@ void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) { FieldSize = FieldInfo.first; FieldAlign = FieldInfo.second; } - + if (FieldPacked) FieldAlign = 8; if (const AlignedAttr *AA = D->getAttr()) @@ -411,23 +411,23 @@ void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) { // The maximum field alignment overrides the aligned attribute. if (MaxFieldAlignment) FieldAlign = std::min(FieldAlign, MaxFieldAlignment); - + // Round up the current record size to the field's alignment boundary. FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); } - + // Place this field at the current location. FieldOffsets.push_back(FieldOffset); - + // Reserve space for this field. if (IsUnion) Size = std::max(Size, FieldSize); else Size = FieldOffset + FieldSize; - + // Remember the next available offset. NextOffset = Size; - + // Remember max struct/class alignment. UpdateAlignment(FieldAlign); } @@ -444,14 +444,14 @@ void ASTRecordLayoutBuilder::FinishLayout() { void ASTRecordLayoutBuilder::UpdateAlignment(unsigned NewAlignment) { if (NewAlignment <= Alignment) return; - + assert(llvm::isPowerOf2_32(NewAlignment && "Alignment not a power of 2")); - + Alignment = NewAlignment; } - + const ASTRecordLayout * -ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx, +ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx, const RecordDecl *D) { ASTRecordLayoutBuilder Builder(Ctx); @@ -459,27 +459,27 @@ ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx, if (!isa(D)) return new ASTRecordLayout(Builder.Size, Builder.Alignment, Builder.Size, - Builder.FieldOffsets.data(), + Builder.FieldOffsets.data(), Builder.FieldOffsets.size()); - + // FIXME: This is not always correct. See the part about bitfields at // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info. // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout. bool IsPODForThePurposeOfLayout = cast(D)->isPOD(); - - assert(Builder.Bases.size() == Builder.BaseOffsets.size() && + + assert(Builder.Bases.size() == Builder.BaseOffsets.size() && "Base offsets vector must be same size as bases vector!"); - assert(Builder.VBases.size() == Builder.VBaseOffsets.size() && + assert(Builder.VBases.size() == Builder.VBaseOffsets.size() && "Base offsets vector must be same size as bases vector!"); // FIXME: This should be done in FinalizeLayout. - uint64_t DataSize = + uint64_t DataSize = IsPODForThePurposeOfLayout ? Builder.Size : Builder.NextOffset; - uint64_t NonVirtualSize = + uint64_t NonVirtualSize = IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize; - + return new ASTRecordLayout(Builder.Size, Builder.Alignment, DataSize, - Builder.FieldOffsets.data(), + Builder.FieldOffsets.data(), Builder.FieldOffsets.size(), NonVirtualSize, Builder.NonVirtualAlignment, @@ -498,11 +498,11 @@ ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx, const ObjCInterfaceDecl *D, const ObjCImplementationDecl *Impl) { ASTRecordLayoutBuilder Builder(Ctx); - + Builder.Layout(D, Impl); - + return new ASTRecordLayout(Builder.Size, Builder.Alignment, Builder.NextOffset, - Builder.FieldOffsets.data(), + Builder.FieldOffsets.data(), Builder.FieldOffsets.size()); } diff --git a/clang/lib/AST/RecordLayoutBuilder.h b/clang/lib/AST/RecordLayoutBuilder.h index 5813e27a84016d0b14f2d470d45da2b72fd80f4d..efaa2eeb9818237687ac817f07b9dd75adba450e 100644 --- a/clang/lib/AST/RecordLayoutBuilder.h +++ b/clang/lib/AST/RecordLayoutBuilder.h @@ -22,19 +22,19 @@ namespace clang { class ObjCImplementationDecl; class ObjCInterfaceDecl; class RecordDecl; - + class ASTRecordLayoutBuilder { ASTContext &Ctx; uint64_t Size; unsigned Alignment; llvm::SmallVector FieldOffsets; - + bool Packed; unsigned MaxFieldAlignment; uint64_t NextOffset; bool IsUnion; - + uint64_t NonVirtualSize; unsigned NonVirtualAlignment; const CXXRecordDecl *PrimaryBase; @@ -45,9 +45,9 @@ class ASTRecordLayoutBuilder { llvm::SmallVector VBases; llvm::SmallVector VBaseOffsets; - + ASTRecordLayoutBuilder(ASTContext &Ctx); - + void Layout(const RecordDecl *D); void Layout(const CXXRecordDecl *D); void Layout(const ObjCInterfaceDecl *D, @@ -77,23 +77,23 @@ class ASTRecordLayoutBuilder { int64_t Offset, llvm::SmallSet &mark, llvm::SmallSet &IndirectPrimary); - + /// FinishLayout - Finalize record layout. Adjust record size based on the /// alignment. void FinishLayout(); - + void UpdateAlignment(unsigned NewAlignment); ASTRecordLayoutBuilder(const ASTRecordLayoutBuilder&); // DO NOT IMPLEMENT void operator=(const ASTRecordLayoutBuilder&); // DO NOT IMPLEMENT public: - static const ASTRecordLayout *ComputeLayout(ASTContext &Ctx, + static const ASTRecordLayout *ComputeLayout(ASTContext &Ctx, const RecordDecl *RD); static const ASTRecordLayout *ComputeLayout(ASTContext &Ctx, const ObjCInterfaceDecl *D, const ObjCImplementationDecl *Impl); }; - + } // end namespace clang #endif diff --git a/clang/lib/AST/Stmt.cpp b/clang/lib/AST/Stmt.cpp index f230018c0df04c940522c61422e1177afc001219..3a838fadafa415bb6880c5b824e3d624ba28b10c 100644 --- a/clang/lib/AST/Stmt.cpp +++ b/clang/lib/AST/Stmt.cpp @@ -95,7 +95,7 @@ bool Stmt::CollectingStats(bool enable) { void SwitchStmt::DoDestroy(ASTContext &Ctx) { // Destroy the SwitchCase statements in this switch. In the normal - // case, this loop will merely decrement the reference counts from + // case, this loop will merely decrement the reference counts from // the Retain() calls in addSwitchCase(); SwitchCase *SC = FirstCase; while (SC) { @@ -103,7 +103,7 @@ void SwitchStmt::DoDestroy(ASTContext &Ctx) { SC->Destroy(Ctx); SC = Next; } - + Stmt::DoDestroy(Ctx); } @@ -187,7 +187,7 @@ std::string AsmStmt::getInputConstraint(unsigned i) const { void AsmStmt::setOutputsAndInputs(unsigned NumOutputs, - unsigned NumInputs, + unsigned NumInputs, const std::string *Names, StringLiteral **Constraints, Stmt **Exprs) { @@ -196,7 +196,7 @@ void AsmStmt::setOutputsAndInputs(unsigned NumOutputs, this->Names.clear(); this->Names.insert(this->Names.end(), Names, Names + NumOutputs + NumInputs); this->Constraints.clear(); - this->Constraints.insert(this->Constraints.end(), + this->Constraints.insert(this->Constraints.end(), Constraints, Constraints + NumOutputs + NumInputs); this->Exprs.clear(); this->Exprs.insert(this->Exprs.end(), Exprs, Exprs + NumOutputs + NumInputs); @@ -207,13 +207,13 @@ void AsmStmt::setOutputsAndInputs(unsigned NumOutputs, /// This returns -1 if the operand name is invalid. int AsmStmt::getNamedOperand(const std::string &SymbolicName) const { unsigned NumPlusOperands = 0; - + // Check if this is an output operand. for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) { if (getOutputName(i) == SymbolicName) return i; } - + for (unsigned i = 0, e = getNumInputs(); i != e; ++i) if (getInputName(i) == SymbolicName) return getNumOutputs() + NumPlusOperands + i; @@ -235,7 +235,7 @@ unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl&Pieces, const char *StrStart = getAsmString()->getStrData(); const char *StrEnd = StrStart + getAsmString()->getByteLength(); const char *CurPtr = StrStart; - + // "Simple" inline asms have no constraints or operands, just convert the asm // string to escape $'s. if (isSimple()) { @@ -257,7 +257,7 @@ unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl&Pieces, // CurStringPiece - The current string that we are building up as we scan the // asm string. std::string CurStringPiece; - + while (1) { // Done with the string? if (CurPtr == StrEnd) { @@ -265,7 +265,7 @@ unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl&Pieces, Pieces.push_back(AsmStringPiece(CurStringPiece)); return 0; } - + char CurChar = *CurPtr++; if (CurChar == '$') { CurStringPiece += "$$"; @@ -274,48 +274,48 @@ unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl&Pieces, CurStringPiece += CurChar; continue; } - + // Escaped "%" character in asm string. if (CurPtr == StrEnd) { // % at end of string is invalid (no escape). DiagOffs = CurPtr-StrStart-1; return diag::err_asm_invalid_escape; } - + char EscapedChar = *CurPtr++; if (EscapedChar == '%') { // %% -> % // Escaped percentage sign. CurStringPiece += '%'; continue; } - + if (EscapedChar == '=') { // %= -> Generate an unique ID. CurStringPiece += "${:uid}"; continue; } - + // Otherwise, we have an operand. If we have accumulated a string so far, // add it to the Pieces list. if (!CurStringPiece.empty()) { Pieces.push_back(AsmStringPiece(CurStringPiece)); CurStringPiece.clear(); } - + // Handle %x4 and %x[foo] by capturing x as the modifier character. char Modifier = '\0'; if (isalpha(EscapedChar)) { Modifier = EscapedChar; EscapedChar = *CurPtr++; } - + if (isdigit(EscapedChar)) { // %n - Assembler operand n unsigned N = 0; - + --CurPtr; while (CurPtr != StrEnd && isdigit(*CurPtr)) N = N*10 + ((*CurPtr++)-'0'); - + unsigned NumOperands = getNumOutputs() + getNumPlusOperands() + getNumInputs(); if (N >= NumOperands) { @@ -326,20 +326,20 @@ unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl&Pieces, Pieces.push_back(AsmStringPiece(N, Modifier)); continue; } - + // Handle %[foo], a symbolic operand reference. if (EscapedChar == '[') { DiagOffs = CurPtr-StrStart-1; - + // Find the ']'. const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr); if (NameEnd == 0) return diag::err_asm_unterminated_symbolic_operand_name; if (NameEnd == CurPtr) return diag::err_asm_empty_symbolic_operand_name; - + std::string SymbolicName(CurPtr, NameEnd); - + int N = getNamedOperand(SymbolicName); if (N == -1) { // Verify that an operand with that name exists. @@ -347,11 +347,11 @@ unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl&Pieces, return diag::err_asm_unknown_symbolic_operand_name; } Pieces.push_back(AsmStringPiece(N, Modifier)); - + CurPtr = NameEnd+1; continue; } - + DiagOffs = CurPtr-StrStart-1; return diag::err_asm_invalid_escape; } @@ -509,7 +509,7 @@ Stmt::child_iterator ReturnStmt::child_end() { } // AsmStmt -Stmt::child_iterator AsmStmt::child_begin() { +Stmt::child_iterator AsmStmt::child_begin() { return Exprs.empty() ? 0 : &Exprs[0]; } Stmt::child_iterator AsmStmt::child_end() { diff --git a/clang/lib/AST/StmtDumper.cpp b/clang/lib/AST/StmtDumper.cpp index 5f320095e7f67f6737e06cdb45e698613ecaebe5..ed92da375f398bd11ed7a7ae4e221472eed5c18e 100644 --- a/clang/lib/AST/StmtDumper.cpp +++ b/clang/lib/AST/StmtDumper.cpp @@ -30,12 +30,12 @@ namespace { SourceManager *SM; FILE *F; unsigned IndentLevel; - + /// MaxDepth - When doing a normal dump (not dumpAll) we only want to dump /// the first few levels of an AST. This keeps track of how many ast levels /// are left. unsigned MaxDepth; - + /// LastLocFilename/LastLocLine - Keep track of the last location we print /// out so that we can print out deltas from then on out. const char *LastLocFilename; @@ -47,18 +47,18 @@ namespace { LastLocFilename = ""; LastLocLine = ~0U; } - + void DumpSubTree(Stmt *S) { // Prune the recursion if not using dump all. if (MaxDepth == 0) return; - + ++IndentLevel; if (S) { if (DeclStmt* DS = dyn_cast(S)) VisitDeclStmt(DS); - else { + else { Visit(S); - + // Print out children. Stmt::child_iterator CI = S->child_begin(), CE = S->child_end(); if (CI != CE) { @@ -75,14 +75,14 @@ namespace { } --IndentLevel; } - + void DumpDeclarator(Decl *D); - + void Indent() const { for (int i = 0, e = IndentLevel; i < e; ++i) fprintf(F, " "); } - + void DumpType(QualType T) { fprintf(F, "'%s'", T.getAsString().c_str()); @@ -90,7 +90,7 @@ namespace { // If the type is directly a typedef, strip off typedefness to give at // least one level of concreteness. if (TypedefType *TDT = dyn_cast(T)) { - QualType Simplified = + QualType Simplified = TDT->LookThroughTypedefs().getQualifiedType(T.getCVRQualifiers()); fprintf(F, ":'%s'", Simplified.getAsString().c_str()); } @@ -108,13 +108,13 @@ namespace { } void DumpSourceRange(const Stmt *Node); void DumpLocation(SourceLocation Loc); - + // Stmts. void VisitStmt(Stmt *Node); void VisitDeclStmt(DeclStmt *Node); void VisitLabelStmt(LabelStmt *Node); void VisitGotoStmt(GotoStmt *Node); - + // Exprs void VisitExpr(Expr *Node); void VisitCastExpr(CastExpr *Node); @@ -142,7 +142,7 @@ namespace { void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node); void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *Node); void DumpCXXTemporary(CXXTemporary *Temporary); - + // ObjC void VisitObjCEncodeExpr(ObjCEncodeExpr *Node); void VisitObjCMessageExpr(ObjCMessageExpr* Node); @@ -162,7 +162,7 @@ namespace { void StmtDumper::DumpLocation(SourceLocation Loc) { SourceLocation SpellingLoc = SM->getSpellingLoc(Loc); - + if (SpellingLoc.isInvalid()) { fprintf(stderr, ""); return; @@ -188,11 +188,11 @@ void StmtDumper::DumpLocation(SourceLocation Loc) { void StmtDumper::DumpSourceRange(const Stmt *Node) { // Can't translate locations if a SourceManager isn't available. if (SM == 0) return; - + // TODO: If the parent expression is available, we can print a delta vs its // location. SourceRange R = Node->getSourceRange(); - + fprintf(stderr, " <"); DumpLocation(R.getBegin()); if (R.getBegin() != R.getEnd()) { @@ -200,7 +200,7 @@ void StmtDumper::DumpSourceRange(const Stmt *Node) { DumpLocation(R.getEnd()); } fprintf(stderr, ">"); - + // } @@ -226,15 +226,15 @@ void StmtDumper::DumpDeclarator(Decl *D) { // Emit storage class for vardecls. if (VarDecl *V = dyn_cast(VD)) { if (V->getStorageClass() != VarDecl::None) - fprintf(F, "%s ", + fprintf(F, "%s ", VarDecl::getStorageClassSpecifierString(V->getStorageClass())); } - + std::string Name = VD->getNameAsString(); - VD->getType().getAsStringInternal(Name, + VD->getType().getAsStringInternal(Name, PrintingPolicy(VD->getASTContext().getLangOptions())); fprintf(F, "%s", Name.c_str()); - + // If this is a vardecl with an initializer, emit it. if (VarDecl *V = dyn_cast(VD)) { if (V->getInit()) { @@ -321,15 +321,15 @@ void StmtDumper::VisitDeclRefExpr(DeclRefExpr *Node) { case Decl::ObjCInterface: fprintf(F,"ObjCInterface"); break; case Decl::ObjCClass: fprintf(F,"ObjCClass"); break; } - - fprintf(F, "='%s' %p", Node->getDecl()->getNameAsString().c_str(), + + fprintf(F, "='%s' %p", Node->getDecl()->getNameAsString().c_str(), (void*)Node->getDecl()); } void StmtDumper::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) { DumpExpr(Node); - fprintf(F, " %sDecl='%s' %p", Node->getDecl()->getDeclKindName(), + fprintf(F, " %sDecl='%s' %p", Node->getDecl()->getDeclKindName(), Node->getDecl()->getNameAsString().c_str(), (void*)Node->getDecl()); if (Node->isFreeIvar()) fprintf(F, " isFreeIvar"); @@ -370,7 +370,7 @@ void StmtDumper::VisitStringLiteral(StringLiteral *Str) { switch (char C = Str->getStrData()[i]) { default: if (isprint(C)) - fputc(C, F); + fputc(C, F); else fprintf(F, "\\%03o", C); break; @@ -401,7 +401,7 @@ void StmtDumper::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *Node) { void StmtDumper::VisitMemberExpr(MemberExpr *Node) { DumpExpr(Node); fprintf(F, " %s%s %p", Node->isArrow() ? "->" : ".", - Node->getMemberDecl()->getNameAsString().c_str(), + Node->getMemberDecl()->getNameAsString().c_str(), (void*)Node->getMemberDecl()); } void StmtDumper::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) { @@ -459,7 +459,7 @@ void StmtDumper::VisitCXXThisExpr(CXXThisExpr *Node) { void StmtDumper::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) { DumpExpr(Node); - fprintf(F, " functional cast to %s", + fprintf(F, " functional cast to %s", Node->getTypeAsWritten().getAsString().c_str()); } @@ -503,21 +503,21 @@ void StmtDumper::VisitObjCMessageExpr(ObjCMessageExpr* Node) { void StmtDumper::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) { DumpExpr(Node); - + fprintf(F, " "); DumpType(Node->getEncodedType()); } void StmtDumper::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) { DumpExpr(Node); - + fprintf(F, " "); fprintf(F, "%s", Node->getSelector().getAsString().c_str()); } void StmtDumper::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) { DumpExpr(Node); - + fprintf(F, " "); fprintf(F, "%s", Node->getProtocol()->getNameAsString().c_str()); } @@ -525,17 +525,17 @@ void StmtDumper::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) { void StmtDumper::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) { DumpExpr(Node); - fprintf(F, " Kind=PropertyRef Property=\"%s\"", + fprintf(F, " Kind=PropertyRef Property=\"%s\"", Node->getProperty()->getNameAsString().c_str()); } void StmtDumper::VisitObjCImplicitSetterGetterRefExpr( ObjCImplicitSetterGetterRefExpr *Node) { DumpExpr(Node); - + ObjCMethodDecl *Getter = Node->getGetterMethod(); ObjCMethodDecl *Setter = Node->getSetterMethod(); - fprintf(F, " Kind=MethodRef Getter=\"%s\" Setter=\"%s\"", + fprintf(F, " Kind=MethodRef Getter=\"%s\" Setter=\"%s\"", Getter->getSelector().getAsString().c_str(), Setter ? Setter->getSelector().getAsString().c_str() : "(null)"); } diff --git a/clang/lib/AST/StmtIterator.cpp b/clang/lib/AST/StmtIterator.cpp index 5c22e28894f9ea849f5f54c5f5db564a7a9c9491..4f62b66e257dff3bd3dab72c996234cf7bb9c65e 100644 --- a/clang/lib/AST/StmtIterator.cpp +++ b/clang/lib/AST/StmtIterator.cpp @@ -23,10 +23,10 @@ static inline VariableArrayType* FindVA(Type* t) { if (VariableArrayType* vat = dyn_cast(vt)) if (vat->getSizeExpr()) return vat; - + t = vt->getElementType().getTypePtr(); } - + return NULL; } @@ -39,20 +39,20 @@ void StmtIteratorBase::NextVA() { if (p) return; - + if (inDecl()) { - if (VarDecl* VD = dyn_cast(decl)) + if (VarDecl* VD = dyn_cast(decl)) if (VD->Init) return; - + NextDecl(); } else if (inDeclGroup()) { - if (VarDecl* VD = dyn_cast(*DGI)) + if (VarDecl* VD = dyn_cast(*DGI)) if (VD->Init) return; - - NextDecl(); + + NextDecl(); } else { assert (inSizeOfTypeVA()); @@ -63,10 +63,10 @@ void StmtIteratorBase::NextVA() { void StmtIteratorBase::NextDecl(bool ImmediateAdvance) { assert (getVAPtr() == NULL); - + if (inDecl()) { assert (decl); - + // FIXME: SIMPLIFY AWAY. if (ImmediateAdvance) decl = 0; @@ -75,10 +75,10 @@ void StmtIteratorBase::NextDecl(bool ImmediateAdvance) { } else { assert (inDeclGroup()); - + if (ImmediateAdvance) ++DGI; - + for ( ; DGI != DGE; ++DGI) if (HandleDecl(*DGI)) return; @@ -88,18 +88,18 @@ void StmtIteratorBase::NextDecl(bool ImmediateAdvance) { } bool StmtIteratorBase::HandleDecl(Decl* D) { - - if (VarDecl* VD = dyn_cast(D)) { + + if (VarDecl* VD = dyn_cast(D)) { if (VariableArrayType* VAPtr = FindVA(VD->getType().getTypePtr())) { setVAPtr(VAPtr); return true; } - + if (VD->getInit()) return true; } else if (TypedefDecl* TD = dyn_cast(D)) { - if (VariableArrayType* VAPtr = + if (VariableArrayType* VAPtr = FindVA(TD->getUnderlyingType().getTypePtr())) { setVAPtr(VAPtr); return true; @@ -110,7 +110,7 @@ bool StmtIteratorBase::HandleDecl(Decl* D) { return true; } - return false; + return false; } StmtIteratorBase::StmtIteratorBase(Decl* d) @@ -130,19 +130,19 @@ StmtIteratorBase::StmtIteratorBase(VariableArrayType* t) } Stmt*& StmtIteratorBase::GetDeclExpr() const { - + if (VariableArrayType* VAPtr = getVAPtr()) { assert (VAPtr->SizeExpr); return VAPtr->SizeExpr; } assert (inDecl() || inDeclGroup()); - + if (inDeclGroup()) { VarDecl* VD = cast(*DGI); return *VD->getInitAddress(); } - + assert (inDecl()); if (VarDecl* VD = dyn_cast(decl)) { diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index 7a0d6d6349574673176e62357a0e0d13966a3ea0..a6f2b823fe6d4b769e3d385de036ab68da0c48c4 100644 --- a/clang/lib/AST/StmtPrinter.cpp +++ b/clang/lib/AST/StmtPrinter.cpp @@ -33,12 +33,12 @@ namespace { PrintingPolicy Policy; public: - StmtPrinter(llvm::raw_ostream &os, ASTContext &C, PrinterHelper* helper, + StmtPrinter(llvm::raw_ostream &os, ASTContext &C, PrinterHelper* helper, const PrintingPolicy &Policy, unsigned Indentation = 0) : OS(os), Context(C), IndentLevel(Indentation), Helper(helper), Policy(Policy) {} - + void PrintStmt(Stmt *S) { PrintStmt(S, Policy.Indentation); } @@ -63,29 +63,29 @@ namespace { void PrintRawDeclStmt(DeclStmt *S); void PrintRawIfStmt(IfStmt *If); void PrintRawCXXCatchStmt(CXXCatchStmt *Catch); - + void PrintExpr(Expr *E) { if (E) Visit(E); else OS << ""; } - + llvm::raw_ostream &Indent(int Delta = 0) { for (int i = 0, e = IndentLevel+Delta; i < e; ++i) OS << " "; return OS; } - + bool PrintOffsetOfDesignator(Expr *E); void VisitUnaryOffsetOf(UnaryOperator *Node); - - void Visit(Stmt* S) { + + void Visit(Stmt* S) { if (Helper && Helper->handledStmt(S,OS)) return; else StmtVisitor::Visit(S); } - + void VisitStmt(Stmt *Node); #define STMT(CLASS, PARENT) \ void Visit##CLASS(CLASS *Node); @@ -108,7 +108,7 @@ void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) { for (CompoundStmt::body_iterator I = Node->body_begin(), E = Node->body_end(); I != E; ++I) PrintStmt(*I); - + Indent() << "}"; } @@ -119,7 +119,7 @@ void StmtPrinter::PrintRawDecl(Decl *D) { void StmtPrinter::PrintRawDeclStmt(DeclStmt *S) { DeclStmt::decl_iterator Begin = S->decl_begin(), End = S->decl_end(); llvm::SmallVector Decls; - for ( ; Begin != End; ++Begin) + for ( ; Begin != End; ++Begin) Decls.push_back(*Begin); Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel); @@ -149,7 +149,7 @@ void StmtPrinter::VisitCaseStmt(CaseStmt *Node) { PrintExpr(Node->getRHS()); } OS << ":\n"; - + PrintStmt(Node->getSubStmt(), 0); } @@ -167,7 +167,7 @@ void StmtPrinter::PrintRawIfStmt(IfStmt *If) { OS << "if ("; PrintExpr(If->getCond()); OS << ')'; - + if (CompoundStmt *CS = dyn_cast(If->getThen())) { OS << ' '; PrintRawCompoundStmt(CS); @@ -177,10 +177,10 @@ void StmtPrinter::PrintRawIfStmt(IfStmt *If) { PrintStmt(If->getThen()); if (If->getElse()) Indent(); } - + if (Stmt *Else = If->getElse()) { OS << "else"; - + if (CompoundStmt *CS = dyn_cast(Else)) { OS << ' '; PrintRawCompoundStmt(CS); @@ -204,7 +204,7 @@ void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) { Indent() << "switch ("; PrintExpr(Node->getCond()); OS << ")"; - + // Pretty print compoundstmt bodies (very common). if (CompoundStmt *CS = dyn_cast(Node->getBody())) { OS << " "; @@ -237,7 +237,7 @@ void StmtPrinter::VisitDoStmt(DoStmt *Node) { PrintStmt(Node->getBody()); Indent(); } - + OS << "while ("; PrintExpr(Node->getCond()); OS << ");\n"; @@ -262,7 +262,7 @@ void StmtPrinter::VisitForStmt(ForStmt *Node) { PrintExpr(Node->getInc()); } OS << ") "; - + if (CompoundStmt *CS = dyn_cast(Node->getBody())) { PrintRawCompoundStmt(CS); OS << "\n"; @@ -281,7 +281,7 @@ void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) { OS << " in "; PrintExpr(Node->getCollection()); OS << ") "; - + if (CompoundStmt *CS = dyn_cast(Node->getBody())) { PrintRawCompoundStmt(CS); OS << "\n"; @@ -322,63 +322,63 @@ void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) { void StmtPrinter::VisitAsmStmt(AsmStmt *Node) { Indent() << "asm "; - + if (Node->isVolatile()) OS << "volatile "; - + OS << "("; VisitStringLiteral(Node->getAsmString()); - + // Outputs if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 || Node->getNumClobbers() != 0) OS << " : "; - + for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) { if (i != 0) OS << ", "; - + if (!Node->getOutputName(i).empty()) { OS << '['; OS << Node->getOutputName(i); OS << "] "; } - + VisitStringLiteral(Node->getOutputConstraintLiteral(i)); OS << " "; Visit(Node->getOutputExpr(i)); } - + // Inputs if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0) OS << " : "; - + for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) { if (i != 0) OS << ", "; - + if (!Node->getInputName(i).empty()) { OS << '['; OS << Node->getInputName(i); OS << "] "; } - + VisitStringLiteral(Node->getInputConstraintLiteral(i)); OS << " "; Visit(Node->getInputExpr(i)); } - + // Clobbers if (Node->getNumClobbers() != 0) OS << " : "; - + for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) { if (i != 0) OS << ", "; - + VisitStringLiteral(Node->getClobber(i)); } - + OS << ");\n"; } @@ -388,11 +388,11 @@ void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) { PrintRawCompoundStmt(TS); OS << "\n"; } - - for (ObjCAtCatchStmt *catchStmt = + + for (ObjCAtCatchStmt *catchStmt = static_cast(Node->getCatchStmts()); - catchStmt; - catchStmt = + catchStmt; + catchStmt = static_cast(catchStmt->getNextCatchStmt())) { Indent() << "@catch("; if (catchStmt->getCatchParamDecl()) { @@ -400,19 +400,18 @@ void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) { PrintRawDecl(DS); } OS << ")"; - if (CompoundStmt *CS = dyn_cast(catchStmt->getCatchBody())) - { - PrintRawCompoundStmt(CS); - OS << "\n"; - } + if (CompoundStmt *CS = dyn_cast(catchStmt->getCatchBody())) { + PrintRawCompoundStmt(CS); + OS << "\n"; + } } - - if (ObjCAtFinallyStmt *FS =static_cast( - Node->getFinallyStmt())) { + + if (ObjCAtFinallyStmt *FS = static_cast( + Node->getFinallyStmt())) { Indent() << "@finally"; PrintRawCompoundStmt(dyn_cast(FS->getFinallyBody())); OS << "\n"; - } + } } void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) { @@ -458,7 +457,7 @@ void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) { void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) { Indent() << "try "; PrintRawCompoundStmt(Node->getTryBlock()); - for(unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) { + for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) { OS << " "; PrintRawCXXCatchStmt(Node->getHandler(i)); } @@ -477,14 +476,14 @@ void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) { OS << Node->getDecl()->getNameAsString(); } -void StmtPrinter::VisitQualifiedDeclRefExpr(QualifiedDeclRefExpr *Node) { +void StmtPrinter::VisitQualifiedDeclRefExpr(QualifiedDeclRefExpr *Node) { NamedDecl *D = Node->getDecl(); Node->getQualifier()->print(OS, Policy); OS << D->getNameAsString(); } -void StmtPrinter::VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *Node) { +void StmtPrinter::VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *Node) { Node->getQualifier()->print(OS, Policy); OS << Node->getDeclName().getAsString(); } @@ -523,7 +522,7 @@ void StmtPrinter::VisitObjCImplicitSetterGetterRefExpr( } if (Node->getGetterMethod()) OS << Node->getGetterMethod()->getNameAsString(); - + } void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) { @@ -594,7 +593,7 @@ void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) { void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) { bool isSigned = Node->getType()->isSignedIntegerType(); OS << Node->getValue().toString(10, isSigned); - + // Emit suffixes. Integer literals are always a builtin integer type. switch (Node->getType()->getAsBuiltinType()->getKind()) { default: assert(0 && "Unexpected type for integer literal!"); @@ -623,7 +622,7 @@ void StmtPrinter::VisitStringLiteral(StringLiteral *Str) { // FIXME: this doesn't print wstrings right. for (unsigned i = 0, e = Str->getByteLength(); i != e; ++i) { unsigned char Char = Str->getStrData()[i]; - + switch (Char) { default: if (isprint(Char)) @@ -653,7 +652,7 @@ void StmtPrinter::VisitParenExpr(ParenExpr *Node) { void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) { if (!Node->isPostfix()) { OS << UnaryOperator::getOpcodeStr(Node->getOpcode()); - + // Print a space if this is an "identifier operator" like __real, or if // it might be concatenated incorrectly like '+'. switch (Node->getOpcode()) { @@ -671,7 +670,7 @@ void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) { } } PrintExpr(Node->getSubExpr()); - + if (Node->isPostfix()) OS << UnaryOperator::getOpcodeStr(Node->getOpcode()); } @@ -741,7 +740,7 @@ void StmtPrinter::VisitMemberExpr(MemberExpr *Node) { Qualifier->print(OS, Policy); OS << Node->getMemberDecl()->getNameAsString(); - + if (Node->hasExplicitTemplateArgumentList()) OS << TemplateSpecializationType::PrintTemplateArgumentList( Node->getTemplateArgs(), @@ -788,7 +787,7 @@ void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) { } void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) { PrintExpr(Node->getCond()); - + if (Node->getLHS()) { OS << " ? "; PrintExpr(Node->getLHS()); @@ -797,7 +796,7 @@ void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) { else { // Handle GCC extension where LHS can be NULL. OS << " ?: "; } - + PrintExpr(Node->getRHS()); } @@ -884,7 +883,7 @@ void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) { } else { PrintExpr(Node->getArrayRangeStart(*D)); OS << " ... "; - PrintExpr(Node->getArrayRangeEnd(*D)); + PrintExpr(Node->getArrayRangeEnd(*D)); } OS << "]"; } @@ -1036,7 +1035,7 @@ void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) { OS << Node->getType().getAsString(); OS << "("; for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(), - ArgEnd = Node->arg_end(); + ArgEnd = Node->arg_end(); Arg != ArgEnd; ++Arg) { if (Arg != Node->arg_begin()) OS << ", "; @@ -1113,7 +1112,7 @@ void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { OS << '.'; if (E->getQualifier()) E->getQualifier()->print(OS, Policy); - + std::string TypeS; E->getDestroyedType().getAsStringInternal(TypeS, Policy); OS << TypeS; @@ -1132,13 +1131,13 @@ void StmtPrinter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { PrintExpr(E->getSubExpr()); } -void +void StmtPrinter::VisitCXXUnresolvedConstructExpr( CXXUnresolvedConstructExpr *Node) { OS << Node->getTypeAsWritten().getAsString(); OS << "("; for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(), - ArgEnd = Node->arg_end(); + ArgEnd = Node->arg_end(); Arg != ArgEnd; ++Arg) { if (Arg != Node->arg_begin()) OS << ", "; @@ -1155,9 +1154,9 @@ void StmtPrinter::VisitCXXUnresolvedMemberExpr(CXXUnresolvedMemberExpr *Node) { else if (Node->hasExplicitTemplateArgumentList()) // FIXME: Track use of "template" keyword explicitly? OS << "template "; - + OS << Node->getMember().getAsString(); - + if (Node->hasExplicitTemplateArgumentList()) { OS << TemplateSpecializationType::PrintTemplateArgumentList( Node->getTemplateArgs(), @@ -1192,7 +1191,7 @@ void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { << E->getQueriedType().getAsString() << ")"; } -// Obj-C +// Obj-C void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) { OS << "@"; @@ -1230,7 +1229,7 @@ void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) { OS << ":"; } else OS << ", "; // Handle variadic methods. - + PrintExpr(Mess->getArg(i)); } } @@ -1244,9 +1243,9 @@ void StmtPrinter::VisitObjCSuperExpr(ObjCSuperExpr *) { void StmtPrinter::VisitBlockExpr(BlockExpr *Node) { BlockDecl *BD = Node->getBlockDecl(); OS << "^"; - + const FunctionType *AFT = Node->getFunctionType(); - + if (isa(AFT)) { OS << "()"; } else if (!BD->param_empty() || cast(AFT)->isVariadic()) { @@ -1259,7 +1258,7 @@ void StmtPrinter::VisitBlockExpr(BlockExpr *Node) { (*AI)->getType().getAsStringInternal(ParamStr, Policy); OS << ParamStr; } - + const FunctionProtoType *FT = cast(AFT); if (FT->isVariadic()) { if (!BD->param_empty()) OS << ", "; @@ -1294,7 +1293,7 @@ void Stmt::printPretty(llvm::raw_ostream &OS, ASTContext& Context, dump(Context.getSourceManager()); return; } - + StmtPrinter P(OS, Context, Helper, Policy, Indentation); P.Visit(const_cast(this)); } diff --git a/clang/lib/AST/StmtProfile.cpp b/clang/lib/AST/StmtProfile.cpp index 806eb8de81df145abcbefaa5850634fdfab67b7d..5a5badd28910682c7f933fe0cbed45a8a62bbfad 100644 --- a/clang/lib/AST/StmtProfile.cpp +++ b/clang/lib/AST/StmtProfile.cpp @@ -28,36 +28,36 @@ namespace { llvm::FoldingSetNodeID &ID; ASTContext &Context; bool Canonical; - + public: StmtProfiler(llvm::FoldingSetNodeID &ID, ASTContext &Context, - bool Canonical) + bool Canonical) : ID(ID), Context(Context), Canonical(Canonical) { } - + void VisitStmt(Stmt *S); - + #define STMT(Node, Base) void Visit##Node(Node *S); #include "clang/AST/StmtNodes.def" - + /// \brief Visit a declaration that is referenced within an expression /// or statement. void VisitDecl(Decl *D); - - /// \brief Visit a type that is referenced within an expression or + + /// \brief Visit a type that is referenced within an expression or /// statement. void VisitType(QualType T); - + /// \brief Visit a name that occurs within an expression or statement. void VisitName(DeclarationName Name); - + /// \brief Visit a nested-name-specifier that occurs within an expression /// or statement. void VisitNestedNameSpecifier(NestedNameSpecifier *NNS); - + /// \brief Visit a template name that occurs within an expression or /// statement. void VisitTemplateName(TemplateName Name); - + /// \brief Visit template arguments that occur within an expression or /// statement. void VisitTemplateArguments(const TemplateArgument *Args, unsigned NumArgs); @@ -348,7 +348,7 @@ void StmtProfiler::VisitInitListExpr(InitListExpr *S) { VisitInitListExpr(S->getSyntacticForm()); return; } - + VisitExpr(S); } @@ -363,7 +363,7 @@ void StmtProfiler::VisitDesignatedInitExpr(DesignatedInitExpr *S) { VisitName(D->getFieldName()); continue; } - + if (D->isArrayDesignator()) { ID.AddInteger(1); } else { @@ -509,7 +509,7 @@ void StmtProfiler::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *S) { VisitType(S->getDestroyedType()); } -void +void StmtProfiler::VisitUnresolvedFunctionNameExpr(UnresolvedFunctionNameExpr *S) { VisitExpr(S); VisitName(S->getName()); @@ -548,7 +548,7 @@ void StmtProfiler::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *S) { const_cast(S->getTemporary(I)->getDestructor())); } -void +void StmtProfiler::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *S) { VisitExpr(S); VisitType(S->getTypeAsWritten()); @@ -617,7 +617,7 @@ void StmtProfiler::VisitObjCIsaExpr(ObjCIsaExpr *S) { void StmtProfiler::VisitDecl(Decl *D) { ID.AddInteger(D? D->getKind() : 0); - + if (Canonical && D) { if (NonTypeTemplateParmDecl *NTTP = dyn_cast(D)) { ID.AddInteger(NTTP->getDepth()); @@ -625,38 +625,38 @@ void StmtProfiler::VisitDecl(Decl *D) { VisitType(NTTP->getType()); return; } - + if (ParmVarDecl *Parm = dyn_cast(D)) { // The Itanium C++ ABI uses the type of a parameter when mangling // expressions that involve function parameters, so we will use the // parameter's type for establishing function parameter identity. That - // way, our definition of "equivalent" (per C++ [temp.over.link]) + // way, our definition of "equivalent" (per C++ [temp.over.link]) // matches the definition of "equivalent" used for name mangling. VisitType(Parm->getType()); return; } - + if (TemplateTemplateParmDecl *TTP = dyn_cast(D)) { ID.AddInteger(TTP->getDepth()); ID.AddInteger(TTP->getIndex()); return; } - + if (OverloadedFunctionDecl *Ovl = dyn_cast(D)) { - // The Itanium C++ ABI mangles references to a set of overloaded + // The Itanium C++ ABI mangles references to a set of overloaded // functions using just the function name, so we do the same here. VisitName(Ovl->getDeclName()); return; } } - + ID.AddPointer(D? D->getCanonicalDecl() : 0); } void StmtProfiler::VisitType(QualType T) { if (Canonical) T = Context.getCanonicalType(T); - + ID.AddPointer(T.getAsOpaquePtr()); } @@ -673,39 +673,39 @@ void StmtProfiler::VisitNestedNameSpecifier(NestedNameSpecifier *NNS) { void StmtProfiler::VisitTemplateName(TemplateName Name) { if (Canonical) Name = Context.getCanonicalTemplateName(Name); - + Name.Profile(ID); } -void StmtProfiler::VisitTemplateArguments(const TemplateArgument *Args, +void StmtProfiler::VisitTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) { ID.AddInteger(NumArgs); for (unsigned I = 0; I != NumArgs; ++I) { const TemplateArgument &Arg = Args[I]; - + // Mostly repetitive with TemplateArgument::Profile! ID.AddInteger(Arg.getKind()); switch (Arg.getKind()) { case TemplateArgument::Null: break; - + case TemplateArgument::Type: VisitType(Arg.getAsType()); break; - + case TemplateArgument::Declaration: VisitDecl(Arg.getAsDecl()); break; - + case TemplateArgument::Integral: Arg.getAsIntegral()->Profile(ID); VisitType(Arg.getIntegralType()); break; - + case TemplateArgument::Expression: Visit(Arg.getAsExpr()); break; - + case TemplateArgument::Pack: VisitTemplateArguments(Arg.pack_begin(), Arg.pack_size()); break; diff --git a/clang/lib/AST/StmtViz.cpp b/clang/lib/AST/StmtViz.cpp index a8f7c76ebe6e96cd86bc05fd10c4fa2921eb96eb..61fd750ccc83f543916472968a90eb19b12c534d 100644 --- a/clang/lib/AST/StmtViz.cpp +++ b/clang/lib/AST/StmtViz.cpp @@ -32,26 +32,26 @@ template<> struct DOTGraphTraits : public DefaultDOTGraphTraits { static std::string getNodeLabel(const Stmt* Node, const Stmt* Graph, bool ShortNames) { - + #ifndef NDEBUG std::string OutSStr; llvm::raw_string_ostream Out(OutSStr); - + if (Node) Out << Node->getStmtClassName(); else Out << ""; - - std::string OutStr = Out.str(); + + std::string OutStr = Out.str(); if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); - + // Process string output to make it nicer... for (unsigned i = 0; i != OutStr.length(); ++i) if (OutStr[i] == '\n') { // Left justify OutStr[i] = '\\'; OutStr.insert(OutStr.begin()+i+1, 'l'); } - + return OutStr; #else return ""; diff --git a/clang/lib/AST/TemplateName.cpp b/clang/lib/AST/TemplateName.cpp index 92c741b35d6724a7fdd79bc9afc8bc858531dae0..24588bc5f11f9e4df34434a10eb84102db192709 100644 --- a/clang/lib/AST/TemplateName.cpp +++ b/clang/lib/AST/TemplateName.cpp @@ -22,7 +22,7 @@ using namespace clang; TemplateDecl *TemplateName::getAsTemplateDecl() const { if (TemplateDecl *Template = Storage.dyn_cast()) return Template; - + if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName()) return QTN->getTemplateDecl(); @@ -30,34 +30,34 @@ TemplateDecl *TemplateName::getAsTemplateDecl() const { } OverloadedFunctionDecl *TemplateName::getAsOverloadedFunctionDecl() const { - if (OverloadedFunctionDecl *Ovl + if (OverloadedFunctionDecl *Ovl = Storage.dyn_cast()) return Ovl; - + if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName()) return QTN->getOverloadedFunctionDecl(); - + return 0; } bool TemplateName::isDependent() const { if (TemplateDecl *Template = getAsTemplateDecl()) { - return isa(Template) || + return isa(Template) || Template->getDeclContext()->isDependentContext(); } if (OverloadedFunctionDecl *Ovl = getAsOverloadedFunctionDecl()) return Ovl->getDeclContext()->isDependentContext(); - + return true; } -void +void TemplateName::print(llvm::raw_ostream &OS, const PrintingPolicy &Policy, bool SuppressNNS) const { if (TemplateDecl *Template = Storage.dyn_cast()) OS << Template->getIdentifier()->getName(); - else if (OverloadedFunctionDecl *Ovl + else if (OverloadedFunctionDecl *Ovl = Storage.dyn_cast()) OS << Ovl->getNameAsString(); else if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName()) { @@ -82,12 +82,12 @@ void TemplateName::dump() const { print(llvm::errs(), PrintingPolicy(LO)); } -TemplateDecl *QualifiedTemplateName::getTemplateDecl() const { - return dyn_cast(Template); +TemplateDecl *QualifiedTemplateName::getTemplateDecl() const { + return dyn_cast(Template); } OverloadedFunctionDecl * QualifiedTemplateName::getOverloadedFunctionDecl() const { - return dyn_cast(Template); + return dyn_cast(Template); } diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp index 9bcfb2ad8fd590f8ed4d802b0b77db18df11f9f3..1a6ea0a136676744228e7cf831132409ffe74045 100644 --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -64,7 +64,7 @@ void DependentSizedArrayType::Destroy(ASTContext& C) { C.Deallocate(this); } -void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, +void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, QualType ET, ArraySizeModifier SizeMod, @@ -76,8 +76,8 @@ void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, E->Profile(ID, Context, true); } -void -DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, +void +DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, QualType ElementType, Expr *SizeExpr) { ID.AddPointer(ElementType.getAsOpaquePtr()); @@ -99,7 +99,7 @@ const Type *Type::getArrayElementTypeNoTypeQual() const { // If this is directly an array type, return it. if (const ArrayType *ATy = dyn_cast(this)) return ATy->getElementType().getTypePtr(); - + // If the canonical form of this type isn't the right kind, reject it. if (!isa(CanonicalType)) { // Look through type qualifiers @@ -107,7 +107,7 @@ const Type *Type::getArrayElementTypeNoTypeQual() const { return AT->getElementType().getTypePtr(); return 0; } - + // If this is a typedef for an array type, strip the typedef off without // losing all typedef information. return cast(getDesugaredType())->getElementType().getTypePtr(); @@ -153,7 +153,7 @@ QualType Type::getDesugaredType(bool ForDisplay) const { if (!DTT->getUnderlyingType()->isDependentType()) return DTT->getUnderlyingType().getDesugaredType(); } - if (const TemplateSpecializationType *Spec + if (const TemplateSpecializationType *Spec = dyn_cast(this)) { if (ForDisplay) return QualType(this, 0); @@ -262,7 +262,7 @@ const ComplexType *Type::getAsComplexIntegerType() const { return CTy; return 0; } - + // If the canonical form of this type isn't what we want, reject it. if (!isa(CanonicalType)) { // Look through type qualifiers (e.g. ExtQualType's). @@ -270,7 +270,7 @@ const ComplexType *Type::getAsComplexIntegerType() const { return CanonicalType.getUnqualifiedType()->getAsComplexIntegerType(); return 0; } - + // If this is a typedef for a complex type, strip the typedef off without // losing all typedef information. return cast(getDesugaredType()); @@ -306,7 +306,7 @@ const FunctionType *Type::getAsFunctionType() const { return CanonicalType.getUnqualifiedType()->getAsFunctionType(); return 0; } - + // If this is a typedef for a function type, strip the typedef off without // losing all typedef information. return cast(getDesugaredType()); @@ -374,7 +374,7 @@ const RecordType *Type::getAsStructureType() const { if (const RecordType *RT = dyn_cast(CanonicalType)) { if (!RT->getDecl()->isStruct()) return 0; - + // If this is a typedef for a structure type, strip the typedef off without // losing all typedef information. return cast(getDesugaredType()); @@ -385,13 +385,13 @@ const RecordType *Type::getAsStructureType() const { return 0; } -const RecordType *Type::getAsUnionType() const { +const RecordType *Type::getAsUnionType() const { // If this is directly a union type, return it. if (const RecordType *RT = dyn_cast(this)) { if (RT->getDecl()->isUnion()) return RT; } - + // If the canonical form of this type isn't the right kind, reject it. if (const RecordType *RT = dyn_cast(CanonicalType)) { if (!RT->getDecl()->isUnion()) @@ -401,7 +401,7 @@ const RecordType *Type::getAsUnionType() const { // losing all typedef information. return cast(getDesugaredType()); } - + // Look through type qualifiers if (isa(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsUnionType(); @@ -419,7 +419,7 @@ const ComplexType *Type::getAsComplexType() const { // Are we directly a complex type? if (const ComplexType *CTy = dyn_cast(this)) return CTy; - + // If the canonical form of this type isn't the right kind, reject it. if (!isa(CanonicalType)) { // Look through type qualifiers @@ -437,7 +437,7 @@ const VectorType *Type::getAsVectorType() const { // Are we directly a vector type? if (const VectorType *VTy = dyn_cast(this)) return VTy; - + // If the canonical form of this type isn't the right kind, reject it. if (!isa(CanonicalType)) { // Look through type qualifiers @@ -455,9 +455,9 @@ const ExtVectorType *Type::getAsExtVectorType() const { // Are we directly an OpenCU vector type? if (const ExtVectorType *VTy = dyn_cast(this)) return VTy; - + // If the canonical form of this type isn't the right kind, reject it. - if (!isa(CanonicalType)) { + if (!isa(CanonicalType)) { // Look through type qualifiers if (isa(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsExtVectorType(); @@ -612,14 +612,14 @@ bool Type::isSignedIntegerType() const { return BT->getKind() >= BuiltinType::Char_S && BT->getKind() <= BuiltinType::LongLong; } - + if (const EnumType *ET = dyn_cast(CanonicalType)) return ET->getDecl()->getIntegerType()->isSignedIntegerType(); - + if (const FixedWidthIntType *FWIT = dyn_cast(CanonicalType)) return FWIT->isSigned(); - + if (const VectorType *VT = dyn_cast(CanonicalType)) return VT->getElementType()->isSignedIntegerType(); if (const ExtQualType *EXTQT = dyn_cast(CanonicalType)) @@ -763,8 +763,8 @@ bool Type::isConstantSizeType() const { /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) /// - a type that can describe objects, but which lacks information needed to /// determine its size. -bool Type::isIncompleteType() const { - switch (CanonicalType->getTypeClass()) { +bool Type::isIncompleteType() const { + switch (CanonicalType->getTypeClass()) { default: return false; case ExtQual: return cast(CanonicalType)->getBaseType()->isIncompleteType(); @@ -816,7 +816,7 @@ bool Type::isPODType() const { return true; case Record: - if (CXXRecordDecl *ClassDecl + if (CXXRecordDecl *ClassDecl = dyn_cast(cast(CanonicalType)->getDecl())) return ClassDecl->isPOD(); @@ -836,7 +836,7 @@ bool Type::isPromotableIntegerType() const { case BuiltinType::Short: case BuiltinType::UShort: return true; - default: + default: return false; } return false; @@ -918,7 +918,7 @@ void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, ID.AddInteger(hasExceptionSpec); if (hasExceptionSpec) { ID.AddInteger(anyExceptionSpec); - for(unsigned i = 0; i != NumExceptions; ++i) + for (unsigned i = 0; i != NumExceptions; ++i) ID.AddPointer(Exs[i].getAsOpaquePtr()); } ID.AddInteger(NoReturn); @@ -957,14 +957,14 @@ QualType TypedefType::LookThroughTypedefs() const { QualType FirstType = getDecl()->getUnderlyingType(); if (!isa(FirstType)) return FirstType; - + // Otherwise, do the fully general loop. unsigned TypeQuals = 0; const TypedefType *TDT = this; while (1) { QualType CurType = TDT->getDecl()->getUnderlyingType(); - - + + /// FIXME: /// FIXME: This is incorrect for ExtQuals! /// FIXME: @@ -980,25 +980,25 @@ TypeOfExprType::TypeOfExprType(Expr *E, QualType can) : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) { } -void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, +void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, Expr *E) { E->Profile(ID, Context, true); } DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) - : Type(Decltype, can, E->isTypeDependent()), E(E), + : Type(Decltype, can, E->isTypeDependent()), E(E), UnderlyingType(underlyingType) { } DependentDecltypeType::DependentDecltypeType(ASTContext &Context, Expr *E) : DecltypeType(E, Context.DependentTy), Context(Context) { } -void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, +void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, Expr *E) { E->Profile(ID, Context, true); } -TagType::TagType(TypeClass TC, TagDecl *D, QualType can) +TagType::TagType(TypeClass TC, TagDecl *D, QualType can) : Type(TC, can, D->isDependentType()), decl(D, 0) {} bool RecordType::classof(const TagType *TT) { @@ -1009,7 +1009,7 @@ bool EnumType::classof(const TagType *TT) { return isa(TT->getDecl()); } -bool +bool TemplateSpecializationType:: anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) { for (unsigned Idx = 0; Idx < NumArgs; ++Idx) { @@ -1017,12 +1017,12 @@ anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) { case TemplateArgument::Null: assert(false && "Should not have a NULL template argument"); break; - + case TemplateArgument::Type: if (Args[Idx].getAsType()->isDependentType()) return true; break; - + case TemplateArgument::Declaration: case TemplateArgument::Integral: // Never dependent @@ -1033,7 +1033,7 @@ anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) { Args[Idx].getAsExpr()->isValueDependent()) return true; break; - + case TemplateArgument::Pack: assert(0 && "FIXME: Implement!"); break; @@ -1044,20 +1044,19 @@ anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) { } TemplateSpecializationType:: -TemplateSpecializationType(ASTContext &Context, TemplateName T, +TemplateSpecializationType(ASTContext &Context, TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon) - : Type(TemplateSpecialization, + : Type(TemplateSpecialization, Canon.isNull()? QualType(this, 0) : Canon, T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)), Context(Context), - Template(T), NumArgs(NumArgs) -{ - assert((!Canon.isNull() || + Template(T), NumArgs(NumArgs) { + assert((!Canon.isNull() || T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) && "No canonical type for non-dependent class template specialization"); - TemplateArgument *TemplateArgs + TemplateArgument *TemplateArgs = reinterpret_cast(this + 1); for (unsigned Arg = 0; Arg < NumArgs; ++Arg) new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]); @@ -1083,10 +1082,10 @@ TemplateSpecializationType::getArg(unsigned Idx) const { return getArgs()[Idx]; } -void -TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, - TemplateName T, - const TemplateArgument *Args, +void +TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, + TemplateName T, + const TemplateArgument *Args, unsigned NumArgs, ASTContext &Context) { T.Profile(ID); @@ -1097,7 +1096,7 @@ TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, const Type *QualifierSet::strip(const Type* T) { QualType DT = T->getDesugaredType(); addCVR(DT.getCVRQualifiers()); - + if (const ExtQualType* EQT = dyn_cast(DT)) { if (EQT->getAddressSpace()) addAddressSpace(EQT->getAddressSpace()); @@ -1162,8 +1161,8 @@ std::string QualType::getAsString() const { return S; } -void -QualType::getAsStringInternal(std::string &S, +void +QualType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const { if (isNull()) { S += "NULL TYPE"; @@ -1186,7 +1185,7 @@ QualType::getAsStringInternal(std::string &S, getTypePtr()->getAsStringInternal(S, Policy); } -void BuiltinType::getAsStringInternal(std::string &S, +void BuiltinType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const { if (S.empty()) { S = getName(Policy.LangOpts); @@ -1238,12 +1237,12 @@ void ExtQualType::getAsStringInternal(std::string &S, const PrintingPolicy &Poli void PointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const { S = '*' + S; - + // Handle things like 'int (*A)[4];' correctly. // FIXME: this should include vectors, but vectors use attributes I guess. if (isa(getPointeeType())) S = '(' + S + ')'; - + getPointeeType().getAsStringInternal(S, Policy); } @@ -1292,7 +1291,7 @@ void ConstantArrayType::getAsStringInternal(std::string &S, const PrintingPolicy S += '['; S += llvm::utostr(getSize().getZExtValue()); S += ']'; - + getElementType().getAsStringInternal(S, Policy); } @@ -1327,17 +1326,17 @@ void IncompleteArrayType::getAsStringInternal(std::string &S, const PrintingPoli void VariableArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const { S += '['; - + if (getIndexTypeQualifier()) { AppendTypeQualList(S, getIndexTypeQualifier()); S += ' '; } - + if (getSizeModifier() == Static) S += "static"; else if (getSizeModifier() == Star) S += '*'; - + if (getSizeExpr()) { std::string SStr; llvm::raw_string_ostream s(SStr); @@ -1345,23 +1344,23 @@ void VariableArrayType::getAsStringInternal(std::string &S, const PrintingPolicy S += s.str(); } S += ']'; - + getElementType().getAsStringInternal(S, Policy); } void DependentSizedArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const { S += '['; - + if (getIndexTypeQualifier()) { AppendTypeQualList(S, getIndexTypeQualifier()); S += ' '; } - + if (getSizeModifier() == Static) S += "static"; else if (getSizeModifier() == Star) S += '*'; - + if (getSizeExpr()) { std::string SStr; llvm::raw_string_ostream s(SStr); @@ -1369,7 +1368,7 @@ void DependentSizedArrayType::getAsStringInternal(std::string &S, const Printing S += s.str(); } S += ']'; - + getElementType().getAsStringInternal(S, Policy); } @@ -1419,7 +1418,7 @@ void TypeOfType::getAsStringInternal(std::string &InnerString, const PrintingPol InnerString = "typeof(" + Tmp + ")" + InnerString; } -void DecltypeType::getAsStringInternal(std::string &InnerString, +void DecltypeType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'decltype(t) X'. InnerString = ' ' + InnerString; @@ -1433,7 +1432,7 @@ void FunctionNoProtoType::getAsStringInternal(std::string &S, const PrintingPoli // If needed for precedence reasons, wrap the inner part in grouping parens. if (!S.empty()) S = "(" + S + ")"; - + S += "()"; if (getNoReturnAttr()) S += " __attribute__((noreturn))"; @@ -1444,7 +1443,7 @@ void FunctionProtoType::getAsStringInternal(std::string &S, const PrintingPolicy // If needed for precedence reasons, wrap the inner part in grouping parens. if (!S.empty()) S = "(" + S + ")"; - + S += "("; std::string Tmp; PrintingPolicy ParamPolicy(Policy); @@ -1455,7 +1454,7 @@ void FunctionProtoType::getAsStringInternal(std::string &S, const PrintingPolicy S += Tmp; Tmp.clear(); } - + if (isVariadic()) { if (getNumArgs()) S += ", "; @@ -1464,7 +1463,7 @@ void FunctionProtoType::getAsStringInternal(std::string &S, const PrintingPolicy // Do not emit int() if we have a proto, emit 'int(void)'. S += "void"; } - + S += ")"; if (getNoReturnAttr()) S += " __attribute__((noreturn))"; @@ -1483,13 +1482,13 @@ void TemplateTypeParmType::getAsStringInternal(std::string &InnerString, const P InnerString = ' ' + InnerString; if (!Name) - InnerString = "type-parameter-" + llvm::utostr_32(Depth) + '-' + + InnerString = "type-parameter-" + llvm::utostr_32(Depth) + '-' + llvm::utostr_32(Index) + InnerString; else InnerString = Name->getName() + InnerString; } -std::string +std::string TemplateSpecializationType::PrintTemplateArgumentList( const TemplateArgument *Args, unsigned NumArgs, @@ -1499,7 +1498,7 @@ TemplateSpecializationType::PrintTemplateArgumentList( for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { if (Arg) SpecString += ", "; - + // Print the argument into a string. std::string ArgString; switch (Args[Arg].getKind()) { @@ -1549,7 +1548,7 @@ TemplateSpecializationType::PrintTemplateArgumentList( return SpecString; } -void +void TemplateSpecializationType:: getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const { std::string SpecString; @@ -1573,7 +1572,7 @@ void QualifiedNameType::getAsStringInternal(std::string &InnerString, const Prin llvm::raw_string_ostream OS(MyString); NNS->print(OS, Policy); } - + std::string TypeStr; PrintingPolicy InnerPolicy(Policy); InnerPolicy.SuppressTagKind = true; @@ -1600,12 +1599,12 @@ void TypenameType::getAsStringInternal(std::string &InnerString, const PrintingP else if (const TemplateSpecializationType *Spec = getTemplateId()) { Spec->getTemplateName().print(OS, Policy, true); OS << TemplateSpecializationType::PrintTemplateArgumentList( - Spec->getArgs(), + Spec->getArgs(), Spec->getNumArgs(), Policy); } } - + if (InnerString.empty()) InnerString.swap(MyString); else @@ -1614,7 +1613,7 @@ void TypenameType::getAsStringInternal(std::string &InnerString, const PrintingP void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID, const ObjCInterfaceDecl *Decl, - ObjCProtocolDecl **protocols, + ObjCProtocolDecl **protocols, unsigned NumProtocols) { ID.AddPointer(Decl); for (unsigned i = 0; i != NumProtocols; i++) @@ -1632,7 +1631,7 @@ void ObjCInterfaceType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; - + std::string ObjCQIString = getDecl()->getNameAsString(); if (getNumProtocols()) { ObjCQIString += '<'; @@ -1649,10 +1648,10 @@ void ObjCInterfaceType::getAsStringInternal(std::string &InnerString, InnerString = ObjCQIString + InnerString; } -void ObjCObjectPointerType::getAsStringInternal(std::string &InnerString, +void ObjCObjectPointerType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const { std::string ObjCQIString; - + if (isObjCIdType() || isObjCQualifiedIdType()) ObjCQIString = "id"; else if (isObjCClassType() || isObjCQualifiedClassType()) @@ -1677,7 +1676,7 @@ void ObjCObjectPointerType::getAsStringInternal(std::string &InnerString, InnerString = ObjCQIString + InnerString; } -void ElaboratedType::getAsStringInternal(std::string &InnerString, +void ElaboratedType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const { std::string TypeStr; PrintingPolicy InnerPolicy(Policy); @@ -1693,7 +1692,7 @@ void TagType::getAsStringInternal(std::string &InnerString, const PrintingPolicy if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; - + const char *Kind = Policy.SuppressTagKind? 0 : getDecl()->getKindName(); const char *ID; if (const IdentifierInfo *II = getDecl()->getIdentifier()) @@ -1707,10 +1706,10 @@ void TagType::getAsStringInternal(std::string &InnerString, const PrintingPolicy // If this is a class template specialization, print the template // arguments. - if (ClassTemplateSpecializationDecl *Spec + if (ClassTemplateSpecializationDecl *Spec = dyn_cast(getDecl())) { const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); - std::string TemplateArgsStr + std::string TemplateArgsStr = TemplateSpecializationType::PrintTemplateArgumentList( TemplateArgs.getFlatArgumentList(), TemplateArgs.flat_size(), @@ -1722,13 +1721,13 @@ void TagType::getAsStringInternal(std::string &InnerString, const PrintingPolicy // Compute the full nested-name-specifier for this type. In C, // this will always be empty. std::string ContextStr; - for (DeclContext *DC = getDecl()->getDeclContext(); + for (DeclContext *DC = getDecl()->getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { std::string MyPart; if (NamespaceDecl *NS = dyn_cast(DC)) { if (NS->getIdentifier()) MyPart = NS->getNameAsString(); - } else if (ClassTemplateSpecializationDecl *Spec + } else if (ClassTemplateSpecializationDecl *Spec = dyn_cast(DC)) { const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); std::string TemplateArgsStr diff --git a/clang/lib/AST/TypeLoc.cpp b/clang/lib/AST/TypeLoc.cpp index 85415ba09abde695083668837c661fa9f18fca85..a95f38897a33630a6012f99d6c758be5386be095 100644 --- a/clang/lib/AST/TypeLoc.cpp +++ b/clang/lib/AST/TypeLoc.cpp @@ -30,7 +30,7 @@ TypeSpecLoc TypeLoc::getTypeSpecLoc() const { if (const DeclaratorLoc *DL = dyn_cast(this)) return DL->getTypeSpecLoc(); - return cast(*this); + return cast(*this); } /// \brief Find the TypeSpecLoc that is part of this TypeLoc and return its @@ -46,9 +46,9 @@ class TypeSizer : public TypeLocVisitor { public: #define ABSTRACT_TYPELOC(CLASS) #define TYPELOC(CLASS, PARENT, TYPE) \ - unsigned Visit##CLASS(CLASS TyLoc) { return TyLoc.getFullDataSize(); } + unsigned Visit##CLASS(CLASS TyLoc) { return TyLoc.getFullDataSize(); } #include "clang/AST/TypeLocNodes.def" - + unsigned VisitTypeLoc(TypeLoc TyLoc) { assert(0 && "A type loc wrapper was not handled!"); return 0; @@ -70,7 +70,7 @@ class NextLoc : public TypeLocVisitor { public: #define TYPELOC(CLASS, PARENT, TYPE) #define DECLARATOR_TYPELOC(CLASS, TYPE) \ - TypeLoc Visit##CLASS(CLASS TyLoc); + TypeLoc Visit##CLASS(CLASS TyLoc); #include "clang/AST/TypeLocNodes.def" TypeLoc VisitTypeSpecLoc(TypeLoc TyLoc) { return TypeLoc(); } @@ -84,16 +84,16 @@ public: } TypeLoc NextLoc::VisitPointerLoc(PointerLoc TL) { - return TL.getPointeeLoc(); + return TL.getPointeeLoc(); } TypeLoc NextLoc::VisitMemberPointerLoc(MemberPointerLoc TL) { - return TL.getPointeeLoc(); + return TL.getPointeeLoc(); } TypeLoc NextLoc::VisitBlockPointerLoc(BlockPointerLoc TL) { - return TL.getPointeeLoc(); + return TL.getPointeeLoc(); } TypeLoc NextLoc::VisitReferenceLoc(ReferenceLoc TL) { - return TL.getPointeeLoc(); + return TL.getPointeeLoc(); } TypeLoc NextLoc::VisitFunctionLoc(FunctionLoc TL) { return TL.getResultLoc(); @@ -105,7 +105,7 @@ TypeLoc NextLoc::VisitArrayLoc(ArrayLoc TL) { /// \brief Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the /// TypeLoc is a PointerLoc and next TypeLoc is for "int". TypeLoc TypeLoc::getNextTypeLoc() const { - return NextLoc().Visit(*this); + return NextLoc().Visit(*this); } //===----------------------------------------------------------------------===// @@ -119,7 +119,7 @@ class TypeSpecRanger : public TypeLocVisitor { public: #define TYPELOC(CLASS, PARENT, TYPE) #define TYPESPEC_TYPELOC(CLASS, TYPE) \ - SourceRange Visit##CLASS(CLASS TyLoc) { return TyLoc.getSourceRange(); } + SourceRange Visit##CLASS(CLASS TyLoc) { return TyLoc.getSourceRange(); } #include "clang/AST/TypeLocNodes.def" SourceRange VisitTypeLoc(TypeLoc TyLoc) { @@ -139,13 +139,13 @@ SourceRange TypeSpecLoc::getSourceRange() const { namespace { class TypeSpecChecker : public TypeLocVisitor { public: - bool VisitTypeSpecLoc(TypeSpecLoc TyLoc) { return true; } + bool VisitTypeSpecLoc(TypeSpecLoc TyLoc) { return true; } }; } bool TypeSpecLoc::classof(const TypeLoc *TL) { - return TypeSpecChecker().Visit(*TL); + return TypeSpecChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -159,7 +159,7 @@ class TypeSpecGetter : public TypeLocVisitor { public: #define TYPELOC(CLASS, PARENT, TYPE) #define DECLARATOR_TYPELOC(CLASS, TYPE) \ - TypeSpecLoc Visit##CLASS(CLASS TyLoc) { return TyLoc.getTypeSpecLoc(); } + TypeSpecLoc Visit##CLASS(CLASS TyLoc) { return TyLoc.getTypeSpecLoc(); } #include "clang/AST/TypeLocNodes.def" TypeSpecLoc VisitTypeLoc(TypeLoc TyLoc) { @@ -179,13 +179,13 @@ namespace { class DeclaratorLocChecker : public TypeLocVisitor { public: - bool VisitDeclaratorLoc(DeclaratorLoc TyLoc) { return true; } + bool VisitDeclaratorLoc(DeclaratorLoc TyLoc) { return true; } }; } bool DeclaratorLoc::classof(const TypeLoc *TL) { - return DeclaratorLocChecker().Visit(*TL); + return DeclaratorLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -197,13 +197,13 @@ namespace { class DefaultTypeSpecLocChecker : public TypeLocVisitor { public: - bool VisitDefaultTypeSpecLoc(DefaultTypeSpecLoc TyLoc) { return true; } + bool VisitDefaultTypeSpecLoc(DefaultTypeSpecLoc TyLoc) { return true; } }; } bool DefaultTypeSpecLoc::classof(const TypeLoc *TL) { - return DefaultTypeSpecLocChecker().Visit(*TL); + return DefaultTypeSpecLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -214,13 +214,13 @@ namespace { class TypedefLocChecker : public TypeLocVisitor { public: - bool VisitTypedefLoc(TypedefLoc TyLoc) { return true; } + bool VisitTypedefLoc(TypedefLoc TyLoc) { return true; } }; } bool TypedefLoc::classof(const TypeLoc *TL) { - return TypedefLocChecker().Visit(*TL); + return TypedefLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -231,13 +231,13 @@ namespace { class PointerLocChecker : public TypeLocVisitor { public: - bool VisitPointerLoc(PointerLoc TyLoc) { return true; } + bool VisitPointerLoc(PointerLoc TyLoc) { return true; } }; } bool PointerLoc::classof(const TypeLoc *TL) { - return PointerLocChecker().Visit(*TL); + return PointerLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -249,13 +249,13 @@ namespace { class BlockPointerLocChecker : public TypeLocVisitor { public: - bool VisitBlockPointerLoc(BlockPointerLoc TyLoc) { return true; } + bool VisitBlockPointerLoc(BlockPointerLoc TyLoc) { return true; } }; } bool BlockPointerLoc::classof(const TypeLoc *TL) { - return BlockPointerLocChecker().Visit(*TL); + return BlockPointerLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -267,13 +267,13 @@ namespace { class MemberPointerLocChecker : public TypeLocVisitor { public: - bool VisitMemberPointerLoc(MemberPointerLoc TyLoc) { return true; } + bool VisitMemberPointerLoc(MemberPointerLoc TyLoc) { return true; } }; } bool MemberPointerLoc::classof(const TypeLoc *TL) { - return MemberPointerLocChecker().Visit(*TL); + return MemberPointerLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -284,13 +284,13 @@ namespace { class ReferenceLocChecker : public TypeLocVisitor { public: - bool VisitReferenceLoc(ReferenceLoc TyLoc) { return true; } + bool VisitReferenceLoc(ReferenceLoc TyLoc) { return true; } }; } bool ReferenceLoc::classof(const TypeLoc *TL) { - return ReferenceLocChecker().Visit(*TL); + return ReferenceLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -301,13 +301,13 @@ namespace { class FunctionLocChecker : public TypeLocVisitor { public: - bool VisitFunctionLoc(FunctionLoc TyLoc) { return true; } + bool VisitFunctionLoc(FunctionLoc TyLoc) { return true; } }; } bool FunctionLoc::classof(const TypeLoc *TL) { - return FunctionLocChecker().Visit(*TL); + return FunctionLocChecker().Visit(*TL); } //===----------------------------------------------------------------------===// @@ -318,11 +318,11 @@ namespace { class ArrayLocChecker : public TypeLocVisitor { public: - bool VisitArrayLoc(ArrayLoc TyLoc) { return true; } + bool VisitArrayLoc(ArrayLoc TyLoc) { return true; } }; } bool ArrayLoc::classof(const TypeLoc *TL) { - return ArrayLocChecker().Visit(*TL); + return ArrayLocChecker().Visit(*TL); } diff --git a/clang/lib/Analysis/AnalysisContext.cpp b/clang/lib/Analysis/AnalysisContext.cpp index da671d62f13792895f9887984173fbe94da72507..a4cb66be04b30c766df348311d47ba75a6bdb0f8 100644 --- a/clang/lib/Analysis/AnalysisContext.cpp +++ b/clang/lib/Analysis/AnalysisContext.cpp @@ -45,18 +45,18 @@ Stmt *AnalysisContext::getBody() { const ImplicitParamDecl *AnalysisContext::getSelfDecl() const { if (const ObjCMethodDecl *MD = dyn_cast(D)) return MD->getSelfDecl(); - + return NULL; } CFG *AnalysisContext::getCFG() { - if (!cfg) + if (!cfg) cfg = CFG::buildCFG(getBody(), &D->getASTContext()); return cfg; } ParentMap &AnalysisContext::getParentMap() { - if (!PM) + if (!PM) PM = new ParentMap(getBody()); return *PM; } @@ -66,12 +66,12 @@ LiveVariables *AnalysisContext::getLiveVariables() { CFG *c = getCFG(); if (!c) return 0; - + liveness = new LiveVariables(D->getASTContext(), *c); liveness->runOnCFG(*c); liveness->runOnAllBlocks(*c, 0, true); } - + return liveness; } @@ -79,7 +79,7 @@ AnalysisContext *AnalysisContextManager::getContext(const Decl *D) { AnalysisContext *&AC = Contexts[D]; if (!AC) AC = new AnalysisContext(D); - + return AC; } @@ -104,14 +104,14 @@ void ScopeContext::Profile(llvm::FoldingSetNodeID &ID, AnalysisContext *ctx, } StackFrameContext* -LocationContextManager::getStackFrame(AnalysisContext *ctx, +LocationContextManager::getStackFrame(AnalysisContext *ctx, const LocationContext *parent, const Stmt *s) { llvm::FoldingSetNodeID ID; StackFrameContext::Profile(ID, ctx, parent, s); void *InsertPos; - StackFrameContext *f = + StackFrameContext *f = cast_or_null(Contexts.FindNodeOrInsertPos(ID, InsertPos)); if (!f) { f = new StackFrameContext(ctx, parent, s); @@ -126,7 +126,7 @@ ScopeContext *LocationContextManager::getScope(AnalysisContext *ctx, llvm::FoldingSetNodeID ID; ScopeContext::Profile(ID, ctx, parent, s); void *InsertPos; - + ScopeContext *scope = cast_or_null(Contexts.FindNodeOrInsertPos(ID, InsertPos)); diff --git a/clang/lib/Analysis/AnalysisManager.cpp b/clang/lib/Analysis/AnalysisManager.cpp index b73e86da8e0b4a73c2fa2ec9fa916715c96da80e..623db17b927debac65bd9c44a39bf17630580e94 100644 --- a/clang/lib/Analysis/AnalysisManager.cpp +++ b/clang/lib/Analysis/AnalysisManager.cpp @@ -17,12 +17,12 @@ using namespace clang; void AnalysisManager::DisplayFunction() { - + if (DisplayedFunction) return; - + DisplayedFunction = true; - + // FIXME: Is getCodeDecl() always a named decl? if (isa(getCodeDecl()) || isa(getCodeDecl())) { diff --git a/clang/lib/Analysis/BasicConstraintManager.cpp b/clang/lib/Analysis/BasicConstraintManager.cpp index cb89d30651079cb1e61a97bd6b9e05f31c124cfb..d0b8289528542ca8450aaa330ca342b828384b6f 100644 --- a/clang/lib/Analysis/BasicConstraintManager.cpp +++ b/clang/lib/Analysis/BasicConstraintManager.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines BasicConstraintManager, a class that tracks simple +// This file defines BasicConstraintManager, a class that tracks simple // equality and inequality constraints on symbolic values of GRState. // //===----------------------------------------------------------------------===// @@ -27,22 +27,22 @@ namespace { class VISIBILITY_HIDDEN ConstEq {}; } typedef llvm::ImmutableMap ConstNotEqTy; typedef llvm::ImmutableMap ConstEqTy; - + static int ConstEqIndex = 0; static int ConstNotEqIndex = 0; namespace clang { template<> struct GRStateTrait : public GRStatePartialTrait { - static inline void* GDMIndex() { return &ConstNotEqIndex; } + static inline void* GDMIndex() { return &ConstNotEqIndex; } }; template<> struct GRStateTrait : public GRStatePartialTrait { - static inline void* GDMIndex() { return &ConstEqIndex; } + static inline void* GDMIndex() { return &ConstEqIndex; } }; -} - +} + namespace { // BasicConstraintManager only tracks equality and inequality constraints of // constants and integer variables. @@ -50,7 +50,7 @@ class VISIBILITY_HIDDEN BasicConstraintManager : public SimpleConstraintManager { GRState::IntSetTy::Factory ISetFactory; public: - BasicConstraintManager(GRStateManager& statemgr) + BasicConstraintManager(GRStateManager& statemgr) : ISetFactory(statemgr.getAllocator()) {} const GRState* AssumeSymNE(const GRState* state, SymbolRef sym, @@ -83,7 +83,7 @@ public: const GRState* RemoveDeadBindings(const GRState* state, SymbolReaper& SymReaper); - void print(const GRState* state, llvm::raw_ostream& Out, + void print(const GRState* state, llvm::raw_ostream& Out, const char* nl, const char *sep); }; @@ -133,7 +133,7 @@ const GRState *BasicConstraintManager::AssumeSymEQ(const GRState *state, // These logic will be handled in another ConstraintManager. const GRState *BasicConstraintManager::AssumeSymLT(const GRState *state, SymbolRef sym, - const llvm::APSInt& V) { + const llvm::APSInt& V) { // Is 'V' the smallest possible value? if (V == llvm::APSInt::getMinValue(V.getBitWidth(), V.isUnsigned())) { // sym cannot be any value less than 'V'. This path is infeasible. @@ -167,14 +167,14 @@ const GRState *BasicConstraintManager::AssumeSymGE(const GRState *state, bool isFeasible = *X >= V; return isFeasible ? state : NULL; } - + // Sym is not a constant, but it is worth looking to see if V is the // maximum integer value. if (V == llvm::APSInt::getMaxValue(V.getBitWidth(), V.isUnsigned())) { // If we know that sym != V, then this condition is infeasible since - // there is no other value greater than V. + // there is no other value greater than V. bool isFeasible = !isNotEqual(state, sym, V); - + // If the path is still feasible then as a consequence we know that // 'sym == V' because we cannot have 'sym > V' (no larger values). // Add this constraint. @@ -193,20 +193,20 @@ BasicConstraintManager::AssumeSymLE(const GRState* state, SymbolRef sym, bool isFeasible = *X <= V; return isFeasible ? state : NULL; } - + // Sym is not a constant, but it is worth looking to see if V is the // minimum integer value. if (V == llvm::APSInt::getMinValue(V.getBitWidth(), V.isUnsigned())) { // If we know that sym != V, then this condition is infeasible since - // there is no other value less than V. + // there is no other value less than V. bool isFeasible = !isNotEqual(state, sym, V); - + // If the path is still feasible then as a consequence we know that // 'sym == V' because we cannot have 'sym < V' (no smaller values). // Add this constraint. return isFeasible ? AddEQ(state, sym, V) : NULL; } - + return state; } @@ -222,10 +222,10 @@ const GRState* BasicConstraintManager::AddNE(const GRState* state, SymbolRef sym // First, retrieve the NE-set associated with the given symbol. ConstNotEqTy::data_type* T = state->get(sym); GRState::IntSetTy S = T ? *T : ISetFactory.GetEmptySet(); - + // Now add V to the NE set. S = ISetFactory.Add(S, &V); - + // Create a new state with the old binding replaced. return state->set(sym, S); } @@ -236,7 +236,7 @@ const llvm::APSInt* BasicConstraintManager::getSymVal(const GRState* state, return T ? *T : NULL; } -bool BasicConstraintManager::isNotEqual(const GRState* state, SymbolRef sym, +bool BasicConstraintManager::isNotEqual(const GRState* state, SymbolRef sym, const llvm::APSInt& V) const { // Retrieve the NE-set associated with the given symbol. @@ -273,14 +273,14 @@ BasicConstraintManager::RemoveDeadBindings(const GRState* state, ConstNotEqTy::Factory& CNEFactory = state->get_context(); for (ConstNotEqTy::iterator I = CNE.begin(), E = CNE.end(); I != E; ++I) { - SymbolRef sym = I.getKey(); + SymbolRef sym = I.getKey(); if (SymReaper.maybeDead(sym)) CNE = CNEFactory.Remove(CNE, sym); } - + return state->set(CNE); } -void BasicConstraintManager::print(const GRState* state, llvm::raw_ostream& Out, +void BasicConstraintManager::print(const GRState* state, llvm::raw_ostream& Out, const char* nl, const char *sep) { // Print equality constraints. @@ -293,23 +293,23 @@ void BasicConstraintManager::print(const GRState* state, llvm::raw_ostream& Out, } // Print != constraints. - + ConstNotEqTy CNE = state->get(); - + if (!CNE.isEmpty()) { Out << nl << sep << "'!=' constraints:"; - + for (ConstNotEqTy::iterator I = CNE.begin(), EI = CNE.end(); I!=EI; ++I) { Out << nl << " $" << I.getKey() << " : "; bool isFirst = true; - - GRState::IntSetTy::iterator J = I.getData().begin(), - EJ = I.getData().end(); - - for ( ; J != EJ; ++J) { + + GRState::IntSetTy::iterator J = I.getData().begin(), + EJ = I.getData().end(); + + for ( ; J != EJ; ++J) { if (isFirst) isFirst = false; else Out << ", "; - + Out << (*J)->getSExtValue(); // Hack: should print to raw_ostream. } } diff --git a/clang/lib/Analysis/BasicObjCFoundationChecks.cpp b/clang/lib/Analysis/BasicObjCFoundationChecks.cpp index 88910990ce29d255697416a3c2baaec0476c0f79..9c20089b4f3cfdc6f7ff3ad96f14e7309083ba36 100644 --- a/clang/lib/Analysis/BasicObjCFoundationChecks.cpp +++ b/clang/lib/Analysis/BasicObjCFoundationChecks.cpp @@ -33,10 +33,10 @@ using namespace clang; static const ObjCInterfaceType* GetReceiverType(const ObjCMessageExpr* ME) { const Expr* Receiver = ME->getReceiver(); - + if (!Receiver) return NULL; - + if (const ObjCObjectPointerType *PT = Receiver->getType()->getAsObjCObjectPointerType()) return PT->getInterfaceType(); @@ -56,75 +56,75 @@ class VISIBILITY_HIDDEN APIMisuse : public BugType { public: APIMisuse(const char* name) : BugType(name, "API Misuse (Apple)") {} }; - + class VISIBILITY_HIDDEN BasicObjCFoundationChecks : public GRSimpleAPICheck { APIMisuse *BT; BugReporter& BR; ASTContext &Ctx; - + bool isNSString(const ObjCInterfaceType *T, const char* suffix); bool AuditNSString(ExplodedNode* N, const ObjCMessageExpr* ME); - - void Warn(ExplodedNode* N, const Expr* E, const std::string& s); + + void Warn(ExplodedNode* N, const Expr* E, const std::string& s); void WarnNilArg(ExplodedNode* N, const Expr* E); - + bool CheckNilArg(ExplodedNode* N, unsigned Arg); public: - BasicObjCFoundationChecks(ASTContext& ctx, BugReporter& br) + BasicObjCFoundationChecks(ASTContext& ctx, BugReporter& br) : BT(0), BR(br), Ctx(ctx) {} - + bool Audit(ExplodedNode* N, GRStateManager&); - -private: - void WarnNilArg(ExplodedNode* N, const ObjCMessageExpr* ME, unsigned Arg) { + +private: + void WarnNilArg(ExplodedNode* N, const ObjCMessageExpr* ME, unsigned Arg) { std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Argument to '" << GetReceiverNameType(ME) << "' method '" << ME->getSelector().getAsString() << "' cannot be nil."; - + // Lazily create the BugType object for NilArg. This will be owned // by the BugReporter object 'BR' once we call BR.EmitWarning. if (!BT) BT = new APIMisuse("nil argument"); - + RangedBugReport *R = new RangedBugReport(*BT, os.str().c_str(), N); R->addRange(ME->getArg(Arg)->getSourceRange()); BR.EmitReport(R); } }; - + } // end anonymous namespace GRSimpleAPICheck* clang::CreateBasicObjCFoundationChecks(ASTContext& Ctx, BugReporter& BR) { - return new BasicObjCFoundationChecks(Ctx, BR); + return new BasicObjCFoundationChecks(Ctx, BR); } bool BasicObjCFoundationChecks::Audit(ExplodedNode* N, GRStateManager&) { - + const ObjCMessageExpr* ME = cast(cast(N->getLocation()).getStmt()); const ObjCInterfaceType *ReceiverType = GetReceiverType(ME); - + if (!ReceiverType) return false; - + const char* name = ReceiverType->getDecl()->getIdentifier()->getName(); - + if (!name) return false; if (name[0] != 'N' || name[1] != 'S') return false; - + name += 2; - - // FIXME: Make all of this faster. + + // FIXME: Make all of this faster. if (isNSString(ReceiverType, name)) return AuditNSString(N, ME); @@ -132,7 +132,7 @@ bool BasicObjCFoundationChecks::Audit(ExplodedNode* N, } static inline bool isNil(SVal X) { - return isa(X); + return isa(X); } //===----------------------------------------------------------------------===// @@ -142,14 +142,14 @@ static inline bool isNil(SVal X) { bool BasicObjCFoundationChecks::CheckNilArg(ExplodedNode* N, unsigned Arg) { const ObjCMessageExpr* ME = cast(cast(N->getLocation()).getStmt()); - + const Expr * E = ME->getArg(Arg); - + if (isNil(N->getState()->getSVal(E))) { WarnNilArg(N, ME, Arg); return true; } - + return false; } @@ -158,35 +158,35 @@ bool BasicObjCFoundationChecks::CheckNilArg(ExplodedNode* N, unsigned Arg) { //===----------------------------------------------------------------------===// bool BasicObjCFoundationChecks::isNSString(const ObjCInterfaceType *T, - const char* suffix) { + const char* suffix) { return !strcmp("String", suffix) || !strcmp("MutableString", suffix); } -bool BasicObjCFoundationChecks::AuditNSString(ExplodedNode* N, +bool BasicObjCFoundationChecks::AuditNSString(ExplodedNode* N, const ObjCMessageExpr* ME) { - + Selector S = ME->getSelector(); - + if (S.isUnarySelector()) return false; // FIXME: This is going to be really slow doing these checks with // lexical comparisons. - + std::string name = S.getAsString(); assert (!name.empty()); const char* cstr = &name[0]; unsigned len = name.size(); - + switch (len) { default: break; - case 8: + case 8: if (!strcmp(cstr, "compare:")) return CheckNilArg(N, 0); - + break; - + case 15: // FIXME: Checking for initWithFormat: will not work in most cases // yet because [NSString alloc] returns id, not NSString*. We will @@ -194,41 +194,41 @@ bool BasicObjCFoundationChecks::AuditNSString(ExplodedNode* N, // to find these errors. if (!strcmp(cstr, "initWithFormat:")) return CheckNilArg(N, 0); - + break; - + case 16: if (!strcmp(cstr, "compare:options:")) return CheckNilArg(N, 0); - + break; - + case 22: if (!strcmp(cstr, "compare:options:range:")) return CheckNilArg(N, 0); - + break; - + case 23: - + if (!strcmp(cstr, "caseInsensitiveCompare:")) return CheckNilArg(N, 0); - + break; case 29: if (!strcmp(cstr, "compare:options:range:locale:")) return CheckNilArg(N, 0); - - break; - + + break; + case 37: if (!strcmp(cstr, "componentsSeparatedByCharactersInSet:")) return CheckNilArg(N, 0); - - break; + + break; } - + return false; } @@ -240,7 +240,7 @@ namespace { class VISIBILITY_HIDDEN AuditCFNumberCreate : public GRSimpleAPICheck { APIMisuse* BT; - + // FIXME: Either this should be refactored into GRSimpleAPICheck, or // it should always be passed with a call to Audit. The latter // approach makes this class more stateless. @@ -249,16 +249,16 @@ class VISIBILITY_HIDDEN AuditCFNumberCreate : public GRSimpleAPICheck { BugReporter& BR; public: - AuditCFNumberCreate(ASTContext& ctx, BugReporter& br) + AuditCFNumberCreate(ASTContext& ctx, BugReporter& br) : BT(0), Ctx(ctx), II(&Ctx.Idents.get("CFNumberCreate")), BR(br){} - + ~AuditCFNumberCreate() {} - + bool Audit(ExplodedNode* N, GRStateManager&); - + private: void AddError(const TypedRegion* R, const Expr* Ex, ExplodedNode *N, - uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind); + uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind); }; } // end anonymous namespace @@ -289,7 +289,7 @@ namespace { public: Optional() : IsKnown(false), Val(0) {} Optional(const T& val) : IsKnown(true), Val(val) {} - + bool isKnown() const { return IsKnown; } const T& getValue() const { @@ -305,12 +305,12 @@ namespace { static Optional GetCFNumberSize(ASTContext& Ctx, uint64_t i) { static unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 }; - + if (i < kCFNumberCharType) return FixedSize[i-1]; - + QualType T; - + switch (i) { case kCFNumberCharType: T = Ctx.CharTy; break; case kCFNumberShortType: T = Ctx.ShortTy; break; @@ -322,11 +322,11 @@ static Optional GetCFNumberSize(ASTContext& Ctx, uint64_t i) { case kCFNumberCFIndexType: case kCFNumberNSIntegerType: case kCFNumberCGFloatType: - // FIXME: We need a way to map from names to Type*. + // FIXME: We need a way to map from names to Type*. default: return Optional(); } - + return Ctx.getTypeSize(T); } @@ -350,72 +350,72 @@ static const char* GetCFNumberTypeStr(uint64_t i) { "kCFNumberNSIntegerType", "kCFNumberCGFloatType" }; - + return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType"; } #endif -bool AuditCFNumberCreate::Audit(ExplodedNode* N,GRStateManager&){ +bool AuditCFNumberCreate::Audit(ExplodedNode* N,GRStateManager&){ const CallExpr* CE = cast(cast(N->getLocation()).getStmt()); - const Expr* Callee = CE->getCallee(); - SVal CallV = N->getState()->getSVal(Callee); + const Expr* Callee = CE->getCallee(); + SVal CallV = N->getState()->getSVal(Callee); const FunctionDecl* FD = CallV.getAsFunctionDecl(); if (!FD || FD->getIdentifier() != II || CE->getNumArgs()!=3) return false; - + // Get the value of the "theType" argument. SVal TheTypeVal = N->getState()->getSVal(CE->getArg(1)); - + // FIXME: We really should allow ranges of valid theType values, and // bifurcate the state appropriately. nonloc::ConcreteInt* V = dyn_cast(&TheTypeVal); - + if (!V) return false; - + uint64_t NumberKind = V->getValue().getLimitedValue(); Optional TargetSize = GetCFNumberSize(Ctx, NumberKind); - + // FIXME: In some cases we can emit an error. if (!TargetSize.isKnown()) return false; - + // Look at the value of the integer being passed by reference. Essentially // we want to catch cases where the value passed in is not equal to the // size of the type being created. SVal TheValueExpr = N->getState()->getSVal(CE->getArg(2)); - + // FIXME: Eventually we should handle arbitrary locations. We can do this // by having an enhanced memory model that does low-level typing. loc::MemRegionVal* LV = dyn_cast(&TheValueExpr); if (!LV) return false; - + const TypedRegion* R = dyn_cast(LV->getBaseRegion()); if (!R) return false; QualType T = Ctx.getCanonicalType(R->getValueType(Ctx)); - + // FIXME: If the pointee isn't an integer type, should we flag a warning? // People can do weird stuff with pointers. - - if (!T->isIntegerType()) + + if (!T->isIntegerType()) return false; - + uint64_t SourceSize = Ctx.getTypeSize(T); - + // CHECK: is SourceSize == TargetSize - + if (SourceSize == TargetSize) return false; - + AddError(R, CE->getArg(2), N, SourceSize, TargetSize, NumberKind); - + // FIXME: We can actually create an abstract "CFNumber" object that has // the bits initialized to the provided values. return SourceSize < TargetSize; @@ -425,23 +425,23 @@ void AuditCFNumberCreate::AddError(const TypedRegion* R, const Expr* Ex, ExplodedNode *N, uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind) { - + std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << (SourceSize == 8 ? "An " : "A ") << SourceSize << " bit integer is used to initialize a CFNumber " "object that represents " << (TargetSize == 8 ? "an " : "a ") - << TargetSize << " bit integer. "; + << TargetSize << " bit integer. "; if (SourceSize < TargetSize) os << (TargetSize - SourceSize) - << " bits of the CFNumber value will be garbage." ; + << " bits of the CFNumber value will be garbage." ; else os << (SourceSize - TargetSize) << " bits of the input integer will be lost."; - + // Lazily create the BugType object. This will be owned // by the BugReporter object 'BR' once we call BR.EmitWarning. if (!BT) BT = new APIMisuse("Bad use of CFNumberCreate"); @@ -451,7 +451,7 @@ void AuditCFNumberCreate::AddError(const TypedRegion* R, const Expr* Ex, } GRSimpleAPICheck* -clang::CreateAuditCFNumberCreate(ASTContext& Ctx, BugReporter& BR) { +clang::CreateAuditCFNumberCreate(ASTContext& Ctx, BugReporter& BR) { return new AuditCFNumberCreate(Ctx, BR); } @@ -462,22 +462,22 @@ clang::CreateAuditCFNumberCreate(ASTContext& Ctx, BugReporter& BR) { namespace { class VISIBILITY_HIDDEN AuditCFRetainRelease : public GRSimpleAPICheck { APIMisuse *BT; - + // FIXME: Either this should be refactored into GRSimpleAPICheck, or // it should always be passed with a call to Audit. The latter // approach makes this class more stateless. ASTContext& Ctx; IdentifierInfo *Retain, *Release; BugReporter& BR; - + public: - AuditCFRetainRelease(ASTContext& ctx, BugReporter& br) + AuditCFRetainRelease(ASTContext& ctx, BugReporter& br) : BT(0), Ctx(ctx), Retain(&Ctx.Idents.get("CFRetain")), Release(&Ctx.Idents.get("CFRelease")), BR(br){} - + ~AuditCFRetainRelease() {} - + bool Audit(ExplodedNode* N, GRStateManager&); }; } // end anonymous namespace @@ -485,23 +485,23 @@ public: bool AuditCFRetainRelease::Audit(ExplodedNode* N, GRStateManager&) { const CallExpr* CE = cast(cast(N->getLocation()).getStmt()); - + // If the CallExpr doesn't have exactly 1 argument just give up checking. if (CE->getNumArgs() != 1) return false; - + // Check if we called CFRetain/CFRelease. const GRState* state = N->getState(); SVal X = state->getSVal(CE->getCallee()); const FunctionDecl* FD = X.getAsFunctionDecl(); - + if (!FD) return false; - - const IdentifierInfo *FuncII = FD->getIdentifier(); + + const IdentifierInfo *FuncII = FD->getIdentifier(); if (!(FuncII == Retain || FuncII == Release)) return false; - + // Finally, check if the argument is NULL. // FIXME: We should be able to bifurcate the state here, as a successful // check will result in the value not being NULL afterwards. @@ -511,7 +511,7 @@ bool AuditCFRetainRelease::Audit(ExplodedNode* N, GRStateManager&) { if (state->getStateManager().isEqual(state, CE->getArg(0), 0)) { if (!BT) BT = new APIMisuse("null passed to CFRetain/CFRelease"); - + const char *description = (FuncII == Retain) ? "Null pointer argument in call to CFRetain" : "Null pointer argument in call to CFRelease"; @@ -524,10 +524,10 @@ bool AuditCFRetainRelease::Audit(ExplodedNode* N, GRStateManager&) { return false; } - - + + GRSimpleAPICheck* -clang::CreateAuditCFRetainRelease(ASTContext& Ctx, BugReporter& BR) { +clang::CreateAuditCFRetainRelease(ASTContext& Ctx, BugReporter& BR) { return new AuditCFRetainRelease(Ctx, BR); } @@ -541,8 +541,8 @@ void clang::RegisterAppleChecks(GRExprEngine& Eng, const Decl &D) { Eng.AddCheck(CreateBasicObjCFoundationChecks(Ctx, BR), Stmt::ObjCMessageExprClass); - Eng.AddCheck(CreateAuditCFNumberCreate(Ctx, BR), Stmt::CallExprClass); + Eng.AddCheck(CreateAuditCFNumberCreate(Ctx, BR), Stmt::CallExprClass); Eng.AddCheck(CreateAuditCFRetainRelease(Ctx, BR), Stmt::CallExprClass); - + RegisterNSErrorChecks(BR, Eng, D); } diff --git a/clang/lib/Analysis/BasicObjCFoundationChecks.h b/clang/lib/Analysis/BasicObjCFoundationChecks.h index 8aa996095b9b326133a7b4c2556e1c3c166ba9c1..1271ae4ab1c044c2c0ee4fa36e4b748dcaa93869 100644 --- a/clang/lib/Analysis/BasicObjCFoundationChecks.h +++ b/clang/lib/Analysis/BasicObjCFoundationChecks.h @@ -25,24 +25,24 @@ #define LLVM_CLANG_ANALYSIS_BASICOBJCFOUNDATIONCHECKS namespace clang { - + class GRSimpleAPICheck; class ASTContext; -class GRStateManager; +class GRStateManager; class BugReporter; class GRExprEngine; - + GRSimpleAPICheck *CreateBasicObjCFoundationChecks(ASTContext& Ctx, BugReporter& BR); - + GRSimpleAPICheck *CreateAuditCFNumberCreate(ASTContext& Ctx, BugReporter& BR); - + GRSimpleAPICheck *CreateAuditCFRetainRelease(ASTContext& Ctx, BugReporter& BR); - + void RegisterNSErrorChecks(BugReporter& BR, GRExprEngine &Eng, const Decl &D); - + } // end clang namespace #endif diff --git a/clang/lib/Analysis/BasicStore.cpp b/clang/lib/Analysis/BasicStore.cpp index 682feb50d825c421608af72e1e3a8d6833aa562e..388b2e9144da40a814f1eb2c65bf81b2852f3e32 100644 --- a/clang/lib/Analysis/BasicStore.cpp +++ b/clang/lib/Analysis/BasicStore.cpp @@ -20,10 +20,10 @@ using namespace clang; -typedef llvm::ImmutableMap BindingsTy; +typedef llvm::ImmutableMap BindingsTy; namespace { - + class VISIBILITY_HIDDEN BasicStoreSubRegionMap : public SubRegionMap { public: BasicStoreSubRegionMap() {} @@ -32,13 +32,13 @@ public: return true; // Do nothing. No subregions. } }; - + class VISIBILITY_HIDDEN BasicStoreManager : public StoreManager { BindingsTy::Factory VBFactory; public: BasicStoreManager(GRStateManager& mgr) : StoreManager(mgr), VBFactory(mgr.getAllocator()) {} - + ~BasicStoreManager() {} SubRegionMap *getSubRegionMap(const GRState *state) { @@ -47,7 +47,7 @@ public: SValuator::CastResult Retrieve(const GRState *state, Loc loc, QualType T = QualType()); - + const GRState *InvalidateRegion(const GRState *state, const MemRegion *R, const Expr *E, unsigned Count); @@ -57,8 +57,8 @@ public: Store scanForIvars(Stmt *B, const Decl* SelfDecl, const MemRegion *SelfRegion, Store St); - - Store BindInternal(Store St, Loc loc, SVal V); + + Store BindInternal(Store St, Loc loc, SVal V); Store Remove(Store St, Loc loc); Store getInitialStore(const LocationContext *InitLoc); @@ -66,27 +66,27 @@ public: virtual Loc getLoc(const VarDecl* VD, const LocationContext *LC) { return ValMgr.makeLoc(MRMgr.getVarRegion(VD, LC)); } - + const GRState *BindCompoundLiteral(const GRState *state, const CompoundLiteralExpr* cl, SVal val) { return state; } - + SVal getLValueVar(const GRState *state, const VarDecl *VD, const LocationContext *LC); SVal getLValueString(const GRState *state, const StringLiteral *S); SVal getLValueCompoundLiteral(const GRState *state, const CompoundLiteralExpr *CL); SVal getLValueIvar(const GRState *state, const ObjCIvarDecl* D, SVal Base); - SVal getLValueField(const GRState *state, SVal Base, const FieldDecl *D); + SVal getLValueField(const GRState *state, SVal Base, const FieldDecl *D); SVal getLValueElement(const GRState *state, QualType elementType, SVal Base, SVal Offset); /// ArrayToPointer - Used by GRExprEngine::VistCast to handle implicit /// conversions between arrays and pointers. SVal ArrayToPointer(Loc Array) { return Array; } - + /// RemoveDeadBindings - Scans a BasicStore of 'state' for dead values. /// It updatees the GRState object in place with the values removed. void RemoveDeadBindings(GRState &state, Stmt* Loc, SymbolReaper& SymReaper, @@ -118,7 +118,7 @@ public: private: ASTContext& getContext() { return StateMgr.getContext(); } }; - + } // end anonymous namespace @@ -131,7 +131,7 @@ SVal BasicStoreManager::getLValueVar(const GRState *state, const VarDecl* VD, return ValMgr.makeLoc(MRMgr.getVarRegion(VD, LC)); } -SVal BasicStoreManager::getLValueString(const GRState *state, +SVal BasicStoreManager::getLValueString(const GRState *state, const StringLiteral* S) { return ValMgr.makeLoc(MRMgr.getStringRegion(S)); } @@ -144,7 +144,7 @@ SVal BasicStoreManager::getLValueCompoundLiteral(const GRState *state, SVal BasicStoreManager::getLValueIvar(const GRState *state, const ObjCIvarDecl* D, SVal Base) { - + if (Base.isUnknownOrUndef()) return Base; @@ -154,7 +154,7 @@ SVal BasicStoreManager::getLValueIvar(const GRState *state, const MemRegion *BaseR = cast(BaseL).getRegion(); return ValMgr.makeLoc(MRMgr.getObjCIvarRegion(D, BaseR)); } - + return UnknownVal(); } @@ -163,10 +163,10 @@ SVal BasicStoreManager::getLValueField(const GRState *state, SVal Base, if (Base.isUnknownOrUndef()) return Base; - - Loc BaseL = cast(Base); + + Loc BaseL = cast(Base); const MemRegion* BaseR = 0; - + switch(BaseL.getSubKind()) { case loc::GotoLabelKind: return UndefinedVal(); @@ -174,7 +174,7 @@ SVal BasicStoreManager::getLValueField(const GRState *state, SVal Base, case loc::MemRegionKind: BaseR = cast(BaseL).getRegion(); break; - + case loc::ConcreteIntKind: // While these seem funny, this can happen through casts. // FIXME: What we should return is the field offset. For example, @@ -186,7 +186,7 @@ SVal BasicStoreManager::getLValueField(const GRState *state, SVal Base, assert ("Unhandled Base."); return Base; } - + return ValMgr.makeLoc(MRMgr.getFieldRegion(D, BaseR)); } @@ -196,18 +196,18 @@ SVal BasicStoreManager::getLValueElement(const GRState *state, if (Base.isUnknownOrUndef()) return Base; - - Loc BaseL = cast(Base); + + Loc BaseL = cast(Base); const MemRegion* BaseR = 0; - + switch(BaseL.getSubKind()) { case loc::GotoLabelKind: // Technically we can get here if people do funny things with casts. return UndefinedVal(); - + case loc::MemRegionKind: { const MemRegion *R = cast(BaseL).getRegion(); - + if (isa(R)) { // int x; // char* y = (char*) &x; @@ -215,12 +215,12 @@ SVal BasicStoreManager::getLValueElement(const GRState *state, // y[0] = 'a'; return Base; } - + if (isa(R) || isa(R)) { BaseR = R; break; } - + break; } @@ -230,13 +230,13 @@ SVal BasicStoreManager::getLValueElement(const GRState *state, // add the field offset to the integer value. That way funny things // like this work properly: &(((struct foo *) 0xa)->f) return Base; - + default: assert ("Unhandled Base."); return Base; } - - if (BaseR) { + + if (BaseR) { return ValMgr.makeLoc(MRMgr.getElementRegion(elementType, UnknownVal(), BaseR, getContext())); } @@ -246,38 +246,38 @@ SVal BasicStoreManager::getLValueElement(const GRState *state, static bool isHigherOrderRawPtr(QualType T, ASTContext &C) { bool foundPointer = false; - while (1) { + while (1) { const PointerType *PT = T->getAs(); if (!PT) { if (!foundPointer) return false; - + // intptr_t* or intptr_t**, etc? if (T->isIntegerType() && C.getTypeSize(T) == C.getTypeSize(C.VoidPtrTy)) return true; - + QualType X = C.getCanonicalType(T).getUnqualifiedType(); return X == C.VoidTy; } - + foundPointer = true; T = PT->getPointeeType(); - } + } } - + SValuator::CastResult BasicStoreManager::Retrieve(const GRState *state, Loc loc, QualType T) { - + if (isa(loc)) return SValuator::CastResult(state, UnknownVal()); - + assert(!isa(loc)); - + switch (loc.getSubKind()) { case loc::MemRegionKind: { const MemRegion* R = cast(loc).getRegion(); - + if (const ElementRegion *ER = dyn_cast(R)) { // Just support void**, void***, intptr_t*, intptr_t**, etc., for now. // This is needed to handle OSCompareAndSwapPtr() and friends. @@ -286,45 +286,45 @@ SValuator::CastResult BasicStoreManager::Retrieve(const GRState *state, if (!isHigherOrderRawPtr(T, Ctx)) return SValuator::CastResult(state, UnknownVal()); - + // FIXME: Should check for element 0. // Otherwise, strip the element region. R = ER->getSuperRegion(); } - + if (!(isa(R) || isa(R))) return SValuator::CastResult(state, UnknownVal()); - + BindingsTy B = GetBindings(state->getStore()); BindingsTy::data_type *Val = B.lookup(R); - + if (!Val) break; - + return CastRetrievedVal(*Val, state, cast(R), T); } - + case loc::ConcreteIntKind: // Some clients may call GetSVal with such an option simply because // they are doing a quick scan through their Locs (potentially to // invalidate their bindings). Just return Undefined. return SValuator::CastResult(state, UndefinedVal()); - + default: assert (false && "Invalid Loc."); break; } - + return SValuator::CastResult(state, UnknownVal()); } - -Store BasicStoreManager::BindInternal(Store store, Loc loc, SVal V) { + +Store BasicStoreManager::BindInternal(Store store, Loc loc, SVal V) { if (isa(loc)) return store; const MemRegion* R = cast(loc).getRegion(); ASTContext &C = StateMgr.getContext(); - + // Special case: handle store of pointer values (Loc) to pointers via // a cast to intXX_t*, void*, etc. This is needed to handle // OSCompareAndSwap32Barrier/OSCompareAndSwap64Barrier. @@ -332,20 +332,20 @@ Store BasicStoreManager::BindInternal(Store store, Loc loc, SVal V) { if (const ElementRegion *ER = dyn_cast(R)) { // FIXME: Should check for index 0. QualType T = ER->getLocationType(C); - + if (isHigherOrderRawPtr(T, C)) R = ER->getSuperRegion(); - } - + } + if (!(isa(R) || isa(R))) return store; const TypedRegion *TyR = cast(R); - + // Do not bind to arrays. We need to explicitly check for this so that // we do not encounter any weirdness of trying to load/store from arrays. if (TyR->isBoundable() && TyR->getValueType(C)->isArrayType()) - return store; + return store; if (nonloc::LocAsInteger *X = dyn_cast(&V)) { // Only convert 'V' to a location iff the underlying region type @@ -354,7 +354,7 @@ Store BasicStoreManager::BindInternal(Store store, Loc loc, SVal V) { // a pointer. We may wish to flag a type error here if the types // are incompatible. This may also cause lots of breakage // elsewhere. Food for thought. - if (TyR->isBoundable() && Loc::IsLocType(TyR->getValueType(C))) + if (TyR->isBoundable() && Loc::IsLocType(TyR->getValueType(C))) V = X->getLoc(); } @@ -368,10 +368,10 @@ Store BasicStoreManager::Remove(Store store, Loc loc) { switch (loc.getSubKind()) { case loc::MemRegionKind: { const MemRegion* R = cast(loc).getRegion(); - + if (!(isa(R) || isa(R))) return store; - + return VBFactory.Remove(GetBindings(store), R).getRoot(); } default: @@ -384,11 +384,11 @@ void BasicStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, SymbolReaper& SymReaper, llvm::SmallVectorImpl& RegionRoots) -{ +{ Store store = state.getStore(); BindingsTy B = GetBindings(store); typedef SVal::symbol_iterator symbol_iterator; - + // Iterate over the variable bindings. for (BindingsTy::iterator I=B.begin(), E=B.end(); I!=E ; ++I) { if (const VarRegion *VR = dyn_cast(I.getKey())) { @@ -402,20 +402,20 @@ BasicStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, } else continue; - + // Mark the bindings in the data as live. SVal X = I.getData(); for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI) SymReaper.markLive(*SI); } - + // Scan for live variables and live symbols. llvm::SmallPtrSet Marked; - + while (!RegionRoots.empty()) { const MemRegion* MR = RegionRoots.back(); RegionRoots.pop_back(); - + while (MR) { if (const SymbolicRegion* SymR = dyn_cast(MR)) { SymReaper.markLive(SymR->getSymbol()); @@ -424,17 +424,17 @@ BasicStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, else if (isa(MR) || isa(MR)) { if (Marked.count(MR)) break; - - Marked.insert(MR); + + Marked.insert(MR); SVal X = Retrieve(&state, loc::MemRegionVal(MR)).getSVal(); - + // FIXME: We need to handle symbols nested in region definitions. for (symbol_iterator SI=X.symbol_begin(),SE=X.symbol_end();SI!=SE;++SI) SymReaper.markLive(*SI); - + if (!isa(X)) break; - + const loc::MemRegionVal& LVD = cast(X); RegionRoots.push_back(LVD.getRegion()); break; @@ -445,15 +445,15 @@ BasicStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, break; } } - - // Remove dead variable bindings. + + // Remove dead variable bindings. for (BindingsTy::iterator I=B.begin(), E=B.end(); I!=E ; ++I) { const MemRegion* R = I.getKey(); - + if (!Marked.count(R)) { store = Remove(store, ValMgr.makeLoc(R)); SVal X = I.getData(); - + for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI) SymReaper.maybeDead(*SI); } @@ -467,10 +467,10 @@ Store BasicStoreManager::scanForIvars(Stmt *B, const Decl* SelfDecl, const MemRegion *SelfRegion, Store St) { for (Stmt::child_iterator CI=B->child_begin(), CE=B->child_end(); CI != CE; ++CI) { - + if (!*CI) continue; - + // Check if the statement is an ivar reference. We only // care about self.ivar. if (ObjCIvarRefExpr *IV = dyn_cast(*CI)) { @@ -478,8 +478,8 @@ Store BasicStoreManager::scanForIvars(Stmt *B, const Decl* SelfDecl, if (const DeclRefExpr *DR = dyn_cast(Base)) { if (DR->getDecl() == SelfDecl) { const MemRegion *IVR = MRMgr.getObjCIvarRegion(IV->getDecl(), - SelfRegion); - SVal X = ValMgr.getRegionValueSymbolVal(IVR); + SelfRegion); + SVal X = ValMgr.getRegionValueSymbolVal(IVR); St = BindInternal(St, ValMgr.makeLoc(IVR), X); } } @@ -487,11 +487,11 @@ Store BasicStoreManager::scanForIvars(Stmt *B, const Decl* SelfDecl, else St = scanForIvars(*CI, SelfDecl, SelfRegion, St); } - + return St; } -Store BasicStoreManager::getInitialStore(const LocationContext *InitLoc) { +Store BasicStoreManager::getInitialStore(const LocationContext *InitLoc) { // The LiveVariables information already has a compilation of all VarDecls // used in the function. Iterate through this set, and "symbolicate" // any VarDecl whose value originally comes from outside the function. @@ -504,7 +504,7 @@ Store BasicStoreManager::getInitialStore(const LocationContext *InitLoc) { // Handle implicit parameters. if (ImplicitParamDecl* PD = dyn_cast(ND)) { - const Decl& CD = *InitLoc->getDecl(); + const Decl& CD = *InitLoc->getDecl(); if (const ObjCMethodDecl* MD = dyn_cast(&CD)) { if (MD->getSelfDecl() == PD) { // FIXME: Just use a symbolic region, and remove ObjCObjectRegion @@ -512,10 +512,10 @@ Store BasicStoreManager::getInitialStore(const LocationContext *InitLoc) { const ObjCObjectRegion *SelfRegion = MRMgr.getObjCObjectRegion(MD->getClassInterface(), MRMgr.getHeapRegion()); - + St = BindInternal(St, ValMgr.makeLoc(MRMgr.getVarRegion(PD, InitLoc)), ValMgr.makeLoc(SelfRegion)); - + // Scan the method for ivar references. While this requires an // entire AST scan, the cost should not be high in practice. St = scanForIvars(MD->getBody(), PD, SelfRegion, St); @@ -543,9 +543,9 @@ Store BasicStoreManager::getInitialStore(const LocationContext *InitLoc) { Store BasicStoreManager::BindDeclInternal(Store store, const VarDecl* VD, const LocationContext *LC, SVal* InitVal) { - + BasicValueFactory& BasicVals = StateMgr.getBasicVals(); - + // BasicStore does not model arrays and structs. if (VD->getType()->isArrayType() || VD->getType()->isStructureType()) return store; @@ -560,14 +560,14 @@ Store BasicStoreManager::BindDeclInternal(Store store, const VarDecl* VD, // Static global variables should not be visited here. assert(!(VD->getStorageClass() == VarDecl::Static && VD->isFileVarDecl())); - + // Process static variables. if (VD->getStorageClass() == VarDecl::Static) { // C99: 6.7.8 Initialization // If an object that has static storage duration is not initialized - // explicitly, then: - // —if it has pointer type, it is initialized to a null pointer; - // —if it has arithmetic type, it is initialized to (positive or + // explicitly, then: + // —if it has pointer type, it is initialized to a null pointer; + // —if it has arithmetic type, it is initialized to (positive or // unsigned) zero; if (!InitVal) { QualType T = VD->getType(); @@ -598,18 +598,18 @@ Store BasicStoreManager::BindDeclInternal(Store store, const VarDecl* VD, void BasicStoreManager::print(Store store, llvm::raw_ostream& Out, const char* nl, const char *sep) { - + BindingsTy B = GetBindings(store); Out << "Variables:" << nl; - + bool isFirst = true; - + for (BindingsTy::iterator I=B.begin(), E=B.end(); I != E; ++I) { if (isFirst) isFirst = false; else Out << nl; - + Out << ' ' << I.getKey() << " : " << I.getData(); } } @@ -617,7 +617,7 @@ void BasicStoreManager::print(Store store, llvm::raw_ostream& Out, void BasicStoreManager::iterBindings(Store store, BindingsHandler& f) { BindingsTy B = GetBindings(store); - + for (BindingsTy::iterator I=B.begin(), E=B.end(); I != E; ++I) f.HandleBinding(*this, store, I.getKey(), I.getData()); @@ -634,10 +634,10 @@ const GRState *BasicStoreManager::InvalidateRegion(const GRState *state, const Expr *E, unsigned Count) { R = R->getBaseRegion(); - + if (!(isa(R) || isa(R))) return state; - + QualType T = cast(R)->getValueType(R->getContext()); SVal V = ValMgr.getConjuredSymbolVal(E, T, Count); return Bind(state, loc::MemRegionVal(R), V); diff --git a/clang/lib/Analysis/BasicValueFactory.cpp b/clang/lib/Analysis/BasicValueFactory.cpp index 5ed6d2276947fdcbfc5b164b09d01a98bf451735..b33c277f86f90c9d68fba9db0798e2c671938b7b 100644 --- a/clang/lib/Analysis/BasicValueFactory.cpp +++ b/clang/lib/Analysis/BasicValueFactory.cpp @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// // // This file defines BasicValueFactory, a class that manages the lifetime -// of APSInt objects and symbolic constraints used by GRExprEngine +// of APSInt objects and symbolic constraints used by GRExprEngine // and related classes. // //===----------------------------------------------------------------------===// @@ -17,7 +17,7 @@ using namespace clang; -void CompoundValData::Profile(llvm::FoldingSetNodeID& ID, QualType T, +void CompoundValData::Profile(llvm::FoldingSetNodeID& ID, QualType T, llvm::ImmutableList L) { T.Profile(ID); ID.AddPointer(L.getInternalPointer()); @@ -40,7 +40,7 @@ template<> struct FoldingSetTrait { ID.AddPointer( (void*) X.second); } }; - + template<> struct FoldingSetTrait { static inline void Profile(const SValPair& X, llvm::FoldingSetNodeID& ID) { X.first.Profile(ID); @@ -61,8 +61,8 @@ BasicValueFactory::~BasicValueFactory() { // frees an aux. memory allocated to represent very large constants. for (APSIntSetTy::iterator I=APSIntSet.begin(), E=APSIntSet.end(); I!=E; ++I) I->getValue().~APSInt(); - - delete (PersistentSValsTy*) PersistentSVals; + + delete (PersistentSValsTy*) PersistentSVals; delete (PersistentSValPairsTy*) PersistentSValPairs; } @@ -70,16 +70,16 @@ const llvm::APSInt& BasicValueFactory::getValue(const llvm::APSInt& X) { llvm::FoldingSetNodeID ID; void* InsertPos; typedef llvm::FoldingSetNodeWrapper FoldNodeTy; - + X.Profile(ID); FoldNodeTy* P = APSIntSet.FindNodeOrInsertPos(ID, InsertPos); - - if (!P) { + + if (!P) { P = (FoldNodeTy*) BPAlloc.Allocate(); new (P) FoldNodeTy(X); APSIntSet.InsertNode(P, InsertPos); } - + return *P; } @@ -92,22 +92,22 @@ const llvm::APSInt& BasicValueFactory::getValue(const llvm::APInt& X, const llvm::APSInt& BasicValueFactory::getValue(uint64_t X, unsigned BitWidth, bool isUnsigned) { llvm::APSInt V(BitWidth, isUnsigned); - V = X; + V = X; return getValue(V); } const llvm::APSInt& BasicValueFactory::getValue(uint64_t X, QualType T) { - + unsigned bits = Ctx.getTypeSize(T); llvm::APSInt V(bits, T->isUnsignedIntegerType() || Loc::IsLocType(T)); V = X; return getValue(V); } -const CompoundValData* +const CompoundValData* BasicValueFactory::getCompoundValData(QualType T, llvm::ImmutableList Vals) { - + llvm::FoldingSetNodeID ID; CompoundValData::Profile(ID, T, Vals); void* InsertPos; @@ -129,104 +129,104 @@ BasicValueFactory::getLazyCompoundValData(const GRState *state, llvm::FoldingSetNodeID ID; LazyCompoundValData::Profile(ID, state, region); void* InsertPos; - + LazyCompoundValData *D = LazyCompoundValDataSet.FindNodeOrInsertPos(ID, InsertPos); - + if (!D) { D = (LazyCompoundValData*) BPAlloc.Allocate(); new (D) LazyCompoundValData(state, region); LazyCompoundValDataSet.InsertNode(D, InsertPos); } - + return D; } const llvm::APSInt* BasicValueFactory::EvaluateAPSInt(BinaryOperator::Opcode Op, const llvm::APSInt& V1, const llvm::APSInt& V2) { - + switch (Op) { default: assert (false && "Invalid Opcode."); - + case BinaryOperator::Mul: return &getValue( V1 * V2 ); - + case BinaryOperator::Div: return &getValue( V1 / V2 ); - + case BinaryOperator::Rem: return &getValue( V1 % V2 ); - + case BinaryOperator::Add: return &getValue( V1 + V2 ); - + case BinaryOperator::Sub: return &getValue( V1 - V2 ); - + case BinaryOperator::Shl: { // FIXME: This logic should probably go higher up, where we can // test these conditions symbolically. - + // FIXME: Expand these checks to include all undefined behavior. - + if (V2.isSigned() && V2.isNegative()) return NULL; - + uint64_t Amt = V2.getZExtValue(); - + if (Amt > V1.getBitWidth()) return NULL; - + return &getValue( V1.operator<<( (unsigned) Amt )); } - + case BinaryOperator::Shr: { - + // FIXME: This logic should probably go higher up, where we can // test these conditions symbolically. - + // FIXME: Expand these checks to include all undefined behavior. - + if (V2.isSigned() && V2.isNegative()) return NULL; - + uint64_t Amt = V2.getZExtValue(); - + if (Amt > V1.getBitWidth()) return NULL; - + return &getValue( V1.operator>>( (unsigned) Amt )); } - + case BinaryOperator::LT: return &getTruthValue( V1 < V2 ); - + case BinaryOperator::GT: return &getTruthValue( V1 > V2 ); - + case BinaryOperator::LE: return &getTruthValue( V1 <= V2 ); - + case BinaryOperator::GE: return &getTruthValue( V1 >= V2 ); - + case BinaryOperator::EQ: return &getTruthValue( V1 == V2 ); - + case BinaryOperator::NE: return &getTruthValue( V1 != V2 ); - + // Note: LAnd, LOr, Comma are handled specially by higher-level logic. - + case BinaryOperator::And: return &getValue( V1 & V2 ); - + case BinaryOperator::Or: return &getValue( V1 | V2 ); - + case BinaryOperator::Xor: return &getValue( V1 ^ V2 ); } @@ -235,21 +235,21 @@ BasicValueFactory::EvaluateAPSInt(BinaryOperator::Opcode Op, const std::pair& BasicValueFactory::getPersistentSValWithData(const SVal& V, uintptr_t Data) { - + // Lazily create the folding set. if (!PersistentSVals) PersistentSVals = new PersistentSValsTy(); - + llvm::FoldingSetNodeID ID; void* InsertPos; V.Profile(ID); ID.AddPointer((void*) Data); - + PersistentSValsTy& Map = *((PersistentSValsTy*) PersistentSVals); - + typedef llvm::FoldingSetNodeWrapper FoldNodeTy; FoldNodeTy* P = Map.FindNodeOrInsertPos(ID, InsertPos); - - if (!P) { + + if (!P) { P = (FoldNodeTy*) BPAlloc.Allocate(); new (P) FoldNodeTy(std::make_pair(V, Data)); Map.InsertNode(P, InsertPos); @@ -260,31 +260,31 @@ BasicValueFactory::getPersistentSValWithData(const SVal& V, uintptr_t Data) { const std::pair& BasicValueFactory::getPersistentSValPair(const SVal& V1, const SVal& V2) { - + // Lazily create the folding set. if (!PersistentSValPairs) PersistentSValPairs = new PersistentSValPairsTy(); - + llvm::FoldingSetNodeID ID; void* InsertPos; V1.Profile(ID); V2.Profile(ID); - + PersistentSValPairsTy& Map = *((PersistentSValPairsTy*) PersistentSValPairs); - + typedef llvm::FoldingSetNodeWrapper FoldNodeTy; FoldNodeTy* P = Map.FindNodeOrInsertPos(ID, InsertPos); - - if (!P) { + + if (!P) { P = (FoldNodeTy*) BPAlloc.Allocate(); new (P) FoldNodeTy(std::make_pair(V1, V2)); Map.InsertNode(P, InsertPos); } - + return P->getValue(); } const SVal* BasicValueFactory::getPersistentSVal(SVal X) { return &getPersistentSValWithData(X, 0).first; -} +} diff --git a/clang/lib/Analysis/BugReporter.cpp b/clang/lib/Analysis/BugReporter.cpp index e54a50078e91d81631075b1b9d2d9340a2124fb4..23ca53d6e97880f28486c9eb76050f5a3ba27205 100644 --- a/clang/lib/Analysis/BugReporter.cpp +++ b/clang/lib/Analysis/BugReporter.cpp @@ -53,7 +53,7 @@ static inline const Stmt* GetStmt(ProgramPoint P) { return SP->getStmt(); else if (const BlockEdge* BE = dyn_cast(&P)) return BE->getSrc()->getTerminator(); - + return 0; } @@ -71,7 +71,7 @@ static const Stmt* GetPreviousStmt(const ExplodedNode* N) { for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N)) if (const Stmt *S = GetStmt(N->getLocation())) return S; - + return 0; } @@ -92,30 +92,30 @@ static const Stmt* GetNextStmt(const ExplodedNode* N) { default: break; } - + // Some expressions don't have locations. if (S->getLocStart().isInvalid()) continue; - + return S; } - + return 0; } static inline const Stmt* -GetCurrentOrPreviousStmt(const ExplodedNode* N) { +GetCurrentOrPreviousStmt(const ExplodedNode* N) { if (const Stmt *S = GetStmt(N->getLocation())) return S; - + return GetPreviousStmt(N); } - + static inline const Stmt* -GetCurrentOrNextStmt(const ExplodedNode* N) { +GetCurrentOrNextStmt(const ExplodedNode* N) { if (const Stmt *S = GetStmt(N->getLocation())) return S; - + return GetNextStmt(N); } @@ -132,63 +132,62 @@ class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver { public: NodeMapClosure(NodeBackMap *m) : M(*m) {} ~NodeMapClosure() {} - + const ExplodedNode* getOriginalNode(const ExplodedNode* N) { NodeBackMap::iterator I = M.find(N); return I == M.end() ? 0 : I->second; } }; - + class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext { BugReport *R; PathDiagnosticClient *PDC; llvm::OwningPtr PM; NodeMapClosure NMC; -public: +public: PathDiagnosticBuilder(GRBugReporter &br, - BugReport *r, NodeBackMap *Backmap, + BugReport *r, NodeBackMap *Backmap, PathDiagnosticClient *pdc) : BugReporterContext(br), - R(r), PDC(pdc), NMC(Backmap) - { + R(r), PDC(pdc), NMC(Backmap) { addVisitor(R); } - + PathDiagnosticLocation ExecutionContinues(const ExplodedNode* N); - + PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os, const ExplodedNode* N); - + ParentMap& getParentMap() { if (PM.get() == 0) PM.reset(new ParentMap(getCodeDecl().getBody())); return *PM.get(); } - + const Stmt *getParent(const Stmt *S) { return getParentMap().getParent(S); } - + virtual NodeMapClosure& getNodeResolver() { return NMC; } BugReport& getReport() { return *R; } PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S); - + PathDiagnosticLocation getEnclosingStmtLocation(const PathDiagnosticLocation &L) { if (const Stmt *S = L.asStmt()) return getEnclosingStmtLocation(S); - + return L; } - + PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const { return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive; } bool supportsLogicalOpControlFlow() const { return PDC ? PDC->supportsLogicalOpControlFlow() : true; - } + } }; } // end anonymous namespace @@ -197,10 +196,10 @@ PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode* N) { if (const Stmt *S = GetNextStmt(N)) return PathDiagnosticLocation(S, getSourceManager()); - return FullSourceLoc(N->getLocationContext()->getDecl()->getBodyRBrace(), + return FullSourceLoc(N->getLocationContext()->getDecl()->getBodyRBrace(), getSourceManager()); } - + PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os, const ExplodedNode* N) { @@ -208,9 +207,9 @@ PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os, // Slow, but probably doesn't matter. if (os.str().empty()) os << ' '; - + const PathDiagnosticLocation &Loc = ExecutionContinues(N); - + if (Loc.asStmt()) os << "Execution continues on line " << getSourceManager().getInstantiationLineNumber(Loc.asLocation()) @@ -219,16 +218,16 @@ PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os, os << "Execution jumps to the end of the " << (isa(N->getLocationContext()->getDecl()) ? "method" : "function") << '.'; - + return Loc; } static bool IsNested(const Stmt *S, ParentMap &PM) { if (isa(S) && PM.isConsumedExpr(cast(S))) return true; - + const Stmt *Parent = PM.getParentIgnoreParens(S); - + if (Parent) switch (Parent->getStmtClass()) { case Stmt::ForStmtClass: @@ -238,29 +237,29 @@ static bool IsNested(const Stmt *S, ParentMap &PM) { default: break; } - - return false; + + return false; } PathDiagnosticLocation PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { assert(S && "Null Stmt* passed to getEnclosingStmtLocation"); - ParentMap &P = getParentMap(); + ParentMap &P = getParentMap(); SourceManager &SMgr = getSourceManager(); while (IsNested(S, P)) { const Stmt *Parent = P.getParentIgnoreParens(S); - + if (!Parent) break; - + switch (Parent->getStmtClass()) { case Stmt::BinaryOperatorClass: { const BinaryOperator *B = cast(Parent); if (B->isLogicalOp()) return PathDiagnosticLocation(S, SMgr); break; - } + } case Stmt::CompoundStmtClass: case Stmt::StmtExprClass: return PathDiagnosticLocation(S, SMgr); @@ -270,20 +269,20 @@ PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { if (cast(Parent)->getCond() == S) return PathDiagnosticLocation(Parent, SMgr); else - return PathDiagnosticLocation(S, SMgr); + return PathDiagnosticLocation(S, SMgr); case Stmt::ConditionalOperatorClass: // For '?', if we are referring to condition, just have the edge point // to the entire '?' expression. if (cast(Parent)->getCond() == S) return PathDiagnosticLocation(Parent, SMgr); else - return PathDiagnosticLocation(S, SMgr); + return PathDiagnosticLocation(S, SMgr); case Stmt::DoStmtClass: - return PathDiagnosticLocation(S, SMgr); + return PathDiagnosticLocation(S, SMgr); case Stmt::ForStmtClass: if (cast(Parent)->getBody() == S) - return PathDiagnosticLocation(S, SMgr); - break; + return PathDiagnosticLocation(S, SMgr); + break; case Stmt::IfStmtClass: if (cast(Parent)->getCond() != S) return PathDiagnosticLocation(S, SMgr); @@ -302,7 +301,7 @@ PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { S = Parent; } - + assert(S && "Cannot have null Stmt for PathDiagnosticLocation"); // Special case: DeclStmts can appear in for statement declarations, in which @@ -315,8 +314,8 @@ PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { return PathDiagnosticLocation(Parent, SMgr); default: break; - } - } + } + } } else if (isa(S)) { // Special case: the binary operator represents the initialization @@ -339,84 +338,84 @@ PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { static const VarDecl* GetMostRecentVarDeclBinding(const ExplodedNode* N, GRStateManager& VMgr, SVal X) { - + for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) { - + ProgramPoint P = N->getLocation(); - + if (!isa(P)) continue; - + const DeclRefExpr* DR = dyn_cast(cast(P).getStmt()); - + if (!DR) continue; - + SVal Y = N->getState()->getSVal(DR); - + if (X != Y) continue; - + const VarDecl* VD = dyn_cast(DR->getDecl()); - + if (!VD) continue; - + return VD; } - + return 0; } namespace { -class VISIBILITY_HIDDEN NotableSymbolHandler +class VISIBILITY_HIDDEN NotableSymbolHandler : public StoreManager::BindingsHandler { - + SymbolRef Sym; const GRState* PrevSt; const Stmt* S; GRStateManager& VMgr; const ExplodedNode* Pred; - PathDiagnostic& PD; + PathDiagnostic& PD; BugReporter& BR; - + public: - + NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s, GRStateManager& vmgr, const ExplodedNode* pred, PathDiagnostic& pd, BugReporter& br) : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {} - + bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal V) { - + SymbolRef ScanSym = V.getAsSymbol(); - + if (ScanSym != Sym) return true; - - // Check if the previous state has this binding. + + // Check if the previous state has this binding. SVal X = PrevSt->getSVal(loc::MemRegionVal(R)); - + if (X == V) // Same binding? return true; - + // Different binding. Only handle assignments for now. We don't pull - // this check out of the loop because we will eventually handle other + // this check out of the loop because we will eventually handle other // cases. - + VarDecl *VD = 0; - + if (const BinaryOperator* B = dyn_cast(S)) { if (!B->isAssignmentOp()) return true; - + // What variable did we assign to? DeclRefExpr* DR = dyn_cast(B->getLHS()->IgnoreParenCasts()); - + if (!DR) return true; - + VD = dyn_cast(DR->getDecl()); } else if (const DeclStmt* DS = dyn_cast(S)) { @@ -425,28 +424,28 @@ public: // holds by contruction in the CFG. VD = dyn_cast(*DS->decl_begin()); } - + if (!VD) return true; - + // What is the most recently referenced variable with this binding? const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V); - + if (!MostRecent) return true; - + // Create the diagnostic. FullSourceLoc L(S->getLocStart(), BR.getSourceManager()); - + if (Loc::IsLocType(VD->getType())) { std::string msg = "'" + std::string(VD->getNameAsString()) + "' now aliases '" + MostRecent->getNameAsString() + "'"; - + PD.push_front(new PathDiagnosticEventPiece(L, msg)); } - + return true; - } + } }; } @@ -454,13 +453,13 @@ static void HandleNotableSymbol(const ExplodedNode* N, const Stmt* S, SymbolRef Sym, BugReporter& BR, PathDiagnostic& PD) { - + const ExplodedNode* Pred = N->pred_empty() ? 0 : *N->pred_begin(); const GRState* PrevSt = Pred ? Pred->getState() : 0; - + if (!PrevSt) return; - + // Look at the region bindings of the current state that map to the // specified symbol. Are any of them not in the previous state? GRStateManager& VMgr = cast(BR).getStateManager(); @@ -471,34 +470,34 @@ static void HandleNotableSymbol(const ExplodedNode* N, namespace { class VISIBILITY_HIDDEN ScanNotableSymbols : public StoreManager::BindingsHandler { - + llvm::SmallSet AlreadyProcessed; const ExplodedNode* N; const Stmt* S; GRBugReporter& BR; PathDiagnostic& PD; - + public: ScanNotableSymbols(const ExplodedNode* n, const Stmt* s, GRBugReporter& br, PathDiagnostic& pd) : N(n), S(s), BR(br), PD(pd) {} - + bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal V) { - + SymbolRef ScanSym = V.getAsSymbol(); - + if (!ScanSym) return true; - + if (!BR.isNotable(ScanSym)) return true; - + if (AlreadyProcessed.count(ScanSym)) return true; - + AlreadyProcessed.insert(ScanSym); - + HandleNotableSymbol(N, S, ScanSym, BR, PD); return true; } @@ -516,54 +515,54 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, const ExplodedNode *N) { SourceManager& SMgr = PDB.getSourceManager(); - const ExplodedNode* NextNode = N->pred_empty() + const ExplodedNode* NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); while (NextNode) { - N = NextNode; + N = NextNode; NextNode = GetPredecessorNode(N); - + ProgramPoint P = N->getLocation(); - + if (const BlockEdge* BE = dyn_cast(&P)) { CFGBlock* Src = BE->getSrc(); CFGBlock* Dst = BE->getDst(); Stmt* T = Src->getTerminator(); - + if (!T) continue; - + FullSourceLoc Start(T->getLocStart(), SMgr); - + switch (T->getStmtClass()) { default: break; - + case Stmt::GotoStmtClass: - case Stmt::IndirectGotoStmtClass: { + case Stmt::IndirectGotoStmtClass: { const Stmt* S = GetNextStmt(N); - + if (!S) continue; - + std::string sbuf; - llvm::raw_string_ostream os(sbuf); + llvm::raw_string_ostream os(sbuf); const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S); - + os << "Control jumps to line " << End.asLocation().getInstantiationLineNumber(); PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); break; } - - case Stmt::SwitchStmtClass: { + + case Stmt::SwitchStmtClass: { // Figure out what case arm we took. std::string sbuf; llvm::raw_string_ostream os(sbuf); - + if (Stmt* S = Dst->getLabel()) { PathDiagnosticLocation End(S, SMgr); - + switch (S->getStmtClass()) { default: os << "No cases match in the switch statement. " @@ -574,21 +573,21 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, os << "Control jumps to the 'default' case at line " << End.asLocation().getInstantiationLineNumber(); break; - + case Stmt::CaseStmtClass: { - os << "Control jumps to 'case "; - CaseStmt* Case = cast(S); + os << "Control jumps to 'case "; + CaseStmt* Case = cast(S); Expr* LHS = Case->getLHS()->IgnoreParenCasts(); - - // Determine if it is an enum. + + // Determine if it is an enum. bool GetRawInt = true; - + if (DeclRefExpr* DR = dyn_cast(LHS)) { // FIXME: Maybe this should be an assertion. Are there cases // were it is not an EnumConstantDecl? EnumConstantDecl* D = dyn_cast(DR->getDecl()); - + if (D) { GetRawInt = false; os << D->getNameAsString(); @@ -608,14 +607,14 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, } else { os << "'Default' branch taken. "; - const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); + const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); } - + break; } - + case Stmt::BreakStmtClass: case Stmt::ContinueStmtClass: { std::string sbuf; @@ -625,117 +624,117 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, os.str())); break; } - + // Determine control-flow for ternary '?'. case Stmt::ConditionalOperatorClass: { std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "'?' condition is "; - + if (*(Src->succ_begin()+1) == Dst) os << "false"; else os << "true"; - + PathDiagnosticLocation End = PDB.ExecutionContinues(N); - + if (const Stmt *S = End.asStmt()) End = PDB.getEnclosingStmtLocation(S); - + PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); break; } - + // Determine control-flow for short-circuited '&&' and '||'. case Stmt::BinaryOperatorClass: { if (!PDB.supportsLogicalOpControlFlow()) break; - + BinaryOperator *B = cast(T); std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Left side of '"; - + if (B->getOpcode() == BinaryOperator::LAnd) { os << "&&" << "' is "; - + if (*(Src->succ_begin()+1) == Dst) { os << "false"; PathDiagnosticLocation End(B->getLHS(), SMgr); PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr); PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); - } + } else { os << "true"; PathDiagnosticLocation Start(B->getLHS(), SMgr); PathDiagnosticLocation End = PDB.ExecutionContinues(N); PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); - } + } } else { assert(B->getOpcode() == BinaryOperator::LOr); os << "||" << "' is "; - + if (*(Src->succ_begin()+1) == Dst) { os << "false"; PathDiagnosticLocation Start(B->getLHS(), SMgr); PathDiagnosticLocation End = PDB.ExecutionContinues(N); PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, - os.str())); + os.str())); } else { os << "true"; PathDiagnosticLocation End(B->getLHS(), SMgr); PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr); PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, - os.str())); + os.str())); } } - + break; } - - case Stmt::DoStmtClass: { + + case Stmt::DoStmtClass: { if (*(Src->succ_begin()) == Dst) { std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << "Loop condition is true. "; PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); - + if (const Stmt *S = End.asStmt()) End = PDB.getEnclosingStmtLocation(S); - + PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); } else { PathDiagnosticLocation End = PDB.ExecutionContinues(N); - + if (const Stmt *S = End.asStmt()) End = PDB.getEnclosingStmtLocation(S); - + PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, "Loop condition is false. Exiting loop")); } - + break; } - + case Stmt::WhileStmtClass: - case Stmt::ForStmtClass: { + case Stmt::ForStmtClass: { if (*(Src->succ_begin()+1) == Dst) { std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << "Loop condition is false. "; PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); if (const Stmt *S = End.asStmt()) End = PDB.getEnclosingStmtLocation(S); - + PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, os.str())); } @@ -743,32 +742,32 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, PathDiagnosticLocation End = PDB.ExecutionContinues(N); if (const Stmt *S = End.asStmt()) End = PDB.getEnclosingStmtLocation(S); - + PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, "Loop condition is true. Entering loop body")); } - + break; } - + case Stmt::IfStmtClass: { PathDiagnosticLocation End = PDB.ExecutionContinues(N); - + if (const Stmt *S = End.asStmt()) End = PDB.getEnclosingStmtLocation(S); - + if (*(Src->succ_begin()+1) == Dst) PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, "Taking false branch")); - else + else PD.push_front(new PathDiagnosticControlFlowPiece(Start, End, "Taking true branch")); - + break; } } } - + if (NextNode) { for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(), E = PDB.visitor_end(); I!=E; ++I) { @@ -776,15 +775,15 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, PD.push_front(p); } } - - if (const PostStmt* PS = dyn_cast(&P)) { + + if (const PostStmt* PS = dyn_cast(&P)) { // Scan the region bindings, and see if a "notable" symbol has a new // lval binding. ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD); PDB.getStateManager().iterBindings(N->getState(), SNS); } } - + // After constructing the full PathDiagnostic, do a pass over it to compact // PathDiagnosticPieces that occur within a macro. CompactPathDiagnostic(PD, PDB.getSourceManager()); @@ -796,20 +795,20 @@ static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, static bool IsControlFlowExpr(const Stmt *S) { const Expr *E = dyn_cast(S); - + if (!E) return false; - - E = E->IgnoreParenCasts(); - + + E = E->IgnoreParenCasts(); + if (isa(E)) return true; - + if (const BinaryOperator *B = dyn_cast(E)) if (B->isLogicalOp()) return true; - - return false; + + return false; } namespace { @@ -818,25 +817,25 @@ class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation { public: ContextLocation(const PathDiagnosticLocation &L, bool isdead = false) : PathDiagnosticLocation(L), IsDead(isdead) {} - - void markDead() { IsDead = true; } + + void markDead() { IsDead = true; } bool isDead() const { return IsDead; } }; - + class VISIBILITY_HIDDEN EdgeBuilder { std::vector CLocs; typedef std::vector::iterator iterator; PathDiagnostic &PD; PathDiagnosticBuilder &PDB; PathDiagnosticLocation PrevLoc; - + bool IsConsumedExpr(const PathDiagnosticLocation &L); - + bool containsLocation(const PathDiagnosticLocation &Container, const PathDiagnosticLocation &Containee); - + PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L); - + PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L, bool firstCharOnly = false) { if (const Stmt *S = L.asStmt()) { @@ -864,20 +863,20 @@ class VISIBILITY_HIDDEN EdgeBuilder { firstCharOnly = true; continue; } - + break; } - + if (S != Original) L = PathDiagnosticLocation(S, L.getManager()); } - + if (firstCharOnly) L = PathDiagnosticLocation(L.asLocation()); return L; } - + void popLocation() { if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) { // For contexts, we only one the first character as the range. @@ -885,18 +884,18 @@ class VISIBILITY_HIDDEN EdgeBuilder { } CLocs.pop_back(); } - - PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L); + + PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L); public: EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb) : PD(pd), PDB(pdb) { - + // If the PathDiagnostic already has pieces, add the enclosing statement // of the first piece as a context as well. if (!PD.empty()) { PrevLoc = PD.begin()->getLocation(); - + if (const Stmt *S = PrevLoc.asStmt()) addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); } @@ -904,7 +903,7 @@ public: ~EdgeBuilder() { while (!CLocs.empty()) popLocation(); - + // Finally, add an initial edge from the start location of the first // statement (if it doesn't already exist). // FIXME: Should handle CXXTryStmt if analyser starts supporting C++. @@ -914,20 +913,20 @@ public: SourceLocation Loc = (*CS->body_begin())->getLocStart(); rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager())); } - + } void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false); - + void addEdge(const Stmt *S, bool alwaysAdd = false) { addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd); } - + void rawAddEdge(PathDiagnosticLocation NewLoc); - + void addContext(const Stmt *S); void addExtendedContext(const Stmt *S); -}; +}; } // end anonymous namespace @@ -936,10 +935,10 @@ EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) { if (const Stmt *S = L.asStmt()) { if (IsControlFlowExpr(S)) return L; - - return PDB.getEnclosingStmtLocation(S); + + return PDB.getEnclosingStmtLocation(S); } - + return L; } @@ -948,10 +947,10 @@ bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, if (Container == Containee) return true; - + if (Container.asDecl()) return true; - + if (const Stmt *S = Containee.asStmt()) if (const Stmt *ContainerS = Container.asStmt()) { while (S) { @@ -965,25 +964,25 @@ bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, // Less accurate: compare using source ranges. SourceRange ContainerR = Container.asRange(); SourceRange ContaineeR = Containee.asRange(); - + SourceManager &SM = PDB.getSourceManager(); SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin()); SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd()); SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin()); SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd()); - + unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg); unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd); unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg); unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd); - + assert(ContainerBegLine <= ContainerEndLine); - assert(ContaineeBegLine <= ContaineeEndLine); - + assert(ContaineeBegLine <= ContaineeEndLine); + return (ContainerBegLine <= ContaineeBegLine && ContainerEndLine >= ContaineeEndLine && (ContainerBegLine != ContaineeBegLine || - SM.getInstantiationColumnNumber(ContainerRBeg) <= + SM.getInstantiationColumnNumber(ContainerRBeg) <= SM.getInstantiationColumnNumber(ContaineeRBeg)) && (ContainerEndLine != ContaineeEndLine || SM.getInstantiationColumnNumber(ContainerREnd) >= @@ -1003,13 +1002,13 @@ void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { PrevLoc = NewLoc; return; } - + const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc); const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc); - + if (NewLocClean.asLocation() == PrevLocClean.asLocation()) return; - + // FIXME: Ignore intra-macro edges for now. if (NewLocClean.asLocation().getInstantiationLoc() == PrevLocClean.asLocation().getInstantiationLoc()) @@ -1020,15 +1019,15 @@ void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { } void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) { - + if (!alwaysAdd && NewLoc.asLocation().isMacroID()) return; - + const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc); while (!CLocs.empty()) { ContextLocation &TopContextLoc = CLocs.back(); - + // Is the top location context the same as the one for the new location? if (TopContextLoc == CLoc) { if (alwaysAdd) { @@ -1045,21 +1044,21 @@ void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) { if (containsLocation(TopContextLoc, CLoc)) { if (alwaysAdd) { rawAddEdge(NewLoc); - + if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) { CLocs.push_back(ContextLocation(CLoc, true)); return; } } - + CLocs.push_back(CLoc); - return; + return; } // Context does not contain the location. Flush it. popLocation(); } - + // If we reach here, there is no enclosing context. Just add the edge. rawAddEdge(NewLoc); } @@ -1067,15 +1066,15 @@ void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) { bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) { if (const Expr *X = dyn_cast_or_null(L.asStmt())) return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X); - + return false; } - + void EdgeBuilder::addExtendedContext(const Stmt *S) { if (!S) return; - - const Stmt *Parent = PDB.getParent(S); + + const Stmt *Parent = PDB.getParent(S); while (Parent) { if (isa(Parent)) Parent = PDB.getParent(Parent); @@ -1092,16 +1091,16 @@ void EdgeBuilder::addExtendedContext(const Stmt *S) { break; } } - + addContext(S); } - + void EdgeBuilder::addContext(const Stmt *S) { if (!S) return; PathDiagnosticLocation L(S, PDB.getSourceManager()); - + while (!CLocs.empty()) { const PathDiagnosticLocation &TopContextLoc = CLocs.back(); @@ -1111,7 +1110,7 @@ void EdgeBuilder::addContext(const Stmt *S) { if (containsLocation(TopContextLoc, L)) { CLocs.push_back(L); - return; + return; } // Context does not contain the location. Flush it. @@ -1124,11 +1123,11 @@ void EdgeBuilder::addContext(const Stmt *S) { static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N) { - - + + EdgeBuilder EB(PD, PDB); - const ExplodedNode* NextNode = N->pred_empty() + const ExplodedNode* NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); while (NextNode) { N = NextNode; @@ -1140,26 +1139,26 @@ static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, if (const BlockEdge *BE = dyn_cast(&P)) { const CFGBlock &Blk = *BE->getSrc(); const Stmt *Term = Blk.getTerminator(); - + // Are we jumping to the head of a loop? Add a special diagnostic. if (const Stmt *Loop = BE->getDst()->getLoopTarget()) { PathDiagnosticLocation L(Loop, PDB.getSourceManager()); const CompoundStmt *CS = NULL; - + if (!Term) { if (const ForStmt *FS = dyn_cast(Loop)) CS = dyn_cast(FS->getBody()); else if (const WhileStmt *WS = dyn_cast(Loop)) - CS = dyn_cast(WS->getBody()); + CS = dyn_cast(WS->getBody()); } - + PathDiagnosticEventPiece *p = new PathDiagnosticEventPiece(L, "Looping back to the head of the loop"); - + EB.addEdge(p->getLocation(), true); PD.push_front(p); - + if (CS) { PathDiagnosticLocation BL(CS->getRBracLoc(), PDB.getSourceManager()); @@ -1167,14 +1166,14 @@ static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, EB.addEdge(BL); } } - + if (Term) EB.addContext(Term); - + break; } - if (const BlockEntrance *BE = dyn_cast(&P)) { + if (const BlockEntrance *BE = dyn_cast(&P)) { if (const Stmt* S = BE->getFirstStmt()) { if (IsControlFlowExpr(S)) { // Add the proper context for '&&', '||', and '?'. @@ -1187,10 +1186,10 @@ static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, break; } } while (0); - + if (!NextNode) continue; - + for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(), E = PDB.visitor_end(); I!=E; ++I) { if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) { @@ -1198,9 +1197,9 @@ static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, EB.addEdge(Loc, true); PD.push_front(p); if (const Stmt *S = Loc.asStmt()) - EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); + EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); } - } + } } } @@ -1216,46 +1215,46 @@ void BugType::FlushReports(BugReporter &BR) {} BugReport::~BugReport() {} RangedBugReport::~RangedBugReport() {} -const Stmt* BugReport::getStmt() const { - ProgramPoint ProgP = EndNode->getLocation(); +const Stmt* BugReport::getStmt() const { + ProgramPoint ProgP = EndNode->getLocation(); const Stmt *S = NULL; - + if (BlockEntrance* BE = dyn_cast(&ProgP)) { CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); if (BE->getBlock() == &Exit) S = GetPreviousStmt(EndNode); } if (!S) - S = GetStmt(ProgP); - - return S; + S = GetStmt(ProgP); + + return S; } PathDiagnosticPiece* BugReport::getEndPath(BugReporterContext& BRC, const ExplodedNode* EndPathNode) { - + const Stmt* S = getStmt(); - + if (!S) return NULL; const SourceRange *Beg, *End; - getRanges(Beg, End); + getRanges(Beg, End); PathDiagnosticLocation L(S, BRC.getSourceManager()); - + // Only add the statement itself as a range if we didn't specify any // special ranges for this report. PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(), Beg == End); - + for (; Beg != End; ++Beg) P->addRange(*Beg); - + return P; } -void BugReport::getRanges(const SourceRange*& beg, const SourceRange*& end) { +void BugReport::getRanges(const SourceRange*& beg, const SourceRange*& end) { if (const Expr* E = dyn_cast_or_null(getStmt())) { R = E->getSourceRange(); assert(R.isValid()); @@ -1266,7 +1265,7 @@ void BugReport::getRanges(const SourceRange*& beg, const SourceRange*& end) { beg = end = 0; } -SourceLocation BugReport::getLocation() const { +SourceLocation BugReport::getLocation() const { if (EndNode) if (const Stmt* S = GetCurrentOrPreviousStmt(EndNode)) { // For member expressions, return the location of the '.' or '->'. @@ -1325,8 +1324,8 @@ void BugReporter::FlushReports() { BugReportEquivClass& EQ = *EI; FlushReport(EQ); } - - // Delete the BugType object. + + // Delete the BugType object. // FIXME: this will *not* delete the BugReportEquivClasses, since FoldingSet // only deletes the buckets, not the nodes themselves. @@ -1346,9 +1345,9 @@ static std::pair, MakeReportGraph(const ExplodedGraph* G, const ExplodedNode** NStart, const ExplodedNode** NEnd) { - + // Create the trimmed graph. It will contain the shortest paths from the - // error nodes to the root. In the new graph we should only have one + // error nodes to the root. In the new graph we should only have one // error node unless there are two or more error nodes with the same minimum // path length. ExplodedGraph* GTrim; @@ -1356,12 +1355,12 @@ MakeReportGraph(const ExplodedGraph* G, llvm::DenseMap InverseMap; llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap); - + // Create owning pointers for GTrim and NMap just to ensure that they are // released when this function exists. llvm::OwningPtr AutoReleaseGTrim(GTrim); llvm::OwningPtr AutoReleaseNMap(NMap); - + // Find the (first) error node in the trimmed graph. We just need to consult // the node map (NMap) which maps from nodes in the original graph to nodes // in the new graph. @@ -1376,68 +1375,68 @@ MakeReportGraph(const ExplodedGraph* G, WS.push(N); IndexMap[*I] = NodeIndex; } - + assert(!WS.empty() && "No error node found in the trimmed graph."); // Create a new (third!) graph with a single path. This is the graph // that will be returned to the caller. ExplodedGraph *GNew = new ExplodedGraph(GTrim->getContext()); - + // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS // to the root node, and then construct a new graph that contains only // a single path. llvm::DenseMap Visited; - + unsigned cnt = 0; const ExplodedNode* Root = 0; - + while (!WS.empty()) { const ExplodedNode* Node = WS.front(); WS.pop(); - + if (Visited.find(Node) != Visited.end()) continue; - + Visited[Node] = cnt++; - + if (Node->pred_empty()) { Root = Node; break; } - + for (ExplodedNode::const_pred_iterator I=Node->pred_begin(), E=Node->pred_end(); I!=E; ++I) WS.push(*I); } - + assert(Root); - + // Now walk from the root down the BFS path, always taking the successor // with the lowest number. - ExplodedNode *Last = 0, *First = 0; + ExplodedNode *Last = 0, *First = 0; NodeBackMap *BM = new NodeBackMap(); unsigned NodeIndex = 0; - + for ( const ExplodedNode *N = Root ;;) { // Lookup the number associated with the current node. llvm::DenseMap::iterator I = Visited.find(N); assert(I != Visited.end()); - + // Create the equivalent node in the new graph with the same state // and location. ExplodedNode* NewN = GNew->getNode(N->getLocation(), N->getState()); - + // Store the mapping to the original node. llvm::DenseMap::iterator IMitr=InverseMap.find(N); assert(IMitr != InverseMap.end() && "No mapping to original node."); (*BM)[NewN] = (const ExplodedNode*) IMitr->second; - + // Link up the new node with the previous node. if (Last) NewN->addPredecessor(Last); - + Last = NewN; - + // Are we at the final node? IndexMapTy::iterator IMI = IndexMap.find((const ExplodedNode*)(IMitr->second)); @@ -1446,29 +1445,29 @@ MakeReportGraph(const ExplodedGraph* G, NodeIndex = IMI->second; break; } - + // Find the next successor node. We choose the node that is marked // with the lowest DFS number. ExplodedNode::const_succ_iterator SI = N->succ_begin(); ExplodedNode::const_succ_iterator SE = N->succ_end(); N = 0; - + for (unsigned MinVal = 0; SI != SE; ++SI) { - + I = Visited.find(*SI); - + if (I == Visited.end()) continue; - + if (!N || I->second < MinVal) { N = *SI; MinVal = I->second; } } - + assert(N); } - + assert(First); return std::make_pair(std::make_pair(GNew, BM), @@ -1480,23 +1479,23 @@ MakeReportGraph(const ExplodedGraph* G, static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) { typedef std::vector > MacroStackTy; - + typedef std::vector PiecesTy; - + MacroStackTy MacroStack; PiecesTy Pieces; - + for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) { // Get the location of the PathDiagnosticPiece. - const FullSourceLoc Loc = I->getLocation().asLocation(); - + const FullSourceLoc Loc = I->getLocation().asLocation(); + // Determine the instantiation location, which is the location we group // related PathDiagnosticPieces. - SourceLocation InstantiationLoc = Loc.isMacroID() ? + SourceLocation InstantiationLoc = Loc.isMacroID() ? SM.getInstantiationLoc(Loc) : SourceLocation(); - + if (Loc.isFileID()) { MacroStack.clear(); Pieces.push_back(&*I); @@ -1504,7 +1503,7 @@ static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) { } assert(Loc.isMacroID()); - + // Is the PathDiagnosticPiece within the same macro group? if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) { MacroStack.back().first->push_back(&*I); @@ -1518,22 +1517,22 @@ static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) { SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ? SM.getInstantiationLoc(Loc) : SourceLocation(); - + // Walk the entire macro stack. while (!MacroStack.empty()) { if (InstantiationLoc == MacroStack.back().second) { MacroGroup = MacroStack.back().first; break; } - + if (ParentInstantiationLoc == MacroStack.back().second) { MacroGroup = MacroStack.back().first; break; } - + MacroStack.pop_back(); } - + if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) { // Create a new macro group and add it to the stack. PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc); @@ -1544,7 +1543,7 @@ static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) { assert(InstantiationLoc.isFileID()); Pieces.push_back(NewGroup); } - + MacroGroup = NewGroup; MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc)); } @@ -1552,62 +1551,62 @@ static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) { // Finally, add the PathDiagnosticPiece to the group. MacroGroup->push_back(&*I); } - + // Now take the pieces and construct a new PathDiagnostic. PD.resetPath(false); - + for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) { if (PathDiagnosticMacroPiece *MP=dyn_cast(*I)) if (!MP->containsEvent()) { delete MP; continue; } - + PD.push_back(*I); } } void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD, BugReportEquivClass& EQ) { - + std::vector Nodes; - + for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) { const ExplodedNode* N = I->getEndNode(); if (N) Nodes.push_back(N); } - + if (Nodes.empty()) return; - + // Construct a new graph that contains only a single path from the error - // node to a root. + // node to a root. const std::pair, std::pair >& GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size()); - + // Find the BugReport with the original location. BugReport *R = 0; unsigned i = 0; for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i) if (i == GPair.second.second) { R = *I; break; } - + assert(R && "No original report found for sliced graph."); - + llvm::OwningPtr ReportGraph(GPair.first.first); llvm::OwningPtr BackMap(GPair.first.second); const ExplodedNode *N = GPair.second.first; - - // Start building the path diagnostic... + + // Start building the path diagnostic... PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient()); - + if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N)) PD.push_back(Piece); else return; - + R->registerInitialVisitors(PDB, N); - + switch (PDB.getGenerationScheme()) { case PathDiagnosticClient::Extensive: GenerateExtensivePathDiagnostic(PD, PDB, N); @@ -1622,17 +1621,17 @@ void BugReporter::Register(BugType *BT) { BugTypes = F.Add(BugTypes, BT); } -void BugReporter::EmitReport(BugReport* R) { +void BugReporter::EmitReport(BugReport* R) { // Compute the bug report's hash to determine its equivalence class. llvm::FoldingSetNodeID ID; R->Profile(ID); - - // Lookup the equivance class. If there isn't one, create it. + + // Lookup the equivance class. If there isn't one, create it. BugType& BT = R->getBugType(); Register(&BT); void *InsertPos; - BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos); - + BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos); + if (!EQ) { EQ = new BugReportEquivClass(R); BT.EQClasses.InsertNode(EQ, InsertPos); @@ -1645,11 +1644,11 @@ void BugReporter::FlushReport(BugReportEquivClass& EQ) { assert(!EQ.Reports.empty()); BugReport &R = **EQ.begin(); PathDiagnosticClient* PD = getPathDiagnosticClient(); - + // FIXME: Make sure we use the 'R' for the path that was actually used. - // Probably doesn't make a difference in practice. + // Probably doesn't make a difference in practice. BugType& BT = R.getBugType(); - + llvm::OwningPtr D(new PathDiagnostic(R.getBugType().getName(), !PD || PD->useVerboseDescription() @@ -1657,16 +1656,16 @@ void BugReporter::FlushReport(BugReportEquivClass& EQ) { BT.getCategory())); GeneratePathDiagnostic(*D.get(), EQ); - + // Get the meta data. std::pair Meta = R.getExtraDescriptiveText(); for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s); // Emit a summary diagnostic to the regular Diagnostics engine. const SourceRange *Beg = 0, *End = 0; - R.getRanges(Beg, End); + R.getRanges(Beg, End); Diagnostic& Diag = getDiagnostic(); - FullSourceLoc L(R.getLocation(), getSourceManager()); + FullSourceLoc L(R.getLocation(), getSourceManager()); unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning, R.getShortDescription().c_str()); @@ -1681,15 +1680,15 @@ void BugReporter::FlushReport(BugReportEquivClass& EQ) { // Emit a full diagnostic for the path if we have a PathDiagnosticClient. if (!PD) return; - - if (D->empty()) { + + if (D->empty()) { PathDiagnosticPiece* piece = new PathDiagnosticEventPiece(L, R.getDescription()); for ( ; Beg != End; ++Beg) piece->addRange(*Beg); D->push_back(piece); } - + PD->HandlePathDiagnostic(D.take()); } @@ -1702,7 +1701,7 @@ void BugReporter::EmitBasicReport(const char* name, const char* str, void BugReporter::EmitBasicReport(const char* name, const char* category, const char* str, SourceLocation Loc, SourceRange* RBeg, unsigned NumRanges) { - + // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'. BugType *BT = new BugType(name, category); FullSourceLoc L = getContext().getFullLoc(Loc); diff --git a/clang/lib/Analysis/BugReporterVisitors.cpp b/clang/lib/Analysis/BugReporterVisitors.cpp index 8b3502805d8c592f2878bdd8c06b99e0a8c19d11..b76ffb18a616381d78f81e4d5acdd44eaa9bf163 100644 --- a/clang/lib/Analysis/BugReporterVisitors.cpp +++ b/clang/lib/Analysis/BugReporterVisitors.cpp @@ -28,7 +28,7 @@ const Stmt *clang::bugreporter::GetDerefExpr(const ExplodedNode *N) { // Pattern match for a few useful cases (do something smarter later): // a[0], p->f, *p const Stmt *S = N->getLocationAs()->getStmt(); - + if (const UnaryOperator *U = dyn_cast(S)) { if (U->getOpcode() == UnaryOperator::Deref) return U->getSubExpr()->IgnoreParenCasts(); @@ -41,8 +41,8 @@ const Stmt *clang::bugreporter::GetDerefExpr(const ExplodedNode *N) { // to reason about them. return AE->getBase(); } - - return NULL; + + return NULL; } const Stmt* @@ -91,19 +91,19 @@ class VISIBILITY_HIDDEN FindLastStoreBRVisitor : public BugReporterVisitor { public: FindLastStoreBRVisitor(SVal v, const MemRegion *r) : R(r), V(v), satisfied(false), StoreSite(0) {} - + PathDiagnosticPiece* VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext& BRC) { - + if (satisfied) return NULL; - - if (!StoreSite) { + + if (!StoreSite) { const ExplodedNode *Node = N, *Last = NULL; - + for ( ; Node ; Last = Node, Node = Node->getFirstPred()) { - + if (const VarRegion *VR = dyn_cast(R)) { if (const PostStmt *P = Node->getLocationAs()) if (const DeclStmt *DS = P->getStmtAs()) @@ -112,35 +112,35 @@ public: break; } } - + if (Node->getState()->getSVal(R) != V) break; } - + if (!Node || !Last) { satisfied = true; return NULL; } - + StoreSite = Last; } - + if (StoreSite != N) return NULL; - + satisfied = true; std::string sbuf; llvm::raw_string_ostream os(sbuf); - + if (const PostStmt *PS = N->getLocationAs()) { if (const DeclStmt *DS = PS->getStmtAs()) { - + if (const VarRegion *VR = dyn_cast(R)) { os << "Variable '" << VR->getDecl()->getNameAsString() << "' "; } else return NULL; - + if (isa(V)) { bool b = false; ASTContext &C = BRC.getASTContext(); @@ -152,7 +152,7 @@ public: } } } - + if (!b) os << "initialized to a null pointer value"; } @@ -165,13 +165,13 @@ public: if (VD->getInit()) os << "initialized to a garbage value"; else - os << "declared without an initial value"; - } + os << "declared without an initial value"; + } } } } - - if (os.str().empty()) { + + if (os.str().empty()) { if (isa(V)) { bool b = false; ASTContext &C = BRC.getASTContext(); @@ -183,7 +183,7 @@ public: } } } - + if (!b) os << "Null pointer value stored to "; } @@ -196,18 +196,18 @@ public: } else return NULL; - + if (const VarRegion *VR = dyn_cast(R)) { os << '\'' << VR->getDecl()->getNameAsString() << '\''; } else return NULL; } - + // FIXME: Refactor this into BugReporterContext. - const Stmt *S = 0; + const Stmt *S = 0; ProgramPoint P = N->getLocation(); - + if (BlockEdge *BE = dyn_cast(&P)) { CFGBlock *BSrc = BE->getSrc(); S = BSrc->getTerminatorCondition(); @@ -215,10 +215,10 @@ public: else if (PostStmt *PS = dyn_cast(&P)) { S = PS->getStmt(); } - + if (!S) return NULL; - + // Construct a new PathDiagnosticPiece. PathDiagnosticLocation L(S, BRC.getSourceManager()); return new PathDiagnosticEventPiece(L, os.str()); @@ -238,42 +238,42 @@ class VISIBILITY_HIDDEN TrackConstraintBRVisitor : public BugReporterVisitor { public: TrackConstraintBRVisitor(SVal constraint, bool assumption) : Constraint(constraint), Assumption(assumption), isSatisfied(false) {} - + PathDiagnosticPiece* VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext& BRC) { if (isSatisfied) return NULL; - + // Check if in the previous state it was feasible for this constraint // to *not* be true. if (PrevN->getState()->assume(Constraint, !Assumption)) { - + isSatisfied = true; - + // As a sanity check, make sure that the negation of the constraint // was infeasible in the current state. If it is feasible, we somehow // missed the transition point. if (N->getState()->assume(Constraint, !Assumption)) return NULL; - + // We found the transition point for the constraint. We now need to - // pretty-print the constraint. (work-in-progress) + // pretty-print the constraint. (work-in-progress) std::string sbuf; llvm::raw_string_ostream os(sbuf); - + if (isa(Constraint)) { os << "Assuming pointer value is "; os << (Assumption ? "non-null" : "null"); } - + if (os.str().empty()) return NULL; - + // FIXME: Refactor this into BugReporterContext. - const Stmt *S = 0; + const Stmt *S = 0; ProgramPoint P = N->getLocation(); - + if (BlockEdge *BE = dyn_cast(&P)) { CFGBlock *BSrc = BE->getSrc(); S = BSrc->getTerminatorCondition(); @@ -281,65 +281,65 @@ public: else if (PostStmt *PS = dyn_cast(&P)) { S = PS->getStmt(); } - + if (!S) return NULL; - + // Construct a new PathDiagnosticPiece. PathDiagnosticLocation L(S, BRC.getSourceManager()); return new PathDiagnosticEventPiece(L, os.str()); } - + return NULL; - } + } }; } // end anonymous namespace static void registerTrackConstraint(BugReporterContext& BRC, SVal Constraint, bool Assumption) { - BRC.addVisitor(new TrackConstraintBRVisitor(Constraint, Assumption)); + BRC.addVisitor(new TrackConstraintBRVisitor(Constraint, Assumption)); } void clang::bugreporter::registerTrackNullOrUndefValue(BugReporterContext& BRC, const void *data, const ExplodedNode* N) { - + const Stmt *S = static_cast(data); - + if (!S) return; - + GRStateManager &StateMgr = BRC.getStateManager(); - const GRState *state = N->getState(); - - if (const DeclRefExpr *DR = dyn_cast(S)) { - if (const VarDecl *VD = dyn_cast(DR->getDecl())) { + const GRState *state = N->getState(); + + if (const DeclRefExpr *DR = dyn_cast(S)) { + if (const VarDecl *VD = dyn_cast(DR->getDecl())) { const VarRegion *R = StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext()); - + // What did we load? SVal V = state->getSVal(S); - - if (isa(V) || isa(V) + + if (isa(V) || isa(V) || V.isUndef()) { registerFindLastStore(BRC, R, V); } } } - + SVal V = state->getSValAsScalarOrLoc(S); - + // Uncomment this to find cases where we aren't properly getting the // base value that was dereferenced. // assert(!V.isUnknownOrUndef()); - + // Is it a symbolic value? if (loc::MemRegionVal *L = dyn_cast(&V)) { const SubRegion *R = cast(L->getRegion()); while (R && !isa(R)) { R = dyn_cast(R->getSuperRegion()); } - + if (R) { assert(isa(R)); registerTrackConstraint(BRC, loc::MemRegionVal(R), false); diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp index ee64bd2f3fef53ed249117b3908af684eb106cb3..d5fde0a8198fb9038b8139bc0feccbc47145c8a9 100644 --- a/clang/lib/Analysis/CFG.cpp +++ b/clang/lib/Analysis/CFG.cpp @@ -133,8 +133,8 @@ private: CFGBlock *createBlock(bool add_successor = true); bool FinishBlock(CFGBlock* B); CFGBlock *addStmt(Stmt *S) { return Visit(S, true); } - - + + /// TryResult - a class representing a variant over the values /// 'true', 'false', or 'unknown'. This is returned by TryEvaluateBool, /// and is used by the CFGBuilder to decide if a branch condition @@ -144,7 +144,7 @@ private: public: TryResult(bool b) : X(b ? 1 : 0) {} TryResult() : X(-1) {} - + bool isTrue() const { return X == 1; } bool isFalse() const { return X == 0; } bool isKnown() const { return X >= 0; } @@ -153,7 +153,7 @@ private: X ^= 0x1; } }; - + /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 /// if we can evaluate to a known value, otherwise return -1. TryResult TryEvaluateBool(Expr *S) { @@ -292,109 +292,109 @@ tryAgain: case Stmt::AddrLabelExprClass: return VisitAddrLabelExpr(cast(S), alwaysAdd); - + case Stmt::BinaryOperatorClass: return VisitBinaryOperator(cast(S), alwaysAdd); - + case Stmt::BlockExprClass: return VisitBlockExpr(cast(S), alwaysAdd); case Stmt::BlockDeclRefExprClass: return VisitBlockDeclRefExpr(cast(S), alwaysAdd); - + case Stmt::BreakStmtClass: return VisitBreakStmt(cast(S)); - + case Stmt::CallExprClass: return VisitCallExpr(cast(S), alwaysAdd); - + case Stmt::CaseStmtClass: return VisitCaseStmt(cast(S)); case Stmt::ChooseExprClass: return VisitChooseExpr(cast(S)); - + case Stmt::CompoundStmtClass: return VisitCompoundStmt(cast(S)); - + case Stmt::ConditionalOperatorClass: return VisitConditionalOperator(cast(S)); - + case Stmt::ContinueStmtClass: return VisitContinueStmt(cast(S)); - + case Stmt::DeclStmtClass: return VisitDeclStmt(cast(S)); - + case Stmt::DefaultStmtClass: return VisitDefaultStmt(cast(S)); - + case Stmt::DoStmtClass: return VisitDoStmt(cast(S)); - + case Stmt::ForStmtClass: return VisitForStmt(cast(S)); - + case Stmt::GotoStmtClass: return VisitGotoStmt(cast(S)); - + case Stmt::IfStmtClass: return VisitIfStmt(cast(S)); - + case Stmt::IndirectGotoStmtClass: return VisitIndirectGotoStmt(cast(S)); - + case Stmt::LabelStmtClass: return VisitLabelStmt(cast(S)); - + case Stmt::ObjCAtCatchStmtClass: - return VisitObjCAtCatchStmt(cast(S)); - + return VisitObjCAtCatchStmt(cast(S)); + case Stmt::CXXThrowExprClass: return VisitCXXThrowExpr(cast(S)); case Stmt::ObjCAtSynchronizedStmtClass: return VisitObjCAtSynchronizedStmt(cast(S)); - + case Stmt::ObjCAtThrowStmtClass: return VisitObjCAtThrowStmt(cast(S)); - + case Stmt::ObjCAtTryStmtClass: return VisitObjCAtTryStmt(cast(S)); - + case Stmt::ObjCForCollectionStmtClass: return VisitObjCForCollectionStmt(cast(S)); - + case Stmt::ParenExprClass: S = cast(S)->getSubExpr(); - goto tryAgain; - + goto tryAgain; + case Stmt::NullStmtClass: return Block; - + case Stmt::ReturnStmtClass: return VisitReturnStmt(cast(S)); - + case Stmt::SizeOfAlignOfExprClass: - return VisitSizeOfAlignOfExpr(cast(S), alwaysAdd); - + return VisitSizeOfAlignOfExpr(cast(S), alwaysAdd); + case Stmt::StmtExprClass: return VisitStmtExpr(cast(S), alwaysAdd); - + case Stmt::SwitchStmtClass: return VisitSwitchStmt(cast(S)); - + case Stmt::WhileStmtClass: return VisitWhileStmt(cast(S)); } } - + CFGBlock *CFGBuilder::VisitStmt(Stmt *S, bool alwaysAdd) { if (alwaysAdd) { autoCreateBlock(); Block->appendStmt(S); } - + return VisitChildren(S); } @@ -407,7 +407,7 @@ CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) { } return B; } - + CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd) { AddressTakenLabels.insert(A->getLabel()); @@ -418,26 +418,26 @@ CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd) { return Block; } - + CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd) { if (B->isLogicalOp()) { // && or || CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); ConfluenceBlock->appendStmt(B); - + if (!FinishBlock(ConfluenceBlock)) return 0; - + // create the block evaluating the LHS CFGBlock* LHSBlock = createBlock(false); LHSBlock->setTerminator(B); - + // create the block evaluating the RHS Succ = ConfluenceBlock; Block = NULL; CFGBlock* RHSBlock = addStmt(B->getRHS()); if (!FinishBlock(RHSBlock)) return 0; - + // See if this is a known constant. TryResult KnownVal = TryEvaluateBool(B->getLHS()); if (KnownVal.isKnown() && (B->getOpcode() == BinaryOperator::LOr)) @@ -447,23 +447,23 @@ CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd) { if (B->getOpcode() == BinaryOperator::LOr) { LHSBlock->addSuccessor(KnownVal.isTrue() ? NULL : ConfluenceBlock); LHSBlock->addSuccessor(KnownVal.isFalse() ? NULL : RHSBlock); - } else { + } else { assert (B->getOpcode() == BinaryOperator::LAnd); LHSBlock->addSuccessor(KnownVal.isFalse() ? NULL : RHSBlock); LHSBlock->addSuccessor(KnownVal.isTrue() ? NULL : ConfluenceBlock); } - + // Generate the blocks for evaluating the LHS. Block = LHSBlock; return addStmt(B->getLHS()); - } + } else if (B->getOpcode() == BinaryOperator::Comma) { // , autoCreateBlock(); Block->appendStmt(B); addStmt(B->getRHS()); return addStmt(B->getLHS()); } - + return VisitStmt(B, alwaysAdd); } @@ -477,28 +477,28 @@ CFGBlock *CFGBuilder::VisitBlockDeclRefExpr(BlockDeclRefExpr* E, // FIXME return NYS(); } - + CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { // "break" is a control-flow statement. Thus we stop processing the current // block. if (Block && !FinishBlock(Block)) return 0; - + // Now create a new block that ends with the break statement. Block = createBlock(false); Block->setTerminator(B); - + // If there is no target for the break, then we are looking at an incomplete // AST. This means that the CFG cannot be constructed. if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock); else badCFG = true; - - + + return Block; } - + CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, bool alwaysAdd) { // If this is a call to a no-return function, this stops the block here. bool NoReturn = false; @@ -512,17 +512,17 @@ CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, bool alwaysAdd) { if (!NoReturn) return VisitStmt(C, alwaysAdd); - + if (Block && !FinishBlock(Block)) return 0; - + // Create new block with no successor for the remaining pieces. Block = createBlock(false); Block->appendStmt(C); // Wire this to the exit block directly. Block->addSuccessor(&cfg->getExit()); - + return VisitChildren(C); } @@ -531,42 +531,42 @@ CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C) { ConfluenceBlock->appendStmt(C); if (!FinishBlock(ConfluenceBlock)) return 0; - + Succ = ConfluenceBlock; Block = NULL; CFGBlock* LHSBlock = addStmt(C->getLHS()); if (!FinishBlock(LHSBlock)) return 0; - + Succ = ConfluenceBlock; Block = NULL; CFGBlock* RHSBlock = addStmt(C->getRHS()); if (!FinishBlock(RHSBlock)) return 0; - + Block = createBlock(false); // See if this is a known constant. const TryResult& KnownVal = TryEvaluateBool(C->getCond()); Block->addSuccessor(KnownVal.isFalse() ? NULL : LHSBlock); Block->addSuccessor(KnownVal.isTrue() ? NULL : RHSBlock); Block->setTerminator(C); - return addStmt(C->getCond()); + return addStmt(C->getCond()); } - - -CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) { - CFGBlock* LastBlock = Block; + + +CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) { + CFGBlock* LastBlock = Block; for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); I != E; ++I ) { LastBlock = addStmt(*I); - + if (badCFG) return NULL; - } + } return LastBlock; } - + CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) { // Create the confluence block that will "merge" the results of the ternary // expression. @@ -574,7 +574,7 @@ CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) { ConfluenceBlock->appendStmt(C); if (!FinishBlock(ConfluenceBlock)) return 0; - + // Create a block for the LHS expression if there is an LHS expression. A // GCC extension allows LHS to be NULL, causing the condition to be the // value that is returned instead. @@ -588,16 +588,16 @@ CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) { return 0; Block = NULL; } - + // Create the block for the RHS expression. Succ = ConfluenceBlock; CFGBlock* RHSBlock = addStmt(C->getRHS()); if (!FinishBlock(RHSBlock)) return 0; - + // Create the block that will contain the condition. Block = createBlock(false); - + // See if this is a known constant. const TryResult& KnownVal = TryEvaluateBool(C->getCond()); if (LHSBlock) { @@ -622,8 +622,8 @@ CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) { ConfluenceBlock->pred_end()); } } - - Block->addSuccessor(KnownVal.isTrue() ? NULL : RHSBlock); + + Block->addSuccessor(KnownVal.isTrue() ? NULL : RHSBlock); Block->setTerminator(C); return addStmt(C->getCond()); } @@ -635,45 +635,45 @@ CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { Block->appendStmt(DS); return VisitDeclSubExpr(DS->getSingleDecl()); } - + CFGBlock *B = 0; - + // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. typedef llvm::SmallVector BufTy; BufTy Buf(DS->decl_begin(), DS->decl_end()); - + for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { // Get the alignment of the new DeclStmt, padding out to >=8 bytes. unsigned A = llvm::AlignOf::Alignment < 8 ? 8 : llvm::AlignOf::Alignment; - + // Allocate the DeclStmt using the BumpPtrAllocator. It will get // automatically freed with the CFG. DeclGroupRef DG(*I); Decl *D = *I; - void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); + void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); - + // Append the fake DeclStmt to block. Block->appendStmt(DSNew); B = VisitDeclSubExpr(D); } - - return B; + + return B; } - + /// VisitDeclSubExpr - Utility method to add block-level expressions for /// initializers in Decls. CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) { assert(Block); VarDecl *VD = dyn_cast(D); - + if (!VD) return Block; - + Expr *Init = VD->getInit(); - + if (Init) { // Optimization: Don't create separate block-level statements for literals. switch (Init->getStmtClass()) { @@ -685,12 +685,12 @@ CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) { Block = addStmt(Init); } } - + // If the type of VD is a VLA, then we must process its size expressions. for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) Block = addStmt(VA->getSizeExpr()); - + return Block; } @@ -879,7 +879,7 @@ CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) { // See if this is a known constant. TryResult KnownVal(true); - + if (F->getCond()) KnownVal = TryEvaluateBool(F->getCond()); @@ -1171,8 +1171,8 @@ CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) { Succ = EntryConditionBlock; return EntryConditionBlock; } - - + + CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { // FIXME: For now we pretend that @catch and the code it contains does not // exit. @@ -1329,7 +1329,7 @@ CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) { return Block; } - + CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, bool alwaysAdd) { @@ -1337,17 +1337,17 @@ CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, autoCreateBlock(); Block->appendStmt(E); } - + // VLA types have expressions that must be evaluated. if (E->isArgumentType()) { for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr()); VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) addStmt(VA->getSizeExpr()); } - + return Block; } - + /// VisitStmtExpr - Utility method to handle (nested) statement /// expressions (a GCC extension). CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, bool alwaysAdd) { @@ -1416,7 +1416,7 @@ CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) { if (CS->getSubStmt()) addStmt(CS->getSubStmt()); - + CFGBlock* CaseBlock = Block; if (!CaseBlock) CaseBlock = createBlock(); @@ -1445,7 +1445,7 @@ CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) { CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { if (Terminator->getSubStmt()) addStmt(Terminator->getSubStmt()); - + DefaultCaseBlock = Block; if (!DefaultCaseBlock) @@ -1454,7 +1454,7 @@ CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { // Default statements partition blocks, so this is the top of the basic block // we were processing (the "default:" is the label). DefaultCaseBlock->setLabel(Terminator); - + if (!FinishBlock(DefaultCaseBlock)) return 0; diff --git a/clang/lib/Analysis/CFRefCount.cpp b/clang/lib/Analysis/CFRefCount.cpp index 9cd59c2c145a56a07335dfffe7fdf97b96d6453a..e511f76195af2c942129864f68e1f6f46f5b66dd 100644 --- a/clang/lib/Analysis/CFRefCount.cpp +++ b/clang/lib/Analysis/CFRefCount.cpp @@ -22,7 +22,7 @@ #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/PathSensitive/SymbolManager.h" #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" -#include "clang/AST/DeclObjC.h" +#include "clang/AST/DeclObjC.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableMap.h" @@ -44,7 +44,7 @@ using namespace clang; // MemoryMgmt/Tasks/MemoryManagementRules.html // // "You take ownership of an object if you create it using a method whose name -// begins with "alloc" or "new" or contains "copy" (for example, alloc, +// begins with "alloc" or "new" or contains "copy" (for example, alloc, // newObject, or mutableCopy), or if you send it a retain message. You are // responsible for relinquishing ownership of objects you own using release // or autorelease. Any other time you receive an object, you must @@ -62,8 +62,8 @@ static inline bool isWordEnd(char ch, char prev, char next) { || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate || !isalpha(ch); } - -static inline const char* parseWord(const char* s) { + +static inline const char* parseWord(const char* s) { char ch = *s, prev = '\0'; assert(ch != '\0'); char next = *(s+1); @@ -77,18 +77,18 @@ static inline const char* parseWord(const char* s) { static NamingConvention deriveNamingConvention(Selector S) { IdentifierInfo *II = S.getIdentifierInfoForSlot(0); - + if (!II) return NoConvention; - + const char *s = II->getName(); - + // A method/function name may contain a prefix. We don't know it is there, // however, until we encounter the first '_'. bool InPossiblePrefix = true; bool AtBeginning = true; NamingConvention C = NoConvention; - + while (*s != '\0') { // Skip '_'. if (*s == '_') { @@ -103,24 +103,24 @@ static NamingConvention deriveNamingConvention(Selector S) { ++s; continue; } - + // Skip numbers, ':', etc. if (!isalpha(*s)) { ++s; continue; } - + const char *wordEnd = parseWord(s); assert(wordEnd > s); unsigned len = wordEnd - s; - + switch (len) { default: break; case 3: // Methods starting with 'new' follow the create rule. if (AtBeginning && StringsEqualNoCase("new", s, len)) - C = CreateRule; + C = CreateRule; break; case 4: // Methods starting with 'alloc' or contain 'copy' follow the @@ -136,7 +136,7 @@ static NamingConvention deriveNamingConvention(Selector S) { C = CreateRule; break; } - + // If we aren't in the prefix and have a derived convention then just // return it now. if (!InPossiblePrefix && C != NoConvention) @@ -156,10 +156,10 @@ static bool followsFundamentalRule(Selector S) { } static const ObjCMethodDecl* -ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) { +ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) { ObjCInterfaceDecl *ID = const_cast(MD->getClassInterface()); - + return MD->isInstanceMethod() ? ID->lookupInstanceMethod(MD->getSelector()) : ID->lookupClassMethod(MD->getSelector()); @@ -178,12 +178,12 @@ public: GenericNodeBuilder(GREndPathNodeBuilder &enb) : SNB(0), S(0), tag(0), ENB(&enb) {} - + ExplodedNode *MakeNode(const GRState *state, ExplodedNode *Pred) { if (SNB) - return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag), + return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag), state, Pred); - + assert(ENB); return ENB->generateNode(state, Pred); } @@ -211,16 +211,16 @@ static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) { static bool hasPrefix(const char* s, const char* prefix) { if (!prefix) return true; - + char c = *s; char cP = *prefix; - + while (c != '\0' && cP != '\0') { if (c != cP) break; c = *(++s); cP = *(++prefix); } - + return cP == '\0'; } @@ -231,14 +231,14 @@ static bool hasSuffix(const char* s, const char* suffix) { static bool isRefType(QualType RetTy, const char* prefix, ASTContext* Ctx = 0, const char* name = 0) { - + // Recursively walk the typedef stack, allowing typedefs of reference types. while (1) { if (TypedefType* TD = dyn_cast(RetTy.getTypePtr())) { const char* TDName = TD->getDecl()->getIdentifier()->getName(); if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref")) return true; - + RetTy = TD->getDecl()->getUnderlyingType(); continue; } @@ -282,14 +282,14 @@ typedef llvm::ImmutableMap ArgEffects; namespace { /// RetEffect is used to summarize a function/method call's behavior with -/// respect to its return value. +/// respect to its return value. class VISIBILITY_HIDDEN RetEffect { public: enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol, NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias, OwnedWhenTrackedReceiver }; - - enum ObjKind { CF, ObjC, AnyObj }; + + enum ObjKind { CF, ObjC, AnyObj }; private: Kind K; @@ -298,124 +298,124 @@ private: RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {} RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {} - + public: Kind getKind() const { return K; } ObjKind getObjKind() const { return O; } - - unsigned getIndex() const { + + unsigned getIndex() const { assert(getKind() == Alias); return index; } - + bool isOwned() const { return K == OwnedSymbol || K == OwnedAllocatedSymbol || K == OwnedWhenTrackedReceiver; } - + static RetEffect MakeOwnedWhenTrackedReceiver() { return RetEffect(OwnedWhenTrackedReceiver, ObjC); } - + static RetEffect MakeAlias(unsigned Idx) { return RetEffect(Alias, Idx); } static RetEffect MakeReceiverAlias() { return RetEffect(ReceiverAlias); - } + } static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) { return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o); - } + } static RetEffect MakeNotOwned(ObjKind o) { return RetEffect(NotOwnedSymbol, o); } static RetEffect MakeGCNotOwned() { return RetEffect(GCNotOwnedSymbol, ObjC); } - + static RetEffect MakeNoRet() { return RetEffect(NoRet); } - + void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned)K); ID.AddInteger((unsigned)O); ID.AddInteger(index); } }; - - + + class VISIBILITY_HIDDEN RetainSummary { /// Args - an ordered vector of (index, ArgEffect) pairs, where index /// specifies the argument (starting from 0). This can be sparsely /// populated; arguments with no entry in Args use 'DefaultArgEffect'. ArgEffects Args; - + /// DefaultArgEffect - The default ArgEffect to apply to arguments that /// do not have an entry in Args. ArgEffect DefaultArgEffect; - + /// Receiver - If this summary applies to an Objective-C message expression, /// this is the effect applied to the state of the receiver. ArgEffect Receiver; - + /// Ret - The effect on the return value. Used to indicate if the /// function/method call returns a new tracked symbol, returns an /// alias of one of the arguments in the call, and so on. RetEffect Ret; - + /// EndPath - Indicates that execution of this method/function should /// terminate the simulation of a path. bool EndPath; - + public: RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff, ArgEffect ReceiverEff, bool endpath = false) : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R), - EndPath(endpath) {} - + EndPath(endpath) {} + /// getArg - Return the argument effect on the argument specified by /// idx (starting from 0). ArgEffect getArg(unsigned idx) const { if (const ArgEffect *AE = Args.lookup(idx)) return *AE; - + return DefaultArgEffect; } - + /// setDefaultArgEffect - Set the default argument effect. void setDefaultArgEffect(ArgEffect E) { DefaultArgEffect = E; } - + /// setArg - Set the argument effect on the argument specified by idx. void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) { Args = AF.Add(Args, idx, E); } - + /// getRetEffect - Returns the effect on the return value of the call. RetEffect getRetEffect() const { return Ret; } - + /// setRetEffect - Set the effect of the return value of the call. void setRetEffect(RetEffect E) { Ret = E; } - + /// isEndPath - Returns true if executing the given method/function should /// terminate the path. bool isEndPath() const { return EndPath; } - + /// getReceiverEffect - Returns the effect on the receiver of the call. /// This is only meaningful if the summary applies to an ObjCMessageExpr*. ArgEffect getReceiverEffect() const { return Receiver; } - + /// setReceiverEffect - Set the effect on the receiver of the call. void setReceiverEffect(ArgEffect E) { Receiver = E; } - + typedef ArgEffects::iterator ExprIterator; - + ExprIterator begin_args() const { return Args.begin(); } ExprIterator end_args() const { return Args.end(); } - + static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A, RetEffect RetEff, ArgEffect DefaultEff, ArgEffect ReceiverEff, bool EndPath) { @@ -425,7 +425,7 @@ public: ID.AddInteger((unsigned) ReceiverEff); ID.AddInteger((unsigned) EndPath); } - + void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath); } @@ -440,7 +440,7 @@ namespace { class VISIBILITY_HIDDEN ObjCSummaryKey { IdentifierInfo* II; Selector S; -public: +public: ObjCSummaryKey(IdentifierInfo* ii, Selector s) : II(ii), S(s) {} @@ -449,10 +449,10 @@ public: ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s) : II(d ? d->getIdentifier() : ii), S(s) {} - + ObjCSummaryKey(Selector s) : II(0), S(s) {} - + IdentifierInfo* getIdentifier() const { return II; } Selector getSelector() const { return S; } }; @@ -464,56 +464,56 @@ template <> struct DenseMapInfo { return ObjCSummaryKey(DenseMapInfo::getEmptyKey(), DenseMapInfo::getEmptyKey()); } - + static inline ObjCSummaryKey getTombstoneKey() { return ObjCSummaryKey(DenseMapInfo::getTombstoneKey(), - DenseMapInfo::getTombstoneKey()); + DenseMapInfo::getTombstoneKey()); } - + static unsigned getHashValue(const ObjCSummaryKey &V) { return (DenseMapInfo::getHashValue(V.getIdentifier()) - & 0x88888888) + & 0x88888888) | (DenseMapInfo::getHashValue(V.getSelector()) & 0x55555555); } - + static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) { return DenseMapInfo::isEqual(LHS.getIdentifier(), RHS.getIdentifier()) && DenseMapInfo::isEqual(LHS.getSelector(), RHS.getSelector()); } - + static bool isPod() { return DenseMapInfo::isPod() && DenseMapInfo::isPod(); } }; } // end llvm namespace - + namespace { class VISIBILITY_HIDDEN ObjCSummaryCache { typedef llvm::DenseMap MapTy; MapTy M; public: ObjCSummaryCache() {} - + RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName, Selector S) { // Lookup the method using the decl for the class @interface. If we // have no decl, lookup using the class name. return D ? find(D, S) : find(ClsName, S); } - - RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) { + + RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) { // Do a lookup with the (D,S) pair. If we find a match return // the iterator. ObjCSummaryKey K(D, S); MapTy::iterator I = M.find(K); - + if (I != M.end() || !D) return I->second; - + // Walk the super chain. If we find a hit with a parent, we'll end // up returning that summary. We actually allow that key (null,S), as // we cache summaries for the null ObjCInterfaceDecl* to allow us to @@ -523,62 +523,62 @@ public: for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) { if ((I = M.find(ObjCSummaryKey(C, S))) != M.end()) break; - + if (!C) return NULL; } - - // Cache the summary with original key to make the next lookup faster + + // Cache the summary with original key to make the next lookup faster // and return the iterator. RetainSummary *Summ = I->second; M[K] = Summ; return Summ; } - + RetainSummary* find(Expr* Receiver, Selector S) { return find(getReceiverDecl(Receiver), S); } - + RetainSummary* find(IdentifierInfo* II, Selector S) { // FIXME: Class method lookup. Right now we dont' have a good way // of going between IdentifierInfo* and the class hierarchy. MapTy::iterator I = M.find(ObjCSummaryKey(II, S)); - + if (I == M.end()) I = M.find(ObjCSummaryKey(S)); - + return I == M.end() ? NULL : I->second; } - - const ObjCInterfaceDecl* getReceiverDecl(Expr* E) { + + const ObjCInterfaceDecl* getReceiverDecl(Expr* E) { if (const ObjCObjectPointerType* PT = E->getType()->getAsObjCObjectPointerType()) return PT->getInterfaceDecl(); return NULL; } - + RetainSummary*& operator[](ObjCMessageExpr* ME) { - + Selector S = ME->getSelector(); - + if (Expr* Receiver = ME->getReceiver()) { const ObjCInterfaceDecl* OD = getReceiverDecl(Receiver); return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S]; } - + return M[ObjCSummaryKey(ME->getClassName(), S)]; } - + RetainSummary*& operator[](ObjCSummaryKey K) { return M[K]; } - + RetainSummary*& operator[](Selector S) { return M[ ObjCSummaryKey(S) ]; } -}; +}; } // end anonymous namespace //===----------------------------------------------------------------------===// @@ -591,29 +591,29 @@ class VISIBILITY_HIDDEN RetainSummaryManager { //==-----------------------------------------------------------------==// // Typedefs. //==-----------------------------------------------------------------==// - + typedef llvm::DenseMap FuncSummariesTy; - + typedef ObjCSummaryCache ObjCMethodSummariesTy; - + //==-----------------------------------------------------------------==// // Data. //==-----------------------------------------------------------------==// - + /// Ctx - The ASTContext object for the analyzed ASTs. ASTContext& Ctx; /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier /// "CFDictionaryCreate". IdentifierInfo* CFDictionaryCreateII; - + /// GCEnabled - Records whether or not the analyzed code runs in GC mode. const bool GCEnabled; - + /// FuncSummaries - A map from FunctionDecls to summaries. - FuncSummariesTy FuncSummaries; - + FuncSummariesTy FuncSummaries; + /// ObjCClassMethodSummaries - A map from selectors (for instance methods) /// to summaries. ObjCMethodSummariesTy ObjCClassMethodSummaries; @@ -624,34 +624,34 @@ class VISIBILITY_HIDDEN RetainSummaryManager { /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects, /// and all other data used by the checker. llvm::BumpPtrAllocator BPAlloc; - + /// AF - A factory for ArgEffects objects. - ArgEffects::Factory AF; - + ArgEffects::Factory AF; + /// ScratchArgs - A holding buffer for construct ArgEffects. ArgEffects ScratchArgs; - + /// ObjCAllocRetE - Default return effect for methods returning Objective-C /// objects. RetEffect ObjCAllocRetE; - /// ObjCInitRetE - Default return effect for init methods returning + /// ObjCInitRetE - Default return effect for init methods returning /// Objective-C objects. RetEffect ObjCInitRetE; - + RetainSummary DefaultSummary; RetainSummary* StopSummary; - + //==-----------------------------------------------------------------==// // Methods. //==-----------------------------------------------------------------==// - + /// getArgEffects - Returns a persistent ArgEffects object based on the /// data in ScratchArgs. ArgEffects getArgEffects(); - enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable }; - + enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable }; + public: RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; } @@ -659,13 +659,13 @@ public: RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate(); return new (Summ) RetainSummary(DefaultSummary); } - + RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func); - + RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD); - RetainSummary* getCFSummaryGetRule(FunctionDecl* FD); + RetainSummary* getCFSummaryGetRule(FunctionDecl* FD); RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName); - + RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff, ArgEffect ReceiverEff = DoNothing, ArgEffect DefaultEff = MayEscape, @@ -676,36 +676,36 @@ public: ArgEffect DefaultEff = MayEscape) { return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff); } - + RetainSummary *getPersistentStopSummary() { if (StopSummary) return StopSummary; - + StopSummary = getPersistentSummary(RetEffect::MakeNoRet(), StopTracking, StopTracking); return StopSummary; - } + } RetainSummary *getInitMethodSummary(QualType RetTy); void InitializeClassMethodSummaries(); void InitializeMethodSummaries(); - + bool isTrackedObjCObjectType(QualType T); bool isTrackedCFObjectType(QualType T); - + private: - + void addClsMethSummary(IdentifierInfo* ClsII, Selector S, RetainSummary* Summ) { ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } - + void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) { ObjCClassMethodSummaries[S] = Summ; } - + void addNSObjectMethSummary(Selector S, RetainSummary *Summ) { ObjCMethodSummaries[S] = Summ; } @@ -716,43 +716,43 @@ private: Selector S = GetNullarySelector(nullaryName, Ctx); ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } - + void addInstMethSummary(const char* Cls, const char* nullaryName, RetainSummary *Summ) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); Selector S = GetNullarySelector(nullaryName, Ctx); ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } - + Selector generateSelector(va_list argp) { llvm::SmallVector II; while (const char* s = va_arg(argp, const char*)) II.push_back(&Ctx.Idents.get(s)); - return Ctx.Selectors.getSelector(II.size(), &II[0]); + return Ctx.Selectors.getSelector(II.size(), &II[0]); } - + void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries, RetainSummary* Summ, va_list argp) { Selector S = generateSelector(argp); Summaries[ObjCSummaryKey(ClsII, S)] = Summ; } - + void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); - va_end(argp); + va_end(argp); } - + void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp); va_end(argp); } - + void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); @@ -769,9 +769,9 @@ private: addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); va_end(argp); } - + public: - + RetainSummaryManager(ASTContext& ctx, bool gcenabled) : Ctx(ctx), CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")), @@ -789,17 +789,17 @@ public: InitializeClassMethodSummaries(); InitializeMethodSummaries(); } - + ~RetainSummaryManager(); - - RetainSummary* getSummary(FunctionDecl* FD); - + + RetainSummary* getSummary(FunctionDecl* FD); + RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME, const ObjCInterfaceDecl* ID) { return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(), - ID, ME->getMethodDecl(), ME->getType()); + ID, ME->getMethodDecl(), ME->getType()); } - + RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName, const ObjCInterfaceDecl* ID, const ObjCMethodDecl *MD, @@ -809,7 +809,7 @@ public: const ObjCInterfaceDecl *ID, const ObjCMethodDecl *MD, QualType RetTy); - + RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) { return getClassMethodSummary(ME->getSelector(), ME->getClassName(), ME->getClassInfo().first, @@ -824,17 +824,17 @@ public: Selector S = MD->getSelector(); IdentifierInfo *ClsName = ID->getIdentifier(); QualType ResultTy = MD->getResultType(); - - // Resolve the method decl last. + + // Resolve the method decl last. if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD)) MD = InterfaceMD; - + if (MD->isInstanceMethod()) return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy); else return getClassMethodSummary(S, ClsName, ID, MD, ResultTy); } - + RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD, Selector S, QualType RetTy); @@ -845,14 +845,14 @@ public: const FunctionDecl *FD); bool isGCEnabled() const { return GCEnabled; } - + RetainSummary *copySummary(RetainSummary *OldSumm) { RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate(); new (Summ) RetainSummary(*OldSumm); return Summ; - } + } }; - + } // end anonymous namespace //===----------------------------------------------------------------------===// @@ -871,7 +871,7 @@ RetainSummary* RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff, ArgEffect ReceiverEff, ArgEffect DefaultEff, - bool isEndPath) { + bool isEndPath) { // Create the summary and return it. RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate(); new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath); @@ -887,31 +887,31 @@ bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) { return false; const ObjCObjectPointerType *PT = Ty->getAsObjCObjectPointerType(); - + // Can be true for objects with the 'NSObject' attribute. if (!PT) return true; - + // We assume that id<..>, id, and "Class" all represent tracked objects. if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() || PT->isObjCClassType()) return true; - // Does the interface subclass NSObject? - // FIXME: We can memoize here if this gets too expensive. - const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); + // 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->isForwardDecl()) return true; - + IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject"); for ( ; ID ; ID = ID->getSuperClass()) if (ID->getIdentifier() == NSObjectII) return true; - + return false; } @@ -945,33 +945,33 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { // No summary? Generate one. RetainSummary *S = 0; - + do { // We generate "stop" summaries for implicitly defined functions. if (FD->isImplicit()) { S = getPersistentStopSummary(); break; } - + // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the // function's type. const FunctionType* FT = FD->getType()->getAsFunctionType(); const char* FName = FD->getIdentifier()->getName(); - + // Strip away preceding '_'. Doing this here will effect all the checks // down below. while (*FName == '_') ++FName; - + // Inspect the result type. QualType RetTy = FT->getResultType(); - + // FIXME: This should all be refactored into a chain of "summary lookup" // filters. assert (ScratchArgs.isEmpty()); - + switch (strlen(FName)) { default: break; - + case 17: // Handle: id NSMakeCollectable(CFTypeRef) @@ -1003,10 +1003,10 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { // Part of . (IOKit) // This should be addressed using a API table. ScratchArgs = AF.Add(ScratchArgs, 2, DecRef); - S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); + S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } break; - + case 25: if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) { // Part of . (IOKit) @@ -1015,13 +1015,13 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { DoNothing, DoNothing); } break; - + case 26: if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) { // Part of . (IOKit) // This should be addressed using a API table. S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), - DoNothing, DoNothing); + DoNothing, DoNothing); } break; @@ -1030,7 +1030,7 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { // Part of . // This should be addressed using a API table. ScratchArgs = AF.Add(ScratchArgs, 1, DecRef); - S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); + S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } break; @@ -1043,17 +1043,17 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } break; - + case 32: if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) { // Part of . // This should be addressed using a API table. ScratchArgs = AF.Add(ScratchArgs, 2, DecRef); - S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); + S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } break; } - + // Did we get a summary? if (S) break; @@ -1063,7 +1063,7 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { #if 0 // Handle: NSDeallocateObject(id anObject); // This method does allow 'nil' (although we don't check it now). - if (strcmp(FName, "NSDeallocateObject") == 0) { + if (strcmp(FName, "NSDeallocateObject") == 0) { return RetTy == Ctx.VoidTy ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc) : getPersistentStopSummary(); @@ -1077,7 +1077,7 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { S = getUnarySummary(FT, cfretain); else if (strstr(FName, "MakeCollectable")) S = getUnarySummary(FT, cfmakecollectable); - else + else S = getCFCreateGetRuleSummary(FD, FName); break; @@ -1100,7 +1100,7 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { S = getCFCreateGetRuleSummary(FD, FName); break; } - + break; } @@ -1112,7 +1112,7 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { FName += 4; else FName += 2; - + if (isRelease(FD, FName)) S = getUnarySummary(FT, cfrelease); else { @@ -1122,9 +1122,9 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { // and that ownership cannot be transferred. While this is technically // correct, many methods allow a tracked object to escape. For example: // - // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); + // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); // CFDictionaryAddValue(y, key, x); - // CFRelease(x); + // CFRelease(x); // ... it is okay to use 'x' since 'y' has a reference to it // // We handle this and similar cases with the follow heuristic. If the @@ -1138,34 +1138,34 @@ RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { CStrInCStrNoCase(FName, "AppendValue") || CStrInCStrNoCase(FName, "SetAttribute")) ? MayEscape : DoNothing; - + S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E); } } } while (0); - + if (!S) S = getDefaultSummary(); // Annotations override defaults. assert(S); updateSummaryFromAnnotations(*S, FD); - + FuncSummaries[FD] = S; - return S; + return S; } RetainSummary* RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName) { - + if (strstr(FName, "Create") || strstr(FName, "Copy")) return getCFSummaryCreateRule(FD); - + if (strstr(FName, "Get")) return getCFSummaryGetRule(FD); - + return getDefaultSummary(); } @@ -1178,27 +1178,27 @@ RetainSummaryManager::getUnarySummary(const FunctionType* FT, const FunctionProtoType* FTP = dyn_cast(FT); if (!FTP || FTP->getNumArgs() != 1) return getPersistentStopSummary(); - + assert (ScratchArgs.isEmpty()); - + switch (func) { case cfretain: { ScratchArgs = AF.Add(ScratchArgs, 0, IncRef); return getPersistentSummary(RetEffect::MakeAlias(0), DoNothing, DoNothing); } - + case cfrelease: { ScratchArgs = AF.Add(ScratchArgs, 0, DecRef); return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } - + case cfmakecollectable: { ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable); - return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing); + return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing); } - + default: assert (false && "Not a supported unary function."); return getDefaultSummary(); @@ -1207,17 +1207,17 @@ RetainSummaryManager::getUnarySummary(const FunctionType* FT, RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) { assert (ScratchArgs.isEmpty()); - + if (FD->getIdentifier() == CFDictionaryCreateII) { ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef); ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef); } - + return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); } RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) { - assert (ScratchArgs.isEmpty()); + assert (ScratchArgs.isEmpty()); return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), DoNothing, DoNothing); } @@ -1228,12 +1228,12 @@ RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) { RetainSummary* RetainSummaryManager::getInitMethodSummary(QualType RetTy) { - assert(ScratchArgs.isEmpty()); + assert(ScratchArgs.isEmpty()); // 'init' methods conceptually return a newly allocated object and claim - // the receiver. + // the receiver. if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy)) return getPersistentSummary(ObjCInitRetE, DecRefMsg); - + return getDefaultSummary(); } @@ -1244,7 +1244,7 @@ RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ, return; QualType RetTy = FD->getResultType(); - + // Determine if there is a special return effect for this method. if (isTrackedObjCObjectType(RetTy)) { if (FD->getAttr()) { @@ -1268,20 +1268,20 @@ RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ, return; bool isTrackedLoc = false; - + // Determine if there is a special return effect for this method. if (isTrackedObjCObjectType(MD->getResultType())) { if (MD->getAttr()) { Summ.setRetEffect(ObjCAllocRetE); return; } - + isTrackedLoc = true; } - + if (!isTrackedLoc) isTrackedLoc = MD->getResultType()->getAs() != NULL; - + if (isTrackedLoc && MD->getAttr()) Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); } @@ -1304,10 +1304,10 @@ RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD, ScratchArgs = AF.Add(ScratchArgs, i, StopTracking); } } - + // Any special effect for the receiver? ArgEffect ReceiverEff = DoNothing; - + // If one of the arguments in the selector has the keyword 'delegate' we // should stop tracking the reference count for the receiver. This is // because the reference count is quite possibly handled by a delegate @@ -1317,29 +1317,29 @@ RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD, assert(!str.empty()); if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking; } - + // Look for methods that return an owned object. - if (isTrackedObjCObjectType(RetTy)) { + if (isTrackedObjCObjectType(RetTy)) { // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned // by instance methods. RetEffect E = followsFundamentalRule(S) ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC); - - return getPersistentSummary(E, ReceiverEff, MayEscape); + + return getPersistentSummary(E, ReceiverEff, MayEscape); } - + // Look for methods that return an owned core foundation object. if (isTrackedCFObjectType(RetTy)) { RetEffect E = followsFundamentalRule(S) ? RetEffect::MakeOwned(RetEffect::CF, true) : RetEffect::MakeNotOwned(RetEffect::CF); - + return getPersistentSummary(E, ReceiverEff, MayEscape); } - + if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing) return getDefaultSummary(); - + return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape); } @@ -1352,23 +1352,23 @@ RetainSummaryManager::getInstanceMethodSummary(Selector S, // Look up a summary in our summary cache. RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S); - + if (!Summ) { assert(ScratchArgs.isEmpty()); - + // "initXXX": pass-through for receiver. if (deriveNamingConvention(S) == InitRule) Summ = getInitMethodSummary(RetTy); else Summ = getCommonMethodSummary(MD, S, RetTy); - + // Annotations override defaults. updateSummaryFromAnnotations(*Summ, MD); - + // Memoize the summary. ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ; } - + return Summ; } @@ -1379,8 +1379,8 @@ RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName, QualType RetTy) { assert(ClsName && "Class name must be specified."); - RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S); - + RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S); + if (!Summ) { Summ = getCommonMethodSummary(MD, S, RetTy); // Annotations override defaults. @@ -1388,32 +1388,32 @@ RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName, // Memoize the summary. ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ; } - + return Summ; } -void RetainSummaryManager::InitializeClassMethodSummaries() { +void RetainSummaryManager::InitializeClassMethodSummaries() { assert(ScratchArgs.isEmpty()); RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE); - + // Create the summaries for "alloc", "new", and "allocWithZone:" for // NSObject and its derivatives. addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ); addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ); addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ); - - // Create the [NSAssertionHandler currentHander] summary. + + // Create the [NSAssertionHandler currentHander] summary. addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"), GetNullarySelector("currentHandler", Ctx), getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC))); - + // Create the [NSAutoreleasePool addObject:] summary. ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease); addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"), GetUnarySelector("addObject", Ctx), getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Autorelease)); - + // Create the summaries for [NSObject performSelector...]. We treat // these as 'stop tracking' for the arguments because they are often // used for delegates that can release the object. When we have better @@ -1435,7 +1435,7 @@ void RetainSummaryManager::InitializeClassMethodSummaries() { "withObject", "waitUntilDone", "modes", NULL); addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground", "withObject", NULL); - + // Specially handle NSData. RetainSummary *dataWithBytesNoCopySumm = getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing, @@ -1447,43 +1447,43 @@ void RetainSummaryManager::InitializeClassMethodSummaries() { } void RetainSummaryManager::InitializeMethodSummaries() { - - assert (ScratchArgs.isEmpty()); - + + assert (ScratchArgs.isEmpty()); + // Create the "init" selector. It just acts as a pass-through for the // receiver. - RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg); + RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg); addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); // awakeAfterUsingCoder: behaves basically like an 'init' method. It // claims the receiver and returns a retained object. addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx), InitSumm); - + // The next methods are allocators. RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE); - RetainSummary *CFAllocSumm = + RetainSummary *CFAllocSumm = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); - - // Create the "copy" selector. - addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm); + + // Create the "copy" selector. + addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm); // Create the "mutableCopy" selector. addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm); - + // Create the "retain" selector. RetEffect E = RetEffect::MakeReceiverAlias(); RetainSummary *Summ = getPersistentSummary(E, IncRefMsg); addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); - + // Create the "release" selector. Summ = getPersistentSummary(E, DecRefMsg); addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); - + // Create the "drain" selector. Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef); addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ); - + // Create the -dealloc summary. Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc); addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); @@ -1491,13 +1491,13 @@ void RetainSummaryManager::InitializeMethodSummaries() { // Create the "autorelease" selector. Summ = getPersistentSummary(E, Autorelease); addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); - + // Specially handle NSAutoreleasePool. addInstMethSummary("NSAutoreleasePool", "init", getPersistentSummary(RetEffect::MakeReceiverAlias(), NewAutoreleasePool)); - - // For NSWindow, allocated objects are (initially) self-owned. + + // For NSWindow, allocated objects are (initially) self-owned. // FIXME: For now we opt for false negatives with NSWindow, as these objects // self-own themselves. However, they only do this once they are displayed. // Thus, we need to track an NSWindow's display status. @@ -1506,42 +1506,42 @@ void RetainSummaryManager::InitializeMethodSummaries() { RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(), StopTracking, StopTracking); - + addClassMethSummary("NSWindow", "alloc", NoTrackYet); #if 0 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", NULL); - + addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", "screen", NULL); #endif - + // For NSPanel (which subclasses NSWindow), allocated objects are not // self-owned. // FIXME: For now we don't track NSPanels. object for the same reason // as for NSWindow objects. addClassMethSummary("NSPanel", "alloc", NoTrackYet); - + #if 0 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", NULL); - + addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", "screen", NULL); #endif - + // Don't track allocated autorelease pools yet, as it is okay to prematurely // exit a method. addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet); // Create NSAssertionHandler summaries. addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file", - "lineNumber", "description", NULL); - + "lineNumber", "description", NULL); + addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object", "file", "lineNumber", "description", NULL); - + // Create summaries QCRenderer/QCView -createSnapShotImageOfType: addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType", NULL); @@ -1554,7 +1554,7 @@ void RetainSummaryManager::InitializeMethodSummaries() { addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect", NULL); addInstMethSummary("CIContext", CFAllocSumm, - "createCGImage", "fromRect", "format", "colorSpace", NULL); + "createCGImage", "fromRect", "format", "colorSpace", NULL); addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info", NULL); } @@ -1564,19 +1564,19 @@ void RetainSummaryManager::InitializeMethodSummaries() { //===----------------------------------------------------------------------===// namespace { - + class VISIBILITY_HIDDEN RefVal { -public: +public: enum Kind { - Owned = 0, // Owning reference. - NotOwned, // Reference is not owned by still valid (not freed). + Owned = 0, // Owning reference. + NotOwned, // Reference is not owned by still valid (not freed). Released, // Object has been released. ReturnedOwned, // Returned object passes ownership to caller. ReturnedNotOwned, // Return object does not pass ownership to caller. ERROR_START, ErrorDeallocNotOwned, // -dealloc called on non-owned object. ErrorDeallocGC, // Calling -dealloc with GC enabled. - ErrorUseAfterRelease, // Object used after released. + ErrorUseAfterRelease, // Object used after released. ErrorReleaseNotOwned, // Release of an object that was not owned. ERROR_LEAK_START, ErrorLeak, // A memory leak due to excessive reference counts. @@ -1587,7 +1587,7 @@ public: ErrorReturnedNotOwned }; -private: +private: Kind kind; RetEffect::ObjKind okind; unsigned Cnt; @@ -1600,9 +1600,9 @@ private: RefVal(Kind k, unsigned cnt = 0) : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {} -public: +public: Kind getKind() const { return kind; } - + RetEffect::ObjKind getObjKind() const { return okind; } unsigned getCount() const { return Cnt; } @@ -1611,72 +1611,72 @@ public: void clearCounts() { Cnt = 0; ACnt = 0; } void setCount(unsigned i) { Cnt = i; } void setAutoreleaseCount(unsigned i) { ACnt = i; } - + QualType getType() const { return T; } - + // Useful predicates. - + static bool isError(Kind k) { return k >= ERROR_START; } - + static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; } - + bool isOwned() const { return getKind() == Owned; } - + bool isNotOwned() const { return getKind() == NotOwned; } - + bool isReturnedOwned() const { return getKind() == ReturnedOwned; } - + bool isReturnedNotOwned() const { return getKind() == ReturnedNotOwned; } - + bool isNonLeakError() const { Kind k = getKind(); return isError(k) && !isLeak(k); } - + static RefVal makeOwned(RetEffect::ObjKind o, QualType t, unsigned Count = 1) { return RefVal(Owned, o, Count, 0, t); } - + static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t, unsigned Count = 0) { return RefVal(NotOwned, o, Count, 0, t); } - + // Comparison, profiling, and pretty-printing. - + bool operator==(const RefVal& X) const { return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt; } - + RefVal operator-(size_t i) const { return RefVal(getKind(), getObjKind(), getCount() - i, getAutoreleaseCount(), getType()); } - + RefVal operator+(size_t i) const { return RefVal(getKind(), getObjKind(), getCount() + i, getAutoreleaseCount(), getType()); } - + RefVal operator^(Kind k) const { return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(), getType()); } - + RefVal autorelease() const { return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1, getType()); } - + void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned) kind); ID.AddInteger(Cnt); @@ -1686,41 +1686,41 @@ public: void print(llvm::raw_ostream& Out) const; }; - + void RefVal::print(llvm::raw_ostream& Out) const { if (!T.isNull()) Out << "Tracked Type:" << T.getAsString() << '\n'; - + switch (getKind()) { default: assert(false); - case Owned: { + case Owned: { Out << "Owned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } - + case NotOwned: { Out << "NotOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } - - case ReturnedOwned: { + + case ReturnedOwned: { Out << "ReturnedOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } - + case ReturnedNotOwned: { Out << "ReturnedNotOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } - + case Released: Out << "Released"; break; @@ -1728,19 +1728,19 @@ void RefVal::print(llvm::raw_ostream& Out) const { case ErrorDeallocGC: Out << "-dealloc (GC)"; break; - + case ErrorDeallocNotOwned: Out << "-dealloc (not-owned)"; break; - + case ErrorLeak: Out << "Leaked"; - break; - + break; + case ErrorLeakReturned: Out << "Leaked (Bad naming)"; break; - + case ErrorGCLeakReturned: Out << "Leaked (GC-ed at return)"; break; @@ -1748,38 +1748,38 @@ void RefVal::print(llvm::raw_ostream& Out) const { case ErrorUseAfterRelease: Out << "Use-After-Release [ERROR]"; break; - + case ErrorReleaseNotOwned: Out << "Release of Not-Owned [ERROR]"; break; - + case RefVal::ErrorOverAutorelease: Out << "Over autoreleased"; break; - + case RefVal::ErrorReturnedNotOwned: Out << "Non-owned object returned instead of owned"; break; } - + if (ACnt) { Out << " [ARC +" << ACnt << ']'; } } - + } // end anonymous namespace //===----------------------------------------------------------------------===// // RefBindings - State used to track object reference counts. //===----------------------------------------------------------------------===// - + typedef llvm::ImmutableMap RefBindings; static int RefBIndex = 0; namespace clang { template<> struct GRStateTrait : public GRStatePartialTrait { - static inline void* GDMIndex() { return &RefBIndex; } + static inline void* GDMIndex() { return &RefBIndex; } }; } @@ -1800,12 +1800,12 @@ namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; } namespace clang { template<> struct GRStateTrait : public GRStatePartialTrait { - static inline void* GDMIndex() { return &AutoRBIndex; } + static inline void* GDMIndex() { return &AutoRBIndex; } }; template<> struct GRStateTrait : public GRStatePartialTrait { - static inline void* GDMIndex() { return &AutoRCIndex; } + static inline void* GDMIndex() { return &AutoRCIndex; } }; } // end clang namespace @@ -1820,14 +1820,14 @@ static const GRState * SendAutorelease(const GRState *state, SymbolRef pool = GetCurrentAutoreleasePool(state); const ARCounts *cnts = state->get(pool); ARCounts newCnts(0); - + if (cnts) { const unsigned *cnt = (*cnts).lookup(sym); newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1); } else newCnts = F.Add(F.GetEmptyMap(), sym, 1); - + return state->set(pool, newCnts); } @@ -1836,7 +1836,7 @@ static const GRState * SendAutorelease(const GRState *state, //===----------------------------------------------------------------------===// namespace { - + class VISIBILITY_HIDDEN CFRefCount : public GRTransferFuncs { public: class BindingsPrinter : public GRState::Printer { @@ -1847,9 +1847,9 @@ public: private: typedef llvm::DenseMap - SummaryLogTy; + SummaryLogTy; - RetainSummaryManager Summaries; + RetainSummaryManager Summaries; SummaryLogTy SummaryLog; const LangOptions& LOpts; ARCounts::Factory ARCountFactory; @@ -1860,7 +1860,7 @@ private: BugType *overAutorelease; BugType *returnNotOwnedForOwned; BugReporter *BR; - + const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind& hasErr); @@ -1870,40 +1870,40 @@ private: ExplodedNode* Pred, const GRState* St, RefVal::Kind hasErr, SymbolRef Sym); - + const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V, llvm::SmallVectorImpl &Leaked); - + ExplodedNode* ProcessLeaks(const GRState * state, llvm::SmallVectorImpl &Leaked, GenericNodeBuilder &Builder, GRExprEngine &Eng, ExplodedNode *Pred = 0); - -public: + +public: CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts) : Summaries(Ctx, gcenabled), LOpts(lopts), useAfterRelease(0), releaseNotOwned(0), deallocGC(0), deallocNotOwned(0), leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), returnNotOwnedForOwned(0), BR(0) {} - + virtual ~CFRefCount() {} - + void RegisterChecks(BugReporter &BR); - + virtual void RegisterPrinters(std::vector& Printers) { Printers.push_back(new BindingsPrinter()); } - + bool isGCEnabled() const { return Summaries.isGCEnabled(); } const LangOptions& getLangOptions() const { return LOpts; } - + const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const { SummaryLogTy::const_iterator I = SummaryLog.find(N); return I == SummaryLog.end() ? 0 : I->second; } - + // Calls. void EvalSummary(ExplodedNodeSet& Dst, @@ -1914,47 +1914,47 @@ public: const RetainSummary& Summ, ExprIterator arg_beg, ExprIterator arg_end, ExplodedNode* Pred); - + virtual void EvalCall(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, CallExpr* CE, SVal L, - ExplodedNode* Pred); - - + ExplodedNode* Pred); + + virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ObjCMessageExpr* ME, ExplodedNode* Pred); - + bool EvalObjCMessageExprAux(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ObjCMessageExpr* ME, ExplodedNode* Pred); - // Stores. + // Stores. virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val); // End-of-path. - + virtual void EvalEndPath(GRExprEngine& Engine, GREndPathNodeBuilder& Builder); - + virtual void EvalDeadSymbols(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ExplodedNode* Pred, Stmt* S, const GRState* state, SymbolReaper& SymReaper); - + std::pair HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd, ExplodedNode* Pred, GRExprEngine &Eng, SymbolRef Sym, RefVal V, bool &stop); // Return statements. - + virtual void EvalReturn(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, @@ -1977,34 +1977,34 @@ static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym, else Out << ""; Out << ":{"; - + // Get the contents of the pool. if (const ARCounts *cnts = state->get(Sym)) for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J) Out << '(' << J.getKey() << ',' << J.getData() << ')'; - Out << '}'; + Out << '}'; } void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out, const GRState* state, const char* nl, const char* sep) { - + RefBindings B = state->get(); - + if (!B.isEmpty()) Out << sep << nl; - + for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { Out << (*I).first << " : "; (*I).second.print(Out); Out << nl; } - + // Print the autorelease stack. Out << sep << nl << "AR pool stack:"; ARStack stack = state->get(); - + PrintPool(Out, SymbolRef(), state); // Print the caller's pool. for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I) PrintPool(Out, *I, state); @@ -2017,117 +2017,117 @@ void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out, //===----------------------------------------------------------------------===// namespace { - + //===-------------===// // Bug Descriptions. // - //===-------------===// - + //===-------------===// + class VISIBILITY_HIDDEN CFRefBug : public BugType { protected: CFRefCount& TF; - - CFRefBug(CFRefCount* tf, const char* name) - : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {} + + CFRefBug(CFRefCount* tf, const char* name) + : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {} public: - + CFRefCount& getTF() { return TF; } const CFRefCount& getTF() const { return TF; } - + // FIXME: Eventually remove. virtual const char* getDescription() const = 0; - + virtual bool isLeak() const { return false; } }; - + class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug { public: UseAfterRelease(CFRefCount* tf) : CFRefBug(tf, "Use-after-release") {} - + const char* getDescription() const { return "Reference-counted object is used after it is released"; - } + } }; - + class VISIBILITY_HIDDEN BadRelease : public CFRefBug { public: BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {} - + const char* getDescription() const { return "Incorrect decrement of the reference count of an " "object is not owned at this point by the caller"; } }; - + class VISIBILITY_HIDDEN DeallocGC : public CFRefBug { public: DeallocGC(CFRefCount *tf) : CFRefBug(tf, "-dealloc called while using garbage collection") {} - + const char *getDescription() const { return "-dealloc called while using garbage collection"; } }; - + class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug { public: DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {} - + const char *getDescription() const { return "-dealloc sent to object that may be referenced elsewhere"; } - }; - + }; + class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug { public: - OverAutorelease(CFRefCount *tf) : + OverAutorelease(CFRefCount *tf) : CFRefBug(tf, "Object sent -autorelease too many times") {} - + const char *getDescription() const { return "Object sent -autorelease too many times"; } }; - + class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug { public: ReturnedNotOwnedForOwned(CFRefCount *tf) : CFRefBug(tf, "Method should return an owned object") {} - + const char *getDescription() const { return "Object with +0 retain counts returned to caller where a +1 " "(owning) retain count is expected"; } }; - + class VISIBILITY_HIDDEN Leak : public CFRefBug { const bool isReturn; protected: Leak(CFRefCount* tf, const char* name, bool isRet) : CFRefBug(tf, name), isReturn(isRet) {} public: - + const char* getDescription() const { return ""; } - + bool isLeak() const { return true; } }; - + class VISIBILITY_HIDDEN LeakAtReturn : public Leak { public: LeakAtReturn(CFRefCount* tf, const char* name) : Leak(tf, name, true) {} }; - + class VISIBILITY_HIDDEN LeakWithinFunction : public Leak { public: LeakWithinFunction(CFRefCount* tf, const char* name) : Leak(tf, name, false) {} - }; - + }; + //===---------===// // Bug Reports. // //===---------===// - + class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport { protected: SymbolRef Sym; @@ -2140,30 +2140,30 @@ namespace { CFRefReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym, const char* endText) : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {} - + virtual ~CFRefReport() {} - + CFRefBug& getBugType() { return (CFRefBug&) RangedBugReport::getBugType(); } const CFRefBug& getBugType() const { return (const CFRefBug&) RangedBugReport::getBugType(); } - + virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) { if (!getBugType().isLeak()) RangedBugReport::getRanges(beg, end); else beg = end = 0; } - + SymbolRef getSymbol() const { return Sym; } - + PathDiagnosticPiece* getEndPath(BugReporterContext& BRC, const ExplodedNode* N); - + std::pair getExtraDescriptiveText(); - + PathDiagnosticPiece* VisitNode(const ExplodedNode* N, const ExplodedNode* PrevN, BugReporterContext& BRC); @@ -2176,36 +2176,36 @@ namespace { CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym, GRExprEngine& Eng); - + PathDiagnosticPiece* getEndPath(BugReporterContext& BRC, const ExplodedNode* N); - + SourceLocation getLocation() const { return AllocSite; } - }; + }; } // end anonymous namespace void CFRefCount::RegisterChecks(BugReporter& BR) { useAfterRelease = new UseAfterRelease(this); BR.Register(useAfterRelease); - + releaseNotOwned = new BadRelease(this); BR.Register(releaseNotOwned); - + deallocGC = new DeallocGC(this); BR.Register(deallocGC); - + deallocNotOwned = new DeallocNotOwned(this); BR.Register(deallocNotOwned); - + overAutorelease = new OverAutorelease(this); BR.Register(overAutorelease); - + returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this); BR.Register(returnNotOwnedForOwned); - + // First register "return" leaks. const char* name = 0; - + if (isGCEnabled()) name = "Leak of returned object when using garbage collection"; else if (getLangOptions().getGCMode() == LangOptions::HybridGC) @@ -2215,13 +2215,13 @@ void CFRefCount::RegisterChecks(BugReporter& BR) { assert(getLangOptions().getGCMode() == LangOptions::NonGC); name = "Leak of returned object"; } - + leakAtReturn = new LeakAtReturn(this, name); BR.Register(leakAtReturn); - + // Second, register leaks within a function/method. if (isGCEnabled()) - name = "Leak of object when using garbage collection"; + name = "Leak of object when using garbage collection"; else if (getLangOptions().getGCMode() == LangOptions::HybridGC) name = "Leak of object when not using garbage collection (GC) in " "dual GC/non-GC code"; @@ -2229,22 +2229,22 @@ void CFRefCount::RegisterChecks(BugReporter& BR) { assert(getLangOptions().getGCMode() == LangOptions::NonGC); name = "Leak"; } - + leakWithinFunction = new LeakWithinFunction(this, name); BR.Register(leakWithinFunction); - + // Save the reference to the BugReporter. this->BR = &BR; } static const char* Msgs[] = { // GC only - "Code is compiled to only use garbage collection", + "Code is compiled to only use garbage collection", // No GC. "Code is compiled to use reference counts", // Hybrid, with GC. "Code is compiled to use either garbage collection (GC) or reference counts" - " (non-GC). The bug occurs with GC enabled", + " (non-GC). The bug occurs with GC enabled", // Hybrid, without GC "Code is compiled to use either garbage collection (GC) or reference counts" " (non-GC). The bug occurs in non-GC mode" @@ -2252,19 +2252,19 @@ static const char* Msgs[] = { std::pair CFRefReport::getExtraDescriptiveText() { CFRefCount& TF = static_cast(getBugType()).getTF(); - + switch (TF.getLangOptions().getGCMode()) { default: assert(false); - + case LangOptions::GCOnly: assert (TF.isGCEnabled()); - return std::make_pair(&Msgs[0], &Msgs[0]+1); - + return std::make_pair(&Msgs[0], &Msgs[0]+1); + case LangOptions::NonGC: assert (!TF.isGCEnabled()); return std::make_pair(&Msgs[1], &Msgs[1]+1); - + case LangOptions::HybridGC: if (TF.isGCEnabled()) return std::make_pair(&Msgs[2], &Msgs[2]+1); @@ -2278,50 +2278,50 @@ static inline bool contains(const llvm::SmallVectorImpl& V, for (llvm::SmallVectorImpl::const_iterator I=V.begin(), E=V.end(); I!=E; ++I) if (*I == X) return true; - + return false; } PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, const ExplodedNode* PrevN, BugReporterContext& BRC) { - + if (!isa(N->getLocation())) return NULL; - + // Check if the type state has changed. const GRState *PrevSt = PrevN->getState(); const GRState *CurrSt = N->getState(); - - const RefVal* CurrT = CurrSt->get(Sym); + + const RefVal* CurrT = CurrSt->get(Sym); if (!CurrT) return NULL; - + const RefVal &CurrV = *CurrT; const RefVal *PrevT = PrevSt->get(Sym); - + // Create a string buffer to constain all the useful things we want // to tell the user. std::string sbuf; llvm::raw_string_ostream os(sbuf); - + // This is the allocation site since the previous node had no bindings // for this symbol. if (!PrevT) { const Stmt* S = cast(N->getLocation()).getStmt(); - + if (const CallExpr *CE = dyn_cast(S)) { // Get the name of the callee (if it is available). SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee()); if (const FunctionDecl* FD = X.getAsFunctionDecl()) os << "Call to function '" << FD->getNameAsString() <<'\''; else - os << "function call"; - } + os << "function call"; + } else { assert (isa(S)); os << "Method"; } - + if (CurrV.getObjKind() == RetEffect::CF) { os << " returns a Core Foundation object with a "; } @@ -2329,10 +2329,10 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, assert (CurrV.getObjKind() == RetEffect::ObjC); os << " returns an Objective-C object with a "; } - + if (CurrV.isOwned()) { os << "+1 retain count (owning reference)."; - + if (static_cast(getBugType()).getTF().isGCEnabled()) { assert(CurrV.getObjKind() == RetEffect::CF); os << " " @@ -2343,39 +2343,39 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, assert (CurrV.isNotOwned()); os << "+0 retain count (non-owning reference)."; } - + PathDiagnosticLocation Pos(S, BRC.getSourceManager()); return new PathDiagnosticEventPiece(Pos, os.str()); } - + // Gather up the effects that were performed on the object at this // program point llvm::SmallVector AEffects; - + if (const RetainSummary *Summ = TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) { // We only have summaries attached to nodes after evaluating CallExpr and // ObjCMessageExprs. const Stmt* S = cast(N->getLocation()).getStmt(); - + if (const CallExpr *CE = dyn_cast(S)) { // Iterate through the parameter expressions and see if the symbol // was ever passed as an argument. unsigned i = 0; - + for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) { - + // Retrieve the value of the argument. Is it the symbol // we are interested in? if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym) continue; - + // We have an argument. Get the effect! AEffects.push_back(Summ->getArg(i)); } } - else if (const ObjCMessageExpr *ME = dyn_cast(S)) { + else if (const ObjCMessageExpr *ME = dyn_cast(S)) { if (const Expr *receiver = ME->getReceiver()) if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) { // The symbol we are tracking is the receiver. @@ -2383,11 +2383,11 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, } } } - + do { // Get the previous type state. RefVal PrevV = *PrevT; - + // Specially handle -dealloc. if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) { // Determine if the object's reference count was pushed to zero. @@ -2400,7 +2400,7 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, break; } } - + // Specially handle CFMakeCollectable and friends. if (contains(AEffects, MakeCollectable)) { // Get the name of the function. @@ -2408,15 +2408,15 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, SVal X = CurrSt->getSValAsScalarOrLoc(cast(S)->getCallee()); const FunctionDecl* FD = X.getAsFunctionDecl(); const std::string& FName = FD->getNameAsString(); - + if (TF.isGCEnabled()) { // Determine if the object's reference count was pushed to zero. assert(!(PrevV == CurrV) && "The typestate *must* have changed."); - + os << "In GC mode a call to '" << FName << "' decrements an object's retain count and registers the " "object with the garbage collector. "; - + if (CurrV.getKind() == RefVal::Released) { assert(CurrV.getCount() == 0); os << "Since it now has a 0 retain count the object can be " @@ -2427,67 +2427,67 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, "After this call its retain count is +" << CurrV.getCount() << '.'; } - else + else os << "When GC is not enabled a call to '" << FName << "' has no effect on its argument."; - + // Nothing more to say. break; } - - // Determine if the typestate has changed. + + // Determine if the typestate has changed. if (!(PrevV == CurrV)) switch (CurrV.getKind()) { case RefVal::Owned: case RefVal::NotOwned: - + if (PrevV.getCount() == CurrV.getCount()) { // Did an autorelease message get sent? if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount()) return 0; - + assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount()); os << "Object sent -autorelease message"; break; } - + if (PrevV.getCount() > CurrV.getCount()) os << "Reference count decremented."; else os << "Reference count incremented."; - + if (unsigned Count = CurrV.getCount()) os << " The object now has a +" << Count << " retain count."; - + if (PrevV.getKind() == RefVal::Released) { assert(TF.isGCEnabled() && CurrV.getCount() > 0); os << " The object is not eligible for garbage collection until the " "retain count reaches 0 again."; } - + break; - + case RefVal::Released: os << "Object released."; break; - + case RefVal::ReturnedOwned: os << "Object returned to caller as an owning reference (single retain " "count transferred to caller)."; break; - + case RefVal::ReturnedNotOwned: os << "Object returned to caller with a +0 (non-owning) retain count."; break; - + default: return NULL; } - + // Emit any remaining diagnostics for the argument effects (if any). for (llvm::SmallVectorImpl::iterator I=AEffects.begin(), E=AEffects.end(); I != E; ++I) { - + // A bunch of things have alternate behavior under GC. if (TF.isGCEnabled()) switch (*I) { @@ -2503,25 +2503,25 @@ PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, continue; } } - } while(0); - + } while (0); + if (os.str().empty()) return 0; // We have nothing to say! const Stmt* S = cast(N->getLocation()).getStmt(); PathDiagnosticLocation Pos(S, BRC.getSourceManager()); PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str()); - + // Add the range by scanning the children of the statement for any bindings // to Sym. - for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); + for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) if (const Expr* Exp = dyn_cast_or_null(*I)) if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) { P->addRange(Exp->getSourceRange()); break; } - + return P; } @@ -2531,56 +2531,56 @@ namespace { SymbolRef Sym; const MemRegion* Binding; bool First; - + public: FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {} - + bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal val) { - - SymbolRef SymV = val.getAsSymbol(); + + SymbolRef SymV = val.getAsSymbol(); if (!SymV || SymV != Sym) return true; - + if (Binding) { First = false; return false; } else Binding = R; - - return true; + + return true; } - + operator bool() { return First && Binding; } const MemRegion* getRegion() { return Binding; } - }; + }; } static std::pair GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N, SymbolRef Sym) { - + // Find both first node that referred to the tracked symbol and the // memory location that value was store to. const ExplodedNode* Last = N; - const MemRegion* FirstBinding = 0; - + const MemRegion* FirstBinding = 0; + while (N) { const GRState* St = N->getState(); RefBindings B = St->get(); - + if (!B.lookup(Sym)) break; - + FindUniqueBinding FB(Sym); - StateMgr.iterBindings(St, FB); - if (FB) FirstBinding = FB.getRegion(); - + StateMgr.iterBindings(St, FB); + if (FB) FirstBinding = FB.getRegion(); + Last = N; - N = N->pred_empty() ? NULL : *(N->pred_begin()); + N = N->pred_empty() ? NULL : *(N->pred_begin()); } - + return std::make_pair(Last, FirstBinding); } @@ -2596,36 +2596,36 @@ CFRefReport::getEndPath(BugReporterContext& BRC, PathDiagnosticPiece* CFRefLeakReport::getEndPath(BugReporterContext& BRC, const ExplodedNode* EndN){ - + // Tell the BugReporterContext to report cases when the tracked symbol is // assigned to different variables, etc. BRC.addNotableSymbol(Sym); - + // We are reporting a leak. Walk up the graph to get to the first node where // the symbol appeared, and also get the first VarDecl that tracked object // is stored to. const ExplodedNode* AllocNode = 0; const MemRegion* FirstBinding = 0; - + llvm::tie(AllocNode, FirstBinding) = GetAllocationSite(BRC.getStateManager(), EndN, Sym); - - // Get the allocate site. + + // Get the allocate site. assert(AllocNode); const Stmt* FirstStmt = cast(AllocNode->getLocation()).getStmt(); - + SourceManager& SMgr = BRC.getSourceManager(); unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart()); - + // Compute an actual location for the leak. Sometimes a leak doesn't // occur at an actual statement (e.g., transition between blocks; end // of function) so we need to walk the graph and compute a real location. const ExplodedNode* LeakN = EndN; PathDiagnosticLocation L; - + while (LeakN) { ProgramPoint P = LeakN->getLocation(); - + if (const PostStmt *PS = dyn_cast(&P)) { L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr); break; @@ -2636,26 +2636,26 @@ CFRefLeakReport::getEndPath(BugReporterContext& BRC, break; } } - + LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin()); } - + if (!L.isValid()) { const Decl &D = BRC.getCodeDecl(); L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr); } - + std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << "Object allocated on line " << AllocLine; - + if (FirstBinding) - os << " and stored into '" << FirstBinding->getString() << '\''; - + os << " and stored into '" << FirstBinding->getString() << '\''; + // Get the retain count. const RefVal* RV = EndN->getState()->get(Sym); - + if (RV->getKind() == RefVal::ErrorLeakReturned) { // FIXME: Per comments in rdar://6320065, "create" only applies to CF // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership @@ -2678,16 +2678,15 @@ CFRefLeakReport::getEndPath(BugReporterContext& BRC, else os << " is no longer referenced after this point and has a retain count of" " +" << RV->getCount() << " (object leaked)"; - + return new PathDiagnosticEventPiece(L, os.str()); } CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym, GRExprEngine& Eng) -: CFRefReport(D, tf, n, sym) -{ - +: CFRefReport(D, tf, n, sym) { + // Most bug reports are cached at the location where they occured. // With leaks, we want to unique them by the location where they were // allocated, and only report a single path. To do this, we need to find @@ -2697,14 +2696,14 @@ CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, // that all ancestor nodes that represent the allocation site have the // same SourceLocation. const ExplodedNode* AllocNode = 0; - + llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding. GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol()); - + // Get the SourceLocation for the allocation site. ProgramPoint P = AllocNode->getLocation(); AllocSite = cast(P).getStmt()->getLocStart(); - + // Fill in the description of the bug. Description.clear(); llvm::raw_string_ostream os(Description); @@ -2713,9 +2712,9 @@ CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, os << "Potential leak "; if (tf.isGCEnabled()) { os << "(when using garbage collection) "; - } + } os << "of an object allocated on line " << AllocLine; - + // FIXME: AllocBinding doesn't get populated for RegionStore yet. if (AllocBinding) os << " and stored into '" << AllocBinding->getString() << '\''; @@ -2737,16 +2736,16 @@ static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) { /// more specific than id. if (const ObjCMessageExpr *ME = dyn_cast(RetE)) if (const ObjCObjectPointerType *PT = RetTy->getAsObjCObjectPointerType()) - if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || + if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || PT->isObjCClassType()) { // At this point we know the return type of the message expression is // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this // is a call to a class method whose type we can resolve. In such // cases, promote the return type to XXX* (where XXX is the class). - const ObjCInterfaceDecl *D = ME->getClassInfo().first; + const ObjCInterfaceDecl *D = ME->getClassInfo().first; return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D)); } - + return RetTy; } @@ -2758,7 +2757,7 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, const RetainSummary& Summ, ExprIterator arg_beg, ExprIterator arg_end, ExplodedNode* Pred) { - + // Get the state. const GRState *state = Builder.GetState(Pred); @@ -2766,10 +2765,10 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, RefVal::Kind hasErr = (RefVal::Kind) 0; unsigned idx = 0; Expr* ErrorExpr = NULL; - SymbolRef ErrorSym = 0; - - for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) { - SVal V = state->getSValAsScalarOrLoc(*I); + SymbolRef ErrorSym = 0; + + for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) { + SVal V = state->getSValAsScalarOrLoc(*I); SymbolRef Sym = V.getAsLocSymbol(); if (Sym) @@ -2779,7 +2778,7 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, ErrorExpr = *I; ErrorSym = Sym; break; - } + } continue; } @@ -2787,14 +2786,14 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, if (loc::MemRegionVal* MR = dyn_cast(&V)) { if (Summ.getArg(idx) == DoNothingByRef) continue; - - // Invalidate the value of the variable passed by reference. - + + // Invalidate the value of the variable passed by reference. + // FIXME: We can have collisions on the conjured symbol if the // expression *I also creates conjured symbols. We probably want // to identify conjured symbols by an expression pair: the enclosing // expression (the context) and the expression itself. This should - // disambiguate conjured symbols. + // disambiguate conjured symbols. unsigned Count = Builder.getCurrentBlockCount(); StoreManager& StoreMgr = Eng.getStateManager().getStoreManager(); @@ -2825,9 +2824,9 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, // Is the invalidated variable something that we were tracking? SymbolRef Sym = state->getSValAsScalarOrLoc(R).getAsLocSymbol(); - + // Remove any existing reference-count binding. - if (Sym) + if (Sym) state = state->remove(Sym); state = StoreMgr.InvalidateRegion(state, R, *I, Count); @@ -2845,9 +2844,9 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, // We should bind it to UnknownVal explicitly. Otherwise default value // may be loaded. state = state->unbindLoc(cast(V).getLoc()); - } - - // Evaluate the effect on the message receiver. + } + + // Evaluate the effect on the message receiver. if (!ErrorExpr && Receiver) { SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol(); if (Sym) { @@ -2860,17 +2859,17 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, } } } - - // Process any errors. + + // Process any errors. if (hasErr) { ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state, hasErr, ErrorSym); return; } - - // Consult the summary for the return value. + + // Consult the summary for the return value. RetEffect RE = Summ.getRetEffect(); - + if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { assert(Receiver); SVal V = state->getSValAsScalarOrLoc(Receiver); @@ -2883,32 +2882,32 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, if (!found) RE = RetEffect::MakeNoRet(); - } - + } + switch (RE.getKind()) { default: assert (false && "Unhandled RetEffect."); break; - - case RetEffect::NoRet: { + + case RetEffect::NoRet: { // Make up a symbol for the return value (not reference counted). // FIXME: Most of this logic is not specific to the retain/release // checker. - + // FIXME: We eventually should handle structs and other compound types // that are returned by value. - + QualType T = Ex->getType(); - + if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count); state = state->BindExpr(Ex, X, false); - } - + } + break; } - + case RetEffect::Alias: { unsigned idx = RE.getIndex(); assert (arg_end >= arg_beg); @@ -2917,20 +2916,20 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, state = state->BindExpr(Ex, V, false); break; } - + case RetEffect::ReceiverAlias: { assert (Receiver); SVal V = state->getSValAsScalarOrLoc(Receiver); state = state->BindExpr(Ex, V, false); break; } - + case RetEffect::OwnedAllocatedSymbol: case RetEffect::OwnedSymbol: { unsigned Count = Builder.getCurrentBlockCount(); - ValueManager &ValMgr = Eng.getValueManager(); + ValueManager &ValMgr = Eng.getValueManager(); SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count); - QualType RetT = GetReturnType(Ex, ValMgr.getContext()); + QualType RetT = GetReturnType(Ex, ValMgr.getContext()); state = state->set(Sym, RefVal::makeOwned(RE.getObjKind(), RetT)); state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false); @@ -2941,31 +2940,31 @@ void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) { bool isFeasible; state = state.Assume(loc::SymbolVal(Sym), true, isFeasible); - assert(isFeasible && "Cannot assume fresh symbol is non-null."); + assert(isFeasible && "Cannot assume fresh symbol is non-null."); } #endif - + break; } - + case RetEffect::GCNotOwnedSymbol: case RetEffect::NotOwnedSymbol: { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count); - QualType RetT = GetReturnType(Ex, ValMgr.getContext()); + QualType RetT = GetReturnType(Ex, ValMgr.getContext()); state = state->set(Sym, RefVal::makeNotOwned(RE.getObjKind(), RetT)); state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false); break; } } - + // Generate a sink node if we are at the end of a path. ExplodedNode *NewNode = Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state) : Builder.MakeNode(Dst, Ex, Pred, state); - + // Annotate the edge with summary we used. if (NewNode) SummaryLog[NewNode] = &Summ; } @@ -2977,9 +2976,9 @@ void CFRefCount::EvalCall(ExplodedNodeSet& Dst, CallExpr* CE, SVal L, ExplodedNode* Pred) { const FunctionDecl* FD = L.getAsFunctionDecl(); - RetainSummary* Summ = !FD ? Summaries.getDefaultSummary() + RetainSummary* Summ = !FD ? Summaries.getDefaultSummary() : Summaries.getSummary(const_cast(FD)); - + assert(Summ); EvalSummary(Dst, Eng, Builder, CE, 0, *Summ, CE->arg_begin(), CE->arg_end(), Pred); @@ -2989,9 +2988,9 @@ void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, ObjCMessageExpr* ME, - ExplodedNode* Pred) { + ExplodedNode* Pred) { RetainSummary* Summ = 0; - + if (Expr* Receiver = ME->getReceiver()) { // We need the type-information of the tracked receiver object // Retrieve it from the state. @@ -3005,7 +3004,7 @@ void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst, SVal V = St->getSValAsScalarOrLoc(Receiver); SymbolRef Sym = V.getAsLocSymbol(); - + if (Sym) { if (const RefVal* T = St->get(Sym)) { if (const ObjCObjectPointerType* PT = @@ -3028,21 +3027,21 @@ void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst, // Special-case: are we sending a mesage to "self"? // This is a hack. When we have full-IP this should be removed. - if (isa(Pred->getLocationContext()->getDecl())) { + if (isa(Pred->getLocationContext()->getDecl())) { if (Expr* Receiver = ME->getReceiver()) { SVal X = St->getSValAsScalarOrLoc(Receiver); - if (loc::MemRegionVal* L = dyn_cast(&X)) { + if (loc::MemRegionVal* L = dyn_cast(&X)) { // Get the region associated with 'self'. - const LocationContext *LC = Pred->getLocationContext(); + const LocationContext *LC = Pred->getLocationContext(); if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl()) { - SVal SelfVal = St->getSVal(St->getRegion(SelfDecl, LC)); + SVal SelfVal = St->getSVal(St->getRegion(SelfDecl, LC)); if (L->getBaseRegion() == SelfVal.getAsRegion()) { // Update the summary to make the default argument effect // 'StopTracking'. Summ = Summaries.copySummary(Summ); Summ->setDefaultArgEffect(StopTracking); } - } + } } } } @@ -3070,18 +3069,18 @@ public: } }; } // end anonymous namespace - -void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) { - // Are we storing to something that causes the value to "escape"? + +void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) { + // Are we storing to something that causes the value to "escape"? bool escapes = false; - + // A value escapes in three possible cases (this may change): // // (1) we are binding to something that is not a memory region. // (2) we are binding to a memregion that does not have stack storage // (3) we are binding to a memregion with stack storage that the store - // does not understand. + // does not understand. const GRState *state = B.getState(); if (!isa(location)) @@ -3089,7 +3088,7 @@ void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) { else { const MemRegion* R = cast(location).getRegion(); escapes = !R->hasStackStorage(); - + if (!escapes) { // To test (3), generate a new state with the binding removed. If it is // the same state, then it escapes (since the store cannot represent @@ -3116,35 +3115,35 @@ void CFRefCount::EvalReturn(ExplodedNodeSet& Dst, GRStmtNodeBuilder& Builder, ReturnStmt* S, ExplodedNode* Pred) { - + Expr* RetE = S->getRetValue(); if (!RetE) return; - + const GRState *state = Builder.GetState(Pred); SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol(); - + if (!Sym) return; - + // Get the reference count binding (if any). const RefVal* T = state->get(Sym); - + if (!T) return; - - // Change the reference count. - RefVal X = *T; - - switch (X.getKind()) { - case RefVal::Owned: { + + // Change the reference count. + RefVal X = *T; + + switch (X.getKind()) { + case RefVal::Owned: { unsigned cnt = X.getCount(); assert (cnt > 0); X.setCount(cnt - 1); X = X ^ RefVal::ReturnedOwned; break; } - + case RefVal::NotOwned: { unsigned cnt = X.getCount(); if (cnt) { @@ -3156,39 +3155,39 @@ void CFRefCount::EvalReturn(ExplodedNodeSet& Dst, } break; } - - default: + + default: return; } - + // Update the binding. state = state->set(Sym, X); Pred = Builder.MakeNode(Dst, S, Pred, state); - + // Did we cache out? if (!Pred) return; - + // Update the autorelease counts. static unsigned autoreleasetag = 0; GenericNodeBuilder Bd(Builder, S, &autoreleasetag); bool stop = false; llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym, X, stop); - + // Did we cache out? if (!Pred || stop) return; - + // Get the updated binding. T = state->get(Sym); assert(T); X = *T; - + // Any leaks or other errors? if (X.isReturnedOwned() && X.getCount() == 0) { - const Decl *CD = Eng.getAnalysisManager().getCodeDecl(); - if (const ObjCMethodDecl* MD = dyn_cast(CD)) { + const Decl *CD = Eng.getAnalysisManager().getCodeDecl(); + if (const ObjCMethodDecl* MD = dyn_cast(CD)) { const RetainSummary &Summ = *Summaries.getMethodSummary(MD); RetEffect RE = Summ.getRetEffect(); bool hasError = false; @@ -3200,20 +3199,20 @@ void CFRefCount::EvalReturn(ExplodedNodeSet& Dst, // a leak (as the caller expects a GC'ed object) because no // method should return ownership unless it returns a CF object. X = X ^ RefVal::ErrorGCLeakReturned; - + // Keep this false until this is properly tested. hasError = true; } else if (!RE.isOwned()) { // Either we are using GC and the returned object is a CF type // or we aren't using GC. In either case, we expect that the - // enclosing method is expected to return ownership. + // enclosing method is expected to return ownership. hasError = true; X = X ^ RefVal::ErrorLeakReturned; } } - - if (hasError) { + + if (hasError) { // Generate an error node. static int ReturnOwnLeakTag = 0; state = state->set(Sym, X); @@ -3227,16 +3226,16 @@ void CFRefCount::EvalReturn(ExplodedNodeSet& Dst, BR->EmitReport(report); } } - } + } } else if (X.isReturnedNotOwned()) { - const Decl *CD = Eng.getAnalysisManager().getCodeDecl(); + const Decl *CD = Eng.getAnalysisManager().getCodeDecl(); if (const ObjCMethodDecl* MD = dyn_cast(CD)) { const RetainSummary &Summ = *Summaries.getMethodSummary(MD); if (Summ.getRetEffect().isOwned()) { // Trying to return a not owned object to a caller expecting an // owned object. - + static int ReturnNotOwnedForOwnedTag = 0; state = state->set(Sym, X ^ RefVal::ErrorReturnedNotOwned); if (ExplodedNode *N = @@ -3261,18 +3260,18 @@ const GRState* CFRefCount::EvalAssume(const GRState *state, // FIXME: We may add to the interface of EvalAssume the list of symbols // whose assumptions have changed. For now we just iterate through the // bindings and check if any of the tracked symbols are NULL. This isn't - // too bad since the number of symbols we will track in practice are + // too bad since the number of symbols we will track in practice are // probably small and EvalAssume is only called at branches and a few // other places. RefBindings B = state->get(); - + if (B.isEmpty()) return state; - - bool changed = false; + + bool changed = false; RefBindings::Factory& RefBFactory = state->get_context(); - for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { + for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { // Check if the symbol is null (or equal to any constant). // If this is the case, stop tracking the symbol. if (state->getSymVal(I.getKey())) { @@ -3280,10 +3279,10 @@ const GRState* CFRefCount::EvalAssume(const GRState *state, B = RefBFactory.Remove(B, I.getKey()); } } - + if (changed) state = state->set(B); - + return state; } @@ -3297,21 +3296,21 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break; case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break; case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break; - case NewAutoreleasePool: E = isGCEnabled() ? DoNothing : + case NewAutoreleasePool: E = isGCEnabled() ? DoNothing : NewAutoreleasePool; break; } - + // Handle all use-after-releases. if (!isGCEnabled() && V.getKind() == RefVal::Released) { V = V ^ RefVal::ErrorUseAfterRelease; hasErr = V.getKind(); return state->set(sym, V); - } - + } + switch (E) { default: assert (false && "Unhandled CFRef transition."); - + case Dealloc: // Any use of -dealloc in GC is *bad*. if (isGCEnabled()) { @@ -3319,7 +3318,7 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, hasErr = V.getKind(); break; } - + switch (V.getKind()) { default: assert(false && "Invalid case."); @@ -3332,13 +3331,13 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, V = V ^ RefVal::ErrorDeallocNotOwned; hasErr = V.getKind(); break; - } + } break; case NewAutoreleasePool: assert(!isGCEnabled()); return state->add(sym); - + case MayEscape: if (V.getKind() == RefVal::Owned) { V = V ^ RefVal::NotOwned; @@ -3346,7 +3345,7 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, } // Fall-through. - + case DoNothingByRef: case DoNothing: return state; @@ -3354,7 +3353,7 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, case Autorelease: if (isGCEnabled()) return state; - + // Update the autorelease counts. state = SendAutorelease(state, ARCountFactory, sym); V = V.autorelease(); @@ -3363,7 +3362,7 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, case StopTracking: return state->remove(sym); - case IncRef: + case IncRef: switch (V.getKind()) { default: assert(false); @@ -3371,15 +3370,15 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, case RefVal::Owned: case RefVal::NotOwned: V = V + 1; - break; + break; case RefVal::Released: // Non-GC cases are handled above. assert(isGCEnabled()); V = (V ^ RefVal::Owned) + 1; break; - } + } break; - + case SelfOwn: V = V ^ RefVal::NotOwned; // Fall-through. @@ -3394,23 +3393,23 @@ const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, if (V.getCount() == 1) V = V ^ RefVal::Released; V = V - 1; break; - + case RefVal::NotOwned: if (V.getCount() > 0) V = V - 1; else { V = V ^ RefVal::ErrorReleaseNotOwned; hasErr = V.getKind(); - } + } break; - + case RefVal::Released: // Non-GC cases are handled above. assert(isGCEnabled()); V = V ^ RefVal::ErrorUseAfterRelease; hasErr = V.getKind(); - break; - } + break; + } break; } return state->set(sym, V); @@ -3425,22 +3424,22 @@ CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd ExplodedNode* Pred, GRExprEngine &Eng, SymbolRef Sym, RefVal V, bool &stop) { - + unsigned ACnt = V.getAutoreleaseCount(); stop = false; // No autorelease counts? Nothing to be done. if (!ACnt) return std::make_pair(Pred, state); - - assert(!isGCEnabled() && "Autorelease counts in GC mode?"); + + assert(!isGCEnabled() && "Autorelease counts in GC mode?"); unsigned Cnt = V.getCount(); - + // FIXME: Handle sending 'autorelease' to already released object. if (V.getKind() == RefVal::ReturnedOwned) ++Cnt; - + if (ACnt <= Cnt) { if (ACnt == Cnt) { V.clearCounts(); @@ -3457,7 +3456,7 @@ CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd ExplodedNode *N = Bd.MakeNode(state, Pred); stop = (N == 0); return std::make_pair(N, state); - } + } // Woah! More autorelease counts then retain counts left. // Emit hard error. @@ -3467,7 +3466,7 @@ CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd if (ExplodedNode *N = Bd.MakeNode(state, Pred)) { N->markAsSink(); - + std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Object over-autoreleased: object was sent -autorelease"; @@ -3479,26 +3478,26 @@ CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd else os << "+" << V.getCount(); os << " retain counts"; - + CFRefReport *report = new CFRefReport(*static_cast(overAutorelease), *this, N, Sym, os.str().c_str()); BR->EmitReport(report); } - + return std::make_pair((ExplodedNode*)0, state); } const GRState * CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V, llvm::SmallVectorImpl &Leaked) { - - bool hasLeak = V.isOwned() || + + bool hasLeak = V.isOwned() || ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0); - + if (!hasLeak) return state->remove(sid); - + Leaked.push_back(sid); return state->set(sid, V ^ RefVal::ErrorLeak); } @@ -3509,49 +3508,49 @@ CFRefCount::ProcessLeaks(const GRState * state, GenericNodeBuilder &Builder, GRExprEngine& Eng, ExplodedNode *Pred) { - + if (Leaked.empty()) return Pred; - + // Generate an intermediate node representing the leak point. ExplodedNode *N = Builder.MakeNode(state, Pred); - + if (N) { for (llvm::SmallVectorImpl::iterator I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { - - CFRefBug *BT = static_cast(Pred ? leakWithinFunction + + CFRefBug *BT = static_cast(Pred ? leakWithinFunction : leakAtReturn); assert(BT && "BugType not initialized."); CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng); BR->EmitReport(report); } } - + return N; } void CFRefCount::EvalEndPath(GRExprEngine& Eng, GREndPathNodeBuilder& Builder) { - + const GRState *state = Builder.getState(); GenericNodeBuilder Bd(Builder); - RefBindings B = state->get(); + RefBindings B = state->get(); ExplodedNode *Pred = 0; for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { bool stop = false; llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng, (*I).first, - (*I).second, stop); + (*I).second, stop); if (stop) return; } - - B = state->get(); - llvm::SmallVector Leaked; - + + B = state->get(); + llvm::SmallVector Leaked; + for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked); @@ -3567,7 +3566,7 @@ void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst, SymbolReaper& SymReaper) { RefBindings B = state->get(); - + // Update counts from autorelease pools for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I != E; ++I) { @@ -3583,32 +3582,32 @@ void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst, return; } } - + B = state->get(); llvm::SmallVector Leaked; - + for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), - E = SymReaper.dead_end(); I != E; ++I) { + E = SymReaper.dead_end(); I != E; ++I) { if (const RefVal* T = B.lookup(*I)) state = HandleSymbolDeath(state, *I, *T, Leaked); - } - + } + static unsigned LeakPPTag = 0; { GenericNodeBuilder Bd(Builder, S, &LeakPPTag); Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred); } - + // Did we cache out? if (!Pred) return; - + // Now generate a new node that nukes the old bindings. RefBindings::Factory& F = state->get_context(); - + for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I); - + state = state->set(B); Builder.MakeNode(Dst, S, Pred, state); } @@ -3621,19 +3620,19 @@ void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst, RefVal::Kind hasErr, SymbolRef Sym) { Builder.BuildSinks = true; ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St); - + if (!N) return; - + CFRefBug *BT = 0; - + switch (hasErr) { default: assert(false && "Unhandled error."); return; case RefVal::ErrorUseAfterRelease: BT = static_cast(useAfterRelease); - break; + break; case RefVal::ErrorReleaseNotOwned: BT = static_cast(releaseNotOwned); break; @@ -3644,7 +3643,7 @@ void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst, BT = static_cast(deallocNotOwned); break; } - + CFRefReport *report = new CFRefReport(*BT, *this, N, Sym); report->addRange(ErrorExpr->getSourceRange()); BR->EmitReport(report); @@ -3657,4 +3656,4 @@ void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst, GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled, const LangOptions& lopts) { return new CFRefCount(Ctx, GCEnabled, lopts); -} +} diff --git a/clang/lib/Analysis/CallGraph.cpp b/clang/lib/Analysis/CallGraph.cpp index 1e28411eb4668ee06b05b96e4747e1e72297d1a0..fdca1dc2f44a5cde77a1dbb1dc555575bd663234 100644 --- a/clang/lib/Analysis/CallGraph.cpp +++ b/clang/lib/Analysis/CallGraph.cpp @@ -41,8 +41,8 @@ public: void VisitChildren(Stmt *S) { for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I != E;++I) - if (*I) - static_cast(this)->Visit(*I); + if (*I) + static_cast(this)->Visit(*I); } }; } @@ -53,7 +53,7 @@ void CGBuilder::VisitCallExpr(CallExpr *CE) { CallGraphNode *CalleeNode = G.getOrInsertFunction(Ent); Decl *Parent = ASTLocation::FindImmediateParent(FD, CE); - + CallerNode->addCallee(ASTLocation(Parent, CE), CalleeNode); } } @@ -92,7 +92,7 @@ void CallGraph::addTU(ASTUnit &AST) { // Set root node to 'main' function. if (FD->getNameAsString() == "main") Root = Node; - + CGBuilder builder(*this, FD, Ent, Node); builder.Visit(FD->getBody()); } @@ -118,9 +118,9 @@ Decl *CallGraph::getDecl(CallGraphNode *Node) { void CallGraph::print(llvm::raw_ostream &os) { for (iterator I = begin(), E = end(); I != E; ++I) { if (I->second->hasCallee()) { - os << "function: " << I->first.getPrintableName() + os << "function: " << I->first.getPrintableName() << " calls:\n"; - for (CallGraphNode::iterator CI = I->second->begin(), + for (CallGraphNode::iterator CI = I->second->begin(), CE = I->second->end(); CI != CE; ++CI) { os << " " << CI->second->getName().c_str(); } @@ -139,13 +139,13 @@ void CallGraph::ViewCallGraph() const { namespace llvm { -template <> +template <> struct DOTGraphTraits : public DefaultDOTGraphTraits { - static std::string getNodeLabel(const CallGraphNode *Node, + static std::string getNodeLabel(const CallGraphNode *Node, const CallGraph &CG, bool ShortNames) { return Node->getName(); - + } }; diff --git a/clang/lib/Analysis/CheckDeadStores.cpp b/clang/lib/Analysis/CheckDeadStores.cpp index 69433d6396a5b81fdcff37ee2288e0ad590329a0..716affb8468a85d2efc72890a6949d509d9d9895 100644 --- a/clang/lib/Analysis/CheckDeadStores.cpp +++ b/clang/lib/Analysis/CheckDeadStores.cpp @@ -33,14 +33,14 @@ class VISIBILITY_HIDDEN DeadStoreObs : public LiveVariables::ObserverTy { BugReporter& BR; ParentMap& Parents; llvm::SmallPtrSet Escaped; - + enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit }; - + public: DeadStoreObs(ASTContext &ctx, BugReporter& br, ParentMap& parents, llvm::SmallPtrSet &escaped) : Ctx(ctx), BR(br), Parents(parents), Escaped(escaped) {} - + virtual ~DeadStoreObs() {} void Report(VarDecl* V, DeadStoreKind dsk, SourceLocation L, SourceRange R) { @@ -48,27 +48,27 @@ public: return; std::string name = V->getNameAsString(); - + const char* BugType = 0; std::string msg; - + switch (dsk) { default: assert(false && "Impossible dead store type."); - + case DeadInit: BugType = "Dead initialization"; msg = "Value stored to '" + name + "' during its initialization is never read"; break; - + case DeadIncrement: BugType = "Dead increment"; case Standard: if (!BugType) BugType = "Dead assignment"; msg = "Value stored to '" + name + "' is never read"; break; - + case Enclosing: BugType = "Dead nested assignment"; msg = "Although the value stored to '" + name + @@ -76,10 +76,10 @@ public: " read from '" + name + "'"; break; } - - BR.EmitBasicReport(BugType, "Dead store", msg.c_str(), L, R); + + BR.EmitBasicReport(BugType, "Dead store", msg.c_str(), L, R); } - + void CheckVarDecl(VarDecl* VD, Expr* Ex, Expr* Val, DeadStoreKind dsk, const LiveVariables::AnalysisDataTy& AD, @@ -87,60 +87,60 @@ public: if (VD->hasLocalStorage() && !Live(VD, AD) && !VD->getAttr()) Report(VD, dsk, Ex->getSourceRange().getBegin(), - Val->getSourceRange()); + Val->getSourceRange()); } - + void CheckDeclRef(DeclRefExpr* DR, Expr* Val, DeadStoreKind dsk, const LiveVariables::AnalysisDataTy& AD, const LiveVariables::ValTy& Live) { - + if (VarDecl* VD = dyn_cast(DR->getDecl())) CheckVarDecl(VD, DR, Val, dsk, AD, Live); } - + bool isIncrement(VarDecl* VD, BinaryOperator* B) { if (B->isCompoundAssignmentOp()) return true; - + Expr* RHS = B->getRHS()->IgnoreParenCasts(); BinaryOperator* BRHS = dyn_cast(RHS); - + if (!BRHS) return false; - + DeclRefExpr *DR; - + if ((DR = dyn_cast(BRHS->getLHS()->IgnoreParenCasts()))) if (DR->getDecl() == VD) return true; - + if ((DR = dyn_cast(BRHS->getRHS()->IgnoreParenCasts()))) if (DR->getDecl() == VD) return true; - + return false; } - + virtual void ObserveStmt(Stmt* S, const LiveVariables::AnalysisDataTy& AD, const LiveVariables::ValTy& Live) { - + // Skip statements in macros. if (S->getLocStart().isMacroID()) return; - - if (BinaryOperator* B = dyn_cast(S)) { + + if (BinaryOperator* B = dyn_cast(S)) { if (!B->isAssignmentOp()) return; // Skip non-assignments. - + if (DeclRefExpr* DR = dyn_cast(B->getLHS())) if (VarDecl *VD = dyn_cast(DR->getDecl())) { Expr* RHS = B->getRHS()->IgnoreParenCasts(); - + // Special case: check for assigning null to a pointer. - // This is a common form of defensive programming. + // This is a common form of defensive programming. if (VD->getType()->isPointerType()) { if (IntegerLiteral* L = dyn_cast(RHS)) - // FIXME: Probably should have an Expr::isNullPointerConstant. + // FIXME: Probably should have an Expr::isNullPointerConstant. if (L->getValue() == 0) return; } @@ -149,19 +149,19 @@ public: if (DeclRefExpr* RhsDR = dyn_cast(RHS)) if (VD == dyn_cast(RhsDR->getDecl())) return; - + // Otherwise, issue a warning. DeadStoreKind dsk = Parents.isConsumedExpr(B) - ? Enclosing + ? Enclosing : (isIncrement(VD,B) ? DeadIncrement : Standard); - + CheckVarDecl(VD, DR, B->getRHS(), dsk, AD, Live); - } + } } else if (UnaryOperator* U = dyn_cast(S)) { if (!U->isIncrementOp()) return; - + // Handle: ++x within a subexpression. The solution is not warn // about preincrements to dead variables when the preincrement occurs // as a subexpression. This can lead to false negatives, e.g. "(++x);" @@ -170,21 +170,21 @@ public: return; Expr *Ex = U->getSubExpr()->IgnoreParenCasts(); - + if (DeclRefExpr* DR = dyn_cast(Ex)) CheckDeclRef(DR, U, DeadIncrement, AD, Live); - } + } else if (DeclStmt* DS = dyn_cast(S)) // Iterate through the decls. Warn if any initializers are complex // expressions that are not live (never used). for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); DI != DE; ++DI) { - + VarDecl* V = dyn_cast(*DI); if (!V) continue; - + if (V->hasLocalStorage()) if (Expr* E = V->getInit()) { // A dead initialization is a variable that is dead after it @@ -200,7 +200,7 @@ public: // due to defensive programming. if (E->isConstantInitializer(Ctx)) return; - + // Special case: check for initializations from constant // variables. // @@ -211,14 +211,14 @@ public: if (VarDecl *VD = dyn_cast(DRE->getDecl())) if (VD->hasGlobalStorage() && VD->getType().isConstQualified()) return; - + Report(V, DeadInit, V->getLocation(), E->getSourceRange()); } } } } }; - + } // end anonymous namespace //===----------------------------------------------------------------------===// @@ -230,9 +230,9 @@ class VISIBILITY_HIDDEN FindEscaped : public CFGRecStmtDeclVisitor{ CFG *cfg; public: FindEscaped(CFG *c) : cfg(c) {} - + CFG& getCFG() { return *cfg; } - + llvm::SmallPtrSet Escaped; void VisitUnaryOperator(UnaryOperator* U) { @@ -249,11 +249,11 @@ public: } }; } // end anonymous namespace - + void clang::CheckDeadStores(LiveVariables& L, BugReporter& BR) { FindEscaped FS(BR.getCFG()); - FS.getCFG().VisitBlockStmts(FS); + FS.getCFG().VisitBlockStmts(FS); DeadStoreObs A(BR.getContext(), BR, BR.getParentMap(), FS.Escaped); L.runOnAllBlocks(*BR.getCFG(), &A); } diff --git a/clang/lib/Analysis/CheckNSError.cpp b/clang/lib/Analysis/CheckNSError.cpp index 0b9ae04ecefb3ce4291719eb281cc350fa999d71..7e596435d00d09febf2187d2ce6e9029eb3744fa 100644 --- a/clang/lib/Analysis/CheckNSError.cpp +++ b/clang/lib/Analysis/CheckNSError.cpp @@ -32,37 +32,37 @@ class VISIBILITY_HIDDEN NSErrorCheck : public BugType { const bool isNSErrorWarning; IdentifierInfo * const II; GRExprEngine &Eng; - + void CheckSignature(const ObjCMethodDecl& MD, QualType& ResultTy, llvm::SmallVectorImpl& ErrorParams); - + void CheckSignature(const FunctionDecl& MD, QualType& ResultTy, llvm::SmallVectorImpl& ErrorParams); bool CheckNSErrorArgument(QualType ArgTy); bool CheckCFErrorArgument(QualType ArgTy); - + void CheckParamDeref(const VarDecl *V, const LocationContext *LC, const GRState *state, BugReporter& BR); - + void EmitRetTyWarning(BugReporter& BR, const Decl& CodeDecl); - + public: NSErrorCheck(const Decl &D, bool isNSError, GRExprEngine& eng) - : BugType(isNSError ? "NSError** null dereference" + : BugType(isNSError ? "NSError** null dereference" : "CFErrorRef* null dereference", "Coding conventions (Apple)"), CodeDecl(D), - isNSErrorWarning(isNSError), + isNSErrorWarning(isNSError), II(&eng.getContext().Idents.get(isNSErrorWarning ? "NSError":"CFErrorRef")), Eng(eng) {} - + void FlushReports(BugReporter& BR); -}; - +}; + } // end anonymous namespace -void clang::RegisterNSErrorChecks(BugReporter& BR, GRExprEngine &Eng, +void clang::RegisterNSErrorChecks(BugReporter& BR, GRExprEngine &Eng, const Decl &D) { BR.Register(new NSErrorCheck(D, true, Eng)); BR.Register(new NSErrorCheck(D, false, Eng)); @@ -71,7 +71,7 @@ void clang::RegisterNSErrorChecks(BugReporter& BR, GRExprEngine &Eng, void NSErrorCheck::FlushReports(BugReporter& BR) { // Get the analysis engine and the exploded analysis graph. ExplodedGraph& G = Eng.getGraph(); - + // Get the ASTContext, which is useful for querying type information. ASTContext &Ctx = BR.getContext(); @@ -84,17 +84,17 @@ void NSErrorCheck::FlushReports(BugReporter& BR) { CheckSignature(*FD, ResultTy, ErrorParams); else return; - + if (ErrorParams.empty()) return; - + if (ResultTy == Ctx.VoidTy) EmitRetTyWarning(BR, CodeDecl); - - for (ExplodedGraph::roots_iterator RI=G.roots_begin(), RE=G.roots_end(); + + for (ExplodedGraph::roots_iterator RI=G.roots_begin(), RE=G.roots_end(); RI!=RE; ++RI) { // Scan the parameters for an implicit null dereference. for (llvm::SmallVectorImpl::iterator I=ErrorParams.begin(), - E=ErrorParams.end(); I!=E; ++I) + E=ErrorParams.end(); I!=E; ++I) CheckParamDeref(*I, (*RI)->getLocationContext(), (*RI)->getState(), BR); } } @@ -102,17 +102,17 @@ void NSErrorCheck::FlushReports(BugReporter& BR) { void NSErrorCheck::EmitRetTyWarning(BugReporter& BR, const Decl& CodeDecl) { std::string sbuf; llvm::raw_string_ostream os(sbuf); - + if (isa(CodeDecl)) os << "Method"; else - os << "Function"; - + os << "Function"; + os << " accepting "; os << (isNSErrorWarning ? "NSError**" : "CFErrorRef*"); os << " should have a non-void return value to indicate whether or not an " "error occurred"; - + BR.EmitBasicReport(isNSErrorWarning ? "Bad return type when passing NSError**" : "Bad return type when passing CFError*", @@ -125,11 +125,11 @@ NSErrorCheck::CheckSignature(const ObjCMethodDecl& M, QualType& ResultTy, llvm::SmallVectorImpl& ErrorParams) { ResultTy = M.getResultType(); - - for (ObjCMethodDecl::param_iterator I=M.param_begin(), + + for (ObjCMethodDecl::param_iterator I=M.param_begin(), E=M.param_end(); I!=E; ++I) { - QualType T = (*I)->getType(); + QualType T = (*I)->getType(); if (isNSErrorWarning) { if (CheckNSErrorArgument(T)) ErrorParams.push_back(*I); @@ -142,14 +142,14 @@ NSErrorCheck::CheckSignature(const ObjCMethodDecl& M, QualType& ResultTy, void NSErrorCheck::CheckSignature(const FunctionDecl& F, QualType& ResultTy, llvm::SmallVectorImpl& ErrorParams) { - + ResultTy = F.getResultType(); - - for (FunctionDecl::param_const_iterator I = F.param_begin(), + + for (FunctionDecl::param_const_iterator I = F.param_begin(), E = F.param_end(); I != E; ++I) { - - QualType T = (*I)->getType(); - + + QualType T = (*I)->getType(); + if (isNSErrorWarning) { if (CheckNSErrorArgument(T)) ErrorParams.push_back(*I); } @@ -160,31 +160,31 @@ NSErrorCheck::CheckSignature(const FunctionDecl& F, QualType& ResultTy, bool NSErrorCheck::CheckNSErrorArgument(QualType ArgTy) { - + const PointerType* PPT = ArgTy->getAs(); if (!PPT) return false; - + const ObjCObjectPointerType* PT = PPT->getPointeeType()->getAsObjCObjectPointerType(); if (!PT) return false; - + const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); - + // FIXME: Can ID ever be NULL? if (ID) return II == ID->getIdentifier(); - + return false; } bool NSErrorCheck::CheckCFErrorArgument(QualType ArgTy) { - + const PointerType* PPT = ArgTy->getAs(); if (!PPT) return false; - + const TypedefType* TT = PPT->getPointeeType()->getAsTypedefType(); if (!TT) return false; @@ -195,24 +195,24 @@ void NSErrorCheck::CheckParamDeref(const VarDecl *Param, const LocationContext *LC, const GRState *rootState, BugReporter& BR) { - + SVal ParamL = rootState->getLValue(Param, LC); const MemRegion* ParamR = cast(ParamL).getRegionAs(); assert (ParamR && "Parameters always have VarRegions."); SVal ParamSVal = rootState->getSVal(ParamR); - + // FIXME: For now assume that ParamSVal is symbolic. We need to generalize // this later. SymbolRef ParamSym = ParamSVal.getAsLocSymbol(); if (!ParamSym) return; - + // Iterate over the implicit-null dereferences. for (GRExprEngine::null_deref_iterator I=Eng.implicit_null_derefs_begin(), E=Eng.implicit_null_derefs_end(); I!=E; ++I) { - + const GRState *state = (*I)->getState(); - const SVal* X = state->get(); + const SVal* X = state->get(); if (!X || X->getAsSymbol() != ParamSym) continue; @@ -221,14 +221,14 @@ void NSErrorCheck::CheckParamDeref(const VarDecl *Param, std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Potential null dereference. According to coding standards "; - + if (isNSErrorWarning) os << "in 'Creating and Returning NSError Objects' the parameter '"; else os << "documented in CoreFoundation/CFError.h the parameter '"; - + os << Param->getNameAsString() << "' may be null."; - + BugReport *report = new BugReport(*this, os.str().c_str(), *I); // FIXME: Notable symbols are now part of the report. We should // add support for notable symbols in BugReport. diff --git a/clang/lib/Analysis/CheckObjCDealloc.cpp b/clang/lib/Analysis/CheckObjCDealloc.cpp index 3392fcfdc3add12f5f1cee361f6fa3e10629afb0..d89edff2de8839cd5dbb04432c0e70d0cfa5dd1f 100644 --- a/clang/lib/Analysis/CheckObjCDealloc.cpp +++ b/clang/lib/Analysis/CheckObjCDealloc.cpp @@ -24,11 +24,11 @@ using namespace clang; -static bool scan_dealloc(Stmt* S, Selector Dealloc) { - +static bool scan_dealloc(Stmt* S, Selector Dealloc) { + if (ObjCMessageExpr* ME = dyn_cast(S)) if (ME->getSelector() == Dealloc) - if(ME->getReceiver()) + if (ME->getReceiver()) if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts()) return isa(Receiver); @@ -37,20 +37,20 @@ static bool scan_dealloc(Stmt* S, Selector Dealloc) { for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I) if (*I && scan_dealloc(*I, Dealloc)) return true; - + return false; } -static bool scan_ivar_release(Stmt* S, ObjCIvarDecl* ID, - const ObjCPropertyDecl* PD, - Selector Release, +static bool scan_ivar_release(Stmt* S, ObjCIvarDecl* ID, + const ObjCPropertyDecl* PD, + Selector Release, IdentifierInfo* SelfII, - ASTContext& Ctx) { - + ASTContext& Ctx) { + // [mMyIvar release] if (ObjCMessageExpr* ME = dyn_cast(S)) if (ME->getSelector() == Release) - if(ME->getReceiver()) + if (ME->getReceiver()) if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts()) if (ObjCIvarRefExpr* E = dyn_cast(Receiver)) if (E->getDecl() == ID) @@ -58,7 +58,7 @@ static bool scan_ivar_release(Stmt* S, ObjCIvarDecl* ID, // [self setMyIvar:nil]; if (ObjCMessageExpr* ME = dyn_cast(S)) - if(ME->getReceiver()) + if (ME->getReceiver()) if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts()) if (DeclRefExpr* E = dyn_cast(Receiver)) if (E->getDecl()->getIdentifier() == SelfII) @@ -66,19 +66,19 @@ static bool scan_ivar_release(Stmt* S, ObjCIvarDecl* ID, ME->getNumArgs() == 1 && ME->getArg(0)->isNullPointerConstant(Ctx)) return true; - + // self.myIvar = nil; if (BinaryOperator* BO = dyn_cast(S)) if (BO->isAssignmentOp()) - if(ObjCPropertyRefExpr* PRE = + if (ObjCPropertyRefExpr* PRE = dyn_cast(BO->getLHS()->IgnoreParenCasts())) - if(PRE->getProperty() == PD) - if(BO->getRHS()->isNullPointerConstant(Ctx)) { + if (PRE->getProperty() == PD) + if (BO->getRHS()->isNullPointerConstant(Ctx)) { // This is only a 'release' if the property kind is not // 'assign'. return PD->getSetterKind() != ObjCPropertyDecl::Assign;; } - + // Recurse to children. for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I) if (*I && scan_ivar_release(*I, ID, PD, Release, SelfII, Ctx)) @@ -91,39 +91,39 @@ void clang::CheckObjCDealloc(const ObjCImplementationDecl* D, const LangOptions& LOpts, BugReporter& BR) { assert (LOpts.getGCMode() != LangOptions::GCOnly); - + ASTContext& Ctx = BR.getContext(); const ObjCInterfaceDecl* ID = D->getClassInterface(); - + // Does the class contain any ivars that are pointers (or id<...>)? // If not, skip the check entirely. // NOTE: This is motivated by PR 2517: // http://llvm.org/bugs/show_bug.cgi?id=2517 - + bool containsPointerIvar = false; - + for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end(); I!=E; ++I) { - + ObjCIvarDecl* ID = *I; QualType T = ID->getType(); - + if (!T->isObjCObjectPointerType() || ID->getAttr()) // Skip IBOutlets. continue; - + containsPointerIvar = true; break; } - + if (!containsPointerIvar) return; - + // Determine if the class subclasses NSObject. IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject"); IdentifierInfo* SenTestCaseII = &Ctx.Idents.get("SenTestCase"); - + for ( ; ID ; ID = ID->getSuperClass()) { IdentifierInfo *II = ID->getIdentifier(); @@ -137,118 +137,118 @@ void clang::CheckObjCDealloc(const ObjCImplementationDecl* D, if (II == SenTestCaseII) return; } - + if (!ID) return; - + // Get the "dealloc" selector. IdentifierInfo* II = &Ctx.Idents.get("dealloc"); - Selector S = Ctx.Selectors.getSelector(0, &II); + Selector S = Ctx.Selectors.getSelector(0, &II); ObjCMethodDecl* MD = 0; - + // Scan the instance methods for "dealloc". for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(), E = D->instmeth_end(); I!=E; ++I) { - + if ((*I)->getSelector() == S) { MD = *I; break; - } + } } - + if (!MD) { // No dealloc found. - - const char* name = LOpts.getGCMode() == LangOptions::NonGC - ? "missing -dealloc" + + const char* name = LOpts.getGCMode() == LangOptions::NonGC + ? "missing -dealloc" : "missing -dealloc (Hybrid MM, non-GC)"; - + std::string buf; llvm::raw_string_ostream os(buf); os << "Objective-C class '" << D->getNameAsString() << "' lacks a 'dealloc' instance method"; - + BR.EmitBasicReport(name, os.str().c_str(), D->getLocStart()); return; } - + // dealloc found. Scan for missing [super dealloc]. if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) { - + const char* name = LOpts.getGCMode() == LangOptions::NonGC ? "missing [super dealloc]" : "missing [super dealloc] (Hybrid MM, non-GC)"; - + std::string buf; llvm::raw_string_ostream os(buf); os << "The 'dealloc' instance method in Objective-C class '" << D->getNameAsString() << "' does not send a 'dealloc' message to its super class" " (missing [super dealloc])"; - + BR.EmitBasicReport(name, os.str().c_str(), D->getLocStart()); return; - } - + } + // Get the "release" selector. IdentifierInfo* RII = &Ctx.Idents.get("release"); - Selector RS = Ctx.Selectors.getSelector(0, &RII); - + Selector RS = Ctx.Selectors.getSelector(0, &RII); + // Get the "self" identifier IdentifierInfo* SelfII = &Ctx.Idents.get("self"); - + // Scan for missing and extra releases of ivars used by implementations // of synthesized properties for (ObjCImplementationDecl::propimpl_iterator I = D->propimpl_begin(), E = D->propimpl_end(); I!=E; ++I) { // We can only check the synthesized properties - if((*I)->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize) + if ((*I)->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize) continue; - + ObjCIvarDecl* ID = (*I)->getPropertyIvarDecl(); if (!ID) continue; - + QualType T = ID->getType(); if (!T->isObjCObjectPointerType()) // Skip non-pointer ivars continue; const ObjCPropertyDecl* PD = (*I)->getPropertyDecl(); - if(!PD) + if (!PD) continue; - + // ivars cannot be set via read-only properties, so we'll skip them - if(PD->isReadOnly()) + if (PD->isReadOnly()) continue; - + // ivar must be released if and only if the kind of setter was not 'assign' bool requiresRelease = PD->getSetterKind() != ObjCPropertyDecl::Assign; - if(scan_ivar_release(MD->getBody(), ID, PD, RS, SelfII, Ctx) + if (scan_ivar_release(MD->getBody(), ID, PD, RS, SelfII, Ctx) != requiresRelease) { const char *name; const char* category = "Memory (Core Foundation/Objective-C)"; - + std::string buf; llvm::raw_string_ostream os(buf); - if(requiresRelease) { + if (requiresRelease) { name = LOpts.getGCMode() == LangOptions::NonGC ? "missing ivar release (leak)" : "missing ivar release (Hybrid MM, non-GC)"; - + os << "The '" << ID->getNameAsString() << "' instance variable was retained by a synthesized property but " - "wasn't released in 'dealloc'"; + "wasn't released in 'dealloc'"; } else { name = LOpts.getGCMode() == LangOptions::NonGC ? "extra ivar release (use-after-release)" : "extra ivar release (Hybrid MM, non-GC)"; - + os << "The '" << ID->getNameAsString() << "' instance variable was not retained by a synthesized property " "but was released in 'dealloc'"; } - + BR.EmitBasicReport(name, category, os.str().c_str(), (*I)->getLocation()); } diff --git a/clang/lib/Analysis/CheckObjCInstMethSignature.cpp b/clang/lib/Analysis/CheckObjCInstMethSignature.cpp index aae1e1da3b83bfbbb4e9973980aeda0062f0b57e..8c0d39629d50341a499540a3f221da322769e145 100644 --- a/clang/lib/Analysis/CheckObjCInstMethSignature.cpp +++ b/clang/lib/Analysis/CheckObjCInstMethSignature.cpp @@ -40,14 +40,14 @@ static void CompareReturnTypes(const ObjCMethodDecl *MethDerived, const ObjCMethodDecl *MethAncestor, BugReporter &BR, ASTContext &Ctx, const ObjCImplementationDecl *ID) { - + QualType ResDerived = MethDerived->getResultType(); - QualType ResAncestor = MethAncestor->getResultType(); - + QualType ResAncestor = MethAncestor->getResultType(); + if (!AreTypesCompatible(ResDerived, ResAncestor, Ctx)) { std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << "The Objective-C class '" << MethDerived->getClassInterface()->getNameAsString() << "', which is derived from class '" @@ -63,7 +63,7 @@ static void CompareReturnTypes(const ObjCMethodDecl *MethDerived, << ResAncestor.getAsString() << "'. These two types are incompatible, and may result in undefined " "behavior for clients of these classes."; - + BR.EmitBasicReport("Incompatible instance method return type", os.str().c_str(), MethDerived->getLocStart()); } @@ -71,23 +71,23 @@ static void CompareReturnTypes(const ObjCMethodDecl *MethDerived, void clang::CheckObjCInstMethSignature(const ObjCImplementationDecl* ID, BugReporter& BR) { - + const ObjCInterfaceDecl* D = ID->getClassInterface(); const ObjCInterfaceDecl* C = D->getSuperClass(); if (!C) return; - + ASTContext& Ctx = BR.getContext(); - + // Build a DenseMap of the methods for quick querying. typedef llvm::DenseMap MapTy; MapTy IMeths; unsigned NumMethods = 0; - + for (ObjCImplementationDecl::instmeth_iterator I=ID->instmeth_begin(), - E=ID->instmeth_end(); I!=E; ++I) { - + E=ID->instmeth_end(); I!=E; ++I) { + ObjCMethodDecl* M = *I; IMeths[M->getSelector()] = M; ++NumMethods; @@ -101,19 +101,19 @@ void clang::CheckObjCInstMethSignature(const ObjCImplementationDecl* ID, ObjCMethodDecl* M = *I; Selector S = M->getSelector(); - + MapTy::iterator MI = IMeths.find(S); if (MI == IMeths.end() || MI->second == 0) continue; - + --NumMethods; ObjCMethodDecl* MethDerived = MI->second; MI->second = 0; - + CompareReturnTypes(MethDerived, M, BR, Ctx, ID); } - + C = C->getSuperClass(); } } diff --git a/clang/lib/Analysis/CheckObjCUnusedIVars.cpp b/clang/lib/Analysis/CheckObjCUnusedIVars.cpp index 75470972f3bb1a39a08502759e2198aac47e53bf..1a900f8976783ac68b4122ace5f277f82df8377f 100644 --- a/clang/lib/Analysis/CheckObjCUnusedIVars.cpp +++ b/clang/lib/Analysis/CheckObjCUnusedIVars.cpp @@ -29,7 +29,7 @@ typedef llvm::DenseMap IvarUsageMap; static void Scan(IvarUsageMap& M, const Stmt* S) { if (!S) return; - + if (const ObjCIvarRefExpr *Ex = dyn_cast(S)) { const ObjCIvarDecl *D = Ex->getDecl(); IvarUsageMap::iterator I = M.find(D); @@ -37,7 +37,7 @@ static void Scan(IvarUsageMap& M, const Stmt* S) { I->second = Used; return; } - + // Blocks can reference an instance variable of a class. if (const BlockExpr *BE = dyn_cast(S)) { Scan(M, BE->getBody()); @@ -51,12 +51,12 @@ static void Scan(IvarUsageMap& M, const Stmt* S) { static void Scan(IvarUsageMap& M, const ObjCPropertyImplDecl* D) { if (!D) return; - + const ObjCIvarDecl* ID = D->getPropertyIvarDecl(); if (!ID) return; - + IvarUsageMap::iterator I = M.find(ID); if (I != M.end()) I->second = Used; @@ -71,9 +71,9 @@ void clang::CheckObjCUnusedIvar(const ObjCImplementationDecl *D, // Iterate over the ivars. for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end(); I!=E; ++I) { - + const ObjCIvarDecl* ID = *I; - + // Ignore ivars that aren't private. if (ID->getAccessControl() != ObjCIvarDecl::Private) continue; @@ -81,31 +81,31 @@ void clang::CheckObjCUnusedIvar(const ObjCImplementationDecl *D, // Skip IB Outlets. if (ID->getAttr()) continue; - + M[ID] = Unused; } if (M.empty()) return; - + // Now scan the methods for accesses. for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(), E = D->instmeth_end(); I!=E; ++I) Scan(M, (*I)->getBody()); - + // Scan for @synthesized property methods that act as setters/getters // to an ivar. for (ObjCImplementationDecl::propimpl_iterator I = D->propimpl_begin(), E = D->propimpl_end(); I!=E; ++I) - Scan(M, *I); - + Scan(M, *I); + // Find ivars that are unused. for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I) if (I->second == Unused) { std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Instance variable '" << I->first->getNameAsString() - << "' in class '" << ID->getNameAsString() + << "' in class '" << ID->getNameAsString() << "' is never used by the methods in its @implementation " "(although it may be used by category methods)."; diff --git a/clang/lib/Analysis/CheckSecuritySyntaxOnly.cpp b/clang/lib/Analysis/CheckSecuritySyntaxOnly.cpp index 1bed9d1a5b87cc0ab0e60e36db6ffac51b9f0a65..9f0d059cb66e9533509556a25935a168fa0df344 100644 --- a/clang/lib/Analysis/CheckSecuritySyntaxOnly.cpp +++ b/clang/lib/Analysis/CheckSecuritySyntaxOnly.cpp @@ -21,18 +21,18 @@ using namespace clang; namespace { class VISIBILITY_HIDDEN WalkAST : public StmtVisitor { - BugReporter &BR; + BugReporter &BR; IdentifierInfo *II_gets; enum { num_rands = 9 }; IdentifierInfo *II_rand[num_rands]; IdentifierInfo *II_random; enum { num_setids = 6 }; IdentifierInfo *II_setid[num_setids]; - + public: WalkAST(BugReporter &br) : BR(br), II_gets(0), II_rand(), II_random(0), II_setid() {} - + // Statement visitor methods. void VisitCallExpr(CallExpr *CE); void VisitForStmt(ForStmt *S); @@ -40,10 +40,10 @@ public: void VisitStmt(Stmt *S) { VisitChildren(S); } void VisitChildren(Stmt *S); - + // Helpers. IdentifierInfo *GetIdentifier(IdentifierInfo *& II, const char *str); - + // Checker-specific methods. void CheckLoopConditionForFloat(const ForStmt *FS); void CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD); @@ -60,8 +60,8 @@ public: IdentifierInfo *WalkAST::GetIdentifier(IdentifierInfo *& II, const char *str) { if (!II) II = &BR.getContext().Idents.get(str); - - return II; + + return II; } //===----------------------------------------------------------------------===// @@ -80,23 +80,22 @@ void WalkAST::VisitCallExpr(CallExpr *CE) { CheckCall_rand(CE, FD); CheckCall_random(CE, FD); } - + // Recurse and check children. VisitChildren(CE); } void WalkAST::VisitCompoundStmt(CompoundStmt *S) { for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) - if (Stmt *child = *I) - { - if (CallExpr *CE = dyn_cast(child)) - CheckUncheckedReturnValue(CE); - Visit(child); - } + if (Stmt *child = *I) { + if (CallExpr *CE = dyn_cast(child)) + CheckUncheckedReturnValue(CE); + Visit(child); + } } void WalkAST::VisitForStmt(ForStmt *FS) { - CheckLoopConditionForFloat(FS); + CheckLoopConditionForFloat(FS); // Recurse and check children. VisitChildren(FS); @@ -111,26 +110,26 @@ void WalkAST::VisitForStmt(ForStmt *FS) { static const DeclRefExpr* GetIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) { expr = expr->IgnoreParenCasts(); - - if (const BinaryOperator *B = dyn_cast(expr)) { + + if (const BinaryOperator *B = dyn_cast(expr)) { if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() || B->getOpcode() == BinaryOperator::Comma)) return NULL; - + if (const DeclRefExpr *lhs = GetIncrementedVar(B->getLHS(), x, y)) return lhs; - + if (const DeclRefExpr *rhs = GetIncrementedVar(B->getRHS(), x, y)) return rhs; - + return NULL; } - + if (const DeclRefExpr *DR = dyn_cast(expr)) { const NamedDecl *ND = DR->getDecl(); return ND == x || ND == y ? DR : NULL; } - + if (const UnaryOperator *U = dyn_cast(expr)) return U->isIncrementDecrementOp() ? GetIncrementedVar(U->getSubExpr(), x, y) : NULL; @@ -145,68 +144,68 @@ GetIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) { void WalkAST::CheckLoopConditionForFloat(const ForStmt *FS) { // Does the loop have a condition? const Expr *condition = FS->getCond(); - + if (!condition) return; // Does the loop have an increment? const Expr *increment = FS->getInc(); - + if (!increment) return; - + // Strip away '()' and casts. condition = condition->IgnoreParenCasts(); increment = increment->IgnoreParenCasts(); - + // Is the loop condition a comparison? const BinaryOperator *B = dyn_cast(condition); if (!B) return; - + // Is this a comparison? if (!(B->isRelationalOp() || B->isEqualityOp())) return; - + // Are we comparing variables? const DeclRefExpr *drLHS = dyn_cast(B->getLHS()->IgnoreParens()); const DeclRefExpr *drRHS = dyn_cast(B->getRHS()->IgnoreParens()); - + // Does at least one of the variables have a floating point type? drLHS = drLHS && drLHS->getType()->isFloatingType() ? drLHS : NULL; drRHS = drRHS && drRHS->getType()->isFloatingType() ? drRHS : NULL; - + if (!drLHS && !drRHS) return; const VarDecl *vdLHS = drLHS ? dyn_cast(drLHS->getDecl()) : NULL; const VarDecl *vdRHS = drRHS ? dyn_cast(drRHS->getDecl()) : NULL; - + if (!vdLHS && !vdRHS) - return; - + return; + // Does either variable appear in increment? const DeclRefExpr *drInc = GetIncrementedVar(increment, vdLHS, vdRHS); - + if (!drInc) return; - + // Emit the error. First figure out which DeclRefExpr in the condition // referenced the compared variable. const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS; - llvm::SmallVector ranges; + llvm::SmallVector ranges; std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << "Variable '" << drCond->getDecl()->getNameAsCString() << "' with floating point type '" << drCond->getType().getAsString() << "' should not be used as a loop counter"; ranges.push_back(drCond->getSourceRange()); ranges.push_back(drInc->getSourceRange()); - + const char *bugType = "Floating point variable used as loop counter"; BR.EmitBasicReport(bugType, "Security", os.str().c_str(), FS->getLocStart(), ranges.data(), ranges.size()); @@ -221,11 +220,11 @@ void WalkAST::CheckLoopConditionForFloat(const ForStmt *FS) { void WalkAST::CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD) { if (FD->getIdentifier() != GetIdentifier(II_gets, "gets")) return; - + const FunctionProtoType *FTP = dyn_cast(FD->getType()); if (!FTP) return; - + // Verify that the function takes a single argument. if (FTP->getNumArgs() != 1) return; @@ -234,10 +233,10 @@ void WalkAST::CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD) { const PointerType *PT = dyn_cast(FTP->getArgType(0)); if (!PT) return; - + if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy) return; - + // Issue a warning. SourceRange R = CE->getCallee()->getSourceRange(); BR.EmitBasicReport("Potential buffer overflow in call to 'gets'", @@ -261,11 +260,11 @@ void WalkAST::CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD) { "lcong48", "rand", "rand_r" }; - + for (size_t i = 0; i < num_rands; i++) - II_rand[i] = &BR.getContext().Idents.get(identifiers[i]); + II_rand[i] = &BR.getContext().Idents.get(identifiers[i]); } - + const IdentifierInfo *id = FD->getIdentifier(); size_t identifierid; @@ -275,24 +274,24 @@ void WalkAST::CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD) { if (identifierid >= num_rands) return; - + const FunctionProtoType *FTP = dyn_cast(FD->getType()); if (!FTP) return; - + if (FTP->getNumArgs() == 1) { // Is the argument an 'unsigned short *'? // (Actually any integer type is allowed.) const PointerType *PT = dyn_cast(FTP->getArgType(0)); if (!PT) return; - + if (! PT->getPointeeType()->isIntegerType()) return; } - else if (FTP->getNumArgs() != 0) + else if (FTP->getNumArgs() != 0) return; - + // Issue a warning. std::string buf1; llvm::raw_string_ostream os1(buf1); @@ -305,7 +304,7 @@ void WalkAST::CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD) { << " Use 'arc4random' instead"; SourceRange R = CE->getCallee()->getSourceRange(); - + BR.EmitBasicReport(os1.str().c_str(), "Security", os2.str().c_str(), CE->getLocStart(), &R, 1); } @@ -318,15 +317,15 @@ void WalkAST::CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD) { void WalkAST::CheckCall_random(const CallExpr *CE, const FunctionDecl *FD) { if (FD->getIdentifier() != GetIdentifier(II_random, "random")) return; - + const FunctionProtoType *FTP = dyn_cast(FD->getType()); if (!FTP) return; - + // Verify that the function takes no argument. if (FTP->getNumArgs() != 0) return; - + // Issue a warning. SourceRange R = CE->getCallee()->getSourceRange(); BR.EmitBasicReport("'random' is not a secure random number generator", @@ -352,11 +351,11 @@ void WalkAST::CheckUncheckedReturnValue(CallExpr *CE) { "setuid", "setgid", "seteuid", "setegid", "setreuid", "setregid" }; - + for (size_t i = 0; i < num_setids; i++) - II_setid[i] = &BR.getContext().Idents.get(identifiers[i]); + II_setid[i] = &BR.getContext().Idents.get(identifiers[i]); } - + const IdentifierInfo *id = FD->getIdentifier(); size_t identifierid; @@ -366,11 +365,11 @@ void WalkAST::CheckUncheckedReturnValue(CallExpr *CE) { if (identifierid >= num_setids) return; - + const FunctionProtoType *FTP = dyn_cast(FD->getType()); if (!FTP) return; - + // Verify that the function takes one or two arguments (depending on // the function). if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2)) @@ -395,7 +394,7 @@ void WalkAST::CheckUncheckedReturnValue(CallExpr *CE) { << "', the following code may execute with unexpected privileges"; SourceRange R = CE->getCallee()->getSourceRange(); - + BR.EmitBasicReport(os1.str().c_str(), "Security", os2.str().c_str(), CE->getLocStart(), &R, 1); } @@ -404,7 +403,7 @@ void WalkAST::CheckUncheckedReturnValue(CallExpr *CE) { // Entry point for check. //===----------------------------------------------------------------------===// -void clang::CheckSecuritySyntaxOnly(const Decl *D, BugReporter &BR) { +void clang::CheckSecuritySyntaxOnly(const Decl *D, BugReporter &BR) { WalkAST walker(BR); - walker.Visit(D->getBody()); + walker.Visit(D->getBody()); } diff --git a/clang/lib/Analysis/Environment.cpp b/clang/lib/Analysis/Environment.cpp index 0b8ee66f1545e2852488eef8f35bb06856f27dc8..1610ad4d271d9cae94dc650fac3274712b44fb4e 100644 --- a/clang/lib/Analysis/Environment.cpp +++ b/clang/lib/Analysis/Environment.cpp @@ -18,61 +18,61 @@ using namespace clang; SVal Environment::GetSVal(const Stmt *E, ValueManager& ValMgr) const { - + for (;;) { - + switch (E->getStmtClass()) { - - case Stmt::AddrLabelExprClass: + + case Stmt::AddrLabelExprClass: return ValMgr.makeLoc(cast(E)); - + // ParenExprs are no-ops. - - case Stmt::ParenExprClass: + + case Stmt::ParenExprClass: E = cast(E)->getSubExpr(); continue; - + case Stmt::CharacterLiteralClass: { const CharacterLiteral* C = cast(E); return ValMgr.makeIntVal(C->getValue(), C->getType()); } - + case Stmt::IntegerLiteralClass: { return ValMgr.makeIntVal(cast(E)); } - + // Casts where the source and target type are the same // are no-ops. We blast through these to get the descendant // subexpression that has a value. - + case Stmt::ImplicitCastExprClass: case Stmt::CStyleCastExprClass: { const CastExpr* C = cast(E); QualType CT = C->getType(); - + if (CT->isVoidType()) return UnknownVal(); - + break; } - + // Handle all other Stmt* using a lookup. - + default: break; }; - + break; } - + return LookupExpr(E); } Environment EnvironmentManager::BindExpr(Environment Env, const Stmt *S, - SVal V, bool Invalidate) { + SVal V, bool Invalidate) { assert(S); - - if (V.isUnknown()) { + + if (V.isUnknown()) { if (Invalidate) return Environment(F.Remove(Env.ExprBindings, S), Env.ACtx); else @@ -86,7 +86,7 @@ namespace { class VISIBILITY_HIDDEN MarkLiveCallback : public SymbolVisitor { SymbolReaper &SymReaper; public: - MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {} + MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {} bool VisitSymbol(SymbolRef sym) { SymReaper.markLive(sym); return true; } }; } // end anonymous namespace @@ -95,45 +95,45 @@ public: // - Remove subexpression bindings. // - Remove dead block expression bindings. // - Keep live block expression bindings: -// - Mark their reachable symbols live in SymbolReaper, +// - Mark their reachable symbols live in SymbolReaper, // see ScanReachableSymbols. // - Mark the region in DRoots if the binding is a loc::MemRegionVal. -Environment +Environment EnvironmentManager::RemoveDeadBindings(Environment Env, const Stmt *S, SymbolReaper &SymReaper, const GRState *ST, llvm::SmallVectorImpl &DRoots) { - + CFG &C = *Env.getAnalysisContext().getCFG(); - + // We construct a new Environment object entirely, as this is cheaper than // individually removing all the subexpression bindings (which will greatly // outnumber block-level expression bindings). Environment NewEnv = getInitialEnvironment(&Env.getAnalysisContext()); - + // Iterate over the block-expr bindings. - for (Environment::iterator I = Env.begin(), E = Env.end(); + for (Environment::iterator I = Env.begin(), E = Env.end(); I != E; ++I) { - + const Stmt *BlkExpr = I.getKey(); - + // Not a block-level expression? if (!C.isBlkExpr(BlkExpr)) continue; - + const SVal &X = I.getData(); - + if (SymReaper.isLive(S, BlkExpr)) { // Copy the binding to the new map. NewEnv.ExprBindings = F.Add(NewEnv.ExprBindings, BlkExpr, X); - + // If the block expr's value is a memory region, then mark that region. if (isa(X)) { const MemRegion* R = cast(X).getRegion(); DRoots.push_back(R); // Mark the super region of the RX as live. - // e.g.: int x; char *y = (char*) &x; if (*y) ... + // e.g.: int x; char *y = (char*) &x; if (*y) ... // 'y' => element region. 'x' is its super region. // We only add one level super region for now. diff --git a/clang/lib/Analysis/ExplodedGraph.cpp b/clang/lib/Analysis/ExplodedGraph.cpp index 88bb120f5da59f5205647872ecc89cef9f516575..463b171249f3ccc4430c6f51c724d329578a0b4e 100644 --- a/clang/lib/Analysis/ExplodedGraph.cpp +++ b/clang/lib/Analysis/ExplodedGraph.cpp @@ -64,10 +64,10 @@ void ExplodedNode::addPredecessor(ExplodedNode* V) { } void ExplodedNode::NodeGroup::addNode(ExplodedNode* N) { - + assert ((reinterpret_cast(N) & Mask) == 0x0); assert (!getFlag()); - + if (getKind() == Size1) { if (ExplodedNode* NOld = getNode()) { std::vector* V = new std::vector(); @@ -93,7 +93,7 @@ void ExplodedNode::NodeGroup::addNode(ExplodedNode* N) { unsigned ExplodedNode::NodeGroup::size() const { if (getFlag()) return 0; - + if (getKind() == Size1) return getNode() ? 1 : 0; else @@ -103,7 +103,7 @@ unsigned ExplodedNode::NodeGroup::size() const { ExplodedNode** ExplodedNode::NodeGroup::begin() const { if (getFlag()) return NULL; - + if (getKind() == Size1) return (ExplodedNode**) (getPtr() ? &P : NULL); else @@ -113,7 +113,7 @@ ExplodedNode** ExplodedNode::NodeGroup::begin() const { ExplodedNode** ExplodedNode::NodeGroup::end() const { if (getFlag()) return NULL; - + if (getKind() == Size1) return (ExplodedNode**) (getPtr() ? &P+1 : NULL); else { @@ -127,47 +127,47 @@ ExplodedNode::NodeGroup::~NodeGroup() { if (getKind() == SizeOther) delete &getVector(getPtr()); } -ExplodedNode *ExplodedGraph::getNode(const ProgramPoint& L, +ExplodedNode *ExplodedGraph::getNode(const ProgramPoint& L, const GRState* State, bool* IsNew) { // Profile 'State' to determine if we already have an existing node. - llvm::FoldingSetNodeID profile; + llvm::FoldingSetNodeID profile; void* InsertPos = 0; - + NodeTy::Profile(profile, L, State); NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos); - + if (!V) { // Allocate a new node. V = (NodeTy*) Allocator.Allocate(); new (V) NodeTy(L, State); - + // Insert the node into the node set and return it. Nodes.InsertNode(V, InsertPos); - + ++NumNodes; - + if (IsNew) *IsNew = true; } else if (IsNew) *IsNew = false; - + return V; } std::pair ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd, llvm::DenseMap *InverseMap) const { - + if (NBeg == NEnd) return std::make_pair((ExplodedGraph*) 0, (InterExplodedGraphMap*) 0); - + assert (NBeg < NEnd); llvm::OwningPtr M(new InterExplodedGraphMap()); - + ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap); - + return std::make_pair(static_cast(G), M.take()); } @@ -179,10 +179,10 @@ ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources, typedef llvm::DenseSet Pass1Ty; Pass1Ty Pass1; - + typedef llvm::DenseMap Pass2Ty; Pass2Ty& Pass2 = M->M; - + llvm::SmallVector WL1, WL2; // ===- Pass 1 (reverse DFS) -=== @@ -190,59 +190,59 @@ ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources, assert(*I); WL1.push_back(*I); } - + // Process the first worklist until it is empty. Because it is a std::list // it acts like a FIFO queue. while (!WL1.empty()) { const ExplodedNode *N = WL1.back(); WL1.pop_back(); - + // Have we already visited this node? If so, continue to the next one. if (Pass1.count(N)) continue; // Otherwise, mark this node as visited. Pass1.insert(N); - + // If this is a root enqueue it to the second worklist. if (N->Preds.empty()) { WL2.push_back(N); continue; } - + // Visit our predecessors and enqueue them. for (ExplodedNode** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) WL1.push_back(*I); } - + // We didn't hit a root? Return with a null pointer for the new graph. if (WL2.empty()) return 0; // Create an empty graph. ExplodedGraph* G = MakeEmptyGraph(); - - // ===- Pass 2 (forward DFS to construct the new graph) -=== + + // ===- Pass 2 (forward DFS to construct the new graph) -=== while (!WL2.empty()) { const ExplodedNode* N = WL2.back(); WL2.pop_back(); - + // Skip this node if we have already processed it. if (Pass2.find(N) != Pass2.end()) continue; - + // Create the corresponding node in the new graph and record the mapping // from the old node to the new node. ExplodedNode* NewN = G->getNode(N->getLocation(), N->State, NULL); Pass2[N] = NewN; - + // Also record the reverse mapping from the new node to the old node. if (InverseMap) (*InverseMap)[NewN] = N; - + // If this node is a root, designate it as such in the graph. if (N->Preds.empty()) G->addRoot(NewN); - + // In the case that some of the intended predecessors of NewN have already // been created, we should hook them up as predecessors. @@ -252,7 +252,7 @@ ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources, Pass2Ty::iterator PI = Pass2.find(*I); if (PI == Pass2.end()) continue; - + NewN->addPredecessor(PI->second); } @@ -261,7 +261,7 @@ ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources, // the new nodes from the original graph that should have nodes created // in the new graph. for (ExplodedNode **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) { - Pass2Ty::iterator PI = Pass2.find(*I); + Pass2Ty::iterator PI = Pass2.find(*I); if (PI != Pass2.end()) { PI->second->addPredecessor(NewN); continue; @@ -271,12 +271,12 @@ ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources, if (Pass1.count(*I)) WL2.push_back(*I); } - + // Finally, explictly mark all nodes without any successors as sinks. if (N->isSink()) NewN->markAsSink(); } - + return G; } diff --git a/clang/lib/Analysis/GRBlockCounter.cpp b/clang/lib/Analysis/GRBlockCounter.cpp index f69a16da401c3aec10eb18042477886ce82cd17d..4f4103ac45b4a0e38f0f0fcf0372bc6fc0d25806 100644 --- a/clang/lib/Analysis/GRBlockCounter.cpp +++ b/clang/lib/Analysis/GRBlockCounter.cpp @@ -1,5 +1,5 @@ //==- GRBlockCounter.h - ADT for counting block visits -------------*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source diff --git a/clang/lib/Analysis/GRCoreEngine.cpp b/clang/lib/Analysis/GRCoreEngine.cpp index 7983dd841b05a768964be8382c5c7d59335309df..909f6196d6f3a33111a8a436879db1d757515eb6 100644 --- a/clang/lib/Analysis/GRCoreEngine.cpp +++ b/clang/lib/Analysis/GRCoreEngine.cpp @@ -1,5 +1,5 @@ //==- GRCoreEngine.cpp - Path-Sensitive Dataflow Engine ------------*- C++ -*-// -// +// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source @@ -48,27 +48,27 @@ public: return U; } }; - + class VISIBILITY_HIDDEN BFS : public GRWorkList { std::queue Queue; public: virtual bool hasWork() const { return !Queue.empty(); } - + virtual void Enqueue(const GRWorkListUnit& U) { Queue.push(U); } - + virtual GRWorkListUnit Dequeue() { // Don't use const reference. The subsequent pop_back() might make it // unsafe. - GRWorkListUnit U = Queue.front(); + GRWorkListUnit U = Queue.front(); Queue.pop(); return U; } }; - + } // end anonymous namespace // Place the dstor for GRWorkList here because it contains virtual member @@ -86,14 +86,14 @@ namespace { virtual bool hasWork() const { return !Queue.empty() || !Stack.empty(); } - + virtual void Enqueue(const GRWorkListUnit& U) { if (isa(U.getNode()->getLocation())) Queue.push(U); else Stack.push_back(U); } - + virtual GRWorkListUnit Dequeue() { // Process all basic blocks to completion. if (!Stack.empty()) { @@ -101,13 +101,13 @@ namespace { Stack.pop_back(); // This technically "invalidates" U, but we are fine. return U; } - + assert(!Queue.empty()); // Don't use const reference. The subsequent pop_back() might make it // unsafe. - GRWorkListUnit U = Queue.front(); + GRWorkListUnit U = Queue.front(); Queue.pop(); - return U; + return U; } }; } // end anonymous namespace @@ -128,13 +128,13 @@ void GRCoreEngine::ProcessStmt(Stmt* S, GRStmtNodeBuilder& Builder) { } bool GRCoreEngine::ProcessBlockEntrance(CFGBlock* Blk, const GRState* State, - GRBlockCounter BC) { + GRBlockCounter BC) { return SubEngine.ProcessBlockEntrance(Blk, State, BC); } void GRCoreEngine::ProcessBranch(Stmt* Condition, Stmt* Terminator, GRBranchNodeBuilder& Builder) { - SubEngine.ProcessBranch(Condition, Terminator, Builder); + SubEngine.ProcessBranch(Condition, Terminator, Builder); } void GRCoreEngine::ProcessIndirectGoto(GRIndirectGotoNodeBuilder& Builder) { @@ -147,52 +147,52 @@ void GRCoreEngine::ProcessSwitch(GRSwitchNodeBuilder& Builder) { /// ExecuteWorkList - Run the worklist algorithm for a maximum number of steps. bool GRCoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps) { - + if (G->num_roots() == 0) { // Initialize the analysis by constructing // the root if none exists. - + CFGBlock* Entry = &(L->getCFG()->getEntry()); - - assert (Entry->empty() && + + assert (Entry->empty() && "Entry block must be empty."); - + assert (Entry->succ_size() == 1 && "Entry block must have 1 successor."); - + // Get the solitary successor. - CFGBlock* Succ = *(Entry->succ_begin()); - + CFGBlock* Succ = *(Entry->succ_begin()); + // Construct an edge representing the // starting location in the function. BlockEdge StartLoc(Entry, Succ, L); - + // Set the current block counter to being empty. WList->setBlockCounter(BCounterFactory.GetEmptyCounter()); - + // Generate the root. GenerateNode(StartLoc, getInitialState(L), 0); } - + while (Steps && WList->hasWork()) { --Steps; const GRWorkListUnit& WU = WList->Dequeue(); - + // Set the current block counter. WList->setBlockCounter(WU.getBlockCounter()); // Retrieve the node. ExplodedNode* Node = WU.getNode(); - + // Dispatch on the location type. switch (Node->getLocation().getKind()) { case ProgramPoint::BlockEdgeKind: HandleBlockEdge(cast(Node->getLocation()), Node); break; - + case ProgramPoint::BlockEntranceKind: HandleBlockEntrance(cast(Node->getLocation()), Node); break; - + case ProgramPoint::BlockExitKind: assert (false && "BlockExit location never occur in forward analysis."); break; @@ -201,22 +201,22 @@ bool GRCoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps) { assert(isa(Node->getLocation())); HandlePostStmt(cast(Node->getLocation()), WU.getBlock(), WU.getIndex(), Node); - break; + break; } } - + return WList->hasWork(); } void GRCoreEngine::HandleBlockEdge(const BlockEdge& L, ExplodedNode* Pred) { - + CFGBlock* Blk = L.getDst(); - - // Check if we are entering the EXIT block. + + // Check if we are entering the EXIT block. if (Blk == &(Pred->getLocationContext()->getCFG()->getExit())) { - - assert (Pred->getLocationContext()->getCFG()->getExit().size() == 0 + + assert (Pred->getLocationContext()->getCFG()->getExit().size() == 0 && "EXIT block cannot contain Stmts."); // Process the final state transition. @@ -228,81 +228,81 @@ void GRCoreEngine::HandleBlockEdge(const BlockEdge& L, ExplodedNode* Pred) { } // FIXME: Should we allow ProcessBlockEntrance to also manipulate state? - + if (ProcessBlockEntrance(Blk, Pred->State, WList->getBlockCounter())) GenerateNode(BlockEntrance(Blk, Pred->getLocationContext()), Pred->State, Pred); } void GRCoreEngine::HandleBlockEntrance(const BlockEntrance& L, ExplodedNode* Pred) { - + // Increment the block counter. GRBlockCounter Counter = WList->getBlockCounter(); Counter = BCounterFactory.IncrementCount(Counter, L.getBlock()->getBlockID()); WList->setBlockCounter(Counter); - - // Process the entrance of the block. + + // Process the entrance of the block. if (Stmt* S = L.getFirstStmt()) { - GRStmtNodeBuilder Builder(L.getBlock(), 0, Pred, this, + GRStmtNodeBuilder Builder(L.getBlock(), 0, Pred, this, SubEngine.getStateManager()); ProcessStmt(S, Builder); } - else + else HandleBlockExit(L.getBlock(), Pred); } void GRCoreEngine::HandleBlockExit(CFGBlock * B, ExplodedNode* Pred) { - + if (Stmt* Term = B->getTerminator()) { switch (Term->getStmtClass()) { default: assert(false && "Analysis for this terminator not implemented."); break; - + case Stmt::BinaryOperatorClass: // '&&' and '||' HandleBranch(cast(Term)->getLHS(), Term, B, Pred); return; - + case Stmt::ConditionalOperatorClass: HandleBranch(cast(Term)->getCond(), Term, B, Pred); return; - + // FIXME: Use constant-folding in CFG construction to simplify this // case. - + case Stmt::ChooseExprClass: HandleBranch(cast(Term)->getCond(), Term, B, Pred); return; - + case Stmt::DoStmtClass: HandleBranch(cast(Term)->getCond(), Term, B, Pred); return; - + case Stmt::ForStmtClass: HandleBranch(cast(Term)->getCond(), Term, B, Pred); return; - + case Stmt::ContinueStmtClass: case Stmt::BreakStmtClass: - case Stmt::GotoStmtClass: + case Stmt::GotoStmtClass: break; - + case Stmt::IfStmtClass: HandleBranch(cast(Term)->getCond(), Term, B, Pred); return; - + case Stmt::IndirectGotoStmtClass: { // Only 1 successor: the indirect goto dispatch block. assert (B->succ_size() == 1); - + GRIndirectGotoNodeBuilder builder(Pred, B, cast(Term)->getTarget(), *(B->succ_begin()), this); - + ProcessIndirectGoto(builder); return; } - + case Stmt::ObjCForCollectionStmtClass: { // In the case of ObjCForCollectionStmt, it appears twice in a CFG: // @@ -317,15 +317,15 @@ void GRCoreEngine::HandleBlockExit(CFGBlock * B, ExplodedNode* Pred) { HandleBranch(Term, Term, B, Pred); return; } - + case Stmt::SwitchStmtClass: { GRSwitchNodeBuilder builder(Pred, B, cast(Term)->getCond(), this); - + ProcessSwitch(builder); return; } - + case Stmt::WhileStmtClass: HandleBranch(cast(Term)->getCond(), Term, B, Pred); return; @@ -334,8 +334,8 @@ void GRCoreEngine::HandleBlockExit(CFGBlock * B, ExplodedNode* Pred) { assert (B->succ_size() == 1 && "Blocks with no terminator should have at most 1 successor."); - - GenerateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()), + + GenerateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()), Pred->State, Pred); } @@ -345,19 +345,19 @@ void GRCoreEngine::HandleBranch(Stmt* Cond, Stmt* Term, CFGBlock * B, GRBranchNodeBuilder Builder(B, *(B->succ_begin()), *(B->succ_begin()+1), Pred, this); - + ProcessBranch(Cond, Term, Builder); } void GRCoreEngine::HandlePostStmt(const PostStmt& L, CFGBlock* B, unsigned StmtIdx, ExplodedNode* Pred) { - + assert (!B->empty()); if (StmtIdx == B->size()) HandleBlockExit(B, Pred); else { - GRStmtNodeBuilder Builder(B, StmtIdx, Pred, this, + GRStmtNodeBuilder Builder(B, StmtIdx, Pred, this, SubEngine.getStateManager()); ProcessStmt((*B)[StmtIdx], Builder); } @@ -365,19 +365,19 @@ void GRCoreEngine::HandlePostStmt(const PostStmt& L, CFGBlock* B, /// GenerateNode - Utility method to generate nodes, hook up successors, /// and add nodes to the worklist. -void GRCoreEngine::GenerateNode(const ProgramPoint& Loc, +void GRCoreEngine::GenerateNode(const ProgramPoint& Loc, const GRState* State, ExplodedNode* Pred) { - + bool IsNew; ExplodedNode* Node = G->getNode(Loc, State, &IsNew); - - if (Pred) + + if (Pred) Node->addPredecessor(Pred); // Link 'Node' with its predecessor. else { assert (IsNew); G->addRoot(Node); // 'Node' has no predecessor. Make it a root. } - + // Only add 'Node' to the worklist if it was freshly generated. if (IsNew) WList->Enqueue(Node); } @@ -385,7 +385,7 @@ void GRCoreEngine::GenerateNode(const ProgramPoint& Loc, GRStmtNodeBuilder::GRStmtNodeBuilder(CFGBlock* b, unsigned idx, ExplodedNode* N, GRCoreEngine* e, GRStateManager &mgr) - : Eng(*e), B(*b), Idx(idx), Pred(N), LastNode(N), Mgr(mgr), Auditor(0), + : Eng(*e), B(*b), Idx(idx), Pred(N), LastNode(N), Mgr(mgr), Auditor(0), PurgingDeadSymbols(false), BuildSinks(false), HasGeneratedNode(false), PointKind(ProgramPoint::PostStmtKind), Tag(0) { Deferred.insert(N); @@ -400,16 +400,16 @@ GRStmtNodeBuilder::~GRStmtNodeBuilder() { void GRStmtNodeBuilder::GenerateAutoTransition(ExplodedNode* N) { assert (!N->isSink()); - + PostStmt Loc(getStmt(), N->getLocationContext()); - + if (Loc == N->getLocation()) { // Note: 'N' should be a fresh node because otherwise it shouldn't be // a member of Deferred. Eng.WList->Enqueue(N, B, Idx+1); return; } - + bool IsNew; ExplodedNode* Succ = Eng.G->getNode(Loc, N->State, &IsNew); Succ->addPredecessor(N); @@ -423,10 +423,10 @@ static inline PostStmt GetPostLoc(const Stmt* S, ProgramPoint::Kind K, switch (K) { default: assert(false && "Invalid PostXXXKind."); - + case ProgramPoint::PostStmtKind: return PostStmt(S, L, tag); - + case ProgramPoint::PostLoadKind: return PostLoad(S, L, tag); @@ -435,19 +435,19 @@ static inline PostStmt GetPostLoc(const Stmt* S, ProgramPoint::Kind K, case ProgramPoint::PostLocationChecksSucceedKind: return PostLocationChecksSucceed(S, L, tag); - + case ProgramPoint::PostOutOfBoundsCheckFailedKind: return PostOutOfBoundsCheckFailed(S, L, tag); - + case ProgramPoint::PostNullCheckFailedKind: return PostNullCheckFailed(S, L, tag); - + case ProgramPoint::PostStoreKind: return PostStore(S, L, tag); - + case ProgramPoint::PostLValueKind: return PostLValue(S, L, tag); - + case ProgramPoint::PostPurgeDeadSymbolsKind: return PostPurgeDeadSymbols(S, L, tag); } @@ -459,10 +459,10 @@ GRStmtNodeBuilder::generateNodeInternal(const Stmt* S, const GRState* State, ProgramPoint::Kind K, const void *tag) { return K == ProgramPoint::PreStmtKind - ? generateNodeInternal(PreStmt(S, Pred->getLocationContext(),tag), + ? generateNodeInternal(PreStmt(S, Pred->getLocationContext(),tag), State, Pred) : generateNodeInternal(GetPostLoc(S, K, Pred->getLocationContext(), tag), - State, Pred); + State, Pred); } ExplodedNode* @@ -473,49 +473,49 @@ GRStmtNodeBuilder::generateNodeInternal(const ProgramPoint &Loc, ExplodedNode* N = Eng.G->getNode(Loc, State, &IsNew); N->addPredecessor(Pred); Deferred.erase(Pred); - + if (IsNew) { Deferred.insert(N); LastNode = N; return N; } - + LastNode = NULL; - return NULL; + return NULL; } ExplodedNode* GRBranchNodeBuilder::generateNode(const GRState* State, bool branch) { - + // If the branch has been marked infeasible we should not generate a node. if (!isFeasible(branch)) return NULL; - + bool IsNew; - + ExplodedNode* Succ = Eng.G->getNode(BlockEdge(Src,branch ? DstT:DstF,Pred->getLocationContext()), State, &IsNew); - + Succ->addPredecessor(Pred); - + if (branch) GeneratedTrue = true; else - GeneratedFalse = true; - + GeneratedFalse = true; + if (IsNew) { Deferred.push_back(Succ); return Succ; } - + return NULL; } GRBranchNodeBuilder::~GRBranchNodeBuilder() { if (!GeneratedTrue) generateNode(Pred->State, true); if (!GeneratedFalse) generateNode(Pred->State, false); - + for (DeferredTy::iterator I=Deferred.begin(), E=Deferred.end(); I!=E; ++I) if (!(*I)->isSink()) Eng.WList->Enqueue(*I); } @@ -525,22 +525,22 @@ ExplodedNode* GRIndirectGotoNodeBuilder::generateNode(const iterator& I, const GRState* St, bool isSink) { bool IsNew; - - ExplodedNode* Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(), + + ExplodedNode* Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()), St, &IsNew); - + Succ->addPredecessor(Pred); - + if (IsNew) { - + if (isSink) Succ->markAsSink(); else Eng.WList->Enqueue(Succ); - + return Succ; } - + return NULL; } @@ -549,42 +549,42 @@ ExplodedNode* GRSwitchNodeBuilder::generateCaseStmtNode(const iterator& I, const GRState* St){ bool IsNew; - + ExplodedNode* Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()), St, &IsNew); Succ->addPredecessor(Pred); - + if (IsNew) { Eng.WList->Enqueue(Succ); return Succ; } - + return NULL; } ExplodedNode* GRSwitchNodeBuilder::generateDefaultCaseNode(const GRState* St, bool isSink) { - + // Get the block for the default case. assert (Src->succ_rbegin() != Src->succ_rend()); CFGBlock* DefaultBlock = *Src->succ_rbegin(); - + bool IsNew; - + ExplodedNode* Succ = Eng.G->getNode(BlockEdge(Src, DefaultBlock, Pred->getLocationContext()), St, &IsNew); Succ->addPredecessor(Pred); - + if (IsNew) { if (isSink) Succ->markAsSink(); else Eng.WList->Enqueue(Succ); - + return Succ; } - + return NULL; } @@ -596,18 +596,18 @@ GREndPathNodeBuilder::~GREndPathNodeBuilder() { ExplodedNode* GREndPathNodeBuilder::generateNode(const GRState* State, const void *tag, ExplodedNode* P) { - HasGeneratedNode = true; + HasGeneratedNode = true; bool IsNew; - - ExplodedNode* Node = Eng.G->getNode(BlockEntrance(&B, + + ExplodedNode* Node = Eng.G->getNode(BlockEntrance(&B, Pred->getLocationContext(), tag), State, &IsNew); - + Node->addPredecessor(P ? P : Pred); - + if (IsNew) { Eng.G->addEndOfPath(Node); return Node; } - + return NULL; } diff --git a/clang/lib/Analysis/GRExprEngine.cpp b/clang/lib/Analysis/GRExprEngine.cpp index 053da67c7d101c6bd471ca3390b1936655e9bdc5..b4b69cdcd61e8baf6494bddd59269ccf19aadb6c 100644 --- a/clang/lib/Analysis/GRExprEngine.cpp +++ b/clang/lib/Analysis/GRExprEngine.cpp @@ -44,7 +44,7 @@ namespace { class VISIBILITY_HIDDEN MappedBatchAuditor : public GRSimpleAPICheck { typedef llvm::ImmutableList Checks; typedef llvm::DenseMap MapTy; - + MapTy M; Checks::Factory F; Checks AllStmts; @@ -52,18 +52,18 @@ class VISIBILITY_HIDDEN MappedBatchAuditor : public GRSimpleAPICheck { public: MappedBatchAuditor(llvm::BumpPtrAllocator& Alloc) : F(Alloc), AllStmts(F.GetEmptyList()) {} - + virtual ~MappedBatchAuditor() { llvm::DenseSet AlreadyVisited; - + for (MapTy::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) for (Checks::iterator I=MI->second.begin(), E=MI->second.end(); I!=E;++I){ GRSimpleAPICheck* check = *I; - + if (AlreadyVisited.count(check)) continue; - + AlreadyVisited.insert(check); delete check; } @@ -75,10 +75,10 @@ public: MapTy::iterator I = M.find(key); M[key] = F.Concat(A, I == M.end() ? F.GetEmptyList() : I->second); } - + void AddCheck(GRSimpleAPICheck *A) { assert (A && "Check cannot be null."); - AllStmts = F.Concat(A, AllStmts); + AllStmts = F.Concat(A, AllStmts); } virtual bool Audit(ExplodedNode* N, GRStateManager& VMgr) { @@ -86,17 +86,17 @@ public: bool isSink = false; for (Checks::iterator I = AllStmts.begin(), E = AllStmts.end(); I!=E; ++I) isSink |= (*I)->Audit(N, VMgr); - + // Next handle the auditors that accept only specific statements. const Stmt* S = cast(N->getLocation()).getStmt(); void* key = reinterpret_cast((uintptr_t) S->getStmtClass()); MapTy::iterator MI = M.find(key); - if (MI != M.end()) { + if (MI != M.end()) { for (Checks::iterator I=MI->second.begin(), E=MI->second.end(); I!=E; ++I) isSink |= (*I)->Audit(N, VMgr); } - - return isSink; + + return isSink; } }; @@ -105,30 +105,30 @@ public: //===----------------------------------------------------------------------===// // Checker worklist routines. //===----------------------------------------------------------------------===// - -void GRExprEngine::CheckerVisit(Stmt *S, ExplodedNodeSet &Dst, + +void GRExprEngine::CheckerVisit(Stmt *S, ExplodedNodeSet &Dst, ExplodedNodeSet &Src, bool isPrevisit) { - + if (Checkers.empty()) { Dst = Src; return; } - + ExplodedNodeSet Tmp; ExplodedNodeSet *PrevSet = &Src; - + for (std::vector::iterator I = Checkers.begin(), E = Checkers.end(); I != E; ++I) { - ExplodedNodeSet *CurrSet = (I+1 == E) ? &Dst + ExplodedNodeSet *CurrSet = (I+1 == E) ? &Dst : (PrevSet == &Tmp) ? &Src : &Tmp; CurrSet->clear(); Checker *checker = *I; - + for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end(); NI != NE; ++NI) checker->GR_Visit(*CurrSet, *Builder, *this, S, *NI, isPrevisit); - + // Update which NodeSet is the current one. PrevSet = CurrSet; } @@ -149,20 +149,20 @@ static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) { GRExprEngine::GRExprEngine(AnalysisManager &mgr) : AMgr(mgr), - CoreEngine(mgr.getASTContext(), *this), + CoreEngine(mgr.getASTContext(), *this), G(CoreEngine.getGraph()), Builder(NULL), - StateMgr(G.getContext(), mgr.getStoreManagerCreator(), + StateMgr(G.getContext(), mgr.getStoreManagerCreator(), mgr.getConstraintManagerCreator(), G.getAllocator()), SymMgr(StateMgr.getSymbolManager()), ValMgr(StateMgr.getValueManager()), SVator(ValMgr.getSValuator()), CurrentStmt(NULL), NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), - RaiseSel(GetNullarySelector("raise", G.getContext())), + RaiseSel(GetNullarySelector("raise", G.getContext())), BR(mgr, *this) {} -GRExprEngine::~GRExprEngine() { +GRExprEngine::~GRExprEngine() { BR.FlushReports(); delete [] NSExceptionInstanceRaiseSelectors; for (std::vector::iterator I=Checkers.begin(), E=Checkers.end(); @@ -184,7 +184,7 @@ void GRExprEngine::setTransferFunctions(GRTransferFuncs* tf) { void GRExprEngine::AddCheck(GRSimpleAPICheck* A, Stmt::StmtClass C) { if (!BatchAuditor) BatchAuditor.reset(new MappedBatchAuditor(getGraph().getAllocator())); - + ((MappedBatchAuditor*) BatchAuditor.get())->AddCheck(A, C); } @@ -197,7 +197,7 @@ void GRExprEngine::AddCheck(GRSimpleAPICheck *A) { const GRState* GRExprEngine::getInitialState(const LocationContext *InitLoc) { const GRState *state = StateMgr.getInitialState(InitLoc); - + // Precondition: the first argument of 'main' is an integer guaranteed // to be > 0. // FIXME: It would be nice if we had a more general mechanism to add @@ -212,13 +212,13 @@ const GRState* GRExprEngine::getInitialState(const LocationContext *InitLoc) { SVal V = state->getSVal(loc::MemRegionVal(R)); SVal Constraint = EvalBinOp(state, BinaryOperator::GT, V, ValMgr.makeZeroVal(T), - getContext().IntTy); + getContext().IntTy); if (const GRState *newState = state->assume(Constraint, true)) state = newState; } } - + return state; } @@ -227,31 +227,31 @@ const GRState* GRExprEngine::getInitialState(const LocationContext *InitLoc) { //===----------------------------------------------------------------------===// void GRExprEngine::ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder) { - + PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), S->getLocStart(), "Error evaluating statement"); - + Builder = &builder; EntryNode = builder.getLastNode(); - + // FIXME: Consolidate. CurrentStmt = S; StateMgr.CurrentStmt = S; - + // Set up our simple checks. if (BatchAuditor) Builder->setAuditor(BatchAuditor.get()); - - // Create the cleaned state. - SymbolReaper SymReaper(*AMgr.getLiveVariables(), SymMgr); + + // Create the cleaned state. + SymbolReaper SymReaper(*AMgr.getLiveVariables(), SymMgr); CleanedState = AMgr.shouldPurgeDead() ? StateMgr.RemoveDeadBindings(EntryNode->getState(), CurrentStmt, SymReaper) : EntryNode->getState(); // Process any special transfer function for dead symbols. ExplodedNodeSet Tmp; - + if (!SymReaper.hasDeadSymbols()) Tmp.Add(EntryNode); else { @@ -260,36 +260,36 @@ void GRExprEngine::ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder) { SaveAndRestore OldPurgeDeadSymbols(Builder->PurgingDeadSymbols); Builder->PurgingDeadSymbols = true; - - getTF().EvalDeadSymbols(Tmp, *this, *Builder, EntryNode, S, + + getTF().EvalDeadSymbols(Tmp, *this, *Builder, EntryNode, S, CleanedState, SymReaper); if (!Builder->BuildSinks && !Builder->HasGeneratedNode) Tmp.Add(EntryNode); } - + bool HasAutoGenerated = false; for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { ExplodedNodeSet Dst; - - // Set the cleaned state. + + // Set the cleaned state. Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I)); - - // Visit the statement. + + // Visit the statement. Visit(S, *I, Dst); // Do we need to auto-generate a node? We only need to do this to generate // a node with a "cleaned" state; GRCoreEngine will actually handle - // auto-transitions for other cases. + // auto-transitions for other cases. if (Dst.size() == 1 && *Dst.begin() == EntryNode && !Builder->HasGeneratedNode && !HasAutoGenerated) { HasAutoGenerated = true; builder.generateNode(S, GetState(EntryNode), *I); } } - + // NULL out these variables to cleanup. CleanedState = NULL; EntryNode = NULL; @@ -297,11 +297,11 @@ void GRExprEngine::ProcessStmt(Stmt* S, GRStmtNodeBuilder& builder) { // FIXME: Consolidate. StateMgr.CurrentStmt = 0; CurrentStmt = 0; - + Builder = NULL; } -void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { +void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), S->getLocStart(), "Error evaluating statement"); @@ -309,32 +309,32 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { // FIXME: add metadata to the CFG so that we can disable // this check when we KNOW that there is no block-level subexpression. // The motivation is that this check requires a hashtable lookup. - + if (S != CurrentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) { Dst.Add(Pred); return; } - + switch (S->getStmtClass()) { - + default: // Cases we intentionally have "default" handle: // AddrLabelExpr, IntegerLiteral, CharacterLiteral - + Dst.Add(Pred); // No-op. Simply propagate the current state unchanged. break; - + case Stmt::ArraySubscriptExprClass: VisitArraySubscriptExpr(cast(S), Pred, Dst, false); break; - + case Stmt::AsmStmtClass: VisitAsmStmt(cast(S), Pred, Dst); break; - + case Stmt::BinaryOperatorClass: { BinaryOperator* B = cast(S); - + if (B->isLogicalOp()) { VisitLogicalExpr(B, Pred, Dst); break; @@ -348,7 +348,7 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { if (AMgr.shouldEagerlyAssume() && (B->isRelationalOp() || B->isEqualityOp())) { ExplodedNodeSet Tmp; VisitBinaryOperator(cast(S), Pred, Tmp); - EvalEagerlyAssume(Dst, Tmp, cast(S)); + EvalEagerlyAssume(Dst, Tmp, cast(S)); } else VisitBinaryOperator(cast(S), Pred, Dst); @@ -365,13 +365,13 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { // FIXME: ChooseExpr is really a constant. We need to fix // the CFG do not model them as explicit control-flow. - + case Stmt::ChooseExprClass: { // __builtin_choose_expr ChooseExpr* C = cast(S); VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); break; } - + case Stmt::CompoundAssignOperatorClass: VisitBinaryOperator(cast(S), Pred, Dst); break; @@ -379,22 +379,22 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { case Stmt::CompoundLiteralExprClass: VisitCompoundLiteralExpr(cast(S), Pred, Dst, false); break; - + case Stmt::ConditionalOperatorClass: { // '?' operator ConditionalOperator* C = cast(S); VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); break; } - + case Stmt::DeclRefExprClass: case Stmt::QualifiedDeclRefExprClass: VisitDeclRefExpr(cast(S), Pred, Dst, false); break; - + case Stmt::DeclStmtClass: VisitDeclStmt(cast(S), Pred, Dst); break; - + case Stmt::ImplicitCastExprClass: case Stmt::CStyleCastExprClass: { CastExpr* C = cast(S); @@ -405,11 +405,11 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { case Stmt::InitListExprClass: VisitInitListExpr(cast(S), Pred, Dst); break; - + case Stmt::MemberExprClass: VisitMemberExpr(cast(S), Pred, Dst, false); break; - + case Stmt::ObjCIvarRefExprClass: VisitObjCIvarRefExpr(cast(S), Pred, Dst, false); break; @@ -417,12 +417,12 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { case Stmt::ObjCForCollectionStmtClass: VisitObjCForCollectionStmt(cast(S), Pred, Dst); break; - + case Stmt::ObjCMessageExprClass: { VisitObjCMessageExpr(cast(S), Pred, Dst); break; } - + case Stmt::ObjCAtThrowStmtClass: { // FIXME: This is not complete. We basically treat @throw as // an abort. @@ -431,19 +431,19 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { MakeNode(Dst, S, Pred, GetState(Pred)); break; } - + case Stmt::ParenExprClass: Visit(cast(S)->getSubExpr()->IgnoreParens(), Pred, Dst); break; - + case Stmt::ReturnStmtClass: VisitReturnStmt(cast(S), Pred, Dst); break; - + case Stmt::SizeOfAlignOfExprClass: VisitSizeOfAlignOfExpr(cast(S), Pred, Dst); break; - + case Stmt::StmtExprClass: { StmtExpr* SE = cast(S); @@ -454,21 +454,21 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { Dst.Add(Pred); break; } - + if (Expr* LastExpr = dyn_cast(*SE->getSubStmt()->body_rbegin())) { const GRState* state = GetState(Pred); MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr))); } else Dst.Add(Pred); - + break; } case Stmt::StringLiteralClass: VisitLValue(cast(S), Pred, Dst); break; - + case Stmt::UnaryOperatorClass: { UnaryOperator *U = cast(S); if (AMgr.shouldEagerlyAssume() && (U->getOpcode() == UnaryOperator::LNot)) { @@ -483,43 +483,43 @@ void GRExprEngine::Visit(Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { } } -void GRExprEngine::VisitLValue(Expr* Ex, ExplodedNode* Pred, +void GRExprEngine::VisitLValue(Expr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst) { - + Ex = Ex->IgnoreParens(); - + if (Ex != CurrentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(Ex)) { Dst.Add(Pred); return; } - + switch (Ex->getStmtClass()) { - + case Stmt::ArraySubscriptExprClass: VisitArraySubscriptExpr(cast(Ex), Pred, Dst, true); return; - + case Stmt::DeclRefExprClass: case Stmt::QualifiedDeclRefExprClass: VisitDeclRefExpr(cast(Ex), Pred, Dst, true); return; - + case Stmt::ObjCIvarRefExprClass: VisitObjCIvarRefExpr(cast(Ex), Pred, Dst, true); return; - + case Stmt::UnaryOperatorClass: VisitUnaryOperator(cast(Ex), Pred, Dst, true); return; - + case Stmt::MemberExprClass: VisitMemberExpr(cast(Ex), Pred, Dst, true); return; - + case Stmt::CompoundLiteralExprClass: VisitCompoundLiteralExpr(cast(Ex), Pred, Dst, true); return; - + case Stmt::ObjCPropertyRefExprClass: case Stmt::ObjCImplicitSetterGetterRefExprClass: // FIXME: Property assignments are lvalues, but not really "locations". @@ -542,7 +542,7 @@ void GRExprEngine::VisitLValue(Expr* Ex, ExplodedNode* Pred, MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V)); return; } - + default: // Arbitrary subexpressions can return aggregate temporaries that // can be used in a lvalue context. We need to enhance our support @@ -551,7 +551,7 @@ void GRExprEngine::VisitLValue(Expr* Ex, ExplodedNode* Pred, assert ((Ex->getType()->isAggregateType()) && "Other kinds of expressions with non-aggregate/union types do" " not have lvalues."); - + Visit(Ex, Pred, Dst); } } @@ -562,7 +562,7 @@ void GRExprEngine::VisitLValue(Expr* Ex, ExplodedNode* Pred, bool GRExprEngine::ProcessBlockEntrance(CFGBlock* B, const GRState*, GRBlockCounter BC) { - + return BC.getNumVisited(B->getBlockID()) < 3; } @@ -586,53 +586,53 @@ ExplodedNode* GRExprEngine::MakeNode(ExplodedNodeSet& Dst, Stmt* S, const GRState* GRExprEngine::MarkBranch(const GRState* state, Stmt* Terminator, bool branchTaken) { - + switch (Terminator->getStmtClass()) { default: return state; - + case Stmt::BinaryOperatorClass: { // '&&' and '||' - + BinaryOperator* B = cast(Terminator); BinaryOperator::Opcode Op = B->getOpcode(); - + assert (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr); - + // For &&, if we take the true branch, then the value of the whole // expression is that of the RHS expression. // // For ||, if we take the false branch, then the value of the whole // expression is that of the RHS expression. - + Expr* Ex = (Op == BinaryOperator::LAnd && branchTaken) || - (Op == BinaryOperator::LOr && !branchTaken) + (Op == BinaryOperator::LOr && !branchTaken) ? B->getRHS() : B->getLHS(); - + return state->BindExpr(B, UndefinedVal(Ex)); } - + case Stmt::ConditionalOperatorClass: { // ?: - + ConditionalOperator* C = cast(Terminator); - + // For ?, if branchTaken == true then the value is either the LHS or // the condition itself. (GNU extension). - - Expr* Ex; - + + Expr* Ex; + if (branchTaken) - Ex = C->getLHS() ? C->getLHS() : C->getCond(); + Ex = C->getLHS() ? C->getLHS() : C->getCond(); else Ex = C->getRHS(); - + return state->BindExpr(C, UndefinedVal(Ex)); } - + case Stmt::ChooseExprClass: { // ?: - + ChooseExpr* C = cast(Terminator); - - Expr* Ex = branchTaken ? C->getLHS() : C->getRHS(); + + Expr* Ex = branchTaken ? C->getLHS() : C->getRHS(); return state->BindExpr(C, UndefinedVal(Ex)); } } @@ -652,19 +652,19 @@ static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state, uint64_t bits = 0; bool bitsInit = false; - + while (CastExpr *CE = dyn_cast(Ex)) { QualType T = CE->getType(); if (!T->isIntegerType()) return UnknownVal(); - + uint64_t newBits = Ctx.getTypeSize(T); if (!bitsInit || newBits < bits) { bitsInit = true; bits = newBits; } - + Ex = CE->getSubExpr(); } @@ -673,26 +673,26 @@ static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state, if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) return UnknownVal(); - + return state->getSVal(Ex); } void GRExprEngine::ProcessBranch(Stmt* Condition, Stmt* Term, GRBranchNodeBuilder& builder) { - + // Check for NULL conditions; e.g. "for(;;)" - if (!Condition) { + if (!Condition) { builder.markInfeasible(false); return; } - + PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), Condition->getLocStart(), "Error evaluating branch"); - const GRState* PrevState = builder.getState(); + const GRState* PrevState = builder.getState(); SVal V = PrevState->getSVal(Condition); - + switch (V.getBaseKind()) { default: break; @@ -707,32 +707,32 @@ void GRExprEngine::ProcessBranch(Stmt* Condition, Stmt* Term, SVal recovered = RecoverCastedSymbol(getStateManager(), builder.getState(), Condition, getContext()); - + if (!recovered.isUnknown()) { V = recovered; break; } } } - + builder.generateNode(MarkBranch(PrevState, Term, true), true); builder.generateNode(MarkBranch(PrevState, Term, false), false); return; } - - case SVal::UndefinedKind: { + + case SVal::UndefinedKind: { ExplodedNode* N = builder.generateNode(PrevState, true); if (N) { N->markAsSink(); UndefBranches.insert(N); } - + builder.markInfeasible(false); return; - } + } } - + // Process the true branch. if (builder.isFeasible(true)) { if (const GRState *state = PrevState->assume(V, true)) @@ -740,8 +740,8 @@ void GRExprEngine::ProcessBranch(Stmt* Condition, Stmt* Term, else builder.markInfeasible(true); } - - // Process the false branch. + + // Process the false branch. if (builder.isFeasible(false)) { if (const GRState *state = PrevState->assume(V, false)) builder.generateNode(MarkBranch(state, Term, false), false); @@ -754,28 +754,28 @@ void GRExprEngine::ProcessBranch(Stmt* Condition, Stmt* Term, /// nodes by processing the 'effects' of a computed goto jump. void GRExprEngine::ProcessIndirectGoto(GRIndirectGotoNodeBuilder& builder) { - const GRState *state = builder.getState(); + const GRState *state = builder.getState(); SVal V = state->getSVal(builder.getTarget()); - + // Three possibilities: // // (1) We know the computed label. // (2) The label is NULL (or some other constant), or Undefined. // (3) We have no clue about the label. Dispatch to all targets. // - + typedef GRIndirectGotoNodeBuilder::iterator iterator; if (isa(V)) { LabelStmt* L = cast(V).getLabel(); - + for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) { if (I.getLabel() == L) { builder.generateNode(I, state); return; } } - + assert (false && "No block with label."); return; } @@ -786,10 +786,10 @@ void GRExprEngine::ProcessIndirectGoto(GRIndirectGotoNodeBuilder& builder) { UndefBranches.insert(N); return; } - + // This is really a catch-all. We don't support symbolics yet. // FIXME: Implement dispatch for symbolic pointers. - + for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) builder.generateNode(I, state); } @@ -797,27 +797,27 @@ void GRExprEngine::ProcessIndirectGoto(GRIndirectGotoNodeBuilder& builder) { void GRExprEngine::VisitGuardedExpr(Expr* Ex, Expr* L, Expr* R, ExplodedNode* Pred, ExplodedNodeSet& Dst) { - + assert (Ex == CurrentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(Ex)); - + const GRState* state = GetState(Pred); SVal X = state->getSVal(Ex); - + assert (X.isUndef()); - + Expr *SE = (Expr*) cast(X).getData(); - assert(SE); + assert(SE); X = state->getSVal(SE); - + // Make sure that we invalidate the previous binding. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true)); } /// ProcessSwitch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. -void GRExprEngine::ProcessSwitch(GRSwitchNodeBuilder& builder) { - typedef GRSwitchNodeBuilder::iterator iterator; - const GRState* state = builder.getState(); +void GRExprEngine::ProcessSwitch(GRSwitchNodeBuilder& builder) { + typedef GRSwitchNodeBuilder::iterator iterator; + const GRState* state = builder.getState(); Expr* CondE = builder.getCondition(); SVal CondV = state->getSVal(CondE); @@ -827,55 +827,55 @@ void GRExprEngine::ProcessSwitch(GRSwitchNodeBuilder& builder) { return; } - const GRState* DefaultSt = state; + const GRState* DefaultSt = state; bool defaultIsFeasible = false; - + for (iterator I = builder.begin(), EI = builder.end(); I != EI; ++I) { CaseStmt* Case = cast(I.getCase()); // Evaluate the LHS of the case value. Expr::EvalResult V1; - bool b = Case->getLHS()->Evaluate(V1, getContext()); - + bool b = Case->getLHS()->Evaluate(V1, getContext()); + // Sanity checks. These go away in Release builds. - assert(b && V1.Val.isInt() && !V1.HasSideEffects + assert(b && V1.Val.isInt() && !V1.HasSideEffects && "Case condition must evaluate to an integer constant."); - b = b; // silence unused variable warning - assert(V1.Val.getInt().getBitWidth() == + b = b; // silence unused variable warning + assert(V1.Val.getInt().getBitWidth() == getContext().getTypeSize(CondE->getType())); - + // Get the RHS of the case, if it exists. Expr::EvalResult V2; - + if (Expr* E = Case->getRHS()) { b = E->Evaluate(V2, getContext()); - assert(b && V2.Val.isInt() && !V2.HasSideEffects + assert(b && V2.Val.isInt() && !V2.HasSideEffects && "Case condition must evaluate to an integer constant."); b = b; // silence unused variable warning } else V2 = V1; - + // FIXME: Eventually we should replace the logic below with a range // comparison, rather than concretize the values within the range. // This should be easy once we have "ranges" for NonLVals. - + do { - nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt())); + nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt())); SVal Res = EvalBinOp(DefaultSt, BinaryOperator::EQ, CondV, CaseVal, getContext().IntTy); - - // Now "assume" that the case matches. + + // Now "assume" that the case matches. if (const GRState* stateNew = state->assume(Res, true)) { builder.generateCaseStmtNode(I, stateNew); - + // If CondV evaluates to a constant, then we know that this // is the *only* case that we can take, so stop evaluating the // others. if (isa(CondV)) return; } - + // Now "assume" that the case doesn't match. Add this state // to the default state (if it is feasible). if (const GRState *stateNew = DefaultSt->assume(Res, false)) { @@ -886,15 +886,15 @@ void GRExprEngine::ProcessSwitch(GRSwitchNodeBuilder& builder) { // Concretize the next value in the range. if (V1.Val.getInt() == V2.Val.getInt()) break; - + ++V1.Val.getInt(); assert (V1.Val.getInt() <= V2.Val.getInt()); - + } while (true); } - + // If we reach here, than we know that the default branch is - // possible. + // possible. if (defaultIsFeasible) builder.generateDefaultCaseNode(DefaultSt); } @@ -904,62 +904,62 @@ void GRExprEngine::ProcessSwitch(GRSwitchNodeBuilder& builder) { void GRExprEngine::VisitLogicalExpr(BinaryOperator* B, ExplodedNode* Pred, ExplodedNodeSet& Dst) { - + assert(B->getOpcode() == BinaryOperator::LAnd || B->getOpcode() == BinaryOperator::LOr); - + assert(B == CurrentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B)); - + const GRState* state = GetState(Pred); SVal X = state->getSVal(B); assert(X.isUndef()); - + Expr* Ex = (Expr*) cast(X).getData(); - + assert(Ex); - + if (Ex == B->getRHS()) { - + X = state->getSVal(Ex); - + // Handle undefined values. - + if (X.isUndef()) { MakeNode(Dst, B, Pred, state->BindExpr(B, X)); return; } - + // We took the RHS. Because the value of the '&&' or '||' expression must // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0 // or 1. Alternatively, we could take a lazy approach, and calculate this // value later when necessary. We don't have the machinery in place for // this right now, and since most logical expressions are used for branches, - // the payoff is not likely to be large. Instead, we do eager evaluation. + // the payoff is not likely to be large. Instead, we do eager evaluation. if (const GRState *newState = state->assume(X, true)) - MakeNode(Dst, B, Pred, + MakeNode(Dst, B, Pred, newState->BindExpr(B, ValMgr.makeIntVal(1U, B->getType()))); - + if (const GRState *newState = state->assume(X, false)) - MakeNode(Dst, B, Pred, + MakeNode(Dst, B, Pred, newState->BindExpr(B, ValMgr.makeIntVal(0U, B->getType()))); } else { // We took the LHS expression. Depending on whether we are '&&' or // '||' we know what the value of the expression is via properties of // the short-circuiting. - X = ValMgr.makeIntVal(B->getOpcode() == BinaryOperator::LAnd ? 0U : 1U, + X = ValMgr.makeIntVal(B->getOpcode() == BinaryOperator::LAnd ? 0U : 1U, B->getType()); MakeNode(Dst, B, Pred, state->BindExpr(B, X)); } } - + //===----------------------------------------------------------------------===// // Transfer functions: Loads and stores. //===----------------------------------------------------------------------===// -void GRExprEngine::VisitDeclRefExpr(DeclRefExpr *Ex, ExplodedNode *Pred, +void GRExprEngine::VisitDeclRefExpr(DeclRefExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst, bool asLValue) { - + const GRState* state = GetState(Pred); const NamedDecl* D = Ex->getDecl(); @@ -989,20 +989,20 @@ void GRExprEngine::VisitDeclRefExpr(DeclRefExpr *Ex, ExplodedNode *Pred, ProgramPoint::PostLValueKind); return; } - + assert (false && "ValueDecl support for this ValueDecl not implemented."); } /// VisitArraySubscriptExpr - Transfer function for array accesses -void GRExprEngine::VisitArraySubscriptExpr(ArraySubscriptExpr* A, +void GRExprEngine::VisitArraySubscriptExpr(ArraySubscriptExpr* A, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue){ - + Expr* Base = A->getBase()->IgnoreParens(); Expr* Idx = A->getIdx()->IgnoreParens(); ExplodedNodeSet Tmp; - + if (Base->getType()->isVectorType()) { // For vector types get its lvalue. // FIXME: This may not be correct. Is the rvalue of a vector its location? @@ -1010,13 +1010,13 @@ void GRExprEngine::VisitArraySubscriptExpr(ArraySubscriptExpr* A, // semantics. VisitLValue(Base, Pred, Tmp); } - else + else Visit(Base, Pred, Tmp); // Get Base's rvalue, which should be an LocVal. - + for (ExplodedNodeSet::iterator I1=Tmp.begin(), E1=Tmp.end(); I1!=E1; ++I1) { ExplodedNodeSet Tmp2; Visit(Idx, *I1, Tmp2); // Evaluate the index. - + for (ExplodedNodeSet::iterator I2=Tmp2.begin(),E2=Tmp2.end();I2!=E2; ++I2) { const GRState* state = GetState(*I2); SVal V = state->getLValue(A->getType(), state->getSVal(Base), @@ -1034,15 +1034,15 @@ void GRExprEngine::VisitArraySubscriptExpr(ArraySubscriptExpr* A, /// VisitMemberExpr - Transfer function for member expressions. void GRExprEngine::VisitMemberExpr(MemberExpr* M, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue) { - + Expr* Base = M->getBase()->IgnoreParens(); ExplodedNodeSet Tmp; - - if (M->isArrow()) + + if (M->isArrow()) Visit(Base, Pred, Tmp); // p->f = ... or ... = p->f else VisitLValue(Base, Pred, Tmp); // x.f = ... or ... = x.f - + FieldDecl *Field = dyn_cast(M->getMemberDecl()); if (!Field) // FIXME: skipping member expressions for non-fields return; @@ -1068,7 +1068,7 @@ void GRExprEngine::EvalBind(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, const GRState* state, SVal location, SVal Val) { const GRState* newState = 0; - + if (location.isUnknown()) { // We know that the new state will be the same as the old state since // the location of the binding is "unknown". Consequently, there @@ -1086,7 +1086,7 @@ void GRExprEngine::EvalBind(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, // doesn't do anything, just auto-propagate the current state. GRStmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, Pred, newState, Ex, newState != state); - + getTF().EvalBind(BuilderRef, location, Val); } @@ -1099,19 +1099,19 @@ void GRExprEngine::EvalBind(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, void GRExprEngine::EvalStore(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, const GRState* state, SVal location, SVal Val, const void *tag) { - + assert (Builder && "GRStmtNodeBuilder must be defined."); - + // Evaluate the location (checks for bad dereferences). Pred = EvalLocation(Ex, Pred, state, location, tag); - + if (!Pred) return; assert (!location.isUndef()); state = GetState(Pred); - // Proceed with the store. + // Proceed with the store. SaveAndRestore OldSPointKind(Builder->PointKind); SaveAndRestore OldTag(Builder->Tag); Builder->PointKind = ProgramPoint::PostStoreKind; @@ -1123,14 +1123,14 @@ void GRExprEngine::EvalLoad(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, const GRState* state, SVal location, const void *tag) { - // Evaluate the location (checks for bad dereferences). + // Evaluate the location (checks for bad dereferences). Pred = EvalLocation(Ex, Pred, state, location, tag); - + if (!Pred) return; - + state = GetState(Pred); - + // Proceed with the load. ProgramPoint::Kind K = ProgramPoint::PostLoadKind; @@ -1144,7 +1144,7 @@ void GRExprEngine::EvalLoad(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, } else { SVal V = state->getSVal(cast(location), Ex->getType()); - + // Casts can create weird scenarios where a location must be implicitly // converted to something else. For example: // @@ -1152,19 +1152,19 @@ void GRExprEngine::EvalLoad(ExplodedNodeSet& Dst, Expr* Ex, ExplodedNode* Pred, // int *y = (int*) &x; // void** -> int* cast. // invalidate(y); // 'x' now binds to a symbolic region // int z = *y; - // + // //if (isa(V) && !Loc::IsLocType(Ex->getType())) { // V = EvalCast(V, Ex->getType()); //} - + MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), K, tag); } } -void GRExprEngine::EvalStore(ExplodedNodeSet& Dst, Expr* Ex, Expr* StoreE, - ExplodedNode* Pred, const GRState* state, +void GRExprEngine::EvalStore(ExplodedNodeSet& Dst, Expr* Ex, Expr* StoreE, + ExplodedNode* Pred, const GRState* state, SVal location, SVal Val, const void *tag) { - + ExplodedNodeSet TmpDst; EvalStore(TmpDst, StoreE, Pred, state, location, Val, tag); @@ -1175,60 +1175,60 @@ void GRExprEngine::EvalStore(ExplodedNodeSet& Dst, Expr* Ex, Expr* StoreE, ExplodedNode* GRExprEngine::EvalLocation(Stmt* Ex, ExplodedNode* Pred, const GRState* state, SVal location, const void *tag) { - + SaveAndRestore OldTag(Builder->Tag); Builder->Tag = tag; - - // Check for loads/stores from/to undefined values. + + // Check for loads/stores from/to undefined values. if (location.isUndef()) { ExplodedNode* N = Builder->generateNode(Ex, state, Pred, ProgramPoint::PostUndefLocationCheckFailedKind); - + if (N) { N->markAsSink(); UndefDeref.insert(N); } - + return 0; } - + // Check for loads/stores from/to unknown locations. Treat as No-Ops. if (location.isUnknown()) return Pred; - + // During a load, one of two possible situations arise: // (1) A crash, because the location (pointer) was NULL. // (2) The location (pointer) is not NULL, and the dereference works. - // + // // We add these assumptions. - - Loc LV = cast(location); - + + Loc LV = cast(location); + // "Assume" that the pointer is not NULL. const GRState *StNotNull = state->assume(LV, true); - + // "Assume" that the pointer is NULL. const GRState *StNull = state->assume(LV, false); - if (StNull) { + if (StNull) { // Use the Generic Data Map to mark in the state what lval was null. const SVal* PersistentLV = getBasicVals().getPersistentSVal(LV); StNull = StNull->set(PersistentLV); - + // We don't use "MakeNode" here because the node will be a sink // and we have no intention of processing it later. ExplodedNode* NullNode = - Builder->generateNode(Ex, StNull, Pred, + Builder->generateNode(Ex, StNull, Pred, ProgramPoint::PostNullCheckFailedKind); - if (NullNode) { - NullNode->markAsSink(); + if (NullNode) { + NullNode->markAsSink(); if (StNotNull) ImplicitNullDeref.insert(NullNode); else ExplicitNullDeref.insert(NullNode); } } - + if (!StNotNull) return NULL; @@ -1245,9 +1245,9 @@ ExplodedNode* GRExprEngine::EvalLocation(Stmt* Ex, ExplodedNode* Pred, SVal NumElements = getStoreManager().getSizeInElements(StNotNull, ER->getSuperRegion()); - const GRState * StInBound = StNotNull->assumeInBound(Idx, NumElements, + const GRState * StInBound = StNotNull->assumeInBound(Idx, NumElements, true); - const GRState* StOutBound = StNotNull->assumeInBound(Idx, NumElements, + const GRState* StOutBound = StNotNull->assumeInBound(Idx, NumElements, false); if (StOutBound) { @@ -1273,7 +1273,7 @@ ExplodedNode* GRExprEngine::EvalLocation(Stmt* Ex, ExplodedNode* Pred, } } #endif - + // Generate a new node indicating the checks succeed. return Builder->generateNode(Ex, StNotNull, Pred, ProgramPoint::PostLocationChecksSucceedKind); @@ -1292,45 +1292,45 @@ ExplodedNode* GRExprEngine::EvalLocation(Stmt* Ex, ExplodedNode* Pred, static bool EvalOSAtomicCompareAndSwap(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, - CallExpr* CE, SVal L, + CallExpr* CE, SVal L, ExplodedNode* Pred) { // Not enough arguments to match OSAtomicCompareAndSwap? if (CE->getNumArgs() != 3) return false; - + ASTContext &C = Engine.getContext(); Expr *oldValueExpr = CE->getArg(0); QualType oldValueType = C.getCanonicalType(oldValueExpr->getType()); Expr *newValueExpr = CE->getArg(1); QualType newValueType = C.getCanonicalType(newValueExpr->getType()); - + // Do the types of 'oldValue' and 'newValue' match? if (oldValueType != newValueType) return false; - + Expr *theValueExpr = CE->getArg(2); const PointerType *theValueType = theValueExpr->getType()->getAs(); - + // theValueType not a pointer? if (!theValueType) return false; - + QualType theValueTypePointee = C.getCanonicalType(theValueType->getPointeeType()).getUnqualifiedType(); - + // The pointee must match newValueType and oldValueType. if (theValueTypePointee != newValueType) return false; - + static unsigned magic_load = 0; static unsigned magic_store = 0; const void *OSAtomicLoadTag = &magic_load; const void *OSAtomicStoreTag = &magic_store; - + // Load 'theValue'. const GRState *state = Pred->getState(); ExplodedNodeSet Tmp; @@ -1339,41 +1339,41 @@ static bool EvalOSAtomicCompareAndSwap(ExplodedNodeSet& Dst, for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { - + ExplodedNode *N = *I; const GRState *stateLoad = N->getState(); SVal theValueVal = stateLoad->getSVal(theValueExpr); SVal oldValueVal = stateLoad->getSVal(oldValueExpr); - + // FIXME: Issue an error. if (theValueVal.isUndef() || oldValueVal.isUndef()) { - return false; + return false; } - + SValuator &SVator = Engine.getSValuator(); - + // Perform the comparison. SVal Cmp = SVator.EvalBinOp(stateLoad, BinaryOperator::EQ, theValueVal, oldValueVal, Engine.getContext().IntTy); const GRState *stateEqual = stateLoad->assume(Cmp, true); - + // Were they equal? if (stateEqual) { // Perform the store. ExplodedNodeSet TmpStore; SVal val = stateEqual->getSVal(newValueExpr); - + // Handle implicit value casts. if (const TypedRegion *R = dyn_cast_or_null(location.getAsRegion())) { llvm::tie(state, val) = SVator.EvalCast(val, state, R->getValueType(C), newValueExpr->getType()); - } - - Engine.EvalStore(TmpStore, theValueExpr, N, stateEqual, location, + } + + Engine.EvalStore(TmpStore, theValueExpr, N, stateEqual, location, val, OSAtomicStoreTag); - + // Now bind the result of the comparison. for (ExplodedNodeSet::iterator I2 = TmpStore.begin(), E2 = TmpStore.end(); I2 != E2; ++I2) { @@ -1383,14 +1383,14 @@ static bool EvalOSAtomicCompareAndSwap(ExplodedNodeSet& Dst, Engine.MakeNode(Dst, CE, predNew, stateNew->BindExpr(CE, Res)); } } - + // Were they not equal? if (const GRState *stateNotEqual = stateLoad->assume(Cmp, false)) { SVal Res = Engine.getValueManager().makeTruthVal(false, CE->getType()); Engine.MakeNode(Dst, CE, N, stateNotEqual->BindExpr(CE, Res)); } } - + return true; } @@ -1404,7 +1404,7 @@ static bool EvalOSAtomic(ExplodedNodeSet& Dst, return false; const char *FName = FD->getNameAsCString(); - + // Check for compare and swap. if (strncmp(FName, "OSAtomicCompareAndSwap", 22) == 0 || strncmp(FName, "objc_atomicCompareAndSwap", 25) == 0) @@ -1418,12 +1418,12 @@ static bool EvalOSAtomic(ExplodedNodeSet& Dst, // Transfer function: Function calls. //===----------------------------------------------------------------------===// static void MarkNoReturnFunction(const FunctionDecl *FD, CallExpr *CE, - const GRState *state, + const GRState *state, GRStmtNodeBuilder *Builder) { if (!FD) return; - if (FD->getAttr() || + if (FD->getAttr() || FD->getAttr()) Builder->BuildSinks = true; else { @@ -1432,11 +1432,11 @@ static void MarkNoReturnFunction(const FunctionDecl *FD, CallExpr *CE, // potentially cache these results. const char* s = FD->getIdentifier()->getName(); unsigned n = strlen(s); - + switch (n) { default: break; - + case 4: if (!memcmp(s, "exit", 4)) Builder->BuildSinks = true; break; @@ -1460,37 +1460,37 @@ static void MarkNoReturnFunction(const FunctionDecl *FD, CallExpr *CE, Builder->BuildSinks = true; break; } - + // FIXME: This is just a wrapper around throwing an exception. // Eventually inter-procedural analysis should handle this easily. if (!memcmp(s, "ziperr", 6)) Builder->BuildSinks = true; break; - + case 7: if (!memcmp(s, "assfail", 7)) Builder->BuildSinks = true; break; - + case 8: - if (!memcmp(s ,"db_error", 8) || + if (!memcmp(s ,"db_error", 8) || !memcmp(s, "__assert", 8)) Builder->BuildSinks = true; break; - + case 12: if (!memcmp(s, "__assert_rtn", 12)) Builder->BuildSinks = true; break; - + case 13: if (!memcmp(s, "__assert_fail", 13)) Builder->BuildSinks = true; break; - + case 14: if (!memcmp(s, "dtrace_assfail", 14) || !memcmp(s, "yy_fatal_error", 14)) Builder->BuildSinks = true; break; - + case 26: if (!memcmp(s, "_XCAssertionFailureHandler", 26) || !memcmp(s, "_DTAssertionFailureHandler", 26) || @@ -1499,7 +1499,7 @@ static void MarkNoReturnFunction(const FunctionDecl *FD, CallExpr *CE, break; } - + } } @@ -1508,7 +1508,7 @@ bool GRExprEngine::EvalBuiltinFunction(const FunctionDecl *FD, CallExpr *CE, ExplodedNodeSet &Dst) { if (!FD) return false; - + unsigned id = FD->getBuiltinID(getContext()); if (!id) return false; @@ -1518,18 +1518,18 @@ bool GRExprEngine::EvalBuiltinFunction(const FunctionDecl *FD, CallExpr *CE, switch (id) { case Builtin::BI__builtin_expect: { // For __builtin_expect, just return the value of the subexpression. - assert (CE->arg_begin() != CE->arg_end()); + assert (CE->arg_begin() != CE->arg_end()); SVal X = state->getSVal(*(CE->arg_begin())); MakeNode(Dst, CE, Pred, state->BindExpr(CE, X)); return true; } - + case Builtin::BI__builtin_alloca: { // FIXME: Refactor into StoreManager itself? MemRegionManager& RM = getStateManager().getRegionManager(); const MemRegion* R = RM.getAllocaRegion(CE, Builder->getCurrentBlockCount()); - + // Set the extent of the region in bytes. This enables us to use the // SVal of the argument directly. If we save the extent in bits, we // cannot represent values like symbol*8. @@ -1543,22 +1543,21 @@ bool GRExprEngine::EvalBuiltinFunction(const FunctionDecl *FD, CallExpr *CE, return false; } -void GRExprEngine::EvalCall(ExplodedNodeSet& Dst, CallExpr* CE, SVal L, +void GRExprEngine::EvalCall(ExplodedNodeSet& Dst, CallExpr* CE, SVal L, ExplodedNode* Pred) { assert (Builder && "GRStmtNodeBuilder must be defined."); - + // FIXME: Allow us to chain together transfer functions. if (EvalOSAtomic(Dst, *this, *Builder, CE, L, Pred)) return; - + getTF().EvalCall(Dst, *this, *Builder, CE, L, Pred); } void GRExprEngine::VisitCall(CallExpr* CE, ExplodedNode* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, - ExplodedNodeSet& Dst) -{ + ExplodedNodeSet& Dst) { // Determine the type of function we're calling (if available). const FunctionProtoType *Proto = NULL; QualType FnType = CE->getCallee()->IgnoreParens()->getType(); @@ -1571,10 +1570,10 @@ void GRExprEngine::VisitCall(CallExpr* CE, ExplodedNode* Pred, void GRExprEngine::VisitCallRec(CallExpr* CE, ExplodedNode* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, - ExplodedNodeSet& Dst, - const FunctionProtoType *Proto, + ExplodedNodeSet& Dst, + const FunctionProtoType *Proto, unsigned ParamIdx) { - + // Process the arguments. if (AI != AE) { // If the call argument is being bound to a reference parameter, @@ -1583,17 +1582,17 @@ void GRExprEngine::VisitCallRec(CallExpr* CE, ExplodedNode* Pred, if (Proto && ParamIdx < Proto->getNumArgs()) VisitAsLvalue = Proto->getArgType(ParamIdx)->isReferenceType(); - ExplodedNodeSet DstTmp; + ExplodedNodeSet DstTmp; if (VisitAsLvalue) - VisitLValue(*AI, Pred, DstTmp); + VisitLValue(*AI, Pred, DstTmp); else - Visit(*AI, Pred, DstTmp); + Visit(*AI, Pred, DstTmp); ++AI; - + for (ExplodedNodeSet::iterator DI=DstTmp.begin(), DE=DstTmp.end(); DI != DE; ++DI) VisitCallRec(CE, *DI, AI, AE, Dst, Proto, ParamIdx + 1); - + return; } @@ -1601,17 +1600,17 @@ void GRExprEngine::VisitCallRec(CallExpr* CE, ExplodedNode* Pred, // the callee expression. ExplodedNodeSet DstTmp; Expr* Callee = CE->getCallee()->IgnoreParens(); - + { // Enter new scope to make the lifetime of 'DstTmp2' bounded. ExplodedNodeSet DstTmp2; Visit(Callee, Pred, DstTmp2); - + // Perform the previsit of the CallExpr, storing the results in DstTmp. CheckerVisit(CE, DstTmp, DstTmp2, true); } - + // Finally, evaluate the function call. - for (ExplodedNodeSet::iterator DI = DstTmp.begin(), DE = DstTmp.end(); + for (ExplodedNodeSet::iterator DI = DstTmp.begin(), DE = DstTmp.end(); DI != DE; ++DI) { const GRState* state = GetState(*DI); @@ -1621,25 +1620,25 @@ void GRExprEngine::VisitCallRec(CallExpr* CE, ExplodedNode* Pred, // function pointer values that are symbolic). // Check for the "noreturn" attribute. - + SaveAndRestore OldSink(Builder->BuildSinks); const FunctionDecl* FD = L.getAsFunctionDecl(); MarkNoReturnFunction(FD, CE, state, Builder); - + // Evaluate the call. if (EvalBuiltinFunction(FD, CE, *DI, Dst)) continue; - // Dispatch to the plug-in transfer function. - + // Dispatch to the plug-in transfer function. + unsigned size = Dst.size(); SaveOr OldHasGen(Builder->HasGeneratedNode); EvalCall(Dst, CE, L, *DI); - + // Handle the case where no nodes where generated. Auto-generate that // contains the updated state if we aren't generating sinks. - + if (!Builder->BuildSinks && Dst.size() == size && !Builder->HasGeneratedNode) MakeNode(Dst, CE, *DI, state); @@ -1656,31 +1655,31 @@ static std::pair EagerlyAssumeTag void GRExprEngine::EvalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, Expr *Ex) { for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { ExplodedNode *Pred = *I; - + // Test if the previous node was as the same expression. This can happen // when the expression fails to evaluate to anything meaningful and // (as an optimization) we don't generate a node. - ProgramPoint P = Pred->getLocation(); + ProgramPoint P = Pred->getLocation(); if (!isa(P) || cast(P).getStmt() != Ex) { - Dst.Add(Pred); + Dst.Add(Pred); continue; - } + } - const GRState* state = Pred->getState(); - SVal V = state->getSVal(Ex); + const GRState* state = Pred->getState(); + SVal V = state->getSVal(Ex); if (isa(V)) { // First assume that the condition is true. if (const GRState *stateTrue = state->assume(V, true)) { - stateTrue = stateTrue->BindExpr(Ex, + stateTrue = stateTrue->BindExpr(Ex, ValMgr.makeIntVal(1U, Ex->getType())); - Dst.Add(Builder->generateNode(PostStmtCustom(Ex, + Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag, Pred->getLocationContext()), stateTrue, Pred)); } - + // Next, assume that the condition is false. if (const GRState *stateFalse = state->assume(V, false)) { - stateFalse = stateFalse->BindExpr(Ex, + stateFalse = stateFalse->BindExpr(Ex, ValMgr.makeIntVal(0U, Ex->getType())); Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag, Pred->getLocationContext()), @@ -1699,16 +1698,16 @@ void GRExprEngine::EvalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, void GRExprEngine::VisitObjCIvarRefExpr(ObjCIvarRefExpr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue) { - + Expr* Base = cast(Ex->getBase()); ExplodedNodeSet Tmp; Visit(Base, Pred, Tmp); - + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); SVal BaseVal = state->getSVal(Base); SVal location = state->getLValue(Ex->getDecl(), BaseVal); - + if (asLValue) MakeNode(Dst, Ex, *I, state->BindExpr(Ex, location)); else @@ -1722,7 +1721,7 @@ void GRExprEngine::VisitObjCIvarRefExpr(ObjCIvarRefExpr* Ex, void GRExprEngine::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { - + // ObjCForCollectionStmts are processed in two places. This method // handles the case where an ObjCForCollectionStmt* occurs as one of the // statements within a basic block. This transfer function does two things: @@ -1734,7 +1733,7 @@ void GRExprEngine::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, // whether or not the container has any more elements. This value // will be tested in ProcessBranch. We need to explicitly bind // this value because a container can contain nil elements. - // + // // FIXME: Eventually this logic should actually do dispatches to // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration). // This will require simulating a temporary NSFastEnumerationState, either @@ -1747,10 +1746,10 @@ void GRExprEngine::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, // For now: simulate (1) by assigning either a symbol or nil if the // container is empty. Thus this transfer function will by default // result in state splitting. - + Stmt* elem = S->getElement(); SVal ElementV; - + if (DeclStmt* DS = dyn_cast(elem)) { VarDecl* ElemD = cast(DS->getSingleDecl()); assert (ElemD->getInit() == 0); @@ -1761,7 +1760,7 @@ void GRExprEngine::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, ExplodedNodeSet Tmp; VisitLValue(cast(elem), Pred, Tmp); - + for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); VisitObjCForCollectionStmtAux(S, *I, Dst, state->getSVal(elem)); @@ -1771,27 +1770,27 @@ void GRExprEngine::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, void GRExprEngine::VisitObjCForCollectionStmtAux(ObjCForCollectionStmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst, SVal ElementV) { - - + + // Get the current state. Use 'EvalLocation' to determine if it is a null // pointer, etc. Stmt* elem = S->getElement(); - + Pred = EvalLocation(elem, Pred, GetState(Pred), ElementV); if (!Pred) return; - + const GRState *state = GetState(Pred); // Handle the case where the container still has elements. SVal TrueV = ValMgr.makeTruthVal(1); const GRState *hasElems = state->BindExpr(S, TrueV); - + // Handle the case where the container has no elements. SVal FalseV = ValMgr.makeTruthVal(0); const GRState *noElems = state->BindExpr(S, FalseV); - + if (loc::MemRegionVal* MV = dyn_cast(&ElementV)) if (const TypedRegion* R = dyn_cast(MV->getRegion())) { // FIXME: The proper thing to do is to really iterate over the @@ -1805,10 +1804,10 @@ void GRExprEngine::VisitObjCForCollectionStmtAux(ObjCForCollectionStmt* S, hasElems = hasElems->bindLoc(ElementV, V); // Bind the location to 'nil' on the false branch. - SVal nilV = ValMgr.makeIntVal(0, T); - noElems = noElems->bindLoc(ElementV, nilV); + SVal nilV = ValMgr.makeIntVal(0, T); + noElems = noElems->bindLoc(ElementV, nilV); } - + // Create the new nodes. MakeNode(Dst, S, Pred, hasElems); MakeNode(Dst, S, Pred, noElems); @@ -1820,38 +1819,38 @@ void GRExprEngine::VisitObjCForCollectionStmtAux(ObjCForCollectionStmt* S, void GRExprEngine::VisitObjCMessageExpr(ObjCMessageExpr* ME, ExplodedNode* Pred, ExplodedNodeSet& Dst){ - + VisitObjCMessageExprArgHelper(ME, ME->arg_begin(), ME->arg_end(), Pred, Dst); -} +} void GRExprEngine::VisitObjCMessageExprArgHelper(ObjCMessageExpr* ME, ObjCMessageExpr::arg_iterator AI, ObjCMessageExpr::arg_iterator AE, ExplodedNode* Pred, ExplodedNodeSet& Dst) { if (AI == AE) { - + // Process the receiver. - + if (Expr* Receiver = ME->getReceiver()) { ExplodedNodeSet Tmp; Visit(Receiver, Pred, Tmp); - + for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitObjCMessageExprDispatchHelper(ME, *NI, Dst); - + return; } - + VisitObjCMessageExprDispatchHelper(ME, Pred, Dst); return; } - + ExplodedNodeSet Tmp; Visit(*AI, Pred, Tmp); - + ++AI; - + for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitObjCMessageExprArgHelper(ME, AI, AE, *NI, Dst); } @@ -1859,53 +1858,53 @@ void GRExprEngine::VisitObjCMessageExprArgHelper(ObjCMessageExpr* ME, void GRExprEngine::VisitObjCMessageExprDispatchHelper(ObjCMessageExpr* ME, ExplodedNode* Pred, ExplodedNodeSet& Dst) { - - // FIXME: More logic for the processing the method call. - + + // FIXME: More logic for the processing the method call. + const GRState* state = GetState(Pred); bool RaisesException = false; - - + + if (Expr* Receiver = ME->getReceiver()) { - + SVal L = state->getSVal(Receiver); - - // Check for undefined control-flow. + + // Check for undefined control-flow. if (L.isUndef()) { ExplodedNode* N = Builder->generateNode(ME, state, Pred); - + if (N) { N->markAsSink(); UndefReceivers.insert(N); } - + return; } - - // "Assume" that the receiver is not NULL. + + // "Assume" that the receiver is not NULL. const GRState *StNotNull = state->assume(L, true); - - // "Assume" that the receiver is NULL. + + // "Assume" that the receiver is NULL. const GRState *StNull = state->assume(L, false); - + if (StNull) { QualType RetTy = ME->getType(); - + // Check if the receiver was nil and the return value a struct. - if(RetTy->isRecordType()) { + if (RetTy->isRecordType()) { if (BR.getParentMap().isConsumedExpr(ME)) { // The [0 ...] expressions will return garbage. Flag either an // explicit or implicit error. Because of the structure of this // function we currently do not bifurfacte the state graph at // this point. // FIXME: We should bifurcate and fill the returned struct with - // garbage. + // garbage. if (ExplodedNode* N = Builder->generateNode(ME, StNull, Pred)) { N->markAsSink(); if (StNotNull) NilReceiverStructRetImplicit.insert(N); else - NilReceiverStructRetExplicit.insert(N); + NilReceiverStructRetExplicit.insert(N); } } } @@ -1918,13 +1917,13 @@ void GRExprEngine::VisitObjCMessageExprDispatchHelper(ObjCMessageExpr* ME, // sizeof(return type) const uint64_t returnTypeSize = Ctx.getTypeSize(ME->getType()); - if(voidPtrSize < returnTypeSize) { + if (voidPtrSize < returnTypeSize) { if (ExplodedNode* N = Builder->generateNode(ME, StNull, Pred)) { N->markAsSink(); - if(StNotNull) + if (StNotNull) NilReceiverLargerThanVoidPtrRetImplicit.insert(N); else - NilReceiverLargerThanVoidPtrRetExplicit.insert(N); + NilReceiverLargerThanVoidPtrRetExplicit.insert(N); } } else if (!StNotNull) { @@ -1952,99 +1951,99 @@ void GRExprEngine::VisitObjCMessageExprDispatchHelper(ObjCMessageExpr* ME, // of this method should assume that the receiver is not nil. if (!StNotNull) return; - + state = StNotNull; } - + // Check if the "raise" message was sent. if (ME->getSelector() == RaiseSel) RaisesException = true; } else { - + IdentifierInfo* ClsName = ME->getClassName(); Selector S = ME->getSelector(); - + // Check for special instance methods. - - if (!NSExceptionII) { + + if (!NSExceptionII) { ASTContext& Ctx = getContext(); - + NSExceptionII = &Ctx.Idents.get("NSException"); } - + if (ClsName == NSExceptionII) { - + enum { NUM_RAISE_SELECTORS = 2 }; - + // Lazily create a cache of the selectors. if (!NSExceptionInstanceRaiseSelectors) { - + ASTContext& Ctx = getContext(); - + NSExceptionInstanceRaiseSelectors = new Selector[NUM_RAISE_SELECTORS]; - + llvm::SmallVector II; unsigned idx = 0; - - // raise:format: + + // raise:format: II.push_back(&Ctx.Idents.get("raise")); - II.push_back(&Ctx.Idents.get("format")); + II.push_back(&Ctx.Idents.get("format")); NSExceptionInstanceRaiseSelectors[idx++] = - Ctx.Selectors.getSelector(II.size(), &II[0]); - - // raise:format::arguments: + Ctx.Selectors.getSelector(II.size(), &II[0]); + + // raise:format::arguments: II.push_back(&Ctx.Idents.get("arguments")); NSExceptionInstanceRaiseSelectors[idx++] = Ctx.Selectors.getSelector(II.size(), &II[0]); } - + for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) if (S == NSExceptionInstanceRaiseSelectors[i]) { RaisesException = true; break; } } } - + // Check for any arguments that are uninitialized/undefined. - + for (ObjCMessageExpr::arg_iterator I = ME->arg_begin(), E = ME->arg_end(); I != E; ++I) { - + if (state->getSVal(*I).isUndef()) { - + // Generate an error node for passing an uninitialized/undefined value // as an argument to a message expression. This node is a sink. ExplodedNode* N = Builder->generateNode(ME, state, Pred); - + if (N) { N->markAsSink(); MsgExprUndefArgs[N] = *I; } - + return; - } + } } - + // Check if we raise an exception. For now treat these as sinks. Eventually // we will want to handle exceptions properly. - + SaveAndRestore OldSink(Builder->BuildSinks); if (RaisesException) Builder->BuildSinks = true; - + // Dispatch to plug-in transfer function. - + unsigned size = Dst.size(); SaveOr OldHasGen(Builder->HasGeneratedNode); - + EvalObjCMessageExpr(Dst, ME, Pred); - + // Handle the case where no nodes where generated. Auto-generate that // contains the updated state if we aren't generating sinks. - + if (!Builder->BuildSinks && Dst.size() == size && !Builder->HasGeneratedNode) MakeNode(Dst, ME, Pred, state); } @@ -2065,9 +2064,9 @@ void GRExprEngine::VisitCast(Expr* CastE, Expr* Ex, ExplodedNode* Pred, Exploded VisitLValue(Ex, Pred, S1); else Visit(Ex, Pred, S1); - + // Check for casting to "void". - if (T->isVoidType()) { + if (T->isVoidType()) { for (ExplodedNodeSet::iterator I1 = S1.begin(), E1 = S1.end(); I1 != E1; ++I1) Dst.Add(*I1); @@ -2085,13 +2084,13 @@ void GRExprEngine::VisitCast(Expr* CastE, Expr* Ex, ExplodedNode* Pred, Exploded } void GRExprEngine::VisitCompoundLiteralExpr(CompoundLiteralExpr* CL, - ExplodedNode* Pred, - ExplodedNodeSet& Dst, + ExplodedNode* Pred, + ExplodedNodeSet& Dst, bool asLValue) { InitListExpr* ILE = cast(CL->getInitializer()->IgnoreParens()); ExplodedNodeSet Tmp; Visit(ILE, Pred, Tmp); - + for (ExplodedNodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I!=EI; ++I) { const GRState* state = GetState(*I); SVal ILV = state->getSVal(ILE); @@ -2105,15 +2104,15 @@ void GRExprEngine::VisitCompoundLiteralExpr(CompoundLiteralExpr* CL, } void GRExprEngine::VisitDeclStmt(DeclStmt *DS, ExplodedNode *Pred, - ExplodedNodeSet& Dst) { + ExplodedNodeSet& Dst) { - // The CFG has one DeclStmt per Decl. + // The CFG has one DeclStmt per Decl. Decl* D = *DS->decl_begin(); - + if (!D || !isa(D)) return; - - const VarDecl* VD = dyn_cast(D); + + const VarDecl* VD = dyn_cast(D); Expr* InitEx = const_cast(VD->getInit()); // FIXME: static variables may have an initializer, but the second @@ -2124,7 +2123,7 @@ void GRExprEngine::VisitDeclStmt(DeclStmt *DS, ExplodedNode *Pred, Visit(InitEx, Pred, Tmp); else Tmp.Add(Pred); - + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); unsigned Count = Builder->getCurrentBlockCount(); @@ -2133,58 +2132,58 @@ void GRExprEngine::VisitDeclStmt(DeclStmt *DS, ExplodedNode *Pred, QualType T = getContext().getCanonicalType(VD->getType()); if (VariableArrayType* VLA = dyn_cast(T)) { // FIXME: Handle multi-dimensional VLAs. - + Expr* SE = VLA->getSizeExpr(); SVal Size = state->getSVal(SE); - + if (Size.isUndef()) { if (ExplodedNode* N = Builder->generateNode(DS, state, Pred)) { - N->markAsSink(); + N->markAsSink(); ExplicitBadSizedVLA.insert(N); } continue; } - - const GRState* zeroState = state->assume(Size, false); + + const GRState* zeroState = state->assume(Size, false); state = state->assume(Size, true); - + if (zeroState) { if (ExplodedNode* N = Builder->generateNode(DS, zeroState, Pred)) { - N->markAsSink(); + N->markAsSink(); if (state) ImplicitBadSizedVLA.insert(N); else ExplicitBadSizedVLA.insert(N); } } - + if (!state) - continue; + continue; } - + // Decls without InitExpr are not initialized explicitly. const LocationContext *LC = (*I)->getLocationContext(); if (InitEx) { SVal InitVal = state->getSVal(InitEx); QualType T = VD->getType(); - + // Recover some path-sensitivity if a scalar value evaluated to // UnknownVal. - if (InitVal.isUnknown() || + if (InitVal.isUnknown() || !getConstraintManager().canReasonAbout(InitVal)) { InitVal = ValMgr.getConjuredSymbolVal(InitEx, Count); - } - + } + state = state->bindDecl(VD, LC, InitVal); - + // The next thing to do is check if the GRTransferFuncs object wants to // update the state based on the new binding. If the GRTransferFunc // object doesn't do anything, just auto-propagate the current state. GRStmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, state, DS,true); getTF().EvalBind(BuilderRef, loc::MemRegionVal(state->getRegion(VD, LC)), - InitVal); - } + InitVal); + } else { state = state->bindDeclWithNoInit(VD, LC); MakeNode(Dst, DS, *I, state); @@ -2200,7 +2199,7 @@ public: llvm::ImmutableList Vals; ExplodedNode* N; InitListExpr::reverse_iterator Itr; - + InitListWLItem(ExplodedNode* n, llvm::ImmutableList vals, InitListExpr::reverse_iterator itr) : Vals(vals), N(n), Itr(itr) {} @@ -2208,52 +2207,52 @@ public: } -void GRExprEngine::VisitInitListExpr(InitListExpr* E, ExplodedNode* Pred, +void GRExprEngine::VisitInitListExpr(InitListExpr* E, ExplodedNode* Pred, ExplodedNodeSet& Dst) { const GRState* state = GetState(Pred); QualType T = getContext().getCanonicalType(E->getType()); - unsigned NumInitElements = E->getNumInits(); + unsigned NumInitElements = E->getNumInits(); if (T->isArrayType() || T->isStructureType() || T->isUnionType() || T->isVectorType()) { llvm::ImmutableList StartVals = getBasicVals().getEmptySValList(); - + // Handle base case where the initializer has no elements. // e.g: static int* myArray[] = {}; if (NumInitElements == 0) { SVal V = ValMgr.makeCompoundVal(T, StartVals); MakeNode(Dst, E, Pred, state->BindExpr(E, V)); return; - } - + } + // Create a worklist to process the initializers. llvm::SmallVector WorkList; - WorkList.reserve(NumInitElements); - WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin())); + WorkList.reserve(NumInitElements); + WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin())); InitListExpr::reverse_iterator ItrEnd = E->rend(); - + // Process the worklist until it is empty. while (!WorkList.empty()) { InitListWLItem X = WorkList.back(); WorkList.pop_back(); - + ExplodedNodeSet Tmp; Visit(*X.Itr, X.N, Tmp); - + InitListExpr::reverse_iterator NewItr = X.Itr + 1; for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { // Get the last initializer value. state = GetState(*NI); SVal InitV = state->getSVal(cast(*X.Itr)); - + // Construct the new list of values by prepending the new value to // the already constructed list. llvm::ImmutableList NewVals = getBasicVals().consVals(InitV, X.Vals); - + if (NewItr == ItrEnd) { // Now we have a list holding all init values. Make CompoundValData. SVal V = ValMgr.makeCompoundVal(T, NewVals); @@ -2267,7 +2266,7 @@ void GRExprEngine::VisitInitListExpr(InitListExpr* E, ExplodedNode* Pred, } } } - + return; } @@ -2293,10 +2292,10 @@ void GRExprEngine::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr* Ex, ExplodedNode* Pred, ExplodedNodeSet& Dst) { QualType T = Ex->getTypeOfArgument(); - uint64_t amt; - + uint64_t amt; + if (Ex->isSizeOf()) { - if (T == getContext().VoidTy) { + if (T == getContext().VoidTy) { // sizeof(void) == 1 byte. amt = 1; } @@ -2307,17 +2306,17 @@ void GRExprEngine::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr* Ex, else if (T->isObjCInterfaceType()) { // Some code tries to take the sizeof an ObjCInterfaceType, relying that // the compiler has laid out its representation. Just report Unknown - // for these. + // for these. return; } else { // All other cases. amt = getContext().getTypeSize(T) / 8; - } + } } else // Get alignment of the type. amt = getContext().getTypeAlign(T) / 8; - + MakeNode(Dst, Ex, Pred, GetState(Pred)->BindExpr(Ex, ValMgr.makeIntVal(amt, Ex->getType()))); } @@ -2327,61 +2326,61 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, ExplodedNodeSet& Dst, bool asLValue) { switch (U->getOpcode()) { - + default: break; - + case UnaryOperator::Deref: { - + Expr* Ex = U->getSubExpr()->IgnoreParens(); ExplodedNodeSet Tmp; Visit(Ex, Pred, Tmp); - + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { - + const GRState* state = GetState(*I); SVal location = state->getSVal(Ex); - + if (asLValue) MakeNode(Dst, U, *I, state->BindExpr(U, location), ProgramPoint::PostLValueKind); else EvalLoad(Dst, U, *I, state, location); - } + } return; } - + case UnaryOperator::Real: { - + Expr* Ex = U->getSubExpr()->IgnoreParens(); ExplodedNodeSet Tmp; Visit(Ex, Pred, Tmp); - + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { - + // FIXME: We don't have complex SValues yet. if (Ex->getType()->isAnyComplexType()) { // Just report "Unknown." Dst.Add(*I); continue; } - + // For all other types, UnaryOperator::Real is an identity operation. assert (U->getType() == Ex->getType()); const GRState* state = GetState(*I); MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); - } - + } + return; } - + case UnaryOperator::Imag: { - + Expr* Ex = U->getSubExpr()->IgnoreParens(); ExplodedNodeSet Tmp; Visit(Ex, Pred, Tmp); - + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { // FIXME: We don't have complex SValues yet. if (Ex->getType()->isAnyComplexType()) { @@ -2389,25 +2388,25 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, Dst.Add(*I); continue; } - + // For all other types, UnaryOperator::Float returns 0. assert (Ex->getType()->isIntegerType()); const GRState* state = GetState(*I); SVal X = ValMgr.makeZeroVal(Ex->getType()); MakeNode(Dst, U, *I, state->BindExpr(U, X)); } - + return; } - - // FIXME: Just report "Unknown" for OffsetOf. + + // FIXME: Just report "Unknown" for OffsetOf. case UnaryOperator::OffsetOf: Dst.Add(Pred); return; - + case UnaryOperator::Plus: assert (!asLValue); // FALL-THROUGH. case UnaryOperator::Extension: { - + // Unary "+" is a no-op, similar to a parentheses. We still have places // where it may be a block-level expression, so we need to // generate an extra node that just propagates the value of the @@ -2416,44 +2415,44 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, Expr* Ex = U->getSubExpr()->IgnoreParens(); ExplodedNodeSet Tmp; Visit(Ex, Pred, Tmp); - - for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { + + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); } - + return; } - + case UnaryOperator::AddrOf: { - + assert(!asLValue); Expr* Ex = U->getSubExpr()->IgnoreParens(); ExplodedNodeSet Tmp; VisitLValue(Ex, Pred, Tmp); - - for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { + + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); SVal V = state->getSVal(Ex); state = state->BindExpr(U, V); MakeNode(Dst, U, *I, state); } - return; + return; } - + case UnaryOperator::LNot: case UnaryOperator::Minus: case UnaryOperator::Not: { - + assert (!asLValue); Expr* Ex = U->getSubExpr()->IgnoreParens(); ExplodedNodeSet Tmp; Visit(Ex, Pred, Tmp); - - for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { + + for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); - + // Get the value of the subexpression. SVal V = state->getSVal(Ex); @@ -2461,41 +2460,41 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, MakeNode(Dst, U, *I, state->BindExpr(U, V)); continue; } - + // QualType DstT = getContext().getCanonicalType(U->getType()); // QualType SrcT = getContext().getCanonicalType(Ex->getType()); -// +// // if (DstT != SrcT) // Perform promotions. -// V = EvalCast(V, DstT); -// +// V = EvalCast(V, DstT); +// // if (V.isUnknownOrUndef()) { // MakeNode(Dst, U, *I, BindExpr(St, U, V)); // continue; // } - + switch (U->getOpcode()) { default: assert(false && "Invalid Opcode."); break; - + case UnaryOperator::Not: // FIXME: Do we need to handle promotions? state = state->BindExpr(U, EvalComplement(cast(V))); - break; - + break; + case UnaryOperator::Minus: // FIXME: Do we need to handle promotions? state = state->BindExpr(U, EvalMinus(cast(V))); - break; - - case UnaryOperator::LNot: - + break; + + case UnaryOperator::LNot: + // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." // // Note: technically we do "E == 0", but this is the same in the // transfer functions as "0 == E". SVal Result; - + if (isa(V)) { Loc X = ValMgr.makeNull(); Result = EvalBinOp(state, BinaryOperator::EQ, cast(V), X, @@ -2506,15 +2505,15 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, Result = EvalBinOp(BinaryOperator::EQ, cast(V), X, U->getType()); } - + state = state->BindExpr(U, Result); - + break; } - + MakeNode(Dst, U, *I, state); } - + return; } } @@ -2525,28 +2524,28 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, ExplodedNodeSet Tmp; Expr* Ex = U->getSubExpr()->IgnoreParens(); VisitLValue(Ex, Pred, Tmp); - + for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { - + const GRState* state = GetState(*I); SVal V1 = state->getSVal(Ex); - - // Perform a load. + + // Perform a load. ExplodedNodeSet Tmp2; EvalLoad(Tmp2, Ex, *I, state, V1); for (ExplodedNodeSet::iterator I2 = Tmp2.begin(), E2 = Tmp2.end(); I2!=E2; ++I2) { - + state = GetState(*I2); SVal V2 = state->getSVal(Ex); - - // Propagate unknown and undefined values. + + // Propagate unknown and undefined values. if (V2.isUnknownOrUndef()) { MakeNode(Dst, U, *I2, state->BindExpr(U, V2)); continue; } - - // Handle all other values. + + // Handle all other values. BinaryOperator::Opcode Op = U->isIncrementOp() ? BinaryOperator::Add : BinaryOperator::Sub; @@ -2560,37 +2559,37 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, else RHS = ValMgr.makeIntVal(1, U->getType()); - SVal Result = EvalBinOp(state, Op, V2, RHS, U->getType()); - + SVal Result = EvalBinOp(state, Op, V2, RHS, U->getType()); + // Conjure a new symbol if necessary to recover precision. if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){ Result = ValMgr.getConjuredSymbolVal(Ex, Builder->getCurrentBlockCount()); - + // If the value is a location, ++/-- should always preserve // non-nullness. Check if the original value was non-null, and if so - // propagate that constraint. + // propagate that constraint. if (Loc::IsLocType(U->getType())) { SVal Constraint = EvalBinOp(state, BinaryOperator::EQ, V2, ValMgr.makeZeroVal(U->getType()), - getContext().IntTy); - + getContext().IntTy); + if (!state->assume(Constraint, true)) { // It isn't feasible for the original value to be null. // Propagate this constraint. Constraint = EvalBinOp(state, BinaryOperator::EQ, Result, ValMgr.makeZeroVal(U->getType()), getContext().IntTy); - + state = state->assume(Constraint, false); assert(state); - } - } + } + } } - + state = state->BindExpr(U, U->isPostfix() ? V2 : Result); - // Perform the store. + // Perform the store. EvalStore(Dst, U, *I2, state, V1, Result); } } @@ -2598,7 +2597,7 @@ void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, ExplodedNode* Pred, void GRExprEngine::VisitAsmStmt(AsmStmt* A, ExplodedNode* Pred, ExplodedNodeSet& Dst) { VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst); -} +} void GRExprEngine::VisitAsmStmtHelperOutputs(AsmStmt* A, AsmStmt::outputs_iterator I, @@ -2608,12 +2607,12 @@ void GRExprEngine::VisitAsmStmtHelperOutputs(AsmStmt* A, VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst); return; } - + ExplodedNodeSet Tmp; VisitLValue(*I, Pred, Tmp); - + ++I; - + for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst); } @@ -2623,35 +2622,35 @@ void GRExprEngine::VisitAsmStmtHelperInputs(AsmStmt* A, AsmStmt::inputs_iterator E, ExplodedNode* Pred, ExplodedNodeSet& Dst) { if (I == E) { - + // We have processed both the inputs and the outputs. All of the outputs // should evaluate to Locs. Nuke all of their values. - + // FIXME: Some day in the future it would be nice to allow a "plug-in" // which interprets the inline asm and stores proper results in the // outputs. - + const GRState* state = GetState(Pred); - + for (AsmStmt::outputs_iterator OI = A->begin_outputs(), OE = A->end_outputs(); OI != OE; ++OI) { - - SVal X = state->getSVal(*OI); + + SVal X = state->getSVal(*OI); assert (!isa(X)); // Should be an Lval, or unknown, undef. - + if (isa(X)) state = state->bindLoc(cast(X), UnknownVal()); } - + MakeNode(Dst, A, Pred, state); return; } - + ExplodedNodeSet Tmp; Visit(*I, Pred, Tmp); - + ++I; - + for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI) VisitAsmStmtHelperInputs(A, I, E, *NI, Dst); } @@ -2659,16 +2658,16 @@ void GRExprEngine::VisitAsmStmtHelperInputs(AsmStmt* A, void GRExprEngine::EvalReturn(ExplodedNodeSet& Dst, ReturnStmt* S, ExplodedNode* Pred) { assert (Builder && "GRStmtNodeBuilder must be defined."); - - unsigned size = Dst.size(); + + unsigned size = Dst.size(); SaveAndRestore OldSink(Builder->BuildSinks); SaveOr OldHasGen(Builder->HasGeneratedNode); getTF().EvalReturn(Dst, *this, *Builder, S, Pred); - + // Handle the case where no nodes where generated. - + if (!Builder->BuildSinks && Dst.size() == size && !Builder->HasGeneratedNode) MakeNode(Dst, S, Pred, GetState(Pred)); } @@ -2677,7 +2676,7 @@ void GRExprEngine::VisitReturnStmt(ReturnStmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst) { Expr* R = S->getRetValue(); - + if (!R) { EvalReturn(Dst, S, Pred); return; @@ -2688,12 +2687,12 @@ void GRExprEngine::VisitReturnStmt(ReturnStmt* S, ExplodedNode* Pred, for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { SVal X = (*I)->getState()->getSVal(R); - + // Check if we return the address of a stack variable. if (isa(X)) { // Determine if the value is on the stack. const MemRegion* R = cast(&X)->getRegion(); - + if (R && R->hasStackStorage()) { // Create a special node representing the error. if (ExplodedNode* N = Builder->generateNode(S, GetState(*I), *I)) { @@ -2711,7 +2710,7 @@ void GRExprEngine::VisitReturnStmt(ReturnStmt* S, ExplodedNode* Pred, } continue; } - + EvalReturn(Dst, S, *I); } } @@ -2727,13 +2726,13 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, ExplodedNodeSet Tmp1; Expr* LHS = B->getLHS()->IgnoreParens(); Expr* RHS = B->getRHS()->IgnoreParens(); - + // FIXME: Add proper support for ObjCImplicitSetterGetterRefExpr. if (isa(LHS)) { - Visit(RHS, Pred, Dst); + Visit(RHS, Pred, Dst); return; } - + if (B->isAssignmentOp()) VisitLValue(LHS, Pred, Tmp1); else @@ -2742,18 +2741,18 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) { SVal LeftV = (*I1)->getState()->getSVal(LHS); - + // Process the RHS. - + ExplodedNodeSet Tmp2; Visit(RHS, *I1, Tmp2); ExplodedNodeSet CheckedSet; CheckerVisit(B, CheckedSet, Tmp2, true); - + // With both the LHS and RHS evaluated, process the operation itself. - - for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end(); + + for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end(); I2 != E2; ++I2) { const GRState* state = GetState(*I2); @@ -2761,41 +2760,41 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, SVal RightV = state->getSVal(RHS); BinaryOperator::Opcode Op = B->getOpcode(); - + switch (Op) { - + case BinaryOperator::Assign: { - + // EXPERIMENTAL: "Conjured" symbols. // FIXME: Handle structs. QualType T = RHS->getType(); - - if ((RightV.isUnknown() || - !getConstraintManager().canReasonAbout(RightV)) - && (Loc::IsLocType(T) || + + if ((RightV.isUnknown() || + !getConstraintManager().canReasonAbout(RightV)) + && (Loc::IsLocType(T) || (T->isScalarType() && T->isIntegerType()))) { - unsigned Count = Builder->getCurrentBlockCount(); + unsigned Count = Builder->getCurrentBlockCount(); RightV = ValMgr.getConjuredSymbolVal(B->getRHS(), Count); } - + // Simulate the effects of a "store": bind the value of the RHS - // to the L-Value represented by the LHS. - EvalStore(Dst, B, LHS, *I2, state->BindExpr(B, RightV), + // to the L-Value represented by the LHS. + EvalStore(Dst, B, LHS, *I2, state->BindExpr(B, RightV), LeftV, RightV); continue; } - + // FALL-THROUGH. default: { - + if (B->isAssignmentOp()) break; - + // Process non-assignments except commas or short-circuited - // logical expressions (LAnd and LOr). + // logical expressions (LAnd and LOr). SVal Result = EvalBinOp(state, Op, LeftV, RightV, B->getType()); - + if (Result.isUnknown()) { if (OldSt != state) { // Generate a new node if we have already created a new state. @@ -2803,30 +2802,30 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, } else Dst.Add(*I2); - + continue; } - + if (Result.isUndef() && !LeftV.isUndef() && !RightV.isUndef()) { - + // The operands were *not* undefined, but the result is undefined. // This is a special node that should be flagged as an error. - + if (ExplodedNode* UndefNode = Builder->generateNode(B, state, *I2)){ - UndefNode->markAsSink(); + UndefNode->markAsSink(); UndefResults.insert(UndefNode); } - + continue; } - + // Otherwise, create a new node. - + MakeNode(Dst, B, *I2, state->BindExpr(B, Result)); continue; } } - + assert (B->isCompoundAssignmentOp()); switch (Op) { @@ -2843,26 +2842,26 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, case BinaryOperator::XorAssign: Op = BinaryOperator::Xor; break; case BinaryOperator::OrAssign: Op = BinaryOperator::Or; break; } - + // Perform a load (the LHS). This performs the checks for // null dereferences, and so on. ExplodedNodeSet Tmp3; SVal location = state->getSVal(LHS); EvalLoad(Tmp3, LHS, *I2, state, location); - - for (ExplodedNodeSet::iterator I3=Tmp3.begin(), E3=Tmp3.end(); I3!=E3; + + for (ExplodedNodeSet::iterator I3=Tmp3.begin(), E3=Tmp3.end(); I3!=E3; ++I3) { - + state = GetState(*I3); SVal V = state->getSVal(LHS); - // Propagate undefined values (left-side). + // Propagate undefined values (left-side). if (V.isUndef()) { - EvalStore(Dst, B, LHS, *I3, state->BindExpr(B, V), + EvalStore(Dst, B, LHS, *I3, state->BindExpr(B, V), location, V); continue; } - + // Propagate unknown values (left and right-side). if (RightV.isUnknown() || V.isUnknown()) { EvalStore(Dst, B, LHS, *I3, state->BindExpr(B, UnknownVal()), @@ -2874,7 +2873,7 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, // // The LHS is not Undef/Unknown. // The RHS is not Unknown. - + // Get the computation type. QualType CTy = cast(B)->getComputationResultType(); @@ -2890,24 +2889,24 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, // Promote LHS. llvm::tie(state, V) = SVator.EvalCast(V, state, CLHSTy, LTy); - // Evaluate operands and promote to result type. - if (RightV.isUndef()) { - // Propagate undefined values (right-side). + // Evaluate operands and promote to result type. + if (RightV.isUndef()) { + // Propagate undefined values (right-side). EvalStore(Dst, B, LHS, *I3, state->BindExpr(B, RightV), location, RightV); continue; } - - // Compute the result of the operation. + + // Compute the result of the operation. SVal Result; llvm::tie(state, Result) = SVator.EvalCast(EvalBinOp(state, Op, V, RightV, CTy), state, B->getType(), CTy); - + if (Result.isUndef()) { // The operands were not undefined, but the result is undefined. if (ExplodedNode* UndefNode = Builder->generateNode(B, state, *I3)) { - UndefNode->markAsSink(); + UndefNode->markAsSink(); UndefResults.insert(UndefNode); } continue; @@ -2915,21 +2914,21 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, // EXPERIMENTAL: "Conjured" symbols. // FIXME: Handle structs. - + SVal LHSVal; - - if ((Result.isUnknown() || + + if ((Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)) - && (Loc::IsLocType(CTy) + && (Loc::IsLocType(CTy) || (CTy->isScalarType() && CTy->isIntegerType()))) { - + unsigned Count = Builder->getCurrentBlockCount(); - + // The symbolic value is actually for the type of the left-hand side // expression, not the computation type, as this is the value the // LValue on the LHS will bind to. LHSVal = ValMgr.getConjuredSymbolVal(B->getRHS(), LTy, Count); - + // However, we need to convert the symbol to the computation type. llvm::tie(state, Result) = SVator.EvalCast(LHSVal, state, CTy, LTy); } @@ -2938,8 +2937,8 @@ void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, // computation type. llvm::tie(state, LHSVal) = SVator.EvalCast(Result, state, LTy, CTy); } - - EvalStore(Dst, B, LHS, *I3, state->BindExpr(B, Result), + + EvalStore(Dst, B, LHS, *I3, state->BindExpr(B, Result), location, LHSVal); } } @@ -2958,9 +2957,9 @@ namespace llvm { template<> struct VISIBILITY_HIDDEN DOTGraphTraits : public DefaultDOTGraphTraits { - + static std::string getNodeAttributes(const ExplodedNode* N, void*) { - + if (GraphPrintCheckerState->isImplicitNullDeref(N) || GraphPrintCheckerState->isExplicitNullDeref(N) || GraphPrintCheckerState->isUndefDeref(N) || @@ -2972,50 +2971,50 @@ struct VISIBILITY_HIDDEN DOTGraphTraits : GraphPrintCheckerState->isBadCall(N) || GraphPrintCheckerState->isUndefArg(N)) return "color=\"red\",style=\"filled\""; - + if (GraphPrintCheckerState->isNoReturnCall(N)) return "color=\"blue\",style=\"filled\""; - + return ""; } - + static std::string getNodeLabel(const ExplodedNode* N, void*,bool ShortNames){ - + std::string sbuf; llvm::raw_string_ostream Out(sbuf); // Program Location. ProgramPoint Loc = N->getLocation(); - + switch (Loc.getKind()) { case ProgramPoint::BlockEntranceKind: - Out << "Block Entrance: B" + Out << "Block Entrance: B" << cast(Loc).getBlock()->getBlockID(); break; - + case ProgramPoint::BlockExitKind: assert (false); break; - + default: { if (StmtPoint *L = dyn_cast(&Loc)) { const Stmt* S = L->getStmt(); SourceLocation SLoc = S->getLocStart(); - Out << S->getStmtClassName() << ' ' << (void*) S << ' '; + Out << S->getStmtClassName() << ' ' << (void*) S << ' '; LangOptions LO; // FIXME. S->printPretty(Out, 0, PrintingPolicy(LO)); - - if (SLoc.isFileID()) { + + if (SLoc.isFileID()) { Out << "\\lline=" << GraphPrintSourceManager->getInstantiationLineNumber(SLoc) << " col=" << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc) << "\\l"; } - + if (isa(Loc)) - Out << "\\lPreStmt\\l;"; + Out << "\\lPreStmt\\l;"; else if (isa(Loc)) Out << "\\lPostLoad\\l;"; else if (isa(Loc)) @@ -3026,7 +3025,7 @@ struct VISIBILITY_HIDDEN DOTGraphTraits : Out << "\\lPostLocationChecksSucceed\\l"; else if (isa(Loc)) Out << "\\lPostNullCheckFailed\\l"; - + if (GraphPrintCheckerState->isImplicitNullDeref(N)) Out << "\\|Implicit-Null Dereference.\\l"; else if (GraphPrintCheckerState->isExplicitNullDeref(N)) @@ -3047,43 +3046,43 @@ struct VISIBILITY_HIDDEN DOTGraphTraits : Out << "\\|Call to NULL/Undefined."; else if (GraphPrintCheckerState->isUndefArg(N)) Out << "\\|Argument in call is undefined"; - + break; } const BlockEdge& E = cast(Loc); Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" << E.getDst()->getBlockID() << ')'; - + if (Stmt* T = E.getSrc()->getTerminator()) { - + SourceLocation SLoc = T->getLocStart(); - + Out << "\\|Terminator: "; LangOptions LO; // FIXME. E.getSrc()->printTerminator(Out, LO); - + if (SLoc.isFileID()) { Out << "\\lline=" << GraphPrintSourceManager->getInstantiationLineNumber(SLoc) << " col=" << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc); } - + if (isa(T)) { Stmt* Label = E.getDst()->getLabel(); - - if (Label) { + + if (Label) { if (CaseStmt* C = dyn_cast(Label)) { Out << "\\lcase "; LangOptions LO; // FIXME. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); - + if (Stmt* RHS = C->getRHS()) { Out << " .. "; RHS->printPretty(Out, 0, PrintingPolicy(LO)); } - + Out << ":"; } else { @@ -3091,7 +3090,7 @@ struct VISIBILITY_HIDDEN DOTGraphTraits : Out << "\\ldefault:"; } } - else + else Out << "\\l(implicit) default:"; } else if (isa(T)) { @@ -3102,28 +3101,28 @@ struct VISIBILITY_HIDDEN DOTGraphTraits : if (*E.getSrc()->succ_begin() == E.getDst()) Out << "true"; else - Out << "false"; + Out << "false"; } - + Out << "\\l"; } - + if (GraphPrintCheckerState->isUndefControlFlow(N)) { Out << "\\|Control-flow based on\\lUndefined value.\\l"; } } } - + Out << "\\|StateID: " << (void*) N->getState() << "\\|"; const GRState *state = N->getState(); state->printDOT(Out); - + Out << "\\l"; return Out.str(); } }; -} // end llvm namespace +} // end llvm namespace #endif #ifndef NDEBUG @@ -3138,7 +3137,7 @@ GetGraphNode::iterator> #endif void GRExprEngine::ViewGraph(bool trim) { -#ifndef NDEBUG +#ifndef NDEBUG if (trim) { std::vector Src; @@ -3150,14 +3149,14 @@ void GRExprEngine::ViewGraph(bool trim) { // Iterate through the reports and get their nodes. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) { for (BugType::const_iterator I2=(*I)->begin(), E2=(*I)->end(); - I2!=E2; ++I2) { + I2!=E2; ++I2) { const BugReportEquivClass& EQ = *I2; const BugReport &R = **EQ.begin(); ExplodedNode *N = const_cast(R.getEndNode()); if (N) Src.push_back(N); } } - + ViewGraph(&Src[0], &Src[0]+Src.size()); } else { @@ -3165,7 +3164,7 @@ void GRExprEngine::ViewGraph(bool trim) { GraphPrintSourceManager = &getContext().getSourceManager(); llvm::ViewGraph(*G.roots_begin(), "GRExprEngine"); - + GraphPrintCheckerState = NULL; GraphPrintSourceManager = NULL; } @@ -3176,14 +3175,14 @@ void GRExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { #ifndef NDEBUG GraphPrintCheckerState = this; GraphPrintSourceManager = &getContext().getSourceManager(); - + std::auto_ptr TrimmedG(G.Trim(Beg, End).first); if (!TrimmedG.get()) llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; else - llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedGRExprEngine"); - + llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedGRExprEngine"); + GraphPrintCheckerState = NULL; GraphPrintSourceManager = NULL; #endif diff --git a/clang/lib/Analysis/GRExprEngineInternalChecks.cpp b/clang/lib/Analysis/GRExprEngineInternalChecks.cpp index ab19a6a94a3153ca9c7584561ffc486b52ec4a01..ab6874ad60db157c868057330d6703319a8b28c2 100644 --- a/clang/lib/Analysis/GRExprEngineInternalChecks.cpp +++ b/clang/lib/Analysis/GRExprEngineInternalChecks.cpp @@ -48,15 +48,15 @@ public: BuiltinBugReport(BugType& bt, const char* desc, ExplodedNode *n) : RangedBugReport(bt, desc, n) {} - + BuiltinBugReport(BugType& bt, const char *shortDesc, const char *desc, ExplodedNode *n) - : RangedBugReport(bt, shortDesc, desc, n) {} - + : RangedBugReport(bt, shortDesc, desc, n) {} + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N); -}; - +}; + class VISIBILITY_HIDDEN BuiltinBug : public BugType { GRExprEngine &Eng; protected: @@ -69,30 +69,30 @@ public: : BugType(n, "Logic errors"), Eng(*eng), desc(n) {} const std::string &getDescription() const { return desc; } - + virtual void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) {} void FlushReports(BugReporter& BR) { FlushReportsImpl(BR, Eng); } - + virtual void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) {} - + template void Emit(BugReporter& BR, ITER I, ITER E); }; - - + + template void BuiltinBug::Emit(BugReporter& BR, ITER I, ITER E) { for (; I != E; ++I) BR.EmitReport(new BuiltinBugReport(*this, desc.c_str(), GetNode(I))); -} +} void BuiltinBugReport::registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N) { static_cast(getBugType()).registerInitialVisitors(BRC, N, this); -} - +} + class VISIBILITY_HIDDEN NullDeref : public BuiltinBug { public: NullDeref(GRExprEngine* eng) @@ -101,14 +101,14 @@ public: void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.null_derefs_begin(), Eng.null_derefs_end()); } - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { registerTrackNullOrUndefValue(BRC, GetDerefExpr(N), N); } }; - + class VISIBILITY_HIDDEN NilReceiverStructRet : public BuiltinBug { public: NilReceiverStructRet(GRExprEngine* eng) : @@ -133,7 +133,7 @@ public: BR.EmitReport(R); } } - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { @@ -146,12 +146,12 @@ public: NilReceiverLargerThanVoidPtrRet(GRExprEngine* eng) : BuiltinBug(eng, "'nil' receiver with return type larger than sizeof(void *)") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::nil_receiver_larger_than_voidptr_ret_iterator I=Eng.nil_receiver_larger_than_voidptr_ret_begin(), E=Eng.nil_receiver_larger_than_voidptr_ret_end(); I!=E; ++I) { - + std::string sbuf; llvm::raw_string_ostream os(sbuf); PostStmt P = cast((*I)->getLocation()); @@ -162,28 +162,28 @@ public: << "' and of size " << Eng.getContext().getTypeSize(ME->getType()) / 8 << " bytes) to be garbage or otherwise undefined."; - + BuiltinBugReport *R = new BuiltinBugReport(*this, os.str().c_str(), *I); R->addRange(ME->getReceiver()->getSourceRange()); BR.EmitReport(R); } - } + } void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { registerTrackNullOrUndefValue(BRC, GetReceiverExpr(N), N); } }; - + class VISIBILITY_HIDDEN UndefinedDeref : public BuiltinBug { public: UndefinedDeref(GRExprEngine* eng) : BuiltinBug(eng,"Dereference of undefined pointer value") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.undef_derefs_begin(), Eng.undef_derefs_end()); } - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { @@ -196,30 +196,30 @@ public: DivZero(GRExprEngine* eng = 0) : BuiltinBug(eng,"Division-by-zero", "Division by zero or undefined value.") {} - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { registerTrackNullOrUndefValue(BRC, GetDenomExpr(N), N); } }; - + class VISIBILITY_HIDDEN UndefResult : public BuiltinBug { public: UndefResult(GRExprEngine* eng) : BuiltinBug(eng,"Undefined result", "Result of operation is undefined.") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.undef_results_begin(), Eng.undef_results_end()); } }; - + class VISIBILITY_HIDDEN BadCall : public BuiltinBug { public: BadCall(GRExprEngine *eng = 0) : BuiltinBug(eng, "Invalid function call", "Called function pointer is a null or undefined pointer value") {} - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { @@ -234,57 +234,57 @@ public: ArgReport(BugType& bt, const char* desc, ExplodedNode *n, const Stmt *arg) : BuiltinBugReport(bt, desc, n), Arg(arg) {} - + ArgReport(BugType& bt, const char *shortDesc, const char *desc, ExplodedNode *n, const Stmt *arg) - : BuiltinBugReport(bt, shortDesc, desc, n), Arg(arg) {} - - const Stmt *getArg() const { return Arg; } + : BuiltinBugReport(bt, shortDesc, desc, n), Arg(arg) {} + + const Stmt *getArg() const { return Arg; } }; class VISIBILITY_HIDDEN BadArg : public BuiltinBug { -public: - BadArg(GRExprEngine* eng=0) : BuiltinBug(eng,"Uninitialized argument", +public: + BadArg(GRExprEngine* eng=0) : BuiltinBug(eng,"Uninitialized argument", "Pass-by-value argument in function call is undefined.") {} BadArg(GRExprEngine* eng, const char* d) : BuiltinBug(eng,"Uninitialized argument", d) {} - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { registerTrackNullOrUndefValue(BRC, static_cast(R)->getArg(), N); - } + } }; - + class VISIBILITY_HIDDEN BadMsgExprArg : public BadArg { public: - BadMsgExprArg(GRExprEngine* eng) + BadMsgExprArg(GRExprEngine* eng) : BadArg(eng,"Pass-by-value argument in message expression is undefined"){} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::UndefArgsTy::iterator I=Eng.msg_expr_undef_arg_begin(), - E = Eng.msg_expr_undef_arg_end(); I!=E; ++I) { + E = Eng.msg_expr_undef_arg_end(); I!=E; ++I) { // Generate a report for this bug. ArgReport *report = new ArgReport(*this, desc.c_str(), I->first, I->second); report->addRange(I->second->getSourceRange()); BR.EmitReport(report); - } - } + } + } }; - + class VISIBILITY_HIDDEN BadReceiver : public BuiltinBug { -public: +public: BadReceiver(GRExprEngine* eng) : BuiltinBug(eng,"Uninitialized receiver", "Receiver in message expression is an uninitialized value") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::ErrorNodes::iterator I=Eng.undef_receivers_begin(), End = Eng.undef_receivers_end(); I!=End; ++I) { - + // Generate a report for this bug. BuiltinBugReport *report = new BuiltinBugReport(*this, desc.c_str(), *I); ExplodedNode* N = *I; @@ -300,14 +300,14 @@ public: const ExplodedNode* N, BuiltinBugReport *R) { registerTrackNullOrUndefValue(BRC, GetReceiverExpr(N), N); - } + } }; class VISIBILITY_HIDDEN RetStack : public BuiltinBug { public: RetStack(GRExprEngine* eng) : BuiltinBug(eng, "Return of address to stack-allocated memory") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::ret_stackaddr_iterator I=Eng.ret_stackaddr_begin(), End = Eng.ret_stackaddr_end(); I!=End; ++I) { @@ -316,42 +316,42 @@ public: const Stmt *S = cast(N->getLocation()).getStmt(); const Expr* E = cast(S)->getRetValue(); assert(E && "Return expression cannot be NULL"); - + // Get the value associated with E. loc::MemRegionVal V = cast(N->getState()->getSVal(E)); - + // Generate a report for this bug. std::string buf; llvm::raw_string_ostream os(buf); SourceRange R; - + // Check if the region is a compound literal. - if (const CompoundLiteralRegion* CR = + if (const CompoundLiteralRegion* CR = dyn_cast(V.getRegion())) { - + const CompoundLiteralExpr* CL = CR->getLiteralExpr(); os << "Address of stack memory associated with a compound literal " "declared on line " << BR.getSourceManager() .getInstantiationLineNumber(CL->getLocStart()) << " returned."; - + R = CL->getSourceRange(); } else if (const AllocaRegion* AR = dyn_cast(V.getRegion())) { const Expr* ARE = AR->getExpr(); SourceLocation L = ARE->getLocStart(); R = ARE->getSourceRange(); - + os << "Address of stack memory allocated by call to alloca() on line " << BR.getSourceManager().getInstantiationLineNumber(L) << " returned."; - } - else { + } + else { os << "Address of stack memory associated with local variable '" << V.getRegion()->getString() << "' returned."; } - + RangedBugReport *report = new RangedBugReport(*this, os.str().c_str(), N); report->addRange(E->getSourceRange()); if (R.isValid()) report->addRange(R); @@ -359,51 +359,51 @@ public: } } }; - + class VISIBILITY_HIDDEN RetUndef : public BuiltinBug { public: RetUndef(GRExprEngine* eng) : BuiltinBug(eng, "Uninitialized return value", "Uninitialized or undefined value returned to caller.") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.ret_undef_begin(), Eng.ret_undef_end()); } - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { registerTrackNullOrUndefValue(BRC, GetRetValExpr(N), N); - } + } }; class VISIBILITY_HIDDEN UndefBranch : public BuiltinBug { struct VISIBILITY_HIDDEN FindUndefExpr { GRStateManager& VM; const GRState* St; - + FindUndefExpr(GRStateManager& V, const GRState* S) : VM(V), St(S) {} - - Expr* FindExpr(Expr* Ex) { + + Expr* FindExpr(Expr* Ex) { if (!MatchesCriteria(Ex)) return 0; - + for (Stmt::child_iterator I=Ex->child_begin(), E=Ex->child_end();I!=E;++I) if (Expr* ExI = dyn_cast_or_null(*I)) { Expr* E2 = FindExpr(ExI); if (E2) return E2; } - + return Ex; } - + bool MatchesCriteria(Expr* Ex) { return St->getSVal(Ex).isUndef(); } }; - + public: UndefBranch(GRExprEngine *eng) : BuiltinBug(eng,"Use of uninitialized value", "Branch condition evaluates to an uninitialized value.") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::undef_branch_iterator I=Eng.undef_branches_begin(), E=Eng.undef_branches_end(); I!=E; ++I) { @@ -442,7 +442,7 @@ public: BR.EmitReport(R); } } - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { @@ -461,12 +461,12 @@ public: Emit(BR, Eng.explicit_oob_memacc_begin(), Eng.explicit_oob_memacc_end()); } }; - + class VISIBILITY_HIDDEN BadSizeVLA : public BuiltinBug { public: BadSizeVLA(GRExprEngine* eng) : BuiltinBug(eng, "Bad variable-length array (VLA) size") {} - + void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::ErrorNodes::iterator I = Eng.ExplicitBadSizedVLA.begin(), @@ -475,26 +475,26 @@ public: // Determine whether this was a 'zero-sized' VLA or a VLA with an // undefined size. ExplodedNode* N = *I; - PostStmt PS = cast(N->getLocation()); + PostStmt PS = cast(N->getLocation()); const DeclStmt *DS = cast(PS.getStmt()); VarDecl* VD = cast(*DS->decl_begin()); QualType T = Eng.getContext().getCanonicalType(VD->getType()); VariableArrayType* VT = cast(T); Expr* SizeExpr = VT->getSizeExpr(); - + std::string buf; llvm::raw_string_ostream os(buf); os << "The expression used to specify the number of elements in the " "variable-length array (VLA) '" << VD->getNameAsString() << "' evaluates to "; - + bool isUndefined = N->getState()->getSVal(SizeExpr).isUndef(); - + if (isUndefined) os << "an undefined or garbage value."; else os << "0. VLAs with no elements have undefined behavior."; - + std::string shortBuf; llvm::raw_string_ostream os_short(shortBuf); os_short << "Variable-length array '" << VD->getNameAsString() << "' " @@ -508,7 +508,7 @@ public: BR.EmitReport(report); } } - + void registerInitialVisitors(BugReporterContext& BRC, const ExplodedNode* N, BuiltinBugReport *R) { @@ -524,7 +524,7 @@ class VISIBILITY_HIDDEN CheckAttrNonNull : public CheckerVisitor { BugType *BT; - + public: CheckAttrNonNull() : BT(0) {} ~CheckAttrNonNull() {} @@ -537,73 +537,73 @@ public: void PreVisitCallExpr(CheckerContext &C, const CallExpr *CE) { const GRState *state = C.getState(); const GRState *originalState = state; - + // Check if the callee has a 'nonnull' attribute. SVal X = state->getSVal(CE->getCallee()); - + const FunctionDecl* FD = X.getAsFunctionDecl(); if (!FD) return; - const NonNullAttr* Att = FD->getAttr(); + const NonNullAttr* Att = FD->getAttr(); if (!Att) return; - + // Iterate through the arguments of CE and check them for null. unsigned idx = 0; - + for (CallExpr::const_arg_iterator I=CE->arg_begin(), E=CE->arg_end(); I!=E; ++I, ++idx) { - + if (!Att->isNonNull(idx)) continue; - + const SVal &V = state->getSVal(*I); const DefinedSVal *DV = dyn_cast(&V); - + if (!DV) continue; - + ConstraintManager &CM = C.getConstraintManager(); const GRState *stateNotNull, *stateNull; llvm::tie(stateNotNull, stateNull) = CM.AssumeDual(state, *DV); - + if (stateNull && !stateNotNull) { // Generate an error node. Check for a null node in case // we cache out. if (ExplodedNode *errorNode = C.GenerateNode(CE, stateNull, true)) { - + // Lazily allocate the BugType object if it hasn't already been // created. Ownership is transferred to the BugReporter object once // the BugReport is passed to 'EmitWarning'. if (!BT) BT = new BugType("Argument with 'nonnull' attribute passed null", "API"); - + EnhancedBugReport *R = new EnhancedBugReport(*BT, "Null pointer passed as an argument to a " "'nonnull' parameter", errorNode); - + // Highlight the range of the argument that was null. const Expr *arg = *I; R->addRange(arg->getSourceRange()); R->addVisitorCreator(registerTrackNullOrUndefValue, arg); - + // Emit the bug report. C.EmitReport(R); } - + // Always return. Either we cached out or we just emitted an error. return; } - + // If a pointer value passed the check we should assume that it is // indeed not null from this point forward. assert(stateNotNull); state = stateNotNull; } - + // If we reach here all of the arguments passed the nonnull check. // If 'state' has been updated generated a new node. if (state != originalState) @@ -614,7 +614,7 @@ public: // Undefined arguments checking. namespace { -class VISIBILITY_HIDDEN CheckUndefinedArg +class VISIBILITY_HIDDEN CheckUndefinedArg : public CheckerVisitor { BadArg *BT; @@ -690,7 +690,7 @@ public: void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B); }; -void CheckBadDiv::PreVisitBinaryOperator(CheckerContext &C, +void CheckBadDiv::PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B) { BinaryOperator::Opcode Op = B->getOpcode(); if (Op != BinaryOperator::Div && @@ -719,19 +719,19 @@ void CheckBadDiv::PreVisitBinaryOperator(CheckerContext &C, // Handle the case where 'Denom' is UnknownVal. const DefinedSVal *DV = dyn_cast(&Denom); - if (!DV) + if (!DV) return; // Check for divide by zero. ConstraintManager &CM = C.getConstraintManager(); const GRState *stateNotZero, *stateZero; llvm::tie(stateNotZero, stateZero) = CM.AssumeDual(C.getState(), *DV); - + if (stateZero && !stateNotZero) { if (ExplodedNode *N = C.GenerateNode(B, stateZero, true)) { if (!BT) BT = new DivZero(); - + C.EmitReport(new BuiltinBugReport(*BT, BT->getDescription().c_str(), N)); } return; @@ -764,7 +764,7 @@ void GRExprEngine::RegisterInternalChecks() { BR.Register(new BadSizeVLA(this)); BR.Register(new NilReceiverStructRet(this)); BR.Register(new NilReceiverLargerThanVoidPtrRet(this)); - + // The following checks do not need to have their associated BugTypes // explicitly registered with the BugReporter. If they issue any BugReports, // their associated BugType will get registered with the BugReporter diff --git a/clang/lib/Analysis/GRState.cpp b/clang/lib/Analysis/GRState.cpp index 74b493dc55c05fef8fc29d5734dc9fc0ef77290c..f269824d5477c40f7a1798947dd9363b060cf657 100644 --- a/clang/lib/Analysis/GRState.cpp +++ b/clang/lib/Analysis/GRState.cpp @@ -27,7 +27,7 @@ GRStateManager::~GRStateManager() { for (std::vector::iterator I=Printers.begin(), E=Printers.end(); I!=E; ++I) delete *I; - + for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end(); I!=E; ++I) I->second.second(I->second.first); @@ -59,13 +59,13 @@ GRStateManager::RemoveDeadBindings(const GRState* state, Stmt* Loc, const GRState *GRState::unbindLoc(Loc LV) const { Store OldStore = getStore(); Store NewStore = getStateManager().StoreMgr->Remove(OldStore, LV); - + if (NewStore == OldStore) return this; - + GRState NewSt = *this; NewSt.St = NewStore; - return getStateManager().getPersistentState(NewSt); + return getStateManager().getPersistentState(NewSt); } SVal GRState::getSValAsScalarOrLoc(const MemRegion *R) const { @@ -87,7 +87,7 @@ SVal GRState::getSValAsScalarOrLoc(const MemRegion *R) const { const GRState *GRState::BindExpr(const Stmt* Ex, SVal V, bool Invalidate) const{ Environment NewEnv = getStateManager().EnvMgr.BindExpr(Env, Ex, V, - Invalidate); + Invalidate); if (NewEnv == Env) return this; @@ -98,7 +98,7 @@ const GRState *GRState::BindExpr(const Stmt* Ex, SVal V, bool Invalidate) const{ const GRState* GRStateManager::getInitialState(const LocationContext *InitLoc) { GRState State(this, - EnvMgr.getInitialEnvironment(InitLoc->getAnalysisContext()), + EnvMgr.getInitialEnvironment(InitLoc->getAnalysisContext()), StoreMgr->getInitialStore(InitLoc), GDMFactory.GetEmptyMap()); @@ -106,16 +106,16 @@ const GRState* GRStateManager::getInitialState(const LocationContext *InitLoc) { } const GRState* GRStateManager::getPersistentState(GRState& State) { - + llvm::FoldingSetNodeID ID; - State.Profile(ID); + State.Profile(ID); void* InsertPos; - + if (GRState* I = StateSet.FindNodeOrInsertPos(ID, InsertPos)) return I; - + GRState* I = (GRState*) Alloc.Allocate(); - new (I) GRState(State); + new (I) GRState(State); StateSet.InsertNode(I, InsertPos); return I; } @@ -131,32 +131,32 @@ const GRState* GRState::makeWithStore(Store store) const { //===----------------------------------------------------------------------===// void GRState::print(llvm::raw_ostream& Out, const char* nl, - const char* sep) const { + const char* sep) const { // Print the store. GRStateManager &Mgr = getStateManager(); Mgr.getStoreManager().print(getStore(), Out, nl, sep); - + CFG &C = *getAnalysisContext().getCFG(); - + // Print Subexpression bindings. bool isFirst = true; - - for (Environment::iterator I = Env.begin(), E = Env.end(); I != E; ++I) { + + for (Environment::iterator I = Env.begin(), E = Env.end(); I != E; ++I) { if (C.isBlkExpr(I.getKey())) continue; - + if (isFirst) { Out << nl << nl << "Sub-Expressions:" << nl; isFirst = false; } else { Out << nl; } - + Out << " (" << (void*) I.getKey() << ") "; LangOptions LO; // FIXME. I.getKey()->printPretty(Out, 0, PrintingPolicy(LO)); Out << " : " << I.getData(); } - + // Print block-expression bindings. isFirst = true; @@ -169,15 +169,15 @@ void GRState::print(llvm::raw_ostream& Out, const char* nl, isFirst = false; } else { Out << nl; } - + Out << " (" << (void*) I.getKey() << ") "; LangOptions LO; // FIXME. I.getKey()->printPretty(Out, 0, PrintingPolicy(LO)); Out << " : " << I.getData(); } - + Mgr.getConstraintManager().print(this, Out, nl, sep); - + // Print checker-specific data. for (std::vector::iterator I = Mgr.Printers.begin(), E = Mgr.Printers.end(); I != E; ++I) { @@ -205,23 +205,23 @@ void* GRStateManager::FindGDMContext(void* K, void* (*CreateContext)(llvm::BumpPtrAllocator&), void (*DeleteContext)(void*)) { - + std::pair& p = GDMContexts[K]; if (!p.first) { p.first = CreateContext(Alloc); p.second = DeleteContext; } - + return p.first; } const GRState* GRStateManager::addGDM(const GRState* St, void* Key, void* Data){ GRState::GenericDataMap M1 = St->getGDM(); GRState::GenericDataMap M2 = GDMFactory.Add(M1, Key, Data); - + if (M1 == M2) return St; - + GRState NewSt = *St; NewSt.GDM = M2; return getPersistentState(NewSt); @@ -240,14 +240,14 @@ class VISIBILITY_HIDDEN ScanReachableSymbols : public SubRegionMap::Visitor { SymbolVisitor &visitor; llvm::OwningPtr SRM; public: - + ScanReachableSymbols(const GRState *st, SymbolVisitor& v) : state(st), visitor(v) {} - + bool scan(nonloc::CompoundVal val); bool scan(SVal val); bool scan(const MemRegion *R); - + // From SubRegionMap::Visitor. bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) { return scan(SubRegion); @@ -262,44 +262,44 @@ bool ScanReachableSymbols::scan(nonloc::CompoundVal val) { return true; } - + bool ScanReachableSymbols::scan(SVal val) { if (loc::MemRegionVal *X = dyn_cast(&val)) return scan(X->getRegion()); if (SymbolRef Sym = val.getAsSymbol()) return visitor.VisitSymbol(Sym); - + if (nonloc::CompoundVal *X = dyn_cast(&val)) return scan(*X); - + return true; } - + bool ScanReachableSymbols::scan(const MemRegion *R) { if (isa(R) || visited.count(R)) return true; - + visited.insert(R); // If this is a symbolic region, visit the symbol for the region. if (const SymbolicRegion *SR = dyn_cast(R)) if (!visitor.VisitSymbol(SR->getSymbol())) return false; - + // If this is a subregion, also visit the parent regions. if (const SubRegion *SR = dyn_cast(R)) if (!scan(SR->getSuperRegion())) return false; - + // Now look at the binding to this region (if any). if (!scan(state->getSValAsScalarOrLoc(R))) return false; - + // Now look at the subregions. if (!SRM.get()) SRM.reset(state->getStateManager().getStoreManager().getSubRegionMap(state)); - + return SRM->iterSubRegions(R, *this); } @@ -314,21 +314,21 @@ bool GRState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const { bool GRStateManager::isEqual(const GRState* state, const Expr* Ex, const llvm::APSInt& Y) { - + SVal V = state->getSVal(Ex); - + if (loc::ConcreteInt* X = dyn_cast(&V)) return X->getValue() == Y; if (nonloc::ConcreteInt* X = dyn_cast(&V)) return X->getValue() == Y; - + if (SymbolRef Sym = V.getAsSymbol()) return ConstraintMgr->isEqual(state, Sym, Y); return false; } - + bool GRStateManager::isEqual(const GRState* state, const Expr* Ex, uint64_t x) { return isEqual(state, Ex, getBasicVals().getValue(x, Ex->getType())); } diff --git a/clang/lib/Analysis/LiveVariables.cpp b/clang/lib/Analysis/LiveVariables.cpp index c9828ce551584e15b2ad47146dc97ef9815745df..4d96c8f8f401513bff5dfdca28897151ed652dad 100644 --- a/clang/lib/Analysis/LiveVariables.cpp +++ b/clang/lib/Analysis/LiveVariables.cpp @@ -29,35 +29,35 @@ using namespace clang; //===----------------------------------------------------------------------===// // Useful constants. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// static const bool Alive = true; -static const bool Dead = false; +static const bool Dead = false; //===----------------------------------------------------------------------===// // Dataflow initialization logic. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { -class VISIBILITY_HIDDEN RegisterDecls +class VISIBILITY_HIDDEN RegisterDecls : public CFGRecStmtDeclVisitor { - + LiveVariables::AnalysisDataTy& AD; - + typedef llvm::SmallVector AlwaysLiveTy; AlwaysLiveTy AlwaysLive; - + public: RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {} ~RegisterDecls() { AD.AlwaysLive.resetValues(AD); - + for (AlwaysLiveTy::iterator I = AlwaysLive.begin(), E = AlwaysLive.end(); - I != E; ++ I) - AD.AlwaysLive(*I, AD) = Alive; + I != E; ++ I) + AD.AlwaysLive(*I, AD) = Alive; } void VisitImplicitParamDecl(ImplicitParamDecl* IPD) { @@ -68,12 +68,12 @@ public: void VisitVarDecl(VarDecl* VD) { // Register the VarDecl for tracking. AD.Register(VD); - + // Does the variable have global storage? If so, it is always live. if (VD->hasGlobalStorage()) - AlwaysLive.push_back(VD); + AlwaysLive.push_back(VD); } - + CFG& getCFG() { return AD.getCFG(); } }; } // end anonymous namespace @@ -82,14 +82,14 @@ LiveVariables::LiveVariables(ASTContext& Ctx, CFG& cfg) { // Register all referenced VarDecls. getAnalysisData().setCFG(cfg); getAnalysisData().setContext(Ctx); - + RegisterDecls R(getAnalysisData()); cfg.VisitBlockStmts(R); } //===----------------------------------------------------------------------===// // Transfer functions. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { @@ -101,85 +101,85 @@ public: LiveVariables::ValTy& getVal() { return LiveState; } CFG& getCFG() { return AD.getCFG(); } - + void VisitDeclRefExpr(DeclRefExpr* DR); void VisitBinaryOperator(BinaryOperator* B); void VisitAssign(BinaryOperator* B); void VisitDeclStmt(DeclStmt* DS); void BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S); void VisitUnaryOperator(UnaryOperator* U); - void Visit(Stmt *S); - void VisitTerminator(CFGBlock* B); - + void Visit(Stmt *S); + void VisitTerminator(CFGBlock* B); + void SetTopValue(LiveVariables::ValTy& V) { V = AD.AlwaysLive; } - + }; - + void TransferFuncs::Visit(Stmt *S) { - + if (S == getCurrentBlkStmt()) { - + if (AD.Observer) AD.Observer->ObserveStmt(S,AD,LiveState); - + if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead; StmtVisitor::Visit(S); } else if (!getCFG().isBlkExpr(S)) { - + if (AD.Observer) AD.Observer->ObserveStmt(S,AD,LiveState); - + StmtVisitor::Visit(S); - + } else { // For block-level expressions, mark that they are live. LiveState(S,AD) = Alive; } } - + void TransferFuncs::VisitTerminator(CFGBlock* B) { - + const Stmt* E = B->getTerminatorCondition(); if (!E) return; - + assert (getCFG().isBlkExpr(E)); LiveState(E, AD) = Alive; } void TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) { - if (VarDecl* V = dyn_cast(DR->getDecl())) + if (VarDecl* V = dyn_cast(DR->getDecl())) LiveState(V,AD) = Alive; } - -void TransferFuncs::VisitBinaryOperator(BinaryOperator* B) { + +void TransferFuncs::VisitBinaryOperator(BinaryOperator* B) { if (B->isAssignmentOp()) VisitAssign(B); else VisitStmt(B); } void TransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { - + // This is a block-level expression. Its value is 'dead' before this point. LiveState(S, AD) = Dead; // This represents a 'use' of the collection. Visit(S->getCollection()); - + // This represents a 'kill' for the variable. Stmt* Element = S->getElement(); DeclRefExpr* DR = 0; VarDecl* VD = 0; - + if (DeclStmt* DS = dyn_cast(Element)) VD = cast(DS->getSingleDecl()); else { - Expr* ElemExpr = cast(Element)->IgnoreParens(); + Expr* ElemExpr = cast(Element)->IgnoreParens(); if ((DR = dyn_cast(ElemExpr))) VD = cast(DR->getDecl()); else { @@ -194,10 +194,10 @@ TransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { } } - + void TransferFuncs::VisitUnaryOperator(UnaryOperator* U) { Expr *E = U->getSubExpr(); - + switch (U->getOpcode()) { case UnaryOperator::PostInc: case UnaryOperator::PostDec: @@ -206,7 +206,7 @@ void TransferFuncs::VisitUnaryOperator(UnaryOperator* U) { // Walk through the subexpressions, blasting through ParenExprs // until we either find a DeclRefExpr or some non-DeclRefExpr // expression. - if (DeclRefExpr* DR = dyn_cast(E->IgnoreParens())) + if (DeclRefExpr* DR = dyn_cast(E->IgnoreParens())) if (VarDecl* VD = dyn_cast(DR->getDecl())) { // Treat the --/++ operator as a kill. if (AD.Observer) { AD.Observer->ObserverKill(DR); } @@ -215,24 +215,24 @@ void TransferFuncs::VisitUnaryOperator(UnaryOperator* U) { } // Fall-through. - + default: return Visit(E); } } - -void TransferFuncs::VisitAssign(BinaryOperator* B) { + +void TransferFuncs::VisitAssign(BinaryOperator* B) { Expr* LHS = B->getLHS(); // Assigning to a variable? if (DeclRefExpr* DR = dyn_cast(LHS->IgnoreParens())) { - + // Update liveness inforamtion. unsigned bit = AD.getIdx(DR->getDecl()); LiveState.getDeclBit(bit) = Dead | AD.AlwaysLive.getDeclBit(bit); - + if (AD.Observer) { AD.Observer->ObserverKill(DR); } - + // Handle things like +=, etc., which also generate "uses" // of a variable. Do this just by visiting the subexpression. if (B->getOpcode() != BinaryOperator::Assign) @@ -240,7 +240,7 @@ void TransferFuncs::VisitAssign(BinaryOperator* B) { } else // Not assigning to a variable. Process LHS as usual. Visit(LHS); - + Visit(B->getRHS()); } @@ -255,44 +255,44 @@ void TransferFuncs::VisitDeclStmt(DeclStmt* DS) { // transfer function for this expression first. if (Expr* Init = VD->getInit()) Visit(Init); - + if (const VariableArrayType* VT = AD.getContext().getAsVariableArrayType(VD->getType())) { StmtIterator I(const_cast(VT)); - StmtIterator E; + StmtIterator E; for (; I != E; ++I) Visit(*I); } - + // Update liveness information by killing the VarDecl. unsigned bit = AD.getIdx(VD); LiveState.getDeclBit(bit) = Dead | AD.AlwaysLive.getDeclBit(bit); } } - + } // end anonymous namespace //===----------------------------------------------------------------------===// // Merge operator: if something is live on any successor block, it is live // in the current block (a set union). -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { struct Merge { - typedef StmtDeclBitVector_Types::ValTy ValTy; - + typedef StmtDeclBitVector_Types::ValTy ValTy; + void operator()(ValTy& Dst, const ValTy& Src) { Dst.OrDeclBits(Src); Dst.OrBlkExprBits(Src); } }; - + typedef DataflowSolver Solver; } // end anonymous namespace //===----------------------------------------------------------------------===// // External interface to run Liveness analysis. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// void LiveVariables::runOnCFG(CFG& cfg) { Solver S(*this); @@ -337,22 +337,22 @@ bool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const { void LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const { const AnalysisDataTy& AD = getAnalysisData(); - + for (AnalysisDataTy::decl_iterator I = AD.begin_decl(), E = AD.end_decl(); I!=E; ++I) - if (V.getDeclBit(I->second)) { + if (V.getDeclBit(I->second)) { fprintf(stderr, " %s <", I->first->getIdentifier()->getName()); I->first->getLocation().dump(SM); fprintf(stderr, ">\n"); } -} +} void LiveVariables::dumpBlockLiveness(SourceManager& M) const { for (BlockDataMapTy::iterator I = getBlockDataMap().begin(), E = getBlockDataMap().end(); I!=E; ++I) { fprintf(stderr, "\n[ B%d (live variables at block exit) ]\n", I->first->getBlockID()); - + dumpLiveness(I->second,M); } diff --git a/clang/lib/Analysis/MemRegion.cpp b/clang/lib/Analysis/MemRegion.cpp index bc51f50abcd20b1cdfc735acdb3569fe1b85e29a..353e63240294bc591d333bee922e8bf8605e98a9 100644 --- a/clang/lib/Analysis/MemRegion.cpp +++ b/clang/lib/Analysis/MemRegion.cpp @@ -55,8 +55,8 @@ void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned)getKind()); } -void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, - const StringLiteral* Str, +void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, + const StringLiteral* Str, const MemRegion* superRegion) { ID.AddInteger((unsigned) StringRegionKind); ID.AddPointer(Str); @@ -114,7 +114,7 @@ void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const { } void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, - QualType ElementType, SVal Idx, + QualType ElementType, SVal Idx, const MemRegion* superRegion) { ID.AddInteger(MemRegion::ElementRegionKind); ID.Add(ElementType); @@ -182,7 +182,7 @@ void ObjCIvarRegion::dumpToStream(llvm::raw_ostream& os) const { os << "ivar{" << superRegion << ',' << getDecl()->getNameAsString() << '}'; } -void StringRegion::dumpToStream(llvm::raw_ostream& os) const { +void StringRegion::dumpToStream(llvm::raw_ostream& os) const { Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOptions())); } @@ -206,8 +206,8 @@ void RegionRawOffset::dumpToStream(llvm::raw_ostream& os) const { // MemRegionManager methods. //===----------------------------------------------------------------------===// -MemSpaceRegion* MemRegionManager::LazyAllocate(MemSpaceRegion*& region) { - if (!region) { +MemSpaceRegion* MemRegionManager::LazyAllocate(MemSpaceRegion*& region) { + if (!region) { region = (MemSpaceRegion*) A.Allocate(); new (region) MemSpaceRegion(this); } @@ -249,13 +249,13 @@ StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str) { VarRegion* MemRegionManager::getVarRegion(const VarDecl *D, const LocationContext *LC) { - + // FIXME: Once we implement scope handling, we will need to properly lookup // 'D' to the proper LocationContext. For now, just strip down to the // StackFrame. while (!isa(LC)) LC = LC->getParent(); - + return getRegion(D, LC); } @@ -320,12 +320,12 @@ AllocaRegion* MemRegionManager::getAllocaRegion(const Expr* E, unsigned cnt) { const MemSpaceRegion *MemRegion::getMemorySpace() const { const MemRegion *R = this; const SubRegion* SR = dyn_cast(this); - + while (SR) { R = SR->getSuperRegion(); SR = dyn_cast(R); } - + return dyn_cast(R); } @@ -365,7 +365,7 @@ bool MemRegion::hasGlobalsStorage() const { bool MemRegion::hasParametersStorage() const { if (const MemSpaceRegion *MS = getMemorySpace()) return MS == getMemRegionManager()->getStackArgumentsRegion(); - + return false; } @@ -385,7 +385,7 @@ bool MemRegion::hasGlobalsOrParametersStorage() const { const MemRegion *MemRegion::getBaseRegion() const { const MemRegion *R = this; while (true) { - if (const ElementRegion *ER = dyn_cast(R)) { + if (const ElementRegion *ER = dyn_cast(R)) { // FIXME: generalize. Essentially we want to strip away ElementRegions // that were layered on a symbolic region because of casts. We only // want to strip away ElementRegions, however, where the index is 0. @@ -418,27 +418,27 @@ RegionRawOffset ElementRegion::getAsRawOffset() const { const ElementRegion *ER = this; const MemRegion *superR = NULL; ASTContext &C = getContext(); - + // FIXME: Handle multi-dimensional arrays. while (ER) { superR = ER->getSuperRegion(); - + // FIXME: generalize to symbolic offsets. SVal index = ER->getIndex(); if (nonloc::ConcreteInt *CI = dyn_cast(&index)) { // Update the offset. int64_t i = CI->getValue().getSExtValue(); - + if (i != 0) { QualType elemType = ER->getElementType(); - + // If we are pointing to an incomplete type, go no further. if (!IsCompleteType(C, elemType)) { superR = ER; break; } - + int64_t size = (int64_t) (C.getTypeSize(elemType) / 8); offset += (i * size); } @@ -447,10 +447,10 @@ RegionRawOffset ElementRegion::getAsRawOffset() const { ER = dyn_cast(superR); continue; } - + return NULL; } - + assert(superR && "super region cannot be NULL"); return RegionRawOffset(superR, offset); } diff --git a/clang/lib/Analysis/PathDiagnostic.cpp b/clang/lib/Analysis/PathDiagnostic.cpp index a608ce0d5884cc7bc43a52af0d0ee29ecbe327c9..1c2f6bfca04149ba071210f4a3a8f65262e25e8a 100644 --- a/clang/lib/Analysis/PathDiagnostic.cpp +++ b/clang/lib/Analysis/PathDiagnostic.cpp @@ -27,7 +27,7 @@ bool PathDiagnosticMacroPiece::containsEvent() const { for (const_iterator I = begin(), E = end(); I!=E; ++I) { if (isa(*I)) return true; - + if (PathDiagnosticMacroPiece *MP = dyn_cast(*I)) if (MP->containsEvent()) return true; @@ -38,14 +38,14 @@ bool PathDiagnosticMacroPiece::containsEvent() const { static size_t GetNumCharsToLastNonPeriod(const char *s) { const char *start = s; - const char *lastNonPeriod = 0; + const char *lastNonPeriod = 0; for ( ; *s != '\0' ; ++s) if (*s != '.') lastNonPeriod = s; - + if (!lastNonPeriod) return 0; - + return (lastNonPeriod - start) + 1; } @@ -84,7 +84,7 @@ void PathDiagnostic::resetPath(bool deletePieces) { if (deletePieces) for (iterator I=begin(), E=end(); I!=E; ++I) delete &*I; - + path.clear(); } @@ -97,7 +97,7 @@ PathDiagnostic::PathDiagnostic(const char* bugtype, const char* desc, Category(category, GetNumCharsToLastNonPeriod(category)) {} PathDiagnostic::PathDiagnostic(const std::string& bugtype, - const std::string& desc, + const std::string& desc, const std::string& category) : Size(0), BugType(bugtype, 0, GetNumCharsToLastNonPeriod(bugtype)), @@ -106,11 +106,11 @@ PathDiagnostic::PathDiagnostic(const std::string& bugtype, void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info) { - + // Create a PathDiagnostic with a single piece. - + PathDiagnostic* D = new PathDiagnostic(); - + const char *LevelStr; switch (DiagLevel) { default: @@ -124,18 +124,18 @@ void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel, llvm::SmallString<100> StrC; StrC += LevelStr; Info.FormatDiagnostic(StrC); - + PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Info.getLocation(), std::string(StrC.begin(), StrC.end())); - + for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) P->addRange(Info.getRange(i)); for (unsigned i = 0, e = Info.getNumCodeModificationHints(); i != e; ++i) P->addCodeModificationHint(Info.getCodeModificationHint(i)); D->push_front(P); - HandlePathDiagnostic(D); + HandlePathDiagnostic(D); } //===----------------------------------------------------------------------===// @@ -155,7 +155,7 @@ FullSourceLoc PathDiagnosticLocation::asLocation() const { case DeclK: return FullSourceLoc(D->getLocation(), const_cast(*SM)); } - + return FullSourceLoc(R.getBegin(), const_cast(*SM)); } @@ -178,7 +178,7 @@ PathDiagnosticRange PathDiagnosticLocation::asRange() const { if (DS->isSingleDecl()) { // Should always be the case, but we'll be defensive. return SourceRange(DS->getLocStart(), - DS->getSingleDecl()->getLocation()); + DS->getSingleDecl()->getLocation()); } break; } @@ -197,7 +197,7 @@ PathDiagnosticRange PathDiagnosticLocation::asRange() const { return SourceRange(L, L); } } - + return S->getSourceRange(); } case DeclK: @@ -219,7 +219,7 @@ PathDiagnosticRange PathDiagnosticLocation::asRange() const { return PathDiagnosticRange(SourceRange(L, L), true); } } - + return R; } diff --git a/clang/lib/Analysis/RangeConstraintManager.cpp b/clang/lib/Analysis/RangeConstraintManager.cpp index 079462e8d19f4e517bddf808751db4798abd4728..73b445e6ab36b61776d23090839cb53c06064a6d 100644 --- a/clang/lib/Analysis/RangeConstraintManager.cpp +++ b/clang/lib/Analysis/RangeConstraintManager.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines RangeConstraintManager, a class that tracks simple +// This file defines RangeConstraintManager, a class that tracks simple // equality and inequality constraints on symbolic values of GRState. // //===----------------------------------------------------------------------===// @@ -66,7 +66,7 @@ public: // consistent (instead of comparing by pointer values) and can potentially // be used to speed up some of the operations in RangeSet. static inline bool isLess(key_type_ref lhs, key_type_ref rhs) { - return *lhs.first < *rhs.first || (!(*rhs.first < *lhs.first) && + return *lhs.first < *rhs.first || (!(*rhs.first < *lhs.first) && *lhs.second < *rhs.second); } }; @@ -78,7 +78,7 @@ class VISIBILITY_HIDDEN RangeSet { typedef llvm::ImmutableSet PrimRangeSet; PrimRangeSet ranges; // no need to make const, since it is an // ImmutableSet - this allows default operator= - // to work. + // to work. public: typedef PrimRangeSet::Factory Factory; typedef PrimRangeSet::iterator iterator; @@ -88,13 +88,13 @@ public: iterator begin() const { return ranges.begin(); } iterator end() const { return ranges.end(); } - + bool isEmpty() const { return ranges.isEmpty(); } - + /// Construct a new RangeSet representing '{ [from, to] }'. RangeSet(Factory &F, const llvm::APSInt &from, const llvm::APSInt &to) : ranges(F.Add(F.GetEmptySet(), Range(from, to))) {} - + /// Profile - Generates a hash profile of this RangeSet for use /// by FoldingSet. void Profile(llvm::FoldingSetNodeID &ID) const { ranges.Profile(ID); } @@ -122,7 +122,7 @@ public: /// value be not be equal to V. RangeSet AddNE(BasicValueFactory &BV, Factory &F, const llvm::APSInt &V) { PrimRangeSet newRanges = ranges; - + // FIXME: We can perhaps enhance ImmutableSet to do this search for us // in log(N) time using the sorted property of the internal AVL tree. for (iterator i = begin(), e = end(); i != e; ++i) { @@ -134,11 +134,11 @@ public: newRanges = F.Add(newRanges, Range(i->From(), BV.Sub1(V))); if (V != i->To()) newRanges = F.Add(newRanges, Range(BV.Add1(V), i->To())); - // All of the ranges are non-overlapping, so we can stop. + // All of the ranges are non-overlapping, so we can stop. break; } } - + return newRanges; } @@ -153,7 +153,7 @@ public: else if (i->To() < V) newRanges = F.Add(newRanges, *i); } - + return newRanges; } @@ -168,7 +168,7 @@ public: else if (i->To() <= V) newRanges = F.Add(newRanges, *i); } - + return newRanges; } @@ -181,7 +181,7 @@ public: else if (i->From() > V) newRanges = F.Add(newRanges, *i); } - + return newRanges; } @@ -208,13 +208,13 @@ public: isFirst = false; else os << ", "; - + os << '[' << i->From().toString(10) << ", " << i->To().toString(10) << ']'; } - os << " }"; + os << " }"; } - + bool operator==(const RangeSet &other) const { return ranges == other.ranges; } @@ -227,13 +227,13 @@ namespace clang { template<> struct GRStateTrait : public GRStatePartialTrait { - static inline void* GDMIndex() { return &ConstraintRangeIndex; } + static inline void* GDMIndex() { return &ConstraintRangeIndex; } }; -} - +} + namespace { class VISIBILITY_HIDDEN RangeConstraintManager : public SimpleConstraintManager{ - RangeSet GetRange(const GRState *state, SymbolRef sym); + RangeSet GetRange(const GRState *state, SymbolRef sym); public: RangeConstraintManager() {} @@ -256,7 +256,7 @@ public: const llvm::APSInt& V); const llvm::APSInt* getSymVal(const GRState* St, SymbolRef sym) const; - + // FIXME: Refactor into SimpleConstraintManager? bool isEqual(const GRState* St, SymbolRef sym, const llvm::APSInt& V) const { const llvm::APSInt *i = getSymVal(St, sym); @@ -265,7 +265,7 @@ public: const GRState* RemoveDeadBindings(const GRState* St, SymbolReaper& SymReaper); - void print(const GRState* St, llvm::raw_ostream& Out, + void print(const GRState* St, llvm::raw_ostream& Out, const char* nl, const char *sep); private: @@ -294,11 +294,11 @@ RangeConstraintManager::RemoveDeadBindings(const GRState* state, ConstraintRangeTy::Factory& CRFactory = state->get_context(); for (ConstraintRangeTy::iterator I = CR.begin(), E = CR.end(); I != E; ++I) { - SymbolRef sym = I.getKey(); + SymbolRef sym = I.getKey(); if (SymReaper.maybeDead(sym)) CR = CRFactory.Remove(CR, sym); } - + return state->set(CR); } @@ -310,11 +310,11 @@ RangeSet RangeConstraintManager::GetRange(const GRState *state, SymbolRef sym) { if (ConstraintRangeTy::data_type* V = state->get(sym)) return *V; - + // Lazily generate a new RangeSet representing all possible values for the // given symbol type. QualType T = state->getSymbolManager().getType(sym); - BasicValueFactory& BV = state->getBasicVals(); + BasicValueFactory& BV = state->getBasicVals(); return RangeSet(F, BV.getMinValue(T), BV.getMaxValue(T)); } @@ -341,16 +341,16 @@ AssumeX(GE) // Pretty-printing. //===------------------------------------------------------------------------===/ -void RangeConstraintManager::print(const GRState* St, llvm::raw_ostream& Out, +void RangeConstraintManager::print(const GRState* St, llvm::raw_ostream& Out, const char* nl, const char *sep) { - + ConstraintRangeTy Ranges = St->get(); - + if (Ranges.isEmpty()) return; - + Out << nl << sep << "ranges of symbol values:"; - + for (ConstraintRangeTy::iterator I=Ranges.begin(), E=Ranges.end(); I!=E; ++I){ Out << nl << ' ' << I.getKey() << " : "; I.getData().print(Out); diff --git a/clang/lib/Analysis/RegionStore.cpp b/clang/lib/Analysis/RegionStore.cpp index 5114035d5f435cca3fa71e085329dbc01794fc3e..41866909391955b7c8bccc89dc23e1622dd2931d 100644 --- a/clang/lib/Analysis/RegionStore.cpp +++ b/clang/lib/Analysis/RegionStore.cpp @@ -41,21 +41,21 @@ typedef llvm::ImmutableMap RegionBindings; namespace { struct VISIBILITY_HIDDEN minimal_features_tag {}; -struct VISIBILITY_HIDDEN maximal_features_tag {}; - +struct VISIBILITY_HIDDEN maximal_features_tag {}; + class VISIBILITY_HIDDEN RegionStoreFeatures { bool SupportsFields; bool SupportsRemaining; - + public: RegionStoreFeatures(minimal_features_tag) : SupportsFields(false), SupportsRemaining(false) {} - + RegionStoreFeatures(maximal_features_tag) : SupportsFields(true), SupportsRemaining(false) {} - + void enableFields(bool t) { SupportsFields = t; } - + bool supportsFields() const { return SupportsFields; } bool supportsRemaining() const { return SupportsRemaining; } }; @@ -107,7 +107,7 @@ typedef RegionDefaultValue::MapTy RegionDefaultBindings; static bool IsAnyPointerOrIntptr(QualType ty, ASTContext &Ctx) { if (ty->isAnyPointerType()) return true; - + return ty->isIntegerType() && ty->isScalarType() && Ctx.getTypeSize(ty) == Ctx.getTypeSize(Ctx.VoidPtrTy); } @@ -117,10 +117,10 @@ static bool IsAnyPointerOrIntptr(QualType ty, ASTContext &Ctx) { //===----------------------------------------------------------------------===// namespace { - + class VISIBILITY_HIDDEN RegionStoreSubRegionMap : public SubRegionMap { typedef llvm::ImmutableSet SetTy; - typedef llvm::DenseMap Map; + typedef llvm::DenseMap Map; SetTy::Factory F; Map M; public: @@ -135,27 +135,27 @@ public: I->second = F.Add(I->second, SubRegion); return false; } - + void process(llvm::SmallVectorImpl &WL, const SubRegion *R); - + ~RegionStoreSubRegionMap() {} - + bool iterSubRegions(const MemRegion* Parent, Visitor& V) const { Map::iterator I = M.find(Parent); if (I == M.end()) return true; - + llvm::ImmutableSet S = I->second; for (llvm::ImmutableSet::iterator SI=S.begin(),SE=S.end(); SI != SE; ++SI) { if (!V.Visit(Parent, *SI)) return false; } - + return true; } - + typedef SetTy::iterator iterator; std::pair begin_end(const MemRegion *R) { @@ -163,13 +163,13 @@ public: SetTy S = I == M.end() ? F.GetEmptySet() : I->second; return std::make_pair(S.begin(), S.end()); } -}; +}; class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager { const RegionStoreFeatures Features; RegionBindings::Factory RBFactory; public: - RegionStoreManager(GRStateManager& mgr, const RegionStoreFeatures &f) + RegionStoreManager(GRStateManager& mgr, const RegionStoreFeatures &f) : StoreManager(mgr), Features(f), RBFactory(mgr.getAllocator()) {} @@ -177,14 +177,14 @@ public: virtual ~RegionStoreManager() {} SubRegionMap *getSubRegionMap(const GRState *state); - + RegionStoreSubRegionMap *getRegionStoreSubRegionMap(const GRState *state); - - + + /// getDefaultBinding - Returns an SVal* representing an optional default /// binding associated with a region and its subregions. Optional getDefaultBinding(const GRState *state, const MemRegion *R); - + /// getLValueString - Returns an SVal representing the lvalue of a /// StringLiteral. Within RegionStore a StringLiteral has an /// associated StringRegion, and the lvalue of a StringLiteral is @@ -202,11 +202,11 @@ public: /// VarRegion, and the lvalue of the variable is the lvalue of that region. SVal getLValueVar(const GRState *ST, const VarDecl *VD, const LocationContext *LC); - + SVal getLValueIvar(const GRState *state, const ObjCIvarDecl* D, SVal Base); SVal getLValueField(const GRState *state, SVal Base, const FieldDecl* D); - + SVal getLValueFieldOrIvar(const GRState *state, SVal Base, const Decl* D); SVal getLValueElement(const GRState *state, QualType elementType, @@ -224,7 +224,7 @@ public: SVal EvalBinOp(const GRState *state, BinaryOperator::Opcode Op,Loc L, NonLoc R, QualType resultTy); - Store getInitialStore(const LocationContext *InitLoc) { + Store getInitialStore(const LocationContext *InitLoc) { return RBFactory.GetEmptyMap().getRoot(); } @@ -234,20 +234,20 @@ public: const GRState *InvalidateRegion(const GRState *state, const MemRegion *R, const Expr *E, unsigned Count); - + private: void RemoveSubRegionBindings(RegionBindings &B, RegionDefaultBindings &DVM, RegionDefaultBindings::Factory &DVMFactory, const MemRegion *R, RegionStoreSubRegionMap &M); - -public: + +public: const GRState *Bind(const GRState *state, Loc LV, SVal V); const GRState *BindCompoundLiteral(const GRState *state, const CompoundLiteralExpr* CL, SVal V); - + const GRState *BindDecl(const GRState *ST, const VarDecl *VD, const LocationContext *LC, SVal InitVal); @@ -258,10 +258,10 @@ public: /// BindStruct - Bind a compound value to a structure. const GRState *BindStruct(const GRState *, const TypedRegion* R, SVal V); - + const GRState *BindArray(const GRState *state, const TypedRegion* R, SVal V); - - /// KillStruct - Set the entire struct to unknown. + + /// KillStruct - Set the entire struct to unknown. const GRState *KillStruct(const GRState *state, const TypedRegion* R); const GRState *setDefaultValue(const GRState *state, const MemRegion* R, SVal V); @@ -271,7 +271,7 @@ public: //===------------------------------------------------------------------===// // Loading values from regions. //===------------------------------------------------------------------===// - + /// The high level logic for this method is this: /// Retrieve (L) /// if L has binding @@ -289,28 +289,28 @@ public: SVal RetrieveElement(const GRState *state, const ElementRegion *R); SVal RetrieveField(const GRState *state, const FieldRegion *R); - + SVal RetrieveObjCIvar(const GRState *state, const ObjCIvarRegion *R); - + SVal RetrieveVar(const GRState *state, const VarRegion *R); - + SVal RetrieveLazySymbol(const GRState *state, const TypedRegion *R); - + SVal RetrieveFieldOrElementCommon(const GRState *state, const TypedRegion *R, QualType Ty, const MemRegion *superR); - + /// Retrieve the values in a struct and return a CompoundVal, used when doing - /// struct copy: - /// struct s x, y; + /// struct copy: + /// struct s x, y; /// x = y; /// y's value is retrieved by this method. SVal RetrieveStruct(const GRState *St, const TypedRegion* R); - + SVal RetrieveArray(const GRState *St, const TypedRegion* R); - + std::pair GetLazyBinding(RegionBindings B, const MemRegion *R); - + const GRState* CopyLazyBindings(nonloc::LazyCompoundVal V, const GRState *state, const TypedRegion *R); @@ -318,7 +318,7 @@ public: //===------------------------------------------------------------------===// // State pruning. //===------------------------------------------------------------------===// - + /// RemoveDeadBindings - Scans the RegionStore of 'state' for dead values. /// It returns a new Store with these values removed. void RemoveDeadBindings(GRState &state, Stmt* Loc, SymbolReaper& SymReaper, @@ -327,14 +327,14 @@ public: //===------------------------------------------------------------------===// // Region "extents". //===------------------------------------------------------------------===// - + const GRState *setExtent(const GRState *state, const MemRegion* R, SVal Extent); SVal getSizeInElements(const GRState *state, const MemRegion* R); //===------------------------------------------------------------------===// // Utility methods. //===------------------------------------------------------------------===// - + static inline RegionBindings GetRegionBindings(Store store) { return RegionBindings(static_cast(store)); } @@ -350,7 +350,7 @@ public: BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); } - + // FIXME: Remove. ASTContext& getContext() { return StateMgr.getContext(); } }; @@ -374,31 +374,31 @@ StoreManager *clang::CreateFieldsOnlyRegionStoreManager(GRStateManager &StMgr) { void RegionStoreSubRegionMap::process(llvm::SmallVectorImpl &WL, - const SubRegion *R) { + const SubRegion *R) { const MemRegion *superR = R->getSuperRegion(); if (add(superR, R)) if (const SubRegion *sr = dyn_cast(superR)) - WL.push_back(sr); + WL.push_back(sr); } RegionStoreSubRegionMap* RegionStoreManager::getRegionStoreSubRegionMap(const GRState *state) { RegionBindings B = GetRegionBindings(state->getStore()); RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap(); - + llvm::SmallVector WL; for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) if (const SubRegion *R = dyn_cast(I.getKey())) M->process(WL, R); - + RegionDefaultBindings DVM = state->get(); for (RegionDefaultBindings::iterator I = DVM.begin(), E = DVM.end(); - I != E; ++I) + I != E; ++I) if (const SubRegion *R = dyn_cast(I.getKey())) M->process(WL, R); - // We also need to record in the subregion map "intermediate" regions that + // We also need to record in the subregion map "intermediate" regions that // don't have direct bindings but are super regions of those that do. while (!WL.empty()) { const SubRegion *R = WL.back(); @@ -423,12 +423,12 @@ RegionStoreManager::RemoveSubRegionBindings(RegionBindings &B, RegionDefaultBindings::Factory &DVMFactory, const MemRegion *R, RegionStoreSubRegionMap &M) { - + RegionStoreSubRegionMap::iterator I, E; for (llvm::tie(I, E) = M.begin_end(R); I != E; ++I) RemoveSubRegionBindings(B, DVM, DVMFactory, *I, M); - + B = RBFactory.Remove(B, R); DVM = DVMFactory.Remove(DVM, R); } @@ -439,48 +439,48 @@ const GRState *RegionStoreManager::InvalidateRegion(const GRState *state, const Expr *E, unsigned Count) { ASTContext& Ctx = StateMgr.getContext(); - + // Strip away casts. R = R->getBaseRegion(); // Remove the bindings to subregions. - { + { // Get the mapping of regions -> subregions. llvm::OwningPtr SubRegions(getRegionStoreSubRegionMap(state)); - + RegionBindings B = GetRegionBindings(state->getStore()); - RegionDefaultBindings DVM = state->get(); + RegionDefaultBindings DVM = state->get(); RegionDefaultBindings::Factory &DVMFactory = state->get_context(); - - RemoveSubRegionBindings(B, DVM, DVMFactory, R, *SubRegions.get()); + + RemoveSubRegionBindings(B, DVM, DVMFactory, R, *SubRegions.get()); state = state->makeWithStore(B.getRoot())->set(DVM); } if (!R->isBoundable()) return state; - + if (isa(R) || isa(R) || isa(R)) { - // Invalidate the region by setting its default value to + // Invalidate the region by setting its default value to // conjured symbol. The type of the symbol is irrelavant. SVal V = ValMgr.getConjuredSymbolVal(E, Ctx.IntTy, Count); return setDefaultValue(state, R, V); } - + const TypedRegion *TR = cast(R); QualType T = TR->getValueType(Ctx); - + if (const RecordType *RT = T->getAsStructureType()) { // FIXME: handle structs with default region value. const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx); - + // No record definition. There is nothing we can do. if (!RD) return state; - - // Invalidate the region by setting its default value to + + // Invalidate the region by setting its default value to // conjured symbol. The type of the symbol is irrelavant. SVal V = ValMgr.getConjuredSymbolVal(E, Ctx.IntTy, Count); return setDefaultValue(state, R, V); @@ -492,7 +492,7 @@ const GRState *RegionStoreManager::InvalidateRegion(const GRState *state, Count); return setDefaultValue(state, TR, V); } - + SVal V = ValMgr.getConjuredSymbolVal(E, T, Count); assert(SymbolManager::canSymbolicate(T) || V.isUnknown()); return Bind(state, ValMgr.makeLoc(TR), V); @@ -506,7 +506,7 @@ const GRState *RegionStoreManager::InvalidateRegion(const GRState *state, /// StringLiteral. Within RegionStore a StringLiteral has an /// associated StringRegion, and the lvalue of a StringLiteral is the /// lvalue of that region. -SVal RegionStoreManager::getLValueString(const GRState *St, +SVal RegionStoreManager::getLValueString(const GRState *St, const StringLiteral* S) { return loc::MemRegionVal(MRMgr.getStringRegion(S)); } @@ -525,7 +525,7 @@ SVal RegionStoreManager::getLValueVar(const GRState *ST, const VarDecl *VD, /// is the lvalue of that region. SVal RegionStoreManager::getLValueCompoundLiteral(const GRState *St, - const CompoundLiteralExpr* CL) { + const CompoundLiteralExpr* CL) { return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL)); } @@ -567,7 +567,7 @@ SVal RegionStoreManager::getLValueFieldOrIvar(const GRState *St, SVal Base, assert(0 && "Unhandled Base."); return Base; } - + // NOTE: We must have this check first because ObjCIvarDecl is a subclass // of FieldDecl. if (const ObjCIvarDecl *ID = dyn_cast(D)) @@ -595,10 +595,10 @@ SVal RegionStoreManager::getLValueElement(const GRState *St, // Pointer of any type can be cast and used as array base. const ElementRegion *ElemR = dyn_cast(BaseRegion); - + // Convert the offset to the appropriate size and signedness. Offset = ValMgr.convertToArrayIndex(Offset); - + if (!ElemR) { // // If the base region is not an ElementRegion, create one. @@ -612,23 +612,23 @@ SVal RegionStoreManager::getLValueElement(const GRState *St, return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset, BaseRegion, getContext())); } - + SVal BaseIdx = ElemR->getIndex(); - + if (!isa(BaseIdx)) return UnknownVal(); - + const llvm::APSInt& BaseIdxI = cast(BaseIdx).getValue(); const llvm::APSInt& OffI = cast(Offset).getValue(); assert(BaseIdxI.isSigned()); - + // Compute the new index. SVal NewIdx = nonloc::ConcreteInt(getBasicVals().getValue(BaseIdxI + OffI)); - + // Construct the new ElementRegion. const MemRegion *ArrayR = ElemR->getSuperRegion(); return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR, - getContext())); + getContext())); } //===----------------------------------------------------------------------===// @@ -637,12 +637,12 @@ SVal RegionStoreManager::getLValueElement(const GRState *St, SVal RegionStoreManager::getSizeInElements(const GRState *state, const MemRegion *R) { - + switch (R->getKind()) { case MemRegion::MemSpaceRegionKind: assert(0 && "Cannot index into a MemSpace"); - return UnknownVal(); - + return UnknownVal(); + case MemRegion::CodeTextRegionKind: // Technically this can happen if people do funny things with casts. return UnknownVal(); @@ -656,23 +656,23 @@ SVal RegionStoreManager::getSizeInElements(const GRState *state, case MemRegion::ObjCObjectRegionKind: case MemRegion::SymbolicRegionKind: return UnknownVal(); - + case MemRegion::StringRegionKind: { const StringLiteral* Str = cast(R)->getStringLiteral(); - // We intentionally made the size value signed because it participates in + // We intentionally made the size value signed because it participates in // operations with signed indices. return ValMgr.makeIntVal(Str->getByteLength()+1, false); } - + case MemRegion::VarRegionKind: { const VarRegion* VR = cast(R); // Get the type of the variable. QualType T = VR->getDesugaredValueType(getContext()); - + // FIXME: Handle variable-length arrays. if (isa(T)) return UnknownVal(); - + if (const ConstantArrayType* CAT = dyn_cast(T)) { // return the size as signed integer. return ValMgr.makeIntVal(CAT->getSize(), false); @@ -682,7 +682,7 @@ SVal RegionStoreManager::getSizeInElements(const GRState *state, // essentially are arrays of size 1. return ValMgr.makeIntVal(1, false); } - + case MemRegion::BEG_DECL_REGIONS: case MemRegion::END_DECL_REGIONS: case MemRegion::BEG_TYPED_REGIONS: @@ -690,7 +690,7 @@ SVal RegionStoreManager::getSizeInElements(const GRState *state, assert(0 && "Infeasible region"); return UnknownVal(); } - + assert(0 && "Unreachable"); return UnknownVal(); } @@ -714,29 +714,29 @@ const GRState *RegionStoreManager::setExtent(const GRState *state, SVal RegionStoreManager::ArrayToPointer(Loc Array) { if (!isa(Array)) return UnknownVal(); - + const MemRegion* R = cast(&Array)->getRegion(); const TypedRegion* ArrayR = dyn_cast(R); - + if (!ArrayR) return UnknownVal(); - + // Strip off typedefs from the ArrayRegion's ValueType. QualType T = ArrayR->getValueType(getContext())->getDesugaredType(); ArrayType *AT = cast(T); T = AT->getElementType(); - + SVal ZeroIdx = ValMgr.makeZeroArrayIndex(); ElementRegion* ER = MRMgr.getElementRegion(T, ZeroIdx, ArrayR, getContext()); - - return loc::MemRegionVal(ER); + + return loc::MemRegionVal(ER); } //===----------------------------------------------------------------------===// // Pointer arithmetic. //===----------------------------------------------------------------------===// -SVal RegionStoreManager::EvalBinOp(const GRState *state, +SVal RegionStoreManager::EvalBinOp(const GRState *state, BinaryOperator::Opcode Op, Loc L, NonLoc R, QualType resultTy) { // Assume the base location is MemRegionVal. @@ -752,15 +752,15 @@ SVal RegionStoreManager::EvalBinOp(const GRState *state, SymbolRef Sym = SR->getSymbol(); QualType T = Sym->getType(getContext()); QualType EleTy; - + if (const PointerType *PT = T->getAs()) EleTy = PT->getPointeeType(); else EleTy = T->getAsObjCObjectPointerType()->getPointeeType(); - + SVal ZeroIdx = ValMgr.makeZeroArrayIndex(); ER = MRMgr.getElementRegion(EleTy, ZeroIdx, SR, getContext()); - break; + break; } case MemRegion::AllocaRegionKind: { const AllocaRegion *AR = cast(MR); @@ -768,14 +768,14 @@ SVal RegionStoreManager::EvalBinOp(const GRState *state, QualType EleTy = T->getAs()->getPointeeType(); SVal ZeroIdx = ValMgr.makeZeroArrayIndex(); ER = MRMgr.getElementRegion(EleTy, ZeroIdx, AR, getContext()); - break; + break; } case MemRegion::ElementRegionKind: { ER = cast(MR); break; } - + // Not yet handled. case MemRegion::VarRegionKind: case MemRegion::StringRegionKind: @@ -784,15 +784,15 @@ SVal RegionStoreManager::EvalBinOp(const GRState *state, case MemRegion::ObjCObjectRegionKind: case MemRegion::ObjCIvarRegionKind: return UnknownVal(); - + case MemRegion::CodeTextRegionKind: // Technically this can happen if people do funny things with casts. return UnknownVal(); - + case MemRegion::MemSpaceRegionKind: assert(0 && "Cannot perform pointer arithmetic on a MemSpace"); return UnknownVal(); - + case MemRegion::BEG_DECL_REGIONS: case MemRegion::END_DECL_REGIONS: case MemRegion::BEG_TYPED_REGIONS: @@ -815,7 +815,7 @@ SVal RegionStoreManager::EvalBinOp(const GRState *state, getContext()); return ValMgr.makeLoc(NewER); } - + return UnknownVal(); } @@ -825,7 +825,7 @@ SVal RegionStoreManager::EvalBinOp(const GRState *state, Optional RegionStoreManager::getDefaultBinding(const GRState *state, const MemRegion *R) { - + if (R->isBoundable()) if (const TypedRegion *TR = dyn_cast(R)) if (TR->getValueType(getContext())->isUnionType()) @@ -837,21 +837,21 @@ Optional RegionStoreManager::getDefaultBinding(const GRState *state, static bool IsReinterpreted(QualType RTy, QualType UsedTy, ASTContext &Ctx) { RTy = Ctx.getCanonicalType(RTy); UsedTy = Ctx.getCanonicalType(UsedTy); - + if (RTy == UsedTy) return false; - - + + // Recursively check the types. We basically want to see if a pointer value - // is ever reinterpreted as a non-pointer, e.g. void** and intptr_t* + // is ever reinterpreted as a non-pointer, e.g. void** and intptr_t* // represents a reinterpretation. if (Loc::IsLocType(RTy) && Loc::IsLocType(UsedTy)) { - const PointerType *PRTy = RTy->getAs(); + const PointerType *PRTy = RTy->getAs(); const PointerType *PUsedTy = UsedTy->getAs(); return PUsedTy && PRTy && IsReinterpreted(PRTy->getPointeeType(), - PUsedTy->getPointeeType(), Ctx); + PUsedTy->getPointeeType(), Ctx); } return true; @@ -878,17 +878,17 @@ RegionStoreManager::Retrieve(const GRState *state, Loc L, QualType T) { // c = *p; if (isa(MR)) return SValuator::CastResult(state, UnknownVal()); - + if (isa(MR)) { ASTContext &Ctx = getContext(); SVal idx = ValMgr.makeZeroArrayIndex(); assert(!T.isNull()); MR = MRMgr.getElementRegion(T, idx, MR, Ctx); } - + if (isa(MR)) return SValuator::CastResult(state, UnknownVal()); - + // FIXME: Perhaps this method should just take a 'const MemRegion*' argument // instead of 'Loc', and have the other Loc cases handled at a higher level. const TypedRegion *R = cast(MR); @@ -911,12 +911,12 @@ RegionStoreManager::Retrieve(const GRState *state, Loc L, QualType T) { RTy = T; assert(Ctx.getCanonicalType(RTy) == Ctx.getCanonicalType(R->getValueType(Ctx))); - } + } #endif if (RTy->isStructureType()) return SValuator::CastResult(state, RetrieveStruct(state, R)); - + // FIXME: Handle unions. if (RTy->isUnionType()) return SValuator::CastResult(state, UnknownVal()); @@ -933,10 +933,10 @@ RegionStoreManager::Retrieve(const GRState *state, Loc L, QualType T) { if (const ElementRegion* ER = dyn_cast(R)) return CastRetrievedVal(RetrieveElement(state, ER), state, ER, T); - + if (const ObjCIvarRegion *IVR = dyn_cast(R)) return CastRetrievedVal(RetrieveObjCIvar(state, IVR), state, IVR, T); - + if (const VarRegion *VR = dyn_cast(R)) return CastRetrievedVal(RetrieveVar(state, VR), state, VR, T); @@ -967,26 +967,26 @@ RegionStoreManager::Retrieve(const GRState *state, Loc L, QualType T) { return SValuator::CastResult(state, ValMgr.getRegionValueSymbolValOrUnknown(R, RTy)); } - + std::pair RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R) { if (const nonloc::LazyCompoundVal *V = dyn_cast_or_null(B.lookup(R))) return std::make_pair(V->getState(), V->getRegion()); - + if (const ElementRegion *ER = dyn_cast(R)) { const std::pair &X = GetLazyBinding(B, ER->getSuperRegion()); - + if (X.first) return std::make_pair(X.first, MRMgr.getElementRegionWithSuper(ER, X.second)); - } + } else if (const FieldRegion *FR = dyn_cast(R)) { const std::pair &X = GetLazyBinding(B, FR->getSuperRegion()); - + if (X.first) return std::make_pair(X.first, MRMgr.getFieldRegionWithSuper(FR, X.second)); @@ -1010,23 +1010,23 @@ SVal RegionStoreManager::RetrieveElement(const GRState* state, SVal Idx = R->getIndex(); if (nonloc::ConcreteInt *CI = dyn_cast(&Idx)) { int64_t i = CI->getValue().getSExtValue(); - int64_t byteLength = Str->getByteLength(); + int64_t byteLength = Str->getByteLength(); if (i > byteLength) { // Buffer overflow checking in GRExprEngine should handle this case, // but we shouldn't rely on it to not overflow here if that checking // is disabled. return UnknownVal(); - } + } char c = (i == byteLength) ? '\0' : Str->getStrData()[i]; return ValMgr.makeIntVal(c, getContext().CharTy); } } - + // Special case: the current region represents a cast and it and the super // region both have pointer types or intptr_t types. If so, perform the // retrieve from the super region and appropriately "cast" the value. // This is needed to support OSAtomicCompareAndSwap and friends or other - // loads that treat integers as pointers and vis versa. + // loads that treat integers as pointers and vis versa. if (R->getIndex().isZeroConstant()) { if (const TypedRegion *superTR = dyn_cast(superR)) { ASTContext &Ctx = getContext(); @@ -1054,21 +1054,21 @@ SVal RegionStoreManager::RetrieveElement(const GRState* state, // Handle LazyCompoundVals for the immediate super region. Other cases // are handled in 'RetrieveFieldOrElementCommon'. - if (const nonloc::LazyCompoundVal *LCV = + if (const nonloc::LazyCompoundVal *LCV = dyn_cast(V)) { - + R = MRMgr.getElementRegionWithSuper(R, LCV->getRegion()); return RetrieveElement(LCV->getState(), R); } - + // Other cases: give up. return UnknownVal(); } - + return RetrieveFieldOrElementCommon(state, R, R->getElementType(), superR); } -SVal RegionStoreManager::RetrieveField(const GRState* state, +SVal RegionStoreManager::RetrieveField(const GRState* state, const FieldRegion* R) { // Check if the region has a binding. @@ -1079,76 +1079,76 @@ SVal RegionStoreManager::RetrieveField(const GRState* state, QualType Ty = R->getValueType(getContext()); return RetrieveFieldOrElementCommon(state, R, Ty, R->getSuperRegion()); } - + SVal RegionStoreManager::RetrieveFieldOrElementCommon(const GRState *state, const TypedRegion *R, QualType Ty, const MemRegion *superR) { - // At this point we have already checked in either RetrieveElement or + // At this point we have already checked in either RetrieveElement or // RetrieveField if 'R' has a direct binding. - + RegionBindings B = GetRegionBindings(state->getStore()); - + while (superR) { if (const Optional &D = getDefaultBinding(state, superR)) { if (SymbolRef parentSym = D->getAsSymbol()) return ValMgr.getDerivedRegionValueSymbolVal(parentSym, R); - + if (D->isZeroConstant()) return ValMgr.makeZeroVal(Ty); - + if (D->isUnknown()) return *D; - + assert(0 && "Unknown default value"); } - + // If our super region is a field or element itself, walk up the region // hierarchy to see if there is a default value installed in an ancestor. if (isa(superR) || isa(superR)) { superR = cast(superR)->getSuperRegion(); continue; } - + break; } - + // Lazy binding? const GRState *lazyBindingState = NULL; const MemRegion *lazyBindingRegion = NULL; llvm::tie(lazyBindingState, lazyBindingRegion) = GetLazyBinding(B, R); - + if (lazyBindingState) { assert(lazyBindingRegion && "Lazy-binding region not set"); - + if (isa(R)) return RetrieveElement(lazyBindingState, cast(lazyBindingRegion)); - + return RetrieveField(lazyBindingState, cast(lazyBindingRegion)); - } - + } + if (R->hasStackStorage() && !R->hasParametersStorage()) { - + if (isa(R)) { // Currently we don't reason specially about Clang-style vectors. Check // if superR is a vector and if so return Unknown. if (const TypedRegion *typedSuperR = dyn_cast(superR)) { if (typedSuperR->getValueType(getContext())->isVectorType()) return UnknownVal(); - } + } } - + return UndefinedVal(); } - + // All other values are symbolic. return ValMgr.getRegionValueSymbolValOrUnknown(R, Ty); } - -SVal RegionStoreManager::RetrieveObjCIvar(const GRState* state, + +SVal RegionStoreManager::RetrieveObjCIvar(const GRState* state, const ObjCIvarRegion* R) { // Check if the region has a binding. @@ -1156,50 +1156,50 @@ SVal RegionStoreManager::RetrieveObjCIvar(const GRState* state, if (const SVal* V = B.lookup(R)) return *V; - + const MemRegion *superR = R->getSuperRegion(); // Check if the super region has a binding. if (const SVal *V = B.lookup(superR)) { if (SymbolRef parentSym = V->getAsSymbol()) return ValMgr.getDerivedRegionValueSymbolVal(parentSym, R); - + // Other cases: give up. return UnknownVal(); } - + return RetrieveLazySymbol(state, R); } SVal RegionStoreManager::RetrieveVar(const GRState *state, const VarRegion *R) { - + // Check if the region has a binding. RegionBindings B = GetRegionBindings(state->getStore()); - + if (const SVal* V = B.lookup(R)) return *V; - + // Lazily derive a value for the VarRegion. const VarDecl *VD = R->getDecl(); - + if (R->hasGlobalsOrParametersStorage()) return ValMgr.getRegionValueSymbolValOrUnknown(R, VD->getType()); - + return UndefinedVal(); } -SVal RegionStoreManager::RetrieveLazySymbol(const GRState *state, +SVal RegionStoreManager::RetrieveLazySymbol(const GRState *state, const TypedRegion *R) { - + QualType valTy = R->getValueType(getContext()); // All other values are symbolic. return ValMgr.getRegionValueSymbolValOrUnknown(R, valTy); } -SVal RegionStoreManager::RetrieveStruct(const GRState *state, - const TypedRegion* R){ +SVal RegionStoreManager::RetrieveStruct(const GRState *state, + const TypedRegion* R) { QualType T = R->getValueType(getContext()); assert(T->isStructureType()); @@ -1240,7 +1240,7 @@ SVal RegionStoreManager::RetrieveArray(const GRState *state, for (uint64_t i = 0; i < size; ++i) { SVal Idx = ValMgr.makeArrayIndex(i); ElementRegion* ER = MRMgr.getElementRegion(CAT->getElementType(), Idx, R, - getContext()); + getContext()); QualType ETy = ER->getElementType(); SVal ElementVal = Retrieve(state, loc::MemRegionVal(ER), ETy).getSVal(); ArrayVal = getBasicVals().consVals(ElementVal, ArrayVal); @@ -1259,15 +1259,15 @@ SVal RegionStoreManager::RetrieveArray(const GRState *state, Store RegionStoreManager::Remove(Store store, Loc L) { const MemRegion* R = 0; - + if (isa(L)) R = cast(L).getRegion(); - + if (R) { - RegionBindings B = GetRegionBindings(store); + RegionBindings B = GetRegionBindings(store); return RBFactory.Remove(B, R).getRoot(); } - + return store; } @@ -1277,17 +1277,17 @@ const GRState *RegionStoreManager::Bind(const GRState *state, Loc L, SVal V) { // If we get here, the location should be a region. const MemRegion *R = cast(L).getRegion(); - + // Check if the region is a struct region. if (const TypedRegion* TR = dyn_cast(R)) if (TR->getValueType(getContext())->isStructureType()) return BindStruct(state, TR, V); - + // Special case: the current region represents a cast and it and the super // region both have pointer types or intptr_t types. If so, perform the // bind to the super region. // This is needed to support OSAtomicCompareAndSwap and friends or other - // loads that treat integers as pointers and vis versa. + // loads that treat integers as pointers and vis versa. if (const ElementRegion *ER = dyn_cast(R)) { if (ER->getIndex().isZeroConstant()) { if (const TypedRegion *superR = @@ -1295,17 +1295,17 @@ const GRState *RegionStoreManager::Bind(const GRState *state, Loc L, SVal V) { ASTContext &Ctx = getContext(); QualType superTy = superR->getValueType(Ctx); QualType erTy = ER->getValueType(Ctx); - - if (IsAnyPointerOrIntptr(superTy, Ctx) && + + if (IsAnyPointerOrIntptr(superTy, Ctx) && IsAnyPointerOrIntptr(erTy, Ctx)) { - SValuator::CastResult cr = - ValMgr.getSValuator().EvalCast(V, state, superTy, erTy); + SValuator::CastResult cr = + ValMgr.getSValuator().EvalCast(V, state, superTy, erTy); return Bind(cr.getState(), loc::MemRegionVal(superR), cr.getSVal()); } } } } - + // Perform the binding. RegionBindings B = GetRegionBindings(state->getStore()); return state->makeWithStore(RBFactory.Add(B, R, V).getRoot()); @@ -1332,7 +1332,7 @@ const GRState * RegionStoreManager::BindCompoundLiteral(const GRState *state, const CompoundLiteralExpr* CL, SVal V) { - + CompoundLiteralRegion* R = MRMgr.getCompoundLiteralRegion(CL); return Bind(state, loc::MemRegionVal(R), V); } @@ -1376,12 +1376,12 @@ const GRState *RegionStoreManager::BindArray(const GRState *state, // Handle lazy compound values. if (nonloc::LazyCompoundVal *LCV = dyn_cast(&Init)) return CopyLazyBindings(*LCV, state, R); - - // Remaining case: explicit compound values. + + // Remaining case: explicit compound values. nonloc::CompoundVal& CV = cast(Init); nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); uint64_t i = 0; - + for (; i < size; ++i, ++VI) { // The init list might be shorter than the array length. if (VI == VE) @@ -1411,10 +1411,10 @@ const GRState *RegionStoreManager::BindArray(const GRState *state, const GRState * RegionStoreManager::BindStruct(const GRState *state, const TypedRegion* R, SVal V) { - + if (!Features.supportsFields()) return state; - + QualType T = R->getValueType(getContext()); assert(T->isStructureType()); @@ -1427,7 +1427,7 @@ RegionStoreManager::BindStruct(const GRState *state, const TypedRegion* R, // Handle lazy compound values. if (const nonloc::LazyCompoundVal *LCV = dyn_cast(&V)) return CopyLazyBindings(*LCV, state, R); - + // We may get non-CompoundVal accidentally due to imprecise cast logic. // Ignore them and kill the field values. if (V.isUnknown() || !isa(V)) @@ -1447,7 +1447,7 @@ RegionStoreManager::BindStruct(const GRState *state, const TypedRegion* R, FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); if (Loc::IsLocType(FTy) || FTy->isIntegerType()) - state = Bind(state, ValMgr.makeLoc(FR), *VI); + state = Bind(state, ValMgr.makeLoc(FR), *VI); else if (FTy->isArrayType()) state = BindArray(state, FR, *VI); else if (FTy->isStructureType()) @@ -1484,7 +1484,7 @@ const GRState *RegionStoreManager::setDefaultValue(const GRState *state, const MemRegion* R, SVal V) { return state->set(R, V); } - + const GRState* RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V, const GRState *state, @@ -1496,46 +1496,46 @@ RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V, RegionDefaultBindings::Factory &DVMFactory = state->get_context(); - llvm::OwningPtr + llvm::OwningPtr SubRegions(getRegionStoreSubRegionMap(state)); - // B and DVM are updated after the call to RemoveSubRegionBindings. + // B and DVM are updated after the call to RemoveSubRegionBindings. RemoveSubRegionBindings(B, DVM, DVMFactory, R, *SubRegions.get()); - + // Now copy the bindings. This amounts to just binding 'V' to 'R'. This // results in a zero-copy algorithm. return state->makeWithStore(RBFactory.Add(B, R, V).getRoot()); } - + //===----------------------------------------------------------------------===// // State pruning. //===----------------------------------------------------------------------===// - + static void UpdateLiveSymbols(SVal X, SymbolReaper& SymReaper) { if (loc::MemRegionVal *XR = dyn_cast(&X)) { const MemRegion *R = XR->getRegion(); - + while (R) { if (const SymbolicRegion *SR = dyn_cast(R)) { SymReaper.markLive(SR->getSymbol()); return; } - + if (const SubRegion *SR = dyn_cast(R)) { R = SR->getSuperRegion(); continue; } - + break; } - + return; } - + for (SVal::symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end();SI!=SE;++SI) SymReaper.markLive(*SI); } - + namespace { class VISIBILITY_HIDDEN TreeScanner { RegionBindings B; @@ -1558,71 +1558,71 @@ public: : B(b), DB(db), SymReaper(symReaper), Marked(marked), ScannedLazyVals(scannedLazyVals), M(m), RS(rs), RegionRoots(regionRoots), MarkKeys(markKeys) {} - + void scanTree(const MemRegion *R); }; } // end anonymous namespace - - + + void TreeScanner::scanTree(const MemRegion *R) { if (MarkKeys) { if (Marked.count(R)) - return; - + return; + Marked.insert(R); } - + // Mark the symbol for any live SymbolicRegion as "live". This means we // should continue to track that symbol. if (const SymbolicRegion* SymR = dyn_cast(R)) SymReaper.markLive(SymR->getSymbol()); - + // Get the data binding for R (if any). const SVal* Xptr = B.lookup(R); - + // Check for lazy bindings. if (const nonloc::LazyCompoundVal *V = dyn_cast_or_null(Xptr)) { - - const LazyCompoundValData *D = V->getCVData(); + + const LazyCompoundValData *D = V->getCVData(); if (!ScannedLazyVals.count(D)) { // Scan the bindings in the LazyCompoundVal. ScannedLazyVals.insert(D); - + // FIXME: Cache subregion maps. const GRState *lazyState = D->getState(); llvm::OwningPtr lazySM(RS.getRegionStoreSubRegionMap(lazyState)); - + Store lazyStore = lazyState->getStore(); RegionBindings lazyB = RS.GetRegionBindings(lazyStore); - + RegionDefaultBindings lazyDB = lazyState->get(); - + // Scan the bindings. TreeScanner scan(lazyB, lazyDB, SymReaper, Marked, ScannedLazyVals, *lazySM.get(), RS, RegionRoots, false); - + scan.scanTree(D->getRegion()); } } - else { - // No direct binding? Get the default binding for R (if any). + else { + // No direct binding? Get the default binding for R (if any). if (!Xptr) Xptr = DB.lookup(R); - + // Direct or default binding? if (Xptr) { SVal X = *Xptr; UpdateLiveSymbols(X, SymReaper); // Update the set of live symbols. - + // If X is a region, then add it to the RegionRoots. if (const MemRegion *RX = X.getAsRegion()) { RegionRoots.push_back(RX); // Mark the super region of the RX as live. - // e.g.: int x; char *y = (char*) &x; if (*y) ... + // e.g.: int x; char *y = (char*) &x; if (*y) ... // 'y' => element region. 'x' is its super region. if (const SubRegion *SR = dyn_cast(RX)) { RegionRoots.push_back(SR->getSuperRegion()); @@ -1630,39 +1630,39 @@ void TreeScanner::scanTree(const MemRegion *R) { } } } - - RegionStoreSubRegionMap::iterator I, E; + + RegionStoreSubRegionMap::iterator I, E; for (llvm::tie(I, E) = M.begin_end(R); I != E; ++I) scanTree(*I); } -void RegionStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, +void RegionStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, SymbolReaper& SymReaper, llvm::SmallVectorImpl& RegionRoots) -{ +{ Store store = state.getStore(); RegionBindings B = GetRegionBindings(store); - + // Lazily constructed backmap from MemRegions to SubRegions. typedef llvm::ImmutableSet SubRegionsTy; typedef llvm::ImmutableMap SubRegionsMapTy; - + // The backmap from regions to subregions. llvm::OwningPtr SubRegions(getRegionStoreSubRegionMap(&state)); - + // Do a pass over the regions in the store. For VarRegions we check if // the variable is still live and if so add it to the list of live roots. - // For other regions we populate our region backmap. + // For other regions we populate our region backmap. llvm::SmallVector IntermediateRoots; - + // Scan the direct bindings for "intermediate" roots. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { const MemRegion *R = I.getKey(); IntermediateRoots.push_back(R); } - + // Scan the default bindings for "intermediate" roots. RegionDefaultBindings DVM = state.get(); for (RegionDefaultBindings::iterator I = DVM.begin(), E = DVM.end(); @@ -1672,18 +1672,18 @@ void RegionStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, } // Process the "intermediate" roots to find if they are referenced by - // real roots. + // real roots. while (!IntermediateRoots.empty()) { const MemRegion* R = IntermediateRoots.back(); IntermediateRoots.pop_back(); - + if (const VarRegion* VR = dyn_cast(R)) { if (SymReaper.isLive(Loc, VR->getDecl())) { RegionRoots.push_back(VR); // This is a live "root". } continue; } - + if (const SymbolicRegion* SR = dyn_cast(R)) { if (SymReaper.isLive(SR->getSymbol())) RegionRoots.push_back(SR); @@ -1695,9 +1695,9 @@ void RegionStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, dyn_cast(cast(R)->getSuperRegion())) IntermediateRoots.push_back(superR); } - + // Process the worklist of RegionRoots. This performs a "mark-and-sweep" - // of the store. We want to find all live symbols and dead regions. + // of the store. We want to find all live symbols and dead regions. llvm::DenseSet Marked; llvm::DenseSet LazyVals; TreeScanner TS(B, DVM, SymReaper, Marked, LazyVals, *SubRegions.get(), @@ -1707,59 +1707,59 @@ void RegionStoreManager::RemoveDeadBindings(GRState &state, Stmt* Loc, const MemRegion *R = RegionRoots.back(); RegionRoots.pop_back(); TS.scanTree(R); - } - + } + // We have now scanned the store, marking reachable regions and symbols // as live. We now remove all the regions that are dead from the store - // as well as update DSymbols with the set symbols that are now dead. + // as well as update DSymbols with the set symbols that are now dead. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { const MemRegion* R = I.getKey(); // If this region live? Is so, none of its symbols are dead. if (Marked.count(R)) continue; - + // Remove this dead region from the store. store = Remove(store, ValMgr.makeLoc(R)); - + // Mark all non-live symbols that this region references as dead. if (const SymbolicRegion* SymR = dyn_cast(R)) SymReaper.maybeDead(SymR->getSymbol()); - + SVal X = I.getData(); SVal::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end(); for (; SI != SE; ++SI) SymReaper.maybeDead(*SI); } - - // Remove dead 'default' bindings. + + // Remove dead 'default' bindings. RegionDefaultBindings NewDVM = DVM; - RegionDefaultBindings::Factory &DVMFactory = + RegionDefaultBindings::Factory &DVMFactory = state.get_context(); - + for (RegionDefaultBindings::iterator I = DVM.begin(), E = DVM.end(); I != E; ++I) { const MemRegion *R = I.getKey(); - + // If this region live? Is so, none of its symbols are dead. if (Marked.count(R)) continue; - + // Remove this dead region. NewDVM = DVMFactory.Remove(NewDVM, R); - + // Mark all non-live symbols that this region references as dead. if (const SymbolicRegion* SymR = dyn_cast(R)) SymReaper.maybeDead(SymR->getSymbol()); - + SVal X = I.getData(); SVal::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end(); for (; SI != SE; ++SI) SymReaper.maybeDead(*SI); } - + // Write the store back. state.setStore(store); - + // Write the updated default bindings back. // FIXME: Right now this involves a fetching of a persistent state. // We can do better. @@ -1775,7 +1775,7 @@ void RegionStoreManager::print(Store store, llvm::raw_ostream& OS, const char* nl, const char *sep) { RegionBindings B = GetRegionBindings(store); OS << "Store (direct bindings):" << nl; - + for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) - OS << ' ' << I.getKey() << " : " << I.getData() << nl; + OS << ' ' << I.getKey() << " : " << I.getData() << nl; } diff --git a/clang/lib/Analysis/SVals.cpp b/clang/lib/Analysis/SVals.cpp index 91674b82ed75d072dcc589d51710b3a9e03e9650..688b7ff6e1e3406b57b514f21c8511fd99435c34 100644 --- a/clang/lib/Analysis/SVals.cpp +++ b/clang/lib/Analysis/SVals.cpp @@ -58,7 +58,7 @@ const FunctionDecl *SVal::getAsFunctionDecl() const { return NULL; } -/// getAsLocSymbol - If this SVal is a location (subclasses Loc) and +/// getAsLocSymbol - If this SVal is a location (subclasses Loc) and /// wraps a symbol, return that SymbolRef. Otherwise return 0. // FIXME: should we consider SymbolRef wrapped in CodeTextRegion? SymbolRef SVal::getAsLocSymbol() const { @@ -76,11 +76,11 @@ SymbolRef SVal::getAsLocSymbol() const { SymbolRef SVal::getAsSymbol() const { if (const nonloc::SymbolVal *X = dyn_cast(this)) return X->getSymbol(); - + if (const nonloc::SymExprVal *X = dyn_cast(this)) if (SymbolRef Y = dyn_cast(X->getSymbolicExpression())) return Y; - + return getAsLocSymbol(); } @@ -89,7 +89,7 @@ SymbolRef SVal::getAsSymbol() const { const SymExpr *SVal::getAsSymbolicExpression() const { if (const nonloc::SymExprVal *X = dyn_cast(this)) return X->getSymbolicExpression(); - + return getAsSymbol(); } @@ -115,13 +115,13 @@ bool SVal::symbol_iterator::operator!=(const symbol_iterator &X) const { SVal::symbol_iterator::symbol_iterator(const SymExpr *SE) { itr.push_back(SE); - while (!isa(itr.back())) expand(); + while (!isa(itr.back())) expand(); } SVal::symbol_iterator& SVal::symbol_iterator::operator++() { assert(!itr.empty() && "attempting to iterate on an 'end' iterator"); assert(isa(itr.back())); - itr.pop_back(); + itr.pop_back(); if (!itr.empty()) while (!isa(itr.back())) expand(); return *this; @@ -135,17 +135,17 @@ SymbolRef SVal::symbol_iterator::operator*() { void SVal::symbol_iterator::expand() { const SymExpr *SE = itr.back(); itr.pop_back(); - + if (const SymIntExpr *SIE = dyn_cast(SE)) { itr.push_back(SIE->getLHS()); return; - } + } else if (const SymSymExpr *SSE = dyn_cast(SE)) { itr.push_back(SSE->getLHS()); itr.push_back(SSE->getRHS()); return; } - + assert(false && "unhandled expansion case"); } @@ -189,10 +189,10 @@ bool SVal::isZeroConstant() const { SVal nonloc::ConcreteInt::evalBinOp(ValueManager &ValMgr, BinaryOperator::Opcode Op, - const nonloc::ConcreteInt& R) const { + const nonloc::ConcreteInt& R) const { const llvm::APSInt* X = ValMgr.getBasicValueFactory().EvaluateAPSInt(Op, getValue(), R.getValue()); - + if (X) return nonloc::ConcreteInt(*X); else @@ -215,12 +215,12 @@ nonloc::ConcreteInt nonloc::ConcreteInt::evalMinus(ValueManager &ValMgr) const { SVal loc::ConcreteInt::EvalBinOp(BasicValueFactory& BasicVals, BinaryOperator::Opcode Op, const loc::ConcreteInt& R) const { - + assert (Op == BinaryOperator::Add || Op == BinaryOperator::Sub || (Op >= BinaryOperator::LT && Op <= BinaryOperator::NE)); - + const llvm::APSInt* X = BasicVals.EvaluateAPSInt(Op, getValue(), R.getValue()); - + if (X) return loc::ConcreteInt(*X); else @@ -234,40 +234,40 @@ SVal loc::ConcreteInt::EvalBinOp(BasicValueFactory& BasicVals, void SVal::dump() const { dumpToStream(llvm::errs()); } void SVal::dumpToStream(llvm::raw_ostream& os) const { - switch (getBaseKind()) { + switch (getBaseKind()) { case UnknownKind: os << "Invalid"; - break; + break; case NonLocKind: cast(this)->dumpToStream(os); - break; + break; case LocKind: cast(this)->dumpToStream(os); - break; + break; case UndefinedKind: os << "Undefined"; - break; + break; default: assert (false && "Invalid SVal."); } } void NonLoc::dumpToStream(llvm::raw_ostream& os) const { - switch (getSubKind()) { + switch (getSubKind()) { case nonloc::ConcreteIntKind: os << cast(this)->getValue().getZExtValue(); if (cast(this)->getValue().isUnsigned()) - os << 'U'; - break; + os << 'U'; + break; case nonloc::SymbolValKind: os << '$' << cast(this)->getSymbol(); - break; + break; case nonloc::SymExprValKind: { const nonloc::SymExprVal& C = *cast(this); const SymExpr *SE = C.getSymbolicExpression(); os << SE; break; - } + } case nonloc::LocAsIntegerKind: { const nonloc::LocAsInteger& C = *cast(this); os << C.getLoc() << " [as " << C.getNumBits() << " bit integer]"; @@ -278,7 +278,7 @@ void NonLoc::dumpToStream(llvm::raw_ostream& os) const { os << "compoundVal{"; bool first = true; for (nonloc::CompoundVal::iterator I=C.begin(), E=C.end(); I!=E; ++I) { - if (first) { + if (first) { os << ' '; first = false; } else @@ -294,24 +294,24 @@ void NonLoc::dumpToStream(llvm::raw_ostream& os) const { os << "lazyCompoundVal{" << (void*) C.getState() << ',' << C.getRegion() << '}'; break; - } + } default: assert (false && "Pretty-printed not implemented for this NonLoc."); break; } } -void Loc::dumpToStream(llvm::raw_ostream& os) const { - switch (getSubKind()) { +void Loc::dumpToStream(llvm::raw_ostream& os) const { + switch (getSubKind()) { case loc::ConcreteIntKind: os << cast(this)->getValue().getZExtValue() << " (Loc)"; - break; + break; case loc::GotoLabelKind: os << "&&" << cast(this)->getLabel()->getID()->getName(); break; case loc::MemRegionKind: os << '&' << cast(this)->getRegion()->getString(); - break; + break; default: assert(false && "Pretty-printing not implemented for this Loc."); break; diff --git a/clang/lib/Analysis/SValuator.cpp b/clang/lib/Analysis/SValuator.cpp index 2542cfdd3c66068d68937aebe7e06abfe46a88dd..383fe45c1d86a98c120a29a112d83b4b74b8b9bb 100644 --- a/clang/lib/Analysis/SValuator.cpp +++ b/clang/lib/Analysis/SValuator.cpp @@ -23,94 +23,94 @@ SVal SValuator::EvalBinOp(const GRState *ST, BinaryOperator::Opcode Op, if (L.isUndef() || R.isUndef()) return UndefinedVal(); - + if (L.isUnknown() || R.isUnknown()) return UnknownVal(); - + if (isa(L)) { if (isa(R)) return EvalBinOpLL(Op, cast(L), cast(R), T); return EvalBinOpLN(ST, Op, cast(L), cast(R), T); } - + if (isa(R)) { // Support pointer arithmetic where the increment/decrement operand - // is on the left and the pointer on the right. + // is on the left and the pointer on the right. assert(Op == BinaryOperator::Add || Op == BinaryOperator::Sub); - + // Commute the operands. return EvalBinOpLN(ST, Op, cast(R), cast(L), T); } - return EvalBinOpNN(Op, cast(L), cast(R), T); + return EvalBinOpNN(Op, cast(L), cast(R), T); } -SValuator::CastResult SValuator::EvalCast(SVal val, const GRState *state, +SValuator::CastResult SValuator::EvalCast(SVal val, const GRState *state, QualType castTy, QualType originalTy){ - + if (val.isUnknownOrUndef() || castTy == originalTy) return CastResult(state, val); - + ASTContext &C = ValMgr.getContext(); - + // For const casts, just propagate the value. - if (C.getCanonicalType(castTy).getUnqualifiedType() == + if (C.getCanonicalType(castTy).getUnqualifiedType() == C.getCanonicalType(originalTy).getUnqualifiedType()) return CastResult(state, val); - + // Check for casts from pointers to integers. if (castTy->isIntegerType() && Loc::IsLocType(originalTy)) return CastResult(state, EvalCastL(cast(val), castTy)); - + // Check for casts from integers to pointers. if (Loc::IsLocType(castTy) && originalTy->isIntegerType()) { if (nonloc::LocAsInteger *LV = dyn_cast(&val)) { // Just unpackage the lval and return it. return CastResult(state, LV->getLoc()); } - + goto DispatchCast; } - + // Just pass through function and block pointers. if (originalTy->isBlockPointerType() || originalTy->isFunctionPointerType()) { assert(Loc::IsLocType(castTy)); return CastResult(state, val); } - + // Check for casts from array type to another type. if (originalTy->isArrayType()) { // We will always decay to a pointer. val = ValMgr.getStateManager().ArrayToPointer(cast(val)); - + // Are we casting from an array to a pointer? If so just pass on // the decayed value. if (castTy->isPointerType()) return CastResult(state, val); - + // Are we casting from an array to an integer? If so, cast the decayed // pointer value to an integer. assert(castTy->isIntegerType()); - + // FIXME: Keep these here for now in case we decide soon that we // need the original decayed type. // QualType elemTy = cast(originalTy)->getElementType(); // QualType pointerTy = C.getPointerType(elemTy); return CastResult(state, EvalCastL(cast(val), castTy)); } - + // Check for casts from a region to a specific type. if (const MemRegion *R = val.getAsRegion()) { // FIXME: We should handle the case where we strip off view layers to get // to a desugared type. - + assert(Loc::IsLocType(castTy)); // We get a symbolic function pointer for a dereference of a function // pointer, but it is of function type. Example: - + // struct FPRec { - // void (*my_func)(int * x); + // void (*my_func)(int * x); // }; // // int bar(int x); @@ -120,29 +120,29 @@ SValuator::CastResult SValuator::EvalCast(SVal val, const GRState *state, // (*foo->my_func)(&x); // return bar(x)+1; // no-warning // } - + assert(Loc::IsLocType(originalTy) || originalTy->isFunctionType() || originalTy->isBlockPointerType()); - + StoreManager &storeMgr = ValMgr.getStateManager().getStoreManager(); - + // Delegate to store manager to get the result of casting a region // to a different type. const StoreManager::CastResult& Res = storeMgr.CastRegion(state, R, castTy); - + // Inspect the result. If the MemRegion* returned is NULL, this // expression evaluates to UnknownVal. R = Res.getRegion(); - + if (R) return CastResult(Res.getState(), loc::MemRegionVal(R)); - + return CastResult(Res.getState(), UnknownVal()); } - - // All other cases. + + // All other cases. DispatchCast: return CastResult(state, - isa(val) ? EvalCastL(cast(val), castTy) + isa(val) ? EvalCastL(cast(val), castTy) : EvalCastNL(cast(val), castTy)); } diff --git a/clang/lib/Analysis/SimpleConstraintManager.cpp b/clang/lib/Analysis/SimpleConstraintManager.cpp index 82801eb05d38369c69ddc26a10f834a50609517a..db3d68a2c7d455552a9368b698ba7f4c31524f88 100644 --- a/clang/lib/Analysis/SimpleConstraintManager.cpp +++ b/clang/lib/Analysis/SimpleConstraintManager.cpp @@ -23,10 +23,10 @@ SimpleConstraintManager::~SimpleConstraintManager() {} bool SimpleConstraintManager::canReasonAbout(SVal X) const { if (nonloc::SymExprVal *SymVal = dyn_cast(&X)) { const SymExpr *SE = SymVal->getSymbolicExpression(); - + if (isa(SE)) return true; - + if (const SymIntExpr *SIE = dyn_cast(SE)) { switch (SIE->getOpcode()) { // We don't reason yet about bitwise-constraints on symbolic values. @@ -46,7 +46,7 @@ bool SimpleConstraintManager::canReasonAbout(SVal X) const { // All other cases. default: return true; - } + } } return false; @@ -54,7 +54,7 @@ bool SimpleConstraintManager::canReasonAbout(SVal X) const { return true; } - + const GRState *SimpleConstraintManager::Assume(const GRState *state, SVal Cond, bool Assumption) { if (Cond.isUnknown()) { @@ -74,14 +74,14 @@ const GRState *SimpleConstraintManager::Assume(const GRState *state, Loc Cond, // EvalAssume is used to call into the GRTransferFunction object to perform // any checker-specific update of the state based on this assumption being - // true or false. + // true or false. return state ? state->getTransferFuncs().EvalAssume(state, Cond, Assumption) : NULL; } const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, Loc Cond, bool Assumption) { - + BasicValueFactory &BasicVals = state->getBasicVals(); switch (Cond.getSubKind()) { @@ -91,7 +91,7 @@ const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, case loc::MemRegionKind: { // FIXME: Should this go into the storemanager? - + const MemRegion *R = cast(Cond).getRegion(); const SubRegion *SubR = dyn_cast(R); @@ -99,7 +99,7 @@ const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, // FIXME: now we only find the first symbolic region. if (const SymbolicRegion *SymR = dyn_cast(SubR)) { if (Assumption) - return AssumeSymNE(state, SymR->getSymbol(), + return AssumeSymNE(state, SymR->getSymbol(), BasicVals.getZeroWithPtrWidth()); else return AssumeSymEQ(state, SymR->getSymbol(), @@ -107,15 +107,15 @@ const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, } SubR = dyn_cast(SubR->getSuperRegion()); } - + // FALL-THROUGH. } - + case loc::GotoLabelKind: return Assumption ? state : NULL; case loc::ConcreteIntKind: { - bool b = cast(Cond).getValue() != 0; + bool b = cast(Cond).getValue() != 0; bool isFeasible = b ? Assumption : !Assumption; return isFeasible ? state : NULL; } @@ -130,7 +130,7 @@ const GRState *SimpleConstraintManager::Assume(const GRState *state, // EvalAssume is used to call into the GRTransferFunction object to perform // any checker-specific update of the state based on this assumption being - // true or false. + // true or false. return state ? state->getTransferFuncs().EvalAssume(state, Cond, Assumption) : NULL; } @@ -138,13 +138,13 @@ const GRState *SimpleConstraintManager::Assume(const GRState *state, const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, NonLoc Cond, bool Assumption) { - + // We cannot reason about SymIntExpr and SymSymExpr. if (!canReasonAbout(Cond)) { // Just return the current state indicating that the path is feasible. // This may be an over-approximation of what is possible. return state; - } + } BasicValueFactory &BasicVals = state->getBasicVals(); SymbolManager &SymMgr = state->getSymbolManager(); @@ -156,7 +156,7 @@ const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, case nonloc::SymbolValKind: { nonloc::SymbolVal& SV = cast(Cond); SymbolRef sym = SV.getSymbol(); - QualType T = SymMgr.getType(sym); + QualType T = SymMgr.getType(sym); const llvm::APSInt &zero = BasicVals.getValue(0, T); return Assumption ? AssumeSymNE(state, sym, zero) @@ -167,7 +167,7 @@ const GRState *SimpleConstraintManager::AssumeAux(const GRState *state, nonloc::SymExprVal V = cast(Cond); if (const SymIntExpr *SE = dyn_cast(V.getSymbolicExpression())) return AssumeSymInt(state, Assumption, SE); - + // For all other symbolic expressions, over-approximate and consider // the constraint feasible. return state; @@ -194,7 +194,7 @@ const GRState *SimpleConstraintManager::AssumeSymInt(const GRState *state, // rest of the constraint manager logic. SymbolRef Sym = cast(SE->getLHS()); const llvm::APSInt &Int = SE->getRHS(); - + switch (SE->getOpcode()) { default: // No logic yet for other operators. Assume the constraint is feasible. @@ -218,7 +218,7 @@ const GRState *SimpleConstraintManager::AssumeSymInt(const GRState *state, case BinaryOperator::LT: return Assumption ? AssumeSymLT(state, Sym, Int) : AssumeSymGE(state, Sym, Int); - + case BinaryOperator::LE: return Assumption ? AssumeSymLE(state, Sym, Int) : AssumeSymGT(state, Sym, Int); @@ -226,9 +226,9 @@ const GRState *SimpleConstraintManager::AssumeSymInt(const GRState *state, } const GRState *SimpleConstraintManager::AssumeInBound(const GRState *state, - SVal Idx, + SVal Idx, SVal UpperBound, - bool Assumption) { + bool Assumption) { // Only support ConcreteInt for now. if (!(isa(Idx) && isa(UpperBound))) diff --git a/clang/lib/Analysis/SimpleConstraintManager.h b/clang/lib/Analysis/SimpleConstraintManager.h index 1e1a10da030fc3e80ce1847c1eb898bc47c381f7..d626dfec8cbbf782e635ce8b1828719bd742e0e1 100644 --- a/clang/lib/Analysis/SimpleConstraintManager.h +++ b/clang/lib/Analysis/SimpleConstraintManager.h @@ -22,8 +22,8 @@ namespace clang { class SimpleConstraintManager : public ConstraintManager { public: SimpleConstraintManager() {} - virtual ~SimpleConstraintManager(); - + virtual ~SimpleConstraintManager(); + //===------------------------------------------------------------------===// // Common implementation for the interface provided by ConstraintManager. //===------------------------------------------------------------------===// @@ -38,16 +38,16 @@ public: const GRState *AssumeSymInt(const GRState *state, bool Assumption, const SymIntExpr *SE); - + const GRState *AssumeInBound(const GRState *state, SVal Idx, SVal UpperBound, bool Assumption); - + protected: - + //===------------------------------------------------------------------===// // Interface that subclasses must implement. //===------------------------------------------------------------------===// - + virtual const GRState *AssumeSymNE(const GRState *state, SymbolRef sym, const llvm::APSInt& V) = 0; @@ -65,13 +65,13 @@ protected: virtual const GRState *AssumeSymGE(const GRState *state, SymbolRef sym, const llvm::APSInt& V) = 0; - + //===------------------------------------------------------------------===// // Internal implementation. //===------------------------------------------------------------------===// - + const GRState *AssumeAux(const GRState *state, Loc Cond,bool Assumption); - + const GRState *AssumeAux(const GRState *state, NonLoc Cond, bool Assumption); }; diff --git a/clang/lib/Analysis/SimpleSValuator.cpp b/clang/lib/Analysis/SimpleSValuator.cpp index 9850b2e036821e897d8c96b5a0fe7ea970e1eca4..442845a7c500df3fe76fc6f20eb9747e2dc53cb2 100644 --- a/clang/lib/Analysis/SimpleSValuator.cpp +++ b/clang/lib/Analysis/SimpleSValuator.cpp @@ -20,22 +20,22 @@ using namespace clang; namespace { class VISIBILITY_HIDDEN SimpleSValuator : public SValuator { protected: - virtual SVal EvalCastNL(NonLoc val, QualType castTy); - virtual SVal EvalCastL(Loc val, QualType castTy); + virtual SVal EvalCastNL(NonLoc val, QualType castTy); + virtual SVal EvalCastL(Loc val, QualType castTy); public: SimpleSValuator(ValueManager &valMgr) : SValuator(valMgr) {} virtual ~SimpleSValuator() {} - - virtual SVal EvalMinus(NonLoc val); - virtual SVal EvalComplement(NonLoc val); + + virtual SVal EvalMinus(NonLoc val); + virtual SVal EvalComplement(NonLoc val); virtual SVal EvalBinOpNN(BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy); virtual SVal EvalBinOpLL(BinaryOperator::Opcode op, Loc lhs, Loc rhs, QualType resultTy); virtual SVal EvalBinOpLN(const GRState *state, BinaryOperator::Opcode op, Loc lhs, NonLoc rhs, QualType resultTy); -}; +}; } // end anonymous namespace SValuator *clang::CreateSimpleSValuator(ValueManager &valMgr) { @@ -47,19 +47,19 @@ SValuator *clang::CreateSimpleSValuator(ValueManager &valMgr) { //===----------------------------------------------------------------------===// SVal SimpleSValuator::EvalCastNL(NonLoc val, QualType castTy) { - + bool isLocType = Loc::IsLocType(castTy); - + if (nonloc::LocAsInteger *LI = dyn_cast(&val)) { if (isLocType) return LI->getLoc(); - - ASTContext &Ctx = ValMgr.getContext(); - + + ASTContext &Ctx = ValMgr.getContext(); + // FIXME: Support promotions/truncations. if (Ctx.getTypeSize(castTy) == Ctx.getTypeSize(Ctx.VoidPtrTy)) return val; - + return UnknownVal(); } @@ -68,17 +68,17 @@ SVal SimpleSValuator::EvalCastNL(NonLoc val, QualType castTy) { QualType T = Ctx.getCanonicalType(se->getType(Ctx)); if (T == Ctx.getCanonicalType(castTy)) return val; - + return UnknownVal(); } - + if (!isa(val)) return UnknownVal(); - + // Only handle casts from integers to integers. if (!isLocType && !castTy->isIntegerType()) return UnknownVal(); - + llvm::APSInt i = cast(val).getValue(); i.setIsUnsigned(castTy->isUnsignedIntegerType() || Loc::IsLocType(castTy)); i.extOrTrunc(ValMgr.getContext().getTypeSize(castTy)); @@ -90,7 +90,7 @@ SVal SimpleSValuator::EvalCastNL(NonLoc val, QualType castTy) { } SVal SimpleSValuator::EvalCastL(Loc val, QualType castTy) { - + // Casts from pointers -> pointers, just return the lval. // // Casts from pointers -> references, just return the lval. These @@ -98,21 +98,21 @@ SVal SimpleSValuator::EvalCastL(Loc val, QualType castTy) { // casting from va_list* to __builtin_va_list&. // assert(!val.isUnknownOrUndef()); - + if (Loc::IsLocType(castTy) || castTy->isReferenceType()) return val; - + // FIXME: Handle transparent unions where a value can be "transparently" // lifted into a union type. if (castTy->isUnionType()) return UnknownVal(); - + assert(castTy->isIntegerType()); unsigned BitWidth = ValMgr.getContext().getTypeSize(castTy); if (!isa(val)) return ValMgr.makeLocAsInteger(val, BitWidth); - + llvm::APSInt i = cast(val).getValue(); i.setIsUnsigned(castTy->isUnsignedIntegerType() || Loc::IsLocType(castTy)); i.extOrTrunc(BitWidth); @@ -124,7 +124,7 @@ SVal SimpleSValuator::EvalCastL(Loc val, QualType castTy) { //===----------------------------------------------------------------------===// SVal SimpleSValuator::EvalMinus(NonLoc val) { - switch (val.getSubKind()) { + switch (val.getSubKind()) { case nonloc::ConcreteIntKind: return cast(val).evalMinus(ValMgr); default: @@ -158,18 +158,18 @@ static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) { } } -// Equality operators for Locs. +// Equality operators for Locs. // FIXME: All this logic will be revamped when we have MemRegion::getLocation() // implemented. static SVal EvalEquality(ValueManager &ValMgr, Loc lhs, Loc rhs, bool isEqual, QualType resultTy) { - + switch (lhs.getSubKind()) { default: assert(false && "EQ/NE not implemented for this Loc."); return UnknownVal(); - + case loc::ConcreteIntKind: { if (SymbolRef rSym = rhs.getAsSymbol()) return ValMgr.makeNonLoc(rSym, @@ -178,7 +178,7 @@ static SVal EvalEquality(ValueManager &ValMgr, Loc lhs, Loc rhs, bool isEqual, cast(lhs).getValue(), resultTy); break; - } + } case loc::MemRegionKind: { if (SymbolRef lSym = lhs.getAsLocSymbol()) { if (isa(rhs)) { @@ -191,11 +191,11 @@ static SVal EvalEquality(ValueManager &ValMgr, Loc lhs, Loc rhs, bool isEqual, } break; } - + case loc::GotoLabelKind: break; } - + return ValMgr.makeTruthVal(isEqual ? lhs == rhs : lhs != rhs, resultTy); } @@ -220,17 +220,17 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, case BinaryOperator::NE: return ValMgr.makeTruthVal(false, resultTy); } - + while (1) { switch (lhs.getSubKind()) { default: - return UnknownVal(); + return UnknownVal(); case nonloc::LocAsIntegerKind: { - Loc lhsL = cast(lhs).getLoc(); + Loc lhsL = cast(lhs).getLoc(); switch (rhs.getSubKind()) { case nonloc::LocAsIntegerKind: return EvalBinOpLL(op, lhsL, cast(rhs).getLoc(), - resultTy); + resultTy); case nonloc::ConcreteIntKind: { // Transform the integer into a location and compare. ASTContext& Ctx = ValMgr.getContext(); @@ -239,7 +239,7 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, i.extOrTrunc(Ctx.getTypeSize(Ctx.VoidPtrTy)); return EvalBinOpLL(op, lhsL, ValMgr.makeLoc(i), resultTy); } - default: + default: switch (op) { case BinaryOperator::EQ: return ValMgr.makeTruthVal(false, resultTy); @@ -250,15 +250,15 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, return UnknownVal(); } } - } + } case nonloc::SymExprValKind: { - // Logical not? + // Logical not? if (!(op == BinaryOperator::EQ && rhs.isZeroConstant())) return UnknownVal(); const SymExpr *symExpr = cast(lhs).getSymbolicExpression(); - + // Only handle ($sym op constant) for now. if (const SymIntExpr *symIntExpr = dyn_cast(symExpr)) { BinaryOperator::Opcode opc = symIntExpr->getOpcode(); @@ -301,7 +301,7 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, case BinaryOperator::GT: case BinaryOperator::LE: case BinaryOperator::GE: - case BinaryOperator::EQ: + case BinaryOperator::EQ: case BinaryOperator::NE: opc = NegateComparison(opc); assert(symIntExpr->getType(ValMgr.getContext()) == resultTy); @@ -310,7 +310,7 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, } } } - case nonloc::ConcreteIntKind: { + case nonloc::ConcreteIntKind: { if (isa(rhs)) { const nonloc::ConcreteInt& lhsInt = cast(lhs); return lhsInt.evalBinOp(ValMgr, op, cast(rhs)); @@ -322,7 +322,7 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, NonLoc tmp = rhs; rhs = lhs; lhs = tmp; - + switch (op) { case BinaryOperator::LT: op = BinaryOperator::GT; continue; case BinaryOperator::GT: op = BinaryOperator::LT; continue; @@ -335,7 +335,7 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, continue; default: return UnknownVal(); - } + } } } case nonloc::SymbolValKind: { @@ -352,7 +352,7 @@ SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op, } SVal SimpleSValuator::EvalBinOpLL(BinaryOperator::Opcode op, Loc lhs, Loc rhs, - QualType resultTy) { + QualType resultTy) { switch (op) { default: return UnknownVal(); @@ -364,7 +364,7 @@ SVal SimpleSValuator::EvalBinOpLL(BinaryOperator::Opcode op, Loc lhs, Loc rhs, SVal SimpleSValuator::EvalBinOpLN(const GRState *state, BinaryOperator::Opcode op, - Loc lhs, NonLoc rhs, QualType resultTy) { + Loc lhs, NonLoc rhs, QualType resultTy) { // Special case: 'rhs' is an integer that has the same width as a pointer and // we are using the integer location in a comparison. Normally this cannot be // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32 @@ -377,13 +377,13 @@ SVal SimpleSValuator::EvalBinOpLN(const GRState *state, if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) { // Convert the signedness of the integer (if necessary). if (x->isSigned()) - x = &ValMgr.getBasicValueFactory().getValue(*x, true); + x = &ValMgr.getBasicValueFactory().getValue(*x, true); return EvalBinOpLL(op, lhs, loc::ConcreteInt(*x), resultTy); } } } - + // Delegate pointer arithmetic to the StoreManager. return state->getStateManager().getStoreManager().EvalBinOp(state, op, lhs, rhs, resultTy); diff --git a/clang/lib/Analysis/Store.cpp b/clang/lib/Analysis/Store.cpp index f0ecda73de38f9869abfaa4de1edabf64049e13f..d1abd57640cdeca500cf53c0db045fb653515abc 100644 --- a/clang/lib/Analysis/Store.cpp +++ b/clang/lib/Analysis/Store.cpp @@ -27,7 +27,7 @@ StoreManager::MakeElementRegion(const GRState *state, const MemRegion *region, // Create a new ElementRegion. SVal idx = ValMgr.makeArrayIndex(index); return CastResult(state, MRMgr.getElementRegion(pointeeTy, idx, region, - ValMgr.getContext())); + ValMgr.getContext())); } // FIXME: Merge with the implementation of the same method in MemRegion.cpp @@ -37,16 +37,16 @@ static bool IsCompleteType(ASTContext &Ctx, QualType Ty) { if (!D->getDefinition(Ctx)) return false; } - + return true; } StoreManager::CastResult StoreManager::CastRegion(const GRState *state, const MemRegion* R, QualType CastToTy) { - + ASTContext& Ctx = StateMgr.getContext(); - + // Handle casts to Objective-C objects. if (CastToTy->isObjCObjectPointerType()) return CastResult(state, R->getBaseRegion()); @@ -55,7 +55,7 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, // FIXME: We may need different solutions, depending on the symbol // involved. Blocks can be casted to/from 'id', as they can be treated // as Objective-C objects. This could possibly be handled by enhancing - // our reasoning of downcasts of symbolic objects. + // our reasoning of downcasts of symbolic objects. if (isa(R) || isa(R)) return CastResult(state, R); @@ -72,7 +72,7 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, // Handle casts to void*. We just pass the region through. if (CanonPointeeTy.getUnqualifiedType() == Ctx.VoidTy) return CastResult(state, R); - + // Handle casts from compatible types. if (R->isBoundable()) if (const TypedRegion *TR = dyn_cast(R)) { @@ -90,7 +90,7 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, case MemRegion::END_TYPED_REGIONS: { assert(0 && "Invalid region cast"); break; - } + } case MemRegion::CodeTextRegionKind: { // CodeTextRegion should be cast to only a function or block pointer type, // although they can in practice be casted to anything, e.g, void*, @@ -98,7 +98,7 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, // Just pass the region through. break; } - + case MemRegion::StringRegionKind: case MemRegion::ObjCObjectRegionKind: // FIXME: Need to handle arbitrary downcasts. @@ -107,9 +107,9 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, case MemRegion::CompoundLiteralRegionKind: case MemRegion::FieldRegionKind: case MemRegion::ObjCIvarRegionKind: - case MemRegion::VarRegionKind: + case MemRegion::VarRegionKind: return MakeElementRegion(state, R, PointeeTy, CastToTy); - + case MemRegion::ElementRegionKind: { // If we are casting from an ElementRegion to another type, the // algorithm is as follows: @@ -117,51 +117,51 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, // (1) Compute the "raw offset" of the ElementRegion from the // base region. This is done by calling 'getAsRawOffset()'. // - // (2a) If we get a 'RegionRawOffset' after calling + // (2a) If we get a 'RegionRawOffset' after calling // 'getAsRawOffset()', determine if the absolute offset - // can be exactly divided into chunks of the size of the - // casted-pointee type. If so, create a new ElementRegion with + // can be exactly divided into chunks of the size of the + // casted-pointee type. If so, create a new ElementRegion with // the pointee-cast type as the new ElementType and the index // being the offset divded by the chunk size. If not, create // a new ElementRegion at offset 0 off the raw offset region. // // (2b) If we don't a get a 'RegionRawOffset' after calling // 'getAsRawOffset()', it means that we are at offset 0. - // + // // FIXME: Handle symbolic raw offsets. - + const ElementRegion *elementR = cast(R); const RegionRawOffset &rawOff = elementR->getAsRawOffset(); const MemRegion *baseR = rawOff.getRegion(); - + // If we cannot compute a raw offset, throw up our hands and return // a NULL MemRegion*. if (!baseR) return CastResult(state, NULL); - + int64_t off = rawOff.getByteOffset(); - + if (off == 0) { // Edge case: we are at 0 bytes off the beginning of baseR. We // check to see if type we are casting to is the same as the base - // region. If so, just return the base region. + // region. If so, just return the base region. if (const TypedRegion *TR = dyn_cast(baseR)) { QualType ObjTy = Ctx.getCanonicalType(TR->getValueType(Ctx)); QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy); if (CanonPointeeTy == ObjTy) return CastResult(state, baseR); } - + // Otherwise, create a new ElementRegion at offset 0. return MakeElementRegion(state, baseR, PointeeTy, CastToTy, 0); } - + // We have a non-zero offset from the base region. We want to determine // if the offset can be evenly divided by sizeof(PointeeTy). If so, // we create an ElementRegion whose index is that value. Otherwise, we // create two ElementRegions, one that reflects a raw offset and the other // that reflects the cast. - + // Compute the index for the new ElementRegion. int64_t newIndex = 0; const MemRegion *newSuperR = 0; @@ -179,18 +179,18 @@ StoreManager::CastRegion(const GRState *state, const MemRegion* R, newSuperR = baseR; } } - + if (!newSuperR) { // Create an intermediate ElementRegion to represent the raw byte. // This will be the super region of the final ElementRegion. SVal idx = ValMgr.makeArrayIndex(off); newSuperR = MRMgr.getElementRegion(Ctx.CharTy, idx, baseR, Ctx); } - + return MakeElementRegion(state, newSuperR, PointeeTy, CastToTy, newIndex); } } - + return CastResult(state, R); } @@ -204,8 +204,8 @@ SValuator::CastResult StoreManager::CastRetrievedVal(SVal V, QualType castTy) { if (castTy.isNull()) return SValuator::CastResult(state, V); - - ASTContext &Ctx = ValMgr.getContext(); + + ASTContext &Ctx = ValMgr.getContext(); return ValMgr.getSValuator().EvalCast(V, state, castTy, R->getValueType(Ctx)); } diff --git a/clang/lib/Analysis/SymbolManager.cpp b/clang/lib/Analysis/SymbolManager.cpp index d2a82fd1fc95b0225ab6dc2575bfa78f831914a4..22e11019295622345833e32020db2a5c4e578e0d 100644 --- a/clang/lib/Analysis/SymbolManager.cpp +++ b/clang/lib/Analysis/SymbolManager.cpp @@ -22,7 +22,7 @@ void SymExpr::dump() const { dumpToStream(llvm::errs()); } -static void print(llvm::raw_ostream& os, BinaryOperator::Opcode Op) { +static void print(llvm::raw_ostream& os, BinaryOperator::Opcode Op) { switch (Op) { default: assert(false && "operator printing not implemented"); @@ -37,13 +37,13 @@ static void print(llvm::raw_ostream& os, BinaryOperator::Opcode Op) { case BinaryOperator::LT: os << "<" ; break; case BinaryOperator::GT: os << '>' ; break; case BinaryOperator::LE: os << "<=" ; break; - case BinaryOperator::GE: os << ">=" ; break; + case BinaryOperator::GE: os << ">=" ; break; case BinaryOperator::EQ: os << "==" ; break; case BinaryOperator::NE: os << "!=" ; break; case BinaryOperator::And: os << '&' ; break; case BinaryOperator::Xor: os << '^' ; break; case BinaryOperator::Or: os << '|' ; break; - } + } } void SymIntExpr::dumpToStream(llvm::raw_ostream& os) const { @@ -54,14 +54,14 @@ void SymIntExpr::dumpToStream(llvm::raw_ostream& os) const { os << ' ' << getRHS().getZExtValue(); if (getRHS().isUnsigned()) os << 'U'; } - + void SymSymExpr::dumpToStream(llvm::raw_ostream& os) const { os << '('; getLHS()->dumpToStream(os); os << ") "; os << '('; getRHS()->dumpToStream(os); - os << ')'; + os << ')'; } void SymbolConjured::dumpToStream(llvm::raw_ostream& os) const { @@ -77,60 +77,60 @@ void SymbolRegionValue::dumpToStream(llvm::raw_ostream& os) const { os << "reg_$" << getSymbolID() << "<" << R << ">"; } -const SymbolRegionValue* +const SymbolRegionValue* SymbolManager::getRegionValueSymbol(const MemRegion* R, QualType T) { llvm::FoldingSetNodeID profile; SymbolRegionValue::Profile(profile, R, T); - void* InsertPos; - SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); - if (!SD) { + void* InsertPos; + SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); + if (!SD) { SD = (SymExpr*) BPAlloc.Allocate(); - new (SD) SymbolRegionValue(SymbolCounter, R, T); + new (SD) SymbolRegionValue(SymbolCounter, R, T); DataSet.InsertNode(SD, InsertPos); ++SymbolCounter; } - + return cast(SD); } const SymbolConjured* SymbolManager::getConjuredSymbol(const Stmt* E, QualType T, unsigned Count, const void* SymbolTag) { - + llvm::FoldingSetNodeID profile; SymbolConjured::Profile(profile, E, T, Count, SymbolTag); - void* InsertPos; - SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); - if (!SD) { + void* InsertPos; + SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); + if (!SD) { SD = (SymExpr*) BPAlloc.Allocate(); - new (SD) SymbolConjured(SymbolCounter, E, T, Count, SymbolTag); - DataSet.InsertNode(SD, InsertPos); + new (SD) SymbolConjured(SymbolCounter, E, T, Count, SymbolTag); + DataSet.InsertNode(SD, InsertPos); ++SymbolCounter; } - + return cast(SD); } const SymbolDerived* SymbolManager::getDerivedSymbol(SymbolRef parentSymbol, const TypedRegion *R) { - + llvm::FoldingSetNodeID profile; SymbolDerived::Profile(profile, parentSymbol, R); - void* InsertPos; - SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); - if (!SD) { + void* InsertPos; + SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); + if (!SD) { SD = (SymExpr*) BPAlloc.Allocate(); new (SD) SymbolDerived(SymbolCounter, parentSymbol, R); - DataSet.InsertNode(SD, InsertPos); + DataSet.InsertNode(SD, InsertPos); ++SymbolCounter; } - + return cast(SD); } const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs, - BinaryOperator::Opcode op, + BinaryOperator::Opcode op, const llvm::APSInt& v, QualType t) { llvm::FoldingSetNodeID ID; @@ -143,7 +143,7 @@ const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs, new (data) SymIntExpr(lhs, op, v, t); DataSet.InsertNode(data, InsertPos); } - + return cast(data); } @@ -161,7 +161,7 @@ const SymSymExpr *SymbolManager::getSymSymExpr(const SymExpr *lhs, new (data) SymSymExpr(lhs, op, rhs, t); DataSet.InsertNode(data, InsertPos); } - + return cast(data); } @@ -180,7 +180,7 @@ QualType SymbolRegionValue::getType(ASTContext& C) const { if (const TypedRegion* TR = dyn_cast(R)) return TR->getValueType(C); - + return QualType(); } @@ -198,7 +198,7 @@ void SymbolReaper::markLive(SymbolRef sym) { bool SymbolReaper::maybeDead(SymbolRef sym) { if (isLive(sym)) return false; - + TheDead.insert(sym); return true; } @@ -206,7 +206,7 @@ bool SymbolReaper::maybeDead(SymbolRef sym) { bool SymbolReaper::isLive(SymbolRef sym) { if (TheLiving.count(sym)) return true; - + if (const SymbolDerived *derived = dyn_cast(sym)) { if (isLive(derived->getParentSymbol())) { markLive(sym); @@ -214,7 +214,7 @@ bool SymbolReaper::isLive(SymbolRef sym) { } return false; } - + // Interogate the symbol. It may derive from an input value to // the analyzed function/method. return isa(sym); diff --git a/clang/lib/Analysis/UninitializedValues.cpp b/clang/lib/Analysis/UninitializedValues.cpp index 014ea8255e680b997aa51c70ead4f7e71e1eb2b6..8e7b15862d6659dea12a99baff9c9052a9b53d45 100644 --- a/clang/lib/Analysis/UninitializedValues.cpp +++ b/clang/lib/Analysis/UninitializedValues.cpp @@ -25,21 +25,21 @@ using namespace clang; //===----------------------------------------------------------------------===// // Dataflow initialization logic. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN RegisterDecls - : public CFGRecStmtDeclVisitor { + : public CFGRecStmtDeclVisitor { UninitializedValues::AnalysisDataTy& AD; public: RegisterDecls(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {} - + void VisitVarDecl(VarDecl* VD) { AD.Register(VD); } CFG& getCFG() { return AD.getCFG(); } }; - + } // end anonymous namespace void UninitializedValues::InitializeValues(const CFG& cfg) { @@ -49,25 +49,25 @@ void UninitializedValues::InitializeValues(const CFG& cfg) { //===----------------------------------------------------------------------===// // Transfer functions. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN TransferFuncs : public CFGStmtVisitor { - + UninitializedValues::ValTy V; UninitializedValues::AnalysisDataTy& AD; public: TransferFuncs(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {} - + UninitializedValues::ValTy& getVal() { return V; } CFG& getCFG() { return AD.getCFG(); } - + void SetTopValue(UninitializedValues::ValTy& X) { X.setDeclValues(AD); X.resetBlkExprValues(AD); } - + bool VisitDeclRefExpr(DeclRefExpr* DR); bool VisitBinaryOperator(BinaryOperator* B); bool VisitUnaryOperator(UnaryOperator* U); @@ -76,24 +76,24 @@ public: bool VisitDeclStmt(DeclStmt* D); bool VisitConditionalOperator(ConditionalOperator* C); bool BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S); - + bool Visit(Stmt *S); bool BlockStmt_VisitExpr(Expr* E); - + void VisitTerminator(CFGBlock* B) { } }; - + static const bool Initialized = false; -static const bool Uninitialized = true; +static const bool Uninitialized = true; bool TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) { - + if (VarDecl* VD = dyn_cast(DR->getDecl())) if (VD->isBlockVarDecl()) { - + if (AD.Observer) AD.Observer->ObserveDeclRefExpr(V, AD, DR, VD); - + // Pseudo-hack to prevent cascade of warnings. If an accessed variable // is uninitialized, then we are already going to flag a warning for // this variable, which a "source" of uninitialized values. @@ -103,17 +103,17 @@ bool TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) { if (AD.FullUninitTaint) return V(VD,AD); } - + return Initialized; } static VarDecl* FindBlockVarDecl(Expr* E) { - + // Blast through casts and parentheses to find any DeclRefExprs that // refer to a block VarDecl. - + if (DeclRefExpr* DR = dyn_cast(E->IgnoreParenCasts())) - if (VarDecl* VD = dyn_cast(DR->getDecl())) + if (VarDecl* VD = dyn_cast(DR->getDecl())) if (VD->isBlockVarDecl()) return VD; return NULL; @@ -136,7 +136,7 @@ bool TransferFuncs::VisitDeclStmt(DeclStmt* S) { for (DeclStmt::decl_iterator I=S->decl_begin(), E=S->decl_end(); I!=E; ++I) { VarDecl *VD = dyn_cast(*I); if (VD && VD->isBlockVarDecl()) { - if (Stmt* I = VD->getInit()) + if (Stmt* I = VD->getInit()) V(VD,AD) = AD.FullUninitTaint ? V(cast(I),AD) : Initialized; else { // Special case for declarations of array types. For things like: @@ -145,20 +145,20 @@ bool TransferFuncs::VisitDeclStmt(DeclStmt* S) { // // we should treat "x" as being initialized, because the variable // "x" really refers to the memory block. Clearly x[1] is - // uninitialized, but expressions like "(char *) x" really do refer to - // an initialized value. This simple dataflow analysis does not reason + // uninitialized, but expressions like "(char *) x" really do refer to + // an initialized value. This simple dataflow analysis does not reason // about the contents of arrays, although it could be potentially // extended to do so if the array were of constant size. if (VD->getType()->isArrayType()) V(VD,AD) = Initialized; - else + else V(VD,AD) = Uninitialized; } } } return Uninitialized; // Value is never consumed. } - + bool TransferFuncs::VisitCallExpr(CallExpr* C) { VisitChildren(C); return Initialized; @@ -172,14 +172,14 @@ bool TransferFuncs::VisitUnaryOperator(UnaryOperator* U) { return V(VD,AD) = Initialized; break; } - + default: break; } return Visit(U->getSubExpr()); } - + bool TransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { // This represents a use of the 'collection' @@ -203,12 +203,12 @@ TransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { else return Visit(ElemExpr); } - + V(VD,AD) = Initialized; return Initialized; } - - + + bool TransferFuncs::VisitConditionalOperator(ConditionalOperator* C) { Visit(C->getCond()); @@ -228,21 +228,21 @@ bool TransferFuncs::VisitStmt(Stmt* S) { // or "Initialized" to variables referenced in the other subexpressions. for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) if (*I && Visit(*I) == Uninitialized) x = Uninitialized; - + return x; } - + bool TransferFuncs::Visit(Stmt *S) { if (AD.isTracked(static_cast(S))) return V(static_cast(S),AD); else return static_cast*>(this)->Visit(S); } bool TransferFuncs::BlockStmt_VisitExpr(Expr* E) { - bool x = static_cast*>(this)->Visit(E); + bool x = static_cast*>(this)->Visit(E); if (AD.isTracked(E)) V(E,AD) = x; return x; } - + } // end anonymous namespace //===----------------------------------------------------------------------===// @@ -255,7 +255,7 @@ bool TransferFuncs::BlockStmt_VisitExpr(Expr* E) { // Merges take the same approach, preferring soundness. At a confluence point, // if any predecessor has a variable marked uninitialized, the value is // uninitialized at the confluence point. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { typedef StmtDeclBitVector_Types::Union Merge; @@ -264,28 +264,28 @@ namespace { //===----------------------------------------------------------------------===// // Uninitialized values checker. Scan an AST and flag variable uses -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// UninitializedValues_ValueTypes::ObserverTy::~ObserverTy() {} namespace { class VISIBILITY_HIDDEN UninitializedValuesChecker : public UninitializedValues::ObserverTy { - + ASTContext &Ctx; Diagnostic &Diags; llvm::SmallPtrSet AlreadyWarned; - + public: UninitializedValuesChecker(ASTContext &ctx, Diagnostic &diags) : Ctx(ctx), Diags(diags) {} - + virtual void ObserveDeclRefExpr(UninitializedValues::ValTy& V, UninitializedValues::AnalysisDataTy& AD, DeclRefExpr* DR, VarDecl* VD) { assert ( AD.isTracked(VD) && "Unknown VarDecl."); - + if (V(VD,AD) == Uninitialized) if (AlreadyWarned.insert(VD)) Diags.Report(Ctx.getFullLoc(DR->getSourceRange().getBegin()), @@ -297,13 +297,13 @@ public: namespace clang { void CheckUninitializedValues(CFG& cfg, ASTContext &Ctx, Diagnostic &Diags, bool FullUninitTaint) { - + // Compute the uninitialized values information. UninitializedValues U(cfg); U.getAnalysisData().FullUninitTaint = FullUninitTaint; Solver S(U); S.runOnCFG(cfg); - + // Scan for DeclRefExprs that use uninitialized values. UninitializedValuesChecker Observer(Ctx,Diags); U.getAnalysisData().Observer = &Observer; diff --git a/clang/lib/Analysis/ValueManager.cpp b/clang/lib/Analysis/ValueManager.cpp index 44334ce34dab6cfb8a8548d8569398148d51a86b..9fe16af6c9ffc84c461169a9ecf7080ad32d6415 100644 --- a/clang/lib/Analysis/ValueManager.cpp +++ b/clang/lib/Analysis/ValueManager.cpp @@ -28,10 +28,10 @@ SVal ValueManager::makeZeroVal(QualType T) { if (T->isIntegerType()) return makeIntVal(0, T); - + // FIXME: Handle floats. // FIXME: Handle structs. - return UnknownVal(); + return UnknownVal(); } //===----------------------------------------------------------------------===// @@ -58,14 +58,14 @@ NonLoc ValueManager::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, SVal ValueManager::convertToArrayIndex(SVal V) { if (V.isUnknownOrUndef()) return V; - + // Common case: we have an appropriately sized integer. if (nonloc::ConcreteInt* CI = dyn_cast(&V)) { const llvm::APSInt& I = CI->getValue(); if (I.getBitWidth() == ArrayIndexWidth && I.isSigned()) return V; } - + return SVator->EvalCastNL(cast(V), ArrayIndexTy); } @@ -75,24 +75,24 @@ SVal ValueManager::getRegionValueSymbolVal(const MemRegion* R, QualType T) { const TypedRegion* TR = cast(R); T = TR->getValueType(SymMgr.getContext()); } - + if (!SymbolManager::canSymbolicate(T)) return UnknownVal(); SymbolRef sym = SymMgr.getRegionValueSymbol(R, T); - + if (Loc::IsLocType(T)) return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); - + return nonloc::SymbolVal(sym); } SVal ValueManager::getConjuredSymbolVal(const Expr *E, unsigned Count) { QualType T = E->getType(); - + if (!SymbolManager::canSymbolicate(T)) return UnknownVal(); - + SymbolRef sym = SymMgr.getConjuredSymbol(E, Count); if (Loc::IsLocType(T)) @@ -103,7 +103,7 @@ SVal ValueManager::getConjuredSymbolVal(const Expr *E, unsigned Count) { SVal ValueManager::getConjuredSymbolVal(const Expr *E, QualType T, unsigned Count) { - + if (!SymbolManager::canSymbolicate(T)) return UnknownVal(); @@ -122,12 +122,12 @@ SVal ValueManager::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol, if (!SymbolManager::canSymbolicate(T)) return UnknownVal(); - + SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, R); - + if (Loc::IsLocType(T)) return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); - + return nonloc::SymbolVal(sym); } diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp index 6cb5dab53df241fd0cb0f9b5103b23104ba037b1..1a3293775ed615f8d53e9458764ba4ce9a28923f 100644 --- a/clang/lib/Basic/Builtins.cpp +++ b/clang/lib/Basic/Builtins.cpp @@ -34,7 +34,7 @@ Builtin::Context::Context(const TargetInfo &Target) { // Get the target specific builtins from the target. TSRecords = 0; NumTSRecords = 0; - Target.getTargetBuiltins(TSRecords, NumTSRecords); + Target.getTargetBuiltins(TSRecords, NumTSRecords); } /// InitializeBuiltins - Mark the identifiers for all the builtins with their @@ -51,13 +51,13 @@ void Builtin::Context::InitializeBuiltins(IdentifierTable &Table, // Step #2: Register target-specific builtins. for (unsigned i = 0, e = NumTSRecords; i != e; ++i) if (!TSRecords[i].Suppressed && - (!NoBuiltins || - (TSRecords[i].Attributes && + (!NoBuiltins || + (TSRecords[i].Attributes && !strchr(TSRecords[i].Attributes, 'f')))) Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin); } -void +void Builtin::Context::GetBuiltinNames(llvm::SmallVectorImpl &Names, bool NoBuiltins) { // Final all target-independent names @@ -65,18 +65,18 @@ Builtin::Context::GetBuiltinNames(llvm::SmallVectorImpl &Names, if (!BuiltinInfo[i].Suppressed && (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f'))) Names.push_back(BuiltinInfo[i].Name); - + // Find target-specific names. for (unsigned i = 0, e = NumTSRecords; i != e; ++i) if (!TSRecords[i].Suppressed && - (!NoBuiltins || - (TSRecords[i].Attributes && + (!NoBuiltins || + (TSRecords[i].Attributes && !strchr(TSRecords[i].Attributes, 'f')))) Names.push_back(TSRecords[i].Name); } -bool -Builtin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx, +bool +Builtin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg) { const char *Printf = strpbrk(GetRecord(ID).Attributes, "pP"); if (!Printf) diff --git a/clang/lib/Basic/ConvertUTF.c b/clang/lib/Basic/ConvertUTF.c index e5dd3e6bf5706f81e9f3127dd0d8da6690d4601c..124e386c5526507825bb97511a627209bc1bfb3b 100644 --- a/clang/lib/Basic/ConvertUTF.c +++ b/clang/lib/Basic/ConvertUTF.c @@ -34,10 +34,10 @@ Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Sept 2001: fixed const & error conditions per - mods suggested by S. Parent & A. Lillich. + mods suggested by S. Parent & A. Lillich. June 2002: Tim Dodd added detection and handling of incomplete - source sequences, enhanced error detection, added casts - to eliminate compiler warnings. + source sequences, enhanced error detection, added casts + to eliminate compiler warnings. July 2003: slight mods to back out aggressive FFFE detection. Jan 2004: updated switches in from-UTF8 conversions. Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions. @@ -61,8 +61,8 @@ static const UTF32 halfMask = 0x3FFUL; #define UNI_SUR_HIGH_END (UTF32)0xDBFF #define UNI_SUR_LOW_START (UTF32)0xDC00 #define UNI_SUR_LOW_END (UTF32)0xDFFF -#define false 0 -#define true 1 +#define false 0 +#define true 1 /* --------------------------------------------------------------------- */ @@ -90,7 +90,7 @@ static const char trailingBytesForUTF8[256] = { * in a UTF-8 sequence. */ static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, - 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; + 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed @@ -116,46 +116,46 @@ static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF32toUTF16 ( - const UTF32** sourceStart, const UTF32* sourceEnd, - UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { + const UTF32** sourceStart, const UTF32* sourceEnd, + UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF32* source = *sourceStart; UTF16* target = *targetStart; while (source < sourceEnd) { - UTF32 ch; - if (target >= targetEnd) { - result = targetExhausted; break; - } - ch = *source++; - if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ - /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - if (flags == strictConversion) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - *target++ = (UTF16)ch; /* normal case */ - } - } else if (ch > UNI_MAX_LEGAL_UTF32) { - if (flags == strictConversion) { - result = sourceIllegal; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - /* target is a character in range 0xFFFF - 0x10FFFF. */ - if (target + 1 >= targetEnd) { - --source; /* Back up source pointer! */ - result = targetExhausted; break; - } - ch -= halfBase; - *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); - *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); - } + UTF32 ch; + if (target >= targetEnd) { + result = targetExhausted; break; + } + ch = *source++; + if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ + /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { + if (flags == strictConversion) { + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } else { + *target++ = UNI_REPLACEMENT_CHAR; + } + } else { + *target++ = (UTF16)ch; /* normal case */ + } + } else if (ch > UNI_MAX_LEGAL_UTF32) { + if (flags == strictConversion) { + result = sourceIllegal; + } else { + *target++ = UNI_REPLACEMENT_CHAR; + } + } else { + /* target is a character in range 0xFFFF - 0x10FFFF. */ + if (target + 1 >= targetEnd) { + --source; /* Back up source pointer! */ + result = targetExhausted; break; + } + ch -= halfBase; + *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); + *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); + } } *sourceStart = source; *targetStart = target; @@ -165,48 +165,48 @@ ConversionResult ConvertUTF32toUTF16 ( /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF16toUTF32 ( - const UTF16** sourceStart, const UTF16* sourceEnd, - UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { + const UTF16** sourceStart, const UTF16* sourceEnd, + UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF16* source = *sourceStart; UTF32* target = *targetStart; UTF32 ch, ch2; while (source < sourceEnd) { - const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ - ch = *source++; - /* If we have a surrogate pair, convert to UTF32 first. */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { - /* If the 16 bits following the high surrogate are in the source buffer... */ - if (source < sourceEnd) { - ch2 = *source; - /* If it's a low surrogate, convert to UTF32. */ - if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { - ch = ((ch - UNI_SUR_HIGH_START) << halfShift) - + (ch2 - UNI_SUR_LOW_START) + halfBase; - ++source; - } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } else { /* We don't have the 16 bits following the high surrogate. */ - --source; /* return to the high surrogate */ - result = sourceExhausted; - break; - } - } else if (flags == strictConversion) { - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } - if (target >= targetEnd) { - source = oldSource; /* Back up source pointer! */ - result = targetExhausted; break; - } - *target++ = ch; + const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ + ch = *source++; + /* If we have a surrogate pair, convert to UTF32 first. */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { + /* If the 16 bits following the high surrogate are in the source buffer... */ + if (source < sourceEnd) { + ch2 = *source; + /* If it's a low surrogate, convert to UTF32. */ + if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { + ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + + (ch2 - UNI_SUR_LOW_START) + halfBase; + ++source; + } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } else { /* We don't have the 16 bits following the high surrogate. */ + --source; /* return to the high surrogate */ + result = sourceExhausted; + break; + } + } else if (flags == strictConversion) { + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + if (target >= targetEnd) { + source = oldSource; /* Back up source pointer! */ + result = targetExhausted; break; + } + *target++ = ch; } *sourceStart = source; *targetStart = target; @@ -219,67 +219,67 @@ if (result == sourceIllegal) { return result; } ConversionResult ConvertUTF16toUTF8 ( - const UTF16** sourceStart, const UTF16* sourceEnd, - UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { + const UTF16** sourceStart, const UTF16* sourceEnd, + UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF16* source = *sourceStart; UTF8* target = *targetStart; while (source < sourceEnd) { - UTF32 ch; - unsigned short bytesToWrite = 0; - const UTF32 byteMask = 0xBF; - const UTF32 byteMark = 0x80; - const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ - ch = *source++; - /* If we have a surrogate pair, convert to UTF32 first. */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { - /* If the 16 bits following the high surrogate are in the source buffer... */ - if (source < sourceEnd) { - UTF32 ch2 = *source; - /* If it's a low surrogate, convert to UTF32. */ - if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { - ch = ((ch - UNI_SUR_HIGH_START) << halfShift) - + (ch2 - UNI_SUR_LOW_START) + halfBase; - ++source; - } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } else { /* We don't have the 16 bits following the high surrogate. */ - --source; /* return to the high surrogate */ - result = sourceExhausted; - break; - } - } else if (flags == strictConversion) { - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } - /* Figure out how many bytes the result will require */ - if (ch < (UTF32)0x80) { bytesToWrite = 1; - } else if (ch < (UTF32)0x800) { bytesToWrite = 2; - } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; - } else if (ch < (UTF32)0x110000) { bytesToWrite = 4; - } else { bytesToWrite = 3; - ch = UNI_REPLACEMENT_CHAR; - } - - target += bytesToWrite; - if (target > targetEnd) { - source = oldSource; /* Back up source pointer! */ - target -= bytesToWrite; result = targetExhausted; break; - } - switch (bytesToWrite) { /* note: everything falls through. */ - case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; + UTF32 ch; + unsigned short bytesToWrite = 0; + const UTF32 byteMask = 0xBF; + const UTF32 byteMark = 0x80; + const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ + ch = *source++; + /* If we have a surrogate pair, convert to UTF32 first. */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { + /* If the 16 bits following the high surrogate are in the source buffer... */ + if (source < sourceEnd) { + UTF32 ch2 = *source; + /* If it's a low surrogate, convert to UTF32. */ + if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { + ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + + (ch2 - UNI_SUR_LOW_START) + halfBase; + ++source; + } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } else { /* We don't have the 16 bits following the high surrogate. */ + --source; /* return to the high surrogate */ + result = sourceExhausted; + break; + } + } else if (flags == strictConversion) { + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + /* Figure out how many bytes the result will require */ + if (ch < (UTF32)0x80) { bytesToWrite = 1; + } else if (ch < (UTF32)0x800) { bytesToWrite = 2; + } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; + } else if (ch < (UTF32)0x110000) { bytesToWrite = 4; + } else { bytesToWrite = 3; + ch = UNI_REPLACEMENT_CHAR; + } + + target += bytesToWrite; + if (target > targetEnd) { + source = oldSource; /* Back up source pointer! */ + target -= bytesToWrite; result = targetExhausted; break; + } + switch (bytesToWrite) { /* note: everything falls through. */ + case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]); + } + target += bytesToWrite; } *sourceStart = source; *targetStart = target; @@ -289,50 +289,50 @@ ConversionResult ConvertUTF16toUTF8 ( /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF32toUTF8 ( - const UTF32** sourceStart, const UTF32* sourceEnd, - UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { + const UTF32** sourceStart, const UTF32* sourceEnd, + UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF32* source = *sourceStart; UTF8* target = *targetStart; while (source < sourceEnd) { - UTF32 ch; - unsigned short bytesToWrite = 0; - const UTF32 byteMask = 0xBF; - const UTF32 byteMark = 0x80; - ch = *source++; - if (flags == strictConversion ) { - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } - /* - * Figure out how many bytes the result will require. Turn any - * illegally large UTF32 things (> Plane 17) into replacement chars. - */ - if (ch < (UTF32)0x80) { bytesToWrite = 1; - } else if (ch < (UTF32)0x800) { bytesToWrite = 2; - } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; - } else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; - } else { bytesToWrite = 3; - ch = UNI_REPLACEMENT_CHAR; - result = sourceIllegal; - } - - target += bytesToWrite; - if (target > targetEnd) { - --source; /* Back up source pointer! */ - target -= bytesToWrite; result = targetExhausted; break; - } - switch (bytesToWrite) { /* note: everything falls through. */ - case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; + UTF32 ch; + unsigned short bytesToWrite = 0; + const UTF32 byteMask = 0xBF; + const UTF32 byteMark = 0x80; + ch = *source++; + if (flags == strictConversion ) { + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + /* + * Figure out how many bytes the result will require. Turn any + * illegally large UTF32 things (> Plane 17) into replacement chars. + */ + if (ch < (UTF32)0x80) { bytesToWrite = 1; + } else if (ch < (UTF32)0x800) { bytesToWrite = 2; + } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; + } else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; + } else { bytesToWrite = 3; + ch = UNI_REPLACEMENT_CHAR; + result = sourceIllegal; + } + + target += bytesToWrite; + if (target > targetEnd) { + --source; /* Back up source pointer! */ + target -= bytesToWrite; result = targetExhausted; break; + } + switch (bytesToWrite) { /* note: everything falls through. */ + case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); + } + target += bytesToWrite; } *sourceStart = source; *targetStart = target; @@ -342,59 +342,59 @@ ConversionResult ConvertUTF32toUTF8 ( /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF8toUTF32 ( - const UTF8** sourceStart, const UTF8* sourceEnd, - UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { + const UTF8** sourceStart, const UTF8* sourceEnd, + UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF8* source = *sourceStart; UTF32* target = *targetStart; while (source < sourceEnd) { - UTF32 ch = 0; - unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; - if (source + extraBytesToRead >= sourceEnd) { - result = sourceExhausted; break; - } - /* Do this check whether lenient or strict */ - if (!isLegalUTF8(source, extraBytesToRead+1)) { - result = sourceIllegal; - break; - } - /* - * The cases all fall through. See "Note A" below. - */ - switch (extraBytesToRead) { - case 5: ch += *source++; ch <<= 6; - case 4: ch += *source++; ch <<= 6; - case 3: ch += *source++; ch <<= 6; - case 2: ch += *source++; ch <<= 6; - case 1: ch += *source++; ch <<= 6; - case 0: ch += *source++; - } - ch -= offsetsFromUTF8[extraBytesToRead]; - - if (target >= targetEnd) { - source -= (extraBytesToRead+1); /* Back up the source pointer! */ - result = targetExhausted; break; - } - if (ch <= UNI_MAX_LEGAL_UTF32) { - /* - * UTF-16 surrogate values are illegal in UTF-32, and anything - * over Plane 17 (> 0x10FFFF) is illegal. - */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - if (flags == strictConversion) { - source -= (extraBytesToRead+1); /* return to the illegal value itself */ - result = sourceIllegal; - break; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - *target++ = ch; - } - } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */ - result = sourceIllegal; - *target++ = UNI_REPLACEMENT_CHAR; - } + UTF32 ch = 0; + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; + if (source + extraBytesToRead >= sourceEnd) { + result = sourceExhausted; break; + } + /* Do this check whether lenient or strict */ + if (!isLegalUTF8(source, extraBytesToRead+1)) { + result = sourceIllegal; + break; + } + /* + * The cases all fall through. See "Note A" below. + */ + switch (extraBytesToRead) { + case 5: ch += *source++; ch <<= 6; + case 4: ch += *source++; ch <<= 6; + case 3: ch += *source++; ch <<= 6; + case 2: ch += *source++; ch <<= 6; + case 1: ch += *source++; ch <<= 6; + case 0: ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + if (target >= targetEnd) { + source -= (extraBytesToRead+1); /* Back up the source pointer! */ + result = targetExhausted; break; + } + if (ch <= UNI_MAX_LEGAL_UTF32) { + /* + * UTF-16 surrogate values are illegal in UTF-32, and anything + * over Plane 17 (> 0x10FFFF) is illegal. + */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { + if (flags == strictConversion) { + source -= (extraBytesToRead+1); /* return to the illegal value itself */ + result = sourceIllegal; + break; + } else { + *target++ = UNI_REPLACEMENT_CHAR; + } + } else { + *target++ = ch; + } + } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */ + result = sourceIllegal; + *target++ = UNI_REPLACEMENT_CHAR; + } } *sourceStart = source; *targetStart = target; @@ -420,19 +420,19 @@ static Boolean isLegalUTF8(const UTF8 *source, int length) { const UTF8 *srcptr = source+length; switch (length) { default: return false; - /* Everything else falls through when "true"... */ + /* Everything else falls through when "true"... */ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; case 2: if ((a = (*--srcptr)) > 0xBF) return false; - switch (*source) { - /* no fall-through in this inner switch */ - case 0xE0: if (a < 0xA0) return false; break; - case 0xED: if (a > 0x9F) return false; break; - case 0xF0: if (a < 0x90) return false; break; - case 0xF4: if (a > 0x8F) return false; break; - default: if (a < 0x80) return false; - } + switch (*source) { + /* no fall-through in this inner switch */ + case 0xE0: if (a < 0xA0) return false; break; + case 0xED: if (a > 0x9F) return false; break; + case 0xF0: if (a < 0x90) return false; break; + case 0xF4: if (a > 0x8F) return false; break; + default: if (a < 0x80) return false; + } case 1: if (*source >= 0x80 && *source < 0xC2) return false; } @@ -449,7 +449,7 @@ static Boolean isLegalUTF8(const UTF8 *source, int length) { Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) { int length = trailingBytesForUTF8[*source]+1; if (source+length > sourceEnd) { - return false; + return false; } return isLegalUTF8(source, length); } @@ -457,70 +457,70 @@ Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) { /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF8toUTF16 ( - const UTF8** sourceStart, const UTF8* sourceEnd, - UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { + const UTF8** sourceStart, const UTF8* sourceEnd, + UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF8* source = *sourceStart; UTF16* target = *targetStart; while (source < sourceEnd) { - UTF32 ch = 0; - unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; - if (source + extraBytesToRead >= sourceEnd) { - result = sourceExhausted; break; - } - /* Do this check whether lenient or strict */ - if (!isLegalUTF8(source, extraBytesToRead+1)) { - result = sourceIllegal; - break; - } - /* - * The cases all fall through. See "Note A" below. - */ - switch (extraBytesToRead) { - case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ - case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ - case 3: ch += *source++; ch <<= 6; - case 2: ch += *source++; ch <<= 6; - case 1: ch += *source++; ch <<= 6; - case 0: ch += *source++; - } - ch -= offsetsFromUTF8[extraBytesToRead]; - - if (target >= targetEnd) { - source -= (extraBytesToRead+1); /* Back up source pointer! */ - result = targetExhausted; break; - } - if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - if (flags == strictConversion) { - source -= (extraBytesToRead+1); /* return to the illegal value itself */ - result = sourceIllegal; - break; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - *target++ = (UTF16)ch; /* normal case */ - } - } else if (ch > UNI_MAX_UTF16) { - if (flags == strictConversion) { - result = sourceIllegal; - source -= (extraBytesToRead+1); /* return to the start */ - break; /* Bail out; shouldn't continue */ - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - /* target is a character in range 0xFFFF - 0x10FFFF. */ - if (target + 1 >= targetEnd) { - source -= (extraBytesToRead+1); /* Back up source pointer! */ - result = targetExhausted; break; - } - ch -= halfBase; - *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); - *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); - } + UTF32 ch = 0; + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; + if (source + extraBytesToRead >= sourceEnd) { + result = sourceExhausted; break; + } + /* Do this check whether lenient or strict */ + if (!isLegalUTF8(source, extraBytesToRead+1)) { + result = sourceIllegal; + break; + } + /* + * The cases all fall through. See "Note A" below. + */ + switch (extraBytesToRead) { + case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ + case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ + case 3: ch += *source++; ch <<= 6; + case 2: ch += *source++; ch <<= 6; + case 1: ch += *source++; ch <<= 6; + case 0: ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + if (target >= targetEnd) { + source -= (extraBytesToRead+1); /* Back up source pointer! */ + result = targetExhausted; break; + } + if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { + if (flags == strictConversion) { + source -= (extraBytesToRead+1); /* return to the illegal value itself */ + result = sourceIllegal; + break; + } else { + *target++ = UNI_REPLACEMENT_CHAR; + } + } else { + *target++ = (UTF16)ch; /* normal case */ + } + } else if (ch > UNI_MAX_UTF16) { + if (flags == strictConversion) { + result = sourceIllegal; + source -= (extraBytesToRead+1); /* return to the start */ + break; /* Bail out; shouldn't continue */ + } else { + *target++ = UNI_REPLACEMENT_CHAR; + } + } else { + /* target is a character in range 0xFFFF - 0x10FFFF. */ + if (target + 1 >= targetEnd) { + source -= (extraBytesToRead+1); /* Back up source pointer! */ + result = targetExhausted; break; + } + ch -= halfBase; + *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); + *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); + } } *sourceStart = source; *targetStart = target; @@ -533,14 +533,14 @@ ConversionResult ConvertUTF8toUTF16 ( The fall-through switches in UTF-8 reading code save a temp variable, some decrements & conditionals. The switches are equivalent to the following loop: - { - int tmpBytesToRead = extraBytesToRead+1; - do { - ch += *source++; - --tmpBytesToRead; - if (tmpBytesToRead) ch <<= 6; - } while (tmpBytesToRead > 0); - } + { + int tmpBytesToRead = extraBytesToRead+1; + do { + ch += *source++; + --tmpBytesToRead; + if (tmpBytesToRead) ch <<= 6; + } while (tmpBytesToRead > 0); + } In UTF-8 writing code, the switches on "bytesToWrite" are similarly unrolled loops. diff --git a/clang/lib/Basic/Diagnostic.cpp b/clang/lib/Basic/Diagnostic.cpp index 922702fdf51118d27ff5aff8c446ec0f360f916f..81d19cc8264727ff4d3476fff0d747c9cada443a 100644 --- a/clang/lib/Basic/Diagnostic.cpp +++ b/clang/lib/Basic/Diagnostic.cpp @@ -49,7 +49,7 @@ struct StaticDiagInfoRec { bool SFINAE : 1; const char *Description; const char *OptionGroup; - + bool operator<(const StaticDiagInfoRec &RHS) const { return DiagID < RHS.DiagID; } @@ -88,16 +88,16 @@ static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) { IsFirst = false; } #endif - + // Search the diagnostic table with a binary search. StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0 }; - + const StaticDiagInfoRec *Found = std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find); if (Found == StaticDiagInfo + NumDiagEntries || Found->DiagID != DiagID) return 0; - + return Found; } @@ -141,7 +141,7 @@ namespace clang { std::vector DiagInfo; std::map DiagIDs; public: - + /// getDescription - Return the description of the specified custom /// diagnostic. const char *getDescription(unsigned DiagID) const { @@ -149,14 +149,14 @@ namespace clang { "Invalid diagnosic ID"); return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str(); } - + /// getLevel - Return the level of the specified custom diagnostic. Diagnostic::Level getLevel(unsigned DiagID) const { assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() && "Invalid diagnosic ID"); return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first; } - + unsigned getOrCreateDiagID(Diagnostic::Level L, const char *Message, Diagnostic &Diags) { DiagDesc D(L, Message); @@ -164,7 +164,7 @@ namespace clang { std::map::iterator I = DiagIDs.lower_bound(D); if (I != DiagIDs.end() && I->first == D) return I->second; - + // If not, assign a new ID. unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT; DiagIDs.insert(std::make_pair(D, ID)); @@ -172,9 +172,9 @@ namespace clang { return ID; } }; - - } // end diag namespace -} // end clang namespace + + } // end diag namespace +} // end clang namespace //===----------------------------------------------------------------------===// @@ -197,7 +197,7 @@ Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) { WarningsAsErrors = false; SuppressSystemWarnings = false; ExtBehavior = Ext_Ignore; - + ErrorOccurred = false; FatalErrorOccurred = false; NumDiagnostics = 0; @@ -206,10 +206,10 @@ Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) { CustomDiagInfo = 0; CurDiagID = ~0U; LastDiagLevel = Ignored; - + ArgToStringFn = DummyArgToStringFn; ArgToStringCookie = 0; - + // Set all mappings to 'unset'. DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0); DiagMappingsStack.push_back(BlankDiags); @@ -236,7 +236,7 @@ bool Diagnostic::popMappings() { /// and level. If this is the first request for this diagnosic, it is /// registered and created, otherwise the existing ID is returned. unsigned Diagnostic::getCustomDiagID(Level L, const char *Message) { - if (CustomDiagInfo == 0) + if (CustomDiagInfo == 0) CustomDiagInfo = new diag::CustomDiagInfo(); return CustomDiagInfo->getOrCreateDiagID(L, Message, *this); } @@ -282,7 +282,7 @@ Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const { // Handle custom diagnostics, which cannot be mapped. if (DiagID >= diag::DIAG_UPPER_LIMIT) return CustomDiagInfo->getLevel(DiagID); - + unsigned DiagClass = getBuiltinDiagClass(DiagID); assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!"); return getDiagnosticLevel(DiagID, DiagClass); @@ -296,14 +296,14 @@ Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const { // Specific non-error diagnostics may be mapped to various levels from ignored // to error. Errors can only be mapped to fatal. Diagnostic::Level Result = Diagnostic::Fatal; - + // Get the mapping information, if unset, compute it lazily. unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID); if (MappingInfo == 0) { MappingInfo = GetDefaultDiagMapping(DiagID); setDiagnosticMappingInternal(DiagID, MappingInfo, false); } - + switch (MappingInfo & 7) { default: assert(0 && "Unknown mapping!"); case diag::MAP_IGNORE: @@ -326,29 +326,29 @@ Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const { // If warnings are globally mapped to ignore or error, do it. if (IgnoreAllWarnings) return Diagnostic::Ignored; - + Result = Diagnostic::Warning; - + // If this is an extension diagnostic and we're in -pedantic-error mode, and // if the user didn't explicitly map it, upgrade to an error. if (ExtBehavior == Ext_Error && (MappingInfo & 8) == 0 && isBuiltinExtensionDiag(DiagID)) Result = Diagnostic::Error; - + if (WarningsAsErrors) Result = Diagnostic::Error; break; - + case diag::MAP_WARNING_NO_WERROR: // Diagnostics specified with -Wno-error=foo should be set to warnings, but // not be adjusted by -Werror or -pedantic-errors. Result = Diagnostic::Warning; - + // If warnings are globally mapped to ignore or error, do it. if (IgnoreAllWarnings) return Diagnostic::Ignored; - + break; } @@ -357,7 +357,7 @@ Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const { // block, silence it. if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID)) return Diagnostic::Ignored; - + return Result; } @@ -392,7 +392,7 @@ static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping, for (; *Member != -1; ++Member) Diags.setDiagnosticMapping(*Member, Mapping); } - + // Enable/disable all subgroups along with this one. if (const char *SubGroups = Group->SubGroups) { for (; *SubGroups != (char)-1; ++SubGroups) @@ -405,7 +405,7 @@ static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping, /// ignores the request if "Group" was unknown, false otherwise. bool Diagnostic::setDiagnosticGroupMapping(const char *Group, diag::Mapping Map) { - + WarningOption Key = { Group, 0, 0 }; const WarningOption *Found = std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key, @@ -413,7 +413,7 @@ bool Diagnostic::setDiagnosticGroupMapping(const char *Group, if (Found == OptionTable + OptionTableSize || strcmp(Found->Name, Group) != 0) return true; // Option not found. - + MapGroupMembers(Found, Map, *this); return false; } @@ -423,19 +423,19 @@ bool Diagnostic::setDiagnosticGroupMapping(const char *Group, /// finally fully formed. bool Diagnostic::ProcessDiag() { DiagnosticInfo Info(this); - + // Figure out the diagnostic level of this message. Diagnostic::Level DiagLevel; unsigned DiagID = Info.getID(); - + // ShouldEmitInSystemHeader - True if this diagnostic should be produced even // in a system header. bool ShouldEmitInSystemHeader; - + if (DiagID >= diag::DIAG_UPPER_LIMIT) { // Handle custom diagnostics, which cannot be mapped. DiagLevel = CustomDiagInfo->getLevel(DiagID); - + // Custom diagnostics always are emitted in system headers. ShouldEmitInSystemHeader = true; } else { @@ -447,12 +447,12 @@ bool Diagnostic::ProcessDiag() { DiagLevel = Diagnostic::Note; ShouldEmitInSystemHeader = false; // extra consideration is needed } else { - // If this is not an error and we are in a system header, we ignore it. + // If this is not an error and we are in a system header, we ignore it. // Check the original Diag ID here, because we also want to ignore // extensions and warnings in -Werror and -pedantic-errors modes, which // *map* warnings/extensions to errors. ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR; - + DiagLevel = getDiagnosticLevel(DiagID, DiagClass); } } @@ -466,7 +466,7 @@ bool Diagnostic::ProcessDiag() { FatalErrorOccurred = true; LastDiagLevel = DiagLevel; - } + } // If a fatal error has already been emitted, silence all subsequent // diagnostics. @@ -493,7 +493,7 @@ bool Diagnostic::ProcessDiag() { ErrorOccurred = true; ++NumErrors; } - + // Finally, report it. Client->HandleDiagnostic(DiagLevel, Info); if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics; @@ -523,7 +523,7 @@ static void HandleSelectModifier(unsigned ValNo, const char *Argument, unsigned ArgumentLen, llvm::SmallVectorImpl &OutStr) { const char *ArgumentEnd = Argument+ArgumentLen; - + // Skip over 'ValNo' |'s. while (ValNo) { const char *NextVal = std::find(Argument, ArgumentEnd, '|'); @@ -532,7 +532,7 @@ static void HandleSelectModifier(unsigned ValNo, Argument = NextVal+1; // Skip this string. --ValNo; } - + // Get the end of the value. This is either the } or the |. const char *EndPtr = std::find(Argument, ArgumentEnd, '|'); // Add the value to the output string. @@ -605,7 +605,7 @@ static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { // Scan for next or-expr part. Start = std::find(Start, End, ','); - if(Start == End) + if (Start == End) break; ++Start; } @@ -674,7 +674,7 @@ void DiagnosticInfo:: FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { const char *DiagStr = getDiags()->getDescription(getID()); const char *DiagEnd = DiagStr+strlen(DiagStr); - + while (DiagStr != DiagEnd) { if (DiagStr[0] != '%') { // Append non-%0 substrings to Str if we have one. @@ -687,10 +687,10 @@ FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { DiagStr += 2; continue; } - + // Skip the %. ++DiagStr; - + // This must be a placeholder for a diagnostic argument. The format for a // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". // The digit is a number from 0-9 indicating which argument this comes from. @@ -698,7 +698,7 @@ FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { // brace enclosed string. const char *Modifier = 0, *Argument = 0; unsigned ModifierLen = 0, ArgumentLen = 0; - + // Check to see if we have a modifier. If so eat it. if (!isdigit(DiagStr[0])) { Modifier = DiagStr; @@ -711,14 +711,14 @@ FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { if (DiagStr[0] == '{') { ++DiagStr; // Skip {. Argument = DiagStr; - + for (; DiagStr[0] != '}'; ++DiagStr) assert(DiagStr[0] && "Mismatched {}'s in diagnostic string!"); ArgumentLen = DiagStr-Argument; ++DiagStr; // Skip }. } } - + assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); unsigned ArgNo = *DiagStr++ - '0'; @@ -737,14 +737,14 @@ FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { // Don't crash if get passed a null pointer by accident. if (!S) S = "(null)"; - + OutStr.append(S, S + strlen(S)); break; } // ---- INTEGERS ---- case Diagnostic::ak_sint: { int Val = getArgSInt(ArgNo); - + if (ModifierIs(Modifier, ModifierLen, "select")) { HandleSelectModifier((unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "s")) { @@ -761,7 +761,7 @@ FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { } case Diagnostic::ak_uint: { unsigned Val = getArgUInt(ArgNo); - + if (ModifierIs(Modifier, ModifierLen, "select")) { HandleSelectModifier(Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "s")) { @@ -770,7 +770,7 @@ FormatDiagnostic(llvm::SmallVectorImpl &OutStr) const { HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); } else { assert(ModifierLen == 0 && "Unknown integer modifier"); - + // FIXME: Optimize std::string S = llvm::utostr_32(Val); OutStr.append(S.begin(), S.end()); diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp index aadafa558435d5557f043f4be80df2f7a69bd37a..e0a7e657563bee53794be6cc4191667b187db008 100644 --- a/clang/lib/Basic/FileManager.cpp +++ b/clang/lib/Basic/FileManager.cpp @@ -47,8 +47,7 @@ using namespace clang; #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\') namespace { - static std::string GetFullPath(const char *relPath) - { + static std::string GetFullPath(const char *relPath) { char *absPathStrPtr = _fullpath(NULL, relPath, 0); assert(absPathStrPtr && "_fullpath() returned NULL!"); @@ -62,7 +61,7 @@ namespace { class FileManager::UniqueDirContainer { /// UniqueDirs - Cache from full path to existing directories/files. /// - llvm::StringMap UniqueDirs; + llvm::StringMap UniqueDirs; public: DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) { @@ -72,7 +71,7 @@ public: FullPath.c_str() + FullPath.size() ).getValue(); } - + size_t size() { return UniqueDirs.size(); } }; @@ -104,7 +103,7 @@ public: class FileManager::UniqueDirContainer { /// UniqueDirs - Cache from ID's to existing directories/files. /// - std::map, DirectoryEntry> UniqueDirs; + std::map, DirectoryEntry> UniqueDirs; public: DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) { @@ -152,27 +151,27 @@ FileManager::~FileManager() { /// getDirectory - Lookup, cache, and verify the specified directory. This /// returns null if the directory doesn't exist. -/// +/// const DirectoryEntry *FileManager::getDirectory(const char *NameStart, const char *NameEnd) { ++NumDirLookups; llvm::StringMapEntry &NamedDirEnt = DirEntries.GetOrCreateValue(NameStart, NameEnd); - + // See if there is already an entry in the map. if (NamedDirEnt.getValue()) return NamedDirEnt.getValue() == NON_EXISTENT_DIR ? 0 : NamedDirEnt.getValue(); - + ++NumDirCacheMisses; - + // By default, initialize it to invalid. NamedDirEnt.setValue(NON_EXISTENT_DIR); - + // Get the null-terminated directory name as stored as the key of the // DirEntries map. const char *InterndDirName = NamedDirEnt.getKeyData(); - + // Check to see if the directory exists. struct stat StatBuf; if (stat_cached(InterndDirName, &StatBuf) || // Error stat'ing. @@ -180,13 +179,13 @@ const DirectoryEntry *FileManager::getDirectory(const char *NameStart, return 0; // It exists. See if we have already opened a directory with the same inode. - // This occurs when one dir is symlinked to another, for example. + // This occurs when one dir is symlinked to another, for example. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf); - + NamedDirEnt.setValue(&UDE); if (UDE.getName()) // Already have an entry with this inode, return it. return &UDE; - + // Otherwise, we don't have this directory yet, add it. We use the string // key from the DirEntries map as the string. UDE.Name = InterndDirName; @@ -199,11 +198,11 @@ const DirectoryEntry *FileManager::getDirectory(const char *NameStart, /// getFile - Lookup, cache, and verify the specified file. This returns null /// if the file doesn't exist. -/// +/// const FileEntry *FileManager::getFile(const char *NameStart, const char *NameEnd) { ++NumFileLookups; - + // See if there is already an entry in the map. llvm::StringMapEntry &NamedFileEnt = FileEntries.GetOrCreateValue(NameStart, NameEnd); @@ -212,7 +211,7 @@ const FileEntry *FileManager::getFile(const char *NameStart, if (NamedFileEnt.getValue()) return NamedFileEnt.getValue() == NON_EXISTENT_FILE ? 0 : NamedFileEnt.getValue(); - + ++NumFileCacheMisses; // By default, initialize it to invalid. @@ -227,7 +226,7 @@ const FileEntry *FileManager::getFile(const char *NameStart, // Ignore duplicate //'s. while (SlashPos > NameStart && IS_DIR_SEPARATOR_CHAR(SlashPos[-1])) --SlashPos; - + const DirectoryEntry *DirInfo; if (SlashPos < NameStart) { // Use the current directory if file has no path component. @@ -237,17 +236,17 @@ const FileEntry *FileManager::getFile(const char *NameStart, return 0; // If filename ends with a /, it's a directory. else DirInfo = getDirectory(NameStart, SlashPos); - + if (DirInfo == 0) // Directory doesn't exist, file can't exist. return 0; - + // Get the null-terminated file name as stored as the key of the // FileEntries map. const char *InterndFileName = NamedFileEnt.getKeyData(); - + // FIXME: Use the directory info to prune this, before doing the stat syscall. // FIXME: This will reduce the # syscalls. - + // Nope, there isn't. Check to see if the file exists. struct stat StatBuf; //llvm::errs() << "STATING: " << Filename; @@ -258,11 +257,11 @@ const FileEntry *FileManager::getFile(const char *NameStart, return 0; } //llvm::errs() << ": exists\n"; - + // It exists. See if we have already opened a file with the same inode. // This occurs when one dir is symlinked to another, for example. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf); - + NamedFileEnt.setValue(&UFE); if (UFE.getName()) // Already have an entry with this inode, return it. return &UFE; @@ -286,14 +285,14 @@ void FileManager::PrintStats() const { << NumDirCacheMisses << " dir cache misses.\n"; llvm::errs() << NumFileLookups << " file lookups, " << NumFileCacheMisses << " file cache misses.\n"; - + //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; } int MemorizeStatCalls::stat(const char *path, struct stat *buf) { int result = ::stat(path, buf); - - if (result != 0) { + + if (result != 0) { // Cache failed 'stat' results. struct stat empty; StatCalls[path] = StatResult(result, empty); @@ -303,6 +302,6 @@ int MemorizeStatCalls::stat(const char *path, struct stat *buf) { // paths. StatCalls[path] = StatResult(result, *buf); } - - return result; + + return result; } diff --git a/clang/lib/Basic/IdentifierTable.cpp b/clang/lib/Basic/IdentifierTable.cpp index 3810c49f71f3192d400e08a84f51fb968bd096af..93c260fdbe17a180ed6b030778887cc26347915d 100644 --- a/clang/lib/Basic/IdentifierTable.cpp +++ b/clang/lib/Basic/IdentifierTable.cpp @@ -109,9 +109,9 @@ static void AddCXXOperatorKeyword(const char *Keyword, unsigned KWLen, Info.setIsCPlusPlusOperatorKeyword(); } -/// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or +/// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or /// "property". -static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID, +static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID, const char *Name, unsigned NameLen, IdentifierTable &Table) { Table.get(Name, Name+NameLen).setObjCKeywordID(ObjCID); @@ -144,13 +144,13 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { // the first and third character. For preprocessor ID's there are no // collisions (if there were, the switch below would complain about duplicate // case values). Note that this depends on 'if' being null terminated. - + #define HASH(LEN, FIRST, THIRD) \ (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) #define CASE(LEN, FIRST, THIRD, NAME) \ case HASH(LEN, FIRST, THIRD): \ return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME - + unsigned Len = getLength(); if (Len < 2) return tok::pp_not_keyword; const char *Name = getName(); @@ -179,7 +179,7 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { CASE( 8, 'u', 'a', unassert); CASE(12, 'i', 'c', include_next); - + CASE(16, '_', 'i', __include_macros); #undef CASE #undef HASH @@ -198,7 +198,7 @@ void IdentifierTable::PrintStats() const { unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; unsigned AverageIdentifierSize = 0; unsigned MaxIdentifierLength = 0; - + // TODO: Figure out maximum times an identifier had to probe for -stats. for (llvm::StringMap::const_iterator I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { @@ -207,7 +207,7 @@ void IdentifierTable::PrintStats() const { if (MaxIdentifierLength < IdLen) MaxIdentifierLength = IdLen; } - + fprintf(stderr, "\n*** Identifier Table Stats:\n"); fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); @@ -216,7 +216,7 @@ void IdentifierTable::PrintStats() const { fprintf(stderr, "Ave identifier length: %f\n", (AverageIdentifierSize/(double)NumIdentifiers)); fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); - + // Compute statistics about the memory allocated for identifiers. HashTable.getAllocator().PrintStats(); } @@ -232,42 +232,42 @@ unsigned llvm::DenseMapInfo::getHashValue(clang::Selector S) { namespace clang { /// MultiKeywordSelector - One of these variable length records is kept for each /// selector containing more than one keyword. We use a folding set -/// to unique aggregate names (keyword selectors in ObjC parlance). Access to +/// to unique aggregate names (keyword selectors in ObjC parlance). Access to /// this class is provided strictly through Selector. -class MultiKeywordSelector +class MultiKeywordSelector : public DeclarationNameExtra, public llvm::FoldingSetNode { MultiKeywordSelector(unsigned nKeys) { ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; } -public: +public: // Constructor for keyword selectors. MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) { assert((nKeys > 1) && "not a multi-keyword selector"); ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; - + // Fill in the trailing keyword array. IdentifierInfo **KeyInfo = reinterpret_cast(this+1); for (unsigned i = 0; i != nKeys; ++i) KeyInfo[i] = IIV[i]; - } - + } + // getName - Derive the full selector name and return it. std::string getName() const; - + unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; } - + typedef IdentifierInfo *const *keyword_iterator; keyword_iterator keyword_begin() const { return reinterpret_cast(this+1); } - keyword_iterator keyword_end() const { - return keyword_begin()+getNumArgs(); + keyword_iterator keyword_end() const { + return keyword_begin()+getNumArgs(); } IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); return keyword_begin()[i]; } - static void Profile(llvm::FoldingSetNodeID &ID, + static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys, unsigned NumArgs) { ID.AddInteger(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) @@ -287,7 +287,7 @@ unsigned Selector::getNumArgs() const { return 1; // We point to a MultiKeywordSelector (pointer doesn't contain any flags). MultiKeywordSelector *SI = reinterpret_cast(InfoPtr); - return SI->getNumArgs(); + return SI->getNumArgs(); } IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { @@ -308,16 +308,16 @@ std::string MultiKeywordSelector::getName() const { Length += (*I)->getLength(); ++Length; // : } - + Result.reserve(Length); - + for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { if (*I) Result.insert(Result.end(), (*I)->getName(), (*I)->getName()+(*I)->getLength()); Result.push_back(':'); } - + return Result; } @@ -327,7 +327,7 @@ std::string Selector::getAsString() const { if (InfoPtr & ArgFlags) { IdentifierInfo *II = getAsIdentifierInfo(); - + // If the number of arguments is 0 then II is guaranteed to not be null. if (getNumArgs() == 0) return II->getName(); @@ -336,7 +336,7 @@ std::string Selector::getAsString() const { Res += ":"; return Res; } - + // We have a multiple keyword selector (no embedded flags). return reinterpret_cast(InfoPtr)->getName(); } @@ -357,9 +357,9 @@ static SelectorTableImpl &getSelectorTableImpl(void *P) { Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { if (nKeys < 2) return Selector(IIV[0], nKeys); - + SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); - + // Unique selector, to guarantee there is one per name. llvm::FoldingSetNodeID ID; MultiKeywordSelector::Profile(ID, IIV, nKeys); @@ -368,12 +368,12 @@ Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { if (MultiKeywordSelector *SI = SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) return Selector(SI); - + // MultiKeywordSelector objects are not allocated with new because they have a // variable size array (for parameter types) at the end of them. unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); MultiKeywordSelector *SI = - (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size, + (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size, llvm::alignof()); new (SI) MultiKeywordSelector(nKeys, IIV); SelTabImpl.Table.InsertNode(SI, InsertPos); diff --git a/clang/lib/Basic/SourceLocation.cpp b/clang/lib/Basic/SourceLocation.cpp index f21ec8b1e9d7ed1246bb296e06066b5830c2dea4..578a4eb34bab50a54a8c13daab275fd15a3dbd00 100644 --- a/clang/lib/Basic/SourceLocation.cpp +++ b/clang/lib/Basic/SourceLocation.cpp @@ -40,7 +40,7 @@ void SourceLocation::print(llvm::raw_ostream &OS, const SourceManager &SM)const{ OS << ""; return; } - + if (isFileID()) { PresumedLoc PLoc = SM.getPresumedLoc(*this); // The instantiation and spelling pos is identical for file locs. @@ -48,7 +48,7 @@ void SourceLocation::print(llvm::raw_ostream &OS, const SourceManager &SM)const{ << ':' << PLoc.getColumn(); return; } - + SM.getInstantiationLoc(*this).print(OS, SM); OS << " getSize() : Buffer->getBufferSize(); } -const llvm::MemoryBuffer *ContentCache::getBuffer() const { +const llvm::MemoryBuffer *ContentCache::getBuffer() const { // Lazily create the Buffer for ContentCaches that wrap files. if (!Buffer && Entry) { // FIXME: Should we support a way to not have to do this check over @@ -59,11 +59,11 @@ const llvm::MemoryBuffer *ContentCache::getBuffer() const { unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) { // Look up the filename in the string table, returning the pre-existing value // if it exists. - llvm::StringMapEntry &Entry = + llvm::StringMapEntry &Entry = FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U); if (Entry.getValue() != ~0U) return Entry.getValue(); - + // Otherwise, assign this the next available ID. Entry.setValue(FilenamesByID.size()); FilenamesByID.push_back(&Entry); @@ -76,25 +76,25 @@ unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) { void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, unsigned LineNo, int FilenameID) { std::vector &Entries = LineEntries[FID]; - + assert((Entries.empty() || Entries.back().FileOffset < Offset) && "Adding line entries out of order!"); - + SrcMgr::CharacteristicKind Kind = SrcMgr::C_User; unsigned IncludeOffset = 0; - + if (!Entries.empty()) { // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember // that we are still in "foo.h". if (FilenameID == -1) FilenameID = Entries.back().FilenameID; - + // If we are after a line marker that switched us to system header mode, or // that set #include information, preserve it. Kind = Entries.back().FileKind; IncludeOffset = Entries.back().IncludeOffset; } - + Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind, IncludeOffset)); } @@ -109,9 +109,9 @@ void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, unsigned EntryExit, SrcMgr::CharacteristicKind FileKind) { assert(FilenameID != -1 && "Unspecified filename should use other accessor"); - + std::vector &Entries = LineEntries[FID]; - + assert((Entries.empty() || Entries.back().FileOffset < Offset) && "Adding line entries out of order!"); @@ -123,14 +123,14 @@ void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, } else if (EntryExit == 2) { assert(!Entries.empty() && Entries.back().IncludeOffset && "PPDirectives should have caught case when popping empty include stack"); - + // Get the include loc of the last entries' include loc as our include loc. IncludeOffset = 0; if (const LineEntry *PrevEntry = FindNearestLineEntry(FID, Entries.back().IncludeOffset)) IncludeOffset = PrevEntry->IncludeOffset; } - + Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, IncludeOffset)); } @@ -138,7 +138,7 @@ void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, /// FindNearestLineEntry - Find the line entry nearest to FID that is before /// it. If there is no line entry before Offset in FID, return null. -const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID, +const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID, unsigned Offset) { const std::vector &Entries = LineEntries[FID]; assert(!Entries.empty() && "No #line entries for this FID after all!"); @@ -157,13 +157,13 @@ const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID, /// \brief Add a new line entry that has already been encoded into /// the internal representation of the line table. -void LineTableInfo::AddEntry(unsigned FID, +void LineTableInfo::AddEntry(unsigned FID, const std::vector &Entries) { LineEntries[FID] = Entries; } /// getLineTableFilenameID - Return the uniqued ID for the specified filename. -/// +/// unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) { if (LineTable == 0) LineTable = new LineTableInfo(); @@ -177,12 +177,12 @@ unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) { void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID) { std::pair LocInfo = getDecomposedInstantiationLoc(Loc); - + const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile(); // Remember that this file has #line directives now if it doesn't already. const_cast(FileInfo).setHasLineDirectives(); - + if (LineTable == 0) LineTable = new LineTableInfo(); LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID); @@ -200,16 +200,16 @@ void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, "Can't set flags without setting the filename!"); return AddLineNote(Loc, LineNo, FilenameID); } - + std::pair LocInfo = getDecomposedInstantiationLoc(Loc); const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile(); - + // Remember that this file has #line directives now if it doesn't already. const_cast(FileInfo).setHasLineDirectives(); - + if (LineTable == 0) LineTable = new LineTableInfo(); - + SrcMgr::CharacteristicKind FileKind; if (IsExternCHeader) FileKind = SrcMgr::C_ExternCSystem; @@ -217,13 +217,13 @@ void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, FileKind = SrcMgr::C_System; else FileKind = SrcMgr::C_User; - + unsigned EntryExit = 0; if (IsFileEntry) EntryExit = 1; else if (IsFileExit) EntryExit = 2; - + LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID, EntryExit, FileKind); } @@ -240,7 +240,7 @@ LineTableInfo &SourceManager::getLineTable() { SourceManager::~SourceManager() { delete LineTable; - + // Delete FileEntry objects corresponding to content caches. Since the actual // content cache objects are bump pointer allocated, we just have to run the // dtors, but we call the deallocate method for completeness. @@ -261,10 +261,10 @@ void SourceManager::clearIDTables() { LastLineNoFileIDQuery = FileID(); LastLineNoContentCache = 0; LastFileIDLookup = FileID(); - + if (LineTable) LineTable->clear(); - + // Use up FileID #0 as an invalid instantiation. NextOffset = 0; createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1); @@ -275,11 +275,11 @@ void SourceManager::clearIDTables() { const ContentCache * SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) { assert(FileEnt && "Didn't specify a file entry to use?"); - + // Do we already have information about this file? ContentCache *&Entry = FileInfos[FileEnt]; if (Entry) return Entry; - + // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned // so that FileInfo can use the low 3 bits of the pointer for its own // nefarious purposes. @@ -349,12 +349,12 @@ FileID SourceManager::createFileID(const ContentCache *File, if (PreallocatedID) { // If we're filling in a preallocated ID, just load in the file // entry and return. - assert(PreallocatedID < SLocEntryLoaded.size() && + assert(PreallocatedID < SLocEntryLoaded.size() && "Preallocate ID out-of-range"); - assert(!SLocEntryLoaded[PreallocatedID] && + assert(!SLocEntryLoaded[PreallocatedID] && "Source location entry already loaded"); assert(Offset && "Preallocate source location cannot have zero offset"); - SLocEntryTable[PreallocatedID] + SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter)); SLocEntryLoaded[PreallocatedID] = true; FileID FID = FileID::get(PreallocatedID); @@ -363,13 +363,13 @@ FileID SourceManager::createFileID(const ContentCache *File, return LastFileIDLookup = FID; } - SLocEntryTable.push_back(SLocEntry::get(NextOffset, + SLocEntryTable.push_back(SLocEntry::get(NextOffset, FileInfo::get(IncludePos, File, FileCharacter))); unsigned FileSize = File->getSize(); assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!"); NextOffset += FileSize+1; - + // Set LastFileIDLookup to the newly created file. The next getFileID call is // almost guaranteed to be from that file. FileID FID = FileID::get(SLocEntryTable.size()-1); @@ -391,9 +391,9 @@ SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc, if (PreallocatedID) { // If we're filling in a preallocated ID, just load in the // instantiation entry and return. - assert(PreallocatedID < SLocEntryLoaded.size() && + assert(PreallocatedID < SLocEntryLoaded.size() && "Preallocate ID out-of-range"); - assert(!SLocEntryLoaded[PreallocatedID] && + assert(!SLocEntryLoaded[PreallocatedID] && "Source location entry already loaded"); assert(Offset && "Preallocate source location cannot have zero offset"); SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II); @@ -426,7 +426,7 @@ SourceManager::getBufferData(FileID FID) const { /// FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { assert(SLocOffset && "Invalid FileID"); - + // After the first and second level caches, I see two common sorts of // behavior: 1) a lot of searched FileID's are "near" the cached file location // or are "near" the cached instantiation location. 2) others are just @@ -435,11 +435,11 @@ FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { // To handle this, we do a linear search for up to 8 steps to catch #1 quickly // then we fall back to a less cache efficient, but more scalable, binary // search to find the location. - + // See if this is near the file point - worst case we start scanning from the // most newly created FileID. std::vector::const_iterator I; - + if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) { // Neither loc prunes our search. I = SLocEntryTable.end(); @@ -474,7 +474,7 @@ FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { if (++NumProbes == 8) break; } - + // Convert "I" back into an index. We know that it is an entry whose index is // larger than the offset we are looking for. unsigned GreaterIndex = I-SLocEntryTable.begin(); @@ -486,16 +486,16 @@ FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { while (1) { unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset(); - + ++NumProbes; - + // If the offset of the midpoint is too large, chop the high side of the // range to the midpoint. if (MidOffset > SLocOffset) { GreaterIndex = MiddleIndex; continue; } - + // If the middle index contains the value, succeed and return. if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) { #if 0 @@ -513,7 +513,7 @@ FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { NumBinaryProbes += NumProbes; return Res; } - + // Otherwise, move the low-side up to the middle index. LessIndex = MiddleIndex; } @@ -550,12 +550,12 @@ SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E, SourceLocation Loc; do { Loc = E->getInstantiation().getInstantiationLocStart(); - + FID = getFileID(Loc); E = &getSLocEntry(FID); Offset += Loc.getOffset()-E->getOffset(); } while (!Loc.isFileID()); - + return std::make_pair(FID, Offset); } @@ -568,12 +568,12 @@ SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, SourceLocation Loc; do { Loc = E->getInstantiation().getSpellingLoc(); - + FID = getFileID(Loc); E = &getSLocEntry(FID); Offset += Loc.getOffset()-E->getOffset(); } while (!Loc.isFileID()); - + return std::make_pair(FID, Offset); } @@ -603,10 +603,10 @@ SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const { std::pair SourceManager::getInstantiationRange(SourceLocation Loc) const { if (Loc.isFileID()) return std::make_pair(Loc, Loc); - + std::pair Res = getImmediateInstantiationRange(Loc); - + // Fully resolve the start and end locations to their ultimate instantiation // points. while (!Res.first.isFileID()) @@ -628,7 +628,7 @@ const char *SourceManager::getCharacterData(SourceLocation SL) const { // Note that this is a hot function in the getSpelling() path, which is // heavily used by -E mode. std::pair LocInfo = getDecomposedSpellingLoc(SL); - + // Note that calling 'getBuffer()' may lazily page in a source file. return getSLocEntry(LocInfo.first).getFile().getContentCache() ->getBuffer()->getBufferStart() + LocInfo.second; @@ -639,7 +639,7 @@ const char *SourceManager::getCharacterData(SourceLocation SL) const { /// this is significantly cheaper to compute than the line number. unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const { const char *Buf = getBuffer(FID)->getBufferStart(); - + unsigned LineStart = FilePos; while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') --LineStart; @@ -662,17 +662,17 @@ unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const { static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc) DISABLE_INLINE; -static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){ +static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){ // Note that calling 'getBuffer()' may lazily page in the file. const MemoryBuffer *Buffer = FI->getBuffer(); - + // Find the file offsets of all of the *physical* source lines. This does // not look at trigraphs, escaped newlines, or anything else tricky. std::vector LineOffsets; - + // Line #1 starts at char 0. LineOffsets.push_back(0); - + const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart(); const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd(); unsigned Offs = 0; @@ -685,7 +685,7 @@ static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){ ++NextBuf; Offs += NextBuf-Buf; Buf = NextBuf; - + if (Buf[0] == '\n' || Buf[0] == '\r') { // If this is \n\r or \r\n, skip both characters. if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) @@ -699,7 +699,7 @@ static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){ ++Offs, ++Buf; } } - + // Copy the offsets into the FileInfo structure. FI->NumLines = LineOffsets.size(); FI->SourceLineCache = Alloc.Allocate(LineOffsets.size()); @@ -717,7 +717,7 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const { else Content = const_cast(getSLocEntry(FID) .getFile().getContentCache()); - + // If this is the first use of line information for this buffer, compute the /// SourceLineCache for it on demand. if (Content->SourceLineCache == 0) @@ -728,11 +728,11 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const { unsigned *SourceLineCache = Content->SourceLineCache; unsigned *SourceLineCacheStart = SourceLineCache; unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines; - + unsigned QueriedFilePos = FilePos+1; // FIXME: I would like to be convinced that this code is worth being as - // complicated as it is, binary search isn't that slow. + // complicated as it is, binary search isn't that slow. // // If it is worth being optimized, then in my opinion it could be more // performant, simpler, and more obviously correct by just "galloping" outward @@ -748,7 +748,7 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const { if (QueriedFilePos >= LastLineNoFilePos) { // FIXME: Potential overflow? SourceLineCache = SourceLineCache+LastLineNoResult-1; - + // The query is likely to be nearby the previous one. Here we check to // see if it is within 5, 10 or 20 lines. It can be far away in cases // where big comment blocks and vertical whitespace eat up lines but @@ -770,17 +770,17 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const { SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; } } - + // If the spread is large, do a "radix" test as our initial guess, based on // the assumption that lines average to approximately the same length. // NOTE: This is currently disabled, as it does not appear to be profitable in // initial measurements. if (0 && SourceLineCacheEnd-SourceLineCache > 20) { unsigned FileLen = Content->SourceLineCache[Content->NumLines-1]; - + // Take a stab at guessing where it is. unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen; - + // Check for -10 and +10 lines. unsigned LowerBound = std::max(int(ApproxPos-10), 0); unsigned UpperBound = std::min(ApproxPos+10, FileLen); @@ -789,17 +789,17 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const { if (SourceLineCache < SourceLineCacheStart+LowerBound && SourceLineCacheStart[LowerBound] < QueriedFilePos) SourceLineCache = SourceLineCacheStart+LowerBound; - + // If the computed upper bound is greater than the query location, move it. if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound && SourceLineCacheStart[UpperBound] >= QueriedFilePos) SourceLineCacheEnd = SourceLineCacheStart+UpperBound; } - + unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); unsigned LineNo = Pos-SourceLineCacheStart; - + LastLineNoFileIDQuery = FID; LastLineNoContentCache = Content; LastLineNoFilePos = QueriedFilePos; @@ -819,14 +819,14 @@ unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const { } /// getFileCharacteristic - return the file characteristic of the specified -/// source location, indicating whether this is a normal file, a system +/// source location, indicating whether this is a normal file, a system /// header, or an "implicit extern C" system header. /// /// This state can be modified with flags on GNU linemarker directives like: /// # 4 "foo.h" 3 /// which changes all source locations in the current file after that to be /// considered to be from a system header. -SrcMgr::CharacteristicKind +SrcMgr::CharacteristicKind SourceManager::getFileCharacteristic(SourceLocation Loc) const { assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!"); std::pair LocInfo = getDecomposedInstantiationLoc(Loc); @@ -836,12 +836,12 @@ SourceManager::getFileCharacteristic(SourceLocation Loc) const { // state. if (!FI.hasLineDirectives()) return FI.getFileCharacteristic(); - + assert(LineTable && "Can't have linetable entries without a LineTable!"); // See if there is a #line directive before the location. const LineEntry *Entry = LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second); - + // If this is before the first line marker, use the file characteristic. if (!Entry) return FI.getFileCharacteristic(); @@ -854,7 +854,7 @@ SourceManager::getFileCharacteristic(SourceLocation Loc) const { /// for normal clients. const char *SourceManager::getBufferName(SourceLocation Loc) const { if (Loc.isInvalid()) return ""; - + return getBuffer(getFileID(Loc))->getBufferIdentifier(); } @@ -868,22 +868,22 @@ const char *SourceManager::getBufferName(SourceLocation Loc) const { /// of an instantiation location, not at the spelling location. PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const { if (Loc.isInvalid()) return PresumedLoc(); - + // Presumed locations are always for instantiation points. std::pair LocInfo = getDecomposedInstantiationLoc(Loc); - + const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile(); const SrcMgr::ContentCache *C = FI.getContentCache(); - + // To get the source name, first consult the FileEntry (if one exists) // before the MemBuffer as this will avoid unnecessarily paging in the // MemBuffer. - const char *Filename = + const char *Filename = C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier(); unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second); unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second); SourceLocation IncludeLoc = FI.getIncludeLoc(); - + // If we have #line directives in this file, update and overwrite the physical // location info if appropriate. if (FI.hasLineDirectives()) { @@ -901,9 +901,9 @@ PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const { // total. unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); - + // Note that column numbers are not molested by line markers. - + // Handle virtual #include manipulation. if (Entry->IncludeOffset) { IncludeLoc = getLocForStartOfFile(LocInfo.first); @@ -932,7 +932,7 @@ SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, if (FI == FileInfos.end()) return SourceLocation(); ContentCache *Content = FI->second; - + // If this is the first use of line information for this buffer, compute the /// SourceLineCache for it on demand. if (Content->SourceLineCache == 0) @@ -940,7 +940,7 @@ SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, if (Line > Content->NumLines) return SourceLocation(); - + unsigned FilePos = Content->SourceLineCache[Line - 1]; const char *Buf = Content->getBuffer()->getBufferStart() + FilePos; unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf; @@ -951,7 +951,7 @@ SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, ++i; if (i < Col-1) return SourceLocation(); - + return getLocForStartOfFile(Content->FirstFID). getFileLocWithOffset(FilePos + Col - 1); } @@ -964,24 +964,24 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!"); if (LHS == RHS) return false; - + std::pair LOffs = getDecomposedLoc(LHS); std::pair ROffs = getDecomposedLoc(RHS); - + // If the source locations are in the same file, just compare offsets. if (LOffs.first == ROffs.first) return LOffs.second < ROffs.second; // If we are comparing a source location with multiple locations in the same // file, we get a big win by caching the result. - + if (LastLFIDForBeforeTUCheck == LOffs.first && LastRFIDForBeforeTUCheck == ROffs.first) return LastResForBeforeTUCheck; - + LastLFIDForBeforeTUCheck = LOffs.first; LastRFIDForBeforeTUCheck = ROffs.first; - + // "Traverse" the include/instantiation stacks of both locations and try to // find a common "ancestor". // @@ -999,15 +999,15 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, UpperLoc = Entry.getInstantiation().getInstantiationLocStart(); else UpperLoc = Entry.getFile().getIncludeLoc(); - + if (UpperLoc.isInvalid()) break; // We reached the top. - + ROffs = getDecomposedLoc(UpperLoc); - + if (LOffs.first == ROffs.first) return LastResForBeforeTUCheck = LOffs.second < ROffs.second; - + ROffsMap[ROffs.first] = ROffs.second; } @@ -1021,33 +1021,33 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, UpperLoc = Entry.getInstantiation().getInstantiationLocStart(); else UpperLoc = Entry.getFile().getIncludeLoc(); - + if (UpperLoc.isInvalid()) break; // We reached the top. - + LOffs = getDecomposedLoc(UpperLoc); - + std::map::iterator I = ROffsMap.find(LOffs.first); if (I != ROffsMap.end()) return LastResForBeforeTUCheck = LOffs.second < I->second; } - + // No common ancestor. // Now we are getting into murky waters. Most probably this is because one // location is in the predefines buffer. - + const FileEntry *LEntry = getSLocEntry(LOffs.first).getFile().getContentCache()->Entry; const FileEntry *REntry = getSLocEntry(ROffs.first).getFile().getContentCache()->Entry; - + // If the locations are in two memory buffers we give up, we can't answer // which one should be considered first. // FIXME: Should there be a way to "include" memory buffers in the translation // unit ? assert((LEntry != 0 || REntry != 0) && "Locations in memory buffers."); (void) REntry; - + // Consider the memory buffer as coming before the file in the translation // unit. if (LEntry == 0) @@ -1066,14 +1066,14 @@ void SourceManager::PrintStats() const { << " mem buffers mapped.\n"; llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, " << NextOffset << "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){ NumLineNumsComputed += I->second->SourceLineCache != 0; NumFileBytesMapped += I->second->getSizeBytesMapped(); } - + llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " << NumLineNumsComputed << " files with line #'s computed.\n"; llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " diff --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp index 5b2ffb7d165c79dcf8cbcfdea86e8b780043a888..35d9ccd401da3fa087ebcdf032873e9edc3e52ca 100644 --- a/clang/lib/Basic/TargetInfo.cpp +++ b/clang/lib/Basic/TargetInfo.cpp @@ -87,17 +87,17 @@ static void removeGCCRegisterPrefix(const char *&Name) { bool TargetInfo::isValidGCCRegisterName(const char *Name) const { const char * const *Names; unsigned NumNames; - + // Get rid of any register prefix. removeGCCRegisterPrefix(Name); - + if (strcmp(Name, "memory") == 0 || strcmp(Name, "cc") == 0) return true; - + getGCCRegNames(Names, NumNames); - + // If we have a number it maps to an entry in the register name array. if (isdigit(Name[0])) { char *End; @@ -111,11 +111,11 @@ bool TargetInfo::isValidGCCRegisterName(const char *Name) const { if (strcmp(Name, Names[i]) == 0) return true; } - + // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; - + getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { @@ -125,15 +125,15 @@ bool TargetInfo::isValidGCCRegisterName(const char *Name) const { return true; } } - + return false; } const char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const { assert(isValidGCCRegisterName(Name) && "Invalid register passed in"); - + removeGCCRegisterPrefix(Name); - + const char * const *Names; unsigned NumNames; @@ -144,16 +144,16 @@ const char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const { char *End; int n = (int)strtol(Name, &End, 0); if (*End == 0) { - assert(n >= 0 && (unsigned)n < NumNames && + assert(n >= 0 && (unsigned)n < NumNames && "Out of bounds register number!"); return Names[n]; } } - + // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; - + getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { @@ -163,7 +163,7 @@ const char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const { return Aliases[i].Register; } } - + return Name; } @@ -200,10 +200,10 @@ bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const { Info.setAllowsMemory(); break; } - + Name++; } - + return true; } @@ -216,14 +216,14 @@ bool TargetInfo::resolveSymbolicName(const char *&Name, const char *Start = Name; while (*Name && *Name != ']') Name++; - + if (!*Name) { // Missing ']' return false; } - + std::string SymbolicName(Start, Name - Start); - + for (Index = 0; Index != NumOutputs; ++Index) if (SymbolicName == OutputConstraints[Index].getName()) return true; @@ -242,12 +242,12 @@ bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints, // Check if we have a matching constraint if (*Name >= '0' && *Name <= '9') { unsigned i = *Name - '0'; - + // Check if matching constraint is out of bounds. if (i >= NumOutputs) return false; - - // The constraint should have the same info as the respective + + // The constraint should have the same info as the respective // output constraint. Info.setTiedOperand(i, OutputConstraints[i]); } else if (!validateAsmConstraint(Name, Info)) { @@ -261,9 +261,9 @@ bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints, unsigned Index = 0; if (!resolveSymbolicName(Name, OutputConstraints, NumOutputs, Index)) return false; - + break; - } + } case '%': // commutative // FIXME: Fail if % is used with the last operand. break; @@ -291,9 +291,9 @@ bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints, Info.setAllowsMemory(); break; } - + Name++; } - + return true; } diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp index d9cd42c32328abc9eab82f00fe83953cb5dd51b5..4e63db6eaf385061499a502be729c863f82479e8 100644 --- a/clang/lib/Basic/Targets.cpp +++ b/clang/lib/Basic/Targets.cpp @@ -111,11 +111,11 @@ static void getDarwinOSXDefines(std::vector &Defs, const llvm::Triple &Triple) { if (Triple.getOS() != llvm::Triple::Darwin) return; - + // Figure out which "darwin number" the target triple is. "darwin9" -> 10.5. unsigned Maj, Min, Rev; Triple.getDarwinNumber(Maj, Min, Rev); - + char MacOSXStr[] = "1000"; if (Maj >= 4 && Maj <= 13) { // 10.0-10.9 // darwin7 -> 1030, darwin8 -> 1040, darwin9 -> 1050, etc. @@ -132,11 +132,11 @@ static void getDarwinIPhoneOSDefines(std::vector &Defs, const llvm::Triple &Triple) { if (Triple.getOS() != llvm::Triple::Darwin) return; - + // Figure out which "darwin number" the target triple is. "darwin9" -> 10.5. unsigned Maj, Min, Rev; Triple.getDarwinNumber(Maj, Min, Rev); - + // When targetting iPhone OS, interpret the minor version and // revision as the iPhone OS version char iPhoneOSStr[] = "10000"; @@ -155,7 +155,7 @@ static void getDarwinIPhoneOSDefines(std::vector &Defs, static void GetDarwinLanguageOptions(LangOptions &Opts, const llvm::Triple &Triple) { Opts.NeXTRuntime = true; - + if (Triple.getOS() != llvm::Triple::Darwin) return; @@ -183,7 +183,7 @@ protected: getDarwinDefines(Defines, Opts); getDarwinOSXDefines(Defines, Triple); } - + /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line /// options. @@ -204,7 +204,7 @@ public: virtual const char *getUnicodeStringSection() const { return "__TEXT,__ustring"; } - + virtual std::string isValidSectionSpecifier(const llvm::StringRef &SR) const { // Let MCSectionMachO validate this. llvm::StringRef Segment, Section; @@ -230,7 +230,7 @@ protected: DefineStd(Defs, "unix", Opts); } public: - DragonFlyBSDTargetInfo(const std::string &triple) + DragonFlyBSDTargetInfo(const std::string &triple) : OSTargetInfo(triple) {} }; @@ -258,7 +258,7 @@ protected: Define(Defs, "__ELF__", "1"); } public: - FreeBSDTargetInfo(const std::string &triple) + FreeBSDTargetInfo(const std::string &triple) : OSTargetInfo(triple) { this->UserLabelPrefix = ""; } @@ -279,7 +279,7 @@ protected: Define(Defs, "_REENTRANT", "1"); } public: - LinuxTargetInfo(const std::string& triple) + LinuxTargetInfo(const std::string& triple) : OSTargetInfo(triple) { this->UserLabelPrefix = ""; } @@ -299,7 +299,7 @@ protected: Define(Defs, "_POSIX_THREADS", "1"); } public: - NetBSDTargetInfo(const std::string &triple) + NetBSDTargetInfo(const std::string &triple) : OSTargetInfo(triple) { this->UserLabelPrefix = ""; } @@ -320,7 +320,7 @@ protected: Define(Defs, "_POSIX_THREADS", "1"); } public: - OpenBSDTargetInfo(const std::string &triple) + OpenBSDTargetInfo(const std::string &triple) : OSTargetInfo(triple) {} }; @@ -337,14 +337,14 @@ protected: Define(Defs, "__SVR4"); } public: - SolarisTargetInfo(const std::string& triple) + SolarisTargetInfo(const std::string& triple) : OSTargetInfo(triple) { this->UserLabelPrefix = ""; this->WCharType = this->SignedLong; // FIXME: WIntType should be SignedLong } }; -} // end anonymous namespace. +} // end anonymous namespace. /// GetWindowsLanguageOptions - Set the default language options for Windows. static void GetWindowsLanguageOptions(LangOptions &Opts, @@ -609,12 +609,12 @@ public: virtual bool setFeatureEnabled(llvm::StringMap &Features, const std::string &Name, bool Enabled) const; - virtual void getDefaultFeatures(const std::string &CPU, + virtual void getDefaultFeatures(const std::string &CPU, llvm::StringMap &Features) const; virtual void HandleTargetFeatures(const llvm::StringMap &Features); }; -void X86TargetInfo::getDefaultFeatures(const std::string &CPU, +void X86TargetInfo::getDefaultFeatures(const std::string &CPU, llvm::StringMap &Features) const { // FIXME: This should not be here. Features["3dnow"] = false; @@ -658,7 +658,7 @@ void X86TargetInfo::getDefaultFeatures(const std::string &CPU, setFeatureEnabled(Features, "sse4", true); else if (CPU == "k6" || CPU == "winchip-c6") setFeatureEnabled(Features, "mmx", true); - else if (CPU == "k6-2" || CPU == "k6-3" || CPU == "athlon" || + else if (CPU == "k6-2" || CPU == "k6-3" || CPU == "athlon" || CPU == "athlon-tbird" || CPU == "winchip2" || CPU == "c3") { setFeatureEnabled(Features, "mmx", true); setFeatureEnabled(Features, "3dnow", true); @@ -667,14 +667,14 @@ void X86TargetInfo::getDefaultFeatures(const std::string &CPU, setFeatureEnabled(Features, "3dnowa", true); } else if (CPU == "k8" || CPU == "opteron" || CPU == "athlon64" || CPU == "athlon-fx") { - setFeatureEnabled(Features, "sse2", true); + setFeatureEnabled(Features, "sse2", true); setFeatureEnabled(Features, "3dnowa", true); } else if (CPU == "c3-2") setFeatureEnabled(Features, "sse", true); } bool X86TargetInfo::setFeatureEnabled(llvm::StringMap &Features, - const std::string &Name, + const std::string &Name, bool Enabled) const { // FIXME: This *really* should not be here. if (!Features.count(Name) && Name != "sse4") @@ -688,13 +688,13 @@ bool X86TargetInfo::setFeatureEnabled(llvm::StringMap &Features, else if (Name == "sse2") Features["mmx"] = Features["sse"] = Features["sse2"] = true; else if (Name == "sse3") - Features["mmx"] = Features["sse"] = Features["sse2"] = + Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = true; else if (Name == "ssse3") - Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = + Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = Features["ssse3"] = true; else if (Name == "sse4") - Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = + Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = Features["ssse3"] = Features["sse41"] = Features["sse42"] = true; else if (Name == "3dnow") Features["3dnowa"] = true; @@ -702,16 +702,16 @@ bool X86TargetInfo::setFeatureEnabled(llvm::StringMap &Features, Features["3dnow"] = Features["3dnowa"] = true; } else { if (Name == "mmx") - Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = + Features["mmx"] = Features["sse"] = Features["sse2"] = Features["sse3"] = Features["ssse3"] = Features["sse41"] = Features["sse42"] = false; else if (Name == "sse") - Features["sse"] = Features["sse2"] = Features["sse3"] = + Features["sse"] = Features["sse2"] = Features["sse3"] = Features["ssse3"] = Features["sse41"] = Features["sse42"] = false; else if (Name == "sse2") - Features["sse2"] = Features["sse3"] = Features["ssse3"] = + Features["sse2"] = Features["sse3"] = Features["ssse3"] = Features["sse41"] = Features["sse42"] = false; else if (Name == "sse3") - Features["sse3"] = Features["ssse3"] = Features["sse41"] = + Features["sse3"] = Features["ssse3"] = Features["sse41"] = Features["sse42"] = false; else if (Name == "ssse3") Features["ssse3"] = Features["sse41"] = Features["sse42"] = false; @@ -963,7 +963,7 @@ public: namespace { class DarwinX86_64TargetInfo : public DarwinTargetInfo { public: - DarwinX86_64TargetInfo(const std::string& triple) + DarwinX86_64TargetInfo(const std::string& triple) : DarwinTargetInfo(triple) { Int64Type = SignedLongLong; } @@ -973,7 +973,7 @@ public: namespace { class OpenBSDX86_64TargetInfo : public OpenBSDTargetInfo { public: - OpenBSDX86_64TargetInfo(const std::string& triple) + OpenBSDX86_64TargetInfo(const std::string& triple) : OpenBSDTargetInfo(triple) { IntMaxType = SignedLongLong; UIntMaxType = UnsignedLongLong; @@ -1089,7 +1089,7 @@ public: namespace { -class DarwinARMTargetInfo : +class DarwinARMTargetInfo : public DarwinTargetInfo { protected: virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, @@ -1099,7 +1099,7 @@ protected: } public: - DarwinARMTargetInfo(const std::string& triple) + DarwinARMTargetInfo(const std::string& triple) : DarwinTargetInfo(triple) {} }; } // end anonymous namespace. @@ -1244,7 +1244,7 @@ namespace { Define(Defines, "__pic16"); Define(Defines, "rom", "__attribute__((address_space(1)))"); Define(Defines, "ram", "__attribute__((address_space(0)))"); - Define(Defines, "_section(SectName)", + Define(Defines, "_section(SectName)", "__attribute__((section(SectName)))"); Define(Defines, "_address(Addr)", "__attribute__((section(\"Address=\"#Addr)))"); @@ -1255,7 +1255,7 @@ namespace { } virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const {} - virtual const char *getVAListDeclaration() const { + virtual const char *getVAListDeclaration() const { return ""; } virtual const char *getClobbers() const { @@ -1480,12 +1480,12 @@ namespace { namespace { - // LLVM and Clang cannot be used directly to output native binaries for - // target, but is used to compile C code to llvm bitcode with correct + // LLVM and Clang cannot be used directly to output native binaries for + // target, but is used to compile C code to llvm bitcode with correct // type and alignment information. - // - // TCE uses the llvm bitcode as input and uses it for generating customized - // target processor and program binary. TCE co-design environment is + // + // TCE uses the llvm bitcode as input and uses it for generating customized + // target processor and program binary. TCE co-design environment is // publicly available in http://tce.cs.tut.fi class TCETargetInfo : public TargetInfo{ diff --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp index 0c98c40866aec50a82e3836788c79d973d6f54da..43b098e021254fd16f04a80af444fe2dd67d3c83 100644 --- a/clang/lib/CodeGen/CGBlocks.cpp +++ b/clang/lib/CodeGen/CGBlocks.cpp @@ -60,14 +60,14 @@ BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size, llvm::Constant *BlockModule::getNSConcreteGlobalBlock() { if (NSConcreteGlobalBlock == 0) - NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty, + NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty, "_NSConcreteGlobalBlock"); return NSConcreteGlobalBlock; } llvm::Constant *BlockModule::getNSConcreteStackBlock() { if (NSConcreteStackBlock == 0) - NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty, + NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty, "_NSConcreteStackBlock"); return NSConcreteStackBlock; } @@ -427,16 +427,16 @@ RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) { QualType ResultType = FnType->getAsFunctionType()->getResultType(); - const CGFunctionInfo &FnInfo = + const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(ResultType, Args); - + // Cast the function pointer to the right type. - const llvm::Type *BlockFTy = + const llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo, false); - + const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy); Func = Builder.CreateBitCast(Func, BlockFTyPtr); - + // And call the block. return EmitCall(FnInfo, Func, Args); } @@ -583,7 +583,7 @@ CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr, // Check if we should generate debug info for this block. if (CGM.getDebugInfo()) DebugInfo = CGM.getDebugInfo(); - + // Arrange for local static and local extern declarations to appear // to be local to this function as well, as they are directly referenced // in a block. @@ -591,7 +591,7 @@ CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr, i != ldm.end(); ++i) { const VarDecl *VD = dyn_cast(i->first); - + if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage()) LocalDeclMap[VD] = i->second; } @@ -609,7 +609,7 @@ CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr, const FunctionType *BlockFunctionType = BExpr->getFunctionType(); QualType ResultType; bool IsVariadic; - if (const FunctionProtoType *FTy = + if (const FunctionProtoType *FTy = dyn_cast(BlockFunctionType)) { ResultType = FTy->getResultType(); IsVariadic = FTy->isVariadic(); @@ -721,7 +721,7 @@ GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T, ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0, getContext().getPointerType(getContext().VoidTy)); Args.push_back(std::make_pair(Src, Src->getType())); - + const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args); @@ -803,7 +803,7 @@ GenerateDestroyHelperFunction(bool BlockHasCopyDispose, getContext().getPointerType(getContext().VoidTy)); Args.push_back(std::make_pair(Src, Src->getType())); - + const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args); @@ -887,7 +887,7 @@ GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) { ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0, getContext().getPointerType(getContext().VoidTy)); Args.push_back(std::make_pair(Src, Src->getType())); - + const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args); @@ -926,7 +926,7 @@ GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) { V = Builder.CreateStructGEP(V, 6, "x"); V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0)); llvm::Value *SrcObj = Builder.CreateLoad(V); - + flag |= BLOCK_BYREF_CALLER; llvm::Value *N = llvm::ConstantInt::get( @@ -951,7 +951,7 @@ BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T, getContext().getPointerType(getContext().VoidTy)); Args.push_back(std::make_pair(Src, Src->getType())); - + const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args); diff --git a/clang/lib/CodeGen/CGBlocks.h b/clang/lib/CodeGen/CGBlocks.h index 61415adc9b6a2c39c362523c09827a5847d8c256..6309e1d87d8d4b550de7d04d4c009ba37cac4f03 100644 --- a/clang/lib/CodeGen/CGBlocks.h +++ b/clang/lib/CodeGen/CGBlocks.h @@ -66,7 +66,7 @@ class BlockModule : public BlockBase { CodeGenTypes &Types; CodeGenModule &CGM; llvm::LLVMContext &VMContext; - + ASTContext &getContext() const { return Context; } llvm::Module &getModule() const { return TheModule; } CodeGenTypes &getTypes() { return Types; } @@ -89,7 +89,7 @@ public: /// NSConcreteStackBlock - Cached reference to the class poinnter for stack /// blocks. llvm::Constant *NSConcreteStackBlock; - + const llvm::Type *BlockDescriptorType; const llvm::Type *GenericBlockLiteralType; const llvm::Type *GenericExtendedBlockLiteralType; @@ -157,11 +157,11 @@ public: /// ByCopyDeclRefs - Variables from parent scopes that have been imported /// into this block. llvm::SmallVector ByCopyDeclRefs; - - // ByRefDeclRefs - __block variables from parent scopes that have been + + // ByRefDeclRefs - __block variables from parent scopes that have been // imported into this block. llvm::SmallVector ByRefDeclRefs; - + BlockInfo(const llvm::Type *blt, const char *n) : BlockLiteralTy(blt), Name(n) { // Skip asm prefix, if any. diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index bfb6be8b79179fbb811627fac44fd064cbb429b4..77c408a9638597f21fb4bd67a75e442b1edc6b45 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -25,21 +25,21 @@ using namespace llvm; /// Utility to insert an atomic instruction based on Instrinsic::ID /// and the expression node. -static RValue EmitBinaryAtomic(CodeGenFunction& CGF, +static RValue EmitBinaryAtomic(CodeGenFunction& CGF, Intrinsic::ID Id, const CallExpr *E) { const llvm::Type *ResType[2]; ResType[0] = CGF.ConvertType(E->getType()); ResType[1] = CGF.ConvertType(E->getArg(0)->getType()); Value *AtomF = CGF.CGM.getIntrinsic(Id, ResType, 2); - return RValue::get(CGF.Builder.CreateCall2(AtomF, - CGF.EmitScalarExpr(E->getArg(0)), + return RValue::get(CGF.Builder.CreateCall2(AtomF, + CGF.EmitScalarExpr(E->getArg(0)), CGF.EmitScalarExpr(E->getArg(1)))); } /// Utility to insert an atomic instruction based Instrinsic::ID and // the expression node, where the return value is the result of the // operation. -static RValue EmitBinaryAtomicPost(CodeGenFunction& CGF, +static RValue EmitBinaryAtomicPost(CodeGenFunction& CGF, Intrinsic::ID Id, const CallExpr *E, Instruction::BinaryOps Op) { const llvm::Type *ResType[2]; @@ -49,26 +49,26 @@ static RValue EmitBinaryAtomicPost(CodeGenFunction& CGF, Value *Ptr = CGF.EmitScalarExpr(E->getArg(0)); Value *Operand = CGF.EmitScalarExpr(E->getArg(1)); Value *Result = CGF.Builder.CreateCall2(AtomF, Ptr, Operand); - + if (Id == Intrinsic::atomic_load_nand) Result = CGF.Builder.CreateNot(Result); - - + + return RValue::get(CGF.Builder.CreateBinOp(Op, Result, Operand)); } -RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, +RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, unsigned BuiltinID, const CallExpr *E) { // See if we can constant fold this builtin. If so, don't emit it at all. Expr::EvalResult Result; if (E->Evaluate(Result, CGM.getContext())) { if (Result.Val.isInt()) - return RValue::get(llvm::ConstantInt::get(VMContext, + return RValue::get(llvm::ConstantInt::get(VMContext, Result.Val.getInt())); else if (Result.Val.isFloat()) return RValue::get(ConstantFP::get(VMContext, Result.Val.getFloat())); } - + switch (BuiltinID) { default: break; // Handle intrinsics and libm functions below. case Builtin::BI__builtin___CFStringMakeConstantString: @@ -77,13 +77,13 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_va_start: case Builtin::BI__builtin_va_end: { Value *ArgValue = EmitVAListRef(E->getArg(0)); - const llvm::Type *DestType = + const llvm::Type *DestType = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); if (ArgValue->getType() != DestType) - ArgValue = Builder.CreateBitCast(ArgValue, DestType, + ArgValue = Builder.CreateBitCast(ArgValue, DestType, ArgValue->getName().data()); - Intrinsic::ID inst = (BuiltinID == Builtin::BI__builtin_va_end) ? + Intrinsic::ID inst = (BuiltinID == Builtin::BI__builtin_va_end) ? Intrinsic::vaend : Intrinsic::vastart; return RValue::get(Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue)); } @@ -91,36 +91,36 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, Value *DstPtr = EmitVAListRef(E->getArg(0)); Value *SrcPtr = EmitVAListRef(E->getArg(1)); - const llvm::Type *Type = + const llvm::Type *Type = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); DstPtr = Builder.CreateBitCast(DstPtr, Type); SrcPtr = Builder.CreateBitCast(SrcPtr, Type); - return RValue::get(Builder.CreateCall2(CGM.getIntrinsic(Intrinsic::vacopy), + return RValue::get(Builder.CreateCall2(CGM.getIntrinsic(Intrinsic::vacopy), DstPtr, SrcPtr)); } case Builtin::BI__builtin_abs: { - Value *ArgValue = EmitScalarExpr(E->getArg(0)); - + Value *ArgValue = EmitScalarExpr(E->getArg(0)); + Value *NegOp = Builder.CreateNeg(ArgValue, "neg"); - Value *CmpResult = - Builder.CreateICmpSGE(ArgValue, + Value *CmpResult = + Builder.CreateICmpSGE(ArgValue, llvm::Constant::getNullValue(ArgValue->getType()), "abscond"); - Value *Result = + Value *Result = Builder.CreateSelect(CmpResult, ArgValue, NegOp, "abs"); - + return RValue::get(Result); } case Builtin::BI__builtin_ctz: case Builtin::BI__builtin_ctzl: case Builtin::BI__builtin_ctzll: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); - + const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::cttz, &ArgType, 1); - const llvm::Type *ResultType = ConvertType(E->getType()); + const llvm::Type *ResultType = ConvertType(E->getType()); Value *Result = Builder.CreateCall(F, ArgValue, "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); @@ -130,11 +130,11 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_clzl: case Builtin::BI__builtin_clzll: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); - + const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::ctlz, &ArgType, 1); - const llvm::Type *ResultType = ConvertType(E->getType()); + const llvm::Type *ResultType = ConvertType(E->getType()); Value *Result = Builder.CreateCall(F, ArgValue, "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); @@ -145,12 +145,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_ffsll: { // ffs(x) -> x ? cttz(x) + 1 : 0 Value *ArgValue = EmitScalarExpr(E->getArg(0)); - + const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::cttz, &ArgType, 1); - + const llvm::Type *ResultType = ConvertType(E->getType()); - Value *Tmp = Builder.CreateAdd(Builder.CreateCall(F, ArgValue, "tmp"), + Value *Tmp = Builder.CreateAdd(Builder.CreateCall(F, ArgValue, "tmp"), llvm::ConstantInt::get(ArgType, 1), "tmp"); Value *Zero = llvm::Constant::getNullValue(ArgType); Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero"); @@ -164,13 +164,13 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_parityll: { // parity(x) -> ctpop(x) & 1 Value *ArgValue = EmitScalarExpr(E->getArg(0)); - + const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::ctpop, &ArgType, 1); - + const llvm::Type *ResultType = ConvertType(E->getType()); Value *Tmp = Builder.CreateCall(F, ArgValue, "tmp"); - Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1), + Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1), "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); @@ -180,10 +180,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_popcountl: case Builtin::BI__builtin_popcountll: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); - + const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::ctpop, &ArgType, 1); - + const llvm::Type *ResultType = ConvertType(E->getType()); Value *Result = Builder.CreateCall(F, ArgValue, "tmp"); if (Result->getType() != ResultType) @@ -199,7 +199,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::bswap, &ArgType, 1); return RValue::get(Builder.CreateCall(F, ArgValue, "tmp")); - } + } case Builtin::BI__builtin_object_size: { // FIXME: Implement. For now we just always fail and pretend we // don't know the object size. @@ -213,9 +213,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_prefetch: { Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0)); // FIXME: Technically these constants should of type 'int', yes? - RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) : + RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) : llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); - Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : + Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 3); Value *F = CGM.getIntrinsic(Intrinsic::prefetch, 0, 0); return RValue::get(Builder.CreateCall3(F, Address, RW, Locality)); @@ -243,9 +243,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_isunordered: { // Ordered comparisons: we know the arguments to these are matching scalar // floating point values. - Value *LHS = EmitScalarExpr(E->getArg(0)); + Value *LHS = EmitScalarExpr(E->getArg(0)); Value *RHS = EmitScalarExpr(E->getArg(1)); - + switch (BuiltinID) { default: assert(0 && "Unknown ordered comparison"); case Builtin::BI__builtin_isgreater: @@ -263,7 +263,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_islessgreater: LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp"); break; - case Builtin::BI__builtin_isunordered: + case Builtin::BI__builtin_isunordered: LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp"); break; } @@ -352,7 +352,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_longjmp: { Value *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp, 0, 0); Value *Buf = EmitScalarExpr(E->getArg(0)); - const llvm::Type *DestType = + const llvm::Type *DestType = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); Buf = Builder.CreateBitCast(Buf, DestType); return RValue::get(Builder.CreateCall(F, Buf)); @@ -409,7 +409,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__sync_fetch_and_nand_8: case Builtin::BI__sync_fetch_and_nand_16: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_nand, E); - + // Clang extensions: not overloaded yet. case Builtin::BI__sync_fetch_and_min: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_min, E); @@ -425,7 +425,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__sync_add_and_fetch_4: case Builtin::BI__sync_add_and_fetch_8: case Builtin::BI__sync_add_and_fetch_16: - return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_add, E, + return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_add, E, llvm::Instruction::Add); case Builtin::BI__sync_sub_and_fetch_1: case Builtin::BI__sync_sub_and_fetch_2: @@ -462,7 +462,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__sync_nand_and_fetch_16: return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_nand, E, llvm::Instruction::And); - + case Builtin::BI__sync_val_compare_and_swap_1: case Builtin::BI__sync_val_compare_and_swap_2: case Builtin::BI__sync_val_compare_and_swap_4: @@ -473,7 +473,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, ResType[0]= ConvertType(E->getType()); ResType[1] = ConvertType(E->getArg(0)->getType()); Value *AtomF = CGM.getIntrinsic(Intrinsic::atomic_cmp_swap, ResType, 2); - return RValue::get(Builder.CreateCall3(AtomF, + return RValue::get(Builder.CreateCall3(AtomF, EmitScalarExpr(E->getArg(0)), EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2)))); @@ -490,7 +490,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, ResType[1] = llvm::PointerType::getUnqual(ResType[0]); Value *AtomF = CGM.getIntrinsic(Intrinsic::atomic_cmp_swap, ResType, 2); Value *OldVal = EmitScalarExpr(E->getArg(1)); - Value *PrevVal = Builder.CreateCall3(AtomF, + Value *PrevVal = Builder.CreateCall3(AtomF, EmitScalarExpr(E->getArg(0)), OldVal, EmitScalarExpr(E->getArg(2))); @@ -524,7 +524,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, Builder.CreateCall(CGM.getIntrinsic(Intrinsic::memory_barrier), C, C + 5); return RValue::get(0); } - + // Library functions with special handling. case Builtin::BIsqrt: case Builtin::BIsqrtf: @@ -551,31 +551,31 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, return RValue::get(Builder.CreateCall2(F, Base, Exponent, "tmp")); } } - + // If this is an alias for a libm function (e.g. __builtin_sin) turn it into // that function. if (getContext().BuiltinInfo.isLibFunction(BuiltinID) || getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID)) - return EmitCall(CGM.getBuiltinLibFunction(BuiltinID), + return EmitCall(CGM.getBuiltinLibFunction(BuiltinID), E->getCallee()->getType(), E->arg_begin(), E->arg_end()); - + // See if we have a target specific intrinsic. const char *Name = getContext().BuiltinInfo.GetName(BuiltinID); Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic; if (const char *Prefix = - llvm::Triple::getArchTypePrefix(Target.getTriple().getArch())) + llvm::Triple::getArchTypePrefix(Target.getTriple().getArch())) IntrinsicID = Intrinsic::getIntrinsicForGCCBuiltin(Prefix, Name); - + if (IntrinsicID != Intrinsic::not_intrinsic) { SmallVector Args; - + Function *F = CGM.getIntrinsic(IntrinsicID); const llvm::FunctionType *FTy = F->getFunctionType(); - + for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { Value *ArgValue = EmitScalarExpr(E->getArg(i)); - + // If the intrinsic arg type is different from the builtin arg type // we need to do a bit cast. const llvm::Type *PTy = FTy->getParamType(i); @@ -584,36 +584,36 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, "Must be able to losslessly bit cast to param"); ArgValue = Builder.CreateBitCast(ArgValue, PTy); } - + Args.push_back(ArgValue); } - + Value *V = Builder.CreateCall(F, Args.data(), Args.data() + Args.size()); QualType BuiltinRetType = E->getType(); - + const llvm::Type *RetTy = llvm::Type::getVoidTy(VMContext); if (!BuiltinRetType->isVoidType()) RetTy = ConvertType(BuiltinRetType); - + if (RetTy != V->getType()) { assert(V->getType()->canLosslesslyBitCastTo(RetTy) && "Must be able to losslessly bit cast result type"); V = Builder.CreateBitCast(V, RetTy); } - + return RValue::get(V); } - + // See if we have a target specific builtin that needs to be lowered. if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E)) return RValue::get(V); - + ErrorUnsupported(E, "builtin function"); - + // Unknown builtin, for now just dump it out and return undef. if (hasAggregateLLVMType(E->getType())) return RValue::getAggregate(CreateTempAlloca(ConvertType(E->getType()))); return RValue::get(llvm::UndefValue::get(ConvertType(E->getType()))); -} +} Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { @@ -629,9 +629,9 @@ Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID, } } -Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, +Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E) { - + llvm::SmallVector Ops; for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) @@ -639,9 +639,9 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, switch (BuiltinID) { default: return 0; - case X86::BI__builtin_ia32_pslldi128: + case X86::BI__builtin_ia32_pslldi128: case X86::BI__builtin_ia32_psllqi128: - case X86::BI__builtin_ia32_psllwi128: + case X86::BI__builtin_ia32_psllwi128: case X86::BI__builtin_ia32_psradi128: case X86::BI__builtin_ia32_psrawi128: case X86::BI__builtin_ia32_psrldi128: @@ -655,7 +655,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, Ops[1] = Builder.CreateBitCast(Ops[1], Ops[0]->getType(), "bitcast"); const char *name = 0; Intrinsic::ID ID = Intrinsic::not_intrinsic; - + switch (BuiltinID) { default: assert(0 && "Unsupported shift intrinsic!"); case X86::BI__builtin_ia32_pslldi128: @@ -692,11 +692,11 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, break; } llvm::Function *F = CGM.getIntrinsic(ID); - return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); + return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); } - case X86::BI__builtin_ia32_pslldi: + case X86::BI__builtin_ia32_pslldi: case X86::BI__builtin_ia32_psllqi: - case X86::BI__builtin_ia32_psllwi: + case X86::BI__builtin_ia32_psllwi: case X86::BI__builtin_ia32_psradi: case X86::BI__builtin_ia32_psrawi: case X86::BI__builtin_ia32_psrldi: @@ -707,7 +707,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, Ops[1] = Builder.CreateBitCast(Ops[1], Ty, "bitcast"); const char *name = 0; Intrinsic::ID ID = Intrinsic::not_intrinsic; - + switch (BuiltinID) { default: assert(0 && "Unsupported shift intrinsic!"); case X86::BI__builtin_ia32_pslldi: @@ -744,7 +744,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, break; } llvm::Function *F = CGM.getIntrinsic(ID); - return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); + return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); } case X86::BI__builtin_ia32_cmpps: { llvm::Function *F = CGM.getIntrinsic(Intrinsic::x86_sse_cmp_ps); @@ -783,10 +783,10 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, const llvm::Type *EltTy = llvm::Type::getInt64Ty(VMContext); llvm::Type *PtrTy = llvm::PointerType::getUnqual(EltTy); llvm::Type *VecTy = llvm::VectorType::get(EltTy, 2); - + // cast val v2i64 Ops[1] = Builder.CreateBitCast(Ops[1], VecTy, "cast"); - + // extract (0, 1) unsigned Index = BuiltinID == X86::BI__builtin_ia32_storelps ? 0 : 1; llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Index); @@ -799,9 +799,9 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, } } -Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned BuiltinID, +Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { switch (BuiltinID) { default: return 0; } -} +} diff --git a/clang/lib/CodeGen/CGCXX.cpp b/clang/lib/CodeGen/CGCXX.cpp index f610de827650c24b2fb7a138fc6523dd6527eccd..e311912d95fd9f1a06beb21f0edda63b300f6639 100644 --- a/clang/lib/CodeGen/CGCXX.cpp +++ b/clang/lib/CodeGen/CGCXX.cpp @@ -11,7 +11,7 @@ // //===----------------------------------------------------------------------===// -// We might split this into multiple files if it gets too unwieldy +// We might split this into multiple files if it gets too unwieldy #include "CodeGenFunction.h" #include "CodeGenModule.h" @@ -25,54 +25,54 @@ using namespace clang; using namespace CodeGen; -void +void CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor, llvm::Constant *DeclPtr) { // FIXME: This is ABI dependent and we use the Itanium ABI. - - const llvm::Type *Int8PtrTy = + + const llvm::Type *Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); - + std::vector Params; Params.push_back(Int8PtrTy); - + // Get the destructor function type - const llvm::Type *DtorFnTy = + const llvm::Type *DtorFnTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy); - + Params.clear(); Params.push_back(DtorFnTy); Params.push_back(Int8PtrTy); Params.push_back(Int8PtrTy); - + // Get the __cxa_atexit function type // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); - const llvm::FunctionType *AtExitFnTy = + const llvm::FunctionType *AtExitFnTy = llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false); - + llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy, "__cxa_atexit"); - + llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy, "__dso_handle"); - + llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete); - + llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy), llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy), llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) }; Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args)); } -void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, +void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr) { assert(D.hasGlobalStorage() && "VarDecl must have global storage!"); - + const Expr *Init = D.getInit(); QualType T = D.getType(); - + if (T->isReferenceType()) { ErrorUnsupported(Init, "global variable that binds to a reference"); } else if (!hasAggregateLLVMType(T)) { @@ -82,7 +82,7 @@ void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified()); } else { EmitAggExpr(Init, DeclPtr, T.isVolatileQualified()); - + if (const RecordType *RT = T->getAs()) { CXXRecordDecl *RD = cast(RT->getDecl()); if (!RD->hasTrivialDestructor()) @@ -95,16 +95,16 @@ void CodeGenModule::EmitCXXGlobalInitFunc() { if (CXXGlobalInits.empty()) return; - + const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false); - + // Create our global initialization function. // FIXME: Should this be tweakable by targets? - llvm::Function *Fn = + llvm::Function *Fn = llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, "__cxx_global_initialization", &TheModule); - + CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, &CXXGlobalInits[0], CXXGlobalInits.size()); @@ -114,20 +114,20 @@ CodeGenModule::EmitCXXGlobalInitFunc() { void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, const VarDecl **Decls, unsigned NumDecls) { - StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(), + StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(), SourceLocation()); - + for (unsigned i = 0; i != NumDecls; ++i) { const VarDecl *D = Decls[i]; - + llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D); EmitCXXGlobalVarDeclInit(*D, DeclPtr); } FinishFunction(); } -void -CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D, +void +CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV) { // FIXME: This should use __cxa_guard_{acquire,release}? @@ -137,36 +137,36 @@ CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D, llvm::SmallString<256> GuardVName; llvm::raw_svector_ostream GuardVOut(GuardVName); mangleGuardVariable(&D, getContext(), GuardVOut); - + // Create the guard variable. - llvm::GlobalValue *GuardV = + llvm::GlobalValue *GuardV = new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false, GV->getLinkage(), llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)), GuardVName.str()); - + // Load the first byte of the guard variable. const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0); - llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy), + llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy), "tmp"); - + // Compare it against 0. llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)); llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool"); - + llvm::BasicBlock *InitBlock = createBasicBlock("init"); llvm::BasicBlock *EndBlock = createBasicBlock("init.end"); // If the guard variable is 0, jump to the initializer code. Builder.CreateCondBr(ICmp, InitBlock, EndBlock); - + EmitBlock(InitBlock); EmitCXXGlobalVarDeclInit(D, GV); Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1), Builder.CreateBitCast(GuardV, PtrTy)); - + EmitBlock(EndBlock); } @@ -175,25 +175,25 @@ RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD, llvm::Value *This, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd) { - assert(MD->isInstance() && + assert(MD->isInstance() && "Trying to emit a member call expr on a static method!"); // A call to a trivial destructor requires no code generation. if (const CXXDestructorDecl *Destructor = dyn_cast(MD)) if (Destructor->isTrivial()) return RValue::get(0); - + const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); - + CallArgList Args; - + // Push the this ptr. Args.push_back(std::make_pair(RValue::get(This), MD->getThisType(getContext()))); - + // And the rest of the call args EmitCallArgs(Args, FPT, ArgBeg, ArgEnd); - + QualType ResultType = MD->getType()->getAsFunctionType()->getResultType(); return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, MD); @@ -205,11 +205,11 @@ RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) { const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); - const llvm::Type *Ty = - CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), + const llvm::Type *Ty = + CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), FPT->isVariadic()); llvm::Value *This; - + if (ME->isArrow()) This = EmitScalarExpr(ME->getBase()); else { @@ -218,27 +218,27 @@ RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) { } // C++ [class.virtual]p12: - // Explicit qualification with the scope operator (5.1) suppresses the + // Explicit qualification with the scope operator (5.1) suppresses the // virtual call mechanism. llvm::Value *Callee; if (MD->isVirtual() && !ME->hasQualifier()) Callee = BuildVirtualCall(MD, This, Ty); - else if (const CXXDestructorDecl *Destructor + else if (const CXXDestructorDecl *Destructor = dyn_cast(MD)) Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty); else Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); - - return EmitCXXMemberCall(MD, Callee, This, + + return EmitCXXMemberCall(MD, Callee, This, CE->arg_begin(), CE->arg_end()); } -RValue +RValue CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD) { - assert(MD->isInstance() && + assert(MD->isInstance() && "Trying to emit a member call expr on a static method!"); - + if (MD->isCopyAssignment()) { const CXXRecordDecl *ClassDecl = cast(MD->getDeclContext()); if (ClassDecl->hasTrivialCopyAssignment()) { @@ -251,15 +251,15 @@ CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, return RValue::get(This); } } - + const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); - const llvm::Type *Ty = - CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), + const llvm::Type *Ty = + CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), FPT->isVariadic()); llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); - + llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); - + return EmitCXXMemberCall(MD, Callee, This, E->arg_begin() + 1, E->arg_end()); } @@ -268,30 +268,30 @@ RValue CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) { assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) && "EmitCXXFunctionalCastExpr - called with wrong cast"); - + CXXMethodDecl *MD = E->getTypeConversionMethod(); assert(MD && "EmitCXXFunctionalCastExpr - null conversion method"); assert(isa(MD) && "EmitCXXFunctionalCastExpr - not" " method decl"); const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); - - const llvm::Type *Ty = - CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), + + const llvm::Type *Ty = + CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), FPT->isVariadic()); llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress(); RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0); if (RV.isAggregate()) - RV = RValue::get(RV.getAggregateAddr()); + RV = RValue::get(RV.getAggregateAddr()); return RV; } llvm::Value *CodeGenFunction::LoadCXXThis() { - assert(isa(CurFuncDecl) && + assert(isa(CurFuncDecl) && "Must be in a C++ member function decl to load 'this'"); assert(cast(CurFuncDecl)->isInstance() && "Must be in a C++ member function decl to load 'this'"); - + // FIXME: What if we're inside a block? // ans: See how CodeGenFunction::LoadObjCSelf() uses // CodeGenFunction::BlockForwardSelf() for how to do this. @@ -306,7 +306,7 @@ GetNestedPaths(llvm::SmallVectorImpl &NestedBasePaths, e = ClassDecl->bases_end(); i != e; ++i) { if (i->isVirtual()) continue; - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (Base == BaseClassDecl) { NestedBasePaths.push_back(BaseClassDecl); @@ -318,7 +318,7 @@ GetNestedPaths(llvm::SmallVectorImpl &NestedBasePaths, e = ClassDecl->bases_end(); i != e; ++i) { if (i->isVirtual()) continue; - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) { NestedBasePaths.push_back(Base); @@ -329,34 +329,34 @@ GetNestedPaths(llvm::SmallVectorImpl &NestedBasePaths, } llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue, - const CXXRecordDecl *ClassDecl, + const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl) { if (ClassDecl == BaseClassDecl) return BaseValue; - + llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); llvm::SmallVector NestedBasePaths; GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl); - assert(NestedBasePaths.size() > 0 && + assert(NestedBasePaths.size() > 0 && "AddressCXXOfBaseClass - inheritence path failed"); NestedBasePaths.push_back(ClassDecl); uint64_t Offset = 0; - + // Accessing a member of the base class. Must add delata to // the load of 'this'. for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) { const CXXRecordDecl *DerivedClass = NestedBasePaths[i]; const CXXRecordDecl *BaseClass = NestedBasePaths[i-1]; - const ASTRecordLayout &Layout = + const ASTRecordLayout &Layout = getContext().getASTRecordLayout(DerivedClass); Offset += Layout.getBaseClassOffset(BaseClass) / 8; } - llvm::Value *OffsetVal = + llvm::Value *OffsetVal = llvm::ConstantInt::get( CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset); BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr); BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr"); - QualType BTy = + QualType BTy = getContext().getCanonicalType( getContext().getTypeDeclType(const_cast(BaseClassDecl))); const llvm::Type *BasePtr = ConvertType(BTy); @@ -377,52 +377,52 @@ CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, llvm::Value *This) { const ConstantArrayType *CA = dyn_cast(Array); assert(CA && "Do we support VLA for construction ?"); - + // Create a temporary for the loop index and initialize it with 0. llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), "loop.index"); - llvm::Value* zeroConstant = + llvm::Value* zeroConstant = llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); Builder.CreateStore(zeroConstant, IndexPtr, false); - + // Start the loop with a block that tests the condition. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); - + EmitBlock(CondBlock); - + llvm::BasicBlock *ForBody = createBasicBlock("for.body"); - + // Generate: if (loop-index < number-of-elements fall to the loop body, // otherwise, go to the block after the for-loop. uint64_t NumElements = getContext().getConstantArrayElementCount(CA); - llvm::Value * NumElementsPtr = + llvm::Value * NumElementsPtr = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); llvm::Value *Counter = Builder.CreateLoad(IndexPtr); - llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, + llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, "isless"); // If the condition is true, execute the body. Builder.CreateCondBr(IsLess, ForBody, AfterFor); - + EmitBlock(ForBody); - + llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); // Inside the loop body, emit the constructor call on the array element. Counter = Builder.CreateLoad(IndexPtr); llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx"); EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0); - + EmitBlock(ContinueBlock); - + // Emit the increment of the loop counter. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); Counter = Builder.CreateLoad(IndexPtr); NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); Builder.CreateStore(NextVal, IndexPtr, false); - + // Finally, branch back up to the condition for the next iteration. EmitBranch(CondBlock); - + // Emit the fall-through block. EmitBlock(AfterFor, true); } @@ -435,7 +435,7 @@ CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, llvm::Value *This) { const ConstantArrayType *CA = dyn_cast(Array); assert(CA && "Do we support VLA for destruction ?"); - llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), + llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 1); uint64_t ElementCount = getContext().getConstantArrayElementCount(CA); // Create a temporary for the loop index and initialize it with count of @@ -443,54 +443,54 @@ CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), "loop.index"); // Index = ElementCount; - llvm::Value* UpperCount = + llvm::Value* UpperCount = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount); Builder.CreateStore(UpperCount, IndexPtr, false); - + // Start the loop with a block that tests the condition. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); - + EmitBlock(CondBlock); - + llvm::BasicBlock *ForBody = createBasicBlock("for.body"); - + // Generate: if (loop-index != 0 fall to the loop body, // otherwise, go to the block after the for-loop. - llvm::Value* zeroConstant = + llvm::Value* zeroConstant = llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); llvm::Value *Counter = Builder.CreateLoad(IndexPtr); llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant, "isne"); // If the condition is true, execute the body. Builder.CreateCondBr(IsNE, ForBody, AfterFor); - + EmitBlock(ForBody); - + llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); // Inside the loop body, emit the constructor call on the array element. Counter = Builder.CreateLoad(IndexPtr); Counter = Builder.CreateSub(Counter, One); llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx"); EmitCXXDestructorCall(D, Dtor_Complete, Address); - + EmitBlock(ContinueBlock); - + // Emit the decrement of the loop counter. Counter = Builder.CreateLoad(IndexPtr); Counter = Builder.CreateSub(Counter, One, "dec"); Builder.CreateStore(Counter, IndexPtr, false); - + // Finally, branch back up to the condition for the next iteration. EmitBranch(CondBlock); - + // Emit the fall-through block. EmitBlock(AfterFor, true); } void -CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, - CXXCtorType Type, +CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, + CXXCtorType Type, llvm::Value *This, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd) { @@ -506,31 +506,31 @@ CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, return; } } - + llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd); } -void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D, +void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, llvm::Value *This) { llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type); - + EmitCXXMemberCall(D, Callee, This, 0, 0); } -void -CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, +void +CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E) { assert(Dest && "Must have a destination!"); - - const CXXRecordDecl *RD = + + const CXXRecordDecl *RD = cast(E->getType()->getAs()->getDecl()); if (RD->hasTrivialConstructor()) return; - // Code gen optimization to eliminate copy constructor and return + // Code gen optimization to eliminate copy constructor and return // its first argument instead. if (getContext().getLangOptions().ElideConstructors && E->isElidable()) { CXXConstructExpr::const_arg_iterator i = E->arg_begin(); @@ -538,7 +538,7 @@ CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, return; } // Call the constructor. - EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest, + EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest, E->arg_begin(), E->arg_end()); } @@ -547,21 +547,21 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { ErrorUnsupported(E, "new[] expression"); return llvm::UndefValue::get(ConvertType(E->getType())); } - + QualType AllocType = E->getAllocatedType(); FunctionDecl *NewFD = E->getOperatorNew(); const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType(); - + CallArgList NewArgs; // The allocation size is the first argument. QualType SizeTy = getContext().getSizeType(); - llvm::Value *AllocSize = - llvm::ConstantInt::get(ConvertType(SizeTy), + llvm::Value *AllocSize = + llvm::ConstantInt::get(ConvertType(SizeTy), getContext().getTypeSize(AllocType) / 8); NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy)); - + // Emit the rest of the arguments. // FIXME: Ideally, this should just use EmitCallArgs. CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin(); @@ -571,24 +571,24 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { // has already been emitted. for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) { QualType ArgType = NewFTy->getArgType(i); - + assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). - getTypePtr() == - getContext().getCanonicalType(NewArg->getType()).getTypePtr() && + getTypePtr() == + getContext().getCanonicalType(NewArg->getType()).getTypePtr() && "type mismatch in call argument!"); - - NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), + + NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), ArgType)); - + } - - // Either we've emitted all the call args, or we have a call to a + + // Either we've emitted all the call args, or we have a call to a // variadic function. - assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) && + assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) && "Extra arguments in non-variadic function!"); - + // If we still have any arguments, emit them using the type of the argument. - for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end(); + for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end(); NewArg != NewArgEnd; ++NewArg) { QualType ArgType = NewArg->getType(); NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), @@ -596,7 +596,7 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { } // Emit the call to new. - RValue RV = + RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs), CGM.GetAddrOfFunction(GlobalDecl(NewFD)), NewArgs, NewFD); @@ -618,26 +618,26 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { NewNull = createBasicBlock("new.null"); NewNotNull = createBasicBlock("new.notnull"); NewEnd = createBasicBlock("new.end"); - - llvm::Value *IsNull = - Builder.CreateICmpEQ(NewPtr, + + llvm::Value *IsNull = + Builder.CreateICmpEQ(NewPtr, llvm::Constant::getNullValue(NewPtr->getType()), "isnull"); - + Builder.CreateCondBr(IsNull, NewNull, NewNotNull); EmitBlock(NewNotNull); } - + NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType())); - + if (AllocType->isPODType()) { if (E->getNumConstructorArgs() > 0) { - assert(E->getNumConstructorArgs() == 1 && + assert(E->getNumConstructorArgs() == 1 && "Can only have one argument to initializer of POD type."); const Expr *Init = E->getConstructorArg(0); - - if (!hasAggregateLLVMType(AllocType)) + + if (!hasAggregateLLVMType(AllocType)) Builder.CreateStore(EmitScalarExpr(Init), NewPtr); else if (AllocType->isAnyComplexType()) EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified()); @@ -645,11 +645,11 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified()); } } else { - // Call the constructor. + // Call the constructor. CXXConstructorDecl *Ctor = E->getConstructor(); - - EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr, - E->constructor_arg_begin(), + + EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr, + E->constructor_arg_begin(), E->constructor_arg_end()); } @@ -658,15 +658,15 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { EmitBlock(NewNull); Builder.CreateBr(NewEnd); EmitBlock(NewEnd); - + llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType()); PHI->reserveOperandSpace(2); PHI->addIncoming(NewPtr, NewNotNull); PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull); - + NewPtr = PHI; } - + return NewPtr; } @@ -676,22 +676,22 @@ void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { return; }; - QualType DeleteTy = + QualType DeleteTy = E->getArgument()->getType()->getAs()->getPointeeType(); - + llvm::Value *Ptr = EmitScalarExpr(E->getArgument()); - + // Null check the pointer. llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); - llvm::Value *IsNull = + llvm::Value *IsNull = Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()), "isnull"); - + Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); EmitBlock(DeleteNotNull); - + // Call the destructor if necessary. if (const RecordType *RT = DeleteTy->getAs()) { if (CXXRecordDecl *RD = dyn_cast(RT->getDecl())) { @@ -701,29 +701,29 @@ void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { ErrorUnsupported(E, "delete expression with virtual destructor"); return; } - + EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr); } } } - + // Call delete. FunctionDecl *DeleteFD = E->getOperatorDelete(); - const FunctionProtoType *DeleteFTy = + const FunctionProtoType *DeleteFTy = DeleteFD->getType()->getAsFunctionProtoType(); - + CallArgList DeleteArgs; QualType ArgTy = DeleteFTy->getArgType(0); llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy)); - + // Emit the call to delete. - EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(), + EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(), DeleteArgs), CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)), DeleteArgs, DeleteFD); - + EmitBlock(DeleteEnd); } @@ -732,34 +732,34 @@ void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { EmitGlobal(GlobalDecl(D, Ctor_Base)); } -void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, +void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type) { - + llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type); - + CodeGenFunction(*this).GenerateCode(D, Fn); - + SetFunctionDefinitionAttributes(D, Fn); SetLLVMFunctionAttributesForDefinition(D, Fn); } llvm::Function * -CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, +CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type) { const llvm::FunctionType *FTy = getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); - + const char *Name = getMangledCXXCtorName(D, Type); return cast( GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); } -const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, +const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, CXXCtorType Type) { llvm::SmallString<256> Name; llvm::raw_svector_ostream Out(Name); mangleCXXCtor(D, Type, Context, Out); - + Name += '\0'; return UniqueMangledName(Name.begin(), Name.end()); } @@ -769,33 +769,33 @@ void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) { EmitCXXDestructor(D, Dtor_Base); } -void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, +void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type) { llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type); - + CodeGenFunction(*this).GenerateCode(D, Fn); - + SetFunctionDefinitionAttributes(D, Fn); SetLLVMFunctionAttributesForDefinition(D, Fn); } llvm::Function * -CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, +CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type) { const llvm::FunctionType *FTy = getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); - + const char *Name = getMangledCXXDtorName(D, Type); return cast( GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); } -const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D, +const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D, CXXDtorType Type) { llvm::SmallString<256> Name; llvm::raw_svector_ostream Out(Name); mangleCXXDtor(D, Type, Context, Out); - + Name += '\0'; return UniqueMangledName(Name.begin(), Name.end()); } @@ -891,7 +891,7 @@ public: const CXXRecordDecl *RD, uint64_t Offset) { for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (i->isVirtual() && !SeenVBase.count(Base)) { SeenVBase.insert(Base); @@ -998,7 +998,7 @@ public: // If we can find a previously allocated slot for this, reuse it. if (OverrideMethod(MD, m, MorallyVirtual, Offset)) return; - + // else allocate a new slot. Index[MD] = submethods.size(); submethods.push_back(m); @@ -1029,7 +1029,7 @@ public: e = RD->bases_end(); i != e; ++i) { if (i->isVirtual()) continue; - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (Base != PrimaryBase || PrimaryBaseWasVirtual) { uint64_t o = Offset + Layout.getBaseClassOffset(Base); @@ -1090,7 +1090,7 @@ public: return; const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); - const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); + const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual(); // vtables are composed from the chain of primaries. @@ -1113,7 +1113,7 @@ public: return 0; const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); - const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); + const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual(); std::vector offsets; @@ -1154,7 +1154,7 @@ public: Path->push_back(std::make_pair(RD, Offset)); for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), e = RD->bases_end(); i != e; ++i) { - const CXXRecordDecl *Base = + const CXXRecordDecl *Base = cast(i->getType()->getAs()->getDecl()); if (i->isVirtual() && !IndirectPrimary.count(Base)) { // Mark it so we don't output it twice. @@ -1306,7 +1306,7 @@ llvm::Value * CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This, const llvm::Type *Ty) { // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch. - + // FIXME: move to Context if (vtableinfo == 0) vtableinfo = new VtableInfo(CGM); @@ -1328,39 +1328,39 @@ CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This, /// array of objects from SrcValue to DestValue. Copying can be either a bitwise /// copy or via a copy constructor call. // FIXME. Consolidate this with EmitCXXAggrConstructorCall. -void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest, +void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest, llvm::Value *Src, const ArrayType *Array, - const CXXRecordDecl *BaseClassDecl, + const CXXRecordDecl *BaseClassDecl, QualType Ty) { const ConstantArrayType *CA = dyn_cast(Array); assert(CA && "VLA cannot be copied over"); bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor(); - + // Create a temporary for the loop index and initialize it with 0. llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), "loop.index"); - llvm::Value* zeroConstant = + llvm::Value* zeroConstant = llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); Builder.CreateStore(zeroConstant, IndexPtr, false); // Start the loop with a block that tests the condition. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); - + EmitBlock(CondBlock); - + llvm::BasicBlock *ForBody = createBasicBlock("for.body"); // Generate: if (loop-index < number-of-elements fall to the loop body, // otherwise, go to the block after the for-loop. uint64_t NumElements = getContext().getConstantArrayElementCount(CA); - llvm::Value * NumElementsPtr = + llvm::Value * NumElementsPtr = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); llvm::Value *Counter = Builder.CreateLoad(IndexPtr); - llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, + llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, "isless"); // If the condition is true, execute the body. Builder.CreateCondBr(IsLess, ForBody, AfterFor); - + EmitBlock(ForBody); llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); // Inside the loop body, emit the constructor call on the array element. @@ -1369,75 +1369,75 @@ void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest, Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress"); if (BitwiseCopy) EmitAggregateCopy(Dest, Src, Ty); - else if (CXXConstructorDecl *BaseCopyCtor = + else if (CXXConstructorDecl *BaseCopyCtor = BaseClassDecl->getCopyConstructor(getContext(), 0)) { - llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, + llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); CallArgList CallArgs; // Push the this (Dest) ptr. CallArgs.push_back(std::make_pair(RValue::get(Dest), BaseCopyCtor->getThisType(getContext()))); - + // Push the Src ptr. CallArgs.push_back(std::make_pair(RValue::get(Src), BaseCopyCtor->getParamDecl(0)->getType())); - QualType ResultType = + QualType ResultType = BaseCopyCtor->getType()->getAsFunctionType()->getResultType(); EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), Callee, CallArgs, BaseCopyCtor); } EmitBlock(ContinueBlock); - + // Emit the increment of the loop counter. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); Counter = Builder.CreateLoad(IndexPtr); NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); Builder.CreateStore(NextVal, IndexPtr, false); - + // Finally, branch back up to the condition for the next iteration. EmitBranch(CondBlock); - + // Emit the fall-through block. EmitBlock(AfterFor, true); } /// EmitClassAggrCopyAssignment - This routine generates code to assign a class -/// array of objects from SrcValue to DestValue. Assignment can be either a +/// array of objects from SrcValue to DestValue. Assignment can be either a /// bitwise assignment or via a copy assignment operator function call. /// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy -void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, +void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, llvm::Value *Src, const ArrayType *Array, - const CXXRecordDecl *BaseClassDecl, + const CXXRecordDecl *BaseClassDecl, QualType Ty) { const ConstantArrayType *CA = dyn_cast(Array); assert(CA && "VLA cannot be asssigned"); bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment(); - + // Create a temporary for the loop index and initialize it with 0. llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), "loop.index"); - llvm::Value* zeroConstant = + llvm::Value* zeroConstant = llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); Builder.CreateStore(zeroConstant, IndexPtr, false); // Start the loop with a block that tests the condition. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); - + EmitBlock(CondBlock); - + llvm::BasicBlock *ForBody = createBasicBlock("for.body"); // Generate: if (loop-index < number-of-elements fall to the loop body, // otherwise, go to the block after the for-loop. uint64_t NumElements = getContext().getConstantArrayElementCount(CA); - llvm::Value * NumElementsPtr = + llvm::Value * NumElementsPtr = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); llvm::Value *Counter = Builder.CreateLoad(IndexPtr); - llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, + llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, "isless"); // If the condition is true, execute the body. Builder.CreateCondBr(IsLess, ForBody, AfterFor); - + EmitBlock(ForBody); llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); // Inside the loop body, emit the assignment operator call on array element. @@ -1457,12 +1457,12 @@ void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), FPT->isVariadic()); llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy); - + CallArgList CallArgs; // Push the this (Dest) ptr. CallArgs.push_back(std::make_pair(RValue::get(Dest), MD->getThisType(getContext()))); - + // Push the Src ptr. CallArgs.push_back(std::make_pair(RValue::get(Src), MD->getParamDecl(0)->getType())); @@ -1471,16 +1471,16 @@ void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, Callee, CallArgs, MD); } EmitBlock(ContinueBlock); - + // Emit the increment of the loop counter. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); Counter = Builder.CreateLoad(IndexPtr); NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); Builder.CreateStore(NextVal, IndexPtr, false); - + // Finally, branch back up to the condition for the next iteration. EmitBranch(CondBlock); - + // Emit the fall-through block. EmitBlock(AfterFor, true); } @@ -1490,7 +1490,7 @@ void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, /// or via a copy constructor call. void CodeGenFunction::EmitClassMemberwiseCopy( llvm::Value *Dest, llvm::Value *Src, - const CXXRecordDecl *ClassDecl, + const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl, QualType Ty) { if (ClassDecl) { Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl); @@ -1500,20 +1500,20 @@ void CodeGenFunction::EmitClassMemberwiseCopy( EmitAggregateCopy(Dest, Src, Ty); return; } - - if (CXXConstructorDecl *BaseCopyCtor = + + if (CXXConstructorDecl *BaseCopyCtor = BaseClassDecl->getCopyConstructor(getContext(), 0)) { - llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, + llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); CallArgList CallArgs; // Push the this (Dest) ptr. CallArgs.push_back(std::make_pair(RValue::get(Dest), BaseCopyCtor->getThisType(getContext()))); - + // Push the Src ptr. CallArgs.push_back(std::make_pair(RValue::get(Src), BaseCopyCtor->getParamDecl(0)->getType())); - QualType ResultType = + QualType ResultType = BaseCopyCtor->getType()->getAsFunctionType()->getResultType(); EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), Callee, CallArgs, BaseCopyCtor); @@ -1521,13 +1521,13 @@ void CodeGenFunction::EmitClassMemberwiseCopy( } /// EmitClassCopyAssignment - This routine generates code to copy assign a class -/// object from SrcValue to DestValue. Assignment can be either a bitwise +/// object from SrcValue to DestValue. Assignment can be either a bitwise /// assignment of via an assignment operator call. // FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot. void CodeGenFunction::EmitClassCopyAssignment( llvm::Value *Dest, llvm::Value *Src, - const CXXRecordDecl *ClassDecl, - const CXXRecordDecl *BaseClassDecl, + const CXXRecordDecl *ClassDecl, + const CXXRecordDecl *BaseClassDecl, QualType Ty) { if (ClassDecl) { Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl); @@ -1537,35 +1537,35 @@ void CodeGenFunction::EmitClassCopyAssignment( EmitAggregateCopy(Dest, Src, Ty); return; } - + const CXXMethodDecl *MD = 0; - bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(), + bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(), MD); assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign"); (void)ConstCopyAssignOp; const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); - const llvm::Type *LTy = - CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), + const llvm::Type *LTy = + CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), FPT->isVariadic()); llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy); - + CallArgList CallArgs; // Push the this (Dest) ptr. CallArgs.push_back(std::make_pair(RValue::get(Dest), MD->getThisType(getContext()))); - + // Push the Src ptr. CallArgs.push_back(std::make_pair(RValue::get(Src), MD->getParamDecl(0)->getType())); - QualType ResultType = + QualType ResultType = MD->getType()->getAsFunctionType()->getResultType(); EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), Callee, CallArgs, MD); } /// SynthesizeDefaultConstructor - synthesize a default constructor -void +void CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD, const FunctionDecl *FD, llvm::Function *Fn, @@ -1577,18 +1577,18 @@ CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD, /// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy /// constructor, in accordance with section 12.8 (p7 and p8) of C++03 -/// The implicitly-defined copy constructor for class X performs a memberwise -/// copy of its subobjects. The order of copying is the same as the order +/// The implicitly-defined copy constructor for class X performs a memberwise +/// copy of its subobjects. The order of copying is the same as the order /// of initialization of bases and members in a user-defined constructor /// Each subobject is copied in the manner appropriate to its type: -/// if the subobject is of class type, the copy constructor for the class is +/// if the subobject is of class type, the copy constructor for the class is /// used; -/// if the subobject is an array, each element is copied, in the manner +/// if the subobject is an array, each element is copied, in the manner /// appropriate to the element type; -/// if the subobject is of scalar type, the built-in assignment operator is +/// if the subobject is of scalar type, the built-in assignment operator is /// used. -/// Virtual base class subobjects shall be copied only once by the -/// implicitly-defined copy constructor +/// Virtual base class subobjects shall be copied only once by the +/// implicitly-defined copy constructor void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, const FunctionDecl *FD, @@ -1598,7 +1598,7 @@ void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, assert(!ClassDecl->hasUserDeclaredCopyConstructor() && "SynthesizeCXXCopyConstructor - copy constructor has definition already"); StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation()); - + FunctionArgList::const_iterator i = Args.begin(); const VarDecl *ThisArg = i->first; llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg); @@ -1606,28 +1606,28 @@ void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, const VarDecl *SrcArg = (i+1)->first; llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg); llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj); - + for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { // FIXME. copy constrution of virtual base NYI if (Base->isVirtual()) continue; - + CXXRecordDecl *BaseClassDecl = cast(Base->getType()->getAs()->getDecl()); EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl, Base->getType()); } - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { QualType FieldType = getContext().getCanonicalType((*Field)->getType()); - const ConstantArrayType *Array = + const ConstantArrayType *Array = getContext().getAsConstantArrayType(FieldType); if (Array) FieldType = getContext().getBaseElementType(FieldType); - + if (const RecordType *FieldClassType = FieldType->getAs()) { CXXRecordDecl *FieldClassDecl = cast(FieldClassType->getDecl()); @@ -1636,15 +1636,15 @@ void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, if (Array) { const llvm::Type *BasePtr = ConvertType(FieldType); BasePtr = llvm::PointerType::getUnqual(BasePtr); - llvm::Value *DestBaseAddrPtr = + llvm::Value *DestBaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr); - llvm::Value *SrcBaseAddrPtr = + llvm::Value *SrcBaseAddrPtr = Builder.CreateBitCast(RHS.getAddress(), BasePtr); EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array, FieldClassDecl, FieldType); } - else - EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(), + else + EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(), 0 /*ClassDecl*/, FieldClassDecl, FieldType); continue; } @@ -1655,27 +1655,27 @@ void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, EmitStoreThroughLValue(RVRHS, LHS, FieldType); } FinishFunction(); -} +} /// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator. -/// Before the implicitly-declared copy assignment operator for a class is -/// implicitly defined, all implicitly- declared copy assignment operators for -/// its direct base classes and its nonstatic data members shall have been +/// Before the implicitly-declared copy assignment operator for a class is +/// implicitly defined, all implicitly- declared copy assignment operators for +/// its direct base classes and its nonstatic data members shall have been /// implicitly defined. [12.8-p12] -/// The implicitly-defined copy assignment operator for class X performs -/// memberwise assignment of its subob- jects. The direct base classes of X are -/// assigned first, in the order of their declaration in -/// the base-specifier-list, and then the immediate nonstatic data members of X -/// are assigned, in the order in which they were declared in the class +/// The implicitly-defined copy assignment operator for class X performs +/// memberwise assignment of its subob- jects. The direct base classes of X are +/// assigned first, in the order of their declaration in +/// the base-specifier-list, and then the immediate nonstatic data members of X +/// are assigned, in the order in which they were declared in the class /// definition.Each subobject is assigned in the manner appropriate to its type: -/// if the subobject is of class type, the copy assignment operator for the -/// class is used (as if by explicit qualification; that is, ignoring any +/// if the subobject is of class type, the copy assignment operator for the +/// class is used (as if by explicit qualification; that is, ignoring any /// possible virtual overriding functions in more derived classes); /// -/// if the subobject is an array, each element is assigned, in the manner +/// if the subobject is an array, each element is assigned, in the manner /// appropriate to the element type; /// -/// if the subobject is of scalar type, the built-in assignment operator is +/// if the subobject is of scalar type, the built-in assignment operator is /// used. void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, const FunctionDecl *FD, @@ -1686,7 +1686,7 @@ void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, assert(!ClassDecl->hasUserDeclaredCopyAssignment() && "SynthesizeCXXCopyAssignment - copy assignment has user declaration"); StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation()); - + FunctionArgList::const_iterator i = Args.begin(); const VarDecl *ThisArg = i->first; llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg); @@ -1694,28 +1694,28 @@ void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, const VarDecl *SrcArg = (i+1)->first; llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg); llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj); - + for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { // FIXME. copy assignment of virtual base NYI if (Base->isVirtual()) continue; - + CXXRecordDecl *BaseClassDecl = cast(Base->getType()->getAs()->getDecl()); EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl, Base->getType()); } - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { QualType FieldType = getContext().getCanonicalType((*Field)->getType()); - const ConstantArrayType *Array = + const ConstantArrayType *Array = getContext().getAsConstantArrayType(FieldType); if (Array) FieldType = getContext().getBaseElementType(FieldType); - + if (const RecordType *FieldClassType = FieldType->getAs()) { CXXRecordDecl *FieldClassDecl = cast(FieldClassType->getDecl()); @@ -1732,7 +1732,7 @@ void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, FieldClassDecl, FieldType); } else - EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(), + EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(), 0 /*ClassDecl*/, FieldClassDecl, FieldType); continue; } @@ -1742,12 +1742,12 @@ void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, RValue RVRHS = EmitLoadOfLValue(RHS, FieldType); EmitStoreThroughLValue(RVRHS, LHS, FieldType); } - + // return *this; Builder.CreateStore(LoadOfThis, ReturnValue); - + FinishFunction(); -} +} /// EmitCtorPrologue - This routine generates necessary code to initialize /// base classes and non-static data members belonging to this constructor. @@ -1756,7 +1756,7 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { const CXXRecordDecl *ClassDecl = cast(CD->getDeclContext()); // FIXME: Add vbase initialization llvm::Value *LoadOfThis = 0; - + for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), E = CD->init_end(); B != E; ++B) { @@ -1764,23 +1764,23 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { if (Member->isBaseInitializer()) { LoadOfThis = LoadCXXThis(); Type *BaseType = Member->getBaseClass(); - CXXRecordDecl *BaseClassDecl = + CXXRecordDecl *BaseClassDecl = cast(BaseType->getAs()->getDecl()); - llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl, + llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl, BaseClassDecl); EmitCXXConstructorCall(Member->getConstructor(), Ctor_Complete, V, - Member->const_arg_begin(), + Member->const_arg_begin(), Member->const_arg_end()); } else { // non-static data member initilaizers. FieldDecl *Field = Member->getMember(); QualType FieldType = getContext().getCanonicalType((Field)->getType()); - const ConstantArrayType *Array = + const ConstantArrayType *Array = getContext().getAsConstantArrayType(FieldType); if (Array) FieldType = getContext().getBaseElementType(FieldType); - + LoadOfThis = LoadCXXThis(); LValue LHS; if (FieldType->isReferenceType()) { @@ -1794,32 +1794,32 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { } if (FieldType->getAs()) { if (!Field->isAnonymousStructOrUnion()) { - assert(Member->getConstructor() && + assert(Member->getConstructor() && "EmitCtorPrologue - no constructor to initialize member"); if (Array) { const llvm::Type *BasePtr = ConvertType(FieldType); BasePtr = llvm::PointerType::getUnqual(BasePtr); - llvm::Value *BaseAddrPtr = + llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr); - EmitCXXAggrConstructorCall(Member->getConstructor(), + EmitCXXAggrConstructorCall(Member->getConstructor(), Array, BaseAddrPtr); } else EmitCXXConstructorCall(Member->getConstructor(), Ctor_Complete, LHS.getAddress(), - Member->const_arg_begin(), + Member->const_arg_begin(), Member->const_arg_end()); continue; } else { // Initializing an anonymous union data member. FieldDecl *anonMember = Member->getAnonUnionMember(); - LHS = EmitLValueForField(LHS.getAddress(), anonMember, + LHS = EmitLValueForField(LHS.getAddress(), anonMember, /*IsUnion=*/true, 0); FieldType = anonMember->getType(); } } - + assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only"); Expr *RhsExpr = *Member->arg_begin(); RValue RHS; @@ -1834,20 +1834,20 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) { // Nontrivial default constructor with no initializer list. It may still - // have bases classes and/or contain non-static data members which require + // have bases classes and/or contain non-static data members which require // construction. - for (CXXRecordDecl::base_class_const_iterator Base = + for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { // FIXME. copy assignment of virtual base NYI if (Base->isVirtual()) continue; - + CXXRecordDecl *BaseClassDecl = cast(Base->getType()->getAs()->getDecl()); if (BaseClassDecl->hasTrivialConstructor()) continue; - if (CXXConstructorDecl *BaseCX = + if (CXXConstructorDecl *BaseCX = BaseClassDecl->getDefaultConstructor(getContext())) { LoadOfThis = LoadCXXThis(); llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl, @@ -1855,40 +1855,40 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0); } } - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { QualType FieldType = getContext().getCanonicalType((*Field)->getType()); - const ConstantArrayType *Array = + const ConstantArrayType *Array = getContext().getAsConstantArrayType(FieldType); if (Array) FieldType = getContext().getBaseElementType(FieldType); if (!FieldType->getAs() || Field->isAnonymousStructOrUnion()) continue; const RecordType *ClassRec = FieldType->getAs(); - CXXRecordDecl *MemberClassDecl = + CXXRecordDecl *MemberClassDecl = dyn_cast(ClassRec->getDecl()); if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor()) continue; - if (CXXConstructorDecl *MamberCX = + if (CXXConstructorDecl *MamberCX = MemberClassDecl->getDefaultConstructor(getContext())) { LoadOfThis = LoadCXXThis(); LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); if (Array) { const llvm::Type *BasePtr = ConvertType(FieldType); BasePtr = llvm::PointerType::getUnqual(BasePtr); - llvm::Value *BaseAddrPtr = + llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr); EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr); } else - EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(), + EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(), 0, 0); } } } - + // Initialize the vtable pointer if (ClassDecl->isDynamicClass()) { if (!LoadOfThis) @@ -1904,7 +1904,7 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { } /// EmitDtorEpilogue - Emit all code that comes at the end of class's -/// destructor. This is to call destructors on members and base classes +/// destructor. This is to call destructors on members and base classes /// in reverse order of their construction. /// FIXME: This needs to take a CXXDtorType. void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { @@ -1912,14 +1912,14 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { assert(!ClassDecl->getNumVBases() && "FIXME: Destruction of virtual bases not supported"); (void)ClassDecl; // prevent warning. - + for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(), *E = DD->destr_end(); B != E; ++B) { uintptr_t BaseOrMember = (*B); if (DD->isMemberToDestroy(BaseOrMember)) { FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember); QualType FieldType = getContext().getCanonicalType((FD)->getType()); - const ConstantArrayType *Array = + const ConstantArrayType *Array = getContext().getAsConstantArrayType(FieldType); if (Array) FieldType = getContext().getBaseElementType(FieldType); @@ -1932,9 +1932,9 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { if (Array) { const llvm::Type *BasePtr = ConvertType(FieldType); BasePtr = llvm::PointerType::getUnqual(BasePtr); - llvm::Value *BaseAddrPtr = + llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr); - EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), + EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), Array, BaseAddrPtr); } else @@ -1946,7 +1946,7 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { CXXRecordDecl *BaseClassDecl = cast(RT->getDecl()); if (BaseClassDecl->hasTrivialDestructor()) continue; - llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(), + llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(), ClassDecl,BaseClassDecl); EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()), Dtor_Complete, V); @@ -1955,10 +1955,10 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial()) return; // Case of destructor synthesis with fields and base classes - // which have non-trivial destructors. They must be destructed in + // which have non-trivial destructors. They must be destructed in // reverse order of their construction. llvm::SmallVector DestructedFields; - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { @@ -1976,7 +1976,7 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { for (int i = DestructedFields.size() -1; i >= 0; --i) { FieldDecl *Field = DestructedFields[i]; QualType FieldType = Field->getType(); - const ConstantArrayType *Array = + const ConstantArrayType *Array = getContext().getAsConstantArrayType(FieldType); if (Array) FieldType = getContext().getBaseElementType(FieldType); @@ -1987,23 +1987,23 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { if (Array) { const llvm::Type *BasePtr = ConvertType(FieldType); BasePtr = llvm::PointerType::getUnqual(BasePtr); - llvm::Value *BaseAddrPtr = + llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr); - EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), + EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), Array, BaseAddrPtr); } else EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()), Dtor_Complete, LHS.getAddress()); } - + llvm::SmallVector DestructedBases; for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { // FIXME. copy assignment of virtual base NYI if (Base->isVirtual()) continue; - + CXXRecordDecl *BaseClassDecl = cast(Base->getType()->getAs()->getDecl()); if (BaseClassDecl->hasTrivialDestructor()) @@ -2014,7 +2014,7 @@ void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { return; for (int i = DestructedBases.size() -1; i >= 0; --i) { CXXRecordDecl *BaseClassDecl = DestructedBases[i]; - llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(), + llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(), ClassDecl,BaseClassDecl); EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()), Dtor_Complete, V); @@ -2025,13 +2025,13 @@ void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD, const FunctionDecl *FD, llvm::Function *Fn, const FunctionArgList &Args) { - + const CXXRecordDecl *ClassDecl = cast(CD->getDeclContext()); assert(!ClassDecl->hasUserDeclaredDestructor() && "SynthesizeDefaultDestructor - destructor has user declaration"); (void) ClassDecl; - + StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation()); EmitDtorEpilogue(CD); FinishFunction(); -} +} diff --git a/clang/lib/CodeGen/CGCXX.h b/clang/lib/CodeGen/CGCXX.h index 6051d9133c026e69d859f5fa22ed364ac205f8d2..1e6adb05a0d92d497c6f7515471753a8fd6cf6de 100644 --- a/clang/lib/CodeGen/CGCXX.h +++ b/clang/lib/CodeGen/CGCXX.h @@ -30,7 +30,7 @@ enum CXXDtorType { Dtor_Complete, // Complete object dtor Dtor_Base // Base object dtor }; - + } // end namespace clang #endif // CLANG_CODEGEN_CGCXX_H diff --git a/clang/lib/CodeGen/CGCXXTemp.cpp b/clang/lib/CodeGen/CGCXXTemp.cpp index 30de1115c0a9904ccf9512b6dc5deb2125fc507e..fbb2b9f719db22fb32c3510d8427629300ac8987 100644 --- a/clang/lib/CodeGen/CGCXXTemp.cpp +++ b/clang/lib/CodeGen/CGCXXTemp.cpp @@ -15,20 +15,20 @@ using namespace clang; using namespace CodeGen; -void CodeGenFunction::PushCXXTemporary(const CXXTemporary *Temporary, +void CodeGenFunction::PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr) { llvm::BasicBlock *DtorBlock = createBasicBlock("temp.dtor"); - + llvm::Value *CondPtr = 0; - - // Check if temporaries need to be conditional. If so, we'll create a - // condition boolean, initialize it to 0 and + + // Check if temporaries need to be conditional. If so, we'll create a + // condition boolean, initialize it to 0 and if (!ConditionalTempDestructionStack.empty()) { CondPtr = CreateTempAlloca(llvm::Type::getInt1Ty(VMContext), "cond"); - + // Initialize it to false. This initialization takes place right after // the alloca insert point. - llvm::StoreInst *SI = + llvm::StoreInst *SI = new llvm::StoreInst(llvm::ConstantInt::getFalse(VMContext), CondPtr); llvm::BasicBlock *Block = AllocaInsertPt->getParent(); Block->getInstList().insertAfter((llvm::Instruction *)AllocaInsertPt, SI); @@ -36,8 +36,8 @@ void CodeGenFunction::PushCXXTemporary(const CXXTemporary *Temporary, // Now set it to true. Builder.CreateStore(llvm::ConstantInt::getTrue(VMContext), CondPtr); } - - LiveTemporaries.push_back(CXXLiveTemporaryInfo(Temporary, Ptr, DtorBlock, + + LiveTemporaries.push_back(CXXLiveTemporaryInfo(Temporary, Ptr, DtorBlock, CondPtr)); PushCleanupBlock(DtorBlock); @@ -45,15 +45,15 @@ void CodeGenFunction::PushCXXTemporary(const CXXTemporary *Temporary, void CodeGenFunction::PopCXXTemporary() { const CXXLiveTemporaryInfo& Info = LiveTemporaries.back(); - + CleanupBlockInfo CleanupInfo = PopCleanupBlock(); - assert(CleanupInfo.CleanupBlock == Info.DtorBlock && + assert(CleanupInfo.CleanupBlock == Info.DtorBlock && "Cleanup block mismatch!"); - assert(!CleanupInfo.SwitchBlock && + assert(!CleanupInfo.SwitchBlock && "Should not have a switch block for temporary cleanup!"); - assert(!CleanupInfo.EndBlock && + assert(!CleanupInfo.EndBlock && "Should not have an end block for temporary cleanup!"); - + EmitBlock(Info.DtorBlock); llvm::BasicBlock *CondEnd = 0; @@ -63,12 +63,12 @@ void CodeGenFunction::PopCXXTemporary() { if (Info.CondPtr) { llvm::BasicBlock *CondBlock = createBasicBlock("cond.dtor.call"); CondEnd = createBasicBlock("cond.dtor.end"); - + llvm::Value *Cond = Builder.CreateLoad(Info.CondPtr); Builder.CreateCondBr(Cond, CondBlock, CondEnd); EmitBlock(CondBlock); } - + EmitCXXDestructorCall(Info.Temporary->getDestructor(), Dtor_Complete, Info.ThisPtr); @@ -77,7 +77,7 @@ void CodeGenFunction::PopCXXTemporary() { Builder.CreateStore(llvm::ConstantInt::getFalse(VMContext), Info.CondPtr); EmitBlock(CondEnd); } - + LiveTemporaries.pop_back(); } @@ -89,7 +89,7 @@ CodeGenFunction::EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, // If we shouldn't destroy the temporaries, just emit the // child expression. if (!E->shouldDestroyTemporaries()) - return EmitAnyExpr(E->getSubExpr(), AggLoc, IsAggLocVolatile, + return EmitAnyExpr(E->getSubExpr(), AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false, IsInitializer); // Keep track of the current cleanup stack depth. @@ -97,21 +97,21 @@ CodeGenFunction::EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, (void) CleanupStackDepth; unsigned OldNumLiveTemporaries = LiveTemporaries.size(); - - RValue RV = EmitAnyExpr(E->getSubExpr(), AggLoc, IsAggLocVolatile, + + RValue RV = EmitAnyExpr(E->getSubExpr(), AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false, IsInitializer); - + // Pop temporaries. while (LiveTemporaries.size() > OldNumLiveTemporaries) PopCXXTemporary(); - + assert(CleanupEntries.size() == CleanupStackDepth && "Cleanup size mismatch!"); - + return RV; } -void +void CodeGenFunction::PushConditionalTempDestruction() { // Store the current number of live temporaries. ConditionalTempDestructionStack.push_back(LiveTemporaries.size()); @@ -120,13 +120,13 @@ CodeGenFunction::PushConditionalTempDestruction() { void CodeGenFunction::PopConditionalTempDestruction() { size_t NumLiveTemporaries = ConditionalTempDestructionStack.back(); ConditionalTempDestructionStack.pop_back(); - + // Pop temporaries. while (LiveTemporaries.size() > NumLiveTemporaries) { - assert(LiveTemporaries.back().CondPtr && + assert(LiveTemporaries.back().CondPtr && "Conditional temporary must have a cond ptr!"); PopCXXTemporary(); - } + } } - + diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp index 0a187fca7672cdd994c22b7abe6a499d1b7f6b89..2da16a15ac181ba03ff9fb66b503631c6d618350 100644 --- a/clang/lib/CodeGen/CGCall.cpp +++ b/clang/lib/CodeGen/CGCall.cpp @@ -33,13 +33,13 @@ using namespace CodeGen; // FIXME: Use iterator and sidestep silly type array creation. -const +const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) { - return getFunctionInfo(FTNP->getResultType(), + return getFunctionInfo(FTNP->getResultType(), llvm::SmallVector()); } -const +const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) { llvm::SmallVector ArgTys; // FIXME: Kill copy. @@ -53,7 +53,7 @@ const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) { // Add the 'this' pointer unless this is a static method. if (MD->isInstance()) ArgTys.push_back(MD->getThisType(Context)); - + const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType(); for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) ArgTys.push_back(FTP->getArgType(i)); @@ -64,7 +64,7 @@ const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) { if (const CXXMethodDecl *MD = dyn_cast(FD)) if (MD->isInstance()) return getFunctionInfo(MD); - + const FunctionType *FTy = FD->getType()->getAsFunctionType(); if (const FunctionProtoType *FTP = dyn_cast(FTy)) return getFunctionInfo(FTP); @@ -82,21 +82,21 @@ const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) { return getFunctionInfo(MD->getResultType(), ArgTys); } -const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, +const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, const CallArgList &Args) { // FIXME: Kill copy. llvm::SmallVector ArgTys; - for (CallArgList::const_iterator i = Args.begin(), e = Args.end(); + for (CallArgList::const_iterator i = Args.begin(), e = Args.end(); i != e; ++i) ArgTys.push_back(i->second); return getFunctionInfo(ResTy, ArgTys); } -const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, +const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, const FunctionArgList &Args) { // FIXME: Kill copy. llvm::SmallVector ArgTys; - for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); + for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e; ++i) ArgTys.push_back(i->second); return getFunctionInfo(ResTy, ArgTys); @@ -123,7 +123,7 @@ const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, return *FI; } -CGFunctionInfo::CGFunctionInfo(QualType ResTy, +CGFunctionInfo::CGFunctionInfo(QualType ResTy, const llvm::SmallVector &ArgTys) { NumArgs = ArgTys.size(); Args = new ArgInfo[1 + NumArgs]; @@ -134,20 +134,20 @@ CGFunctionInfo::CGFunctionInfo(QualType ResTy, /***/ -void CodeGenTypes::GetExpandedTypes(QualType Ty, +void CodeGenTypes::GetExpandedTypes(QualType Ty, std::vector &ArgTys) { const RecordType *RT = Ty->getAsStructureType(); assert(RT && "Can only expand structure types."); const RecordDecl *RD = RT->getDecl(); - assert(!RD->hasFlexibleArrayMember() && + assert(!RD->hasFlexibleArrayMember() && "Cannot expand structure with flexible array."); - + for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i) { const FieldDecl *FD = *i; - assert(!FD->isBitField() && + assert(!FD->isBitField() && "Cannot expand structure with bit-field members."); - + QualType FT = FD->getType(); if (CodeGenFunction::hasAggregateLLVMType(FT)) { GetExpandedTypes(FT, ArgTys); @@ -157,19 +157,19 @@ void CodeGenTypes::GetExpandedTypes(QualType Ty, } } -llvm::Function::arg_iterator +llvm::Function::arg_iterator CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, llvm::Function::arg_iterator AI) { const RecordType *RT = Ty->getAsStructureType(); assert(RT && "Can only expand structure types."); RecordDecl *RD = RT->getDecl(); - assert(LV.isSimple() && - "Unexpected non-simple lvalue during struct expansion."); + assert(LV.isSimple() && + "Unexpected non-simple lvalue during struct expansion."); llvm::Value *Addr = LV.getAddress(); for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i) { - FieldDecl *FD = *i; + FieldDecl *FD = *i; QualType FT = FD->getType(); // FIXME: What are the right qualifiers here? @@ -185,8 +185,8 @@ CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, return AI; } -void -CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, +void +CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, llvm::SmallVector &Args) { const RecordType *RT = Ty->getAsStructureType(); assert(RT && "Can only expand structure types."); @@ -196,16 +196,16 @@ CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, llvm::Value *Addr = RV.getAggregateAddr(); for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i) { - FieldDecl *FD = *i; + FieldDecl *FD = *i; QualType FT = FD->getType(); - + // FIXME: What are the right qualifiers here? LValue LV = EmitLValueForField(Addr, FD, false, 0); if (CodeGenFunction::hasAggregateLLVMType(FT)) { ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args); } else { RValue RV = EmitLoadOfLValue(LV, FT); - assert(RV.isScalar() && + assert(RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."); Args.push_back(RV.getScalarVal()); } @@ -221,7 +221,7 @@ CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr, const llvm::Type *Ty, CodeGenFunction &CGF) { - const llvm::Type *SrcTy = + const llvm::Type *SrcTy = cast(SrcPtr->getType())->getElementType(); uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty); @@ -244,9 +244,9 @@ static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr, // Otherwise do coercion through memory. This is stupid, but // simple. llvm::Value *Tmp = CGF.CreateTempAlloca(Ty); - llvm::Value *Casted = + llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy)); - llvm::StoreInst *Store = + llvm::StoreInst *Store = CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted); // FIXME: Use better alignment / avoid requiring aligned store. Store->setAlignment(1); @@ -263,7 +263,7 @@ static void CreateCoercedStore(llvm::Value *Src, llvm::Value *DstPtr, CodeGenFunction &CGF) { const llvm::Type *SrcTy = Src->getType(); - const llvm::Type *DstTy = + const llvm::Type *DstTy = cast(DstPtr->getType())->getElementType(); uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -287,7 +287,7 @@ static void CreateCoercedStore(llvm::Value *Src, // to that information. llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy); CGF.Builder.CreateStore(Src, Tmp); - llvm::Value *Casted = + llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy)); llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); // FIXME: Use better alignment / avoid requiring aligned load. @@ -335,11 +335,11 @@ CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) { ResultType = RetAI.getCoerceToType(); break; } - - for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), + + for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { const ABIArgInfo &AI = it->info; - + switch (AI.getKind()) { case ABIArgInfo::Ignore: break; @@ -359,7 +359,7 @@ CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) { case ABIArgInfo::Direct: ArgTys.push_back(ConvertType(it->type)); break; - + case ABIArgInfo::Expand: GetExpandedTypes(it->type, ArgTys); break; @@ -414,7 +414,7 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, break; case ABIArgInfo::Indirect: - PAL.push_back(llvm::AttributeWithIndex::get(Index, + PAL.push_back(llvm::AttributeWithIndex::get(Index, llvm::Attribute::StructRet | llvm::Attribute::NoAlias)); ++Index; @@ -428,7 +428,7 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, break; case ABIArgInfo::Expand: - assert(0 && "Invalid ABI kind for return argument"); + assert(0 && "Invalid ABI kind for return argument"); } if (RetAttrs) @@ -439,12 +439,12 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, // register variable. signed RegParm = 0; if (TargetDecl) - if (const RegparmAttr *RegParmAttr + if (const RegparmAttr *RegParmAttr = TargetDecl->getAttr()) RegParm = RegParmAttr->getNumParams(); unsigned PointerWidth = getContext().Target.getPointerWidth(0); - for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), + for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { QualType ParamType = it->type; const ABIArgInfo &AI = it->info; @@ -483,10 +483,10 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, case ABIArgInfo::Ignore: // Skip increment, no matching LLVM parameter. - continue; + continue; case ABIArgInfo::Expand: { - std::vector Tys; + std::vector Tys; // FIXME: This is rather inefficient. Do we ever actually need to do // anything here? The result should be just reconstructed on the other // side, so extension should be a non-issue. @@ -495,7 +495,7 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, continue; } } - + if (Attributes) PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes)); ++Index; @@ -525,13 +525,13 @@ void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, // Emit allocs for param decls. Give the LLVM Argument nodes names. llvm::Function::arg_iterator AI = Fn->arg_begin(); - + // Name the struct return argument. if (CGM.ReturnTypeUsesSret(FI)) { AI->setName("agg.result"); ++AI; } - + assert(FI.arg_size() == Args.size() && "Mismatch between function signature & arguments."); CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); @@ -556,7 +556,7 @@ void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, V = EmitScalarConversion(V, Ty, Arg->getType()); } } - EmitParmDecl(*Arg, V); + EmitParmDecl(*Arg, V); break; } @@ -580,17 +580,17 @@ void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, EmitParmDecl(*Arg, V); break; } - + case ABIArgInfo::Expand: { // If this structure was expanded into multiple arguments then // we need to create a temporary and reconstruct it from the // arguments. std::string Name = Arg->getNameAsString(); - llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty), + llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty), (Name + ".addr").c_str()); // FIXME: What are the right qualifiers here? - llvm::Function::arg_iterator End = - ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI); + llvm::Function::arg_iterator End = + ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI); EmitParmDecl(*Arg, Temp); // Name the arguments used in expansion and increment AI. @@ -602,14 +602,14 @@ void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, case ABIArgInfo::Ignore: // Initialize the local variable appropriately. - if (hasAggregateLLVMType(Ty)) { + if (hasAggregateLLVMType(Ty)) { EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty))); } else { EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType()))); } - + // Skip increment, no matching LLVM parameter. - continue; + continue; case ABIArgInfo::Coerce: { assert(AI != Fn->arg_end() && "Argument mismatch!"); @@ -668,16 +668,16 @@ void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, case ABIArgInfo::Ignore: break; - + case ABIArgInfo::Coerce: RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this); break; case ABIArgInfo::Expand: - assert(0 && "Invalid ABI kind for return argument"); + assert(0 && "Invalid ABI kind for return argument"); } } - + if (RV) { Builder.CreateRet(RV); } else { @@ -688,12 +688,12 @@ void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) { if (ArgType->isReferenceType()) return EmitReferenceBindingToExpr(E, ArgType); - + return EmitAnyExprToTemp(E); } RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, - llvm::Value *Callee, + llvm::Value *Callee, const CallArgList &CallArgs, const Decl *TargetDecl) { // FIXME: We no longer need the types from CallArgs; lift up and simplify. @@ -703,17 +703,17 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, // location that we would like to return into. QualType RetTy = CallInfo.getReturnType(); const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); - - + + // If the call returns a temporary with struct return, create a temporary // alloca to hold the result. if (CGM.ReturnTypeUsesSret(CallInfo)) Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy))); - + assert(CallInfo.arg_size() == CallArgs.size() && "Mismatch between function signature & arguments."); CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); - for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); + for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); I != E; ++I, ++info_it) { const ABIArgInfo &ArgInfo = info_it->info; RValue RV = I->first; @@ -726,7 +726,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, if (RV.isScalar()) EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second); else - StoreComplexToAddr(RV.getComplexVal(), Args.back(), false); + StoreComplexToAddr(RV.getComplexVal(), Args.back(), false); } else { Args.push_back(RV.getAggregateAddr()); } @@ -745,7 +745,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, Args.push_back(Builder.CreateLoad(RV.getAggregateAddr())); } break; - + case ABIArgInfo::Ignore: break; @@ -758,9 +758,9 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, } else if (RV.isComplex()) { SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce"); StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false); - } else + } else SrcPtr = RV.getAggregateAddr(); - Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), + Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this)); break; } @@ -770,7 +770,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, break; } } - + // If the callee is a bitcast of a function to a varargs pointer to function // type, check to see if we can remove the bitcast. This handles some cases // with unprototyped functions. @@ -780,7 +780,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, const llvm::FunctionType *CurFT = cast(CurPT->getElementType()); const llvm::FunctionType *ActualFT = CalleeF->getFunctionType(); - + if (CE->getOpcode() == llvm::Instruction::BitCast && ActualFT->getReturnType() == CurFT->getReturnType() && ActualFT->getNumParams() == CurFT->getNumParams() && @@ -791,7 +791,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, ArgsMatch = false; break; } - + // Strip the cast if we can get away with it. This is a nice cleanup, // but also allows us to inline the function at -O0 if it is marked // always_inline. @@ -799,20 +799,20 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, Callee = CalleeF; } } - + llvm::BasicBlock *InvokeDest = getInvokeDest(); CodeGen::AttributeListType AttributeList; CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList); llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(), AttributeList.end()); - + llvm::CallSite CS; if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) { CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size()); } else { llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); - CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, + CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args.data(), Args.data()+Args.size()); EmitBlock(Cont); } @@ -828,15 +828,15 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, if (CS.doesNotReturn()) { Builder.CreateUnreachable(); Builder.ClearInsertionPoint(); - + // FIXME: For now, emit a dummy basic block because expr emitters in // generally are not ready to handle emitting expressions at unreachable // points. EnsureInsertPoint(); - + // Return a reasonable RValue. return GetUndefRValue(RetTy); - } + } llvm::Instruction *CI = CS.getInstruction(); if (Builder.isNamePreserving() && @@ -882,7 +882,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, } case ABIArgInfo::Expand: - assert(0 && "Invalid ABI kind for return argument"); + assert(0 && "Invalid ABI kind for return argument"); } assert(0 && "Unhandled ABIArgInfo::Kind"); diff --git a/clang/lib/CodeGen/CGCall.h b/clang/lib/CodeGen/CGCall.h index daf6f00045012e149cf6508fb2d208383b453b5c..2c1048d935efd7c5edc5782d1cdb724dd79fef83 100644 --- a/clang/lib/CodeGen/CGCall.h +++ b/clang/lib/CodeGen/CGCall.h @@ -49,9 +49,9 @@ namespace CodeGen { /// FunctionArgList - Type for representing both the decl and type /// of parameters to a function. The decl must be either a /// ParmVarDecl or ImplicitParamDecl. - typedef llvm::SmallVector, + typedef llvm::SmallVector, 16> FunctionArgList; - + /// CGFunctionInfo - Class to encapsulate the information about a /// function definition. class CGFunctionInfo : public llvm::FoldingSetNode { @@ -67,7 +67,7 @@ namespace CodeGen { typedef const ArgInfo *const_arg_iterator; typedef ArgInfo *arg_iterator; - CGFunctionInfo(QualType ResTy, + CGFunctionInfo(QualType ResTy, const llvm::SmallVector &ArgTys); ~CGFunctionInfo() { delete[] Args; } @@ -89,7 +89,7 @@ namespace CodeGen { it->type.Profile(ID); } template - static void Profile(llvm::FoldingSetNodeID &ID, + static void Profile(llvm::FoldingSetNodeID &ID, QualType ResTy, Iterator begin, Iterator end) { diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index e53f1fa52545ad090f5732d8fd0e839873ea6472..aaaa4d4fa57937301c27865295fc3cbc9b2144a0 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -59,7 +59,7 @@ llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) { FileName = PLoc.getFilename(); FID = PLoc.getIncludeLoc().getRawEncoding(); } - + // See if this compile unit has been used before. llvm::DICompileUnit &Unit = CompileUnitCache[FID]; if (!Unit.isNull()) return Unit; @@ -112,10 +112,10 @@ llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) { unsigned RuntimeVers = 0; if (LO.ObjC1) RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1; - + // Create new compile unit. return Unit = DebugFactory.CreateCompileUnit(LangTag, AbsFileName.getLast(), - AbsFileName.getDirname(), + AbsFileName.getDirname(), Producer, isMain, isOptimized, Flags, RuntimeVers); } @@ -144,13 +144,13 @@ llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT, case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; case BuiltinType::Float: case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; - } + } // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(BT); uint64_t Align = M->getContext().getTypeAlign(BT); uint64_t Offset = 0; - - return DebugFactory.CreateBasicType(Unit, + + return DebugFactory.CreateBasicType(Unit, BT->getName(M->getContext().getLangOptions()), Unit, 0, Size, Align, Offset, /*flags*/ 0, Encoding); @@ -162,17 +162,17 @@ llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty, unsigned Encoding = llvm::dwarf::DW_ATE_complex_float; if (Ty->isComplexIntegerType()) Encoding = llvm::dwarf::DW_ATE_lo_user; - + uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); uint64_t Offset = 0; - + return DebugFactory.CreateBasicType(Unit, "complex", Unit, 0, Size, Align, Offset, /*flags*/ 0, Encoding); } -/// getOrCreateCVRType - Get the CVR qualified type from the cache or create +/// getOrCreateCVRType - Get the CVR qualified type from the cache or create /// a new one if necessary. llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) { // We will create one Derived type for one qualifier and recurse to handle any @@ -181,19 +181,19 @@ llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) { unsigned Tag; if (Ty.isConstQualified()) { Tag = llvm::dwarf::DW_TAG_const_type; - Ty.removeConst(); + Ty.removeConst(); FromTy = getOrCreateType(Ty, Unit); } else if (Ty.isVolatileQualified()) { Tag = llvm::dwarf::DW_TAG_volatile_type; - Ty.removeVolatile(); + Ty.removeVolatile(); FromTy = getOrCreateType(Ty, Unit); } else { assert(Ty.isRestrictQualified() && "Unknown type qualifier for debug info"); Tag = llvm::dwarf::DW_TAG_restrict_type; - Ty.removeRestrict(); + Ty.removeRestrict(); FromTy = getOrCreateType(Ty, Unit); } - + // No need to fill in the Name, Line, Size, Alignment, Offset in case of // CVR derived types. return DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(), @@ -203,11 +203,11 @@ llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) { llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, llvm::DICompileUnit Unit) { llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit); - + // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); - + return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, "", llvm::DICompileUnit(), 0, Size, Align, 0, 0, EltTy); @@ -216,11 +216,11 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, llvm::DICompileUnit Unit) { llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit); - + // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); - + return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, "", llvm::DICompileUnit(), 0, Size, Align, 0, 0, EltTy); @@ -274,11 +274,11 @@ llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor", DefUnit, 0, FieldOffset, 0, 0, 0, llvm::DIType(), Elements); - + // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); - + DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, "", llvm::DICompileUnit(), 0, Size, Align, 0, 0, EltTy); @@ -344,7 +344,7 @@ llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic", DefUnit, 0, FieldOffset, 0, 0, 0, llvm::DIType(), Elements); - + BlockLiteralGenericSet = true; BlockLiteralGeneric = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, @@ -358,7 +358,7 @@ llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, // Typedefs are derived from some other type. If we have a typedef of a // typedef, make sure to emit the whole chain. llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); - + // We don't set size information, but do specify where the typedef was // declared. std::string TyName = Ty->getDecl()->getNameAsString(); @@ -379,7 +379,7 @@ llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, // Add the result type at least. EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); - + // Set up remainder of arguments if there is a prototype. // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! if (const FunctionProtoType *FTP = dyn_cast(Ty)) { @@ -391,7 +391,7 @@ llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, llvm::DIArray EltTypeArray = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); - + return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, Unit, "", llvm::DICompileUnit(), 0, 0, 0, 0, 0, @@ -402,7 +402,7 @@ llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, llvm::DICompileUnit Unit) { RecordDecl *Decl = Ty->getDecl(); - + unsigned Tag; if (Decl->isStruct()) Tag = llvm::dwarf::DW_TAG_structure_type; @@ -425,7 +425,7 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, DefUnit = getOrCreateCompileUnit(Decl->getLocation()); Line = PLoc.getLine(); } - + // Records and classes and unions can all be recursive. To handle them, we // first generate a debug descriptor for the struct as a forward declaration. // Then (if it is a definition) we go through and get debug info for all of @@ -435,7 +435,7 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, llvm::DICompositeType FwdDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0, llvm::DIType(), llvm::DIArray()); - + // If this is just a forward declaration, return it. if (!Decl->getDefinition(M->getContext())) return FwdDecl; @@ -451,7 +451,7 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, unsigned FieldNo = 0; for (RecordDecl::field_iterator I = Decl->field_begin(), - E = Decl->field_end(); + E = Decl->field_end(); I != E; ++I, ++FieldNo) { FieldDecl *Field = *I; llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); @@ -467,7 +467,7 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc); llvm::DICompileUnit FieldDefUnit; unsigned FieldLine = 0; - + if (!PLoc.isInvalid()) { FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc); FieldLine = PLoc.getLine(); @@ -477,18 +477,18 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, uint64_t FieldSize = 0; unsigned FieldAlign = 0; if (!FType->isIncompleteArrayType()) { - + // Bit size, align and offset of the type. FieldSize = M->getContext().getTypeSize(FType); Expr *BitWidth = Field->getBitWidth(); if (BitWidth) FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue(); - + FieldAlign = M->getContext().getTypeAlign(FType); } - uint64_t FieldOffset = RL.getFieldOffset(FieldNo); - + uint64_t FieldOffset = RL.getFieldOffset(FieldNo); + // Create a DW_TAG_member node to remember the offset of this field in the // struct. FIXME: This is an absolutely insane way to capture this // information. When we gut debug info, this should be fixed. @@ -498,14 +498,14 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, FieldOffset, 0, FieldTy); EltTys.push_back(FieldTy); } - + llvm::DIArray Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); - + llvm::DICompositeType RealDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(), Elements); @@ -515,7 +515,7 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, FwdDecl.replaceAllUsesWith(RealDecl); // Update TypeCache. - TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; + TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; return RealDecl; } @@ -523,7 +523,7 @@ llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, llvm::DICompileUnit Unit) { ObjCInterfaceDecl *Decl = Ty->getDecl(); - + unsigned Tag = llvm::dwarf::DW_TAG_structure_type; SourceManager &SM = M->getContext().getSourceManager(); @@ -534,7 +534,7 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation()); unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine(); - + unsigned RuntimeLang = DefUnit.getLanguage(); // To handle recursive interface, we @@ -547,7 +547,7 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0, llvm::DIType(), llvm::DIArray(), RuntimeLang); - + // If this is just a forward declaration, return it. if (Decl->isForwardDecl()) return FwdDecl; @@ -561,9 +561,9 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, ObjCInterfaceDecl *SClass = Decl->getSuperClass(); if (SClass) { - llvm::DIType SClassTy = + llvm::DIType SClassTy = getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit); - llvm::DIType InhTag = + llvm::DIType InhTag = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance, Unit, "", llvm::DICompileUnit(), 0, 0, 0, 0 /* offset */, 0, SClassTy); @@ -590,13 +590,13 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc); unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine(); - + QualType FType = Field->getType(); uint64_t FieldSize = 0; unsigned FieldAlign = 0; if (!FType->isIncompleteArrayType()) { - + // Bit size, align and offset of the type. FieldSize = M->getContext().getTypeSize(FType); Expr *BitWidth = Field->getBitWidth(); @@ -606,14 +606,14 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, FieldAlign = M->getContext().getTypeAlign(FType); } - uint64_t FieldOffset = RL.getFieldOffset(FieldNo); - + uint64_t FieldOffset = RL.getFieldOffset(FieldNo); + unsigned Flags = 0; if (Field->getAccessControl() == ObjCIvarDecl::Protected) Flags = llvm::DIType::FlagProtected; else if (Field->getAccessControl() == ObjCIvarDecl::Private) Flags = llvm::DIType::FlagPrivate; - + // Create a DW_TAG_member node to remember the offset of this field in the // struct. FIXME: This is an absolutely insane way to capture this // information. When we gut debug info, this should be fixed. @@ -623,14 +623,14 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, FieldOffset, Flags, FieldTy); EltTys.push_back(FieldTy); } - + llvm::DIArray Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); - + llvm::DICompositeType RealDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(), Elements, @@ -641,7 +641,7 @@ llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, FwdDecl.replaceAllUsesWith(RealDecl); // Update TypeCache. - TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; + TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; return RealDecl; } @@ -652,13 +652,13 @@ llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty, llvm::SmallVector Enumerators; // Create DIEnumerator elements for each enumerator. - for (EnumDecl::enumerator_iterator + for (EnumDecl::enumerator_iterator Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end(); Enum != EnumEnd; ++Enum) { Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsString(), Enum->getInitVal().getZExtValue())); } - + // Return a CompositeType for the enum itself. llvm::DIArray EltArray = DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size()); @@ -670,7 +670,7 @@ llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty, PresumedLoc PLoc = SM.getPresumedLoc(DefLoc); unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine(); - + // Size and align of the type. uint64_t Size = 0; unsigned Align = 0; @@ -678,7 +678,7 @@ llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty, Size = M->getContext().getTypeSize(Ty); Align = M->getContext().getTypeAlign(Ty); } - + return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type, Unit, EnumName, DefUnit, Line, Size, Align, 0, 0, @@ -691,7 +691,7 @@ llvm::DIType CGDebugInfo::CreateType(const TagType *Ty, return CreateType(RT, Unit); else if (const EnumType *ET = dyn_cast(Ty)) return CreateType(ET, Unit); - + return llvm::DIType(); } @@ -699,8 +699,8 @@ llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DICompileUnit Unit) { uint64_t Size; uint64_t Align; - - + + // FIXME: make getTypeAlign() aware of VLAs and incomplete array types if (const VariableArrayType *VAT = dyn_cast(Ty)) { Size = 0; @@ -714,7 +714,7 @@ llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, Size = M->getContext().getTypeSize(Ty); Align = M->getContext().getTypeAlign(Ty); } - + // Add the dimensions of the array. FIXME: This loses CV qualifiers from // interior arrays, do we care? Why aren't nested arrays represented the // obvious/recursive way? @@ -722,14 +722,14 @@ llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, QualType EltTy(Ty, 0); while ((Ty = dyn_cast(EltTy))) { uint64_t Upper = 0; - if (const ConstantArrayType *CAT = dyn_cast(Ty)) + if (const ConstantArrayType *CAT = dyn_cast(Ty)) if (CAT->getSize().getZExtValue()) - Upper = CAT->getSize().getZExtValue() - 1; + Upper = CAT->getSize().getZExtValue() - 1; // FIXME: Verify this is right for VLAs. Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper)); EltTy = Ty->getElementType(); } - + llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size()); @@ -747,7 +747,7 @@ llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DICompileUnit Unit) { if (Ty.isNull()) return llvm::DIType(); - + // Check TypeCache first. llvm::DIType &Slot = TypeCache[Ty.getAsOpaquePtr()]; if (!Slot.isNull()) return Slot; @@ -778,7 +778,7 @@ llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, return llvm::DIType(); case Type::ObjCObjectPointer: return Slot = CreateType(cast(Ty), Unit); - case Type::ObjCInterface: + case Type::ObjCInterface: return Slot = CreateType(cast(Ty), Unit); case Type::Builtin: return Slot = CreateType(cast(Ty), Unit); case Type::Complex: return Slot = CreateType(cast(Ty), Unit); @@ -788,14 +788,14 @@ llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, case Type::Typedef: return Slot = CreateType(cast(Ty), Unit); case Type::Record: case Type::Enum: - return Slot = CreateType(cast(Ty), Unit); + return Slot = CreateType(cast(Ty), Unit); case Type::FunctionProto: case Type::FunctionNoProto: return Slot = CreateType(cast(Ty), Unit); case Type::Elaborated: return Slot = getOrCreateType(cast(Ty)->getUnderlyingType(), Unit); - + case Type::ConstantArray: case Type::ConstantArrayWithExpr: case Type::ConstantArrayWithoutExpr: @@ -812,7 +812,7 @@ llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, return Slot = getOrCreateType(cast(Ty)->getUnderlyingType(), Unit); } - + return Slot; } @@ -822,25 +822,25 @@ void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType, llvm::Function *Fn, CGBuilderTy &Builder) { const char *LinkageName = Name; - + // Skip the asm prefix if it exists. // // FIXME: This should probably be the unmangled name? if (Name[0] == '\01') ++Name; - + // FIXME: Why is this using CurLoc??? llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc); SourceManager &SM = M->getContext().getSourceManager(); unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine(); - + llvm::DISubprogram SP = DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo, getOrCreateType(ReturnType, Unit), Fn->hasInternalLinkage(), true/*definition*/); - + DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock()); - + // Push function on region stack. RegionStack.push_back(SP); } @@ -848,10 +848,10 @@ void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType, void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) { if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; - + // Don't bother if things are the same as last time. SourceManager &SM = M->getContext().getSourceManager(); - if (CurLoc == PrevLoc + if (CurLoc == PrevLoc || (SM.getInstantiationLineNumber(CurLoc) == SM.getInstantiationLineNumber(PrevLoc) && SM.isFromSameFile(CurLoc, PrevLoc))) @@ -864,7 +864,7 @@ void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) { llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc); PresumedLoc PLoc = SM.getPresumedLoc(CurLoc); DebugFactory.InsertStopPoint(Unit, PLoc.getLine(), PLoc.getColumn(), - Builder.GetInsertBlock()); + Builder.GetInsertBlock()); } /// EmitRegionStart- Constructs the debug code for entering a declarative @@ -885,7 +885,7 @@ void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) { // Provide an region stop point. EmitStopPoint(Fn, Builder); - + DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock()); RegionStack.pop_back(); } @@ -914,9 +914,9 @@ void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag, else Unit = llvm::DICompileUnit(); - + // Create the descriptor for the variable. - llvm::DIVariable D = + llvm::DIVariable D = DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsString(), Unit, Line, Ty); // Insert an llvm.dbg.declare into the current block. @@ -939,7 +939,7 @@ void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, /// EmitGlobalVariable - Emit information about a global variable. -void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, +void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, const VarDecl *Decl) { // Do not emit variable debug information while generating optimized code. @@ -959,14 +959,14 @@ void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, QualType T = Decl->getType(); if (T->isIncompleteArrayType()) { - + // CodeGen turns int[] into int[1] so we'll do the same here. llvm::APSInt ConstVal(32); - + ConstVal = 1; QualType ET = M->getContext().getAsArrayType(T)->getElementType(); - - T = M->getContext().getConstantArrayType(ET, ConstVal, + + T = M->getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal, 0); } @@ -977,7 +977,7 @@ void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, } /// EmitGlobalVariable - Emit information about an objective-c interface. -void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, +void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, ObjCInterfaceDecl *Decl) { // Create global variable debug descriptor. llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation()); @@ -989,14 +989,14 @@ void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, QualType T = M->getContext().getObjCInterfaceType(Decl); if (T->isIncompleteArrayType()) { - + // CodeGen turns int[] into int[1] so we'll do the same here. llvm::APSInt ConstVal(32); - + ConstVal = 1; QualType ET = M->getContext().getAsArrayType(T)->getElementType(); - - T = M->getContext().getConstantArrayType(ET, ConstVal, + + T = M->getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal, 0); } diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h index ac28e5b879ed5820046cd8be36500894b2c72c94..682f7aedd871ea6563103266d640001f6de75a02 100644 --- a/clang/lib/CodeGen/CGDebugInfo.h +++ b/clang/lib/CodeGen/CGDebugInfo.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This is the source level debug info generator for llvm translation. +// This is the source level debug info generator for llvm translation. // //===----------------------------------------------------------------------===// @@ -29,14 +29,14 @@ namespace clang { namespace CodeGen { class CodeGenModule; -/// CGDebugInfo - This class gathers all debug information during compilation -/// and is responsible for emitting to llvm globals or pass directly to +/// CGDebugInfo - This class gathers all debug information during compilation +/// and is responsible for emitting to llvm globals or pass directly to /// the backend. class CGDebugInfo { CodeGenModule *M; bool isMainCompileUnitCreated; llvm::DIFactory DebugFactory; - + SourceLocation CurLoc, PrevLoc; /// CompileUnitCache - Cache of previously constructed CompileUnits. @@ -45,7 +45,7 @@ class CGDebugInfo { /// TypeCache - Cache of previously constructed Types. // FIXME: Eliminate this map. Be careful of iterator invalidation. std::map TypeCache; - + bool BlockLiteralGenericSet; llvm::DIType BlockLiteralGeneric; @@ -56,7 +56,7 @@ class CGDebugInfo { llvm::DIType CreateType(const ComplexType *Ty, llvm::DICompileUnit U); llvm::DIType CreateCVRType(QualType Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const TypedefType *Ty, llvm::DICompileUnit U); - llvm::DIType CreateType(const ObjCObjectPointerType *Ty, + llvm::DIType CreateType(const ObjCObjectPointerType *Ty, llvm::DICompileUnit Unit); llvm::DIType CreateType(const PointerType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const BlockPointerType *Ty, llvm::DICompileUnit U); @@ -83,12 +83,12 @@ public: /// start of a new function. void EmitFunctionStart(const char *Name, QualType ReturnType, llvm::Function *Fn, CGBuilderTy &Builder); - + /// EmitRegionStart - Emit a call to llvm.dbg.region.start to indicate start - /// of a new block. + /// of a new block. void EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder); - - /// EmitRegionEnd - Emit call to llvm.dbg.region.end to indicate end of a + + /// EmitRegionEnd - Emit call to llvm.dbg.region.end to indicate end of a /// block. void EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder); @@ -101,19 +101,19 @@ public: /// variable declaration. void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder); - + /// EmitGlobalVariable - Emit information about a global variable. void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl); /// EmitGlobalVariable - Emit information about an objective-c interface. void EmitGlobalVariable(llvm::GlobalVariable *GV, ObjCInterfaceDecl *Decl); - + private: /// EmitDeclare - Emit call to llvm.dbg.declare for a variable declaration. void EmitDeclare(const VarDecl *decl, unsigned Tag, llvm::Value *AI, CGBuilderTy &Builder); - - + + /// getOrCreateCompileUnit - Get the compile unit from the cache or create a /// new one if necessary. llvm::DICompileUnit getOrCreateCompileUnit(SourceLocation Loc); diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp index 2b8348eece6883c7ce15e92c56cdfc13e7f744c9..e637d40de0779f5916a68e44f4446ce318e0af40 100644 --- a/clang/lib/CodeGen/CGDecl.cpp +++ b/clang/lib/CodeGen/CGDecl.cpp @@ -35,22 +35,22 @@ void CodeGenFunction::EmitDecl(const Decl &D) { case Decl::Function: // void X(); case Decl::Record: // struct/union/class X; case Decl::Enum: // enum X; - case Decl::EnumConstant: // enum ? { X = ? } + case Decl::EnumConstant: // enum ? { X = ? } case Decl::CXXRecord: // struct/union/class X; [C++] // None of these decls require codegen support. return; - + case Decl::Var: { const VarDecl &VD = cast(D); - assert(VD.isBlockVarDecl() && + assert(VD.isBlockVarDecl() && "Should not see file-scope variables inside a function!"); return EmitBlockVarDecl(VD); } - + case Decl::Typedef: { // typedef int X; const TypedefDecl &TD = cast(D); QualType Ty = TD.getUnderlyingType(); - + if (Ty->isVariablyModifiedType()) EmitVLASize(Ty); } @@ -62,7 +62,7 @@ void CodeGenFunction::EmitDecl(const Decl &D) { void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) { if (D.hasAttr()) CGM.ErrorUnsupported(&D, "__asm__"); - + switch (D.getStorageClass()) { case VarDecl::None: case VarDecl::Auto: @@ -98,22 +98,22 @@ CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D, ContextName = CurFn->getName(); else assert(0 && "Unknown context for block var decl"); - + Name = ContextName + Separator + D.getNameAsString(); } const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty); return new llvm::GlobalVariable(CGM.getModule(), LTy, Ty.isConstant(getContext()), Linkage, - CGM.EmitNullConstant(D.getType()), Name, 0, + CGM.EmitNullConstant(D.getType()), Name, 0, D.isThreadSpecified(), Ty.getAddressSpace()); } -void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { +void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { llvm::Value *&DMEntry = LocalDeclMap[&D]; assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); - - llvm::GlobalVariable *GV = + + llvm::GlobalVariable *GV = CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage); // Store into LocalDeclMap before generating initializer to handle @@ -143,7 +143,7 @@ void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { // in the LLVM type system.) if (GV->getType() != Init->getType()) { llvm::GlobalVariable *OldGV = GV; - + GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), OldGV->isConstant(), OldGV->getLinkage(), Init, "", @@ -154,13 +154,13 @@ void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { GV->takeName(OldGV); // Replace all uses of the old global with the new global - llvm::Constant *NewPtrForOldDecl = + llvm::Constant *NewPtrForOldDecl = llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); OldGV->replaceAllUsesWith(NewPtrForOldDecl); // Erase the old global, since it is no longer used. OldGV->eraseFromParent(); - } + } GV->setInitializer(Init); } @@ -170,14 +170,14 @@ void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { if (const AnnotateAttr *AA = D.getAttr()) { SourceManager &SM = CGM.getContext().getSourceManager(); llvm::Constant *Ann = - CGM.EmitAnnotateAttr(GV, AA, + CGM.EmitAnnotateAttr(GV, AA, SM.getInstantiationLineNumber(D.getLocation())); CGM.AddAnnotation(Ann); } if (const SectionAttr *SA = D.getAttr()) GV->setSection(SA->getName()); - + if (D.hasAttr()) CGM.AddUsedGlobal(GV); @@ -198,7 +198,7 @@ void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { DI->EmitGlobalVariable(static_cast(GV), &D); } } - + /// BuildByRefType - This routine changes a __block variable declared as T x /// into: /// @@ -216,7 +216,7 @@ void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) { QualType Ty = D->getType(); uint64_t Align = getContext().getDeclAlignInBytes(D); - + const llvm::Type *LTy = ConvertType(Ty); bool needsCopyDispose = BlockRequiresCopying(Ty); std::vector Types(needsCopyDispose*2+5); @@ -256,7 +256,7 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { LTy = BuildByRefType(&D); llvm::AllocaInst *Alloc = CreateTempAlloca(LTy); Alloc->setName(D.getNameAsString().c_str()); - + if (isByRef) Align = std::max(Align, unsigned(Target.getPointerAlign(0) / 8)); Alloc->setAlignment(Align); @@ -265,11 +265,11 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { // Targets that don't support recursion emit locals as globals. const char *Class = D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto."; - DeclPtr = CreateStaticBlockVarDecl(D, Class, + DeclPtr = CreateStaticBlockVarDecl(D, Class, llvm::GlobalValue ::InternalLinkage); } - + // FIXME: Can this happen? if (Ty->isVariablyModifiedType()) EmitVLASize(Ty); @@ -281,26 +281,26 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack"); - + llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); llvm::Value *V = Builder.CreateCall(F); - + Builder.CreateStore(V, Stack); DidCallStackSave = true; - + { // Push a cleanup block and restore the stack there. CleanupScope scope(*this); - + V = Builder.CreateLoad(Stack, "tmp"); llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore); Builder.CreateCall(F, V); } } - + // Get the element type. - const llvm::Type *LElemTy = ConvertTypeForMem(Ty); + const llvm::Type *LElemTy = ConvertTypeForMem(Ty); const llvm::Type *LElemPtrTy = llvm::PointerType::get(LElemTy, D.getType().getAddressSpace()); @@ -309,7 +309,7 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { // Downcast the VLA size expression VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext), false, "tmp"); - + // Allocate memory for the array. llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla"); @@ -323,16 +323,16 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { // Emit debug info for local var declaration. if (CGDebugInfo *DI = getDebugInfo()) { assert(HaveInsertPoint() && "Unexpected unreachable point!"); - + DI->setLocation(D.getLocation()); if (Target.useGlobalsForAutomaticVariables()) { DI->EmitGlobalVariable(static_cast(DeclPtr), &D); } else if (isByRef) { - // FIXME: This code is broken and will not emit debug info for the + // FIXME: This code is broken and will not emit debug info for the // variable. The right way to do this would be to tell LLVM that this is a // byref pointer, and what the offset is. Unfortunately, right now it's // not possible unless we create a DIType that corresponds to the byref - // struct. + // struct. /* llvm::Value *Loc; bool needsCopyDispose = BlockRequiresCopying(Ty); @@ -369,7 +369,7 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty); } else if (!hasAggregateLLVMType(Init->getType())) { llvm::Value *V = EmitScalarExpr(Init); - EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified(), + EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified(), D.getType()); } else if (Init->getType()->isAnyComplexType()) { EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified()); @@ -377,7 +377,7 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { EmitAggExpr(Init, Loc, D.getType().isVolatileQualified()); } } - + if (isByRef) { const llvm::PointerType *PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); @@ -448,19 +448,19 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext()); assert(D && "EmitLocalBlockVarDecl - destructor is nul"); assert(!Ty->getAs() && "FIXME - destruction of arrays NYI"); - + CleanupScope scope(*this); EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr); } } - + // Handle the cleanup attribute if (const CleanupAttr *CA = D.getAttr()) { const FunctionDecl *FD = CA->getFunctionDecl(); - + llvm::Constant* F = CGM.GetAddrOfFunction(GlobalDecl(FD)); assert(F && "Could not find function!"); - + CleanupScope scope(*this); const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD); @@ -469,15 +469,15 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { // the type of the pointer. An example of this is // void f(void* arg); // __attribute__((cleanup(f))) void *g; - // + // // To fix this we insert a bitcast here. QualType ArgTy = Info.arg_begin()->type; DeclPtr = Builder.CreateBitCast(DeclPtr, ConvertType(ArgTy)); - + CallArgList Args; - Args.push_back(std::make_pair(RValue::get(DeclPtr), + Args.push_back(std::make_pair(RValue::get(DeclPtr), getContext().getPointerType(D.getType()))); - + EmitCall(Info, F, Args); } @@ -489,14 +489,14 @@ void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { } } -/// Emit an alloca (or GlobalValue depending on target) +/// Emit an alloca (or GlobalValue depending on target) /// for the specified parameter and set up LocalDeclMap. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) { // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? assert((isa(D) || isa(D)) && "Invalid argument to EmitParmDecl"); QualType Ty = D.getType(); - + llvm::Value *DeclPtr; if (!Ty->isConstantSizeType()) { // Variable sized values always are passed by-reference. @@ -510,7 +510,7 @@ void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) { Name += ".addr"; DeclPtr = CreateTempAlloca(LTy); DeclPtr->setName(Name.c_str()); - + // Store the initial value into the alloca. EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(), Ty); } else { diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index 4a04bd3f2001e5f4a58ea5d0073b83a4ea8bde61..969b789d5172ff08cc09db5ed031f0118c6b002e 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -847,7 +847,7 @@ LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) { } std::string FunctionName = - PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type, + PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type, CurCodeDecl); GlobalVarName += FunctionName; @@ -1073,8 +1073,7 @@ LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue, LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, FieldDecl* Field, bool isUnion, - unsigned CVRQualifiers) -{ + unsigned CVRQualifiers) { if (Field->isBitField()) return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers); diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp index f8e9c56b1825d2bca6fde316f883ef17ed35915f..8bda0f3e36ed7a15f903536ba1cea911ef181df4 100644 --- a/clang/lib/CodeGen/CGExprAgg.cpp +++ b/clang/lib/CodeGen/CGExprAgg.cpp @@ -62,7 +62,7 @@ public: //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// - + void VisitStmt(Stmt *S) { CGF.ErrorUnsupported(S, "aggregate expression"); } @@ -75,18 +75,18 @@ public: void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { - EmitAggLoadOfLValue(E); + EmitAggLoadOfLValue(E); } void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { EmitAggLoadOfLValue(E); } void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { - EmitAggLoadOfLValue(E); + EmitAggLoadOfLValue(E); } void VisitPredefinedExpr(const PredefinedExpr *E) { - EmitAggLoadOfLValue(E); + EmitAggLoadOfLValue(E); } - + // Operators. void VisitCastExpr(CastExpr *E); void VisitCallExpr(const CallExpr *E); @@ -101,7 +101,7 @@ public: } void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); - + void VisitConditionalOperator(const ConditionalOperator *CO); void VisitChooseExpr(const ChooseExpr *CE); void VisitInitListExpr(InitListExpr *E); @@ -185,18 +185,18 @@ void AggExprEmitter::VisitCastExpr(CastExpr *E) { return; } if (E->getCastKind() == CastExpr::CK_UserDefinedConversion) { - if (const CXXFunctionalCastExpr *CXXFExpr = + if (const CXXFunctionalCastExpr *CXXFExpr = dyn_cast(E)) CGF.EmitCXXFunctionalCastExpr(CXXFExpr); - else + else if (isa(E)) Visit(E->getSubExpr()); return; } - + // FIXME: Remove the CK_Unknown check here. - assert((E->getCastKind() == CastExpr::CK_NoOp || - E->getCastKind() == CastExpr::CK_Unknown) && + assert((E->getCastKind() == CastExpr::CK_NoOp || + E->getCastKind() == CastExpr::CK_Unknown) && "Only no-op casts allowed!"); assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), E->getType()) && @@ -209,7 +209,7 @@ void AggExprEmitter::VisitCallExpr(const CallExpr *E) { EmitAggLoadOfLValue(E); return; } - + RValue RV = CGF.EmitCallExpr(E); EmitFinalDestCopy(E, RV); } @@ -259,21 +259,21 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { if (!AggLoc) AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); - CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), + CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), RValue::getAggregate(AggLoc, VolatileDest)); } else if (LHS.isKVCRef()) { llvm::Value *AggLoc = DestPtr; if (!AggLoc) AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); - CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), + CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), RValue::getAggregate(AggLoc, VolatileDest)); } else { bool RequiresGCollection = false; if (CGF.getContext().getLangOptions().NeXTRuntime) { QualType LHSTy = E->getLHS()->getType(); if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs()) - RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); + RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); } // Codegen the RHS so that it stores directly into the LHS. CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), @@ -286,27 +286,27 @@ void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); - + llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); - + CGF.PushConditionalTempDestruction(); CGF.EmitBlock(LHSBlock); - + // Handle the GNU extension for missing LHS. assert(E->getLHS() && "Must have LHS for aggregate value"); Visit(E->getLHS()); CGF.PopConditionalTempDestruction(); CGF.EmitBranch(ContBlock); - + CGF.PushConditionalTempDestruction(); CGF.EmitBlock(RHSBlock); - + Visit(E->getRHS()); CGF.PopConditionalTempDestruction(); CGF.EmitBranch(ContBlock); - + CGF.EmitBlock(ContBlock); } @@ -328,16 +328,16 @@ void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { llvm::Value *Val = DestPtr; - + if (!Val) { // Create a temporary variable. Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); // FIXME: volatile CGF.EmitAggExpr(E->getSubExpr(), Val, false); - } else + } else Visit(E->getSubExpr()); - + // Don't make this a live temporary if we're emitting an initializer expr. if (!IsInitializer) CGF.PushCXXTemporary(E->getTemporary(), Val); @@ -346,7 +346,7 @@ void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { void AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { llvm::Value *Val = DestPtr; - + if (!Val) { // Create a temporary variable. Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); @@ -392,7 +392,7 @@ void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { #if 0 - // FIXME: Disabled while we figure out what to do about + // FIXME: Disabled while we figure out what to do about // test/CodeGen/bitfield.c // // If we can, prefer a copy from a global; this is a lot less code for long @@ -420,7 +420,7 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { cast(DestPtr->getType()); const llvm::ArrayType *AType = cast(APType->getElementType()); - + uint64_t NumInitElements = E->getNumInits(); if (E->getNumInits() > 0) { @@ -435,7 +435,7 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { uint64_t NumArrayElements = AType->getNumElements(); QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); - + unsigned CVRqualifier = ElementType.getCVRQualifiers(); for (uint64_t i = 0; i != NumArrayElements; ++i) { @@ -449,9 +449,9 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { } return; } - + assert(E->getType()->isRecordType() && "Only support structs/unions here!"); - + // Do struct initialization; this code just sets each individual member // to the approprate value. This makes bitfield support automatic; // the disadvantage is that the generated code is more difficult for @@ -465,7 +465,7 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { // specified by the initializer list. if (!E->getInitializedFieldInUnion()) { // Empty union; we have nothing to do. - + #ifndef NDEBUG // Make sure that it's really an empty and not a failure of // semantic analysis. @@ -491,7 +491,7 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { return; } - + // Here we iterate over the fields; this makes it simpler to both // default-initialize fields and skip over unnamed fields. for (RecordDecl::field_iterator Field = SD->field_begin(), @@ -528,13 +528,13 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { /// true, DestPtr cannot be 0. void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest, bool IgnoreResult, - bool IsInitializer, + bool IsInitializer, bool RequiresGCollection) { assert(E && hasAggregateLLVMType(E->getType()) && "Invalid aggregate expression to emit"); assert ((DestPtr != 0 || VolatileDest == false) && "volatile aggregate can't be 0"); - + AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, RequiresGCollection) .Visit(const_cast(E)); @@ -550,7 +550,7 @@ void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, QualType Ty, bool isVolatile) { assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); - + // Aggregate assignment turns into llvm.memcpy. This is almost valid per // C99 6.5.16.1p3, which states "If the value being stored in an object is // read from another object that overlaps in anyway the storage of the first @@ -567,14 +567,14 @@ void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); if (SrcPtr->getType() != BP) SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); - + // Get size and alignment info for this aggregate. std::pair TypeInfo = getContext().getTypeInfo(Ty); - + // FIXME: Handle variable sized types. const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, LLVMPointerWidth); - + // FIXME: If we have a volatile struct, the optimizer can remove what might // appear to be `extra' memory ops: // @@ -591,6 +591,6 @@ void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, DestPtr, SrcPtr, // TypeInfo.first describes size in bits. llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), TypeInfo.second/8)); } diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index 593406f5d0d3054e3ce62233dfb3766c166d2037..bea6d80b43dcf21932ff5f1746cdc33848f9af37 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -33,63 +33,63 @@ class VISIBILITY_HIDDEN ConstStructBuilder { CodeGenModule &CGM; CodeGenFunction *CGF; - bool Packed; + bool Packed; unsigned NextFieldOffsetInBytes; - + std::vector Elements; ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF) : CGM(CGM), CGF(CGF), Packed(false), NextFieldOffsetInBytes(0) { } - bool AppendField(const FieldDecl *Field, uint64_t FieldOffset, + bool AppendField(const FieldDecl *Field, uint64_t FieldOffset, const Expr *InitExpr) { uint64_t FieldOffsetInBytes = FieldOffset / 8; - - assert(NextFieldOffsetInBytes <= FieldOffsetInBytes + + assert(NextFieldOffsetInBytes <= FieldOffsetInBytes && "Field offset mismatch!"); - + // Emit the field. llvm::Constant *C = CGM.EmitConstantExpr(InitExpr, Field->getType(), CGF); if (!C) return false; unsigned FieldAlignment = getAlignment(C); - + // Round up the field offset to the alignment of the field type. - uint64_t AlignedNextFieldOffsetInBytes = + uint64_t AlignedNextFieldOffsetInBytes = llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment); - + if (AlignedNextFieldOffsetInBytes > FieldOffsetInBytes) { std::vector PackedElements; - + assert(!Packed && "Alignment is wrong even with a packed struct!"); - + // Convert the struct to a packed struct. uint64_t ElementOffsetInBytes = 0; - + for (unsigned i = 0, e = Elements.size(); i != e; ++i) { llvm::Constant *C = Elements[i]; - - unsigned ElementAlign = + + unsigned ElementAlign = CGM.getTargetData().getABITypeAlignment(C->getType()); - uint64_t AlignedElementOffsetInBytes = + uint64_t AlignedElementOffsetInBytes = llvm::RoundUpToAlignment(ElementOffsetInBytes, ElementAlign); - + if (AlignedElementOffsetInBytes > ElementOffsetInBytes) { // We need some padding. - uint64_t NumBytes = + uint64_t NumBytes = AlignedElementOffsetInBytes - ElementOffsetInBytes; - + const llvm::Type *Ty = llvm::Type::getInt8Ty(CGF->getLLVMContext()); - if (NumBytes > 1) + if (NumBytes > 1) Ty = llvm::ArrayType::get(Ty, NumBytes); - + llvm::Constant *Padding = llvm::Constant::getNullValue(Ty); PackedElements.push_back(Padding); ElementOffsetInBytes += getSizeInBytes(Padding); } - + PackedElements.push_back(C); ElementOffsetInBytes += getSizeInBytes(C); } @@ -105,51 +105,51 @@ class VISIBILITY_HIDDEN ConstStructBuilder { if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) { // We need to append padding. AppendPadding(FieldOffsetInBytes - NextFieldOffsetInBytes); - + assert(NextFieldOffsetInBytes == FieldOffsetInBytes && "Did not add enough padding!"); - + AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes; } - + // Add the field. Elements.push_back(C); NextFieldOffsetInBytes = AlignedNextFieldOffsetInBytes + getSizeInBytes(C); return true; } - - bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, + + bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, const Expr *InitExpr) { - llvm::ConstantInt *CI = - cast_or_null(CGM.EmitConstantExpr(InitExpr, - Field->getType(), + llvm::ConstantInt *CI = + cast_or_null(CGM.EmitConstantExpr(InitExpr, + Field->getType(), CGF)); // FIXME: Can this ever happen? if (!CI) return false; - + if (FieldOffset > NextFieldOffsetInBytes * 8) { // We need to add padding. - uint64_t NumBytes = - llvm::RoundUpToAlignment(FieldOffset - + uint64_t NumBytes = + llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBytes * 8, 8) / 8; - + AppendPadding(NumBytes); } - uint64_t FieldSize = + uint64_t FieldSize = Field->getBitWidth()->EvaluateAsInt(CGM.getContext()).getZExtValue(); llvm::APInt FieldValue = CI->getValue(); - + // Promote the size of FieldValue if necessary // FIXME: This should never occur, but currently it can because initializer // constants are cast to bool, and because clang is not enforcing bitfield // width limits. if (FieldSize > FieldValue.getBitWidth()) FieldValue.zext(FieldSize); - + // Truncate the size of FieldValue to the bit field size. if (FieldSize < FieldValue.getBitWidth()) FieldValue.trunc(FieldSize); @@ -158,18 +158,18 @@ class VISIBILITY_HIDDEN ConstStructBuilder { // Either part of the field or the entire field can go into the previous // byte. assert(!Elements.empty() && "Elements can't be empty!"); - - unsigned BitsInPreviousByte = + + unsigned BitsInPreviousByte = NextFieldOffsetInBytes * 8 - FieldOffset; - - bool FitsCompletelyInPreviousByte = + + bool FitsCompletelyInPreviousByte = BitsInPreviousByte >= FieldValue.getBitWidth(); - + llvm::APInt Tmp = FieldValue; - + if (!FitsCompletelyInPreviousByte) { unsigned NewFieldWidth = FieldSize - BitsInPreviousByte; - + if (CGM.getTargetData().isBigEndian()) { Tmp = Tmp.lshr(NewFieldWidth); Tmp.trunc(BitsInPreviousByte); @@ -184,7 +184,7 @@ class VISIBILITY_HIDDEN ConstStructBuilder { FieldValue.trunc(NewFieldWidth); } } - + Tmp.zext(8); if (CGM.getTargetData().isBigEndian()) { if (FitsCompletelyInPreviousByte) @@ -196,14 +196,14 @@ class VISIBILITY_HIDDEN ConstStructBuilder { // Or in the bits that go into the previous byte. Tmp |= cast(Elements.back())->getValue(); Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp); - + if (FitsCompletelyInPreviousByte) return true; } - + while (FieldValue.getBitWidth() > 8) { llvm::APInt Tmp; - + if (CGM.getTargetData().isBigEndian()) { // We want the high bits. Tmp = FieldValue; @@ -213,13 +213,13 @@ class VISIBILITY_HIDDEN ConstStructBuilder { // We want the low bits. Tmp = FieldValue; Tmp.trunc(8); - + FieldValue = FieldValue.lshr(8); } - + Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp)); NextFieldOffsetInBytes++; - + FieldValue.trunc(FieldValue.getBitWidth() - 8); } @@ -231,10 +231,10 @@ class VISIBILITY_HIDDEN ConstStructBuilder { if (FieldValue.getBitWidth() < 8) { if (CGM.getTargetData().isBigEndian()) { unsigned BitWidth = FieldValue.getBitWidth(); - + FieldValue.zext(8); FieldValue = FieldValue << (8 - BitWidth); - } else + } else FieldValue.zext(8); } @@ -244,19 +244,19 @@ class VISIBILITY_HIDDEN ConstStructBuilder { NextFieldOffsetInBytes++; return true; } - + void AppendPadding(uint64_t NumBytes) { if (!NumBytes) return; const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext()); - if (NumBytes > 1) + if (NumBytes > 1) Ty = llvm::ArrayType::get(Ty, NumBytes); llvm::Constant *C = llvm::Constant::getNullValue(Ty); Elements.push_back(C); assert(getAlignment(C) == 1 && "Padding must have 1 byte alignment!"); - + NextFieldOffsetInBytes += getSizeInBytes(C); } @@ -265,19 +265,19 @@ class VISIBILITY_HIDDEN ConstStructBuilder { uint64_t RecordSizeInBytes = RecordSize / 8; assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!"); - + unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes; AppendPadding(NumPadBytes); } - + bool Build(InitListExpr *ILE) { RecordDecl *RD = ILE->getType()->getAs()->getDecl(); const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); - + unsigned FieldNo = 0; unsigned ElementNo = 0; - for (RecordDecl::field_iterator Field = RD->field_begin(), - FieldEnd = RD->field_end(); + for (RecordDecl::field_iterator Field = RD->field_begin(), + FieldEnd = RD->field_end(); ElementNo < ILE->getNumInits() && Field != FieldEnd; ++Field, ++FieldNo) { if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field) @@ -286,7 +286,7 @@ class VISIBILITY_HIDDEN ConstStructBuilder { if (Field->isBitField()) { if (!Field->getIdentifier()) continue; - + if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo), ILE->getInit(ElementNo))) return false; @@ -295,63 +295,63 @@ class VISIBILITY_HIDDEN ConstStructBuilder { ILE->getInit(ElementNo))) return false; } - + ElementNo++; } - + uint64_t LayoutSizeInBytes = Layout.getSize() / 8; - + if (NextFieldOffsetInBytes > LayoutSizeInBytes) { // If the struct is bigger than the size of the record type, // we must have a flexible array member at the end. assert(RD->hasFlexibleArrayMember() && "Must have flexible array member if struct is bigger than type!"); - + // No tail padding is necessary. return true; } - + // Append tail padding if necessary. AppendTailPadding(Layout.getSize()); - - assert(Layout.getSize() / 8 == NextFieldOffsetInBytes && + + assert(Layout.getSize() / 8 == NextFieldOffsetInBytes && "Tail padding mismatch!"); - + return true; } - + unsigned getAlignment(const llvm::Constant *C) const { if (Packed) return 1; - + return CGM.getTargetData().getABITypeAlignment(C->getType()); } - + uint64_t getSizeInBytes(const llvm::Constant *C) const { return CGM.getTargetData().getTypeAllocSize(C->getType()); } - + public: static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, InitListExpr *ILE) { ConstStructBuilder Builder(CGM, CGF); - + if (!Builder.Build(ILE)) return 0; - - llvm::Constant *Result = + + llvm::Constant *Result = llvm::ConstantStruct::get(CGM.getLLVMContext(), Builder.Elements, Builder.Packed); assert(llvm::RoundUpToAlignment(Builder.NextFieldOffsetInBytes, - Builder.getAlignment(Result)) == + Builder.getAlignment(Result)) == Builder.getSizeInBytes(Result) && "Size mismatch!"); return Result; } }; - -class VISIBILITY_HIDDEN ConstExprEmitter : + +class VISIBILITY_HIDDEN ConstExprEmitter : public StmtVisitor { CodeGenModule &CGM; CodeGenFunction *CGF; @@ -360,23 +360,23 @@ public: ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf) : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) { } - + //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// - + llvm::Constant *VisitStmt(Stmt *S) { return 0; } - - llvm::Constant *VisitParenExpr(ParenExpr *PE) { - return Visit(PE->getSubExpr()); + + llvm::Constant *VisitParenExpr(ParenExpr *PE) { + return Visit(PE->getSubExpr()); } - + llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return Visit(E->getInitializer()); } - + llvm::Constant *VisitCastExpr(CastExpr* E) { switch (E->getCastKind()) { case CastExpr::CK_ToUnion: { @@ -386,11 +386,11 @@ public: const llvm::Type *Ty = ConvertType(E->getType()); Expr *SubExpr = E->getSubExpr(); - llvm::Constant *C = + llvm::Constant *C = CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF); if (!C) return 0; - + // Build a struct with the union sub-element as the first member, // and padded to the appropriate size std::vector Elts; @@ -399,7 +399,7 @@ public: Types.push_back(C->getType()); unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType()); unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty); - + assert(CurSize <= TotalSize && "Union size mismatch!"); if (unsigned NumPadBytes = TotalSize - CurSize) { const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext); @@ -409,7 +409,7 @@ public: Elts.push_back(llvm::Constant::getNullValue(Ty)); Types.push_back(Ty); } - + llvm::StructType* STy = llvm::StructType::get(C->getType()->getContext(), Types, false); return llvm::ConstantStruct::get(STy, Elts); @@ -438,7 +438,7 @@ public: unsigned NumInitElements = ILE->getNumInits(); // FIXME: Check for wide strings // FIXME: Check for NumInitElements exactly equal to 1?? - if (NumInitElements > 0 && + if (NumInitElements > 0 && (isa(ILE->getInit(0)) || isa(ILE->getInit(0))) && ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType()) @@ -446,7 +446,7 @@ public: const llvm::Type *ElemTy = AType->getElementType(); unsigned NumElements = AType->getNumElements(); - // Initialising an array requires us to automatically + // Initialising an array requires us to automatically // initialise any elements that have not been initialised explicitly unsigned NumInitableElts = std::min(NumInitElements, NumElements); @@ -472,18 +472,18 @@ public: std::vector Types; for (unsigned i = 0; i < Elts.size(); ++i) Types.push_back(Elts[i]->getType()); - const llvm::StructType *SType = llvm::StructType::get(AType->getContext(), + const llvm::StructType *SType = llvm::StructType::get(AType->getContext(), Types, true); return llvm::ConstantStruct::get(SType, Elts); } - return llvm::ConstantArray::get(AType, Elts); + return llvm::ConstantArray::get(AType, Elts); } llvm::Constant *EmitStructInitialization(InitListExpr *ILE) { return ConstStructBuilder::BuildStruct(CGM, CGF, ILE); } - + llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) { return ConstStructBuilder::BuildStruct(CGM, CGF, ILE); } @@ -511,13 +511,13 @@ public: for (; i < NumElements; ++i) Elts.push_back(llvm::Constant::getNullValue(ElemTy)); - return llvm::ConstantVector::get(VType, Elts); + return llvm::ConstantVector::get(VType, Elts); } - + llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) { return CGM.EmitNullConstant(E->getType()); } - + llvm::Constant *VisitInitListExpr(InitListExpr *ILE) { if (ILE->getType()->isScalarType()) { // We have a scalar in braces. Just use the first element. @@ -527,7 +527,7 @@ public: } return CGM.EmitNullConstant(ILE->getType()); } - + if (ILE->getType()->isArrayType()) return EmitArrayInitialization(ILE); @@ -548,7 +548,7 @@ public: llvm::Constant *VisitStringLiteral(StringLiteral *E) { assert(!E->getType()->isPointerType() && "Strings are always arrays"); - + // This must be a string initializing an array in a static initializer. // Don't emit it as the address of the string, emit the string data itself // as an inline array. @@ -563,13 +563,13 @@ public: std::string Str; CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); const ConstantArrayType *CAT = cast(E->getType()); - + // Resize the string to the right size, adding zeros at the end, or // truncating as needed. Str.resize(CAT->getSize().getZExtValue(), '\0'); return llvm::ConstantArray::get(VMContext, Str, false); } - + llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) { return Visit(E->getSubExpr()); } @@ -597,14 +597,14 @@ public: E->getType().getAddressSpace()); return C; } - case Expr::DeclRefExprClass: + case Expr::DeclRefExprClass: case Expr::QualifiedDeclRefExprClass: { NamedDecl *Decl = cast(E)->getDecl(); if (const FunctionDecl *FD = dyn_cast(Decl)) return CGM.GetAddrOfFunction(GlobalDecl(FD)); if (const VarDecl* VD = dyn_cast(Decl)) { // We can never refer to a variable with local storage. - if (!VD->hasLocalStorage()) { + if (!VD->hasLocalStorage()) { if (VD->isFileVarDecl() || VD->hasExternalStorage()) return CGM.GetAddrOfGlobalVar(VD); else if (VD->isBlockVarDecl()) { @@ -627,10 +627,10 @@ public: case Expr::PredefinedExprClass: { // __func__/__FUNCTION__ -> "". __PRETTY_FUNCTION__ -> "top level". std::string Str; - if (cast(E)->getIdentType() == + if (cast(E)->getIdentType() == PredefinedExpr::PrettyFunction) Str = "top level"; - + return CGM.GetAddrOfConstantCString(Str, ".tmp"); } case Expr::AddrLabelExprClass: { @@ -643,7 +643,7 @@ public: } case Expr::CallExprClass: { CallExpr* CE = cast(E); - if (CE->isBuiltinCall(CGM.getContext()) != + if (CE->isBuiltinCall(CGM.getContext()) != Builtin::BI__builtin___CFStringMakeConstantString) break; const Expr *Arg = CE->getArg(0)->IgnoreParenCasts(); @@ -665,23 +665,23 @@ public: return 0; } }; - + } // end anonymous namespace. llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF) { Expr::EvalResult Result; - + bool Success = false; - + if (DestType->isReferenceType()) Success = E->EvaluateAsLValue(Result, Context); - else + else Success = E->Evaluate(Result, Context); - + if (Success) { - assert(!Result.HasSideEffects && + assert(!Result.HasSideEffects && "Constant expr should not have any side effects!"); switch (Result.Val.getKind()) { case APValue::Uninitialized: @@ -689,17 +689,17 @@ llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, return 0; case APValue::LValue: { const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType); - llvm::Constant *Offset = - llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), + llvm::Constant *Offset = + llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), Result.Val.getLValueOffset()); - + llvm::Constant *C; if (const Expr *LVBase = Result.Val.getLValueBase()) { C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast(LVBase)); // Apply offset if necessary. if (!Offset->isNullValue()) { - const llvm::Type *Type = + const llvm::Type *Type = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type); Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1); @@ -728,9 +728,9 @@ llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, } } case APValue::Int: { - llvm::Constant *C = llvm::ConstantInt::get(VMContext, + llvm::Constant *C = llvm::ConstantInt::get(VMContext, Result.Val.getInt()); - + if (C->getType() == llvm::Type::getInt1Ty(VMContext)) { const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); C = llvm::ConstantExpr::getZExt(C, BoolTy); @@ -739,30 +739,30 @@ llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, } case APValue::ComplexInt: { llvm::Constant *Complex[2]; - + Complex[0] = llvm::ConstantInt::get(VMContext, Result.Val.getComplexIntReal()); - Complex[1] = llvm::ConstantInt::get(VMContext, + Complex[1] = llvm::ConstantInt::get(VMContext, Result.Val.getComplexIntImag()); - + return llvm::ConstantStruct::get(VMContext, Complex, 2); } case APValue::Float: return llvm::ConstantFP::get(VMContext, Result.Val.getFloat()); case APValue::ComplexFloat: { llvm::Constant *Complex[2]; - - Complex[0] = llvm::ConstantFP::get(VMContext, + + Complex[0] = llvm::ConstantFP::get(VMContext, Result.Val.getComplexFloatReal()); Complex[1] = llvm::ConstantFP::get(VMContext, Result.Val.getComplexFloatImag()); - + return llvm::ConstantStruct::get(VMContext, Complex, 2); } case APValue::Vector: { llvm::SmallVector Inits; unsigned NumElts = Result.Val.getVectorLength(); - + for (unsigned i = 0; i != NumElts; ++i) { APValue &Elt = Result.Val.getVectorElt(i); if (Elt.isInt()) @@ -787,9 +787,9 @@ llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { // No need to check for member pointers when not compiling C++. if (!getContext().getLangOptions().CPlusPlus) return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); - + if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { - + QualType ElementTy = CAT->getElementType(); // FIXME: Handle arrays of structs that contain member pointers. @@ -799,8 +799,8 @@ llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { std::vector Array(NumElements); for (uint64_t i = 0; i != NumElements; ++i) Array[i] = Element; - - const llvm::ArrayType *ATy = + + const llvm::ArrayType *ATy = cast(getTypes().ConvertTypeForMem(T)); return llvm::ConstantArray::get(ATy, Array); } @@ -808,19 +808,19 @@ llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { if (const RecordType *RT = T->getAs()) { const RecordDecl *RD = RT->getDecl(); - // FIXME: It would be better if there was a way to explicitly compute the + // FIXME: It would be better if there was a way to explicitly compute the // record layout instead of converting to a type. Types.ConvertTagDeclType(RD); - + const CGRecordLayout &Layout = Types.getCGRecordLayout(RD); if (Layout.containsMemberPointer()) { assert(0 && "FIXME: No support for structs with member pointers yet!"); } } - + // FIXME: Handle structs that contain member pointers. - if (T->isMemberPointerType()) + if (T->isMemberPointerType()) return llvm::Constant::getAllOnesValue(getTypes().ConvertTypeForMem(T)); - + return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); } diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index 3dc95902af789023455ec7d3dafeee64aab25ab4..b4ce838af354fbf86a42f299f38da9afb708974c 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -889,8 +889,7 @@ Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { return llvm::Constant::getNullValue(ConvertType(E->getType())); } -Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) -{ +Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) { Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress(); const llvm::Type* ResultType = ConvertType(E->getType()); return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof"); diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp index 58999129813bb7ea83fa7d779c9e6e3d05aaada8..d437df484be62c4ba3ac44b1a51699bac3e38734 100644 --- a/clang/lib/CodeGen/CGObjC.cpp +++ b/clang/lib/CodeGen/CGObjC.cpp @@ -24,7 +24,7 @@ using namespace clang; using namespace CodeGen; /// Emits an instance of NSConstantString representing the object. -llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) +llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) { llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(E); // FIXME: This bitcast should just be made an invariant on the Runtime. @@ -50,7 +50,7 @@ RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) { // Only the lookup mechanism and first two arguments of the method // implementation vary between runtimes. We can get the receiver and // arguments in generic code. - + CGObjCRuntime &Runtime = CGM.getObjCRuntime(); const Expr *ReceiverExpr = E->getReceiver(); bool isSuperMessage = false; @@ -70,7 +70,7 @@ RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) { } else { Receiver = Runtime.GetClass(Builder, OID); } - + isClassMessage = true; } else if (isa(E->getReceiver())) { isSuperMessage = true; @@ -81,7 +81,7 @@ RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) { CallArgList Args; EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end()); - + if (isSuperMessage) { // super is only valid in an Objective-C method const ObjCMethodDecl *OMD = cast(CurFuncDecl); @@ -94,7 +94,7 @@ RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) { isClassMessage, Args); } - return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(), + return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(), Receiver, isClassMessage, Args, E->getMethodDecl()); } @@ -110,7 +110,7 @@ void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD); CGM.SetInternalFunctionAttributes(OMD, Fn, FI); - Args.push_back(std::make_pair(OMD->getSelfDecl(), + Args.push_back(std::make_pair(OMD->getSelfDecl(), OMD->getSelfDecl()->getType())); Args.push_back(std::make_pair(OMD->getCmdDecl(), OMD->getCmdDecl()->getType())); @@ -123,7 +123,7 @@ void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, } /// Generate an Objective-C method. An Objective-C method is a C function with -/// its pointer, name, and types registered in the class struture. +/// its pointer, name, and types registered in the class struture. void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { // Check if we should generate debug info for this method. if (CGM.getDebugInfo() && !OMD->hasAttr()) @@ -159,9 +159,9 @@ void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) && (PD->getSetterKind() == ObjCPropertyDecl::Copy || PD->getSetterKind() == ObjCPropertyDecl::Retain)) { - llvm::Value *GetPropertyFn = + llvm::Value *GetPropertyFn = CGM.getObjCRuntime().GetPropertyGetFunction(); - + if (!GetPropertyFn) { CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy"); FinishFunction(); @@ -175,7 +175,7 @@ void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, ValueDecl *Cmd = OMD->getCmdDecl(); llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd"); QualType IdTy = getContext().getObjCIdType(); - llvm::Value *SelfAsId = + llvm::Value *SelfAsId = Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar); llvm::Value *True = @@ -187,12 +187,12 @@ void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy)); // FIXME: We shouldn't need to get the function info here, the // runtime already should have computed it to build the function. - RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args), + RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args), GetPropertyFn, Args); // We need to fix the type here. Ivars with copy & retain are // always objects so we don't need to worry about complex or // aggregates. - RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), + RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), Types.ConvertType(PD->getType()))); EmitReturnOfRValue(RV, PD->getType()); } else { @@ -203,7 +203,7 @@ void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, CodeGenTypes &Types = CGM.getTypes(); RValue RV = EmitLoadOfLValue(LV, Ivar->getType()); RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), - Types.ConvertType(PD->getType()))); + Types.ConvertType(PD->getType()))); EmitReturnOfRValue(RV, PD->getType()); } } @@ -226,7 +226,7 @@ void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, StartObjCMethod(OMD, IMP->getClassInterface()); bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy; - bool IsAtomic = + bool IsAtomic = !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic); // Determine if we should use an objc_setProperty call for @@ -236,16 +236,16 @@ void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, if (IsCopy || (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly && PD->getSetterKind() == ObjCPropertyDecl::Retain)) { - llvm::Value *SetPropertyFn = + llvm::Value *SetPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction(); - + if (!SetPropertyFn) { CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy"); FinishFunction(); return; } - - // Emit objc_setProperty((id) self, _cmd, offset, arg, + + // Emit objc_setProperty((id) self, _cmd, offset, arg, // , ). // FIXME: Can't this be simpler? This might even be worse than the // corresponding gcc code. @@ -253,11 +253,11 @@ void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, ValueDecl *Cmd = OMD->getCmdDecl(); llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd"); QualType IdTy = getContext().getObjCIdType(); - llvm::Value *SelfAsId = + llvm::Value *SelfAsId = Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar); llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()]; - llvm::Value *ArgAsId = + llvm::Value *ArgAsId = Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"), Types.ConvertType(IdTy)); llvm::Value *True = @@ -269,13 +269,13 @@ void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType())); Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy)); Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy)); - Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False), + Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False), getContext().BoolTy)); - Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False), + Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False), getContext().BoolTy)); // FIXME: We shouldn't need to get the function info here, the runtime // already should have computed it to build the function. - EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args), + EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args), SetPropertyFn, Args); } else { SourceLocation Loc = PD->getLocation(); @@ -309,13 +309,13 @@ QualType CodeGenFunction::TypeOfSelfObject() { return PTy->getPointeeType(); } -RValue CodeGenFunction::EmitObjCSuperPropertyGet(const Expr *Exp, +RValue CodeGenFunction::EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S) { llvm::Value *Receiver = LoadObjCSelf(); const ObjCMethodDecl *OMD = cast(CurFuncDecl); bool isClassMessage = OMD->isClassMethod(); bool isCategoryImpl = isa(OMD->getDeclContext()); - return CGM.getObjCRuntime().GenerateMessageSendSuper(*this, + return CGM.getObjCRuntime().GenerateMessageSendSuper(*this, Exp->getType(), S, OMD->getClassInterface(), @@ -323,7 +323,7 @@ RValue CodeGenFunction::EmitObjCSuperPropertyGet(const Expr *Exp, Receiver, isClassMessage, CallArgList()); - + } RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) { @@ -334,11 +334,11 @@ RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) { if (isa(E->getBase())) return EmitObjCSuperPropertyGet(E, S); return CGM.getObjCRuntime(). - GenerateMessageSend(*this, Exp->getType(), S, - EmitScalarExpr(E->getBase()), + GenerateMessageSend(*this, Exp->getType(), S, + EmitScalarExpr(E->getBase()), false, CallArgList()); } else { - const ObjCImplicitSetterGetterRefExpr *KE = + const ObjCImplicitSetterGetterRefExpr *KE = cast(Exp); Selector S = KE->getGetterMethod()->getSelector(); llvm::Value *Receiver; @@ -347,11 +347,11 @@ RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) { Receiver = CGM.getObjCRuntime().GetClass(Builder, OID); } else if (isa(KE->getBase())) return EmitObjCSuperPropertyGet(KE, S); - else + else Receiver = EmitScalarExpr(KE->getBase()); return CGM.getObjCRuntime(). - GenerateMessageSend(*this, Exp->getType(), S, - Receiver, + GenerateMessageSend(*this, Exp->getType(), S, + Receiver, KE->getInterfaceDecl() != 0, CallArgList()); } } @@ -365,7 +365,7 @@ void CodeGenFunction::EmitObjCSuperPropertySet(const Expr *Exp, bool isClassMessage = OMD->isClassMethod(); bool isCategoryImpl = isa(OMD->getDeclContext()); Args.push_back(std::make_pair(Src, Exp->getType())); - CGM.getObjCRuntime().GenerateMessageSendSuper(*this, + CGM.getObjCRuntime().GenerateMessageSendSuper(*this, Exp->getType(), S, OMD->getClassInterface(), @@ -384,13 +384,13 @@ void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp, if (isa(E->getBase())) { EmitObjCSuperPropertySet(E, S, Src); return; - } + } CallArgList Args; Args.push_back(std::make_pair(Src, E->getType())); - CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S, - EmitScalarExpr(E->getBase()), + CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S, + EmitScalarExpr(E->getBase()), false, Args); - } else if (const ObjCImplicitSetterGetterRefExpr *E = + } else if (const ObjCImplicitSetterGetterRefExpr *E = dyn_cast(Exp)) { Selector S = E->getSetterMethod()->getSelector(); CallArgList Args; @@ -404,19 +404,19 @@ void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp, } else Receiver = EmitScalarExpr(E->getBase()); Args.push_back(std::make_pair(Src, E->getType())); - CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S, - Receiver, + CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S, + Receiver, E->getInterfaceDecl() != 0, Args); } else assert (0 && "bad expression node in EmitObjCPropertySet"); } void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ - llvm::Constant *EnumerationMutationFn = + llvm::Constant *EnumerationMutationFn = CGM.getObjCRuntime().EnumerationMutationFunction(); llvm::Value *DeclAddress; QualType ElementTy; - + if (!EnumerationMutationFn) { CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); return; @@ -427,62 +427,62 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ assert(HaveInsertPoint() && "DeclStmt destroyed insert point!"); const Decl* D = SD->getSingleDecl(); ElementTy = cast(D)->getType(); - DeclAddress = LocalDeclMap[D]; + DeclAddress = LocalDeclMap[D]; } else { ElementTy = cast(S.getElement())->getType(); DeclAddress = 0; } - + // Fast enumeration state. QualType StateTy = getContext().getObjCFastEnumerationStateType(); - llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy), + llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy), "state.ptr"); - StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3); + StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3); EmitMemSetToZero(StatePtr, StateTy); - + // Number of elements in the items array. static const unsigned NumItems = 16; - + // Get selector llvm::SmallVector II; II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState")); II.push_back(&CGM.getContext().Idents.get("objects")); II.push_back(&CGM.getContext().Idents.get("count")); - Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(), + Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(), &II[0]); QualType ItemsTy = getContext().getConstantArrayType(getContext().getObjCIdType(), - llvm::APInt(32, NumItems), + llvm::APInt(32, NumItems), ArrayType::Normal, 0); llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr"); - + llvm::Value *Collection = EmitScalarExpr(S.getCollection()); - + CallArgList Args; - Args.push_back(std::make_pair(RValue::get(StatePtr), + Args.push_back(std::make_pair(RValue::get(StatePtr), getContext().getPointerType(StateTy))); - - Args.push_back(std::make_pair(RValue::get(ItemsPtr), + + Args.push_back(std::make_pair(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy))); - + const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); - Args.push_back(std::make_pair(RValue::get(Count), + Args.push_back(std::make_pair(RValue::get(Count), getContext().UnsignedLongTy)); - - RValue CountRV = - CGM.getObjCRuntime().GenerateMessageSend(*this, + + RValue CountRV = + CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().UnsignedLongTy, FastEnumSel, Collection, false, Args); llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr"); Builder.CreateStore(CountRV.getScalarVal(), LimitPtr); - + llvm::BasicBlock *NoElements = createBasicBlock("noelements"); llvm::BasicBlock *SetStartMutations = createBasicBlock("setstartmutations"); - + llvm::Value *Limit = Builder.CreateLoad(LimitPtr); llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy); @@ -490,60 +490,60 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ Builder.CreateCondBr(IsZero, NoElements, SetStartMutations); EmitBlock(SetStartMutations); - - llvm::Value *StartMutationsPtr = + + llvm::Value *StartMutationsPtr = CreateTempAlloca(UnsignedLongLTy); - - llvm::Value *StateMutationsPtrPtr = + + llvm::Value *StateMutationsPtrPtr = Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); - llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, + llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); - - llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr, + + llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr, "mutations"); - + Builder.CreateStore(StateMutations, StartMutationsPtr); - + llvm::BasicBlock *LoopStart = createBasicBlock("loopstart"); EmitBlock(LoopStart); llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr"); Builder.CreateStore(Zero, CounterPtr); - - llvm::BasicBlock *LoopBody = createBasicBlock("loopbody"); + + llvm::BasicBlock *LoopBody = createBasicBlock("loopbody"); EmitBlock(LoopBody); StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations"); - llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr, + llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr, "mutations"); - llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations, + llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations, StartMutations, "tobool"); - - + + llvm::BasicBlock *WasMutated = createBasicBlock("wasmutated"); llvm::BasicBlock *WasNotMutated = createBasicBlock("wasnotmutated"); - + Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated); - + EmitBlock(WasMutated); llvm::Value *V = - Builder.CreateBitCast(Collection, + Builder.CreateBitCast(Collection, ConvertType(getContext().getObjCIdType()), "tmp"); CallArgList Args2; - Args2.push_back(std::make_pair(RValue::get(V), + Args2.push_back(std::make_pair(RValue::get(V), getContext().getObjCIdType())); // FIXME: We shouldn't need to get the function info here, the runtime already // should have computed it to build the function. - EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2), + EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2), EnumerationMutationFn, Args2); - + EmitBlock(WasNotMutated); - - llvm::Value *StateItemsPtr = + + llvm::Value *StateItemsPtr = Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter"); @@ -551,39 +551,39 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr, "stateitems"); - llvm::Value *CurrentItemPtr = + llvm::Value *CurrentItemPtr = Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr"); - + llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem"); - + // Cast the item to the right type. CurrentItem = Builder.CreateBitCast(CurrentItem, ConvertType(ElementTy), "tmp"); - + if (!DeclAddress) { LValue LV = EmitLValue(cast(S.getElement())); - + // Set the value to null. Builder.CreateStore(CurrentItem, LV.getAddress()); } else Builder.CreateStore(CurrentItem, DeclAddress); - + // Increment the counter. - Counter = Builder.CreateAdd(Counter, + Counter = Builder.CreateAdd(Counter, llvm::ConstantInt::get(UnsignedLongLTy, 1)); Builder.CreateStore(Counter, CounterPtr); - + llvm::BasicBlock *LoopEnd = createBasicBlock("loopend"); llvm::BasicBlock *AfterBody = createBasicBlock("afterbody"); - + BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); EmitStmt(S.getBody()); - + BreakContinueStack.pop_back(); - + EmitBlock(AfterBody); - + llvm::BasicBlock *FetchMore = createBasicBlock("fetchmore"); Counter = Builder.CreateLoad(CounterPtr); @@ -593,18 +593,18 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ // Fetch more elements. EmitBlock(FetchMore); - - CountRV = - CGM.getObjCRuntime().GenerateMessageSend(*this, + + CountRV = + CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().UnsignedLongTy, - FastEnumSel, + FastEnumSel, Collection, false, Args); Builder.CreateStore(CountRV.getScalarVal(), LimitPtr); Limit = Builder.CreateLoad(LimitPtr); - + IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero"); Builder.CreateCondBr(IsZero, NoElements, LoopStart); - + // No more elements. EmitBlock(NoElements); @@ -612,7 +612,7 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ // If the element was not a declaration, set it to be null. LValue LV = EmitLValue(cast(S.getElement())); - + // Set the value to null. Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)), LV.getAddress()); @@ -621,19 +621,16 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ EmitBlock(LoopEnd); } -void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) -{ +void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S); } -void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) -{ +void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { CGM.getObjCRuntime().EmitThrowStmt(*this, S); } void CodeGenFunction::EmitObjCAtSynchronizedStmt( - const ObjCAtSynchronizedStmt &S) -{ + const ObjCAtSynchronizedStmt &S) { CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S); } diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp index 63d45e9bd7b2b9a33c60aea48bc6eb3ecde20b49..264e9d0215bf79ae954ddd80eb6301c8a4233187 100644 --- a/clang/lib/CodeGen/CGObjCGNU.cpp +++ b/clang/lib/CodeGen/CGObjCGNU.cpp @@ -79,8 +79,8 @@ private: const llvm::SmallVectorImpl &IvarOffsets); llvm::Constant *GenerateMethodList(const std::string &ClassName, const std::string &CategoryName, - const llvm::SmallVectorImpl &MethodSels, - const llvm::SmallVectorImpl &MethodTypes, + const llvm::SmallVectorImpl &MethodSels, + const llvm::SmallVectorImpl &MethodTypes, bool isClassMethodList); llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName); llvm::Constant *GenerateProtocolList( @@ -110,7 +110,7 @@ private: public: CGObjCGNU(CodeGen::CodeGenModule &cgm); virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *); - virtual CodeGen::RValue + virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, @@ -118,7 +118,7 @@ public: bool IsClassMessage, const CallArgList &CallArgs, const ObjCMethodDecl *Method); - virtual CodeGen::RValue + virtual CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, @@ -132,8 +132,8 @@ public: virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl *Method); - - virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, + + virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD); virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); @@ -144,7 +144,7 @@ public: virtual llvm::Function *GetPropertyGetFunction(); virtual llvm::Function *GetPropertySetFunction(); virtual llvm::Constant *EnumerationMutationFunction(); - + virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S); virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, @@ -160,7 +160,7 @@ public: virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, - llvm::Value *DestPtr, + llvm::Value *DestPtr, llvm::Value *SrcPtr, QualType Ty); virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, @@ -197,9 +197,10 @@ static std::string SymbolNameForClass(const std::string &ClassName) { return "_OBJC_CLASS_" + ClassName; } -static std::string SymbolNameForMethod(const std::string &ClassName, const - std::string &CategoryName, const std::string &MethodName, bool isClassMethod) -{ +static std::string SymbolNameForMethod(const std::string &ClassName, + const std::string &CategoryName, + const std::string &MethodName, + bool isClassMethod) { return "_OBJC_METHOD_" + ClassName + "("+CategoryName+")"+ (isClassMethod ? "+" : "-") + MethodName; } @@ -211,13 +212,13 @@ CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm) CGM.getTypes().ConvertType(CGM.getContext().IntTy)); LongTy = cast( CGM.getTypes().ConvertType(CGM.getContext().LongTy)); - + Zeros[0] = llvm::ConstantInt::get(LongTy, 0); Zeros[1] = Zeros[0]; NULLPtr = llvm::ConstantPointerNull::get( llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext))); // C string type. Used in lots of places. - PtrToInt8Ty = + PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); // Get the selector Type. SelectorTy = cast( @@ -225,11 +226,11 @@ CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm) PtrToIntTy = llvm::PointerType::getUnqual(IntTy); PtrTy = PtrToInt8Ty; - + // Object type ASTIdTy = CGM.getContext().getObjCIdType(); IdTy = cast(CGM.getTypes().ConvertType(ASTIdTy)); - + // IMP type std::vector IMPArgs; IMPArgs.push_back(IdTy); @@ -261,7 +262,7 @@ llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) { llvm::GlobalValue::PrivateLinkage, ".objc_untyped_selector_alias"+Sel.getAsString(), NULL, &TheModule); - + return Builder.CreateLoad(US); } @@ -315,7 +316,7 @@ llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty, //an OpenStep implementation, this should let them select their own class for //constant strings. llvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) { - std::string Str(SL->getString()->getStrData(), + std::string Str(SL->getString()->getStrData(), SL->getString()->getByteLength()); std::vector Ivars; Ivars.push_back(NULLPtr); @@ -393,7 +394,7 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, } } // Cast the pointer to a simplified version of the class structure - ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass, + ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass, llvm::PointerType::getUnqual( llvm::StructType::get(VMContext, IdTy, IdTy, NULL))); // Get the superclass pointer @@ -413,7 +414,7 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, std::vector Params; Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy)); Params.push_back(SelectorTy); - llvm::Constant *lookupFunction = + llvm::Constant *lookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( llvm::PointerType::getUnqual(impType), Params, true), "objc_msg_lookup_super"); @@ -425,7 +426,7 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, return CGF.EmitCall(FnInfo, imp, ActualArgs); } -/// Generate code for a message send expression. +/// Generate code for a message send expression. CodeGen::RValue CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, @@ -468,14 +469,14 @@ CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, self = llvm::ConstantPointerNull::get(IdTy); } Params.push_back(self->getType()); - llvm::Constant *lookupFunction = + llvm::Constant *lookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( llvm::PointerType::getUnqual(impType), Params, true), "objc_msg_lookup_sender"); imp = CGF.Builder.CreateCall3(lookupFunction, Receiver, cmd, self); } else { - llvm::Constant *lookupFunction = + llvm::Constant *lookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( llvm::PointerType::getUnqual(impType), Params, true), "objc_msg_lookup"); @@ -486,16 +487,16 @@ CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, return CGF.EmitCall(FnInfo, imp, ActualArgs); } -/// Generates a MethodList. Used in construction of a objc_class and +/// Generates a MethodList. Used in construction of a objc_class and /// objc_category structures. llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName, - const std::string &CategoryName, - const llvm::SmallVectorImpl &MethodSels, - const llvm::SmallVectorImpl &MethodTypes, + const std::string &CategoryName, + const llvm::SmallVectorImpl &MethodSels, + const llvm::SmallVectorImpl &MethodTypes, bool isClassMethodList) { if (MethodSels.empty()) return NULLPtr; - // Get the method structure type. + // Get the method structure type. llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext, PtrToInt8Ty, // Really a selector, but the runtime creates it us. PtrToInt8Ty, // Method types @@ -530,8 +531,8 @@ llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName, llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext); llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy); llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext, - NextPtrTy, - IntTy, + NextPtrTy, + IntTy, ObjCMethodArrayTy, NULL); // Refine next pointer type to concrete type @@ -545,7 +546,7 @@ llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName, Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), MethodTypes.size())); Methods.push_back(MethodArray); - + // Create an instance of the structure return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list"); } @@ -555,7 +556,7 @@ llvm::Constant *CGObjCGNU::GenerateIvarList( const llvm::SmallVectorImpl &IvarNames, const llvm::SmallVectorImpl &IvarTypes, const llvm::SmallVectorImpl &IvarOffsets) { - // Get the method structure type. + // Get the method structure type. llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, @@ -575,7 +576,7 @@ llvm::Constant *CGObjCGNU::GenerateIvarList( llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy, IvarNames.size()); - + Elements.clear(); Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size())); Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)); @@ -611,7 +612,7 @@ llvm::Constant *CGObjCGNU::GenerateClassStructure( LongTy, // instance_size IVars->getType(), // ivars Methods->getType(), // methods - // These are all filled in by the runtime, so we pretend + // These are all filled in by the runtime, so we pretend PtrTy, // dtable PtrTy, // subclass_list PtrTy, // sibling_class @@ -643,7 +644,7 @@ llvm::Constant *CGObjCGNU::GenerateClassStructure( llvm::Constant *CGObjCGNU::GenerateProtocolMethodList( const llvm::SmallVectorImpl &MethodNames, const llvm::SmallVectorImpl &MethodTypes) { - // Get the method structure type. + // Get the method structure type. llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext, PtrToInt8Ty, // Really a selector, but the runtime does the casting for us. PtrToInt8Ty, @@ -652,7 +653,7 @@ llvm::Constant *CGObjCGNU::GenerateProtocolMethodList( std::vector Elements; for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) { Elements.clear(); - Elements.push_back(MethodNames[i]); + Elements.push_back(MethodNames[i]); Elements.push_back(MethodTypes[i]); Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements)); } @@ -678,7 +679,7 @@ llvm::Constant *CGObjCGNU::GenerateProtocolList( LongTy,//FIXME: Should be size_t ProtocolArrayTy, NULL); - std::vector Elements; + std::vector Elements; for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); iter != endIter ; iter++) { llvm::Constant *protocol = ExistingProtocols[*iter]; @@ -697,10 +698,10 @@ llvm::Constant *CGObjCGNU::GenerateProtocolList( return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list"); } -llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder, +llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder, const ObjCProtocolDecl *PD) { llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()]; - const llvm::Type *T = + const llvm::Type *T = CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); } @@ -723,7 +724,7 @@ llvm::Constant *CGObjCGNU::GenerateEmptyProtocol( InstanceMethodList->getType(), ClassMethodList->getType(), NULL); - std::vector Elements; + std::vector Elements; // The isa pointer must be set to a magic number so the runtime knows it's // the correct layout. Elements.push_back(llvm::ConstantExpr::getIntToPtr( @@ -755,7 +756,7 @@ void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { // Collect information about class methods: llvm::SmallVector ClassMethodNames; llvm::SmallVector ClassMethodTypes; - for (ObjCProtocolDecl::classmeth_iterator + for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(), endIter = PD->classmeth_end(); iter != endIter ; iter++) { std::string TypeStr; @@ -778,7 +779,7 @@ void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { InstanceMethodList->getType(), ClassMethodList->getType(), NULL); - std::vector Elements; + std::vector Elements; // The isa pointer must be set to a magic number so the runtime knows it's // the correct layout. Elements.push_back(llvm::ConstantExpr::getIntToPtr( @@ -787,7 +788,7 @@ void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { Elements.push_back(ProtocolList); Elements.push_back(InstanceMethodList); Elements.push_back(ClassMethodList); - ExistingProtocols[ProtocolName] = + ExistingProtocols[ProtocolName] = llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements, ".objc_protocol"), IdTy); } @@ -810,7 +811,7 @@ void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { // Collect information about class methods llvm::SmallVector ClassMethodSels; llvm::SmallVector ClassMethodTypes; - for (ObjCCategoryImplDecl::classmeth_iterator + for (ObjCCategoryImplDecl::classmeth_iterator iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end(); iter != endIter ; iter++) { ClassMethodSels.push_back((*iter)->getSelector()); @@ -830,7 +831,7 @@ void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { std::vector Elements; Elements.push_back(MakeConstantString(CategoryName)); Elements.push_back(MakeConstantString(ClassName)); - // Instance method list + // Instance method list Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes, false), PtrTy)); @@ -842,7 +843,7 @@ void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { Elements.push_back(llvm::ConstantExpr::getBitCast( GenerateProtocolList(Protocols), PtrTy)); Categories.push_back(llvm::ConstantExpr::getBitCast( - MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, + MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy)); } @@ -850,7 +851,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { ASTContext &Context = CGM.getContext(); // Get the superclass name. - const ObjCInterfaceDecl * SuperClassDecl = + const ObjCInterfaceDecl * SuperClassDecl = OID->getClassInterface()->getSuperClass(); std::string SuperClassName; if (SuperClassDecl) { @@ -865,7 +866,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { // Emit the symbol that is used to generate linker errors if this class is // referenced in other modules but not declared. std::string classSymbolName = "__objc_class_name_" + ClassName; - if (llvm::GlobalVariable *symbol = + if (llvm::GlobalVariable *symbol = TheModule.getGlobalVariable(classSymbolName)) { symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0)); } else { @@ -873,7 +874,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0), classSymbolName); } - + // Get the size of instances. int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8; @@ -881,8 +882,8 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { llvm::SmallVector IvarNames; llvm::SmallVector IvarTypes; llvm::SmallVector IvarOffsets; - - int superInstanceSize = !SuperClassDecl ? 0 : + + int superInstanceSize = !SuperClassDecl ? 0 : Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8; // For non-fragile ivars, set the instance size to 0 - {the size of just this // class}. The runtime will then set this to the correct value on load. @@ -912,7 +913,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { // Collect information about instance methods llvm::SmallVector InstanceMethodSels; llvm::SmallVector InstanceMethodTypes; - for (ObjCImplementationDecl::instmeth_iterator + for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(), endIter = OID->instmeth_end(); iter != endIter ; iter++) { InstanceMethodSels.push_back((*iter)->getSelector()); @@ -920,7 +921,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { Context.getObjCEncodingForMethodDecl((*iter),TypeStr); InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); } - for (ObjCImplDecl::propimpl_iterator + for (ObjCImplDecl::propimpl_iterator iter = OID->propimpl_begin(), endIter = OID->propimpl_end(); iter != endIter ; iter++) { ObjCPropertyDecl *property = (*iter)->getPropertyDecl(); @@ -974,7 +975,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { ClassMethodSels, ClassMethodTypes, true); llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, IvarOffsets); - // Irrespective of whether we are compiling for a fragile or non-fragile ABI, + // Irrespective of whether we are compiling for a fragile or non-fragile ABI, // we emit a symbol containing the offset for each ivar in the class. This // allows code compiled for the non-Fragile ABI to inherit from code compiled // for the legacy ABI, without causing problems. The converse is also @@ -986,7 +987,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { // the offset (third field in ivar structure) const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext); llvm::Constant *offsetPointerIndexes[] = {Zeros[0], - llvm::ConstantInt::get(IndexTy, 1), 0, + llvm::ConstantInt::get(IndexTy, 1), 0, llvm::ConstantInt::get(IndexTy, 2) }; for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(), @@ -1041,7 +1042,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { } -llvm::Function *CGObjCGNU::ModuleInitFunction() { +llvm::Function *CGObjCGNU::ModuleInitFunction() { // Only emit an ObjC load function if no Objective-C stuff has been called if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && ExistingProtocols.empty() && TypedSelectors.empty() && @@ -1078,12 +1079,12 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { ".objc_static_class_name")); Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, ConstantStrings)); - llvm::StructType *StaticsListTy = + llvm::StructType *StaticsListTy = llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL); llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy); Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics"); - llvm::ArrayType *StaticsListArrayTy = + llvm::ArrayType *StaticsListArrayTy = llvm::ArrayType::get(StaticsListPtrTy, 2); Elements.clear(); Elements.push_back(Statics); @@ -1094,7 +1095,7 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { // Array of classes, categories, and constant objects llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty, Classes.size() + Categories.size() + 2); - llvm::StructType *SymTabTy = llvm::StructType::get(VMContext, + llvm::StructType *SymTabTy = llvm::StructType::get(VMContext, LongTy, SelStructPtrTy, llvm::Type::getInt16Ty(VMContext), llvm::Type::getInt16Ty(VMContext), @@ -1130,7 +1131,7 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { llvm::Constant *SelectorList = MakeGlobal( llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors, ".objc_selector_list"); - Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, + Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, SelStructPtrTy)); // Now that all of the static selectors exist, create pointers to them. @@ -1158,7 +1159,7 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { llvm::Constant *Idxs[] = {Zeros[0], llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]}; llvm::Constant *SelPtr = new llvm::GlobalVariable - (TheModule, SelStructPtrTy, + (TheModule, SelStructPtrTy, true, llvm::GlobalValue::InternalLinkage, llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), ".objc_sel_ptr"); @@ -1171,10 +1172,10 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { (*iter).second->setAliasee(SelPtr); } // Number of classes defined. - Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), + Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), Classes.size())); // Number of categories defined - Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), + Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), Categories.size())); // Create an array of classes, then categories, then static object instances Classes.insert(Classes.end(), Categories.begin(), Categories.end()); @@ -1183,7 +1184,7 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { Classes.push_back(NULLPtr); llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes); Elements.push_back(ClassList); - // Construct the symbol table + // Construct the symbol table llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements); // The symbol table is contained in a module which has some version-checking @@ -1193,8 +1194,8 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { Elements.clear(); // Runtime version used for compatibility checking. if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { - Elements.push_back(llvm::ConstantInt::get(LongTy, - NonFragileRuntimeVersion)); + Elements.push_back(llvm::ConstantInt::get(LongTy, + NonFragileRuntimeVersion)); } else { Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion)); } @@ -1229,8 +1230,8 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() { } llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, - const ObjCContainerDecl *CD) { - const ObjCCategoryImplDecl *OCD = + const ObjCContainerDecl *CD) { + const ObjCCategoryImplDecl *OCD = dyn_cast(OMD->getDeclContext()); std::string CategoryName = OCD ? OCD->getNameAsString() : ""; std::string ClassName = OMD->getClassInterface()->getNameAsString(); @@ -1238,50 +1239,51 @@ llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, bool isClassMethod = !OMD->isInstanceMethod(); CodeGenTypes &Types = CGM.getTypes(); - const llvm::FunctionType *MethodTy = + const llvm::FunctionType *MethodTy = Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName, MethodName, isClassMethod); - llvm::Function *Method = llvm::Function::Create(MethodTy, - llvm::GlobalValue::InternalLinkage, - FunctionName, - &TheModule); + llvm::Function *Method + = llvm::Function::Create(MethodTy, + llvm::GlobalValue::InternalLinkage, + FunctionName, + &TheModule); return Method; } llvm::Function *CGObjCGNU::GetPropertyGetFunction() { - std::vector Params; - const llvm::Type *BoolTy = - CGM.getTypes().ConvertType(CGM.getContext().BoolTy); - Params.push_back(IdTy); - Params.push_back(SelectorTy); - // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 - Params.push_back(LongTy); - Params.push_back(BoolTy); - // void objc_getProperty (id, SEL, ptrdiff_t, bool) - const llvm::FunctionType *FTy = - llvm::FunctionType::get(IdTy, Params, false); - return cast(CGM.CreateRuntimeFunction(FTy, - "objc_getProperty")); + std::vector Params; + const llvm::Type *BoolTy = + CGM.getTypes().ConvertType(CGM.getContext().BoolTy); + Params.push_back(IdTy); + Params.push_back(SelectorTy); + // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 + Params.push_back(LongTy); + Params.push_back(BoolTy); + // void objc_getProperty (id, SEL, ptrdiff_t, bool) + const llvm::FunctionType *FTy = + llvm::FunctionType::get(IdTy, Params, false); + return cast(CGM.CreateRuntimeFunction(FTy, + "objc_getProperty")); } llvm::Function *CGObjCGNU::GetPropertySetFunction() { - std::vector Params; - const llvm::Type *BoolTy = - CGM.getTypes().ConvertType(CGM.getContext().BoolTy); - Params.push_back(IdTy); - Params.push_back(SelectorTy); - // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 - Params.push_back(LongTy); - Params.push_back(IdTy); - Params.push_back(BoolTy); - Params.push_back(BoolTy); - // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) - const llvm::FunctionType *FTy = - llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); - return cast(CGM.CreateRuntimeFunction(FTy, - "objc_setProperty")); + std::vector Params; + const llvm::Type *BoolTy = + CGM.getTypes().ConvertType(CGM.getContext().BoolTy); + Params.push_back(IdTy); + Params.push_back(SelectorTy); + // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 + Params.push_back(LongTy); + Params.push_back(IdTy); + Params.push_back(BoolTy); + Params.push_back(BoolTy); + // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) + const llvm::FunctionType *FTy = + llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); + return cast(CGM.CreateRuntimeFunction(FTy, + "objc_setProperty")); } llvm::Constant *CGObjCGNU::EnumerationMutationFunction() { @@ -1324,7 +1326,7 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); - llvm::Value *SyncArg = + llvm::Value *SyncArg = CGF.EmitScalarExpr(cast(S).getSynchExpr()); SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); CGF.Builder.CreateCall(SyncEnter, SyncArg); @@ -1339,7 +1341,7 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, CGF.setInvokeDest(TryHandler); CGF.EmitBlock(TryBlock); - CGF.EmitStmt(isTry ? cast(S).getTryBody() + CGF.EmitStmt(isTry ? cast(S).getTryBody() : cast(S).getSynchBody()); // Jump to @finally if there is no exception @@ -1353,7 +1355,7 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, int PointerWidth = td.getTypeSizeInBits(PtrTy); assert((PointerWidth == 32 || PointerWidth == 64) && "Can't yet handle exceptions if pointers are not 32 or 64 bits"); - llvm::Value *llvm_eh_exception = + llvm::Value *llvm_eh_exception = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception); llvm::Value *llvm_eh_selector = PointerWidth == 32 ? CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32) : @@ -1392,13 +1394,13 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, HasCatchAll = true; // No further catches after this one will ever by reached break; - } + } // All other types should be Objective-C interface pointer types. - const ObjCObjectPointerType *OPT = + const ObjCObjectPointerType *OPT = CatchDecl->getType()->getAsObjCObjectPointerType(); assert(OPT && "Invalid @catch type."); - const ObjCInterfaceType *IT = + const ObjCInterfaceType *IT = OPT->getPointeeType()->getAsObjCInterfaceType(); assert(IT && "Invalid @catch type."); llvm::Value *EHType = @@ -1439,11 +1441,11 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, CGF.EmitBlock(Match); } - + if (CatchBody) { llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc, CGF.ConvertType(CatchParam->getType())); - + // Bind the catch parameter if it exists. if (CatchParam) { // CatchParam is a ParmVarDecl because of the grammar @@ -1491,7 +1493,7 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, if (isTry) { - if (const ObjCAtFinallyStmt* FinallyStmt = + if (const ObjCAtFinallyStmt* FinallyStmt = cast(S).getFinallyStmt()) CGF.EmitStmt(FinallyStmt->getFinallyBody()); } else { @@ -1501,7 +1503,7 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); - llvm::Value *SyncArg = + llvm::Value *SyncArg = CGF.EmitScalarExpr(cast(S).getSynchExpr()); SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); CGF.Builder.CreateCall(SyncExit, SyncArg); @@ -1518,7 +1520,7 @@ void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, CGF.EmitBlock(FinallyRethrow); CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr)); CGF.Builder.CreateUnreachable(); - + CGF.EmitBlock(FinallyEnd); } @@ -1530,20 +1532,20 @@ void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, std::vector Args(1, IdTy); llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); - llvm::Value *ThrowFn = + llvm::Value *ThrowFn = CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); - + if (const Expr *ThrowExpr = S.getThrowExpr()) { llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); ExceptionAsObject = Exception; } else { - assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && + assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && "Unexpected rethrow outside @catch block."); ExceptionAsObject = CGF.ObjCEHValueStack.back(); } ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp"); - + // Note: This may have to be an invoke, if we want to support constructs like: // @try { // @throw(obj); @@ -1566,37 +1568,32 @@ void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, } llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, - llvm::Value *AddrWeakObj) -{ + llvm::Value *AddrWeakObj) { return 0; } void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { return; } void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { return; } void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { return; } void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { return; } void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, - llvm::Value *DestPtr, + llvm::Value *DestPtr, llvm::Value *SrcPtr, QualType Ty) { return; @@ -1618,7 +1615,7 @@ llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( // Don't emit the guess in non-PIC code because the linker will not be able // to replace it with the real version for a library. In non-PIC code you // must compile with the fragile ABI if you want to use ivars from a - // GCC-compiled class. + // GCC-compiled class. if (CGM.getLangOptions().PICLevel) { llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule, llvm::Type::getInt32Ty(VMContext), false, @@ -1654,11 +1651,11 @@ static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, if (OIVD == Ivars[k]) return OID; } - + // Otherwise check in the super class. if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) return FindIvarInterface(Context, Super, OIVD); - + return 0; } diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp index 03c4f47a8cc9401fc3c3c398c8cd2b3a188f19fd..e6853854263d3f883a0290f7be5003fa03cc2e72 100644 --- a/clang/lib/CodeGen/CGObjCMac.cpp +++ b/clang/lib/CodeGen/CGObjCMac.cpp @@ -104,7 +104,7 @@ LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, unsigned CVRQualifiers, llvm::Value *Offset) { // Compute (type*) ( (char *) BaseValue + Offset) - llvm::Type *I8Ptr = + llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(CGF.getLLVMContext())); QualType IvarTy = Ivar->getType(); const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy); @@ -939,8 +939,7 @@ protected: public: CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : - CGM(cgm), VMContext(cgm.getLLVMContext()) - { } + CGM(cgm), VMContext(cgm.getLLVMContext()) { } virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL); @@ -1402,8 +1401,7 @@ static bool hasObjCExceptionAttribute(ASTContext &Context, /* *** CGObjCMac Public Interface *** */ CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), - ObjCTypes(cgm) -{ + ObjCTypes(cgm) { ObjCABI = 1; EmitImageInfo(); } @@ -2689,8 +2687,7 @@ void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, /// object: objc_read_weak (id *src) /// llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, - llvm::Value *AddrWeakObj) -{ + llvm::Value *AddrWeakObj) { const llvm::Type* DestTy = cast(AddrWeakObj->getType())->getElementType(); AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, @@ -2705,8 +2702,7 @@ llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, /// objc_assign_weak (id src, id *dst) /// void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -2726,8 +2722,7 @@ void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, /// objc_assign_global (id src, id *dst) /// void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -2747,8 +2742,7 @@ void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, /// objc_assign_ivar (id src, id *dst) /// void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -2768,8 +2762,7 @@ void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, /// objc_assign_strongCast (id src, id *dst) /// void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -3055,10 +3048,10 @@ void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI, if (RD) { if (Field->isBitField()) { CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field); - - const llvm::Type *Ty = + + const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType()); - uint64_t TypeSize = + uint64_t TypeSize = CGM.getTypes().getTargetData().getTypeAllocSize(Ty); FieldOffset = Info.FieldNo * TypeSize; } else @@ -3516,8 +3509,7 @@ void CGObjCMac::FinishModule() { CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), - ObjCTypes(cgm) -{ + ObjCTypes(cgm) { ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL; ObjCABI = 2; } @@ -3525,8 +3517,7 @@ CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) /* *** */ ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) - : VMContext(cgm.getLLVMContext()), CGM(cgm) -{ + : VMContext(cgm.getLLVMContext()), CGM(cgm) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -3612,8 +3603,7 @@ ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) } ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) - : ObjCCommonTypesHelper(cgm) -{ + : ObjCCommonTypesHelper(cgm) { // struct _objc_method_description { // SEL name; // char *types; @@ -3666,7 +3656,7 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(VMContext); const llvm::Type *T = - llvm::StructType::get(VMContext, + llvm::StructType::get(VMContext, llvm::PointerType::getUnqual(ProtocolListTyHolder), LongTy, llvm::ArrayType::get(ProtocolTyHolder, 0), @@ -3835,8 +3825,7 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) } ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) - : ObjCCommonTypesHelper(cgm) -{ + : ObjCCommonTypesHelper(cgm) { // struct _method_list_t { // uint32_t entsize; // sizeof(struct _objc_method) // uint32_t method_count; @@ -3908,7 +3897,7 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // uint32_t alignment; // uint32_t size; // } - IvarnfABITy = llvm::StructType::get(VMContext, + IvarnfABITy = llvm::StructType::get(VMContext, llvm::PointerType::getUnqual(LongTy), Int8PtrTy, Int8PtrTy, @@ -5056,7 +5045,7 @@ CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend( Name += '_'; std::string SelName(Sel.getAsString()); // Replace all ':' in selector name with '_' ouch! - for(unsigned i = 0; i < SelName.size(); i++) + for (unsigned i = 0; i < SelName.size(); i++) if (SelName[i] == ':') SelName[i] = '_'; Name += SelName; @@ -5277,8 +5266,8 @@ llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder, /// objc_assign_ivar (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, + llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -5299,8 +5288,7 @@ void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, /// void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign( CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -5337,8 +5325,7 @@ void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable( /// llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( CodeGen::CodeGenFunction &CGF, - llvm::Value *AddrWeakObj) -{ + llvm::Value *AddrWeakObj) { const llvm::Type* DestTy = cast(AddrWeakObj->getType())->getElementType(); AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); @@ -5352,8 +5339,7 @@ llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( /// objc_assign_weak (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); @@ -5373,8 +5359,7 @@ void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, /// objc_assign_global (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, - llvm::Value *src, llvm::Value *dst) -{ + llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa(SrcTy)) { unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy); diff --git a/clang/lib/CodeGen/CGObjCRuntime.h b/clang/lib/CodeGen/CGObjCRuntime.h index d82df9d881d71adaa197f62875f76728e1addf74..8951ab6d32b7a6d1af6d3e81ad36477caf394c43 100644 --- a/clang/lib/CodeGen/CGObjCRuntime.h +++ b/clang/lib/CodeGen/CGObjCRuntime.h @@ -86,7 +86,7 @@ protected: llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers, - llvm::Value *Offset); + llvm::Value *Offset); public: virtual ~CGObjCRuntime(); @@ -101,7 +101,7 @@ public: virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel) = 0; - /// Get a typed selector. + /// Get a typed selector. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl *Method) = 0; @@ -114,9 +114,9 @@ public: /// Generate a class stucture for this class. virtual void GenerateClass(const ObjCImplementationDecl *OID) = 0; - - /// Generate an Objective-C message send operation. - virtual CodeGen::RValue + + /// Generate an Objective-C message send operation. + virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, @@ -143,34 +143,34 @@ public: virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, const ObjCProtocolDecl *OPD) = 0; - /// Generate the named protocol. Protocols contain method metadata but no - /// implementations. + /// Generate the named protocol. Protocols contain method metadata but no + /// implementations. virtual void GenerateProtocol(const ObjCProtocolDecl *OPD) = 0; /// Generate a function preamble for a method with the specified - /// types. + /// types. // FIXME: Current this just generates the Function definition, but really this // should also be generating the loads of the parameters, as the runtime // should have full control over how parameters are passed. - virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, + virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD) = 0; /// Return the runtime function for getting properties. virtual llvm::Constant *GetPropertyGetFunction() = 0; - + /// Return the runtime function for setting properties. virtual llvm::Constant *GetPropertySetFunction() = 0; /// GetClass - Return a reference to the class for the given /// interface decl. - virtual llvm::Value *GetClass(CGBuilderTy &Builder, + virtual llvm::Value *GetClass(CGBuilderTy &Builder, const ObjCInterfaceDecl *OID) = 0; /// EnumerationMutationFunction - Return the function that's called by the /// compiler when a mutation is detected during foreach iteration. virtual llvm::Constant *EnumerationMutationFunction() = 0; - + virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S) = 0; virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, @@ -185,7 +185,7 @@ public: llvm::Value *src, llvm::Value *dest) = 0; virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest) = 0; - + virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, @@ -195,12 +195,12 @@ public: const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) = 0; virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, - llvm::Value *DestPtr, + llvm::Value *DestPtr, llvm::Value *SrcPtr, QualType Ty) = 0; }; -/// Creates an instance of an Objective-C runtime class. +/// Creates an instance of an Objective-C runtime class. //TODO: This should include some way of selecting which runtime to target. CGObjCRuntime *CreateGNUObjCRuntime(CodeGenModule &CGM); CGObjCRuntime *CreateMacObjCRuntime(CodeGenModule &CGM); diff --git a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp index f2fd885ee4d9a1cf17a388ee4727315529d0ee1f..d26c7721da27af57ca249a2f6df84e2d035e42f7 100644 --- a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp +++ b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp @@ -37,7 +37,7 @@ void CGRecordLayoutBuilder::Layout(const RecordDecl *D) { if (LayoutFields(D)) return; - + // We weren't able to layout the struct. Try again with a packed struct Packed = true; AlignmentAsLLVMStruct = 1; @@ -45,52 +45,52 @@ void CGRecordLayoutBuilder::Layout(const RecordDecl *D) { FieldTypes.clear(); LLVMFields.clear(); LLVMBitFields.clear(); - + LayoutFields(D); } void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D, uint64_t FieldOffset) { - uint64_t FieldSize = + uint64_t FieldSize = D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue(); - + if (FieldSize == 0) return; uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8; unsigned NumBytesToAppend; - + if (FieldOffset < NextFieldOffset) { assert(BitsAvailableInLastField && "Bitfield size mismatch!"); assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!"); - + // The bitfield begins in the previous bit-field. - NumBytesToAppend = + NumBytesToAppend = llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8; } else { assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly"); // Append padding if necessary. AppendBytes((FieldOffset - NextFieldOffset) / 8); - - NumBytesToAppend = + + NumBytesToAppend = llvm::RoundUpToAlignment(FieldSize, 8) / 8; - + assert(NumBytesToAppend && "No bytes to append!"); } const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType()); uint64_t TypeSizeInBits = getTypeSizeInBytes(Ty) * 8; - + LLVMBitFields.push_back(LLVMBitFieldInfo(D, FieldOffset / TypeSizeInBits, - FieldOffset % TypeSizeInBits, + FieldOffset % TypeSizeInBits, FieldSize)); - + AppendBytes(NumBytesToAppend); - + AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct, getTypeAlignment(Ty)); - BitsAvailableInLastField = + BitsAvailableInLastField = NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize); } @@ -105,14 +105,14 @@ bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D, // don't affect the struct alignment. if (!Packed && !D->getDeclName()) return false; - + LayoutBitField(D, FieldOffset); return true; } - + assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!"); uint64_t FieldOffsetInBytes = FieldOffset / 8; - + const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType()); unsigned TypeAlignment = getTypeAlignment(Ty); @@ -122,7 +122,7 @@ bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D, assert(!Packed && "Alignment is wrong even with packed struct!"); return false; } - + if (const RecordType *RT = D->getType()->getAs()) { const RecordDecl *RD = cast(RT->getDecl()); if (const PragmaPackAttr *PPA = RD->getAttr()) { @@ -132,72 +132,72 @@ bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D, } // Round up the field offset to the alignment of the field type. - uint64_t AlignedNextFieldOffsetInBytes = + uint64_t AlignedNextFieldOffsetInBytes = llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment); if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) { assert(!Packed && "Could not place field even with packed struct!"); return false; } - + if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) { // Even with alignment, the field offset is not at the right place, // insert padding. uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes; - + AppendBytes(PaddingInBytes); } - + // Now append the field. LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size())); AppendField(FieldOffsetInBytes, Ty); - + return true; } void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) { assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!"); - + const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D); - + const llvm::Type *Ty = 0; uint64_t Size = 0; unsigned Align = 0; - + unsigned FieldNo = 0; - for (RecordDecl::field_iterator Field = D->field_begin(), + for (RecordDecl::field_iterator Field = D->field_begin(), FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { - assert(Layout.getFieldOffset(FieldNo) == 0 && + assert(Layout.getFieldOffset(FieldNo) == 0 && "Union field offset did not start at the beginning of record!"); if (Field->isBitField()) { - uint64_t FieldSize = + uint64_t FieldSize = Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue(); - + // Ignore zero sized bit fields. if (FieldSize == 0) continue; - + // Add the bit field info. Types.addBitFieldInfo(*Field, 0, 0, FieldSize); } else Types.addFieldInfo(*Field, 0); - - const llvm::Type *FieldTy = + + const llvm::Type *FieldTy = Types.ConvertTypeForMemRecursive(Field->getType()); unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy); uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy); - + if (FieldAlign < Align) continue; - + if (FieldAlign > Align || FieldSize > Size) { Ty = FieldTy; Align = FieldAlign; Size = FieldSize; } } - + // Now add our field. if (Ty) { AppendField(0, Ty); @@ -208,7 +208,7 @@ void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) { Align = 1; } } - + // Append tail padding. if (Layout.getSize() / 8 > Size) AppendPadding(Layout.getSize() / 8, Align); @@ -217,15 +217,15 @@ void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) { bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) { assert(!D->isUnion() && "Can't call LayoutFields on a union!"); assert(Alignment && "Did not set alignment!"); - + const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D); - + unsigned FieldNo = 0; - for (RecordDecl::field_iterator Field = D->field_begin(), + for (RecordDecl::field_iterator Field = D->field_begin(), FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) { - assert(!Packed && + assert(!Packed && "Could not layout fields even with a packed LLVM struct!"); return false; } @@ -233,21 +233,21 @@ bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) { // Append tail padding if necessary. AppendTailPadding(Layout.getSize()); - + return true; } void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) { assert(RecordSize % 8 == 0 && "Invalid record size!"); - + uint64_t RecordSizeInBytes = RecordSize / 8; assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!"); - + unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes; AppendBytes(NumPadBytes); } -void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes, +void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes, const llvm::Type *FieldTy) { AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct, getTypeAlignment(FieldTy)); @@ -260,19 +260,19 @@ void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes, BitsAvailableInLastField = 0; } -void +void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes, const llvm::Type *FieldTy) { AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy)); } -void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes, +void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes, unsigned FieldAlignment) { assert(NextFieldOffsetInBytes <= FieldOffsetInBytes && "Incorrect field layout!"); - + // Round up the field offset to the alignment of the field type. - uint64_t AlignedNextFieldOffsetInBytes = + uint64_t AlignedNextFieldOffsetInBytes = llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment); if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) { @@ -287,11 +287,11 @@ void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes, void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) { if (NumBytes == 0) return; - + const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext()); if (NumBytes > 1) Ty = llvm::ArrayType::get(Ty, NumBytes); - + // Append the padding field AppendField(NextFieldOffsetInBytes, Ty); } @@ -299,7 +299,7 @@ void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) { unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const { if (Packed) return 1; - + return Types.getTargetData().getABITypeAlignment(Ty); } @@ -311,26 +311,26 @@ void CGRecordLayoutBuilder::CheckForMemberPointer(const FieldDecl *FD) { // This record already contains a member pointer. if (ContainsMemberPointer) return; - + // Can only have member pointers if we're compiling C++. if (!Types.getContext().getLangOptions().CPlusPlus) return; - + QualType Ty = FD->getType(); - + if (Ty->isMemberPointerType()) { // We have a member pointer! ContainsMemberPointer = true; return; } - + } CGRecordLayout * CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types, const RecordDecl *D) { CGRecordLayoutBuilder Builder(Types); - + Builder.Layout(D); const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(), @@ -339,7 +339,7 @@ CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types, assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 == Types.getTargetData().getTypeAllocSize(Ty) && "Type size mismatch!"); - + // Add all the field numbers. for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) { const FieldDecl *FD = Builder.LLVMFields[i].first; @@ -351,9 +351,9 @@ CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types, // Add bitfield info. for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) { const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i]; - + Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size); } - + return new CGRecordLayout(Ty, Builder.ContainsMemberPointer); } diff --git a/clang/lib/CodeGen/CGRecordLayoutBuilder.h b/clang/lib/CodeGen/CGRecordLayoutBuilder.h index 63ddc10df52863972170c8fd1c4ca06c476fdb16..d1a13aa29711ed9c3895fce632e5db12b74db90b 100644 --- a/clang/lib/CodeGen/CGRecordLayoutBuilder.h +++ b/clang/lib/CodeGen/CGRecordLayoutBuilder.h @@ -25,57 +25,57 @@ namespace llvm { namespace clang { class FieldDecl; class RecordDecl; - + namespace CodeGen { class CGRecordLayout; class CodeGenTypes; -class CGRecordLayoutBuilder { +class CGRecordLayoutBuilder { CodeGenTypes &Types; - + /// Packed - Whether the resulting LLVM struct will be packed or not. bool Packed; /// ContainsMemberPointer - Whether one of the fields is a member pointer /// or is a struct that contains a member pointer. bool ContainsMemberPointer; - + /// Alignment - Contains the alignment of the RecordDecl. unsigned Alignment; /// AlignmentAsLLVMStruct - Will contain the maximum alignment of all the /// LLVM types. unsigned AlignmentAsLLVMStruct; - + /// BitsAvailableInLastField - If a bit field spans only part of a LLVM field, /// this will have the number of bits still available in the field. char BitsAvailableInLastField; /// NextFieldOffsetInBytes - Holds the next field offset in bytes. uint64_t NextFieldOffsetInBytes; - + /// FieldTypes - Holds the LLVM types that the struct is created from. std::vector FieldTypes; - + /// LLVMFieldInfo - Holds a field and its corresponding LLVM field number. typedef std::pair LLVMFieldInfo; llvm::SmallVector LLVMFields; /// LLVMBitFieldInfo - Holds location and size information about a bit field. struct LLVMBitFieldInfo { - LLVMBitFieldInfo(const FieldDecl *FD, unsigned FieldNo, unsigned Start, + LLVMBitFieldInfo(const FieldDecl *FD, unsigned FieldNo, unsigned Start, unsigned Size) : FD(FD), FieldNo(FieldNo), Start(Start), Size(Size) { } - + const FieldDecl *FD; - + unsigned FieldNo; unsigned Start; unsigned Size; }; llvm::SmallVector LLVMBitFields; - - CGRecordLayoutBuilder(CodeGenTypes &Types) + + CGRecordLayoutBuilder(CodeGenTypes &Types) : Types(Types), Packed(false), ContainsMemberPointer(false) , Alignment(0), AlignmentAsLLVMStruct(1) , BitsAvailableInLastField(0), NextFieldOffsetInBytes(0) { } @@ -85,15 +85,15 @@ class CGRecordLayoutBuilder { /// LayoutUnion - Will layout a union RecordDecl. void LayoutUnion(const RecordDecl *D); - + /// LayoutField - try to layout all fields in the record decl. /// Returns false if the operation failed because the struct is not packed. bool LayoutFields(const RecordDecl *D); - + /// LayoutField - layout a single field. Returns false if the operation failed /// because the current struct is not packed. bool LayoutField(const FieldDecl *D, uint64_t FieldOffset); - + /// LayoutBitField - layout a single bit field. void LayoutBitField(const FieldDecl *D, uint64_t FieldOffset); @@ -107,28 +107,28 @@ class CGRecordLayoutBuilder { /// AppendPadding - Appends enough padding bytes so that the total /// struct size is a multiple of the field alignment. void AppendPadding(uint64_t FieldOffsetInBytes, unsigned FieldAlignment); - + /// AppendBytes - Append a given number of bytes to the record. void AppendBytes(uint64_t NumBytes); /// AppendTailPadding - Append enough tail padding so that the type will have /// the passed size. void AppendTailPadding(uint64_t RecordSize); - + unsigned getTypeAlignment(const llvm::Type *Ty) const; uint64_t getTypeSizeInBytes(const llvm::Type *Ty) const; /// CheckForMemberPointer - Check if the field contains a member pointer. void CheckForMemberPointer(const FieldDecl *FD); - + public: /// ComputeLayout - Return the right record layout for a given record decl. - static CGRecordLayout *ComputeLayout(CodeGenTypes &Types, + static CGRecordLayout *ComputeLayout(CodeGenTypes &Types, const RecordDecl *D); }; - + } // end namespace CodeGen } // end namespace clang - -#endif + +#endif diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp index 12e3a95373a11dae11f9e38d96f26b3ae182904f..26d1c3b8a4bf466e0993d38e0a3e960a5afa3e82 100644 --- a/clang/lib/CodeGen/CGStmt.cpp +++ b/clang/lib/CodeGen/CGStmt.cpp @@ -72,7 +72,7 @@ void CodeGenFunction::EmitStmt(const Stmt *S) { ErrorUnsupported(S, "statement"); EmitAnyExpr(cast(S), 0, false, true); - + // Expression emitters don't handle unreachable blocks yet, so look for one // explicitly here. This handles the common case of a call to a noreturn // function. @@ -83,14 +83,14 @@ void CodeGenFunction::EmitStmt(const Stmt *S) { } } break; - case Stmt::IndirectGotoStmtClass: + case Stmt::IndirectGotoStmtClass: EmitIndirectGotoStmt(cast(*S)); break; case Stmt::IfStmtClass: EmitIfStmt(cast(*S)); break; case Stmt::WhileStmtClass: EmitWhileStmt(cast(*S)); break; case Stmt::DoStmtClass: EmitDoStmt(cast(*S)); break; case Stmt::ForStmtClass: EmitForStmt(cast(*S)); break; - + case Stmt::ReturnStmtClass: EmitReturnStmt(cast(*S)); break; case Stmt::SwitchStmtClass: EmitSwitchStmt(cast(*S)); break; @@ -98,7 +98,7 @@ void CodeGenFunction::EmitStmt(const Stmt *S) { case Stmt::ObjCAtTryStmtClass: EmitObjCAtTryStmt(cast(*S)); - break; + break; case Stmt::ObjCAtCatchStmtClass: assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt"); break; @@ -111,7 +111,7 @@ void CodeGenFunction::EmitStmt(const Stmt *S) { case Stmt::ObjCAtSynchronizedStmtClass: EmitObjCAtSynchronizedStmt(cast(*S)); break; - case Stmt::ObjCForCollectionStmtClass: + case Stmt::ObjCForCollectionStmtClass: EmitObjCForCollectionStmt(cast(*S)); break; } @@ -141,7 +141,7 @@ RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, llvm::Value *AggLoc, bool isAggVol) { PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), "LLVM IR generation of compound statement ('{}')"); - + CGDebugInfo *DI = getDebugInfo(); if (DI) { EnsureInsertPoint(); @@ -156,7 +156,7 @@ RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, size_t CleanupStackDepth = CleanupEntries.size(); bool OldDidCallStackSave = DidCallStackSave; DidCallStackSave = false; - + for (CompoundStmt::const_body_iterator I = S.body_begin(), E = S.body_end()-GetLast; I != E; ++I) EmitStmt(*I); @@ -164,7 +164,7 @@ RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, if (DI) { EnsureInsertPoint(); DI->setLocation(S.getRBracLoc()); - + // FIXME: The llvm backend is currently not ready to deal with region_end // for block scoping. In the presence of always_inline functions it gets so // confused that it doesn't emit any debug info. Just disable this for now. @@ -172,10 +172,10 @@ RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, } RValue RV; - if (!GetLast) + if (!GetLast) RV = RValue::get(0); else { - // We have to special case labels here. They are statements, but when put + // We have to special case labels here. They are statements, but when put // at the end of a statement expression, they yield the value of their // subexpression. Handle this by walking through all labels we encounter, // emitting them before we evaluate the subexpr. @@ -184,22 +184,22 @@ RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, EmitLabel(*LS); LastStmt = LS->getSubStmt(); } - + EnsureInsertPoint(); - + RV = EmitAnyExpr(cast(LastStmt), AggLoc); } DidCallStackSave = OldDidCallStackSave; - + EmitCleanupBlocks(CleanupStackDepth); - + return RV; } void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { llvm::BranchInst *BI = dyn_cast(BB->getTerminator()); - + // If there is a cleanup stack, then we it isn't worth trying to // simplify this block (we would need to remove it from the scope map // and cleanup entry). @@ -235,7 +235,7 @@ void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { CleanupEntries.back().Blocks.push_back(BB); } } - + CurFn->getBasicBlockList().push_back(BB); Builder.SetInsertPoint(BB); } @@ -282,7 +282,7 @@ void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { // EmitIndirectSwitches(). We need a default dest, so we use the // current BB, but this is overwritten. llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()), - llvm::Type::getInt32Ty(VMContext), + llvm::Type::getInt32Ty(VMContext), "addr"); llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock()); IndirectSwitches.push_back(I); @@ -294,7 +294,7 @@ void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { void CodeGenFunction::EmitIfStmt(const IfStmt &S) { // C99 6.8.4.1: The first substatement is executed if the expression compares // unequal to 0. The condition must be a scalar type. - + // If the condition constant folds and can be elided, try to avoid emitting // the condition and the dead arm of the if/else. if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) { @@ -302,7 +302,7 @@ void CodeGenFunction::EmitIfStmt(const IfStmt &S) { const Stmt *Executed = S.getThen(), *Skipped = S.getElse(); if (Cond == -1) // Condition false? std::swap(Executed, Skipped); - + // If the skipped block has no labels in it, just emit the executed block. // This avoids emitting dead code and simplifies the CFG substantially. if (!ContainsLabel(Skipped)) { @@ -320,19 +320,19 @@ void CodeGenFunction::EmitIfStmt(const IfStmt &S) { if (S.getElse()) ElseBlock = createBasicBlock("if.else"); EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock); - + // Emit the 'then' code. EmitBlock(ThenBlock); EmitStmt(S.getThen()); EmitBranch(ContBlock); - + // Emit the 'else' code if present. if (const Stmt *Else = S.getElse()) { EmitBlock(ElseBlock); EmitStmt(Else); EmitBranch(ContBlock); } - + // Emit the continuation block for code after the if. EmitBlock(ContBlock, true); } @@ -350,7 +350,7 @@ void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { // Store the blocks to use for break and continue. BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader)); - + // Evaluate the conditional in the while header. C99 6.8.5.1: The // evaluation of the controlling expression takes place before each // execution of the loop body. @@ -359,23 +359,23 @@ void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { // while(1) is common, avoid extra exit blocks. Be sure // to correctly handle break/continue though. bool EmitBoolCondBranch = true; - if (llvm::ConstantInt *C = dyn_cast(BoolCondVal)) + if (llvm::ConstantInt *C = dyn_cast(BoolCondVal)) if (C->isOne()) EmitBoolCondBranch = false; - + // As long as the condition is true, go to the loop body. if (EmitBoolCondBranch) Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); - + // Emit the loop body. EmitBlock(LoopBody); EmitStmt(S.getBody()); - BreakContinueStack.pop_back(); - + BreakContinueStack.pop_back(); + // Cycle to the condition. EmitBranch(LoopHeader); - + // Emit the exit block. EmitBlock(ExitBlock, true); @@ -393,20 +393,20 @@ void CodeGenFunction::EmitDoStmt(const DoStmt &S) { EmitBlock(LoopBody); llvm::BasicBlock *DoCond = createBasicBlock("do.cond"); - + // Store the blocks to use for break and continue. BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond)); - + // Emit the body of the loop into the block. EmitStmt(S.getBody()); - + BreakContinueStack.pop_back(); - + EmitBlock(DoCond); - + // C99 6.8.5.2: "The evaluation of the controlling expression takes place // after each execution of the loop body." - + // Evaluate the conditional in the while header. // C99 6.8.5p2/p4: The first substatement is executed if the expression // compares unequal to 0. The condition must be a scalar type. @@ -415,14 +415,14 @@ void CodeGenFunction::EmitDoStmt(const DoStmt &S) { // "do {} while (0)" is common in macros, avoid extra blocks. Be sure // to correctly handle break/continue though. bool EmitBoolCondBranch = true; - if (llvm::ConstantInt *C = dyn_cast(BoolCondVal)) + if (llvm::ConstantInt *C = dyn_cast(BoolCondVal)) if (C->isZero()) EmitBoolCondBranch = false; // As long as the condition is true, iterate the loop. if (EmitBoolCondBranch) Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo); - + // Emit the exit block. EmitBlock(AfterDo); @@ -451,25 +451,25 @@ void CodeGenFunction::EmitForStmt(const ForStmt &S) { if (S.getCond()) { // As long as the condition is true, iterate the loop. llvm::BasicBlock *ForBody = createBasicBlock("for.body"); - + // C99 6.8.5p2/p4: The first substatement is executed if the expression // compares unequal to 0. The condition must be a scalar type. EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor); - - EmitBlock(ForBody); + + EmitBlock(ForBody); } else { // Treat it as a non-zero constant. Don't even create a new block for the // body, just fall into it. } - // If the for loop doesn't have an increment we can just use the + // If the for loop doesn't have an increment we can just use the // condition as the continue block. llvm::BasicBlock *ContinueBlock; if (S.getInc()) ContinueBlock = createBasicBlock("for.inc"); else - ContinueBlock = CondBlock; - + ContinueBlock = CondBlock; + // Store the blocks to use for break and continue. BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock)); @@ -477,13 +477,13 @@ void CodeGenFunction::EmitForStmt(const ForStmt &S) { EmitStmt(S.getBody()); BreakContinueStack.pop_back(); - + // If there is an increment, emit it next. if (S.getInc()) { EmitBlock(ContinueBlock); EmitStmt(S.getInc()); } - + // Finally, branch back up to the condition for the next iteration. EmitBranch(CondBlock); @@ -508,7 +508,7 @@ void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { // Emit the result value, even if unused, to evalute the side effects. const Expr *RV = S.getRetValue(); - + // FIXME: Clean this up by using an LValue for ReturnTemp, // EmitStoreThroughLValue, and EmitAnyExpr. if (!ReturnValue) { @@ -601,8 +601,8 @@ void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { LHS++; } return; - } - + } + // The range is too big. Emit "if" condition into a new block, // making sure to save and restore the current insertion point. llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); @@ -617,10 +617,10 @@ void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { Builder.SetInsertPoint(CaseRangeBlock); // Emit range check. - llvm::Value *Diff = - Builder.CreateSub(SwitchInsn->getCondition(), + llvm::Value *Diff = + Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(VMContext, LHS), "tmp"); - llvm::Value *Cond = + llvm::Value *Cond = Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(VMContext, Range), "tmp"); Builder.CreateCondBr(Cond, CaseDest, FalseDest); @@ -637,12 +637,12 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { EmitCaseStmtRange(S); return; } - + EmitBlock(createBasicBlock("sw.bb")); llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext()); SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); - + // Recursively emitting the statement is acceptable, but is not wonderful for // code where we have many case statements nested together, i.e.: // case 1: @@ -663,14 +663,14 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { NextCase = dyn_cast(CurCase->getSubStmt()); } - + // Normal default recursion for non-cases. EmitStmt(CurCase->getSubStmt()); } void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) { llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); - assert(DefaultBlock->empty() && + assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?"); EmitBlock(DefaultBlock); EmitStmt(S.getSubStmt()); @@ -706,13 +706,13 @@ void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { // Emit switch body. EmitStmt(S.getBody()); - + BreakContinueStack.pop_back(); // Update the default block in case explicit case range tests have // been chained on top. SwitchInsn->setSuccessor(0, CaseRangeBlock); - + // If a default was never emitted then reroute any jumps to it and // discard. if (!DefaultBlock->getParent()) { @@ -731,7 +731,7 @@ static std::string SimplifyConstraint(const char *Constraint, TargetInfo &Target, llvm::SmallVectorImpl *OutCons=0) { std::string Result; - + while (*Constraint) { switch (*Constraint) { default: @@ -749,7 +749,7 @@ SimplifyConstraint(const char *Constraint, TargetInfo &Target, assert(OutCons && "Must pass output names to constraints with a symbolic name"); unsigned Index; - bool result = Target.resolveSymbolicName(Constraint, + bool result = Target.resolveSymbolicName(Constraint, &(*OutCons)[0], OutCons->size(), Index); assert(result && "Could not resolve symbolic name"); result=result; @@ -757,10 +757,10 @@ SimplifyConstraint(const char *Constraint, TargetInfo &Target, break; } } - + Constraint++; } - + return Result; } @@ -769,9 +769,9 @@ llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S, const Expr *InputExpr, std::string &ConstraintStr) { llvm::Value *Arg; - if (Info.allowsRegister() || !Info.allowsMemory()) { + if (Info.allowsRegister() || !Info.allowsMemory()) { const llvm::Type *Ty = ConvertType(InputExpr->getType()); - + if (Ty->isSingleValueType()) { Arg = EmitScalarExpr(InputExpr); } else { @@ -782,7 +782,7 @@ llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S, if (Size <= 64 && llvm::isPowerOf2_64(Size)) { Ty = llvm::IntegerType::get(VMContext, Size); Ty = llvm::PointerType::getUnqual(Ty); - + Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty)); } else { Arg = Dest.getAddress(); @@ -795,7 +795,7 @@ llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S, Arg = Dest.getAddress(); ConstraintStr += '*'; } - + return Arg; } @@ -805,7 +805,7 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { llvm::SmallVector Pieces; unsigned DiagOffs; S.AnalyzeAsmString(Pieces, getContext(), DiagOffs); - + // Assemble the pieces into the final asm string. std::string AsmString; for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { @@ -817,19 +817,19 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' + Pieces[i].getModifier() + '}'; } - + // Get all the output and input constraints together. llvm::SmallVector OutputConstraintInfos; llvm::SmallVector InputConstraintInfos; - for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { + for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), S.getOutputName(i)); bool result = Target.validateOutputConstraint(Info); assert(result && "Failed to parse output constraint"); result=result; OutputConstraintInfos.push_back(Info); - } - + } + for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), S.getInputName(i)); @@ -839,9 +839,9 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { assert(result && "Failed to parse input constraint"); InputConstraintInfos.push_back(Info); } - + std::string Constraints; - + std::vector ResultRegDests; std::vector ResultRegQualTys; std::vector ResultRegTypes; @@ -854,16 +854,16 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { std::vector InOutArgs; std::vector InOutArgTypes; - for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { + for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; // Simplify the output constraint. std::string OutputConstraint(S.getOutputConstraint(i)); OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target); - + const Expr *OutExpr = S.getOutputExpr(i); OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); - + LValue Dest = EmitLValue(OutExpr); if (!Constraints.empty()) Constraints += ','; @@ -876,7 +876,7 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { ResultRegDests.push_back(Dest); ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); ResultTruncRegTypes.push_back(ResultRegTypes.back()); - + // If this output is tied to an input, and if the input is larger, then // we need to set the actual result type of the inline asm node to be the // same as the input type. @@ -889,10 +889,10 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { break; } assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); - + QualType InputTy = S.getInputExpr(InputNo)->getType(); QualType OutputTy = OutExpr->getType(); - + uint64_t InputSize = getContext().getTypeSize(InputTy); if (getContext().getTypeSize(OutputTy) < InputSize) { // Form the asm to return the value as a larger integer type. @@ -905,13 +905,13 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { Constraints += "=*"; Constraints += OutputConstraint; } - + if (Info.isReadWrite()) { InOutConstraints += ','; const Expr *InputExpr = S.getOutputExpr(i); llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints); - + if (Info.allowsRegister()) InOutConstraints += llvm::utostr(i); else @@ -921,9 +921,9 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { InOutArgs.push_back(Arg); } } - + unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs(); - + for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { const Expr *InputExpr = S.getInputExpr(i); @@ -931,14 +931,14 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { if (!Constraints.empty()) Constraints += ','; - + // Simplify the input constraint. std::string InputConstraint(S.getInputConstraint(i)); InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target, &OutputConstraintInfos); llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints); - + // If this input argument is tied to a larger output result, extend the // input to be the same size as the output. The LLVM backend wants to see // the input and output of a matching constraint be the same size. Note @@ -948,7 +948,7 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { unsigned Output = Info.getTiedOperand(); QualType OutputTy = S.getOutputExpr(Output)->getType(); QualType InputTy = InputExpr->getType(); - + if (getContext().getTypeSize(OutputTy) > getContext().getTypeSize(InputTy)) { // Use ptrtoint as appropriate so that we can do our extension. @@ -959,35 +959,35 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(VMContext, OutputSize)); } } - - + + ArgTypes.push_back(Arg->getType()); Args.push_back(Arg); Constraints += InputConstraint; } - + // Append the "input" part of inout constraints last. for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { ArgTypes.push_back(InOutArgTypes[i]); Args.push_back(InOutArgs[i]); } Constraints += InOutConstraints; - + // Clobbers for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { std::string Clobber(S.getClobber(i)->getStrData(), S.getClobber(i)->getByteLength()); Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str()); - + if (i != 0 || NumConstraints != 0) Constraints += ','; - + Constraints += "~{"; Constraints += Clobber; Constraints += '}'; } - + // Add machine specific clobbers std::string MachineClobbers = Target.getClobbers(); if (!MachineClobbers.empty()) { @@ -1003,17 +1003,17 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { ResultType = ResultRegTypes[0]; else ResultType = llvm::StructType::get(VMContext, ResultRegTypes); - - const llvm::FunctionType *FTy = + + const llvm::FunctionType *FTy = llvm::FunctionType::get(ResultType, ArgTypes, false); - - llvm::InlineAsm *IA = - llvm::InlineAsm::get(FTy, AsmString, Constraints, + + llvm::InlineAsm *IA = + llvm::InlineAsm::get(FTy, AsmString, Constraints, S.isVolatile() || S.getNumOutputs() == 0); llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end()); Result->addAttribute(~0, llvm::Attribute::NoUnwind); - - + + // Extract all of the register value results from the asm. std::vector RegResults; if (ResultRegTypes.size() == 1) { @@ -1024,10 +1024,10 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { RegResults.push_back(Tmp); } } - + for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { llvm::Value *Tmp = RegResults[i]; - + // If the result type of the LLVM IR asm doesn't match the result type of // the expression, do the conversion. if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { @@ -1036,13 +1036,13 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { // ResultTruncRegTypes can be a pointer. uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy); Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, (unsigned)ResSize)); - + if (Tmp->getType() != TruncTy) { assert(isa(TruncTy)); Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); } } - + EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i], ResultRegQualTys[i]); } diff --git a/clang/lib/CodeGen/CGValue.h b/clang/lib/CodeGen/CGValue.h index 5aaf951a542d92ee97a4d72297266698c28dc92d..fe97afad6e8e967a41a49de1b982c155b67ad11f 100644 --- a/clang/lib/CodeGen/CGValue.h +++ b/clang/lib/CodeGen/CGValue.h @@ -37,14 +37,14 @@ class RValue { // TODO: Encode this into the low bit of pointer for more efficient // return-by-value. enum { Scalar, Complex, Aggregate } Flavor; - + bool Volatile:1; public: - + bool isScalar() const { return Flavor == Scalar; } bool isComplex() const { return Flavor == Complex; } bool isAggregate() const { return Flavor == Aggregate; } - + bool isVolatileQualified() const { return Volatile; } /// getScalar() - Return the Value* of this scalar value. @@ -58,13 +58,13 @@ public: std::pair getComplexVal() const { return std::pair(V1, V2); } - + /// getAggregateAddr() - Return the Value* of the address of the aggregate. llvm::Value *getAggregateAddr() const { assert(isAggregate() && "Not an aggregate!"); return V1; } - + static RValue get(llvm::Value *V) { RValue ER; ER.V1 = V; @@ -106,7 +106,7 @@ public: /// bitrange. class LValue { // FIXME: alignment? - + enum { Simple, // This is a normal l-value, use getAddress(). VectorElt, // This is a vector element l-value (V[i]), use getVector* @@ -123,16 +123,16 @@ class LValue { Weak, // __weak object expression Strong // __strong object expression }; - + llvm::Value *V; - + union { // Index into a vector subscript: V[i] llvm::Value *VectorIdx; // ExtVector element subset: V.xyx llvm::Constant *VectorElts; - + // BitField start bit and size struct { unsigned short StartBit; @@ -152,7 +152,7 @@ class LValue { // objective-c's ivar bool Ivar:1; - + // LValue is non-gc'able for any reason, including being a parameter or local // variable. bool NonGC: 1; @@ -161,7 +161,7 @@ class LValue { bool GlobalObjCRef : 1; // objective-c's gc attributes - unsigned ObjCType : 2; + unsigned ObjCType : 2; // address space unsigned AddressSpace; @@ -175,7 +175,7 @@ private: R.ObjCType = None; R.Ivar = R.NonGC = R.GlobalObjCRef = false; } - + public: bool isSimple() const { return LVType == Simple; } bool isVectorElt() const { return LVType == VectorElt; } @@ -187,10 +187,10 @@ public: bool isVolatileQualified() const { return Volatile; } bool isRestrictQualified() const { return Restrict; } unsigned getQualifiers() const { - return (Volatile ? QualType::Volatile : 0) | + return (Volatile ? QualType::Volatile : 0) | (Restrict ? QualType::Restrict : 0); } - + bool isObjCIvar() const { return Ivar; } bool isNonGC () const { return NonGC; } bool isGlobalObjCRef() const { return GlobalObjCRef; } @@ -206,7 +206,7 @@ public: static void SetGlobalObjCRef(LValue& R, bool iValue) { R.GlobalObjCRef = iValue; } - + static void SetObjCNonGC(LValue& R, bool iValue) { R.NonGC = iValue; } @@ -218,7 +218,7 @@ public: else R.ObjCType = None; } - + // simple lvalue llvm::Value *getAddress() const { assert(isSimple()); return V; } // vector elt lvalue @@ -267,7 +267,7 @@ public: SetObjCType(GCAttrs, R); return R; } - + static LValue MakeVectorElt(llvm::Value *Vec, llvm::Value *Idx, unsigned Qualifiers) { LValue R; @@ -277,7 +277,7 @@ public: SetQualifiers(Qualifiers,R); return R; } - + static LValue MakeExtVectorElt(llvm::Value *Vec, llvm::Constant *Elts, unsigned Qualifiers) { LValue R; @@ -312,8 +312,8 @@ public: SetQualifiers(Qualifiers,R); return R; } - - static LValue MakeKVCRef(const ObjCImplicitSetterGetterRefExpr *E, + + static LValue MakeKVCRef(const ObjCImplicitSetterGetterRefExpr *E, unsigned Qualifiers) { LValue R; R.LVType = KVCRef; diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp b/clang/lib/CodeGen/CodeGenFunction.cpp index e3511edd2be47f6ff8e6464ea315f004dd9f0ba3..be2406d063bdef871e97fdffc9583126006eeda6 100644 --- a/clang/lib/CodeGen/CodeGenFunction.cpp +++ b/clang/lib/CodeGen/CodeGenFunction.cpp @@ -23,11 +23,11 @@ using namespace clang; using namespace CodeGen; -CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) +CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) : BlockFunction(cgm, *this, Builder), CGM(cgm), Target(CGM.getContext().Target), Builder(cgm.getModule().getContext()), - DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), + DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), CXXThisDecl(0) { LLVMIntTy = ConvertType(getContext().IntTy); LLVMPointerWidth = Target.getPointerWidth(0); @@ -41,7 +41,7 @@ ASTContext &CodeGenFunction::getContext() const { llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { llvm::BasicBlock *&BB = LabelMap[S]; if (BB) return BB; - + // Create, but don't insert, the new block. return BB = createBasicBlock(S->getName()); } @@ -69,7 +69,7 @@ bool CodeGenFunction::hasAggregateLLVMType(QualType T) { // FIXME: Use positive checks instead of negative ones to be more robust in // the face of extension. return !T->hasPointerRepresentation() && !T->isRealType() && - !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() && + !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() && !T->isBlockPointerType() && !T->isMemberPointerType(); } @@ -95,7 +95,7 @@ void CodeGenFunction::EmitReturnBlock() { // branch then we can just put the code in that block instead. This // cleans up functions which started with a unified return block. if (ReturnBlock->hasOneUse()) { - llvm::BranchInst *BI = + llvm::BranchInst *BI = dyn_cast(*ReturnBlock->use_begin()); if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { // Reset insertion point and delete the branch. @@ -123,8 +123,8 @@ void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { "did not remove all blocks from block scope map!"); assert(CleanupEntries.empty() && "mismatched push/pop in cleanup stack!"); - - // Emit function epilog (to return). + + // Emit function epilog (to return). EmitReturnBlock(); // Emit debug descriptor for function end. @@ -141,7 +141,7 @@ void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { Ptr->eraseFromParent(); } -void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, +void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, llvm::Function *Fn, const FunctionArgList &Args, SourceLocation StartLoc) { @@ -161,14 +161,14 @@ void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, EntryBB); if (Builder.isNamePreserving()) AllocaInsertPt->setName("allocapt"); - + ReturnBlock = createBasicBlock("return"); ReturnValue = 0; if (!RetTy->isVoidType()) ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); - + Builder.SetInsertPoint(EntryBB); - + // Emit subprogram debug descriptor. // FIXME: The cast here is a huge hack. if (CGDebugInfo *DI = getDebugInfo()) { @@ -177,9 +177,9 @@ void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder); } else { // Just use LLVM function name. - + // FIXME: Remove unnecessary conversion to std::string when API settles. - DI->EmitFunctionStart(std::string(Fn->getName()).c_str(), + DI->EmitFunctionStart(std::string(Fn->getName()).c_str(), RetTy, CurFn, Builder); } } @@ -187,7 +187,7 @@ void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, // FIXME: Leaked. CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); EmitFunctionProlog(*CurFnInfo, CurFn, Args); - + // If any of the arguments have a variably modified type, make sure to // emit the type size. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); @@ -204,27 +204,27 @@ void CodeGenFunction::GenerateCode(const FunctionDecl *FD, // Check if we should generate debug info for this function. if (CGM.getDebugInfo() && !FD->hasAttr()) DebugInfo = CGM.getDebugInfo(); - + FunctionArgList Args; - + if (const CXXMethodDecl *MD = dyn_cast(FD)) { if (MD->isInstance()) { // Create the implicit 'this' decl. // FIXME: I'm not entirely sure I like using a fake decl just for code // generation. Maybe we can come up with a better way? CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), - &getContext().Idents.get("this"), + &getContext().Idents.get("this"), MD->getThisType(getContext())); Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); } } - + if (FD->getNumParams()) { const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType(); assert(FProto && "Function def must have prototype!"); for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) - Args.push_back(std::make_pair(FD->getParamDecl(i), + Args.push_back(std::make_pair(FD->getParamDecl(i), FProto->getArgType(i))); } @@ -238,9 +238,9 @@ void CodeGenFunction::GenerateCode(const FunctionDecl *FD, EmitDtorEpilogue(DD); FinishFunction(S->getRBracLoc()); } - else + else if (const CXXConstructorDecl *CD = dyn_cast(FD)) { - const CXXRecordDecl *ClassDecl = + const CXXRecordDecl *ClassDecl = cast(CD->getDeclContext()); (void) ClassDecl; if (CD->isCopyConstructor(getContext())) { @@ -259,7 +259,7 @@ void CodeGenFunction::GenerateCode(const FunctionDecl *FD, else if (const CXXMethodDecl *MD = dyn_cast(FD)) if (MD->isCopyAssignment()) SynthesizeCXXCopyAssignment(MD, FD, Fn, Args); - + // Destroy the 'this' declaration. if (CXXThisDecl) CXXThisDecl->Destroy(getContext()); @@ -271,27 +271,27 @@ void CodeGenFunction::GenerateCode(const FunctionDecl *FD, bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { // Null statement, not a label! if (S == 0) return false; - + // If this is a label, we have to emit the code, consider something like: // if (0) { ... foo: bar(); } goto foo; if (isa(S)) return true; - + // If this is a case/default statement, and we haven't seen a switch, we have // to emit the code. if (isa(S) && !IgnoreCaseStmts) return true; - + // If this is a switch statement, we want to ignore cases below it. if (isa(S)) IgnoreCaseStmts = true; - + // Scan subexpressions for verboten labels. for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); I != E; ++I) if (ContainsLabel(*I, IgnoreCaseStmts)) return true; - + return false; } @@ -304,13 +304,13 @@ int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { // FIXME: Rename and handle conversion of other evaluatable things // to bool. Expr::EvalResult Result; - if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || + if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || Result.HasSideEffects) return 0; // Not foldable, not integer or not fully evaluatable. - + if (CodeGenFunction::ContainsLabel(Cond)) return 0; // Contains a label. - + return Result.Val.getInt().getBoolValue() ? 1 : -1; } @@ -326,7 +326,7 @@ void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); if (const CastExpr *E = dyn_cast(Cond)) if (E->getCastKind() == CastExpr::CK_UserDefinedConversion) { - if (const CXXFunctionalCastExpr *CXXFExpr = + if (const CXXFunctionalCastExpr *CXXFExpr = dyn_cast(E)) { EmitCXXFunctionalCastExpr(CXXFExpr); return; @@ -335,7 +335,7 @@ void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, return EmitBranchOnBoolExpr(E->getSubExpr(), TrueBlock, FalseBlock); assert(false && "EmitBranchOnBoolExpr - Expected CStyleCastExpr"); } - + if (const BinaryOperator *CondBOp = dyn_cast(Cond)) { // Handle X && Y in a condition. if (CondBOp->getOpcode() == BinaryOperator::LAnd) { @@ -345,20 +345,20 @@ void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, // br(1 && X) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); } - + // If we have "X && 1", simplify the code to use an uncond branch. // "X && 0" would have been constant folded to 0. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { // br(X && 1) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); } - + // Emit the LHS as a conditional. If the LHS conditional is false, we // want to jump to the FalseBlock. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); EmitBlock(LHSTrue); - + EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); return; } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { @@ -368,31 +368,31 @@ void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, // br(0 || X) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); } - + // If we have "X || 0", simplify the code to use an uncond branch. // "X || 1" would have been constant folded to 1. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { // br(X || 0) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); } - + // Emit the LHS as a conditional. If the LHS conditional is true, we // want to jump to the TrueBlock. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); EmitBlock(LHSFalse); - + EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); return; } } - + if (const UnaryOperator *CondUOp = dyn_cast(Cond)) { // br(!x, t, f) -> br(x, f, t) if (CondUOp->getOpcode() == UnaryOperator::LNot) return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); } - + if (const ConditionalOperator *CondOp = dyn_cast(Cond)) { // Handle ?: operator. @@ -438,25 +438,25 @@ void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { // Don't bother emitting a zero-byte memset. if (TypeInfo.first == 0) return; - + // FIXME: Handle variable sized types. - const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, + const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, LLVMPointerWidth); Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)), // TypeInfo.first describes size in bits. llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), TypeInfo.second/8)); } void CodeGenFunction::EmitIndirectSwitches() { llvm::BasicBlock *Default; - + if (IndirectSwitches.empty()) return; - + if (!LabelIDs.empty()) { Default = getBasicBlockForLabel(LabelIDs.begin()->first); } else { @@ -469,20 +469,20 @@ void CodeGenFunction::EmitIndirectSwitches() { for (std::vector::iterator i = IndirectSwitches.begin(), e = IndirectSwitches.end(); i != e; ++i) { llvm::SwitchInst *I = *i; - + I->setSuccessor(0, Default); - for (std::map::iterator LI = LabelIDs.begin(), + for (std::map::iterator LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) { I->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), - LI->second), + LI->second), getBasicBlockForLabel(LI->first)); } - } + } } llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; - + assert(SizeEntry && "Did not emit size for type"); return SizeEntry; } @@ -490,15 +490,15 @@ llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { assert(Ty->isVariablyModifiedType() && "Must pass variably modified type to EmitVLASizes!"); - + EnsureInsertPoint(); - + if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; - + if (!SizeEntry) { const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); - + // Get the element size; QualType ElemTy = VAT->getElementType(); llvm::Value *ElemSize; @@ -507,21 +507,21 @@ llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { else ElemSize = llvm::ConstantInt::get(SizeTy, getContext().getTypeSize(ElemTy) / 8); - + llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); - + SizeEntry = Builder.CreateMul(ElemSize, NumElements); } - + return SizeEntry; } - + if (const ArrayType *AT = dyn_cast(Ty)) { EmitVLASize(AT->getElementType()); return 0; - } - + } + const PointerType *PT = Ty->getAs(); assert(PT && "unknown VM type!"); EmitVLASize(PT->getPointeeType()); @@ -535,32 +535,29 @@ llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { return EmitLValue(E).getAddress(); } -void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) -{ +void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) { CleanupEntries.push_back(CleanupEntry(CleanupBlock)); } -void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) -{ - assert(CleanupEntries.size() >= OldCleanupStackSize && +void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { + assert(CleanupEntries.size() >= OldCleanupStackSize && "Cleanup stack mismatch!"); - + while (CleanupEntries.size() > OldCleanupStackSize) EmitCleanupBlock(); } -CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() -{ +CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { CleanupEntry &CE = CleanupEntries.back(); - + llvm::BasicBlock *CleanupBlock = CE.CleanupBlock; - + std::vector Blocks; std::swap(Blocks, CE.Blocks); - + std::vector BranchFixups; std::swap(BranchFixups, CE.BranchFixups); - + CleanupEntries.pop_back(); // Check if any branch fixups pointed to the scope we just popped. If so, @@ -568,12 +565,12 @@ CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); BlockScopeMap::iterator I = BlockScopes.find(Dest); - + if (I == BlockScopes.end()) continue; - + assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); - + if (I->second == CleanupEntries.size()) { // We don't need to do this branch fixup. BranchFixups[i] = BranchFixups.back(); @@ -583,29 +580,29 @@ CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() continue; } } - + llvm::BasicBlock *SwitchBlock = 0; llvm::BasicBlock *EndBlock = 0; if (!BranchFixups.empty()) { SwitchBlock = createBasicBlock("cleanup.switch"); EndBlock = createBasicBlock("cleanup.end"); - + llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); - + Builder.SetInsertPoint(SwitchBlock); - llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), + llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), "cleanup.dst"); llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); - + // Create a switch instruction to determine where to jump next. - llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, + llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, BranchFixups.size()); // Restore the current basic block (if any) if (CurBB) { Builder.SetInsertPoint(CurBB); - + // If we had a current basic block, we also need to emit an instruction // to initialize the cleanup destination. Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)), @@ -616,13 +613,13 @@ CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { llvm::BranchInst *BI = BranchFixups[i]; llvm::BasicBlock *Dest = BI->getSuccessor(0); - + // Fixup the branch instruction to point to the cleanup block. BI->setSuccessor(0, CleanupBlock); - + if (CleanupEntries.empty()) { llvm::ConstantInt *ID; - + // Check if we already have a destination for this block. if (Dest == SI->getDefaultDest()) ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); @@ -631,24 +628,24 @@ CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() if (!ID) { // No code found, get a new unique one by using the number of // switch successors. - ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), + ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), SI->getNumSuccessors()); SI->addCase(ID, Dest); } } - + // Store the jump destination before the branch instruction. new llvm::StoreInst(ID, DestCodePtr, BI); } else { // We need to jump through another cleanup block. Create a pad block // with a branch instruction that jumps to the final destination and // add it as a branch fixup to the current cleanup scope. - + // Create the pad block. llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); // Create a unique case ID. - llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), + llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), SI->getNumSuccessors()); // Store the jump destination before the branch instruction. @@ -656,89 +653,86 @@ CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() // Add it as the destination. SI->addCase(ID, CleanupPad); - + // Create the branch to the final destination. llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); CleanupPad->getInstList().push_back(BI); - + // And add it as a branch fixup. CleanupEntries.back().BranchFixups.push_back(BI); } } } - + // Remove all blocks from the block scope map. for (size_t i = 0, e = Blocks.size(); i != e; ++i) { assert(BlockScopes.count(Blocks[i]) && "Did not find block in scope map!"); - + BlockScopes.erase(Blocks[i]); } - + return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock); } -void CodeGenFunction::EmitCleanupBlock() -{ +void CodeGenFunction::EmitCleanupBlock() { CleanupBlockInfo Info = PopCleanupBlock(); - + llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); - if (CurBB && !CurBB->getTerminator() && + if (CurBB && !CurBB->getTerminator() && Info.CleanupBlock->getNumUses() == 0) { CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); delete Info.CleanupBlock; - } else + } else EmitBlock(Info.CleanupBlock); - + if (Info.SwitchBlock) EmitBlock(Info.SwitchBlock); if (Info.EndBlock) EmitBlock(Info.EndBlock); } -void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) -{ - assert(!CleanupEntries.empty() && +void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { + assert(!CleanupEntries.empty() && "Trying to add branch fixup without cleanup block!"); - + // FIXME: We could be more clever here and check if there's already a branch // fixup for this destination and recycle it. CleanupEntries.back().BranchFixups.push_back(BI); } -void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) -{ +void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { if (!HaveInsertPoint()) return; - + llvm::BranchInst* BI = Builder.CreateBr(Dest); - + Builder.ClearInsertionPoint(); - + // The stack is empty, no need to do any cleanup. if (CleanupEntries.empty()) return; - + if (!Dest->getParent()) { // We are trying to branch to a block that hasn't been inserted yet. AddBranchFixup(BI); return; } - + BlockScopeMap::iterator I = BlockScopes.find(Dest); if (I == BlockScopes.end()) { // We are trying to jump to a block that is outside of any cleanup scope. AddBranchFixup(BI); return; } - + assert(I->second < CleanupEntries.size() && "Trying to branch into cleanup region"); - + if (I->second == CleanupEntries.size() - 1) { // We have a branch to a block in the same scope. return; } - + AddBranchFixup(BI); } diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h index 063ebf92de2b479c3cd5fb4c6185fd37e1f54236..0fac947efe19d80b547626246bf46a9da10f395d 100644 --- a/clang/lib/CodeGen/CodeGenFunction.h +++ b/clang/lib/CodeGen/CodeGenFunction.h @@ -166,20 +166,20 @@ public: /// this behavior for branches? void EmitBranchThroughCleanup(llvm::BasicBlock *Dest); - /// PushConditionalTempDestruction - Should be called before a conditional + /// PushConditionalTempDestruction - Should be called before a conditional /// part of an expression is emitted. For example, before the RHS of the /// expression below is emitted: - /// + /// /// b && f(T()); /// /// This is used to make sure that any temporaryes created in the conditional /// branch are only destroyed if the branch is taken. void PushConditionalTempDestruction(); - - /// PopConditionalTempDestruction - Should be called after a conditional + + /// PopConditionalTempDestruction - Should be called after a conditional /// part of an expression has been emitted. void PopConditionalTempDestruction(); - + private: CGDebugInfo* DebugInfo; @@ -261,37 +261,37 @@ private: /// CXXThisDecl - When parsing an C++ function, this will hold the implicit /// 'this' declaration. ImplicitParamDecl *CXXThisDecl; - + /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary. struct CXXLiveTemporaryInfo { /// Temporary - The live temporary. const CXXTemporary *Temporary; - + /// ThisPtr - The pointer to the temporary. llvm::Value *ThisPtr; - + /// DtorBlock - The destructor block. llvm::BasicBlock *DtorBlock; - + /// CondPtr - If this is a conditional temporary, this is the pointer to /// the condition variable that states whether the destructor should be /// called or not. llvm::Value *CondPtr; - + CXXLiveTemporaryInfo(const CXXTemporary *temporary, llvm::Value *thisptr, llvm::BasicBlock *dtorblock, llvm::Value *condptr) - : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock), + : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock), CondPtr(condptr) { } }; - + llvm::SmallVector LiveTemporaries; - /// ConditionalTempDestructionStack - Contains the number of live temporaries + /// ConditionalTempDestructionStack - Contains the number of live temporaries /// when PushConditionalTempDestruction was called. This is used so that /// we know how many temporaries were created by a certain expression. llvm::SmallVector ConditionalTempDestructionStack; - + public: CodeGenFunction(CodeGenModule &cgm); @@ -368,32 +368,32 @@ public: bool Extern, int64_t nv, int64_t v); void EmitCtorPrologue(const CXXConstructorDecl *CD); - + void SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, const FunctionDecl *FD, llvm::Function *Fn, const FunctionArgList &Args); - + void SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, const FunctionDecl *FD, llvm::Function *Fn, const FunctionArgList &Args); - + void SynthesizeDefaultConstructor(const CXXConstructorDecl *CD, const FunctionDecl *FD, llvm::Function *Fn, const FunctionArgList &Args); - + void SynthesizeDefaultDestructor(const CXXDestructorDecl *CD, const FunctionDecl *FD, llvm::Function *Fn, const FunctionArgList &Args); - + /// EmitDtorEpilogue - Emit all code that comes at the end of class's - /// destructor. This is to call destructors on members and base classes + /// destructor. This is to call destructors on members and base classes /// in reverse order of their construction. void EmitDtorEpilogue(const CXXDestructorDecl *DD); - + /// EmitFunctionProlog - Emit the target specific LLVM code to load the /// arguments for the given function. This is also responsible for naming the /// LLVM function arguments. @@ -559,42 +559,42 @@ public: /// LoadCXXThis - Load the value of 'this'. This function is only valid while /// generating code for an C++ member function. llvm::Value *LoadCXXThis(); - + /// AddressCXXOfBaseClass - This function will add the necessary delta /// to the load of 'this' and returns address of the base class. - // FIXME. This currently only does a derived to non-virtual base conversion. + // FIXME. This currently only does a derived to non-virtual base conversion. // Other kinds of conversions will come later. llvm::Value *AddressCXXOfBaseClass(llvm::Value *ThisValue, - const CXXRecordDecl *ClassDecl, + const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl); - - void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue, + + void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue, const ArrayType *Array, const CXXRecordDecl *BaseClassDecl, QualType Ty); - void EmitClassAggrCopyAssignment(llvm::Value *DestValue, + void EmitClassAggrCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue, const ArrayType *Array, const CXXRecordDecl *BaseClassDecl, QualType Ty); void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue, - const CXXRecordDecl *ClassDecl, + const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl, QualType Ty); - + void EmitClassCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue, - const CXXRecordDecl *ClassDecl, + const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl, QualType Ty); - - void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, + + void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, llvm::Value *This, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd); - + void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, const ArrayType *Array, llvm::Value *This); @@ -602,16 +602,16 @@ public: void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, const ArrayType *Array, llvm::Value *This); - + void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, llvm::Value *This); - + void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr); void PopCXXTemporary(); - + llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); void EmitCXXDeleteExpr(const CXXDeleteExpr *E); - + //===--------------------------------------------------------------------===// // Declaration Emission //===--------------------------------------------------------------------===// @@ -621,7 +621,7 @@ public: /// This function can be called with a null (unreachable) insert point. void EmitDecl(const Decl &D); - /// EmitBlockVarDecl - Emit a block variable declaration. + /// EmitBlockVarDecl - Emit a block variable declaration. /// /// This function can be called with a null (unreachable) insert point. void EmitBlockVarDecl(const VarDecl &D); @@ -799,7 +799,7 @@ public: LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E); LValue EmitCXXConstructLValue(const CXXConstructExpr *E); LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); - + LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); @@ -822,13 +822,13 @@ public: llvm::Value *Callee, const CallArgList &Args, const Decl *TargetDecl = 0); - + RValue EmitCall(llvm::Value *Callee, QualType FnType, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd, const Decl *TargetDecl = 0); RValue EmitCallExpr(const CallExpr *E); - + llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This, const llvm::Type *Ty); RValue EmitCXXMemberCall(const CXXMethodDecl *MD, @@ -840,10 +840,10 @@ public: RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD); - + RValue EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E); - - RValue EmitBuiltinExpr(const FunctionDecl *FD, + + RValue EmitBuiltinExpr(const FunctionDecl *FD, unsigned BuiltinID, const CallExpr *E); RValue EmitBlockCallExpr(const CallExpr *E); @@ -873,7 +873,7 @@ public: /// expression. Will emit a temporary variable if E is not an LValue. RValue EmitReferenceBindingToExpr(const Expr* E, QualType DestType, bool IsInitializer = false); - + //===--------------------------------------------------------------------===// // Expression Emission //===--------------------------------------------------------------------===// @@ -946,20 +946,20 @@ public: /// with the C++ runtime so that its destructor will be called at exit. void EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor, llvm::Constant *DeclPtr); - - /// GenerateCXXGlobalInitFunc - Generates code for initializing global + + /// GenerateCXXGlobalInitFunc - Generates code for initializing global /// variables. void GenerateCXXGlobalInitFunc(llvm::Function *Fn, const VarDecl **Decls, unsigned NumDecls); - + void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E); - + RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, - llvm::Value *AggLoc = 0, + llvm::Value *AggLoc = 0, bool IsAggLocVolatile = false, bool IsInitializer = false); - + //===--------------------------------------------------------------------===// // Internal Helpers //===--------------------------------------------------------------------===// @@ -1004,7 +1004,7 @@ private: void ExpandTypeToArgs(QualType Ty, RValue Src, llvm::SmallVector &Args); - llvm::Value* EmitAsmInput(const AsmStmt &S, + llvm::Value* EmitAsmInput(const AsmStmt &S, const TargetInfo::ConstraintInfo &Info, const Expr *InputExpr, std::string &ConstraintStr); @@ -1017,9 +1017,9 @@ private: /// EmitCallArg - Emit a single call argument. RValue EmitCallArg(const Expr *E, QualType ArgType); - + /// EmitCallArgs - Emit call arguments for a function. - /// The CallArgTypeInfo parameter is used for iterating over the known + /// The CallArgTypeInfo parameter is used for iterating over the known /// argument types of the function being called. template void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, @@ -1034,21 +1034,21 @@ private: QualType ArgType = *I; assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). - getTypePtr() == - getContext().getCanonicalType(Arg->getType()).getTypePtr() && + getTypePtr() == + getContext().getCanonicalType(Arg->getType()).getTypePtr() && "type mismatch in call argument!"); - - Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), + + Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), ArgType)); } - - // Either we've emitted all the call args, or we have a call to a + + // Either we've emitted all the call args, or we have a call to a // variadic function. - assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && + assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && "Extra arguments in non-variadic function!"); - + } - + // If we still have any arguments, emit them using the type of the argument. for (; Arg != ArgEnd; ++Arg) { QualType ArgType = Arg->getType(); @@ -1057,7 +1057,7 @@ private: } } }; - + } // end namespace CodeGen } // end namespace clang diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 180a68659d521eecfb4c326dc4f0881234c3d749..fbd8521e19365ef9a61e7749b6ab214a7ff14e41 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -81,7 +81,7 @@ void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, bool OmitOnError) { if (OmitOnError && getDiags().hasErrorOccurred()) return; - unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, + unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, "cannot compile this %0 yet"); std::string Msg = Type; getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) @@ -94,13 +94,13 @@ void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, bool OmitOnError) { if (OmitOnError && getDiags().hasErrorOccurred()) return; - unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, + unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, "cannot compile this %0 yet"); std::string Msg = Type; getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; } -LangOptions::VisibilityMode +LangOptions::VisibilityMode CodeGenModule::getDeclVisibilityMode(const Decl *D) const { if (const VarDecl *VD = dyn_cast(D)) if (VD->getStorageClass() == VarDecl::PrivateExtern) @@ -109,7 +109,7 @@ CodeGenModule::getDeclVisibilityMode(const Decl *D) const { if (const VisibilityAttr *attr = D->getAttr()) { switch (attr->getVisibility()) { default: assert(0 && "Unknown visibility!"); - case VisibilityAttr::DefaultVisibility: + case VisibilityAttr::DefaultVisibility: return LangOptions::Default; case VisibilityAttr::HiddenVisibility: return LangOptions::Hidden; @@ -121,7 +121,7 @@ CodeGenModule::getDeclVisibilityMode(const Decl *D) const { return getLangOptions().getVisibilityMode(); } -void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, +void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const { // Internal definitions always have default visibility. if (GV->hasLocalLinkage()) { @@ -142,12 +142,12 @@ void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, const char *CodeGenModule::getMangledName(const GlobalDecl &GD) { const NamedDecl *ND = GD.getDecl(); - + if (const CXXConstructorDecl *D = dyn_cast(ND)) return getMangledCXXCtorName(D, GD.getCtorType()); if (const CXXDestructorDecl *D = dyn_cast(ND)) return getMangledCXXDtorName(D, GD.getDtorType()); - + return getMangledName(ND); } @@ -163,7 +163,7 @@ const char *CodeGenModule::getMangledName(const NamedDecl *ND) { assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); return ND->getNameAsCString(); } - + llvm::SmallString<256> Name; llvm::raw_svector_ostream Out(Name); if (!mangleName(ND, Context, Out)) { @@ -178,7 +178,7 @@ const char *CodeGenModule::getMangledName(const NamedDecl *ND) { const char *CodeGenModule::UniqueMangledName(const char *NameStart, const char *NameEnd) { assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!"); - + return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData(); } @@ -199,21 +199,21 @@ void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { // Ctor function type is void()*. llvm::FunctionType* CtorFTy = - llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), + llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), std::vector(), false); llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); // Get the type of a ctor entry, { i32, void ()* }. - llvm::StructType* CtorStructTy = - llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), + llvm::StructType* CtorStructTy = + llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), llvm::PointerType::getUnqual(CtorFTy), NULL); // Construct the constructor and destructor arrays. std::vector Ctors; for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { std::vector S; - S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), + S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), I->second, false)); S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); @@ -237,38 +237,38 @@ void CodeGenModule::EmitAnnotations() { llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), Annotations.size()), Annotations); - llvm::GlobalValue *gv = - new llvm::GlobalVariable(TheModule, Array->getType(), false, - llvm::GlobalValue::AppendingLinkage, Array, + llvm::GlobalValue *gv = + new llvm::GlobalVariable(TheModule, Array->getType(), false, + llvm::GlobalValue::AppendingLinkage, Array, "llvm.global.annotations"); gv->setSection("llvm.metadata"); } static CodeGenModule::GVALinkage -GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, +GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, const LangOptions &Features) { // The kind of external linkage this function will have, if it is not // inline or static. CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; - if (Context.getLangOptions().CPlusPlus && + if (Context.getLangOptions().CPlusPlus && FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) External = CodeGenModule::GVA_TemplateInstantiation; - + if (const CXXMethodDecl *MD = dyn_cast(FD)) { // C++ member functions defined inside the class are always inline. if (MD->isInline() || !MD->isOutOfLine()) return CodeGenModule::GVA_CXXInline; - + return External; } - + // "static" functions get internal linkage. if (FD->getStorageClass() == FunctionDecl::Static) return CodeGenModule::GVA_Internal; if (!FD->isInline()) return External; - + // If the inline function explicitly has the GNU inline attribute on it, or if // this is C89 mode, we use to GNU semantics. if (!Features.C99 && !Features.CPlusPlus) { @@ -291,7 +291,7 @@ GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, // have already handled "static inline" above, with the GVA_Internal case. if (Features.CPlusPlus) // inline and extern inline. return CodeGenModule::GVA_CXXInline; - + assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode"); if (FD->isC99InlineDefinition()) return CodeGenModule::GVA_C99Inline; @@ -335,7 +335,7 @@ void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, } void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, - const CGFunctionInfo &Info, + const CGFunctionInfo &Info, llvm::Function *F) { AttributeListType AttributeList; ConstructAttributeList(Info, D, AttributeList); @@ -354,16 +354,16 @@ void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F) { if (!Features.Exceptions && !Features.ObjCNonFragileABI) - F->addFnAttr(llvm::Attribute::NoUnwind); + F->addFnAttr(llvm::Attribute::NoUnwind); if (D->hasAttr()) F->addFnAttr(llvm::Attribute::AlwaysInline); - + if (D->hasAttr()) F->addFnAttr(llvm::Attribute::NoInline); } -void CodeGenModule::SetCommonAttributes(const Decl *D, +void CodeGenModule::SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV) { setGlobalVisibility(GV, D); @@ -390,19 +390,19 @@ void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, bool IsIncompleteFunction) { if (!IsIncompleteFunction) SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); - + // Only a few attributes are set on declarations; these may later be // overridden by a definition. - + if (FD->hasAttr()) { F->setLinkage(llvm::Function::DLLImportLinkage); - } else if (FD->hasAttr() || + } else if (FD->hasAttr() || FD->hasAttr()) { // "extern_weak" is overloaded in LLVM; we probably should have - // separate linkage types for this. + // separate linkage types for this. F->setLinkage(llvm::Function::ExternalWeakLinkage); } else { - F->setLinkage(llvm::Function::ExternalLinkage); + F->setLinkage(llvm::Function::ExternalLinkage); } if (const SectionAttr *SA = FD->getAttr()) @@ -410,7 +410,7 @@ void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, } void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { - assert(!GV->isDeclaration() && + assert(!GV->isDeclaration() && "Only globals with definition can force usage."); LLVMUsed.push_back(GV); } @@ -422,22 +422,22 @@ void CodeGenModule::EmitLLVMUsed() { llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); - + // Convert LLVMUsed to what ConstantArray needs. std::vector UsedArray; UsedArray.resize(LLVMUsed.size()); for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { - UsedArray[i] = - llvm::ConstantExpr::getBitCast(cast(&*LLVMUsed[i]), + UsedArray[i] = + llvm::ConstantExpr::getBitCast(cast(&*LLVMUsed[i]), i8PTy); } - + if (UsedArray.empty()) return; llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); - - llvm::GlobalVariable *GV = - new llvm::GlobalVariable(getModule(), ATy, false, + + llvm::GlobalVariable *GV = + new llvm::GlobalVariable(getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, llvm::ConstantArray::get(ATy, UsedArray), "llvm.used"); @@ -459,27 +459,27 @@ void CodeGenModule::EmitDeferred() { // just ignore the deferred decl. llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; assert(CGRef && "Deferred decl wasn't referenced?"); - + if (!CGRef->isDeclaration()) continue; - + // Otherwise, emit the definition and move on to the next one. EmitGlobalDefinition(D); } } -/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the +/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the /// annotation information for a given GlobalValue. The annotation struct is -/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the -/// GlobalValue being annotated. The second field is the constant string -/// created from the AnnotateAttr's annotation. The third field is a constant +/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the +/// GlobalValue being annotated. The second field is the constant string +/// created from the AnnotateAttr's annotation. The third field is a constant /// string containing the name of the translation unit. The fourth field is /// the line number in the file of the annotated value declaration. /// /// FIXME: this does not unique the annotation string constants, as llvm-gcc /// appears to. /// -llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, +llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, unsigned LineNo) { llvm::Module *M = &getModule(); @@ -488,7 +488,7 @@ llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, // which are the 2nd and 3rd elements of the global annotation structure. const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); - llvm::Constant *anno = llvm::ConstantArray::get(VMContext, + llvm::Constant *anno = llvm::ConstantArray::get(VMContext, AA->getAnnotation(), true); llvm::Constant *unit = llvm::ConstantArray::get(VMContext, M->getModuleIdentifier(), @@ -496,14 +496,14 @@ llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, // Get the two global values corresponding to the ConstantArrays we just // created to hold the bytes of the strings. - llvm::GlobalValue *annoGV = + llvm::GlobalValue *annoGV = new llvm::GlobalVariable(*M, anno->getType(), false, llvm::GlobalValue::PrivateLinkage, anno, GV->getName()); // translation unit name string, emitted into the llvm.metadata section. llvm::GlobalValue *unitGV = new llvm::GlobalVariable(*M, unit->getType(), false, - llvm::GlobalValue::PrivateLinkage, unit, + llvm::GlobalValue::PrivateLinkage, unit, ".str"); // Create the ConstantStruct for the global annotation. @@ -524,12 +524,12 @@ bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { if (const FunctionDecl *FD = dyn_cast(Global)) { // Constructors and destructors should never be deferred. - if (FD->hasAttr() || + if (FD->hasAttr() || FD->hasAttr()) return false; GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); - + // static, static inline, always_inline, and extern inline functions can // always be deferred. Normal inline functions can be deferred in C99/C++. if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || @@ -537,7 +537,7 @@ bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { return true; return false; } - + const VarDecl *VD = cast(Global); assert(VD->isFileVarDecl() && "Invalid decl"); @@ -546,7 +546,7 @@ bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { void CodeGenModule::EmitGlobal(GlobalDecl GD) { const ValueDecl *Global = GD.getDecl(); - + // If this is an alias definition (which otherwise looks like a declaration) // emit it now. if (Global->hasAttr()) @@ -563,7 +563,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) { // In C++, if this is marked "extern", defer code generation. if (getLangOptions().CPlusPlus && !VD->getInit() && - (VD->getStorageClass() == VarDecl::Extern || + (VD->getStorageClass() == VarDecl::Extern || VD->isExternC(getContext()))) return; @@ -595,7 +595,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) { void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { const ValueDecl *D = GD.getDecl(); - + if (const CXXConstructorDecl *CD = dyn_cast(D)) EmitCXXConstructor(CD, GD.getCtorType()); else if (const CXXDestructorDecl *DD = dyn_cast(D)) @@ -624,16 +624,16 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, if (Entry) { if (Entry->getType()->getElementType() == Ty) return Entry; - + // Make sure the result is of the correct type. const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); return llvm::ConstantExpr::getBitCast(Entry, PTy); } - + // This is the first use or definition of a mangled name. If there is a // deferred decl with this name, remember that we need to emit it at the end // of the file. - llvm::DenseMap::iterator DDI = + llvm::DenseMap::iterator DDI = DeferredDecls.find(MangledName); if (DDI != DeferredDecls.end()) { // Move the potentially referenced deferred decl to the DeferredDeclsToEmit @@ -649,20 +649,20 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, // A called constructor which has no definition or declaration need be // synthesized. else if (const CXXConstructorDecl *CD = dyn_cast(FD)) { - const CXXRecordDecl *ClassDecl = + const CXXRecordDecl *ClassDecl = cast(CD->getDeclContext()); if (CD->isCopyConstructor(getContext())) DeferredCopyConstructorToEmit(D); else if (!ClassDecl->hasUserDeclaredConstructor()) DeferredDeclsToEmit.push_back(D); } - else if (isa(FD)) + else if (isa(FD)) DeferredDestructorToEmit(D); else if (const CXXMethodDecl *MD = dyn_cast(FD)) if (MD->isCopyAssignment()) DeferredCopyAssignmentToEmit(D); } - + // This function doesn't have a complete type (for example, the return // type is an incomplete struct). Use a fake type instead, and make // sure not to try to set attributes. @@ -672,7 +672,7 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, std::vector(), false); IsIncompleteFunction = true; } - llvm::Function *F = llvm::Function::Create(cast(Ty), + llvm::Function *F = llvm::Function::Create(cast(Ty), llvm::Function::ExternalLinkage, "", &getModule()); F->setName(MangledName); @@ -685,13 +685,13 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, /// Defer definition of copy constructor(s) which need be implicitly defined. void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { - const CXXConstructorDecl *CD = + const CXXConstructorDecl *CD = cast(CopyCtorDecl.getDecl()); const CXXRecordDecl *ClassDecl = cast(CD->getDeclContext()); if (ClassDecl->hasTrivialCopyConstructor() || ClassDecl->hasUserDeclaredCopyConstructor()) return; - + // First make sure all direct base classes and virtual bases and non-static // data mebers which need to have their copy constructors implicitly defined // are defined. 12.8.p7 @@ -699,11 +699,11 @@ void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { Base != ClassDecl->bases_end(); ++Base) { CXXRecordDecl *BaseClassDecl = cast(Base->getType()->getAs()->getDecl()); - if (CXXConstructorDecl *BaseCopyCtor = + if (CXXConstructorDecl *BaseCopyCtor = BaseClassDecl->getCopyConstructor(Context, 0)) GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); } - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { @@ -715,7 +715,7 @@ void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { continue; CXXRecordDecl *FieldClassDecl = cast(FieldClassType->getDecl()); - if (CXXConstructorDecl *FieldCopyCtor = + if (CXXConstructorDecl *FieldCopyCtor = FieldClassDecl->getCopyConstructor(Context, 0)) GetAddrOfCXXConstructor(FieldCopyCtor, Ctor_Complete); } @@ -727,11 +727,11 @@ void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { void CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { const CXXMethodDecl *CD = cast(CopyAssignDecl.getDecl()); const CXXRecordDecl *ClassDecl = cast(CD->getDeclContext()); - + if (ClassDecl->hasTrivialCopyAssignment() || ClassDecl->hasUserDeclaredCopyAssignment()) return; - + // First make sure all direct base classes and virtual bases and non-static // data mebers which need to have their copy assignments implicitly defined // are defined. 12.8.p12 @@ -745,7 +745,7 @@ void CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { BaseClassDecl->hasConstCopyAssignment(getContext(), MD)) GetAddrOfFunction(GlobalDecl(MD), 0); } - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { @@ -764,7 +764,7 @@ void CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { GetAddrOfFunction(GlobalDecl(MD), 0); } } - DeferredDeclsToEmit.push_back(CopyAssignDecl); + DeferredDeclsToEmit.push_back(CopyAssignDecl); } void CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { @@ -778,11 +778,11 @@ void CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { Base != ClassDecl->bases_end(); ++Base) { CXXRecordDecl *BaseClassDecl = cast(Base->getType()->getAs()->getDecl()); - if (const CXXDestructorDecl *BaseDtor = + if (const CXXDestructorDecl *BaseDtor = BaseClassDecl->getDestructor(Context)) GetAddrOfCXXDestructor(BaseDtor, Dtor_Complete); } - + for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), FieldEnd = ClassDecl->field_end(); Field != FieldEnd; ++Field) { @@ -794,7 +794,7 @@ void CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { continue; CXXRecordDecl *FieldClassDecl = cast(FieldClassType->getDecl()); - if (const CXXDestructorDecl *FieldDtor = + if (const CXXDestructorDecl *FieldDtor = FieldClassDecl->getDestructor(Context)) GetAddrOfCXXDestructor(FieldDtor, Dtor_Complete); } @@ -839,15 +839,15 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, if (Entry) { if (Entry->getType() == Ty) return Entry; - + // Make sure the result is of the correct type. return llvm::ConstantExpr::getBitCast(Entry, Ty); } - + // This is the first use or definition of a mangled name. If there is a // deferred decl with this name, remember that we need to emit it at the end // of the file. - llvm::DenseMap::iterator DDI = + llvm::DenseMap::iterator DDI = DeferredDecls.find(MangledName); if (DDI != DeferredDecls.end()) { // Move the potentially referenced deferred decl to the DeferredDeclsToEmit @@ -855,11 +855,11 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, DeferredDeclsToEmit.push_back(DDI->second); DeferredDecls.erase(DDI); } - - llvm::GlobalVariable *GV = - new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, + + llvm::GlobalVariable *GV = + new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, llvm::GlobalValue::ExternalLinkage, - 0, "", 0, + 0, "", 0, false, Ty->getAddressSpace()); GV->setName(MangledName); @@ -873,13 +873,13 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, if (D->getStorageClass() == VarDecl::PrivateExtern) GV->setVisibility(llvm::GlobalValue::HiddenVisibility); - if (D->hasAttr() || + if (D->hasAttr() || D->hasAttr()) GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); GV->setThreadLocal(D->isThreadSpecified()); } - + return Entry = GV; } @@ -894,8 +894,8 @@ llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, QualType ASTTy = D->getType(); if (Ty == 0) Ty = getTypes().ConvertTypeForMem(ASTTy); - - const llvm::PointerType *PTy = + + const llvm::PointerType *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); } @@ -931,7 +931,7 @@ void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { llvm::Constant *Init = 0; QualType ASTTy = D->getType(); - + if (D->getInit() == 0) { // This is a tentative definition; tentative definitions are // implicitly initialized with { 0 }. @@ -946,7 +946,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { Init = EmitNullConstant(D->getType()); } else { Init = EmitConstantExpr(D->getInit(), D->getType()); - + if (!Init) { QualType T = D->getInit()->getType(); if (getLangOptions().CPlusPlus) { @@ -961,7 +961,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { const llvm::Type* InitType = Init->getType(); llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); - + // Strip off a bitcast if we got one back. if (llvm::ConstantExpr *CE = dyn_cast(Entry)) { assert(CE->getOpcode() == llvm::Instruction::BitCast || @@ -969,10 +969,10 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { CE->getOpcode() == llvm::Instruction::GetElementPtr); Entry = CE->getOperand(0); } - + // Entry is now either a Function or GlobalVariable. llvm::GlobalVariable *GV = dyn_cast(Entry); - + // We have a definition after a declaration with the wrong type. // We must make a new GlobalVariable* and update everything that used OldGV // (a declaration or tentative definition) with the new GlobalVariable* @@ -985,7 +985,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { if (GV == 0 || GV->getType()->getElementType() != InitType || GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { - + // Remove the old entry from GlobalDeclMap so that we'll create a new one. GlobalDeclMap.erase(getMangledName(D)); @@ -994,7 +994,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { GV->takeName(cast(Entry)); // Replace all uses of the old global with the new global - llvm::Constant *NewPtrForOldDecl = + llvm::Constant *NewPtrForOldDecl = llvm::ConstantExpr::getBitCast(GV, Entry->getType()); Entry->replaceAllUsesWith(NewPtrForOldDecl); @@ -1017,7 +1017,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { // members, it cannot be declared "LLVM const". GV->setConstant(true); } - + GV->setAlignment(getContext().getDeclAlignInBytes(D)); // Set the llvm linkage type as appropriate. @@ -1064,7 +1064,7 @@ static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, // If we're redefining a global as a function, don't transform it. llvm::Function *OldFn = dyn_cast(Old); if (OldFn == 0) return; - + const llvm::Type *NewRetTy = NewFn->getReturnType(); llvm::SmallVector ArgList; @@ -1074,7 +1074,7 @@ static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, unsigned OpNo = UI.getOperandNo(); llvm::CallInst *CI = dyn_cast(*UI++); if (!CI || OpNo != 0) continue; - + // If the return types don't match exactly, and if the call isn't dead, then // we can't transform this call. if (CI->getType() != NewRetTy && !CI->use_empty()) @@ -1095,7 +1095,7 @@ static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, } if (DontTransform) continue; - + // Okay, we can transform this. Create the new call instruction and copy // over the required information. ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); @@ -1118,21 +1118,21 @@ static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { const llvm::FunctionType *Ty; const FunctionDecl *D = cast(GD.getDecl()); - + if (const CXXMethodDecl *MD = dyn_cast(D)) { bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic(); - + Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic); } else { Ty = cast(getTypes().ConvertType(D->getType())); - + // As a special case, make sure that definitions of K&R function // "type foo()" aren't declared as varargs (which forces the backend // to do unnecessary work). if (D->getType()->isFunctionNoProtoType()) { assert(Ty->isVarArg() && "Didn't lower type as expected"); - // Due to stret, the lowered function could have arguments. - // Just create the same type as was lowered by ConvertType + // Due to stret, the lowered function could have arguments. + // Just create the same type as was lowered by ConvertType // but strip off the varargs bit. std::vector Args(Ty->param_begin(), Ty->param_end()); Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); @@ -1141,17 +1141,17 @@ void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { // Get or create the prototype for the function. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); - + // Strip off a bitcast if we got one back. if (llvm::ConstantExpr *CE = dyn_cast(Entry)) { assert(CE->getOpcode() == llvm::Instruction::BitCast); Entry = CE->getOperand(0); } - - + + if (cast(Entry)->getType()->getElementType() != Ty) { llvm::GlobalValue *OldFn = cast(Entry); - + // If the types mismatch then we have to rewrite the definition. assert(OldFn->isDeclaration() && "Shouldn't replace non-declaration"); @@ -1167,7 +1167,7 @@ void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { GlobalDeclMap.erase(getMangledName(D)); llvm::Function *NewFn = cast(GetAddrOfFunction(GD, Ty)); NewFn->takeName(OldFn); - + // If this is an implementation of a function without a prototype, try to // replace any existing uses of the function (which may be calls) with uses // of the new function @@ -1175,27 +1175,27 @@ void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); OldFn->removeDeadConstantUsers(); } - + // Replace uses of F with the Function we will endow with a body. if (!Entry->use_empty()) { - llvm::Constant *NewPtrForOldDecl = + llvm::Constant *NewPtrForOldDecl = llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); Entry->replaceAllUsesWith(NewPtrForOldDecl); } - + // Ok, delete the old function now, which is dead. OldFn->eraseFromParent(); - + Entry = NewFn; } - + llvm::Function *Fn = cast(Entry); CodeGenFunction(*this).GenerateCode(D, Fn); SetFunctionDefinitionAttributes(D, Fn); SetLLVMFunctionAttributesForDefinition(D, Fn); - + if (const ConstructorAttr *CA = D->getAttr()) AddGlobalCtor(Fn, CA->getPriority()); if (const DestructorAttr *DA = D->getAttr()) @@ -1207,7 +1207,7 @@ void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { assert(AA && "Not an alias?"); const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); - + // Unique the name through the identifier table. const char *AliaseeName = AA->getAliasee().c_str(); AliaseeName = getContext().Idents.get(AliaseeName).getName(); @@ -1222,22 +1222,22 @@ void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { llvm::PointerType::getUnqual(DeclTy), 0); // Create the new alias itself, but don't set a name yet. - llvm::GlobalValue *GA = + llvm::GlobalValue *GA = new llvm::GlobalAlias(Aliasee->getType(), llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); - + // See if there is already something with the alias' name in the module. const char *MangledName = getMangledName(D); llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; - + if (Entry && !Entry->isDeclaration()) { // If there is a definition in the module, then it wins over the alias. // This is dubious, but allow it to be safe. Just ignore the alias. GA->eraseFromParent(); return; } - + if (Entry) { // If there is a declaration in the module, then we had an extern followed // by the alias, as in: @@ -1246,12 +1246,12 @@ void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { // int test6() __attribute__((alias("test7"))); // // Remove it and replace uses of it with the alias. - + Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, Entry->getType())); Entry->eraseFromParent(); } - + // Now we know that there is no conflict, set the name. Entry = GA; GA->setName(MangledName); @@ -1267,7 +1267,7 @@ void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { } else { GA->setLinkage(llvm::Function::DLLExportLinkage); } - } else if (D->hasAttr() || + } else if (D->hasAttr() || D->hasAttr()) { GA->setLinkage(llvm::Function::WeakAnyLinkage); } @@ -1279,20 +1279,20 @@ void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { /// "__builtin_fabsf", return a Function* for "fabsf". llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || - Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && + Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && "isn't a lib fn"); - + // Get the name, skip over the __builtin_ prefix (if necessary). const char *Name = Context.BuiltinInfo.GetName(BuiltinID); if (Context.BuiltinInfo.isLibFunction(BuiltinID)) Name += 10; - + // Get the type for the builtin. ASTContext::GetBuiltinTypeError Error; QualType Type = Context.GetBuiltinType(BuiltinID, Error); assert(Error == ASTContext::GE_None && "Can't get builtin type"); - const llvm::FunctionType *Ty = + const llvm::FunctionType *Ty = cast(getTypes().ConvertType(Type)); // Unique the name through the identifier table. @@ -1336,7 +1336,7 @@ GetConstantCFStringEntry(llvm::StringMap &Map, // Check for simple case. if (!Literal->containsNonAsciiOrNull()) { StringLength = NumBytes; - return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), + return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), StringLength)); } @@ -1344,18 +1344,18 @@ GetConstantCFStringEntry(llvm::StringMap &Map, llvm::SmallVector ToBuf(NumBytes); const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); UTF16 *ToPtr = &ToBuf[0]; - - ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, + + ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, ToPtr + NumBytes, strictConversion); - + // Check for conversion failure. if (Result != conversionOK) { // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove // this duplicate code. assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); StringLength = NumBytes; - return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), + return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), StringLength)); } @@ -1391,41 +1391,41 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { unsigned StringLength = 0; bool isUTF16 = false; llvm::StringMapEntry &Entry = - GetConstantCFStringEntry(CFConstantStringMap, Literal, + GetConstantCFStringEntry(CFConstantStringMap, Literal, getTargetData().isLittleEndian(), isUTF16, StringLength); - + if (llvm::Constant *C = Entry.getValue()) return C; - + llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); llvm::Constant *Zeros[] = { Zero, Zero }; - + // If we don't already have it, get __CFConstantStringClassReference. if (!CFConstantStringClassRef) { const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); Ty = llvm::ArrayType::get(Ty, 0); - llvm::Constant *GV = CreateRuntimeVariable(Ty, + llvm::Constant *GV = CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); // Decay array -> ptr CFConstantStringClassRef = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); } - + QualType CFTy = getContext().getCFConstantStringType(); - const llvm::StructType *STy = + const llvm::StructType *STy = cast(getTypes().ConvertType(CFTy)); std::vector Fields(4); // Class pointer. Fields[0] = CFConstantStringClassRef; - + // Flags. const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); - Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : + Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : llvm::ConstantInt::get(Ty, 0x07C8); // String pointer. @@ -1449,30 +1449,30 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { // are following gcc here. isConstant = true; } - llvm::GlobalVariable *GV = - new llvm::GlobalVariable(getModule(), C->getType(), isConstant, + llvm::GlobalVariable *GV = + new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, Prefix); if (Sect) GV->setSection(Sect); if (isUTF16) { unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8; - GV->setAlignment(Align); + GV->setAlignment(Align); } Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); // String length. Ty = getTypes().ConvertType(getContext().LongTy); Fields[3] = llvm::ConstantInt::get(Ty, StringLength); - + // The struct. C = llvm::ConstantStruct::get(STy, Fields); - GV = new llvm::GlobalVariable(getModule(), C->getType(), true, - llvm::GlobalVariable::PrivateLinkage, C, + GV = new llvm::GlobalVariable(getModule(), C->getType(), true, + llvm::GlobalVariable::PrivateLinkage, C, "_unnamed_cfstring_"); if (const char *Sect = getContext().Target.getCFStringSection()) GV->setSection(Sect); Entry.setValue(GV); - + return GV; } @@ -1485,16 +1485,16 @@ std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { const ConstantArrayType *CAT = getContext().getAsConstantArrayType(E->getType()); assert(CAT && "String isn't pointer or array!"); - + // Resize the string to the right size. std::string Str(StrData, StrData+Len); uint64_t RealLen = CAT->getSize().getZExtValue(); - + if (E->isWide()) RealLen *= getContext().Target.getWCharWidth()/8; - + Str.resize(RealLen, '\0'); - + return Str; } @@ -1518,16 +1518,16 @@ CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { /// GenerateWritableString -- Creates storage for a string literal. -static llvm::Constant *GenerateStringLiteral(const std::string &str, +static llvm::Constant *GenerateStringLiteral(const std::string &str, bool constant, CodeGenModule &CGM, const char *GlobalName) { // Create Constant for this string literal. Don't add a '\0'. llvm::Constant *C = llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); - + // Create a global variable for this string - return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, + return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, llvm::GlobalValue::PrivateLinkage, C, GlobalName); } @@ -1551,8 +1551,8 @@ llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, // Don't share any string literals if strings aren't constant. if (!IsConstant) return GenerateStringLiteral(str, false, *this, GlobalName); - - llvm::StringMapEntry &Entry = + + llvm::StringMapEntry &Entry = ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); if (Entry.getValue()) @@ -1574,12 +1574,12 @@ llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, /// EmitObjCPropertyImplementations - Emit information for synthesized /// properties for an implementation. -void CodeGenModule::EmitObjCPropertyImplementations(const +void CodeGenModule::EmitObjCPropertyImplementations(const ObjCImplementationDecl *D) { - for (ObjCImplementationDecl::propimpl_iterator + for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { ObjCPropertyImplDecl *PID = *i; - + // Dynamic is just for type-checking. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { ObjCPropertyDecl *PD = PID->getPropertyDecl(); @@ -1631,7 +1631,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { // Ignore dependent declarations. if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) return; - + switch (D->getKind()) { case Decl::CXXConversion: case Decl::CXXMethod: @@ -1639,9 +1639,9 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { // Skip function templates if (cast(D)->getDescribedFunctionTemplate()) return; - + // Fall through - + case Decl::Var: EmitGlobal(GlobalDecl(cast(D))); break; @@ -1668,7 +1668,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { break; // Objective-C Decls - + // Forward declarations, no (immediate) code generation. case Decl::ObjCClass: case Decl::ObjCForwardProtocol: @@ -1691,7 +1691,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { EmitObjCPropertyImplementations(OMD); Runtime->GenerateClass(OMD); break; - } + } case Decl::ObjCMethod: { ObjCMethodDecl *OMD = cast(D); // If this is not a prototype, emit the body. @@ -1699,7 +1699,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { CodeGenFunction(*this).GenerateObjCMethod(OMD); break; } - case Decl::ObjCCompatibleAlias: + case Decl::ObjCCompatibleAlias: // compatibility-alias is a directive and has no code gen. break; @@ -1711,7 +1711,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { FileScopeAsmDecl *AD = cast(D); std::string AsmString(AD->getAsmString()->getStrData(), AD->getAsmString()->getByteLength()); - + const std::string &S = getModule().getModuleInlineAsm(); if (S.empty()) getModule().setModuleInlineAsm(AsmString); @@ -1719,8 +1719,8 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { getModule().setModuleInlineAsm(S + '\n' + AsmString); break; } - - default: + + default: // Make sure we handled everything we should, every other kind is a // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind // function. Need to recode Decl::Kind to do that easily. diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h index 2aa97de2b0919e4e70a8297831e5603ad1a799d0..607f2a172c2c7e53e19eb811dffef87f1e8d2887 100644 --- a/clang/lib/CodeGen/CodeGenModule.h +++ b/clang/lib/CodeGen/CodeGenModule.h @@ -73,32 +73,32 @@ namespace CodeGen { // a regular VarDecl or a FunctionDecl. class GlobalDecl { llvm::PointerIntPair Value; - + public: GlobalDecl() {} - + explicit GlobalDecl(const ValueDecl *VD) : Value(VD, 0) { assert(!isa(VD) && "Use other ctor with ctor decls!"); assert(!isa(VD) && "Use other ctor with dtor decls!"); } - GlobalDecl(const CXXConstructorDecl *D, CXXCtorType Type) + GlobalDecl(const CXXConstructorDecl *D, CXXCtorType Type) : Value(D, Type) {} GlobalDecl(const CXXDestructorDecl *D, CXXDtorType Type) : Value(D, Type) {} - + const ValueDecl *getDecl() const { return Value.getPointer(); } - + CXXCtorType getCtorType() const { assert(isa(getDecl()) && "Decl is not a ctor!"); return static_cast(Value.getInt()); } - + CXXDtorType getDtorType() const { assert(isa(getDecl()) && "Decl is not a dtor!"); return static_cast(Value.getInt()); } }; - + /// CodeGenModule - This class organizes the cross-function state that is used /// while generating LLVM code. class CodeGenModule : public BlockModule { @@ -176,11 +176,11 @@ class CodeGenModule : public BlockModule { /// CXXGlobalInits - Variables with global initializers that need to run /// before main. std::vector CXXGlobalInits; - + /// CFConstantStringClassRef - Cached reference to the class for constant /// strings. This value has type int * but is actually an Obj-C class pointer. llvm::Constant *CFConstantStringClassRef; - + llvm::LLVMContext &VMContext; public: CodeGenModule(ASTContext &C, const CompileOptions &CompileOpts, @@ -255,7 +255,7 @@ public: /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant /// array for the given ObjCEncodeExpr node. llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); - + /// GetAddrOfConstantString - Returns a pointer to a character array /// containing the literal. This contents are exactly that of the given /// string, i.e. it will not be null terminated automatically; see @@ -280,14 +280,14 @@ public: /// GetAddrOfCXXConstructor - Return the address of the constructor of the /// given type. - llvm::Function *GetAddrOfCXXConstructor(const CXXConstructorDecl *D, + llvm::Function *GetAddrOfCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); /// GetAddrOfCXXDestructor - Return the address of the constructor of the /// given type. - llvm::Function *GetAddrOfCXXDestructor(const CXXDestructorDecl *D, + llvm::Function *GetAddrOfCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); - + /// getBuiltinLibFunction - Given a builtin id for a function like /// "__builtin_fabsf", return a Function* for "fabsf". llvm::Value *getBuiltinLibFunction(unsigned BuiltinID); @@ -378,9 +378,9 @@ public: const char *getMangledName(const GlobalDecl &D); const char *getMangledName(const NamedDecl *ND); - const char *getMangledCXXCtorName(const CXXConstructorDecl *D, + const char *getMangledCXXCtorName(const CXXConstructorDecl *D, CXXCtorType Type); - const char *getMangledCXXDtorName(const CXXDestructorDecl *D, + const char *getMangledCXXDtorName(const CXXDestructorDecl *D, CXXDtorType Type); void EmitTentativeDefinition(const VarDecl *D); @@ -392,12 +392,12 @@ public: GVA_StrongExternal, GVA_TemplateInstantiation }; - + private: /// UniqueMangledName - Unique a name by (if necessary) inserting it into the /// MangledNames string map. const char *UniqueMangledName(const char *NameStart, const char *NameEnd); - + llvm::Constant *GetOrCreateLLVMFunction(const char *MangledName, const llvm::Type *Ty, GlobalDecl D); @@ -407,7 +407,7 @@ private: void DeferredCopyConstructorToEmit(GlobalDecl D); void DeferredCopyAssignmentToEmit(GlobalDecl D); void DeferredDestructorToEmit(GlobalDecl D); - + /// SetCommonAttributes - Set attributes which are common to any /// form of a global definition (alias, Objective-C method, /// function, global variable). @@ -416,9 +416,9 @@ private: void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); /// SetFunctionDefinitionAttributes - Set attributes for a global definition. - void SetFunctionDefinitionAttributes(const FunctionDecl *D, + void SetFunctionDefinitionAttributes(const FunctionDecl *D, llvm::GlobalValue *GV); - + /// SetFunctionAttributes - Set function attributes for a function /// declaration. void SetFunctionAttributes(const FunctionDecl *FD, @@ -437,29 +437,29 @@ private: void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); // C++ related functions. - + void EmitNamespace(const NamespaceDecl *D); void EmitLinkageSpec(const LinkageSpecDecl *D); /// EmitCXXConstructors - Emit constructors (base, complete) from a /// C++ constructor Decl. void EmitCXXConstructors(const CXXConstructorDecl *D); - + /// EmitCXXConstructor - Emit a single constructor with the given type from /// a C++ constructor Decl. void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); - - /// EmitCXXDestructors - Emit destructors (base, complete) from a + + /// EmitCXXDestructors - Emit destructors (base, complete) from a /// C++ destructor Decl. void EmitCXXDestructors(const CXXDestructorDecl *D); - + /// EmitCXXDestructor - Emit a single destructor with the given type from /// a C++ destructor Decl. void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); - + /// EmitCXXGlobalInitFunc - Emit a function that initializes C++ globals. void EmitCXXGlobalInitFunc(); - + // FIXME: Hardcoding priority here is gross. void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); diff --git a/clang/lib/CodeGen/CodeGenTypes.cpp b/clang/lib/CodeGen/CodeGenTypes.cpp index 48f8192094c80375027c954354dd2bd0a5d28636..94db8366654846702cfe57d792ab2dcf042ffda6 100644 --- a/clang/lib/CodeGen/CodeGenTypes.cpp +++ b/clang/lib/CodeGen/CodeGenTypes.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This is the code that handles AST -> LLVM type lowering. +// This is the code that handles AST -> LLVM type lowering. // //===----------------------------------------------------------------------===// @@ -34,8 +34,8 @@ CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M, } CodeGenTypes::~CodeGenTypes() { - for(llvm::DenseMap::iterator - I = CGRecordLayouts.begin(), E = CGRecordLayouts.end(); + for (llvm::DenseMap::iterator + I = CGRecordLayouts.begin(), E = CGRecordLayouts.end(); I != E; ++I) delete I->second; CGRecordLayouts.clear(); @@ -65,7 +65,7 @@ const llvm::Type *CodeGenTypes::ConvertType(QualType T) { const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) { T = Context.getCanonicalType(T); - + // See if type is already cached. llvm::DenseMap::iterator I = TypeCache.find(T.getTypePtr()); @@ -75,7 +75,7 @@ const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) { return I->second.get(); const llvm::Type *ResultType = ConvertNewType(T); - TypeCache.insert(std::make_pair(T.getTypePtr(), + TypeCache.insert(std::make_pair(T.getTypePtr(), llvm::PATypeHolder(ResultType))); return ResultType; } @@ -94,15 +94,15 @@ const llvm::Type *CodeGenTypes::ConvertTypeForMemRecursive(QualType T) { /// memory representation is usually i8 or i32, depending on the target. const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) { const llvm::Type *R = ConvertType(T); - + // If this is a non-bool type, don't map it. if (R != llvm::Type::getInt1Ty(getLLVMContext())) return R; - + // Otherwise, return an integer of the target-specified size. return llvm::IntegerType::get(getLLVMContext(), (unsigned)Context.getTypeSize(T)); - + } // Code to verify a given function type is complete, i.e. the return type @@ -124,15 +124,15 @@ static const TagType *VerifyFuncTypeComplete(const Type* T) { /// replace the 'opaque' type we previously made for it if applicable. void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { const Type *Key = Context.getTagDeclType(TD).getTypePtr(); - llvm::DenseMap::iterator TDTI = + llvm::DenseMap::iterator TDTI = TagDeclTypes.find(Key); if (TDTI == TagDeclTypes.end()) return; - + // Remember the opaque LLVM type for this tagdecl. llvm::PATypeHolder OpaqueHolder = TDTI->second; assert(isa(OpaqueHolder.get()) && "Updating compilation of an already non-opaque type?"); - + // Remove it from TagDeclTypes so that it will be regenerated. TagDeclTypes.erase(TDTI); @@ -163,7 +163,7 @@ void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { } } -static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext, +static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext, const llvm::fltSemantics &format) { if (&format == &llvm::APFloat::IEEEsingle) return llvm::Type::getFloatTy(VMContext); @@ -181,7 +181,7 @@ static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext, const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { const clang::Type &Ty = *Context.getCanonicalType(T); - + switch (Ty.getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) @@ -204,7 +204,7 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { case BuiltinType::Bool: // Note that we always return bool as i1 for use as a scalar type. return llvm::Type::getInt1Ty(getLLVMContext()); - + case BuiltinType::Char_S: case BuiltinType::Char_U: case BuiltinType::SChar: @@ -222,13 +222,13 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { case BuiltinType::Char32: return llvm::IntegerType::get(getLLVMContext(), static_cast(Context.getTypeSize(T))); - + case BuiltinType::Float: case BuiltinType::Double: case BuiltinType::LongDouble: - return getTypeForFormat(getLLVMContext(), + return getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T)); - + case BuiltinType::UInt128: case BuiltinType::Int128: return llvm::IntegerType::get(getLLVMContext(), 128); @@ -236,10 +236,10 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { break; } case Type::FixedWidthInt: - return llvm::IntegerType::get(getLLVMContext(), + return llvm::IntegerType::get(getLLVMContext(), cast(T)->getWidth()); case Type::Complex: { - const llvm::Type *EltTy = + const llvm::Type *EltTy = ConvertTypeRecursive(cast(Ty).getElementType()); return llvm::StructType::get(TheModule.getContext(), EltTy, EltTy, NULL); } @@ -258,7 +258,7 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { PointersToResolve.push_back(std::make_pair(ETy, PointeeType)); return llvm::PointerType::get(PointeeType, ETy.getAddressSpace()); } - + case Type::VariableArray: { const VariableArrayType &A = cast(Ty); assert(A.getIndexTypeQualifier() == 0 && @@ -305,7 +305,7 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { const FunctionNoProtoType *FNPT = cast(&Ty); return GetFunctionType(getFunctionInfo(FNPT), true); } - + case Type::ExtQual: return ConvertTypeRecursive(QualType(cast(Ty).getBaseType(), 0)); @@ -319,12 +319,12 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { T = llvm::OpaqueType::get(getLLVMContext()); return T; } - + case Type::ObjCObjectPointer: { // Protocol qualifications do not influence the LLVM type, we just return a // pointer to the underlying interface type. We don't need to worry about // recursive conversion. - const llvm::Type *T = + const llvm::Type *T = ConvertTypeRecursive(cast(Ty).getPointeeType()); return llvm::PointerType::getUnqual(T); } @@ -333,10 +333,10 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { case Type::Enum: { const TagDecl *TD = cast(Ty).getDecl(); const llvm::Type *Res = ConvertTagDeclType(TD); - + std::string TypeName(TD->getKindName()); TypeName += '.'; - + // Name the codegen type after the typedef name // if there is no tag type name available if (TD->getIdentifier()) @@ -345,8 +345,8 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { TypeName += TdT->getDecl()->getNameAsString(); else TypeName += "anon"; - - TheModule.addTypeName(TypeName, Res); + + TheModule.addTypeName(TypeName, Res); return Res; } @@ -365,7 +365,7 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { QualType ETy = cast(Ty).getPointeeType(); if (ETy->isFunctionType()) { return llvm::StructType::get(TheModule.getContext(), - ConvertType(Context.getPointerDiffType()), + ConvertType(Context.getPointerDiffType()), ConvertType(Context.getPointerDiffType()), NULL); } else @@ -375,7 +375,7 @@ const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { case Type::TemplateSpecialization: assert(false && "Dependent types can't get here"); } - + // FIXME: implement. return llvm::OpaqueType::get(getLLVMContext()); } @@ -395,18 +395,18 @@ const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) { } } } - + // TagDecl's are not necessarily unique, instead use the (clang) // type connected to the decl. - const Type *Key = + const Type *Key = Context.getTagDeclType(TD).getTypePtr(); - llvm::DenseMap::iterator TDTI = + llvm::DenseMap::iterator TDTI = TagDeclTypes.find(Key); - + // If we've already compiled this tag type, use the previous definition. if (TDTI != TagDeclTypes.end()) return TDTI->second; - + // If this is still a forward definition, just define an opaque type to use // for this tagged decl. if (!TD->isDefinition()) { @@ -414,14 +414,14 @@ const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) { TagDeclTypes.insert(std::make_pair(Key, ResultType)); return ResultType; } - + // Okay, this is a definition of a type. Compile the implementation now. - + if (TD->isEnum()) { // Don't bother storing enums in TagDeclTypes. return ConvertTypeRecursive(cast(TD)->getIntegerType()); } - + // This decl could well be recursive. In this case, insert an opaque // definition of this type, which the recursive uses will get. We will then // refine this opaque version later. @@ -430,30 +430,30 @@ const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) { // type. This will later be refined to the actual type. llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(getLLVMContext()); TagDeclTypes.insert(std::make_pair(Key, ResultHolder)); - + const llvm::Type *ResultType; const RecordDecl *RD = cast(TD); // Layout fields. - CGRecordLayout *Layout = + CGRecordLayout *Layout = CGRecordLayoutBuilder::ComputeLayout(*this, RD); - + CGRecordLayouts[Key] = Layout; ResultType = Layout->getLLVMType(); - + // Refine our Opaque type to ResultType. This can invalidate ResultType, so // make sure to read the result out of the holder. cast(ResultHolder.get()) ->refineAbstractTypeTo(ResultType); - + return ResultHolder.get(); -} +} /// getLLVMFieldNo - Return llvm::StructType element number /// that corresponds to the field FD. unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) { assert(!FD->isBitField() && "Don't use getLLVMFieldNo on bit fields!"); - + llvm::DenseMap::iterator I = FieldInfo.find(FD); assert (I != FieldInfo.end() && "Unable to find field info"); return I->second; @@ -481,11 +481,11 @@ void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned FieldNo, /// getCGRecordLayout - Return record layout info for the given llvm::Type. const CGRecordLayout & CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const { - const Type *Key = + const Type *Key = Context.getTagDeclType(TD).getTypePtr(); llvm::DenseMap::iterator I = CGRecordLayouts.find(Key); - assert (I != CGRecordLayouts.end() + assert (I != CGRecordLayouts.end() && "Unable to find record layout information for type"); return *I->second; } diff --git a/clang/lib/CodeGen/CodeGenTypes.h b/clang/lib/CodeGen/CodeGenTypes.h index f8df1b429ba39134667022b91c7ac8602734e46b..0e73d481cd86f739d0251690754c70d943342058 100644 --- a/clang/lib/CodeGen/CodeGenTypes.h +++ b/clang/lib/CodeGen/CodeGenTypes.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This is the code that handles AST -> LLVM type lowering. +// This is the code that handles AST -> LLVM type lowering. // //===----------------------------------------------------------------------===// @@ -49,20 +49,20 @@ namespace clang { namespace CodeGen { class CodeGenTypes; - /// CGRecordLayout - This class handles struct and union layout info while + /// CGRecordLayout - This class handles struct and union layout info while /// lowering AST types to LLVM types. class CGRecordLayout { CGRecordLayout(); // DO NOT IMPLEMENT - + /// LLVMType - The LLVMType corresponding to this record layout. const llvm::Type *LLVMType; - + /// ContainsMemberPointer - Whether one of the fields in this record layout /// is a member pointer, or a struct that contains a member pointer. bool ContainsMemberPointer; - + public: - CGRecordLayout(const llvm::Type *T, bool ContainsMemberPointer) + CGRecordLayout(const llvm::Type *T, bool ContainsMemberPointer) : LLVMType(T), ContainsMemberPointer(ContainsMemberPointer) { } /// getLLVMType - Return llvm type associated with this record. @@ -73,9 +73,9 @@ namespace CodeGen { bool containsMemberPointer() const { return ContainsMemberPointer; } - + }; - + /// CodeGenTypes - This class organizes the cross-module state that is used /// while lowering AST types to LLVM types. class CodeGenTypes { @@ -84,7 +84,7 @@ class CodeGenTypes { llvm::Module& TheModule; const llvm::TargetData& TheTargetData; mutable const ABIInfo* TheABIInfo; - + llvm::SmallVector, 8> PointersToResolve; @@ -98,9 +98,9 @@ class CodeGenTypes { /// types are never refined. llvm::DenseMap InterfaceTypes; - /// CGRecordLayouts - This maps llvm struct type with corresponding - /// record layout info. - /// FIXME : If CGRecordLayout is less than 16 bytes then use + /// CGRecordLayouts - This maps llvm struct type with corresponding + /// record layout info. + /// FIXME : If CGRecordLayout is less than 16 bytes then use /// inline it in the map. llvm::DenseMap CGRecordLayouts; @@ -113,8 +113,8 @@ class CodeGenTypes { public: struct BitFieldInfo { - BitFieldInfo(unsigned FieldNo, - unsigned Start, + BitFieldInfo(unsigned FieldNo, + unsigned Start, unsigned Size) : FieldNo(FieldNo), Start(Start), Size(Size) {} @@ -128,7 +128,7 @@ private: /// TypeCache - This map keeps cache of llvm::Types (through PATypeHolder) /// and maps llvm::Types to corresponding clang::Type. llvm::PATypeHolder is - /// used instead of llvm::Type because it allows us to bypass potential + /// used instead of llvm::Type because it allows us to bypass potential /// dangling type pointers due to type refinement on llvm side. llvm::DenseMap TypeCache; @@ -140,17 +140,17 @@ private: public: CodeGenTypes(ASTContext &Ctx, llvm::Module &M, const llvm::TargetData &TD); ~CodeGenTypes(); - + const llvm::TargetData &getTargetData() const { return TheTargetData; } TargetInfo &getTarget() const { return Target; } ASTContext &getContext() const { return Context; } const ABIInfo &getABIInfo() const; llvm::LLVMContext &getLLVMContext() { return TheModule.getContext(); } - /// ConvertType - Convert type T into a llvm::Type. + /// ConvertType - Convert type T into a llvm::Type. const llvm::Type *ConvertType(QualType T); const llvm::Type *ConvertTypeRecursive(QualType T); - + /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from /// ConvertType in that it is used to convert to the memory representation for /// a type. For example, the scalar representation for _Bool is i1, but the @@ -161,20 +161,20 @@ public: /// GetFunctionType - Get the LLVM function type for \arg Info. const llvm::FunctionType *GetFunctionType(const CGFunctionInfo &Info, bool IsVariadic); - + const CGRecordLayout &getCGRecordLayout(const TagDecl*) const; - + /// getLLVMFieldNo - Return llvm::StructType element number /// that corresponds to the field FD. unsigned getLLVMFieldNo(const FieldDecl *FD); - + /// UpdateCompletedType - When we find the full definition for a TagDecl, /// replace the 'opaque' type we previously made for it if applicable. void UpdateCompletedType(const TagDecl *TD); /// getFunctionInfo - Get the CGFunctionInfo for this function signature. - const CGFunctionInfo &getFunctionInfo(QualType RetTy, - const llvm::SmallVector + const CGFunctionInfo &getFunctionInfo(QualType RetTy, + const llvm::SmallVector &ArgTys); const CGFunctionInfo &getFunctionInfo(const FunctionNoProtoType *FTNP); @@ -182,12 +182,12 @@ public: const CGFunctionInfo &getFunctionInfo(const FunctionDecl *FD); const CGFunctionInfo &getFunctionInfo(const CXXMethodDecl *MD); const CGFunctionInfo &getFunctionInfo(const ObjCMethodDecl *MD); - const CGFunctionInfo &getFunctionInfo(QualType ResTy, + const CGFunctionInfo &getFunctionInfo(QualType ResTy, const CallArgList &Args); public: - const CGFunctionInfo &getFunctionInfo(QualType ResTy, + const CGFunctionInfo &getFunctionInfo(QualType ResTy, const FunctionArgList &Args); - + public: // These are internal details of CGT that shouldn't be used externally. /// addFieldInfo - Assign field number to field FD. void addFieldInfo(const FieldDecl *FD, unsigned FieldNo); diff --git a/clang/lib/CodeGen/Mangle.cpp b/clang/lib/CodeGen/Mangle.cpp index 04bd52b8d4b86dbf7ebe7dd55357e5d748cb5946..f9495b81b32e856b228bf0436b5ec0ae33762512 100644 --- a/clang/lib/CodeGen/Mangle.cpp +++ b/clang/lib/CodeGen/Mangle.cpp @@ -34,7 +34,7 @@ namespace { const CXXMethodDecl *Structor; unsigned StructorType; CXXCtorType CtorType; - + public: CXXNameMangler(ASTContext &C, llvm::raw_ostream &os) : Context(C), Out(os), Structor(0), StructorType(0) { } @@ -46,7 +46,7 @@ namespace { int64_t nv_t, int64_t v_t, int64_t nv_r, int64_t v_r); void mangleGuardVariable(const VarDecl *D); - + void mangleCXXVtable(QualType Type); void mangleCXXRtti(QualType Type); void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type); @@ -54,7 +54,7 @@ namespace { private: bool mangleFunctionDecl(const FunctionDecl *FD); - + void mangleFunctionEncoding(const FunctionDecl *FD); void mangleName(const NamedDecl *ND); void mangleUnqualifiedName(const NamedDecl *ND); @@ -78,19 +78,19 @@ namespace { void mangleExpression(Expr *E); void mangleCXXCtorType(CXXCtorType T); void mangleCXXDtorType(CXXDtorType T); - + void mangleTemplateArgumentList(const TemplateArgumentList &L); void mangleTemplateArgument(const TemplateArgument &A); }; } static bool isInCLinkageSpecification(const Decl *D) { - for (const DeclContext *DC = D->getDeclContext(); + for (const DeclContext *DC = D->getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { - if (const LinkageSpecDecl *Linkage = dyn_cast(DC)) + if (const LinkageSpecDecl *Linkage = dyn_cast(DC)) return Linkage->getLanguage() == LinkageSpecDecl::lang_c; } - + return false; } @@ -101,12 +101,12 @@ bool CXXNameMangler::mangleFunctionDecl(const FunctionDecl *FD) { // C functions are not mangled, and "main" is never mangled. if (!Context.getLangOptions().CPlusPlus || FD->isMain(Context)) return false; - - // No mangling in an "implicit extern C" header. + + // No mangling in an "implicit extern C" header. if (FD->getLocation().isValid() && Context.getSourceManager().isInExternCSystemHeader(FD->getLocation())) return false; - + // No name mangling in a C linkage specification. if (isInCLinkageSpecification(FD)) return false; @@ -127,7 +127,7 @@ bool CXXNameMangler::mangle(const NamedDecl *D) { Out << ALA->getLabel(); return true; } - + // ::= _Z // ::= // ::= @@ -135,36 +135,36 @@ bool CXXNameMangler::mangle(const NamedDecl *D) { // FIXME: Actually use a visitor to decode these? if (const FunctionDecl *FD = dyn_cast(D)) return mangleFunctionDecl(FD); - + if (const VarDecl *VD = dyn_cast(D)) { if (!Context.getLangOptions().CPlusPlus || isInCLinkageSpecification(D) || D->getDeclContext()->isTranslationUnit()) return false; - + Out << "_Z"; mangleName(VD); return true; } - + return false; } -void CXXNameMangler::mangleCXXCtor(const CXXConstructorDecl *D, +void CXXNameMangler::mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type) { assert(!Structor && "Structor already set!"); Structor = D; StructorType = Type; - + mangle(D); } -void CXXNameMangler::mangleCXXDtor(const CXXDestructorDecl *D, +void CXXNameMangler::mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type) { assert(!Structor && "Structor already set!"); Structor = D; StructorType = Type; - + mangle(D); } @@ -180,9 +180,8 @@ void CXXNameMangler::mangleCXXRtti(QualType T) { mangleType(T); } -void CXXNameMangler::mangleGuardVariable(const VarDecl *D) -{ - // ::= GV # Guard variable for one-time +void CXXNameMangler::mangleGuardVariable(const VarDecl *D) { + // ::= GV # Guard variable for one-time // # initialization Out << "_ZGV"; @@ -192,14 +191,14 @@ void CXXNameMangler::mangleGuardVariable(const VarDecl *D) void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) { // ::= mangleName(FD); - + // Whether the mangling of a function type includes the return type depends on // the context and the nature of the function. The rules for deciding whether // the return type is included are: - // + // // 1. Template functions (names or types) have return types encoded, with // the exceptions listed below. - // 2. Function types not appearing as part of a function name mangling, + // 2. Function types not appearing as part of a function name mangling, // e.g. parameters, pointer types, etc., have return type encoded, with the // exceptions listed below. // 3. Non-template function names do not have return types encoded. @@ -233,7 +232,7 @@ void CXXNameMangler::mangleName(const NamedDecl *ND) { // // ::= // ::= St # ::std:: - if (ND->getDeclContext()->isTranslationUnit()) + if (ND->getDeclContext()->isTranslationUnit()) mangleUnqualifiedName(ND); else if (isStdNamespace(ND->getDeclContext())) { Out << "St"; @@ -298,8 +297,8 @@ void CXXNameMangler::mangleThunk(const FunctionDecl *FD, int64_t nv, void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND) { // ::= - // ::= - // ::= + // ::= + // ::= DeclarationName Name = ND->getDeclName(); switch (Name.getNameKind()) { case DeclarationName::Identifier: @@ -335,7 +334,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND) { break; case DeclarationName::CXXConversionFunctionName: - // ::= cv # (cast) + // ::= cv # (cast) Out << "cv"; mangleType(Context.getCanonicalType(Name.getCXXNameType())); break; @@ -349,9 +348,9 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND) { assert(false && "Can't mangle a using directive name!"); break; } - + if (const FunctionDecl *Function = dyn_cast(ND)) { - if (const TemplateArgumentList *TemplateArgs + if (const TemplateArgumentList *TemplateArgs = Function->getTemplateSpecializationArgs()) mangleTemplateArgumentList(*TemplateArgs); } @@ -379,7 +378,7 @@ void CXXNameMangler::mangleNestedName(const NamedDecl *ND) { void CXXNameMangler::mangleLocalName(const NamedDecl *ND) { // := Z E [] // := Z E s [] - // := _ + // := _ Out << 'Z'; mangleFunctionEncoding(cast(ND->getDeclContext())); Out << 'E'; @@ -399,7 +398,7 @@ void CXXNameMangler::manglePrefix(const DeclContext *DC) { if (const NamespaceDecl *Namespace = dyn_cast(DC)) mangleSourceName(Namespace->getIdentifier()); else if (const RecordDecl *Record = dyn_cast(DC)) { - if (const ClassTemplateSpecializationDecl *D = + if (const ClassTemplateSpecializationDecl *D = dyn_cast(Record)) { mangleType(QualType(D->getTypeForDecl(), 0)); } else @@ -407,7 +406,7 @@ void CXXNameMangler::manglePrefix(const DeclContext *DC) { } } -void +void CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { switch (OO) { // ::= nw # new @@ -503,13 +502,13 @@ CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { case OO_None: case OO_Conditional: case NUM_OVERLOADED_OPERATORS: - assert(false && "Not an overloaded operator"); + assert(false && "Not an overloaded operator"); break; } } void CXXNameMangler::mangleCVQualifiers(unsigned Quals) { - // ::= [r] [V] [K] # restrict (C99), volatile, const + // ::= [r] [V] [K] # restrict (C99), volatile, const if (Quals & QualType::Restrict) Out << 'r'; if (Quals & QualType::Volatile) @@ -595,7 +594,7 @@ void CXXNameMangler::mangleType(const BuiltinType *T) { case BuiltinType::Overload: case BuiltinType::Dependent: - assert(false && + assert(false && "Overloaded and dependent types shouldn't get to name mangling"); break; case BuiltinType::UndeducedAuto: @@ -631,9 +630,9 @@ void CXXNameMangler::mangleBareFunctionType(const FunctionType *T, Out << 'v'; return; } - + for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), - ArgEnd = Proto->arg_type_end(); + ArgEnd = Proto->arg_type_end(); Arg != ArgEnd; ++Arg) mangleType(*Arg); @@ -643,7 +642,7 @@ void CXXNameMangler::mangleBareFunctionType(const FunctionType *T, } // ::= -// ::= +// ::= void CXXNameMangler::mangleType(const EnumType *T) { mangleType(static_cast(T)); } @@ -655,9 +654,9 @@ void CXXNameMangler::mangleType(const TagType *T) { mangleName(T->getDecl()->getTypedefForAnonDecl()); else mangleName(T->getDecl()); - + // If this is a class template specialization, mangle the template arguments. - if (ClassTemplateSpecializationDecl *Spec + if (ClassTemplateSpecializationDecl *Spec = dyn_cast(T->getDecl())) mangleTemplateArgumentList(Spec->getTemplateArgs()); } @@ -695,7 +694,7 @@ void CXXNameMangler::mangleType(const MemberPointerType *T) { if (const FunctionProtoType *FPT = dyn_cast(PointeeType)) { mangleCVQualifiers(FPT->getTypeQuals()); mangleType(FPT); - } else + } else mangleType(PointeeType); } @@ -825,18 +824,18 @@ void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { void CXXNameMangler::mangleTemplateArgumentList(const TemplateArgumentList &L) { // ::= I + E Out << "I"; - + for (unsigned i = 0, e = L.size(); i != e; ++i) { const TemplateArgument &A = L[i]; - + mangleTemplateArgument(A); } - + Out << "E"; } void CXXNameMangler::mangleTemplateArgument(const TemplateArgument &A) { - // ::= # type or template + // ::= # type or template // ::= X E # expression // ::= # simple expressions // ::= I * E # argument pack @@ -851,9 +850,9 @@ void CXXNameMangler::mangleTemplateArgument(const TemplateArgument &A) { // ::= L E # integer literal Out << 'L'; - + mangleType(A.getIntegralType()); - + const llvm::APSInt *Integral = A.getAsIntegral(); if (A.getIntegralType()->isBooleanType()) { // Boolean values are encoded as 0/1. @@ -863,7 +862,7 @@ void CXXNameMangler::mangleTemplateArgument(const TemplateArgument &A) { Out << 'n'; Integral->abs().print(Out, false); } - + Out << 'E'; break; } @@ -878,21 +877,21 @@ namespace clang { /// and this routine will return false. In this case, the caller should just /// emit the identifier of the declaration (\c D->getIdentifier()) as its /// name. - bool mangleName(const NamedDecl *D, ASTContext &Context, + bool mangleName(const NamedDecl *D, ASTContext &Context, llvm::raw_ostream &os) { assert(!isa(D) && "Use mangleCXXCtor for constructor decls!"); assert(!isa(D) && "Use mangleCXXDtor for destructor decls!"); - + CXXNameMangler Mangler(Context, os); if (!Mangler.mangle(D)) return false; - + os.flush(); return true; } - + /// \brief Mangles the a thunk with the offset n for the declaration D and /// emits that name to the given output stream. void mangleThunk(const FunctionDecl *FD, int64_t nv, int64_t v, @@ -902,12 +901,12 @@ namespace clang { "Use mangleCXXCtor for constructor decls!"); assert(!isa(FD) && "Use mangleCXXDtor for destructor decls!"); - + CXXNameMangler Mangler(Context, os); Mangler.mangleThunk(FD, nv, v); os.flush(); } - + /// \brief Mangles the a covariant thunk for the declaration D and emits that /// name to the given output stream. void mangleCovariantThunk(const FunctionDecl *FD, int64_t nv_t, int64_t v_t, @@ -918,12 +917,12 @@ namespace clang { "Use mangleCXXCtor for constructor decls!"); assert(!isa(FD) && "Use mangleCXXDtor for destructor decls!"); - + CXXNameMangler Mangler(Context, os); Mangler.mangleCovariantThunk(FD, nv_t, v_t, nv_r, v_r); os.flush(); } - + /// mangleGuardVariable - Returns the mangled name for a guard variable /// for the passed in VarDecl. void mangleGuardVariable(const VarDecl *D, ASTContext &Context, @@ -933,20 +932,20 @@ namespace clang { os.flush(); } - + void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, ASTContext &Context, llvm::raw_ostream &os) { CXXNameMangler Mangler(Context, os); Mangler.mangleCXXCtor(D, Type); - + os.flush(); } - + void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, ASTContext &Context, llvm::raw_ostream &os) { CXXNameMangler Mangler(Context, os); Mangler.mangleCXXDtor(D, Type); - + os.flush(); } diff --git a/clang/lib/CodeGen/Mangle.h b/clang/lib/CodeGen/Mangle.h index 855839170ed24f219c8101834218640e7c14ede5..16f1ae6d3fb296e74a9a924b2c289d0aabd27790 100644 --- a/clang/lib/CodeGen/Mangle.h +++ b/clang/lib/CodeGen/Mangle.h @@ -32,8 +32,8 @@ namespace clang { class FunctionDecl; class NamedDecl; class VarDecl; - - bool mangleName(const NamedDecl *D, ASTContext &Context, + + bool mangleName(const NamedDecl *D, ASTContext &Context, llvm::raw_ostream &os); void mangleThunk(const FunctionDecl *FD, int64_t n, int64_t vn, ASTContext &Context, llvm::raw_ostream &os); @@ -51,4 +51,4 @@ namespace clang { ASTContext &Context, llvm::raw_ostream &os); } -#endif +#endif diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp b/clang/lib/CodeGen/ModuleBuilder.cpp index 600271f7d89f8060ca3469c282edfa98df834e7c..c8f686a06f50b84f965cb5589ca7948b594896d2 100644 --- a/clang/lib/CodeGen/ModuleBuilder.cpp +++ b/clang/lib/CodeGen/ModuleBuilder.cpp @@ -40,27 +40,27 @@ namespace { CodeGeneratorImpl(Diagnostic &diags, const std::string& ModuleName, const CompileOptions &CO, llvm::LLVMContext& C) : Diags(diags), CompileOpts(CO), M(new llvm::Module(ModuleName, C)) {} - + virtual ~CodeGeneratorImpl() {} - + virtual llvm::Module* GetModule() { return M.get(); } - + virtual llvm::Module* ReleaseModule() { return M.take(); } - + virtual void Initialize(ASTContext &Context) { Ctx = &Context; - + M->setTargetTriple(Ctx->Target.getTriple().getTriple()); M->setDataLayout(Ctx->Target.getTargetDescription()); TD.reset(new llvm::TargetData(Ctx->Target.getTargetDescription())); Builder.reset(new CodeGen::CodeGenModule(Context, CompileOpts, *M, *TD, Diags)); } - + virtual void HandleTopLevelDecl(DeclGroupRef DG) { // Make sure to emit all elements of a Decl. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) @@ -94,7 +94,7 @@ namespace { }; } -CodeGenerator *clang::CreateLLVMCodeGen(Diagnostic &Diags, +CodeGenerator *clang::CreateLLVMCodeGen(Diagnostic &Diags, const std::string& ModuleName, const CompileOptions &CO, llvm::LLVMContext& C) { diff --git a/clang/lib/CodeGen/TargetABIInfo.cpp b/clang/lib/CodeGen/TargetABIInfo.cpp index 9525a8ecf5acb9072b554c9caec0f2715c20bf4b..daeec0a31c6207bce3ff2d20533d4a5b153e7eb2 100644 --- a/clang/lib/CodeGen/TargetABIInfo.cpp +++ b/clang/lib/CodeGen/TargetABIInfo.cpp @@ -242,7 +242,7 @@ public: CodeGenFunction &CGF) const; X86_32ABIInfo(ASTContext &Context, bool d, bool p) - : ABIInfo(), Context(Context), IsDarwinVectorABI(d), + : ABIInfo(), Context(Context), IsDarwinVectorABI(d), IsSmallStructInRegABI(p) {} }; } @@ -402,7 +402,7 @@ ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, // Structures with flexible arrays are always indirect. if (const RecordType *RT = Ty->getAsStructureType()) if (RT->getDecl()->hasFlexibleArrayMember()) - return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty, + return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty, Context)); // Ignore empty structs. @@ -1035,7 +1035,7 @@ void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context, for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { unsigned neededInt, neededSSE; - it->info = classifyArgumentType(it->type, Context, VMContext, + it->info = classifyArgumentType(it->type, Context, VMContext, neededInt, neededSSE); // AMD64-ABI 3.2.3p3: If there are no registers available for any @@ -1107,7 +1107,7 @@ static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const { llvm::LLVMContext &VMContext = CGF.getLLVMContext(); - + // Assume that va_list type is correct; should be pointer to LLVM type: // struct { // i32 gp_offset; @@ -1338,7 +1338,7 @@ class ARMABIInfo : public ABIInfo { void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context, llvm::LLVMContext &VMContext) const { - FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context, + FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context, VMContext); for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { @@ -1392,7 +1392,7 @@ ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const { // FIXME: Need to handle alignment - const llvm::Type *BP = + const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(CGF.getLLVMContext())); const llvm::Type *BPP = llvm::PointerType::getUnqual(BP); diff --git a/clang/lib/Driver/Action.cpp b/clang/lib/Driver/Action.cpp index cabc33eaec28808939f6ca4aa3b2e8f16dbcfe73..62434893f939c5bee86ffa42693ca262710e4b4d 100644 --- a/clang/lib/Driver/Action.cpp +++ b/clang/lib/Driver/Action.cpp @@ -29,16 +29,16 @@ const char *Action::getClassName(ActionClass AC) { case LinkJobClass: return "linker"; case LipoJobClass: return "lipo"; } - + assert(0 && "invalid class"); return 0; } -InputAction::InputAction(const Arg &_Input, types::ID _Type) +InputAction::InputAction(const Arg &_Input, types::ID _Type) : Action(InputClass, _Type), Input(_Input) { } -BindArchAction::BindArchAction(Action *Input, const char *_ArchName) +BindArchAction::BindArchAction(Action *Input, const char *_ArchName) : Action(BindArchClass, Input, Input->getType()), ArchName(_ArchName) { } @@ -46,7 +46,7 @@ JobAction::JobAction(ActionClass Kind, Action *Input, types::ID Type) : Action(Kind, Input, Type) { } -JobAction::JobAction(ActionClass Kind, const ActionList &Inputs, types::ID Type) +JobAction::JobAction(ActionClass Kind, const ActionList &Inputs, types::ID Type) : Action(Kind, Inputs, Type) { } @@ -70,10 +70,10 @@ AssembleJobAction::AssembleJobAction(Action *Input, types::ID OutputType) : JobAction(AssembleJobClass, Input, OutputType) { } -LinkJobAction::LinkJobAction(ActionList &Inputs, types::ID Type) +LinkJobAction::LinkJobAction(ActionList &Inputs, types::ID Type) : JobAction(LinkJobClass, Inputs, Type) { } -LipoJobAction::LipoJobAction(ActionList &Inputs, types::ID Type) +LipoJobAction::LipoJobAction(ActionList &Inputs, types::ID Type) : JobAction(LipoJobClass, Inputs, Type) { } diff --git a/clang/lib/Driver/Arg.cpp b/clang/lib/Driver/Arg.cpp index e227d7e2ea15a86d10738b92803b022e17e44aec..a09ba095f119d32ec0d4f969f272b4839d4a3b26 100644 --- a/clang/lib/Driver/Arg.cpp +++ b/clang/lib/Driver/Arg.cpp @@ -14,10 +14,9 @@ using namespace clang::driver; -Arg::Arg(ArgClass _Kind, const Option *_Opt, unsigned _Index, - const Arg *_BaseArg) - : Kind(_Kind), Opt(_Opt), BaseArg(_BaseArg), Index(_Index), Claimed(false) -{ +Arg::Arg(ArgClass _Kind, const Option *_Opt, unsigned _Index, + const Arg *_BaseArg) + : Kind(_Kind), Opt(_Opt), BaseArg(_BaseArg), Index(_Index), Claimed(false) { } Arg::~Arg() { } @@ -54,7 +53,7 @@ std::string Arg::getAsString(const ArgList &Args) const { ArgStringList ASL; render(Args, ASL); - for (ArgStringList::iterator + for (ArgStringList::iterator it = ASL.begin(), ie = ASL.end(); it != ie; ++it) { if (it != ASL.begin()) OS << ' '; @@ -87,7 +86,7 @@ const char *FlagArg::getValue(const ArgList &Args, unsigned N) const { return 0; } -PositionalArg::PositionalArg(const Option *Opt, unsigned Index, +PositionalArg::PositionalArg(const Option *Opt, unsigned Index, const Arg *BaseArg) : Arg(PositionalClass, Opt, Index, BaseArg) { } @@ -120,10 +119,10 @@ const char *JoinedArg::getValue(const ArgList &Args, unsigned N) const { return Args.getArgString(getIndex()) + strlen(getOption().getName()); } -CommaJoinedArg::CommaJoinedArg(const Option *Opt, unsigned Index, +CommaJoinedArg::CommaJoinedArg(const Option *Opt, unsigned Index, const char *Str, const Arg *BaseArg) : Arg(CommaJoinedClass, Opt, Index, BaseArg) { - const char *Prev = Str; + const char *Prev = Str; for (;; ++Str) { char c = *Str; @@ -167,23 +166,23 @@ void SeparateArg::render(const ArgList &Args, ArgStringList &Output) const { } } -const char *SeparateArg::getValue(const ArgList &Args, unsigned N) const { +const char *SeparateArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); return Args.getArgString(getIndex() + 1 + N); } -JoinedAndSeparateArg::JoinedAndSeparateArg(const Option *Opt, unsigned Index, +JoinedAndSeparateArg::JoinedAndSeparateArg(const Option *Opt, unsigned Index, const Arg *BaseArg) : Arg(JoinedAndSeparateClass, Opt, Index, BaseArg) { } -void JoinedAndSeparateArg::render(const ArgList &Args, +void JoinedAndSeparateArg::render(const ArgList &Args, ArgStringList &Output) const { Output.push_back(Args.getArgString(getIndex())); Output.push_back(Args.getArgString(getIndex() + 1)); } -const char *JoinedAndSeparateArg::getValue(const ArgList &Args, +const char *JoinedAndSeparateArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); if (N == 0) diff --git a/clang/lib/Driver/ArgList.cpp b/clang/lib/Driver/ArgList.cpp index 54dd4bb77538218421a17b1811c93196fd27d398..be7109f3f656f65f7ab0721b14491659877eb66a 100644 --- a/clang/lib/Driver/ArgList.cpp +++ b/clang/lib/Driver/ArgList.cpp @@ -31,13 +31,13 @@ Arg *ArgList::getLastArg(options::ID Id, bool Claim) const { return *it; } } - + return 0; } Arg *ArgList::getLastArg(options::ID Id0, options::ID Id1, bool Claim) const { Arg *Res, *A0 = getLastArg(Id0, false), *A1 = getLastArg(Id1, false); - + if (A0 && A1) Res = A0->getIndex() > A1->getIndex() ? A0 : A1; else @@ -102,7 +102,7 @@ void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0) const { } } -void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, +void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { @@ -114,7 +114,7 @@ void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, } } -void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, +void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1, options::ID Id2) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { @@ -139,7 +139,7 @@ void ArgList::AddAllArgValues(ArgStringList &Output, options::ID Id0) const { } } -void ArgList::AddAllArgValues(ArgStringList &Output, options::ID Id0, +void ArgList::AddAllArgValues(ArgStringList &Output, options::ID Id0, options::ID Id1) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { @@ -184,9 +184,8 @@ void ArgList::ClaimAllArgs(options::ID Id0) const { // -InputArgList::InputArgList(const char **ArgBegin, const char **ArgEnd) - : ArgList(ActualArgs), NumInputArgStrings(ArgEnd - ArgBegin) -{ +InputArgList::InputArgList(const char **ArgBegin, const char **ArgEnd) + : ArgList(ActualArgs), NumInputArgStrings(ArgEnd - ArgBegin) { ArgStrings.append(ArgBegin, ArgEnd); } @@ -206,7 +205,7 @@ unsigned InputArgList::MakeIndex(const char *String0) const { return Index; } -unsigned InputArgList::MakeIndex(const char *String0, +unsigned InputArgList::MakeIndex(const char *String0, const char *String1) const { unsigned Index0 = MakeIndex(String0); unsigned Index1 = MakeIndex(String1); @@ -223,13 +222,12 @@ const char *InputArgList::MakeArgString(const char *Str) const { DerivedArgList::DerivedArgList(InputArgList &_BaseArgs, bool _OnlyProxy) : ArgList(_OnlyProxy ? _BaseArgs.getArgs() : ActualArgs), - BaseArgs(_BaseArgs), OnlyProxy(_OnlyProxy) -{ + BaseArgs(_BaseArgs), OnlyProxy(_OnlyProxy) { } DerivedArgList::~DerivedArgList() { // We only own the arguments we explicitly synthesized. - for (iterator it = SynthesizedArgs.begin(), ie = SynthesizedArgs.end(); + for (iterator it = SynthesizedArgs.begin(), ie = SynthesizedArgs.end(); it != ie; ++it) delete *it; } @@ -242,18 +240,18 @@ Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option *Opt) const { return new FlagArg(Opt, BaseArgs.MakeIndex(Opt->getName()), BaseArg); } -Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option *Opt, +Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option *Opt, const char *Value) const { return new PositionalArg(Opt, BaseArgs.MakeIndex(Value), BaseArg); } -Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option *Opt, +Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option *Opt, const char *Value) const { - return new SeparateArg(Opt, BaseArgs.MakeIndex(Opt->getName(), Value), 1, + return new SeparateArg(Opt, BaseArgs.MakeIndex(Opt->getName(), Value), 1, BaseArg); } -Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option *Opt, +Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option *Opt, const char *Value) const { std::string Joined(Opt->getName()); Joined += Value; diff --git a/clang/lib/Driver/Compilation.cpp b/clang/lib/Driver/Compilation.cpp index 7e29b67769d343ab7e5642c7bac21b5a4e6e7b01..ad3cb8dbe1e61115c2fe1d5cdf59fcbfc5e0f30a 100644 --- a/clang/lib/Driver/Compilation.cpp +++ b/clang/lib/Driver/Compilation.cpp @@ -23,20 +23,20 @@ using namespace clang::driver; Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain, - InputArgList *_Args) + InputArgList *_Args) : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args) { } -Compilation::~Compilation() { +Compilation::~Compilation() { delete Args; - + // Free any derived arg lists. - for (llvm::DenseMap::iterator + for (llvm::DenseMap::iterator it = TCArgs.begin(), ie = TCArgs.end(); it != ie; ++it) delete it->second; // Free the actions, if built. - for (ActionList::iterator it = Actions.begin(), ie = Actions.end(); + for (ActionList::iterator it = Actions.begin(), ie = Actions.end(); it != ie; ++it) delete *it; } @@ -52,7 +52,7 @@ const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC) { return *Entry; } -void Compilation::PrintJob(llvm::raw_ostream &OS, const Job &J, +void Compilation::PrintJob(llvm::raw_ostream &OS, const Job &J, const char *Terminator, bool Quote) const { if (const Command *C = dyn_cast(&J)) { OS << " \"" << C->getExecutable() << '"'; @@ -65,22 +65,22 @@ void Compilation::PrintJob(llvm::raw_ostream &OS, const Job &J, } OS << Terminator; } else if (const PipedJob *PJ = dyn_cast(&J)) { - for (PipedJob::const_iterator + for (PipedJob::const_iterator it = PJ->begin(), ie = PJ->end(); it != ie; ++it) PrintJob(OS, **it, (it + 1 != PJ->end()) ? " |\n" : "\n", Quote); } else { const JobList *Jobs = cast(&J); - for (JobList::const_iterator + for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) PrintJob(OS, **it, Terminator, Quote); } } -bool Compilation::CleanupFileList(const ArgStringList &Files, +bool Compilation::CleanupFileList(const ArgStringList &Files, bool IssueErrors) const { bool Success = true; - for (ArgStringList::const_iterator + for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end(); it != ie; ++it) { llvm::sys::Path P(*it); std::string Error; @@ -92,7 +92,7 @@ bool Compilation::CleanupFileList(const ArgStringList &Files, // FIXME: Grumble, P.exists() is broken. PR3837. struct stat buf; - if (::stat(P.c_str(), &buf) == 0 + if (::stat(P.c_str(), &buf) == 0 || errno != ENOENT) { if (IssueErrors) getDriver().Diag(clang::diag::err_drv_unable_to_remove_file) @@ -112,12 +112,12 @@ int Compilation::ExecuteCommand(const Command &C, Argv[0] = C.getExecutable(); std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1); Argv[C.getArguments().size() + 1] = 0; - + if (getDriver().CCCEcho || getArgs().hasArg(options::OPT_v)) PrintJob(llvm::errs(), C, "\n", false); - + std::string Error; - int Res = + int Res = llvm::sys::Program::ExecuteAndWait(Prog, Argv, /*env*/0, /*redirects*/0, /*secondsToWait*/0, /*memoryLimit*/0, @@ -126,7 +126,7 @@ int Compilation::ExecuteCommand(const Command &C, assert(Res && "Error string set with 0 result code!"); getDriver().Diag(clang::diag::err_drv_command_failure) << Error; } - + if (Res) FailingCommand = &C; @@ -134,7 +134,7 @@ int Compilation::ExecuteCommand(const Command &C, return Res; } -int Compilation::ExecuteJob(const Job &J, +int Compilation::ExecuteJob(const Job &J, const Command *&FailingCommand) const { if (const Command *C = dyn_cast(&J)) { return ExecuteCommand(*C, FailingCommand); @@ -142,13 +142,13 @@ int Compilation::ExecuteJob(const Job &J, // Piped commands with a single job are easy. if (PJ->size() == 1) return ExecuteCommand(**PJ->begin(), FailingCommand); - + FailingCommand = *PJ->begin(); getDriver().Diag(clang::diag::err_drv_unsupported_opt) << "-pipe"; return 1; } else { const JobList *Jobs = cast(&J); - for (JobList::const_iterator + for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) if (int Res = ExecuteJob(**it, FailingCommand)) return Res; diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 59099a33e6f0e6a24808aced9a579041b006bc90..24f462f18fc4867d4758ed5cd7e053b9ce8facfb 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -56,8 +56,7 @@ Driver::Driver(const char *_Name, const char *_Dir, CCCUseClangCXX(true), #endif CCCUseClangCPP(true), CCCUsePCH(true), - SuppressMissingInputWarning(false) -{ + SuppressMissingInputWarning(false) { #ifdef USE_PRODUCTION_CLANG // In a "production" build, only use clang on architectures we expect to work. CCCClangArchs.insert(llvm::Triple::x86); diff --git a/clang/lib/Driver/HostInfo.cpp b/clang/lib/Driver/HostInfo.cpp index ceb4ed10231461907983ec70e30d60f4d7597e0f..e950b4a08ee6eaae80736c8da99b9538649e479d 100644 --- a/clang/lib/Driver/HostInfo.cpp +++ b/clang/lib/Driver/HostInfo.cpp @@ -26,9 +26,7 @@ using namespace clang::driver; HostInfo::HostInfo(const Driver &D, const llvm::Triple &_Triple) - : TheDriver(D), Triple(_Triple) -{ - + : TheDriver(D), Triple(_Triple) { } HostInfo::~HostInfo() { diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp index 1b0ea18453d0660bfcea97c7ec55dc0aad88d5ab..280e7c4a5a09dec9bd2e83d740c3b02e8cec4621 100644 --- a/clang/lib/Driver/Job.cpp +++ b/clang/lib/Driver/Job.cpp @@ -14,9 +14,9 @@ using namespace clang::driver; Job::~Job() {} -Command::Command(const Action &_Source, const char *_Executable, +Command::Command(const Action &_Source, const char *_Executable, const ArgStringList &_Arguments) - : Job(CommandClass), Source(_Source), Executable(_Executable), + : Job(CommandClass), Source(_Source), Executable(_Executable), Arguments(_Arguments) { } @@ -30,4 +30,4 @@ void Job::addCommand(Command *C) { else cast(this)->addJob(C); } - + diff --git a/clang/lib/Driver/OptTable.cpp b/clang/lib/Driver/OptTable.cpp index 8c88575764507655d93167b1288a8c52163db05d..affd1c5aa9e58b4e52fdcbed5bfe4c5e35f91666 100644 --- a/clang/lib/Driver/OptTable.cpp +++ b/clang/lib/Driver/OptTable.cpp @@ -77,7 +77,7 @@ static Info OptionInfos[] = { { "", "d", 0, 0, Option::InputClass, OPT_INVALID, OPT_INVALID, 0 }, // The UnknownOption info { "", "", 0, 0, Option::UnknownClass, OPT_INVALID, OPT_INVALID, 0 }, - + #define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ HELPTEXT, METAVAR) \ { NAME, FLAGS, HELPTEXT, METAVAR, \ @@ -124,10 +124,10 @@ OptTable::OptTable() : Options(new Option*[numOptions]) { assert(0 && "Options are not in order!"); } } -#endif +#endif } -OptTable::~OptTable() { +OptTable::~OptTable() { for (unsigned i = 0; i < numOptions; ++i) delete Options[i]; delete[] Options; @@ -168,7 +168,7 @@ const Option *OptTable::getOption(options::ID id) const { Option *OptTable::constructOption(options::ID id) const { Info &info = getInfo(id); - const OptionGroup *Group = + const OptionGroup *Group = cast_or_null(getOption((options::ID) info.GroupID)); const Option *Alias = getOption((options::ID) info.AliasID); @@ -199,10 +199,10 @@ Option *OptTable::constructOption(options::ID id) const { for (const char *s = info.Flags; *s; ++s) { switch (*s) { default: assert(0 && "Invalid option flag."); - case 'J': + case 'J': assert(info.Kind == Option::SeparateClass && "Invalid option."); Opt->setForceJoinedRender(true); break; - case 'S': + case 'S': assert(info.Kind == Option::JoinedClass && "Invalid option."); Opt->setForceSeparateRender(true); break; case 'd': Opt->setDriverOption(true); break; diff --git a/clang/lib/Driver/Option.cpp b/clang/lib/Driver/Option.cpp index cad2bbf2b75eaacf44b904a5a4a395b134747346..c2ace05aa4d13860af95042ee3f9499647c2427a 100644 --- a/clang/lib/Driver/Option.cpp +++ b/clang/lib/Driver/Option.cpp @@ -17,18 +17,17 @@ using namespace clang::driver; Option::Option(OptionClass _Kind, options::ID _ID, const char *_Name, - const OptionGroup *_Group, const Option *_Alias) + const OptionGroup *_Group, const Option *_Alias) : Kind(_Kind), ID(_ID), Name(_Name), Group(_Group), Alias(_Alias), Unsupported(false), LinkerInput(false), NoOptAsInput(false), ForceSeparateRender(false), ForceJoinedRender(false), - DriverOption(false), NoArgumentUnused(false) -{ + DriverOption(false), NoArgumentUnused(false) { // Multi-level aliases are not supported, and alias options cannot // have groups. This just simplifies option tracking, it is not an // inherent limitation. assert((!Alias || (!Alias->Alias && !Group)) && - "Multi-level aliases and aliases with groups are unsupported."); + "Multi-level aliases and aliases with groups are unsupported."); } Option::~Option() { @@ -59,12 +58,12 @@ void Option::dump() const { llvm::errs() << " Group:"; Group->dump(); } - + if (Alias) { llvm::errs() << " Alias:"; Alias->dump(); } - + if (const MultiArgOption *MOA = dyn_cast(this)) llvm::errs() << " NumArgs:" << MOA->getNumArgs(); @@ -77,10 +76,10 @@ bool Option::matches(const Option *Opt) const { return matches(Opt->getAlias()); if (Alias) return Alias->matches(Opt); - + if (this == Opt) return true; - + if (Group) return Group->matches(Opt); return false; @@ -93,16 +92,16 @@ bool Option::matches(options::ID Id) const { // the option table). if (Alias) return Alias->matches(Id); - + if (ID == Id) return true; - + if (Group) return Group->matches(Id); return false; } -OptionGroup::OptionGroup(options::ID ID, const char *Name, +OptionGroup::OptionGroup(options::ID ID, const char *Name, const OptionGroup *Group) : Option(Option::GroupClass, ID, Name, Group, 0) { } @@ -130,13 +129,13 @@ Arg *UnknownOption::accept(const InputArgList &Args, unsigned &Index) const { return 0; } -FlagOption::FlagOption(options::ID ID, const char *Name, +FlagOption::FlagOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::FlagClass, ID, Name, Group, Alias) { } Arg *FlagOption::accept(const InputArgList &Args, unsigned &Index) const { - // Matches iff this is an exact match. + // Matches iff this is an exact match. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return 0; @@ -144,7 +143,7 @@ Arg *FlagOption::accept(const InputArgList &Args, unsigned &Index) const { return new FlagArg(this, Index++); } -JoinedOption::JoinedOption(options::ID ID, const char *Name, +JoinedOption::JoinedOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::JoinedClass, ID, Name, Group, Alias) { } @@ -154,30 +153,30 @@ Arg *JoinedOption::accept(const InputArgList &Args, unsigned &Index) const { return new JoinedArg(this, Index++); } -CommaJoinedOption::CommaJoinedOption(options::ID ID, const char *Name, - const OptionGroup *Group, +CommaJoinedOption::CommaJoinedOption(options::ID ID, const char *Name, + const OptionGroup *Group, const Option *Alias) : Option(Option::CommaJoinedClass, ID, Name, Group, Alias) { } -Arg *CommaJoinedOption::accept(const InputArgList &Args, +Arg *CommaJoinedOption::accept(const InputArgList &Args, unsigned &Index) const { // Always matches. We count the commas now so we can answer // getNumValues easily. - + // Get the suffix string. // FIXME: Avoid strlen, and move to helper method? const char *Suffix = Args.getArgString(Index) + strlen(getName()); return new CommaJoinedArg(this, Index++, Suffix); } -SeparateOption::SeparateOption(options::ID ID, const char *Name, +SeparateOption::SeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::SeparateClass, ID, Name, Group, Alias) { } Arg *SeparateOption::accept(const InputArgList &Args, unsigned &Index) const { - // Matches iff this is an exact match. + // Matches iff this is an exact match. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return 0; @@ -189,15 +188,15 @@ Arg *SeparateOption::accept(const InputArgList &Args, unsigned &Index) const { return new SeparateArg(this, Index - 2, 1); } -MultiArgOption::MultiArgOption(options::ID ID, const char *Name, - const OptionGroup *Group, const Option *Alias, +MultiArgOption::MultiArgOption(options::ID ID, const char *Name, + const OptionGroup *Group, const Option *Alias, unsigned _NumArgs) : Option(Option::MultiArgClass, ID, Name, Group, Alias), NumArgs(_NumArgs) { assert(NumArgs > 1 && "Invalid MultiArgOption!"); } Arg *MultiArgOption::accept(const InputArgList &Args, unsigned &Index) const { - // Matches iff this is an exact match. + // Matches iff this is an exact match. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return 0; @@ -210,12 +209,12 @@ Arg *MultiArgOption::accept(const InputArgList &Args, unsigned &Index) const { } JoinedOrSeparateOption::JoinedOrSeparateOption(options::ID ID, const char *Name, - const OptionGroup *Group, + const OptionGroup *Group, const Option *Alias) : Option(Option::JoinedOrSeparateClass, ID, Name, Group, Alias) { } -Arg *JoinedOrSeparateOption::accept(const InputArgList &Args, +Arg *JoinedOrSeparateOption::accept(const InputArgList &Args, unsigned &Index) const { // If this is not an exact match, it is a joined arg. // FIXME: Avoid strlen. @@ -227,17 +226,17 @@ Arg *JoinedOrSeparateOption::accept(const InputArgList &Args, if (Index > Args.getNumInputArgStrings()) return 0; - return new SeparateArg(this, Index - 2, 1); + return new SeparateArg(this, Index - 2, 1); } JoinedAndSeparateOption::JoinedAndSeparateOption(options::ID ID, - const char *Name, - const OptionGroup *Group, + const char *Name, + const OptionGroup *Group, const Option *Alias) : Option(Option::JoinedAndSeparateClass, ID, Name, Group, Alias) { } -Arg *JoinedAndSeparateOption::accept(const InputArgList &Args, +Arg *JoinedAndSeparateOption::accept(const InputArgList &Args, unsigned &Index) const { // Always matches. diff --git a/clang/lib/Driver/Tool.cpp b/clang/lib/Driver/Tool.cpp index 6f6589ab13273bf9cb0ac96f7b6fefdc50a6021c..781e0a702060d3840a9cd3c2edd1be12476449e6 100644 --- a/clang/lib/Driver/Tool.cpp +++ b/clang/lib/Driver/Tool.cpp @@ -11,7 +11,7 @@ using namespace clang::driver; -Tool::Tool(const char *_Name, const ToolChain &TC) : Name(_Name), +Tool::Tool(const char *_Name, const ToolChain &TC) : Name(_Name), TheToolChain(TC) { } diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp index 20ed31bd6e02b0002c0717cd488d9c885bf80f1f..46b460381f66d954634fe7dc603f93b5520e3846 100644 --- a/clang/lib/Driver/ToolChain.cpp +++ b/clang/lib/Driver/ToolChain.cpp @@ -22,13 +22,13 @@ ToolChain::ToolChain(const HostInfo &_Host, const llvm::Triple &_Triple) ToolChain::~ToolChain() { } -llvm::sys::Path ToolChain::GetFilePath(const Compilation &C, +llvm::sys::Path ToolChain::GetFilePath(const Compilation &C, const char *Name) const { return Host.getDriver().GetFilePath(Name, *this); - + } -llvm::sys::Path ToolChain::GetProgramPath(const Compilation &C, +llvm::sys::Path ToolChain::GetProgramPath(const Compilation &C, const char *Name, bool WantFile) const { return Host.getDriver().GetProgramPath(Name, *this, WantFile); diff --git a/clang/lib/Driver/ToolChains.cpp b/clang/lib/Driver/ToolChains.cpp index 6512203d0931159218332e9c96adc6b21212085f..fb6217d3ed00cc7ca19509b42b5e42de5b9844b8 100644 --- a/clang/lib/Driver/ToolChains.cpp +++ b/clang/lib/Driver/ToolChains.cpp @@ -68,7 +68,7 @@ Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple, Path += "/x86_64"; getFilePaths().push_back(Path); } - + Path = getHost().getDriver().Dir; Path += "/../lib/gcc/"; Path += getToolChainDir(); @@ -142,16 +142,16 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { // more opaque. For now, we follow gcc closely solely for the // purpose of easily achieving feature parity & testability. Once we // have something that works, we should reevaluate each translation - // and try to push it down into tool specific logic. + // and try to push it down into tool specific logic. - Arg *OSXVersion = + Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ, false); Arg *iPhoneVersion = - Args.getLastArg(options::OPT_miphoneos_version_min_EQ, false); + Args.getLastArg(options::OPT_miphoneos_version_min_EQ, false); if (OSXVersion && iPhoneVersion) { getHost().getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with) << OSXVersion->getAsString(Args) - << iPhoneVersion->getAsString(Args); + << iPhoneVersion->getAsString(Args); } else if (!OSXVersion && !iPhoneVersion) { // Chose the default version based on the arch. // @@ -171,7 +171,7 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { DAL->append(DAL->MakeJoinedArg(0, O, Version)); } } - + for (ArgList::iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; @@ -184,7 +184,7 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { // interface for this. unsigned Prev, Index = Prev = A->getIndex() + 1; Arg *XarchArg = Opts.ParseOneArg(Args, Index); - + // If the argument parsing failed or more than one argument was // consumed, the -Xarch_ argument's parameter tried to consume // extra arguments. Emit an error and ignore. @@ -193,7 +193,7 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { // driver behavior; that isn't going to work in our model. We // use isDriverOption() as an approximation, although things // like -O4 are going to slip through. - if (!XarchArg || Index > Prev + 1 || + if (!XarchArg || Index > Prev + 1 || XarchArg->getOption().isDriverOption()) { getHost().getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument) << A->getAsString(Args); @@ -202,7 +202,7 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { XarchArg->setBaseArg(A); A = XarchArg; - } + } // Sob. These is strictly gcc compatible for the time being. Apple // gcc translates options twice, which means that self-expanding @@ -219,7 +219,7 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_static))); DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_static))); break; - + case options::OPT_dependency_file: DAL->append(DAL->MakeSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(Args))); @@ -292,10 +292,10 @@ DerivedArgList *Darwin::TranslateArgs(InputArgList &Args) const { "core2")); return DAL; -} +} bool Darwin::IsMathErrnoDefault() const { - return false; + return false; } bool Darwin::IsUnwindTablesDefault() const { @@ -319,13 +319,12 @@ const char *Darwin::GetForcedPicModel() const { /// command line options. Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple) - : ToolChain(Host, Triple) -{ + : ToolChain(Host, Triple) { std::string Path(getHost().getDriver().Dir); Path += "/../libexec"; getProgramPaths().push_back(Path); - getProgramPaths().push_back(getHost().getDriver().Dir); + getProgramPaths().push_back(getHost().getDriver().Dir); } Generic_GCC::~Generic_GCC() { @@ -335,7 +334,7 @@ Generic_GCC::~Generic_GCC() { delete it->second; } -Tool &Generic_GCC::SelectTool(const Compilation &C, +Tool &Generic_GCC::SelectTool(const Compilation &C, const JobAction &JA) const { Action::ActionClass Key; if (getHost().getDriver().ShouldUseClangCompiler(C, JA, getTriple())) @@ -361,7 +360,7 @@ Tool &Generic_GCC::SelectTool(const Compilation &C, T = new tools::gcc::Assemble(*this); break; case Action::LinkJobClass: T = new tools::gcc::Link(*this); break; - + // This is a bit ungeneric, but the only platform using a driver // driver is Darwin. case Action::LipoJobClass: @@ -373,7 +372,7 @@ Tool &Generic_GCC::SelectTool(const Compilation &C, } bool Generic_GCC::IsMathErrnoDefault() const { - return true; + return true; } bool Generic_GCC::IsUnwindTablesDefault() const { @@ -469,7 +468,7 @@ AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple) Path += "/../libexec"; getProgramPaths().push_back(Path); - getProgramPaths().push_back(getHost().getDriver().Dir); + getProgramPaths().push_back(getHost().getDriver().Dir); getFilePaths().push_back(getHost().getDriver().Dir + "/../lib"); getFilePaths().push_back("/usr/lib"); @@ -536,7 +535,7 @@ DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple) Path += "/../libexec"; getProgramPaths().push_back(Path); - getProgramPaths().push_back(getHost().getDriver().Dir); + getProgramPaths().push_back(getHost().getDriver().Dir); getFilePaths().push_back(getHost().getDriver().Dir + "/../lib"); getFilePaths().push_back("/usr/lib"); diff --git a/clang/lib/Driver/ToolChains.h b/clang/lib/Driver/ToolChains.h index b0cc9cbecdb622ac11bb898c99771e3d134887c7..6a3ce37975b6f133dd1d2be54ad02115882ab8c2 100644 --- a/clang/lib/Driver/ToolChains.h +++ b/clang/lib/Driver/ToolChains.h @@ -69,7 +69,7 @@ class VISIBILITY_HIDDEN Darwin : public ToolChain { const char *getMacosxVersionMin() const; public: - Darwin(const HostInfo &Host, const llvm::Triple& Triple, + Darwin(const HostInfo &Host, const llvm::Triple& Triple, const unsigned (&DarwinVersion)[3], const unsigned (&GCCVersion)[3], bool IsIPhone); @@ -95,7 +95,7 @@ public: return IPhoneOSVersionMin.c_str(); } - const std::string &getToolChainDir() const { + const std::string &getToolChainDir() const { return ToolChainDir; } @@ -114,7 +114,7 @@ public: /// Darwin_GCC - Generic Darwin tool chain using gcc. class VISIBILITY_HIDDEN Darwin_GCC : public Generic_GCC { public: - Darwin_GCC(const HostInfo &Host, const llvm::Triple& Triple) + Darwin_GCC(const HostInfo &Host, const llvm::Triple& Triple) : Generic_GCC(Host, Triple) {} virtual const char *GetDefaultRelocationModel() const { return "pic"; } diff --git a/clang/lib/Driver/Tools.cpp b/clang/lib/Driver/Tools.cpp index d7bf8b72bdc6ce5186e5a173376a6d15f896e95a..7cd57b92fc9c3cc54c1087466f44b387a45c6cae 100644 --- a/clang/lib/Driver/Tools.cpp +++ b/clang/lib/Driver/Tools.cpp @@ -38,7 +38,7 @@ static const char *MakeFormattedString(const ArgList &Args, return Args.MakeArgString(Str.c_str()); } -void Clang::AddPreprocessingOptions(const Driver &D, +void Clang::AddPreprocessingOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, const InputInfo &Output, @@ -131,25 +131,25 @@ void Clang::AddPreprocessingOptions(const Driver &D, P.appendSuffix("pch"); if (P.exists()) FoundPCH = true; - else + else P.eraseSuffix(); } if (!FoundPCH) { P.appendSuffix("pth"); - if (P.exists()) + if (P.exists()) FoundPTH = true; else P.eraseSuffix(); - } - + } + if (!FoundPCH && !FoundPTH) { P.appendSuffix("gch"); if (P.exists()) { FoundPCH = D.CCCUsePCH; FoundPTH = !D.CCCUsePCH; } - else + else P.eraseSuffix(); } @@ -266,8 +266,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // Add -Xanalyzer arguments when running as analyzer. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer); - } - + } + // Perform argument translation for LLVM backend. This // takes some care in reconciling with llvm-gcc. The // issue is that llvm-gcc translates these options based on @@ -358,7 +358,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, CmdArgs.push_back(A->getValue(Args)); } else { // Select default CPU. - + // FIXME: Need target hooks. if (memcmp(getToolChain().getOS().c_str(), "darwin", 6) == 0) { if (getToolChain().getArchName() == "x86_64") @@ -388,7 +388,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // Skip over "-m". assert(Name[0] == '-' && Name[1] == 'm' && "Invalid feature name."); Name += 2; - + bool IsNegative = memcmp(Name, "no-", 3) == 0; if (IsNegative) Name += 3; @@ -396,7 +396,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, A->claim(); CmdArgs.push_back("-target-feature"); CmdArgs.push_back(MakeFormattedString(Args, - llvm::format("%c%s", + llvm::format("%c%s", IsNegative ? '-' : '+', Name))); } @@ -428,7 +428,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Args.AddLastArg(CmdArgs, options::OPT_P); Args.AddLastArg(CmdArgs, options::OPT_mmacosx_version_min_EQ); Args.AddLastArg(CmdArgs, options::OPT_miphoneos_version_min_EQ); - Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); + Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); // Special case debug options to only pass -g to clang. This is // wrong. @@ -489,7 +489,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, if (Args.hasArg(options::OPT__relocatable_pch, true)) CmdArgs.push_back("--relocatable-pch"); - + if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) { CmdArgs.push_back("-fconstant-string-class"); CmdArgs.push_back(A->getValue(Args)); @@ -592,18 +592,18 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // -fsigned-bitfields is default, and clang doesn't yet support // --funsigned-bitfields. - if (!Args.hasFlag(options::OPT_fsigned_bitfields, + if (!Args.hasFlag(options::OPT_fsigned_bitfields, options::OPT_funsigned_bitfields)) D.Diag(clang::diag::warn_drv_clang_unsupported) << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); // -fdiagnostics-fixit-info is default, only pass non-default. - if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info, + if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info, options::OPT_fno_diagnostics_fixit_info)) CmdArgs.push_back("-fno-diagnostics-fixit-info"); // Enable -fdiagnostics-show-option by default. - if (Args.hasFlag(options::OPT_fdiagnostics_show_option, + if (Args.hasFlag(options::OPT_fdiagnostics_show_option, options::OPT_fno_diagnostics_show_option)) CmdArgs.push_back("-fdiagnostics-show-option"); if (!Args.hasFlag(options::OPT_fcolor_diagnostics, @@ -615,7 +615,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // -fdollars-in-identifiers default varies depending on platform and // language; only pass if specified. - if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, + if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, options::OPT_fno_dollars_in_identifiers)) { if (A->getOption().matches(options::OPT_fdollars_in_identifiers)) CmdArgs.push_back("-fdollars-in-identifiers=1"); @@ -625,13 +625,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for // practical purposes. - if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time, + if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time, options::OPT_fno_unit_at_a_time)) { if (A->getOption().matches(options::OPT_fno_unit_at_a_time)) D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args); } - if (Arg *A = Args.getLastArg(options::OPT_traditional, + if (Arg *A = Args.getLastArg(options::OPT_traditional, options::OPT_traditional_cpp)) D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args); @@ -1027,8 +1027,7 @@ void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, - const InputInfoList &Inputs) const -{ + const InputInfoList &Inputs) const { const Driver &D = getToolChain().getHost().getDriver(); // Derived from cpp_unique_options. @@ -1877,8 +1876,7 @@ void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, - const char *LinkingOutput) const -{ + const char *LinkingOutput) const { ArgStringList CmdArgs; Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, @@ -2006,8 +2004,7 @@ void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, - const char *LinkingOutput) const -{ + const char *LinkingOutput) const { ArgStringList CmdArgs; Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, @@ -2135,8 +2132,7 @@ void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, - const char *LinkingOutput) const -{ + const char *LinkingOutput) const { ArgStringList CmdArgs; // When building 32-bit code on FreeBSD/amd64, we have to explicitly diff --git a/clang/lib/Driver/Tools.h b/clang/lib/Driver/Tools.h index 4821c548b1e1ce85d23483555e89d0291c741adc..c584b5ef05ec23be7bc5fdbf882750d37bab5514 100644 --- a/clang/lib/Driver/Tools.h +++ b/clang/lib/Driver/Tools.h @@ -42,9 +42,9 @@ namespace tools { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; @@ -56,9 +56,9 @@ namespace gcc { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; /// RenderExtraToolArgs - Render any arguments necessary to force @@ -66,7 +66,7 @@ namespace gcc { virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const = 0; }; - + class VISIBILITY_HIDDEN Preprocess : public Common { public: Preprocess(const ToolChain &TC) : Common("gcc::Preprocess", TC) {} @@ -126,11 +126,11 @@ namespace gcc { namespace darwin { class VISIBILITY_HIDDEN CC1 : public Tool { public: - static const char *getBaseInputName(const ArgList &Args, + static const char *getBaseInputName(const ArgList &Args, const InputInfoList &Input); - static const char *getBaseInputStem(const ArgList &Args, + static const char *getBaseInputStem(const ArgList &Args, const InputInfoList &Input); - static const char *getDependencyFileName(const ArgList &Args, + static const char *getDependencyFileName(const ArgList &Args, const InputInfoList &Inputs); protected: @@ -143,7 +143,7 @@ namespace darwin { void AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs, const ArgStringList &OutputArgs) const; - void AddCPPUniqueOptionsArgs(const ArgList &Args, + void AddCPPUniqueOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs) const; void AddCPPArgs(const ArgList &Args, ArgStringList &CmdArgs) const; @@ -162,9 +162,9 @@ namespace darwin { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; @@ -174,9 +174,9 @@ namespace darwin { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; @@ -190,9 +190,9 @@ namespace darwin { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; @@ -216,9 +216,9 @@ namespace darwin { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; @@ -232,9 +232,9 @@ namespace darwin { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; } @@ -251,9 +251,9 @@ namespace openbsd { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Link : public Tool { @@ -266,9 +266,9 @@ namespace openbsd { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; } // end namespace openbsd @@ -285,9 +285,9 @@ namespace freebsd { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Link : public Tool { @@ -300,9 +300,9 @@ namespace freebsd { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; } // end namespace freebsd @@ -319,9 +319,9 @@ namespace auroraux { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Link : public Tool { @@ -334,9 +334,9 @@ namespace auroraux { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; } // end namespace auroraux @@ -353,9 +353,9 @@ namespace dragonfly { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Link : public Tool { @@ -368,9 +368,9 @@ namespace dragonfly { virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, - const InputInfo &Output, - const InputInfoList &Inputs, - const ArgList &TCArgs, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, const char *LinkingOutput) const; }; } // end namespace dragonfly diff --git a/clang/lib/Driver/Types.cpp b/clang/lib/Driver/Types.cpp index 60248a17c741a187d8458e88abed990a4fccf7af..eee8c19c27766393a7c3509a0a8ffa461049a8ad 100644 --- a/clang/lib/Driver/Types.cpp +++ b/clang/lib/Driver/Types.cpp @@ -35,38 +35,38 @@ static Info &getInfo(unsigned id) { return TypeInfos[id - 1]; } -const char *types::getTypeName(ID Id) { - return getInfo(Id).Name; +const char *types::getTypeName(ID Id) { + return getInfo(Id).Name; } -types::ID types::getPreprocessedType(ID Id) { - return getInfo(Id).PreprocessedType; +types::ID types::getPreprocessedType(ID Id) { + return getInfo(Id).PreprocessedType; } -const char *types::getTypeTempSuffix(ID Id) { - return getInfo(Id).TempSuffix; +const char *types::getTypeTempSuffix(ID Id) { + return getInfo(Id).TempSuffix; } -bool types::onlyAssembleType(ID Id) { - return strchr(getInfo(Id).Flags, 'a'); +bool types::onlyAssembleType(ID Id) { + return strchr(getInfo(Id).Flags, 'a'); } -bool types::onlyPrecompileType(ID Id) { - return strchr(getInfo(Id).Flags, 'p'); +bool types::onlyPrecompileType(ID Id) { + return strchr(getInfo(Id).Flags, 'p'); } -bool types::canTypeBeUserSpecified(ID Id) { - return strchr(getInfo(Id).Flags, 'u'); +bool types::canTypeBeUserSpecified(ID Id) { + return strchr(getInfo(Id).Flags, 'u'); } -bool types::appendSuffixForType(ID Id) { - return strchr(getInfo(Id).Flags, 'A'); +bool types::appendSuffixForType(ID Id) { + return strchr(getInfo(Id).Flags, 'A'); } -bool types::canLipoType(ID Id) { +bool types::canLipoType(ID Id) { return (Id == TY_Nothing || Id == TY_Image || - Id == TY_Object); + Id == TY_Object); } bool types::isAcceptedByClang(ID Id) { @@ -154,7 +154,7 @@ types::ID types::lookupTypeForTypeSpecifier(const char *Name) { for (unsigned i=0; idecls_begin(), DEnd = Ctx.getTranslationUnitDecl()->decls_end(); - D != DEnd; + D != DEnd; ++D) - { Doc.PrintDecl(*D); - } Doc.toParent(); Doc.finalize(); } @@ -88,9 +86,9 @@ namespace { ASTConsumer *clang::CreateASTPrinterXML(llvm::raw_ostream* out) { return new ASTPrinterXML(out ? *out : llvm::outs()); } - -ASTConsumer *clang::CreateASTDumper() { - return new ASTPrinter(0, true); + +ASTConsumer *clang::CreateASTDumper() { + return new ASTPrinter(0, true); } //===----------------------------------------------------------------------===// @@ -108,7 +106,7 @@ namespace { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) HandleTopLevelSingleDecl(*I); } - + void HandleTopLevelSingleDecl(Decl *D); }; } @@ -116,7 +114,7 @@ namespace { void ASTViewer::HandleTopLevelSingleDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast(D)) { FD->print(llvm::errs()); - + if (FD->getBodyIfAvailable()) { llvm::errs() << '\n'; FD->getBodyIfAvailable()->viewAST(); @@ -124,10 +122,10 @@ void ASTViewer::HandleTopLevelSingleDecl(Decl *D) { } return; } - + if (ObjCMethodDecl *MD = dyn_cast(D)) { MD->print(llvm::errs()); - + if (MD->getBody()) { llvm::errs() << '\n'; MD->getBody()->viewAST(); @@ -157,7 +155,7 @@ public: }; } // end anonymous namespace -void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, +void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, unsigned Indentation) { // Print DeclContext name. switch (DC->getDeclKind()) { @@ -231,7 +229,7 @@ void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, // Print the parameters. Out << "("; bool PrintComma = false; - for (FunctionDecl::param_const_iterator I = FD->param_begin(), + for (FunctionDecl::param_const_iterator I = FD->param_begin(), E = FD->param_end(); I != E; ++I) { if (PrintComma) Out << ", "; @@ -254,7 +252,7 @@ void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, // Print the parameters. Out << "("; bool PrintComma = false; - for (FunctionDecl::param_const_iterator I = D->param_begin(), + for (FunctionDecl::param_const_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { if (PrintComma) Out << ", "; @@ -284,7 +282,7 @@ void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, // Print the parameters. Out << "("; bool PrintComma = false; - for (FunctionDecl::param_const_iterator I = D->param_begin(), + for (FunctionDecl::param_const_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { if (PrintComma) Out << ", "; @@ -354,7 +352,7 @@ void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, case Decl::CXXRecord: case Decl::ObjCMethod: case Decl::ObjCInterface: - case Decl::ObjCCategory: + case Decl::ObjCCategory: case Decl::ObjCProtocol: case Decl::ObjCImplementation: case Decl::ObjCCategoryImpl: @@ -416,8 +414,8 @@ void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, } } } -ASTConsumer *clang::CreateDeclContextPrinter() { - return new DeclContextPrinter(); +ASTConsumer *clang::CreateDeclContextPrinter() { + return new DeclContextPrinter(); } //===----------------------------------------------------------------------===// @@ -428,7 +426,7 @@ class InheritanceViewer : public ASTConsumer { const std::string clsname; public: InheritanceViewer(const std::string& cname) : clsname(cname) {} - + void HandleTranslationUnit(ASTContext &C) { for (ASTContext::type_iterator I=C.types_begin(),E=C.types_end(); I!=E; ++I) if (RecordType *T = dyn_cast(*I)) { @@ -436,12 +434,12 @@ public: // FIXME: This lookup needs to be generalized to handle namespaces and // (when we support them) templates. if (D->getNameAsString() == clsname) { - D->viewInheritance(C); + D->viewInheritance(C); } } } } -}; +}; } ASTConsumer *clang::CreateInheritanceViewer(const std::string& clsname) { diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index 4cd92808f50d45b1937008dfa971d4f3408b6bd1..609889aad9fec20339a403d70ca47bd85223bfd9 100644 --- a/clang/lib/Frontend/ASTUnit.cpp +++ b/clang/lib/Frontend/ASTUnit.cpp @@ -38,38 +38,38 @@ class VISIBILITY_HIDDEN PCHInfoCollector : public PCHReaderListener { std::string &TargetTriple; std::string &Predefines; unsigned &Counter; - + unsigned NumHeaderInfos; - + public: PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, std::string &TargetTriple, std::string &Predefines, unsigned &Counter) : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} - + virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { LangOpt = LangOpts; return false; } - + virtual bool ReadTargetTriple(const std::string &Triple) { TargetTriple = Triple; return false; } - - virtual bool ReadPredefinesBuffer(const char *PCHPredef, + + virtual bool ReadPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID, std::string &SuggestedPredefines) { Predefines = PCHPredef; return false; } - + virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) { HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); } - + virtual void ReadCounter(unsigned Value) { Counter = Value; } @@ -88,7 +88,7 @@ FileManager &ASTUnit::getFileManager() { ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, FileManager &FileMgr, std::string *ErrMsg) { - + llvm::OwningPtr AST(new ASTUnit()); AST->DiagClient.reset(new TextDiagnosticBuffer()); @@ -96,12 +96,12 @@ ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, AST->HeaderInfo.reset(new HeaderSearch(FileMgr)); AST->SourceMgr.reset(new SourceManager()); - + Diagnostic &Diags = *AST->Diags.get(); SourceManager &SourceMgr = *AST->SourceMgr.get(); // Gather Info for preprocessor construction later on. - + LangOptions LangInfo; HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); std::string TargetTriple; @@ -118,16 +118,16 @@ ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, switch (Reader->ReadPCH(Filename)) { case PCHReader::Success: break; - + case PCHReader::Failure: case PCHReader::IgnorePCH: if (ErrMsg) *ErrMsg = "Could not load PCH file"; return NULL; } - + // PCH loaded successfully. Now create the preprocessor. - + // Get information about the target being compiled for. AST->Target.reset(TargetInfo::CreateTargetInfo(TargetTriple)); AST->PP.reset(new Preprocessor(Diags, LangInfo, *AST->Target.get(), @@ -137,7 +137,7 @@ ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, PP.setPredefines(Predefines); PP.setCounterValue(Counter); Reader->setPreprocessor(PP); - + // Create and initialize the ASTContext. AST->Ctx.reset(new ASTContext(LangInfo, @@ -149,14 +149,14 @@ ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, /* FreeMemory = */ true, /* size_reserve = */0)); ASTContext &Context = *AST->Ctx.get(); - + Reader->InitializeContext(Context); - + // Attach the PCH reader to the AST context as an external AST // source, so that declarations will be deserialized from the // PCH file as needed. Source.reset(Reader.take()); Context.setExternalSource(Source); - return AST.take(); + return AST.take(); } diff --git a/clang/lib/Frontend/AnalysisConsumer.cpp b/clang/lib/Frontend/AnalysisConsumer.cpp index a633a62df293169fa29833c6921d745d97f7869d..2d07d89e0449dd005c9e21539795d4354e670e4d 100644 --- a/clang/lib/Frontend/AnalysisConsumer.cpp +++ b/clang/lib/Frontend/AnalysisConsumer.cpp @@ -44,7 +44,7 @@ static ExplodedNode::Auditor* CreateUbiViz(); // Basic type definitions. //===----------------------------------------------------------------------===// -namespace { +namespace { typedef void (*CodeAction)(AnalysisManager& Mgr); } // end anonymous namespace @@ -55,8 +55,8 @@ namespace { static PathDiagnosticClient* CreatePlistHTMLDiagnosticClient(const std::string& prefix, Preprocessor* PP, PreprocessorFactory* PPF) { - llvm::sys::Path F(prefix); - PathDiagnosticClientFactory *PF = + llvm::sys::Path F(prefix); + PathDiagnosticClientFactory *PF = CreateHTMLDiagnosticClientFactory(F.getDirname(), PP, PPF); return CreatePlistDiagnosticClient(prefix, PP, PPF, PF); } @@ -73,9 +73,9 @@ namespace { Actions ObjCMethodActions; Actions ObjCImplementationActions; Actions TranslationUnitActions; - + public: - const LangOptions& LOpts; + const LangOptions& LOpts; Diagnostic &Diags; ASTContext* Ctx; Preprocessor* PP; @@ -127,7 +127,7 @@ namespace { #include "clang/Frontend/Analyses.def" } } - + if (ManagerRegistry::ConstraintMgrCreator != 0) CreateConstraintMgr = ManagerRegistry::ConstraintMgrCreator; else { @@ -140,42 +140,42 @@ namespace { } } } - + void addCodeAction(CodeAction action) { FunctionActions.push_back(action); ObjCMethodActions.push_back(action); } - + void addObjCImplementationAction(CodeAction action) { ObjCImplementationActions.push_back(action); } - + void addTranslationUnitAction(CodeAction action) { TranslationUnitActions.push_back(action); } - + virtual void Initialize(ASTContext &Context) { Ctx = &Context; - Mgr.reset(new AnalysisManager(*Ctx, Diags, LOpts, PD, + Mgr.reset(new AnalysisManager(*Ctx, Diags, LOpts, PD, CreateStoreMgr, CreateConstraintMgr, - Opts.AnalyzerDisplayProgress, - Opts.VisualizeEGDot, Opts.VisualizeEGUbi, + Opts.AnalyzerDisplayProgress, + Opts.VisualizeEGDot, Opts.VisualizeEGUbi, Opts.PurgeDead, Opts.EagerlyAssume, Opts.TrimGraph)); } - + virtual void HandleTopLevelDecl(DeclGroupRef D) { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) HandleTopLevelSingleDecl(*I); } - + void HandleTopLevelSingleDecl(Decl *D); virtual void HandleTranslationUnit(ASTContext &C); - + void HandleCode(Decl* D, Stmt* Body, Actions& actions); }; - - + + } // end anonymous namespace @@ -184,54 +184,54 @@ namespace llvm { static inline void Profile(CodeAction X, FoldingSetNodeID& ID) { ID.AddPointer(reinterpret_cast(reinterpret_cast(X))); } - }; + }; } //===----------------------------------------------------------------------===// // AnalysisConsumer implementation. //===----------------------------------------------------------------------===// -void AnalysisConsumer::HandleTopLevelSingleDecl(Decl *D) { +void AnalysisConsumer::HandleTopLevelSingleDecl(Decl *D) { switch (D->getKind()) { case Decl::Function: { FunctionDecl* FD = cast(D); - if (Opts.AnalyzeSpecificFunction.size() > 0 && + if (Opts.AnalyzeSpecificFunction.size() > 0 && Opts.AnalyzeSpecificFunction != FD->getIdentifier()->getName()) break; - + Stmt* Body = FD->getBody(); if (Body) HandleCode(FD, Body, FunctionActions); break; } - + case Decl::ObjCMethod: { ObjCMethodDecl* MD = cast(D); - + if (Opts.AnalyzeSpecificFunction.size() > 0 && Opts.AnalyzeSpecificFunction != MD->getSelector().getAsString()) return; - + Stmt* Body = MD->getBody(); if (Body) HandleCode(MD, Body, ObjCMethodActions); break; } - + default: break; } } void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { - if(!TranslationUnitActions.empty()) { - for (Actions::iterator I = TranslationUnitActions.begin(), + if (!TranslationUnitActions.empty()) { + for (Actions::iterator I = TranslationUnitActions.begin(), E = TranslationUnitActions.end(); I != E; ++I) - (*I)(*Mgr); + (*I)(*Mgr); } if (!ObjCImplementationActions.empty()) { TranslationUnitDecl *TUD = C.getTranslationUnitDecl(); - + for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end(); I != E; ++I) @@ -246,7 +246,7 @@ void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { } void AnalysisConsumer::HandleCode(Decl* D, Stmt* Body, Actions& actions) { - + // Don't run the actions if an error has occured with parsing the file. if (Diags.hasErrorOccurred()) return; @@ -255,13 +255,13 @@ void AnalysisConsumer::HandleCode(Decl* D, Stmt* Body, Actions& actions) { // otherwise specified. if (!Opts.AnalyzeAll && !Ctx->getSourceManager().isFromMainFile(D->getLocation())) - return; + return; Mgr->setEntryContext(D); - - // Dispatch on the actions. + + // Dispatch on the actions. for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I) - (*I)(*Mgr); + (*I)(*Mgr); } //===----------------------------------------------------------------------===// @@ -283,8 +283,8 @@ static void ActionWarnUninitVals(AnalysisManager& mgr) { static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf, bool StandardWarnings = true) { - - + + llvm::OwningPtr TF(tf); // Display progress. @@ -297,7 +297,7 @@ static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf, GRExprEngine Eng(mgr); Eng.setTransferFunctions(tf); - + if (StandardWarnings) { Eng.RegisterInternalChecks(); RegisterAppleChecks(Eng, *mgr.getCodeDecl()); @@ -309,10 +309,10 @@ static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf, Auditor.reset(CreateUbiViz()); ExplodedNode::SetAuditor(Auditor.get()); } - + // Execute the worklist algorithm. Eng.ExecuteWorkList(mgr.getEntryStackFrame()); - + // Release the auditor (if any) so that it doesn't monitor the graph // created BugReporter. ExplodedNode::SetAuditor(0); @@ -320,34 +320,34 @@ static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf, // Visualize the exploded graph. if (mgr.shouldVisualizeGraphviz()) Eng.ViewGraph(mgr.shouldTrimGraph()); - + // Display warnings. Eng.getBugReporter().FlushReports(); } static void ActionCheckerCFRefAux(AnalysisManager& mgr, bool GCEnabled, bool StandardWarnings) { - + GRTransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(), GCEnabled, mgr.getLangOptions()); - + ActionGRExprEngine(mgr, TF, StandardWarnings); } static void ActionCheckerCFRef(AnalysisManager& mgr) { - + switch (mgr.getLangOptions().getGCMode()) { default: assert (false && "Invalid GC mode."); case LangOptions::NonGC: ActionCheckerCFRefAux(mgr, false, true); break; - + case LangOptions::GCOnly: ActionCheckerCFRefAux(mgr, true, true); break; - + case LangOptions::HybridGC: ActionCheckerCFRefAux(mgr, false, true); ActionCheckerCFRefAux(mgr, true, false); @@ -357,7 +357,7 @@ static void ActionCheckerCFRef(AnalysisManager& mgr) { static void ActionDisplayLiveVariables(AnalysisManager& mgr) { if (LiveVariables* L = mgr.getLiveVariables()) { - mgr.DisplayFunction(); + mgr.DisplayFunction(); L->dumpBlockLiveness(mgr.getSourceManager()); } } @@ -377,28 +377,28 @@ static void ActionCFGView(AnalysisManager& mgr) { } static void ActionSecuritySyntacticChecks(AnalysisManager &mgr) { - BugReporter BR(mgr); + BugReporter BR(mgr); CheckSecuritySyntaxOnly(mgr.getCodeDecl(), BR); } static void ActionWarnObjCDealloc(AnalysisManager& mgr) { if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly) return; - + BugReporter BR(mgr); - - CheckObjCDealloc(cast(mgr.getCodeDecl()), - mgr.getLangOptions(), BR); + + CheckObjCDealloc(cast(mgr.getCodeDecl()), + mgr.getLangOptions(), BR); } static void ActionWarnObjCUnusedIvars(AnalysisManager& mgr) { BugReporter BR(mgr); - CheckObjCUnusedIvar(cast(mgr.getCodeDecl()), BR); + CheckObjCUnusedIvar(cast(mgr.getCodeDecl()), BR); } static void ActionWarnObjCMethSigs(AnalysisManager& mgr) { BugReporter BR(mgr); - + CheckObjCInstMethSignature(cast(mgr.getCodeDecl()), BR); } @@ -426,7 +426,7 @@ ASTConsumer* clang::CreateAnalysisConsumer(Diagnostic &diags, Preprocessor* pp, #include "clang/Frontend/Analyses.def" default: break; } - + // Last, disable the effects of '-Werror' when using the AnalysisConsumer. diags.setWarningsAsErrors(false); @@ -438,7 +438,7 @@ ASTConsumer* clang::CreateAnalysisConsumer(Diagnostic &diags, Preprocessor* pp, //===----------------------------------------------------------------------===// namespace { - + class UbigraphViz : public ExplodedNode::Auditor { llvm::OwningPtr Out; llvm::sys::Path Dir, Filename; @@ -446,21 +446,21 @@ class UbigraphViz : public ExplodedNode::Auditor { typedef llvm::DenseMap VMap; VMap M; - + public: UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir, llvm::sys::Path& filename); - + ~UbigraphViz(); - - virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst); + + virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst); }; - + } // end anonymous namespace static ExplodedNode::Auditor* CreateUbiViz() { std::string ErrMsg; - + llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); if (!ErrMsg.empty()) return 0; @@ -473,31 +473,31 @@ static ExplodedNode::Auditor* CreateUbiViz() { return 0; llvm::errs() << "Writing '" << Filename.str() << "'.\n"; - + llvm::OwningPtr Stream; Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); if (!ErrMsg.empty()) return 0; - + return new UbigraphViz(Stream.take(), Dir, Filename); } void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) { - + assert (Src != Dst && "Self-edges are not allowed."); - + // Lookup the Src. If it is a new node, it's a root. VMap::iterator SrcI= M.find(Src); unsigned SrcID; - + if (SrcI == M.end()) { M[Src] = SrcID = Cntr++; *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; } else SrcID = SrcI->second; - + // Lookup the Dst. VMap::iterator DstI= M.find(Dst); unsigned DstID; @@ -513,7 +513,7 @@ void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) { } // Add the edge. - *Out << "('edge', " << SrcID << ", " << DstID + *Out << "('edge', " << SrcID << ", " << DstID << ", ('arrow','true'), ('oriented', 'true'))\n"; } @@ -535,11 +535,11 @@ UbigraphViz::~UbigraphViz() { args.push_back(Ubiviz.c_str()); args.push_back(Filename.c_str()); args.push_back(0); - + if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; } - + // Delete the directory. - Dir.eraseFromDisk(true); + Dir.eraseFromDisk(true); } diff --git a/clang/lib/Frontend/Backend.cpp b/clang/lib/Frontend/Backend.cpp index 964b4700fe0716b64e60f0076c0db6dafa2bd032..d7097b7f06a0b16c6c1d9b0250d75f5b05ffde79 100644 --- a/clang/lib/Frontend/Backend.cpp +++ b/clang/lib/Frontend/Backend.cpp @@ -47,9 +47,9 @@ namespace { Timer LLVMIRGeneration; Timer CodeGenerationTime; - + llvm::OwningPtr Gen; - + llvm::Module *TheModule; llvm::TargetData *TheTargetData; @@ -72,13 +72,13 @@ namespace { bool AddEmitPasses(std::string &Error); void EmitAssembly(); - - public: - BackendConsumer(BackendAction action, Diagnostic &Diags, + + public: + BackendConsumer(BackendAction action, Diagnostic &Diags, const LangOptions &langopts, const CompileOptions &compopts, const std::string &infile, llvm::raw_ostream* OS, LLVMContext& C) : - Action(action), + Action(action), CompileOpts(compopts), AsmOutStream(OS), LLVMIRGeneration("LLVM IR Generation Time"), @@ -86,11 +86,11 @@ namespace { Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)), TheModule(0), TheTargetData(0), ModuleProvider(0), CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) { - + if (AsmOutStream) FormattedOutStream.setStream(*AsmOutStream, formatted_raw_ostream::PRESERVE_STREAM); - + // Enable -time-passes if -ftime-report is enabled. llvm::TimePassesIsEnabled = CompileOpts.TimePasses; } @@ -105,25 +105,25 @@ namespace { virtual void Initialize(ASTContext &Ctx) { Context = &Ctx; - + if (CompileOpts.TimePasses) LLVMIRGeneration.startTimer(); - + Gen->Initialize(Ctx); TheModule = Gen->GetModule(); ModuleProvider = new ExistingModuleProvider(TheModule); TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription()); - + if (CompileOpts.TimePasses) LLVMIRGeneration.stopTimer(); } - + virtual void HandleTopLevelDecl(DeclGroupRef D) { PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); - + if (CompileOpts.TimePasses) LLVMIRGeneration.startTimer(); @@ -132,7 +132,7 @@ namespace { if (CompileOpts.TimePasses) LLVMIRGeneration.stopTimer(); } - + virtual void HandleTranslationUnit(ASTContext &C) { { PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); @@ -147,12 +147,12 @@ namespace { // EmitAssembly times and registers crash info itself. EmitAssembly(); - + // Force a flush here in case we never get released. if (AsmOutStream) FormattedOutStream.flush(); } - + virtual void HandleTagDeclDefinition(TagDecl *D) { PrettyStackTraceDecl CrashInfo(D, SourceLocation(), Context->getSourceManager(), @@ -163,7 +163,7 @@ namespace { virtual void CompleteTentativeDefinition(VarDecl *D) { Gen->CompleteTentativeDefinition(D); } - }; + }; } FunctionPassManager *BackendConsumer::getCodeGenPasses() const { @@ -216,18 +216,18 @@ bool BackendConsumer::AddEmitPasses(std::string &Error) { if (CompileOpts.CPU.size() || CompileOpts.Features.size()) { SubtargetFeatures Features; Features.setCPU(CompileOpts.CPU); - for (std::vector::iterator + for (std::vector::iterator it = CompileOpts.Features.begin(), ie = CompileOpts.Features.end(); it != ie; ++it) Features.AddFeature(*it); FeaturesStr = Features.getString(); } TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr); - + // Set register scheduler & allocation policy. RegisterScheduler::setDefault(createDefaultScheduler); - RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator : - createLinearScanRegisterAllocator); + RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator : + createLinearScanRegisterAllocator); // From llvm-gcc: // If there are passes we have to run on the entire module, we do codegen @@ -254,7 +254,7 @@ bool BackendConsumer::AddEmitPasses(std::string &Error) { case FileModel::AsmFile: break; } - + if (TM->addPassesToEmitFileFinish(*CodeGenPasses, (MachineCodeEmitter *)0, OptLevel)) { Error = "Unable to interface with target machine!\n"; @@ -292,8 +292,8 @@ void BackendConsumer::CreatePasses() { // For now we always create per module passes. PassManager *PM = getPerModulePasses(); - llvm::createStandardModulePasses(PM, CompileOpts.OptimizationLevel, - CompileOpts.OptimizeSize, + llvm::createStandardModulePasses(PM, CompileOpts.OptimizationLevel, + CompileOpts.OptimizeSize, CompileOpts.UnitAtATime, CompileOpts.UnrollLoops, CompileOpts.SimplifyLibCalls, @@ -302,12 +302,12 @@ void BackendConsumer::CreatePasses() { } /// EmitAssembly - Handle interaction with LLVM backend to generate -/// actual machine code. +/// actual machine code. void BackendConsumer::EmitAssembly() { // Silently ignore if we weren't initialized for some reason. if (!TheModule || !TheTargetData) return; - + TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0); // Make sure IR generation is happy with the module. This is @@ -337,19 +337,19 @@ void BackendConsumer::EmitAssembly() { if (PerFunctionPasses) { PrettyStackTraceString CrashInfo("Per-function optimization"); - + PerFunctionPasses->doInitialization(); for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if (!I->isDeclaration()) PerFunctionPasses->run(*I); PerFunctionPasses->doFinalization(); } - + if (PerModulePasses) { PrettyStackTraceString CrashInfo("Per-module optimization passes"); PerModulePasses->run(*M); } - + if (CodeGenPasses) { PrettyStackTraceString CrashInfo("Code generation"); CodeGenPasses->doInitialization(); diff --git a/clang/lib/Frontend/CacheTokens.cpp b/clang/lib/Frontend/CacheTokens.cpp index 7365882eb8da58349bd33308f9323d972b490d99..e7fc5660ad206042e850efb55223683a6af8cd31 100644 --- a/clang/lib/Frontend/CacheTokens.cpp +++ b/clang/lib/Frontend/CacheTokens.cpp @@ -40,19 +40,19 @@ using namespace clang::io; namespace { class VISIBILITY_HIDDEN PTHEntry { - Offset TokenData, PPCondData; + Offset TokenData, PPCondData; -public: +public: PTHEntry() {} PTHEntry(Offset td, Offset ppcd) : TokenData(td), PPCondData(ppcd) {} - - Offset getTokenOffset() const { return TokenData; } + + Offset getTokenOffset() const { return TokenData; } Offset getPPCondTableOffset() const { return PPCondData; } }; - - + + class VISIBILITY_HIDDEN PTHEntryKeyVariant { union { const FileEntry* FE; const char* Path; }; enum { IsFE = 0x1, IsDE = 0x2, IsNoExist = 0x0 } Kind; @@ -66,15 +66,15 @@ public: PTHEntryKeyVariant(const char* path) : Path(path), Kind(IsNoExist), StatBuf(0) {} - + bool isFile() const { return Kind == IsFE; } - + const char* getCString() const { return Kind == IsFE ? FE->getName() : Path; } - + unsigned getKind() const { return (unsigned) Kind; } - + void EmitData(llvm::raw_ostream& Out) { switch (Kind) { case IsFE: @@ -98,45 +98,45 @@ public: break; } } - + unsigned getRepresentationLength() const { return Kind == IsNoExist ? 0 : 4 + 4 + 2 + 8 + 8; } }; - + class VISIBILITY_HIDDEN FileEntryPTHEntryInfo { public: typedef PTHEntryKeyVariant key_type; typedef key_type key_type_ref; - + typedef PTHEntry data_type; typedef const PTHEntry& data_type_ref; - + static unsigned ComputeHash(PTHEntryKeyVariant V) { return BernsteinHash(V.getCString()); } - - static std::pair + + static std::pair EmitKeyDataLength(llvm::raw_ostream& Out, PTHEntryKeyVariant V, const PTHEntry& E) { unsigned n = strlen(V.getCString()) + 1 + 1; ::Emit16(Out, n); - + unsigned m = V.getRepresentationLength() + (V.isFile() ? 4 + 4 : 0); ::Emit8(Out, m); return std::make_pair(n, m); } - + static void EmitKey(llvm::raw_ostream& Out, PTHEntryKeyVariant V, unsigned n){ // Emit the entry kind. ::Emit8(Out, (unsigned) V.getKind()); // Emit the string. Out.write(V.getCString(), n - 1); } - - static void EmitData(llvm::raw_ostream& Out, PTHEntryKeyVariant V, + + static void EmitData(llvm::raw_ostream& Out, PTHEntryKeyVariant V, const PTHEntry& E, unsigned) { @@ -146,12 +146,12 @@ public: ::Emit32(Out, E.getTokenOffset()); ::Emit32(Out, E.getPPCondTableOffset()); } - + // Emit any other data associated with the key (i.e., stat information). V.EmitData(Out); - } + } }; - + class OffsetOpt { bool valid; Offset off; @@ -180,16 +180,16 @@ class VISIBILITY_HIDDEN PTHWriter { //// Get the persistent id for the given IdentifierInfo*. uint32_t ResolveID(const IdentifierInfo* II); - + /// Emit a token to the PTH file. void EmitToken(const Token& T); void Emit8(uint32_t V) { Out << (unsigned char)(V); } - + void Emit16(uint32_t V) { ::Emit16(Out, V); } - + void Emit24(uint32_t V) { Out << (unsigned char)(V); Out << (unsigned char)(V >> 8); @@ -202,13 +202,13 @@ class VISIBILITY_HIDDEN PTHWriter { void EmitBuf(const char *Ptr, unsigned NumBytes) { Out.write(Ptr, NumBytes); } - + /// EmitIdentifierTable - Emits two tables to the PTH file. The first is /// a hashtable mapping from identifier strings to persistent IDs. /// The second is a straight table mapping from persistent IDs to string data /// (the keys of the first table). std::pair EmitIdentifierTable(); - + /// EmitFileTable - Emit a table mapping from file name strings to PTH /// token data. Offset EmitFileTable() { return PM.Emit(Out); } @@ -217,23 +217,23 @@ class VISIBILITY_HIDDEN PTHWriter { Offset EmitCachedSpellings(); public: - PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp) + PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp) : Out(out), PP(pp), idcount(0), CurStrOffset(0) {} - + PTHMap &getPM() { return PM; } void GeneratePTH(const std::string *MainFile = 0); }; } // end anonymous namespace - -uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) { + +uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) { // Null IdentifierInfo's map to the persistent ID 0. if (!II) return 0; - + IDMap::iterator I = IM.find(II); if (I != IM.end()) return I->second; // We've already added 1. - + IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL. return idcount; } @@ -242,7 +242,7 @@ void PTHWriter::EmitToken(const Token& T) { // Emit the token kind, flags, and length. Emit32(((uint32_t) T.getKind()) | ((((uint32_t) T.getFlags())) << 8)| (((uint32_t) T.getLength()) << 16)); - + if (!T.isLiteral()) { Emit32(ResolveID(T.getIdentifierInfo())); } else { @@ -253,18 +253,18 @@ void PTHWriter::EmitToken(const Token& T) { // Get the string entry. llvm::StringMapEntry *E = &CachedStrs.GetOrCreateValue(s, s+len); - + // If this is a new string entry, bump the PTH offset. if (!E->getValue().hasOffset()) { E->getValue().setOffset(CurStrOffset); StrEntries.push_back(E); CurStrOffset += len + 1; } - + // Emit the relative offset into the PTH file for the spelling string. Emit32(E->getValue().getOffset()); } - + // Emit the offset into the original source file of this token so that we // can reconstruct its SourceLocation. Emit32(PP.getSourceManager().getFileOffset(T.getLocation())); @@ -275,14 +275,14 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { // This speed up reading them back in. Pad(Out, 4); Offset off = (Offset) Out.tell(); - + // Keep track of matching '#if' ... '#endif'. typedef std::vector > PPCondTable; PPCondTable PPCond; std::vector PPStartCond; bool ParsingPreprocessorDirective = false; Token Tok; - + do { L.LexFromRawLexer(Tok); NextToken: @@ -300,7 +300,7 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { EmitToken(Tmp); ParsingPreprocessorDirective = false; } - + if (Tok.is(tok::identifier)) { Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok)); EmitToken(Tok); @@ -320,39 +320,39 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { // If we see the start of line, then we had a null directive "#". if (Tok.isAtStartOfLine()) goto NextToken; - + // Did we see 'include'/'import'/'include_next'? if (Tok.isNot(tok::identifier)) { EmitToken(Tok); continue; } - + IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok); Tok.setIdentifierInfo(II); tok::PPKeywordKind K = II->getPPKeywordID(); - + ParsingPreprocessorDirective = true; - + switch (K) { case tok::pp_not_keyword: // Invalid directives "#foo" can occur in #if 0 blocks etc, just pass // them through. default: break; - + case tok::pp_include: case tok::pp_import: - case tok::pp_include_next: { + case tok::pp_include_next: { // Save the 'include' token. EmitToken(Tok); // Lex the next token as an include string. L.setParsingPreprocessorDirective(true); - L.LexIncludeFilename(Tok); + L.LexIncludeFilename(Tok); L.setParsingPreprocessorDirective(false); assert(!Tok.isAtStartOfLine()); if (Tok.is(tok::identifier)) Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok)); - + break; } case tok::pp_if: @@ -374,11 +374,11 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { assert(PPCond.size() > PPStartCond.back()); assert(PPCond[PPStartCond.back()].second == 0); PPCond[PPStartCond.back()].second = index; - PPStartCond.pop_back(); - // Add the new entry to PPCond. + PPStartCond.pop_back(); + // Add the new entry to PPCond. PPCond.push_back(std::make_pair(HashOff, index)); EmitToken(Tok); - + // Some files have gibberish on the same line as '#endif'. // Discard these tokens. do @@ -386,7 +386,7 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { while (Tok.isNot(tok::eof) && !Tok.isAtStartOfLine()); // We have the next token in hand. // Don't immediately lex the next one. - goto NextToken; + goto NextToken; } case tok::pp_elif: case tok::pp_else: { @@ -407,7 +407,7 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { } } } - + EmitToken(Tok); } while (Tok.isNot(tok::eof)); @@ -435,11 +435,11 @@ PTHEntry PTHWriter::LexTokens(Lexer& L) { Offset PTHWriter::EmitCachedSpellings() { // Write each cached strings to the PTH file. Offset SpellingsOff = Out.tell(); - + for (std::vector*>::iterator I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) EmitBuf((*I)->getKeyData(), (*I)->getKeyLength()+1 /*nul included*/); - + return SpellingsOff; } @@ -447,12 +447,12 @@ void PTHWriter::GeneratePTH(const std::string *MainFile) { // Generate the prologue. Out << "cfe-pth"; Emit32(PTHManager::Version); - + // Leave 4 words for the prologue. Offset PrologueOffset = Out.tell(); for (unsigned i = 0; i < 4; ++i) Emit32(0); - + // Write the name of the MainFile. if (MainFile && !MainFile->empty()) { Emit16(MainFile->length()); @@ -462,17 +462,17 @@ void PTHWriter::GeneratePTH(const std::string *MainFile) { Emit16(0); } Emit8(0); - + // Iterate over all the files in SourceManager. Create a lexer // for each file and cache the tokens. SourceManager &SM = PP.getSourceManager(); const LangOptions &LOpts = PP.getLangOptions(); - + for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(), E = SM.fileinfo_end(); I != E; ++I) { const SrcMgr::ContentCache &C = *I->second; const FileEntry *FE = C.Entry; - + // FIXME: Handle files with non-absolute paths. llvm::sys::Path P(FE->getName()); if (!P.isAbsolute()) @@ -488,13 +488,13 @@ void PTHWriter::GeneratePTH(const std::string *MainFile) { // Write out the identifier table. const std::pair &IdTableOff = EmitIdentifierTable(); - + // Write out the cached strings table. Offset SpellingOff = EmitCachedSpellings(); - + // Write out the file table. - Offset FileTableOff = EmitFileTable(); - + Offset FileTableOff = EmitFileTable(); + // Finally, write the prologue. Out.seek(PrologueOffset); Emit32(IdTableOff.first); @@ -514,20 +514,20 @@ class StatListener : public StatSysCallCache { public: StatListener(PTHMap &pm) : PM(pm) {} ~StatListener() {} - + int stat(const char *path, struct stat *buf) { int result = ::stat(path, buf); - + if (result != 0) // Failed 'stat'. PM.insert(path, PTHEntry()); else if (S_ISDIR(buf->st_mode)) { // Only cache directories with absolute paths. if (!llvm::sys::Path(path).isAbsolute()) return result; - + PM.insert(PTHEntryKeyVariant(buf, path), PTHEntry()); } - + return result; } }; @@ -540,7 +540,7 @@ void clang::CacheTokens(Preprocessor &PP, llvm::raw_fd_ostream* OS) { const FileEntry *MainFile = SrcMgr.getFileEntryForID(SrcMgr.getMainFileID()); llvm::sys::Path MainFilePath(MainFile->getName()); std::string MainFileName; - + if (!MainFilePath.isAbsolute()) { llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory(); P.appendComponent(MainFilePath.str()); @@ -551,16 +551,16 @@ void clang::CacheTokens(Preprocessor &PP, llvm::raw_fd_ostream* OS) { // Create the PTHWriter. PTHWriter PW(*OS, PP); - + // Install the 'stat' system call listener in the FileManager. PP.getFileManager().setStatCache(new StatListener(PW.getPM())); - + // Lex through the entire file. This will populate SourceManager with // all of the header information. Token Tok; PP.EnterMainSourceFile(); do { PP.Lex(Tok); } while (Tok.isNot(tok::eof)); - + // Generate the PTH file. PP.getFileManager().setStatCache(0); PW.GeneratePTH(&MainFileName); @@ -579,32 +579,32 @@ class VISIBILITY_HIDDEN PTHIdentifierTableTrait { public: typedef PTHIdKey* key_type; typedef key_type key_type_ref; - + typedef uint32_t data_type; typedef data_type data_type_ref; - + static unsigned ComputeHash(PTHIdKey* key) { return BernsteinHash(key->II->getName()); } - - static std::pair - EmitKeyDataLength(llvm::raw_ostream& Out, const PTHIdKey* key, uint32_t) { + + static std::pair + EmitKeyDataLength(llvm::raw_ostream& Out, const PTHIdKey* key, uint32_t) { unsigned n = strlen(key->II->getName()) + 1; ::Emit16(Out, n); return std::make_pair(n, sizeof(uint32_t)); } - + static void EmitKey(llvm::raw_ostream& Out, PTHIdKey* key, unsigned n) { // Record the location of the key data. This is used when generating // the mapping from persistent IDs to strings. key->FileOffset = Out.tell(); Out.write(key->II->getName(), n); } - + static void EmitData(llvm::raw_ostream& Out, PTHIdKey*, uint32_t pID, unsigned) { ::Emit32(Out, pID); - } + } }; } // end anonymous namespace @@ -623,7 +623,7 @@ std::pair PTHWriter::EmitIdentifierTable() { // Create the hashtable. OnDiskChainedHashTableGenerator IIOffMap; - + // Generate mapping from persistent IDs -> IdentifierInfo*. for (IDMap::iterator I = IM.begin(), E = IM.end(); I != E; ++I) { // Decrement by 1 because we are using a vector for the lookup and @@ -631,27 +631,27 @@ std::pair PTHWriter::EmitIdentifierTable() { assert(I->second > 0); assert(I->second-1 < idcount); unsigned idx = I->second-1; - + // Store the mapping from persistent ID to IdentifierInfo* IIDMap[idx].II = I->first; - + // Store the reverse mapping in a hashtable. IIOffMap.insert(&IIDMap[idx], I->second); } - + // Write out the inverse map first. This causes the PCIDKey entries to // record PTH file offsets for the string data. This is used to write // the second table. Offset StringTableOffset = IIOffMap.Emit(Out); - - // Now emit the table mapping from persistent IDs to PTH file offsets. + + // Now emit the table mapping from persistent IDs to PTH file offsets. Offset IDOff = Out.tell(); Emit32(idcount); // Emit the number of identifiers. for (unsigned i = 0 ; i < idcount; ++i) Emit32(IIDMap[i].FileOffset); - + // Finally, release the inverse map. free(IIDMap); - + return std::make_pair(IDOff, StringTableOffset); } diff --git a/clang/lib/Frontend/DeclXML.cpp b/clang/lib/Frontend/DeclXML.cpp index 68f931fb6c699b6fc3410797c88755366d4dc97f..b981fc41daa948e7653900dfc926da81c386732b 100644 --- a/clang/lib/Frontend/DeclXML.cpp +++ b/clang/lib/Frontend/DeclXML.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements the XML document class, which provides the means to +// This file implements the XML document class, which provides the means to // dump out the AST in a XML form that exposes type details and other fields. // //===----------------------------------------------------------------------===// @@ -18,22 +18,18 @@ namespace clang { -//--------------------------------------------------------- -class DocumentXML::DeclPrinter : public DeclVisitor -{ +//--------------------------------------------------------- +class DocumentXML::DeclPrinter : public DeclVisitor { DocumentXML& Doc; - void addSubNodes(FunctionDecl* FD) - { - for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) - { + void addSubNodes(FunctionDecl* FD) { + for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { Visit(FD->getParamDecl(i)); Doc.toParent(); } } - void addSubNodes(RecordDecl* RD) - { + void addSubNodes(RecordDecl* RD) { for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i) { Visit(*i); @@ -41,8 +37,7 @@ class DocumentXML::DeclPrinter : public DeclVisitor } } - void addSubNodes(EnumDecl* ED) - { + void addSubNodes(EnumDecl* ED) { for (EnumDecl::enumerator_iterator i = ED->enumerator_begin(), e = ED->enumerator_end(); i != e; ++i) { Visit(*i); @@ -50,54 +45,37 @@ class DocumentXML::DeclPrinter : public DeclVisitor } } - void addSubNodes(EnumConstantDecl* ECD) - { - if (ECD->getInitExpr()) - { + void addSubNodes(EnumConstantDecl* ECD) { + if (ECD->getInitExpr()) Doc.PrintStmt(ECD->getInitExpr()); - } } - void addSubNodes(FieldDecl* FdD) - { + void addSubNodes(FieldDecl* FdD) { if (FdD->isBitField()) - { Doc.PrintStmt(FdD->getBitWidth()); - } } - void addSubNodes(VarDecl* V) - { - if (V->getInit()) - { + void addSubNodes(VarDecl* V) { + if (V->getInit()) Doc.PrintStmt(V->getInit()); - } } - void addSubNodes(ParmVarDecl* argDecl) - { + void addSubNodes(ParmVarDecl* argDecl) { if (argDecl->getDefaultArg()) - { Doc.PrintStmt(argDecl->getDefaultArg()); - } } - void addSpecialAttribute(const char* pName, EnumDecl* ED) - { + void addSpecialAttribute(const char* pName, EnumDecl* ED) { const QualType& enumType = ED->getIntegerType(); if (!enumType.isNull()) - { Doc.addAttribute(pName, enumType); - } } - void addIdAttribute(LinkageSpecDecl* ED) - { + void addIdAttribute(LinkageSpecDecl* ED) { Doc.addAttribute("id", ED); } - void addIdAttribute(NamedDecl* ND) - { + void addIdAttribute(NamedDecl* ND) { Doc.addAttribute("id", ND); } @@ -107,11 +85,11 @@ public: #define NODE_XML( CLASS, NAME ) \ void Visit##CLASS(CLASS* T) \ { \ - Doc.addSubNode(NAME); + Doc.addSubNode(NAME); #define ID_ATTRIBUTE_XML addIdAttribute(T); -#define ATTRIBUTE_XML( FN, NAME ) Doc.addAttribute(NAME, T->FN); -#define ATTRIBUTE_OPT_XML( FN, NAME ) Doc.addAttributeOptional(NAME, T->FN); +#define ATTRIBUTE_XML( FN, NAME ) Doc.addAttribute(NAME, T->FN); +#define ATTRIBUTE_OPT_XML( FN, NAME ) Doc.addAttributeOptional(NAME, T->FN); #define ATTRIBUTE_FILE_LOCATION_XML Doc.addLocation(T->getLocation()); #define ATTRIBUTE_SPECIAL_XML( FN, NAME ) addSpecialAttribute(NAME, T); @@ -120,14 +98,14 @@ public: const char* pAttributeName = NAME; \ const bool optional = false; \ switch (T->FN) { \ - default: assert(0 && "unknown enum value"); + default: assert(0 && "unknown enum value"); #define ATTRIBUTE_ENUM_OPT_XML( FN, NAME ) \ { \ const char* pAttributeName = NAME; \ const bool optional = true; \ switch (T->FN) { \ - default: assert(0 && "unknown enum value"); + default: assert(0 && "unknown enum value"); #define ENUM_XML( VALUE, NAME ) case VALUE: if ((!optional) || NAME[0]) Doc.addAttribute(pAttributeName, NAME); break; #define END_ENUM_XML } } @@ -141,12 +119,10 @@ public: }; -//--------------------------------------------------------- -void DocumentXML::writeDeclToXML(Decl *D) -{ +//--------------------------------------------------------- +void DocumentXML::writeDeclToXML(Decl *D) { DeclPrinter(*this).Visit(D); - if (FunctionDecl *FD = dyn_cast(D)) - { + if (FunctionDecl *FD = dyn_cast(D)) { if (Stmt *Body = FD->getBody()) { addSubNode("Body"); PrintStmt(Body); @@ -156,6 +132,6 @@ void DocumentXML::writeDeclToXML(Decl *D) toParent(); } -//--------------------------------------------------------- +//--------------------------------------------------------- } // NS clang diff --git a/clang/lib/Frontend/DependencyFile.cpp b/clang/lib/Frontend/DependencyFile.cpp index c8a654cff2c4fe0c826d6f46b9f4d22c18b86932..81d1179f28e36b382e0d657e0527216792f39376 100644 --- a/clang/lib/Frontend/DependencyFile.cpp +++ b/clang/lib/Frontend/DependencyFile.cpp @@ -40,8 +40,8 @@ private: void OutputDependencyFile(); public: - DependencyFileCallback(const Preprocessor *_PP, - llvm::raw_ostream *_OS, + DependencyFileCallback(const Preprocessor *_PP, + llvm::raw_ostream *_OS, const std::vector &_Targets, bool _IncludeSystemHeaders, bool _PhonyTarget) @@ -67,8 +67,8 @@ void clang::AttachDependencyFileGen(Preprocessor *PP, llvm::raw_ostream *OS, bool PhonyTarget) { assert(!Targets.empty() && "Target required for dependency generation"); - DependencyFileCallback *PPDep = - new DependencyFileCallback(PP, OS, Targets, IncludeSystemHeaders, + DependencyFileCallback *PPDep = + new DependencyFileCallback(PP, OS, Targets, IncludeSystemHeaders, PhonyTarget); PP->setPPCallbacks(PPDep); } @@ -91,16 +91,16 @@ void DependencyFileCallback::FileChanged(SourceLocation Loc, SrcMgr::CharacteristicKind FileType) { if (Reason != PPCallbacks::EnterFile) return; - + // Dependency generation really does want to go all the way to the // file entry for a source location to find out what is depended on. // We do not want #line markers to affect dependency generation! SourceManager &SM = PP->getSourceManager(); - + const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(SM.getInstantiationLoc(Loc))); if (FE == 0) return; - + const char *Filename = FE->getName(); if (!FileMatchesDepCriteria(Filename, FileType)) return; @@ -138,7 +138,7 @@ void DependencyFileCallback::OutputDependencyFile() { *OS << ':'; Columns += 1; - + // Now add each dependency in the order it was seen, but avoiding // duplicates. for (std::vector::iterator I = Files.begin(), diff --git a/clang/lib/Frontend/DiagChecker.cpp b/clang/lib/Frontend/DiagChecker.cpp index c0f5d141be066f88d81e48ad5c9024e2631b1a46..26bb6ccfa7c7e84248c35278219165728571e6c9 100644 --- a/clang/lib/Frontend/DiagChecker.cpp +++ b/clang/lib/Frontend/DiagChecker.cpp @@ -55,33 +55,33 @@ static void EmitError(Preprocessor &PP, SourceLocation Pos, const char *String){ /// FindDiagnostics - Go through the comment and see if it indicates expected /// diagnostics. If so, then put them in a diagnostic list. -/// +/// static void FindDiagnostics(const char *CommentStart, unsigned CommentLen, DiagList &ExpectedDiags, Preprocessor &PP, SourceLocation Pos, const char *ExpectedStr) { const char *CommentEnd = CommentStart+CommentLen; unsigned ExpectedStrLen = strlen(ExpectedStr); - + // Find all expected-foo diagnostics in the string and add them to // ExpectedDiags. while (CommentStart != CommentEnd) { CommentStart = std::find(CommentStart, CommentEnd, 'e'); if (unsigned(CommentEnd-CommentStart) < ExpectedStrLen) return; - + // If this isn't expected-foo, ignore it. if (memcmp(CommentStart, ExpectedStr, ExpectedStrLen)) { ++CommentStart; continue; } - + CommentStart += ExpectedStrLen; - + // Skip whitespace. while (CommentStart != CommentEnd && isspace(CommentStart[0])) ++CommentStart; - + // Default, if we find the '{' now, is 1 time. int Times = 1; int Temp = 0; @@ -94,12 +94,12 @@ static void FindDiagnostics(const char *CommentStart, unsigned CommentLen, } if (Temp > 0) Times = Temp; - + // Skip whitespace again. while (CommentStart != CommentEnd && isspace(CommentStart[0])) ++CommentStart; - + // We should have a {{ now. if (CommentEnd-CommentStart < 2 || CommentStart[0] != '{' || CommentStart[1] != '{') { @@ -119,7 +119,7 @@ static void FindDiagnostics(const char *CommentStart, unsigned CommentLen, EmitError(PP, Pos, "cannot find end ('}}') of expected string"); return; } - + if (ExpectedEnd[1] == '}') break; @@ -147,10 +147,10 @@ static void FindExpectedDiags(Preprocessor &PP, // Create a raw lexer to pull all the comments out of the main file. We don't // want to look in #include'd headers for expected-error strings. FileID FID = PP.getSourceManager().getMainFileID(); - + // Create a lexer to lex all the tokens of the main file in raw mode. Lexer RawLex(FID, PP.getSourceManager(), PP.getLangOptions()); - + // Return comments as tokens, this is how we find expected diagnostics. RawLex.SetCommentRetentionState(true); @@ -159,11 +159,11 @@ static void FindExpectedDiags(Preprocessor &PP, while (Tok.isNot(tok::eof)) { RawLex.Lex(Tok); if (!Tok.is(tok::comment)) continue; - + std::string Comment = PP.getSpelling(Tok); if (Comment.empty()) continue; - + // Find all expected errors. FindDiagnostics(&Comment[0], Comment.size(), ExpectedErrors, PP, Tok.getLocation(), "expected-error"); @@ -182,7 +182,7 @@ static void FindExpectedDiags(Preprocessor &PP, /// seen diagnostics. If there's anything in it, then something unexpected /// happened. Print the map out in a nice format and return "true". If the map /// is empty and we're not going to print things, then return "false". -/// +/// static bool PrintProblem(SourceManager &SourceMgr, const_diag_iterator diag_begin, const_diag_iterator diag_end, @@ -201,7 +201,7 @@ static bool PrintProblem(SourceManager &SourceMgr, /// CompareDiagLists - Compare two diagnostic lists and return the difference /// between them. -/// +/// static bool CompareDiagLists(SourceManager &SourceMgr, const_diag_iterator d1_begin, const_diag_iterator d1_end, @@ -245,7 +245,7 @@ static bool CompareDiagLists(SourceManager &SourceMgr, /// CheckResults - This compares the expected results to those that /// were actually reported. It emits any discrepencies. Return "true" if there /// were problems. Return "false" otherwise. -/// +/// static bool CheckResults(Preprocessor &PP, const DiagList &ExpectedErrors, const DiagList &ExpectedWarnings, diff --git a/clang/lib/Frontend/DocumentXML.cpp b/clang/lib/Frontend/DocumentXML.cpp index 19a757303f1b190758c8617f74e19545d8fd9990..776fa6dcdaf30dccbb10b06ba623a61ffce1cf1b 100644 --- a/clang/lib/Frontend/DocumentXML.cpp +++ b/clang/lib/Frontend/DocumentXML.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements the XML document class, which provides the means to +// This file implements the XML document class, which provides the means to // dump out the AST in a XML form that exposes type details and other fields. // //===----------------------------------------------------------------------===// @@ -20,23 +20,19 @@ namespace clang { -//--------------------------------------------------------- +//--------------------------------------------------------- DocumentXML::DocumentXML(const std::string& rootName, llvm::raw_ostream& out) : Out(out), Ctx(0), - HasCurrentNodeSubNodes(false) -{ + HasCurrentNodeSubNodes(false) { NodeStack.push(rootName); Out << "\n<" << rootName; } -//--------------------------------------------------------- -DocumentXML& DocumentXML::addSubNode(const std::string& name) -{ +//--------------------------------------------------------- +DocumentXML& DocumentXML::addSubNode(const std::string& name) { if (!HasCurrentNodeSubNodes) - { Out << ">\n"; - } NodeStack.push(name); HasCurrentNodeSubNodes = false; Indent(); @@ -44,46 +40,38 @@ DocumentXML& DocumentXML::addSubNode(const std::string& name) return *this; } -//--------------------------------------------------------- -void DocumentXML::Indent() -{ +//--------------------------------------------------------- +void DocumentXML::Indent() { for (size_t i = 0, e = (NodeStack.size() - 1) * 2; i < e; ++i) Out << ' '; } -//--------------------------------------------------------- -DocumentXML& DocumentXML::toParent() -{ +//--------------------------------------------------------- +DocumentXML& DocumentXML::toParent() { assert(NodeStack.size() > 1 && "to much backtracking"); - if (HasCurrentNodeSubNodes) - { + if (HasCurrentNodeSubNodes) { Indent(); Out << "\n"; - } - else - { + } else Out << "/>\n"; - } NodeStack.pop(); HasCurrentNodeSubNodes = true; - return *this; + return *this; } -//--------------------------------------------------------- +//--------------------------------------------------------- namespace { enum tIdType { ID_NORMAL, ID_FILE, ID_LABEL, ID_LAST }; -unsigned getNewId(tIdType idType) -{ +unsigned getNewId(tIdType idType) { static unsigned int idCounts[ID_LAST] = { 0 }; return ++idCounts[idType]; } -//--------------------------------------------------------- -inline std::string getPrefixedId(unsigned uId, tIdType idType) -{ +//--------------------------------------------------------- +inline std::string getPrefixedId(unsigned uId, tIdType idType) { static const char idPrefix[ID_LAST] = { '_', 'f', 'l' }; char buffer[20]; char* BufPtr = llvm::utohex_buffer(uId, buffer + 20); @@ -91,25 +79,22 @@ inline std::string getPrefixedId(unsigned uId, tIdType idType) return BufPtr; } -//--------------------------------------------------------- +//--------------------------------------------------------- template -bool addToMap(T& idMap, const V& value, tIdType idType = ID_NORMAL) -{ +bool addToMap(T& idMap, const V& value, tIdType idType = ID_NORMAL) { typename T::iterator i = idMap.find(value); bool toAdd = i == idMap.end(); - if (toAdd) - { + if (toAdd) idMap.insert(typename T::value_type(value, getNewId(idType))); - } return toAdd; } } // anon NS -//--------------------------------------------------------- -std::string DocumentXML::escapeString(const char* pStr, std::string::size_type len) -{ +//--------------------------------------------------------- +std::string DocumentXML::escapeString(const char* pStr, + std::string::size_type len) { std::string value; value.reserve(len + 1); char buffer[16]; @@ -118,8 +103,7 @@ std::string DocumentXML::escapeString(const char* pStr, std::string::size_type l default: if (isprint(C)) value += C; - else - { + else { sprintf(buffer, "\\%03o", C); value += buffer; } @@ -142,26 +126,24 @@ std::string DocumentXML::escapeString(const char* pStr, std::string::size_type l return value; } -//--------------------------------------------------------- -void DocumentXML::finalize() -{ +//--------------------------------------------------------- +void DocumentXML::finalize() { assert(NodeStack.size() == 1 && "not completely backtracked"); addSubNode("ReferenceSection"); addSubNode("Types"); - for (XML::IdMap::iterator i = Types.begin(), e = Types.end(); i != e; ++i) - { - if (i->first.getCVRQualifiers() != 0) - { + for (XML::IdMap::iterator i = Types.begin(), e = Types.end(); + i != e; ++i) { + if (i->first.getCVRQualifiers() != 0) { writeTypeToXML(i->first); addAttribute("id", getPrefixedId(i->second, ID_NORMAL)); toParent(); } } - for (XML::IdMap::iterator i = BasicTypes.begin(), e = BasicTypes.end(); i != e; ++i) - { + for (XML::IdMap::iterator i = BasicTypes.begin(), + e = BasicTypes.end(); i != e; ++i) { writeTypeToXML(i->first); addAttribute("id", getPrefixedId(i->second, ID_NORMAL)); toParent(); @@ -170,31 +152,26 @@ void DocumentXML::finalize() toParent().addSubNode("Contexts"); - for (XML::IdMap::iterator i = Contexts.begin(), e = Contexts.end(); i != e; ++i) - { + for (XML::IdMap::iterator i = Contexts.begin(), + e = Contexts.end(); i != e; ++i) { addSubNode(i->first->getDeclKindName()); addAttribute("id", getPrefixedId(i->second, ID_NORMAL)); - if (const NamedDecl *ND = dyn_cast(i->first)) { + if (const NamedDecl *ND = dyn_cast(i->first)) addAttribute("name", ND->getNameAsString()); - } - if (const TagDecl *TD = dyn_cast(i->first)) { + if (const TagDecl *TD = dyn_cast(i->first)) addAttribute("type", getPrefixedId(BasicTypes[TD->getTypeForDecl()], ID_NORMAL)); - } - else if (const FunctionDecl *FD = dyn_cast(i->first)) { + else if (const FunctionDecl *FD = dyn_cast(i->first)) addAttribute("type", getPrefixedId(BasicTypes[FD->getType()->getAsFunctionType()], ID_NORMAL)); - } if (const DeclContext* parent = i->first->getParent()) - { addAttribute("context", parent); - } toParent(); } toParent().addSubNode("Files"); - for (XML::IdMap::iterator i = SourceFiles.begin(), e = SourceFiles.end(); i != e; ++i) - { + for (XML::IdMap::iterator i = SourceFiles.begin(), + e = SourceFiles.end(); i != e; ++i) { addSubNode("File"); addAttribute("id", getPrefixedId(i->second, ID_FILE)); addAttribute("name", escapeString(i->first.c_str(), i->first.size())); @@ -202,26 +179,26 @@ void DocumentXML::finalize() } toParent().toParent(); - + // write the root closing node (which has always subnodes) Out << "\n"; } -//--------------------------------------------------------- -void DocumentXML::addAttribute(const char* pAttributeName, const QualType& pType) -{ +//--------------------------------------------------------- +void DocumentXML::addAttribute(const char* pAttributeName, + const QualType& pType) { addTypeRecursively(pType); addAttribute(pAttributeName, getPrefixedId(Types[pType], ID_NORMAL)); } -//--------------------------------------------------------- -void DocumentXML::addPtrAttribute(const char* pAttributeName, const Type* pType) -{ +//--------------------------------------------------------- +void DocumentXML::addPtrAttribute(const char* pAttributeName, + const Type* pType) { addTypeRecursively(pType); addAttribute(pAttributeName, getPrefixedId(BasicTypes[pType], ID_NORMAL)); } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addTypeRecursively(const QualType& pType) { if (addToMap(Types, pType)) @@ -230,12 +207,12 @@ void DocumentXML::addTypeRecursively(const QualType& pType) // beautifier: a non-qualified type shall be transparent if (pType.getCVRQualifiers() == 0) { - Types[pType] = BasicTypes[pType.getTypePtr()]; + Types[pType] = BasicTypes[pType.getTypePtr()]; } } } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addTypeRecursively(const Type* pType) { if (addToMap(BasicTypes, pType)) @@ -243,7 +220,7 @@ void DocumentXML::addTypeRecursively(const Type* pType) addParentTypes(pType); /* // FIXME: doesn't work in the immediate streaming approach - if (const VariableArrayType *VAT = dyn_cast(pType)) + if (const VariableArrayType *VAT = dyn_cast(pType)) { addSubNode("VariableArraySizeExpression"); PrintStmt(VAT->getSizeExpr()); @@ -253,14 +230,14 @@ void DocumentXML::addTypeRecursively(const Type* pType) } } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addPtrAttribute(const char* pName, const DeclContext* DC) { addContextsRecursively(DC); addAttribute(pName, getPrefixedId(Contexts[DC], ID_NORMAL)); } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addPtrAttribute(const char* pAttributeName, const NamedDecl* D) { if (const DeclContext* DC = dyn_cast(D)) @@ -275,22 +252,22 @@ void DocumentXML::addPtrAttribute(const char* pAttributeName, const NamedDecl* D } } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addPtrAttribute(const char* pName, const NamespaceDecl* D) { addPtrAttribute(pName, static_cast(D)); } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addContextsRecursively(const DeclContext *DC) { if (DC != 0 && addToMap(Contexts, DC)) { addContextsRecursively(DC->getParent()); - } + } } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addSourceFileAttribute(const std::string& fileName) { addToMap(SourceFiles, fileName, ID_FILE); @@ -298,7 +275,7 @@ void DocumentXML::addSourceFileAttribute(const std::string& fileName) } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addPtrAttribute(const char* pName, const LabelStmt* L) { addToMap(Labels, L, ID_LABEL); @@ -306,13 +283,13 @@ void DocumentXML::addPtrAttribute(const char* pName, const LabelStmt* L) } -//--------------------------------------------------------- +//--------------------------------------------------------- PresumedLoc DocumentXML::addLocation(const SourceLocation& Loc) { SourceManager& SM = Ctx->getSourceManager(); SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); PresumedLoc PLoc; - if (!SpellingLoc.isInvalid()) + if (!SpellingLoc.isInvalid()) { PLoc = SM.getPresumedLoc(SpellingLoc); addSourceFileAttribute(PLoc.getFilename()); @@ -323,18 +300,18 @@ PresumedLoc DocumentXML::addLocation(const SourceLocation& Loc) return PLoc; } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::addLocationRange(const SourceRange& R) { PresumedLoc PStartLoc = addLocation(R.getBegin()); - if (R.getBegin() != R.getEnd()) + if (R.getBegin() != R.getEnd()) { SourceManager& SM = Ctx->getSourceManager(); SourceLocation SpellingLoc = SM.getSpellingLoc(R.getEnd()); - if (!SpellingLoc.isInvalid()) + if (!SpellingLoc.isInvalid()) { PresumedLoc PLoc = SM.getPresumedLoc(SpellingLoc); - if (PStartLoc.isInvalid() || + if (PStartLoc.isInvalid() || strcmp(PLoc.getFilename(), PStartLoc.getFilename()) != 0) { addToMap(SourceFiles, PLoc.getFilename(), ID_FILE); addAttribute("endfile", PLoc.getFilename()); @@ -345,17 +322,17 @@ void DocumentXML::addLocationRange(const SourceRange& R) addAttribute("endcol", PLoc.getColumn()); } else { addAttribute("endcol", PLoc.getColumn()); - } + } } } } -//--------------------------------------------------------- +//--------------------------------------------------------- void DocumentXML::PrintDecl(Decl *D) { writeDeclToXML(D); } -//--------------------------------------------------------- +//--------------------------------------------------------- } // NS clang diff --git a/clang/lib/Frontend/FixItRewriter.cpp b/clang/lib/Frontend/FixItRewriter.cpp index ba58df5d83394d4ea7edf143cd28c787f63d5d10..dddcaa97e2fffba19913bb949c26a14261a557d5 100644 --- a/clang/lib/Frontend/FixItRewriter.cpp +++ b/clang/lib/Frontend/FixItRewriter.cpp @@ -34,7 +34,7 @@ FixItRewriter::~FixItRewriter() { Diags.setClient(Client); } -bool FixItRewriter::WriteFixedFile(const std::string &InFileName, +bool FixItRewriter::WriteFixedFile(const std::string &InFileName, const std::string &OutFileName) { if (NumFailures > 0) { Diag(FullSourceLoc(), diag::warn_fixit_no_changes); @@ -59,10 +59,10 @@ bool FixItRewriter::WriteFixedFile(const std::string &InFileName, OutFile = new llvm::raw_fd_ostream(Path.c_str(), Err, llvm::raw_fd_ostream::F_Binary); OwnedStream.reset(OutFile); - } + } FileID MainFileID = Rewrite.getSourceMgr().getMainFileID(); - if (const RewriteBuffer *RewriteBuf = + if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); } else { @@ -99,7 +99,7 @@ void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel, // See if the location of the error is one that matches what the // user requested. bool AcceptableLocation = false; - const FileEntry *File + const FileEntry *File = Rewrite.getSourceMgr().getFileEntryForID( Info.getLocation().getFileID()); unsigned Line = Info.getLocation().getSpellingLineNumber(); @@ -129,14 +129,14 @@ void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel, break; } - if (Hint.InsertionLoc.isValid() && + if (Hint.InsertionLoc.isValid() && !Rewrite.isRewritable(Hint.InsertionLoc)) { CanRewrite = false; break; } } - if (!CanRewrite) { + if (!CanRewrite) { if (Info.getNumCodeModificationHints() > 0) Diag(Info.getLocation(), diag::note_fixit_in_macro); @@ -149,7 +149,7 @@ void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel, } bool Failed = false; - for (unsigned Idx = 0, Last = Info.getNumCodeModificationHints(); + for (unsigned Idx = 0, Last = Info.getNumCodeModificationHints(); Idx < Last; ++Idx) { const CodeModificationHint &Hint = Info.getCodeModificationHint(Idx); if (!Hint.RemoveRange.isValid()) { @@ -158,15 +158,15 @@ void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel, Failed = true; continue; } - + if (Hint.CodeToInsert.empty()) { // We're removing code. if (Rewrite.RemoveText(Hint.RemoveRange.getBegin(), Rewrite.getRangeSize(Hint.RemoveRange))) Failed = true; continue; - } - + } + // We're replacing code. if (Rewrite.ReplaceText(Hint.RemoveRange.getBegin(), Rewrite.getRangeSize(Hint.RemoveRange), @@ -191,5 +191,5 @@ void FixItRewriter::Diag(FullSourceLoc Loc, unsigned DiagID) { Diags.setClient(Client); Diags.Clear(); Diags.Report(Loc, DiagID); - Diags.setClient(this); + Diags.setClient(this); } diff --git a/clang/lib/Frontend/GeneratePCH.cpp b/clang/lib/Frontend/GeneratePCH.cpp index 43a3a6cbc0e284013949833ae4a8bb369dcd3893..bc45cc422585a4f540fb30d890c494fceb56a14a 100644 --- a/clang/lib/Frontend/GeneratePCH.cpp +++ b/clang/lib/Frontend/GeneratePCH.cpp @@ -35,9 +35,9 @@ namespace { llvm::raw_ostream *Out; Sema *SemaPtr; MemorizeStatCalls *StatCalls; // owned by the FileManager - + public: - explicit PCHGenerator(const Preprocessor &PP, + explicit PCHGenerator(const Preprocessor &PP, const char *isysroot, llvm::raw_ostream *Out); virtual void InitializeSema(Sema &S) { SemaPtr = &S; } @@ -45,10 +45,10 @@ namespace { }; } -PCHGenerator::PCHGenerator(const Preprocessor &PP, +PCHGenerator::PCHGenerator(const Preprocessor &PP, const char *isysroot, llvm::raw_ostream *OS) - : PP(PP), isysroot(isysroot), Out(OS), SemaPtr(0), StatCalls(0) { + : PP(PP), isysroot(isysroot), Out(OS), SemaPtr(0), StatCalls(0) { // Install a stat() listener to keep track of all of the stat() // calls. diff --git a/clang/lib/Frontend/HTMLDiagnostics.cpp b/clang/lib/Frontend/HTMLDiagnostics.cpp index 4c84548ad3477a7af8d1b80213c0249e202f6e38..f8bca235bd56e633c8c1228bc1494e971304b88c 100644 --- a/clang/lib/Frontend/HTMLDiagnostics.cpp +++ b/clang/lib/Frontend/HTMLDiagnostics.cpp @@ -39,39 +39,39 @@ class VISIBILITY_HIDDEN HTMLDiagnostics : public PathDiagnosticClient { bool createdDir, noDir; Preprocessor* PP; std::vector BatchedDiags; - llvm::SmallVectorImpl *FilesMade; + llvm::SmallVectorImpl *FilesMade; public: HTMLDiagnostics(const std::string& prefix, Preprocessor* pp, llvm::SmallVectorImpl *filesMade = 0); virtual ~HTMLDiagnostics(); - + virtual void SetPreprocessor(Preprocessor *pp) { PP = pp; } - + virtual void HandlePathDiagnostic(const PathDiagnostic* D); - + unsigned ProcessMacroPiece(llvm::raw_ostream& os, const PathDiagnosticMacroPiece& P, unsigned num); - + void HandlePiece(Rewriter& R, FileID BugFileID, const PathDiagnosticPiece& P, unsigned num, unsigned max); - + void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range, const char *HighlightStart = "", const char *HighlightEnd = ""); void ReportDiag(const PathDiagnostic& D); }; - + } // end anonymous namespace HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix, Preprocessor* pp, llvm::SmallVectorImpl* filesMade) : Directory(prefix), FilePrefix(prefix), createdDir(false), noDir(false), PP(pp), FilesMade(filesMade) { - - // All html files begin with "report" + + // All html files begin with "report" FilePrefix.appendComponent("report"); } @@ -98,9 +98,9 @@ public: : Prefix(prefix), PP(pp) {} virtual ~HTMLDiagnosticsFactory() {} - + const char *getName() const { return "HTMLDiagnostics"; } - + PathDiagnosticClient* createPathDiagnosticClient(llvm::SmallVectorImpl *FilesMade) { @@ -123,12 +123,12 @@ clang::CreateHTMLDiagnosticClientFactory(const std::string& prefix, void HTMLDiagnostics::HandlePathDiagnostic(const PathDiagnostic* D) { if (!D) return; - + if (D->empty()) { delete D; return; } - + const_cast(D)->flattenLocations(); BatchedDiags.push_back(D); } @@ -139,7 +139,7 @@ HTMLDiagnostics::~HTMLDiagnostics() { BatchedDiags.pop_back(); ReportDiag(*D); delete D; - } + } } void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { @@ -148,73 +148,73 @@ void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { createdDir = true; std::string ErrorMsg; Directory.createDirectoryOnDisk(true, &ErrorMsg); - + if (!Directory.isDirectory()) { llvm::errs() << "warning: could not create directory '" << Directory.str() << "'\n" - << "reason: " << ErrorMsg << '\n'; - + << "reason: " << ErrorMsg << '\n'; + noDir = true; - + return; } } - + if (noDir) return; - + const SourceManager &SMgr = D.begin()->getLocation().getManager(); FileID FID; - + // Verify that the entire path is from the same FileID. for (PathDiagnostic::const_iterator I = D.begin(), E = D.end(); I != E; ++I) { FullSourceLoc L = I->getLocation().asLocation().getInstantiationLoc(); - + if (FID.isInvalid()) { FID = SMgr.getFileID(L); } else if (SMgr.getFileID(L) != FID) return; // FIXME: Emit a warning? - + // Check the source ranges. for (PathDiagnosticPiece::range_iterator RI=I->ranges_begin(), RE=I->ranges_end(); RI!=RE; ++RI) { - + SourceLocation L = SMgr.getInstantiationLoc(RI->getBegin()); if (!L.isFileID() || SMgr.getFileID(L) != FID) return; // FIXME: Emit a warning? - + L = SMgr.getInstantiationLoc(RI->getEnd()); - + if (!L.isFileID() || SMgr.getFileID(L) != FID) - return; // FIXME: Emit a warning? + return; // FIXME: Emit a warning? } } - + if (FID.isInvalid()) return; // FIXME: Emit a warning? - + // Create a new rewriter to generate HTML. Rewriter R(const_cast(SMgr), PP->getLangOptions()); - - // Process the path. + + // Process the path. unsigned n = D.size(); unsigned max = n; - + for (PathDiagnostic::const_reverse_iterator I=D.rbegin(), E=D.rend(); I!=E; ++I, --n) HandlePiece(R, FID, *I, n, max); - + // Add line numbers, header, footer, etc. - + // unsigned FID = R.getSourceMgr().getMainFileID(); html::EscapeText(R, FID); html::AddLineNumbers(R, FID); - + // If we have a preprocessor, relex the file and syntax highlight. // We might not have a preprocessor if we come from a deserialized AST file, // for example. - + if (PP) html::SyntaxHighlight(R, FID, *PP); // FIXME: We eventually want to use PPF to create a fresh Preprocessor, @@ -223,69 +223,69 @@ void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { // if (PPF) html::HighlightMacros(R, FID, *PPF); // if (PP) html::HighlightMacros(R, FID, *PP); - + // Get the full directory name of the analyzed file. const FileEntry* Entry = SMgr.getFileEntryForID(FID); - + // This is a cludge; basically we want to append either the full // working directory if we have no directory information. This is // a work in progress. std::string DirName = ""; - + if (!llvm::sys::Path(Entry->getName()).isAbsolute()) { llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory(); DirName = P.str() + "/"; } - - // Add the name of the file as an

tag. - + + // Add the name of the file as an

tag. + { std::string s; llvm::raw_string_ostream os(s); - + os << "\n" << "

Bug Summary

\n\n" "\n\n" "\n"; - + // Output any other meta data. - + for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end(); I!=E; ++I) { os << "\n"; } - + os << "
File:" << html::EscapeText(DirName) << html::EscapeText(Entry->getName()) << "
Location:" - "line " + "line " << (*D.rbegin()).getLocation().asLocation().getInstantiationLineNumber() << ", column " << (*D.rbegin()).getLocation().asLocation().getInstantiationColumnNumber() << "
Description:" << D.getDescription() << "
" << html::EscapeText(*I) << "
\n\n" - "

Annotated Source Code

\n"; - + "

Annotated Source Code

\n"; + R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str()); } - + // Embed meta-data tags. { std::string s; llvm::raw_string_ostream os(s); - - const std::string& BugDesc = D.getDescription(); + + const std::string& BugDesc = D.getDescription(); if (!BugDesc.empty()) os << "\n\n"; - + const std::string& BugType = D.getBugType(); if (!BugType.empty()) os << "\n\n"; - - const std::string& BugCategory = D.getCategory(); + + const std::string& BugCategory = D.getCategory(); if (!BugCategory.empty()) os << "\n\n"; @@ -296,21 +296,21 @@ void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { << " -->\n"; os << "\n\n"; - + // Mark the end of the tags. os << "\n\n"; - + // Insert the text. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str()); } - + // Add CSS, header, and footer. - + html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName()); - + // Get the rewrite buffer. const RewriteBuffer *Buf = R.getRewriteBufferFor(FID); - + if (!Buf) { llvm::errs() << "warning: no diagnostics generated for main file.\n"; return; @@ -318,19 +318,19 @@ void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { // Create the stream to write out the HTML. std::ofstream os; - + { // Create a path for the target HTML file. llvm::sys::Path F(FilePrefix); F.makeUnique(false, NULL); - + // Rename the file with an HTML extension. llvm::sys::Path H(F); H.appendSuffix("html"); F.renamePathOnDisk(H, NULL); - + os.open(H.c_str()); - + if (!os) { llvm::errs() << "warning: could not create file '" << F.str() << "'\n"; return; @@ -339,33 +339,33 @@ void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { if (FilesMade) FilesMade->push_back(H.getLast()); } - + // Emit the HTML to disk. for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I) - os << *I; + os << *I; } void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, const PathDiagnosticPiece& P, unsigned num, unsigned max) { - + // For now, just draw a box above the line in question, and emit the // warning. FullSourceLoc Pos = P.getLocation().asLocation(); - + if (!Pos.isValid()) - return; - + return; + SourceManager &SM = R.getSourceMgr(); assert(&Pos.getManager() == &SM && "SourceManagers are different!"); std::pair LPosInfo = SM.getDecomposedInstantiationLoc(Pos); - + if (LPosInfo.first != BugFileID) return; - + const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first); - const char* FileStart = Buf->getBufferStart(); - + const char* FileStart = Buf->getBufferStart(); + // Compute the column number. Rewind from the current position to the start // of the line. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second); @@ -377,12 +377,12 @@ void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, const char* FileEnd = Buf->getBufferEnd(); while (*LineEnd != '\n' && LineEnd != FileEnd) ++LineEnd; - + // Compute the margin offset by counting tabs and non-tabs. - unsigned PosNo = 0; + unsigned PosNo = 0; for (const char* c = LineStart; c != TokInstantiationPtr; ++c) PosNo += *c == '\t' ? 8 : 1; - + // Create the html for the message. const char *Kind = 0; @@ -392,22 +392,22 @@ void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, // Setting Kind to "Control" is intentional. case PathDiagnosticPiece::Macro: Kind = "Control"; break; } - + std::string sbuf; llvm::raw_string_ostream os(sbuf); - + os << "\n
(P)) { // Get the string and determining its maximum substring. @@ -415,32 +415,32 @@ void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, unsigned max_token = 0; unsigned cnt = 0; unsigned len = Msg.size(); - + for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I) switch (*I) { default: ++cnt; - continue; + continue; case ' ': case '\t': case '\n': if (cnt > max_token) max_token = cnt; cnt = 0; } - + if (cnt > max_token) max_token = cnt; - + // Determine the approximate size of the message bubble in em. unsigned em; const unsigned max_line = 120; - + if (max_token >= max_line) em = max_token / 2; else { unsigned characters = max_line; unsigned lines = len / max_line; - + if (lines > 0) { for (; characters > max_token; --characters) if (len / characters > lines) { @@ -448,18 +448,18 @@ void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, break; } } - + em = characters / 2; } - + if (em < max_line/2) - os << "; max-width:" << em << "em"; + os << "; max-width:" << em << "em"; } else os << "; max-width:100em"; - + os << "\">"; - + if (max > 1) { os << "
"; os << "
(&P)) { + dyn_cast(&P)) { os << "Within the expansion of the macro '"; - + // Get the name of the macro by relexing it. { FullSourceLoc L = MP->getLocation().asLocation().getInstantiationLoc(); @@ -481,15 +481,15 @@ void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, const char* MacroName = L.getDecomposedLoc().second + BufferInfo.first; Lexer rawLexer(L, PP->getLangOptions(), BufferInfo.first, MacroName, BufferInfo.second); - + Token TheTok; rawLexer.LexFromRawLexer(TheTok); for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i) os << MacroName[i]; } - + os << "':\n"; - + if (max > 1) os << "
"; @@ -498,21 +498,21 @@ void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID, } else { os << html::EscapeText(P.getString()); - + if (max > 1) os << ""; } - + os << "
"; // Insert the new html. - unsigned DisplayPos = LineEnd - FileStart; - SourceLocation Loc = + unsigned DisplayPos = LineEnd - FileStart; + SourceLocation Loc = SM.getLocForStartOfFile(LPosInfo.first).getFileLocWithOffset(DisplayPos); R.InsertTextBefore(Loc, os.str()); - // Now highlight the ranges. + // Now highlight the ranges. for (const SourceRange *I = P.ranges_begin(), *E = P.ranges_end(); I != E; ++I) HighlightRange(R, LPosInfo.first, *I); @@ -547,9 +547,9 @@ static void EmitAlphaCounter(llvm::raw_ostream& os, unsigned n) { buf.push_back('a' + x); n = n / ('z' - 'a'); } while (n); - + assert(!buf.empty()); - + for (llvm::SmallVectorImpl::reverse_iterator I=buf.rbegin(), E=buf.rend(); I!=E; ++I) os << *I; @@ -558,10 +558,10 @@ static void EmitAlphaCounter(llvm::raw_ostream& os, unsigned n) { unsigned HTMLDiagnostics::ProcessMacroPiece(llvm::raw_ostream& os, const PathDiagnosticMacroPiece& P, unsigned num) { - + for (PathDiagnosticMacroPiece::const_iterator I=P.begin(), E=P.end(); I!=E; ++I) { - + if (const PathDiagnosticMacroPiece *MP = dyn_cast(*I)) { num = ProcessMacroPiece(os, *MP, num); @@ -579,7 +579,7 @@ unsigned HTMLDiagnostics::ProcessMacroPiece(llvm::raw_ostream& os, << "\n"; } } - + return num; } @@ -589,20 +589,20 @@ void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID, const char *HighlightEnd) { SourceManager &SM = R.getSourceMgr(); const LangOptions &LangOpts = R.getLangOpts(); - + SourceLocation InstantiationStart = SM.getInstantiationLoc(Range.getBegin()); unsigned StartLineNo = SM.getInstantiationLineNumber(InstantiationStart); - + SourceLocation InstantiationEnd = SM.getInstantiationLoc(Range.getEnd()); unsigned EndLineNo = SM.getInstantiationLineNumber(InstantiationEnd); - + if (EndLineNo < StartLineNo) return; - + if (SM.getFileID(InstantiationStart) != BugFileID || SM.getFileID(InstantiationEnd) != BugFileID) return; - + // Compute the column number of the end. unsigned EndColNo = SM.getInstantiationColumnNumber(InstantiationEnd); unsigned OldEndColNo = EndColNo; @@ -611,12 +611,12 @@ void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID, // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1; } - + // Highlight the range. Make the span tag the outermost tag for the // selected range. - + SourceLocation E = InstantiationEnd.getFileLocWithOffset(EndColNo - OldEndColNo); - + html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd); } diff --git a/clang/lib/Frontend/HTMLPrint.cpp b/clang/lib/Frontend/HTMLPrint.cpp index f434bcc0c7499b13de7005e43ca1f9411b4d8955..8d93d70e83f4e43c8fc5ee93c133cd28e69ace0f 100644 --- a/clang/lib/Frontend/HTMLPrint.cpp +++ b/clang/lib/Frontend/HTMLPrint.cpp @@ -26,7 +26,7 @@ using namespace clang; //===----------------------------------------------------------------------===// // Functional HTML pretty-printing. -//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// namespace { class HTMLPrinter : public ASTConsumer { @@ -40,7 +40,7 @@ namespace { PreprocessorFactory* ppf) : Out(OS), Diags(D), PP(pp), PPF(ppf) {} virtual ~HTMLPrinter(); - + void Initialize(ASTContext &context); }; } @@ -48,7 +48,7 @@ namespace { ASTConsumer* clang::CreateHTMLPrinter(llvm::raw_ostream *OS, Diagnostic &D, Preprocessor *PP, PreprocessorFactory* PPF) { - + return new HTMLPrinter(OS, D, PP, PPF); } @@ -78,7 +78,7 @@ HTMLPrinter::~HTMLPrinter() { // If we have a preprocessor, relex the file and syntax highlight. // We might not have a preprocessor if we come from a deserialized AST file, // for example. - + if (PP) html::SyntaxHighlight(R, FID, *PP); if (PPF) html::HighlightMacros(R, FID, *PP); html::EscapeText(R, FID, false, true); diff --git a/clang/lib/Frontend/InitHeaderSearch.cpp b/clang/lib/Frontend/InitHeaderSearch.cpp index 86742615708febadebdb1d0845d175d4e5923cd1..da45bcca97c8e0c34bf715e378ccc05ba9a3b5a3 100644 --- a/clang/lib/Frontend/InitHeaderSearch.cpp +++ b/clang/lib/Frontend/InitHeaderSearch.cpp @@ -29,10 +29,10 @@ void InitHeaderSearch::AddPath(const llvm::StringRef &Path, bool IgnoreSysRoot) { assert(!Path.empty() && "can't handle empty path here"); FileManager &FM = Headers.getFileMgr(); - + // Compute the actual path, taking into consideration -isysroot. llvm::SmallString<256> MappedPath; - + // Handle isysroot. if (Group == System && !IgnoreSysRoot) { // FIXME: Portability. This should be a sys::Path interface, this doesn't @@ -40,7 +40,7 @@ void InitHeaderSearch::AddPath(const llvm::StringRef &Path, if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present. MappedPath.append(isysroot.begin(), isysroot.end()); } - + MappedPath.append(Path.begin(), Path.end()); // Compute the DirectoryLookup type. @@ -51,15 +51,15 @@ void InitHeaderSearch::AddPath(const llvm::StringRef &Path, Type = SrcMgr::C_System; else Type = SrcMgr::C_ExternCSystem; - - + + // If the directory exists, add it. if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) { IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied, isFramework)); return; } - + // Check to see if this is an apple-style headermap (which are not allowed to // be frameworks). if (!isFramework) { @@ -71,7 +71,7 @@ void InitHeaderSearch::AddPath(const llvm::StringRef &Path, } } } - + if (Verbose) llvm::errs() << "ignoring nonexistent directory \"" << MappedPath.str() << "\"\n"; @@ -251,9 +251,9 @@ static void RemoveDuplicates(std::vector &SearchList, llvm::SmallPtrSet SeenHeaderMaps; for (unsigned i = 0; i != SearchList.size(); ++i) { unsigned DirToRemove = i; - + const DirectoryLookup &CurEntry = SearchList[i]; - + if (CurEntry.isNormalDir()) { // If this isn't the first time we've seen this dir, remove it. if (SeenDirs.insert(CurEntry.getDir())) @@ -268,7 +268,7 @@ static void RemoveDuplicates(std::vector &SearchList, if (SeenHeaderMaps.insert(CurEntry.getHeaderMap())) continue; } - + // If we have a normal #include dir/framework/headermap that is shadowed // later in the chain by a system include location, we actually want to // ignore the user's request and drop the user dir... keeping the system @@ -281,13 +281,13 @@ static void RemoveDuplicates(std::vector &SearchList, unsigned FirstDir; for (FirstDir = 0; ; ++FirstDir) { assert(FirstDir != i && "Didn't find dupe?"); - + const DirectoryLookup &SearchEntry = SearchList[FirstDir]; // If these are different lookup types, then they can't be the dupe. if (SearchEntry.getLookupType() != CurEntry.getLookupType()) continue; - + bool isSame; if (CurEntry.isNormalDir()) isSame = SearchEntry.getDir() == CurEntry.getDir(); @@ -297,11 +297,11 @@ static void RemoveDuplicates(std::vector &SearchList, assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap(); } - + if (isSame) break; } - + // If the first dir in the search path is a non-system dir, zap it // instead of the system one. if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User) @@ -315,7 +315,7 @@ static void RemoveDuplicates(std::vector &SearchList, fprintf(stderr, " as it is a non-system directory that duplicates" " a system directory\n"); } - + // This is reached if the current entry is a duplicate. Remove the // DirToRemove (usually the current dir). SearchList.erase(SearchList.begin()+DirToRemove); @@ -334,11 +334,11 @@ void InitHeaderSearch::Realize() { IncludeGroup[After].end()); RemoveDuplicates(SearchList, Verbose); RemoveDuplicates(IncludeGroup[Quoted], Verbose); - + // Prepend QUOTED list on the search list. - SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(), + SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(), IncludeGroup[Quoted].end()); - + bool DontSearchCurDir = false; // TODO: set to true if -I- is set? Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(), diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp index 90e5bdec555046c87d22bdeb79c0923d4739f20c..14657f02d5f23d61321a55fcb3cfa8769fb219a6 100644 --- a/clang/lib/Frontend/InitPreprocessor.cpp +++ b/clang/lib/Frontend/InitPreprocessor.cpp @@ -30,7 +30,7 @@ static void DefineBuiltinMacro(std::vector &Buf, const char *Macro) { // Turn the = into ' '. Buf.insert(Buf.end(), Macro, Equal); Buf.push_back(' '); - + // Per GCC -D semantics, the macro ends at \n if it exists. const char *End = strpbrk(Equal, "\n\r"); if (End) { @@ -40,7 +40,7 @@ static void DefineBuiltinMacro(std::vector &Buf, const char *Macro) { } else { End = Equal+strlen(Equal); } - + Buf.insert(Buf.end(), Equal+1, End); } else { // Push "macroname 1". @@ -62,7 +62,7 @@ static void UndefineBuiltinMacro(std::vector &Buf, const char *Macro) { } /// Add the quoted name of an implicit include file. -static void AddQuotedIncludePath(std::vector &Buf, +static void AddQuotedIncludePath(std::vector &Buf, const std::string &File) { // Implicit include paths should be resolved relative to the current // working directory first, and then use the regular header search @@ -75,7 +75,7 @@ static void AddQuotedIncludePath(std::vector &Buf, Path.makeAbsolute(); if (!Path.exists()) Path = File; - + // Escape double quotes etc. Buf.push_back('"'); std::string EscapedFile = Lexer::Stringify(Path.str()); @@ -85,7 +85,7 @@ static void AddQuotedIncludePath(std::vector &Buf, /// AddImplicitInclude - Add an implicit #include of the specified file to the /// predefines buffer. -static void AddImplicitInclude(std::vector &Buf, +static void AddImplicitInclude(std::vector &Buf, const std::string &File) { const char *Inc = "#include "; Buf.insert(Buf.end(), Inc, Inc+strlen(Inc)); @@ -106,12 +106,12 @@ static void AddImplicitIncludeMacros(std::vector &Buf, /// AddImplicitIncludePTH - Add an implicit #include using the original file /// used to generate a PTH cache. -static void AddImplicitIncludePTH(std::vector &Buf, Preprocessor &PP, +static void AddImplicitIncludePTH(std::vector &Buf, Preprocessor &PP, const std::string& ImplicitIncludePTH) { PTHManager *P = PP.getPTHManager(); assert(P && "No PTHManager."); const char *OriginalFile = P->getOriginalSourceFile(); - + if (!OriginalFile) { assert(!ImplicitIncludePTH.empty()); fprintf(stderr, "error: PTH file '%s' does not designate an original " @@ -119,7 +119,7 @@ static void AddImplicitIncludePTH(std::vector &Buf, Preprocessor &PP, ImplicitIncludePTH.c_str()); exit (1); } - + AddImplicitInclude(Buf, OriginalFile); } @@ -144,7 +144,7 @@ static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal, static void DefineFloatMacros(std::vector &Buf, const char *Prefix, const llvm::fltSemantics *Sem) { const char *DenormMin, *Epsilon, *Max, *Min; - DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324", + DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324", "3.64519953188247460253e-4951L", "4.94065645841246544176568792868221e-324L", "6.47517511943802511092443895822764655e-4966L"); @@ -167,7 +167,7 @@ static void DefineFloatMacros(std::vector &Buf, const char *Prefix, "1.18973149535723176502e+4932L", "1.79769313486231580793728971405301e+308L", "1.18973149535723176508575932662800702e+4932L"); - + char MacroBuf[100]; sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin); DefineBuiltinMacro(Buf, MacroBuf); @@ -210,7 +210,7 @@ static void DefineTypeSize(const char *MacroName, unsigned TypeWidth, MaxVal = (1LL << (TypeWidth - 1)) - 1; else MaxVal = ~0LL >> (64-TypeWidth); - + // FIXME: Switch to using raw_ostream and avoid utostr(). sprintf(MacroBuf, "%s=%s%s", MacroName, llvm::utostr(MaxVal).c_str(), ValSuffix); @@ -232,17 +232,17 @@ static void InitializePredefinedMacros(const TargetInfo &TI, // Compiler version introspection macros. DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend - + // Currently claim to be compatible with GCC 4.2.1-5621. DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2"); DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1"); DefineBuiltinMacro(Buf, "__GNUC__=4"); DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002"); DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\""); - - + + // Initialize language-specific preprocessor defines. - + // These should all be defined in the preprocessor according to the // current language configuration. if (!LangOpts.Microsoft) @@ -260,7 +260,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, // Standard conforming mode? if (!LangOpts.GNUMode) DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1"); - + if (LangOpts.CPlusPlus0x) DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__"); @@ -268,7 +268,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0"); else DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1"); - + if (LangOpts.ObjC1) { DefineBuiltinMacro(Buf, "__OBJC__=1"); if (LangOpts.ObjCNonFragileABI) { @@ -279,15 +279,15 @@ static void InitializePredefinedMacros(const TargetInfo &TI, if (LangOpts.getGCMode() != LangOptions::NonGC) DefineBuiltinMacro(Buf, "__OBJC_GC__=1"); - + if (LangOpts.NeXTRuntime) DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1"); } - + // darwin_constant_cfstrings controls this. This is also dependent // on other things like the runtime I believe. This is set even for C code. DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1"); - + if (LangOpts.ObjC2) DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES"); @@ -301,7 +301,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))"); DefineBuiltinMacro(Buf, "__BLOCKS__=1"); } - + if (LangOpts.CPlusPlus) { DefineBuiltinMacro(Buf, "__DEPRECATED=1"); DefineBuiltinMacro(Buf, "__EXCEPTIONS=1"); @@ -309,32 +309,32 @@ static void InitializePredefinedMacros(const TargetInfo &TI, DefineBuiltinMacro(Buf, "__GXX_WEAK__=1"); if (LangOpts.GNUMode) DefineBuiltinMacro(Buf, "__cplusplus=1"); - else + else // C++ [cpp.predefined]p1: - // The name_ _cplusplusis defined to the value199711Lwhen compiling a + // The name_ _cplusplusis defined to the value199711Lwhen compiling a // C++ translation unit. DefineBuiltinMacro(Buf, "__cplusplus=199711L"); DefineBuiltinMacro(Buf, "__private_extern__=extern"); // Ugly hack to work with GNU libstdc++. DefineBuiltinMacro(Buf, "_GNU_SOURCE=1"); } - + // Filter out some microsoft extensions when trying to parse in ms-compat - // mode. + // mode. if (LangOpts.Microsoft) { DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__"); DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__"); DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__"); DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__"); } - + if (LangOpts.Optimize) DefineBuiltinMacro(Buf, "__OPTIMIZE__=1"); if (LangOpts.OptimizeSize) DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1"); - + // Initialize target-specific preprocessor defines. - + // Define type sizing macros based on the target properties. assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); DefineBuiltinMacro(Buf, "__CHAR_BIT__=8"); @@ -352,7 +352,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, IntMaxWidth = TI.getIntWidth(); IntMaxSuffix = ""; } - + DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf); DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf); DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf); @@ -369,7 +369,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf); // FIXME: TargetInfo hookize __WINT_TYPE__. DefineBuiltinMacro(Buf, "__WINT_TYPE__=int"); - + DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat()); DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat()); DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat()); @@ -377,39 +377,39 @@ static void InitializePredefinedMacros(const TargetInfo &TI, // Define a __POINTER_WIDTH__ macro for stdint.h. sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0)); DefineBuiltinMacro(Buf, MacroBuf); - + if (!LangOpts.CharIsSigned) - DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__"); + DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__"); // Define fixed-sized integer types for stdint.h assert(TI.getCharWidth() == 8 && "unsupported target types"); assert(TI.getShortWidth() == 16 && "unsupported target types"); DefineBuiltinMacro(Buf, "__INT8_TYPE__=char"); DefineBuiltinMacro(Buf, "__INT16_TYPE__=short"); - + if (TI.getIntWidth() == 32) DefineBuiltinMacro(Buf, "__INT32_TYPE__=int"); else { assert(TI.getLongLongWidth() == 32 && "unsupported target types"); DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long"); } - + // 16-bit targets doesn't necessarily have a 64-bit type. if (TI.getLongLongWidth() == 64) DefineType("__INT64_TYPE__", TI.getInt64Type(), Buf); - + // Add __builtin_va_list typedef. { const char *VAList = TI.getVAListDeclaration(); Buf.insert(Buf.end(), VAList, VAList+strlen(VAList)); Buf.push_back('\n'); } - + if (const char *Prefix = TI.getUserLabelPrefix()) { sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix); DefineBuiltinMacro(Buf, MacroBuf); } - + // Build configuration options. FIXME: these should be controlled by // command line options or something. DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0"); @@ -452,15 +452,15 @@ static void InitializePredefinedMacros(const TargetInfo &TI, bool InitializePreprocessor(Preprocessor &PP, const PreprocessorInitOptions& InitOpts) { std::vector PredefineBuffer; - + const char *LineDirective = "# 1 \"\" 3\n"; PredefineBuffer.insert(PredefineBuffer.end(), LineDirective, LineDirective+strlen(LineDirective)); - + // Install things like __POWERPC__, __GNUC__, etc into the macro table. InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(), PredefineBuffer); - + // Add on the predefines from the driver. Wrap in a #line directive to report // that they come from the command line. LineDirective = "# 1 \"\" 1\n"; diff --git a/clang/lib/Frontend/PCHReader.cpp b/clang/lib/Frontend/PCHReader.cpp index f4d06c068bd70eb072405d6c4c14f52c072d79d6..e7321bf6fabcaf100e17320c74afbf3e24d7746c 100644 --- a/clang/lib/Frontend/PCHReader.cpp +++ b/clang/lib/Frontend/PCHReader.cpp @@ -69,21 +69,21 @@ PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) { PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi); PARSE_LANGOPT_BENIGN(PascalStrings); PARSE_LANGOPT_BENIGN(WritableStrings); - PARSE_LANGOPT_IMPORTANT(LaxVectorConversions, + PARSE_LANGOPT_IMPORTANT(LaxVectorConversions, diag::warn_pch_lax_vector_conversions); PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec); PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions); PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime); PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding); PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins); - PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics, + PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics, diag::warn_pch_thread_safe_statics); PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads); PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks); PARSE_LANGOPT_BENIGN(EmitAllDecls); PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno); PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking); - PARSE_LANGOPT_IMPORTANT(HeinousExtensions, + PARSE_LANGOPT_IMPORTANT(HeinousExtensions, diag::warn_pch_heinous_extensions); // FIXME: Most of the options below are benign if the macro wasn't // used. Unfortunately, this means that a PCH compiled without @@ -101,7 +101,7 @@ PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) { PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control); PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed); if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) { - Reader.Diag(diag::warn_pch_gc_mode) + Reader.Diag(diag::warn_pch_gc_mode) << LangOpts.getGCMode() << PPLangOpts.getGCMode(); return true; } @@ -165,7 +165,7 @@ static inline bool startsWith(const std::string &Haystack, return startsWith(Haystack, Needle.c_str()); } -bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, +bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID, std::string &SuggestedPredefines) { @@ -173,19 +173,19 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, unsigned PredefLen = PP.getPredefines().size(); // If the two predefines buffers compare equal, we're done! - if (PredefLen == PCHPredefLen && + if (PredefLen == PCHPredefLen && strncmp(Predef, PCHPredef, PCHPredefLen) == 0) return false; SourceManager &SourceMgr = PP.getSourceManager(); - + // The predefines buffers are different. Determine what the // differences are, and whether they require us to reject the PCH // file. std::vector CmdLineLines = splitLines(Predef, PredefLen); std::vector PCHLines = splitLines(PCHPredef, PCHPredefLen); - // Sort both sets of predefined buffer lines, since + // Sort both sets of predefined buffer lines, since std::sort(CmdLineLines.begin(), CmdLineLines.end()); std::sort(PCHLines.begin(), PCHLines.end()); @@ -204,11 +204,11 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, Reader.Diag(diag::warn_pch_compiler_options_mismatch); return true; } - + // This is a macro definition. Determine the name of the macro // we're defining. std::string::size_type StartOfMacroName = strlen("#define "); - std::string::size_type EndOfMacroName + std::string::size_type EndOfMacroName = Missing.find_first_of("( \n\r", StartOfMacroName); assert(EndOfMacroName != std::string::npos && "Couldn't find the end of the macro name"); @@ -226,19 +226,19 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, if (!startsWith(*ConflictPos, MacroDefStart)) { // Different macro; we're done. ConflictPos = CmdLineLines.end(); - break; + break; } - - assert(ConflictPos->size() > MacroDefLen && + + assert(ConflictPos->size() > MacroDefLen && "Invalid #define in predefines buffer?"); - if ((*ConflictPos)[MacroDefLen] != ' ' && + if ((*ConflictPos)[MacroDefLen] != ' ' && (*ConflictPos)[MacroDefLen] != '(') continue; // Longer macro name; keep trying. - + // We found a conflicting macro definition. break; } - + if (ConflictPos != CmdLineLines.end()) { Reader.Diag(diag::warn_cmdline_conflicting_macro_def) << MacroName; @@ -255,13 +255,13 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, ConflictingDefines = true; continue; } - + // If the macro doesn't conflict, then we'll just pick up the // macro definition from the PCH file. Warn the user that they // made a mistake. if (ConflictingDefines) continue; // Don't complain if there are already conflicting defs - + if (!MissingDefines) { Reader.Diag(diag::warn_cmdline_missing_macro_defs); MissingDefines = true; @@ -275,10 +275,10 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, .getFileLocWithOffset(Offset); Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch); } - + if (ConflictingDefines) return true; - + // Determine what predefines were introduced based on command-line // parameters that were not present when building the PCH // file. Extra #defines are okay, so long as the identifiers being @@ -286,7 +286,7 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, std::vector ExtraPredefines; std::set_difference(CmdLineLines.begin(), CmdLineLines.end(), PCHLines.begin(), PCHLines.end(), - std::back_inserter(ExtraPredefines)); + std::back_inserter(ExtraPredefines)); for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) { const std::string &Extra = ExtraPredefines[I]; if (!startsWith(Extra, "#define ") != 0) { @@ -297,7 +297,7 @@ bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef, // This is an extra macro definition. Determine the name of the // macro we're defining. std::string::size_type StartOfMacroName = strlen("#define "); - std::string::size_type EndOfMacroName + std::string::size_type EndOfMacroName = Extra.find_first_of("( \n\r", StartOfMacroName); assert(EndOfMacroName != std::string::npos && "Couldn't find the end of the macro name"); @@ -338,8 +338,8 @@ void PCHValidator::ReadCounter(unsigned Value) { // PCH reader implementation //===----------------------------------------------------------------------===// -PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context, - const char *isysroot) +PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context, + const char *isysroot) : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context), Consumer(0), @@ -348,16 +348,16 @@ PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context, MethodPoolLookupTable(0), MethodPoolLookupTableData(0), TotalSelectorsInMethodPool(0), SelectorOffsets(0), TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot), - NumStatHits(0), NumStatMisses(0), - NumSLocEntriesRead(0), NumStatementsRead(0), + NumStatHits(0), NumStatMisses(0), + NumSLocEntriesRead(0), NumStatementsRead(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0), NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0), - CurrentlyLoadingTypeOrDecl(0) { + CurrentlyLoadingTypeOrDecl(0) { RelocatablePCH = false; } PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr, - Diagnostic &Diags, const char *isysroot) + Diagnostic &Diags, const char *isysroot) : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0), IdentifierTableData(0), IdentifierLookupTable(0), @@ -365,11 +365,11 @@ PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr, MethodPoolLookupTable(0), MethodPoolLookupTableData(0), TotalSelectorsInMethodPool(0), SelectorOffsets(0), TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot), - NumStatHits(0), NumStatMisses(0), - NumSLocEntriesRead(0), NumStatementsRead(0), + NumStatHits(0), NumStatMisses(0), + NumSLocEntriesRead(0), NumStatementsRead(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0), NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0), - CurrentlyLoadingTypeOrDecl(0) { + CurrentlyLoadingTypeOrDecl(0) { RelocatablePCH = false; } @@ -395,12 +395,12 @@ public: typedef external_key_type internal_key_type; explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { } - + static bool EqualKey(const internal_key_type& a, const internal_key_type& b) { return a == b; } - + static unsigned ComputeHash(Selector Sel) { unsigned N = Sel.getNumArgs(); if (N == 0) @@ -411,11 +411,11 @@ public: R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R); return R; } - + // This hopefully will just get inlined and removed by the optimizer. static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + static std::pair ReadKeyDataLength(const unsigned char*& d) { using namespace clang::io; @@ -423,12 +423,12 @@ public: unsigned DataLen = ReadUnalignedLE16(d); return std::make_pair(KeyLen, DataLen); } - + internal_key_type ReadKey(const unsigned char* d, unsigned) { using namespace clang::io; SelectorTable &SelTable = Reader.getContext()->Selectors; unsigned N = ReadUnalignedLE16(d); - IdentifierInfo *FirstII + IdentifierInfo *FirstII = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)); if (N == 0) return SelTable.getNullarySelector(FirstII); @@ -442,7 +442,7 @@ public: return SelTable.getSelector(N, Args.data()); } - + data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) { using namespace clang::io; unsigned NumInstanceMethods = ReadUnalignedLE16(d); @@ -453,7 +453,7 @@ public: // Load instance methods ObjCMethodList *Prev = 0; for (unsigned I = 0; I != NumInstanceMethods; ++I) { - ObjCMethodDecl *Method + ObjCMethodDecl *Method = cast(Reader.GetDecl(ReadUnalignedLE32(d))); if (!Result.first.Method) { // This is the first method, which is the easy case. @@ -469,7 +469,7 @@ public: // Load factory methods Prev = 0; for (unsigned I = 0; I != NumFactoryMethods; ++I) { - ObjCMethodDecl *Method + ObjCMethodDecl *Method = cast(Reader.GetDecl(ReadUnalignedLE32(d))); if (!Result.second.Method) { // This is the first method, which is the easy case. @@ -485,11 +485,11 @@ public: return Result; } }; - -} // end anonymous namespace + +} // end anonymous namespace /// \brief The on-disk hash table used for the global method pool. -typedef OnDiskChainedHashTable +typedef OnDiskChainedHashTable PCHMethodPoolLookupTable; namespace { @@ -508,23 +508,23 @@ public: typedef external_key_type internal_key_type; - explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0) + explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0) : Reader(Reader), KnownII(II) { } - + static bool EqualKey(const internal_key_type& a, const internal_key_type& b) { return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0 : false; } - + static unsigned ComputeHash(const internal_key_type& a) { return BernsteinHash(a.first, a.second); } - + // This hopefully will just get inlined and removed by the optimizer. static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + static std::pair ReadKeyDataLength(const unsigned char*& d) { using namespace clang::io; @@ -532,14 +532,14 @@ public: unsigned KeyLen = ReadUnalignedLE16(d); return std::make_pair(KeyLen, DataLen); } - + static std::pair ReadKey(const unsigned char* d, unsigned n) { assert(n >= 2 && d[n-1] == '\0'); return std::make_pair((const char*) d, n-1); } - - IdentifierInfo *ReadData(const internal_key_type& k, + + IdentifierInfo *ReadData(const internal_key_type& k, const unsigned char* d, unsigned DataLen) { using namespace clang::io; @@ -571,7 +571,7 @@ public: Bits >>= 1; unsigned ObjCOrBuiltinID = Bits & 0x3FF; Bits >>= 10; - + assert(Bits == 0 && "Extra bits in the identifier?"); DataLen -= 6; @@ -586,7 +586,7 @@ public: // Set or check the various bits in the IdentifierInfo structure. // FIXME: Load token IDs lazily, too? II->setObjCOrBuiltinID(ObjCOrBuiltinID); - assert(II->isExtensionToken() == ExtensionToken && + assert(II->isExtensionToken() == ExtensionToken && "Incorrect extension token flag"); (void)ExtensionToken; II->setIsPoisoned(Poisoned); @@ -611,16 +611,16 @@ public: DeclIDs.push_back(ReadUnalignedLE32(d)); Reader.SetGloballyVisibleDecls(II, DeclIDs); } - + return II; } }; - -} // end anonymous namespace + +} // end anonymous namespace /// \brief The on-disk hash table used to contain information about /// all of the identifiers in the program. -typedef OnDiskChainedHashTable +typedef OnDiskChainedHashTable PCHIdentifierLookupTable; bool PCHReader::Error(const char *Msg) { @@ -646,7 +646,7 @@ bool PCHReader::Error(const char *Msg) { /// /// \returns true if there was a mismatch (in which case the PCH file /// should be ignored), or false otherwise. -bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef, +bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID) { if (Listener) @@ -673,7 +673,7 @@ bool PCHReader::ParseLineTable(llvm::SmallVectorImpl &Record) { std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen); Idx += FilenameLen; MaybeAddSystemRootToFilename(Filename); - FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(), + FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(), Filename.size()); } @@ -690,7 +690,7 @@ bool PCHReader::ParseLineTable(llvm::SmallVectorImpl &Record) { unsigned FileOffset = Record[Idx++]; unsigned LineNo = Record[Idx++]; int FilenameID = Record[Idx++]; - SrcMgr::CharacteristicKind FileKind + SrcMgr::CharacteristicKind FileKind = (SrcMgr::CharacteristicKind)Record[Idx++]; unsigned IncludeOffset = Record[Idx++]; Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, @@ -712,10 +712,10 @@ public: const mode_t mode; const time_t mtime; const off_t size; - + PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s) - : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {} - + : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {} + PCHStatData() : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {} }; @@ -758,7 +758,7 @@ class VISIBILITY_HIDDEN PCHStatLookupTrait { ino_t ino = (ino_t) ReadUnalignedLE32(d); dev_t dev = (dev_t) ReadUnalignedLE32(d); mode_t mode = (mode_t) ReadUnalignedLE16(d); - time_t mtime = (time_t) ReadUnalignedLE64(d); + time_t mtime = (time_t) ReadUnalignedLE64(d); off_t size = (off_t) ReadUnalignedLE64(d); return data_type(ino, dev, mode, mtime, size); } @@ -773,17 +773,17 @@ class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache { CacheTy *Cache; unsigned &NumStatHits, &NumStatMisses; -public: +public: PCHStatCache(const unsigned char *Buckets, const unsigned char *Base, unsigned &NumStatHits, - unsigned &NumStatMisses) + unsigned &NumStatMisses) : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) { Cache = CacheTy::Create(Buckets, Base); } ~PCHStatCache() { delete Cache; } - + int stat(const char *path, struct stat *buf) { // Do the lookup for the file's data in the PCH file. CacheTy::iterator I = Cache->find(path); @@ -793,10 +793,10 @@ public: ++NumStatMisses; return ::stat(path, buf); } - + ++NumStatHits; PCHStatData Data = *I; - + if (!Data.hasStat) return 1; @@ -843,7 +843,7 @@ PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() { } return Success; } - + if (Code == llvm::bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. SLocEntryCursor.ReadSubBlockID(); @@ -853,12 +853,12 @@ PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() { } continue; } - + if (Code == llvm::bitc::DEFINE_ABBREV) { SLocEntryCursor.ReadAbbrevRecord(); continue; } - + // Read a record. const char *BlobStart; unsigned BlobLen; @@ -931,7 +931,7 @@ PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) { Error(ErrorStr.c_str()); return Failure; } - + FileID FID = SourceMgr.createFileID(File, SourceLocation::getFromRawEncoding(Record[1]), (SrcMgr::CharacteristicKind)Record[2], @@ -948,16 +948,16 @@ PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) { unsigned Offset = Record[0]; unsigned Code = SLocEntryCursor.ReadCode(); Record.clear(); - unsigned RecCode + unsigned RecCode = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen); assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file"); (void)RecCode; llvm::MemoryBuffer *Buffer - = llvm::MemoryBuffer::getMemBuffer(BlobStart, + = llvm::MemoryBuffer::getMemBuffer(BlobStart, BlobStart + BlobLen - 1, Name); FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset); - + if (strcmp(Name, "") == 0) { PCHPredefinesBufferID = BufferID; PCHPredefines = BlobStart; @@ -968,7 +968,7 @@ PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) { } case pch::SM_SLOC_INSTANTIATION_ENTRY: { - SourceLocation SpellingLoc + SourceLocation SpellingLoc = SourceLocation::getFromRawEncoding(Record[1]); SourceMgr.createInstantiationLoc(SpellingLoc, SourceLocation::getFromRawEncoding(Record[2]), @@ -977,7 +977,7 @@ PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) { ID, Record[0]); break; - } + } } return Success; @@ -992,10 +992,10 @@ bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, Error("malformed block record in PCH file"); return Failure; } - + while (true) { unsigned Code = Cursor.ReadCode(); - + // We expect all abbrevs to be at the start of the block. if (Code != llvm::bitc::DEFINE_ABBREV) return false; @@ -1005,7 +1005,7 @@ bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, void PCHReader::ReadMacroRecord(uint64_t Offset) { assert(PP && "Forgot to set Preprocessor ?"); - + // Keep track of where we are in the stream, then jump back there // after reading this macro. SavedStreamPosition SavedPosition(Stream); @@ -1014,7 +1014,7 @@ void PCHReader::ReadMacroRecord(uint64_t Offset) { RecordData Record; llvm::SmallVector MacroArgs; MacroInfo *Macro = 0; - + while (true) { unsigned Code = Stream.ReadCode(); switch (Code) { @@ -1029,7 +1029,7 @@ void PCHReader::ReadMacroRecord(uint64_t Offset) { return; } continue; - + case llvm::bitc::DEFINE_ABBREV: Stream.ReadAbbrevRecord(); continue; @@ -1056,10 +1056,10 @@ void PCHReader::ReadMacroRecord(uint64_t Offset) { } SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]); bool isUsed = Record[2]; - + MacroInfo *MI = PP->AllocateMacroInfo(Loc); MI->setIsUsed(isUsed); - + if (RecType == pch::PP_MACRO_FUNCTION_LIKE) { // Decode function-like macro info. bool isC99VarArgs = Record[3]; @@ -1086,12 +1086,12 @@ void PCHReader::ReadMacroRecord(uint64_t Offset) { ++NumMacrosRead; break; } - + case pch::PP_TOKEN: { // If we see a TOKEN before a PP_MACRO_*, then the file is // erroneous, just pretend we didn't see this. if (Macro == 0) break; - + Token Tok; Tok.startToken(); Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0])); @@ -1114,26 +1114,26 @@ void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) { // If this is not a relocatable PCH file, there's nothing to do. if (!RelocatablePCH) return; - + if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<') return; std::string FIXME = Filename; - + if (isysroot == 0) { // If no system root was given, default to '/' Filename.insert(Filename.begin(), '/'); return; } - + unsigned Length = strlen(isysroot); if (isysroot[Length - 1] != '/') Filename.insert(Filename.begin(), '/'); - + Filename.insert(Filename.begin(), isysroot, isysroot + Length); } -PCHReader::PCHReadResult +PCHReader::PCHReadResult PCHReader::ReadPCHBlock() { if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) { Error("malformed block record in PCH file"); @@ -1176,7 +1176,7 @@ PCHReader::ReadPCHBlock() { return Failure; } break; - + case pch::PREPROCESSOR_BLOCK_ID: if (Stream.SkipBlock()) { Error("malformed block record in PCH file"); @@ -1210,7 +1210,7 @@ PCHReader::ReadPCHBlock() { Record.clear(); const char *BlobStart = 0; unsigned BlobLen = 0; - switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record, + switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { default: // Default behavior: ignore. break; @@ -1257,10 +1257,10 @@ PCHReader::ReadPCHBlock() { case pch::IDENTIFIER_TABLE: IdentifierTableData = BlobStart; if (Record[0]) { - IdentifierLookupTable + IdentifierLookupTable = PCHIdentifierLookupTable::Create( (const unsigned char *)IdentifierTableData + Record[0], - (const unsigned char *)IdentifierTableData, + (const unsigned char *)IdentifierTableData, PCHIdentifierLookupTrait(*this)); if (PP) PP->getIdentifierTable().setExternalIdentifierLookup(this); @@ -1322,10 +1322,10 @@ PCHReader::ReadPCHBlock() { case pch::METHOD_POOL: MethodPoolLookupTableData = (const unsigned char *)BlobStart; if (Record[0]) - MethodPoolLookupTable + MethodPoolLookupTable = PCHMethodPoolLookupTable::Create( MethodPoolLookupTableData + Record[0], - MethodPoolLookupTableData, + MethodPoolLookupTableData, PCHMethodPoolLookupTrait(*this)); TotalSelectorsInMethodPool = Record[1]; break; @@ -1338,8 +1338,8 @@ PCHReader::ReadPCHBlock() { case pch::SOURCE_LOCATION_OFFSETS: SLocOffsets = (const uint32_t *)BlobStart; TotalNumSLocEntries = Record[0]; - SourceMgr.PreallocateSLocEntries(this, - TotalNumSLocEntries, + SourceMgr.PreallocateSLocEntries(this, + TotalNumSLocEntries, Record[1]); break; @@ -1370,7 +1370,7 @@ PCHReader::ReadPCHBlock() { OriginalFileName.assign(BlobStart, BlobLen); MaybeAddSystemRootToFilename(OriginalFileName); break; - + case pch::COMMENT_RANGES: Comments = (SourceRange *)BlobStart; NumComments = BlobLen / sizeof(SourceRange); @@ -1394,7 +1394,7 @@ PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) { } // Initialize the stream - StreamFile.init((const unsigned char *)Buffer->getBufferStart(), + StreamFile.init((const unsigned char *)Buffer->getBufferStart(), (const unsigned char *)Buffer->getBufferEnd()); Stream.init(StreamFile); @@ -1409,7 +1409,7 @@ PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) { while (!Stream.AtEndOfStream()) { unsigned Code = Stream.ReadCode(); - + if (Code != llvm::bitc::ENTER_SUBBLOCK) { Error("invalid record at top-level of PCH file"); return Failure; @@ -1455,13 +1455,13 @@ PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) { } break; } - } - + } + // Check the predefines buffer. - if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen, + if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen, PCHPredefinesBufferID)) return IgnorePCH; - + if (PP) { // Initialization of keywords and pragmas occurs before the // PCH file is read, so there may be some identifiers that were @@ -1480,7 +1480,7 @@ PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) { IdEnd = PP->getIdentifierTable().end(); Id != IdEnd; ++Id) Identifiers.push_back(Id->second); - PCHIdentifierLookupTable *IdTable + PCHIdentifierLookupTable *IdTable = (PCHIdentifierLookupTable *)IdentifierLookupTable; for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) { IdentifierInfo *II = Identifiers[I]; @@ -1490,7 +1490,7 @@ PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) { PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info); if (Pos == IdTable->end()) continue; - + // Dereferencing the iterator has the effect of populating the // IdentifierInfo node with the various declarations it needs. (void)*Pos; @@ -1510,7 +1510,7 @@ void PCHReader::InitializeContext(ASTContext &Ctx) { assert(PP && "Forgot to set Preprocessor ?"); PP->getIdentifierTable().setExternalIdentifierLookup(this); PP->getHeaderSearchInfo().SetExternalLookup(this); - + // Load the translation unit declaration ReadDeclRecord(DeclOffsets[0], 0); @@ -1528,7 +1528,7 @@ void PCHReader::InitializeContext(ASTContext &Ctx) { if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING]) Context->setCFConstantStringType(GetType(String)); - if (unsigned FastEnum + if (unsigned FastEnum = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE]) Context->setObjCFastEnumerationStateType(GetType(FastEnum)); if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) { @@ -1564,10 +1564,10 @@ void PCHReader::InitializeContext(ASTContext &Ctx) { Context->setsigjmp_bufDecl(Tag->getDecl()); } } - if (unsigned ObjCIdRedef + if (unsigned ObjCIdRedef = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION]) Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef); - if (unsigned ObjCClassRedef + if (unsigned ObjCClassRedef = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef); } @@ -1588,7 +1588,7 @@ std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) { // Initialize the stream llvm::BitstreamReader StreamFile; llvm::BitstreamCursor Stream; - StreamFile.init((const unsigned char *)Buffer->getBufferStart(), + StreamFile.init((const unsigned char *)Buffer->getBufferStart(), (const unsigned char *)Buffer->getBufferEnd()); Stream.init(StreamFile); @@ -1597,7 +1597,7 @@ std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) { Stream.Read(8) != 'P' || Stream.Read(8) != 'C' || Stream.Read(8) != 'H') { - fprintf(stderr, + fprintf(stderr, "error: '%s' does not appear to be a precompiled header file\n", PCHFileName.c_str()); return std::string(); @@ -1606,10 +1606,10 @@ std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) { RecordData Record; while (!Stream.AtEndOfStream()) { unsigned Code = Stream.ReadCode(); - + if (Code == llvm::bitc::ENTER_SUBBLOCK) { unsigned BlockID = Stream.ReadSubBlockID(); - + // We only know the PCH subblock ID. switch (BlockID) { case pch::PCH_BLOCK_ID: @@ -1618,7 +1618,7 @@ std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) { return std::string(); } break; - + default: if (Stream.SkipBlock()) { fprintf(stderr, "error: malformed block record in PCH file\n"); @@ -1645,10 +1645,10 @@ std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) { Record.clear(); const char *BlobStart = 0; unsigned BlobLen = 0; - if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) + if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) == pch::ORIGINAL_FILE_NAME) return std::string(BlobStart, BlobLen); - } + } return std::string(); } @@ -1671,11 +1671,11 @@ bool PCHReader::ParseLanguageOptions( const llvm::SmallVectorImpl &Record) { if (Listener) { LangOptions LangOpts; - + #define PARSE_LANGOPT(Option) \ LangOpts.Option = Record[Idx]; \ ++Idx - + unsigned Idx = 0; PARSE_LANGOPT(Trigraphs); PARSE_LANGOPT(BCPLComment); @@ -1748,18 +1748,18 @@ QualType PCHReader::ReadTypeRecord(uint64_t Offset) { // Note that we are loading a type record. LoadingTypeOrDecl Loading(*this); - + Stream.JumpToBit(Offset); RecordData Record; unsigned Code = Stream.ReadCode(); switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) { case pch::TYPE_EXT_QUAL: { - assert(Record.size() == 3 && + assert(Record.size() == 3 && "Incorrect encoding of extended qualifier type"); QualType Base = GetType(Record[0]); QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1]; unsigned AddressSpace = Record[2]; - + QualType T = Base; if (GCAttr != QualType::GCNone) T = Context->getObjCGCQualType(T, GCAttr); @@ -1929,7 +1929,7 @@ QualType PCHReader::ReadTypeRecord(uint64_t Offset) { QualType UnderlyingType = GetType(Record[0]); return Context->getTypeOfType(UnderlyingType); } - + case pch::TYPE_DECLTYPE: return Context->getDecltypeType(ReadTypeExpr()); @@ -1974,7 +1974,7 @@ QualType PCHReader::ReadTypeRecord(uint64_t Offset) { QualType PCHReader::GetType(pch::TypeID ID) { - unsigned Quals = ID & 0x07; + unsigned Quals = ID & 0x07; unsigned Index = ID >> 3; if (Index < pch::NUM_PREDEF_TYPE_IDS) { @@ -2023,7 +2023,7 @@ QualType PCHReader::GetType(pch::TypeID ID) { //assert(Index < TypesLoaded.size() && "Type index out-of-range"); if (!TypesLoaded[Index]) TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr(); - + return QualType(TypesLoaded[Index], Quals); } @@ -2057,7 +2057,7 @@ Stmt *PCHReader::GetDeclStmt(uint64_t Offset) { bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC, llvm::SmallVectorImpl &Decls) { - assert(DC->hasExternalLexicalStorage() && + assert(DC->hasExternalLexicalStorage() && "DeclContext has no lexical decls in storage"); uint64_t Offset = DeclContextOffsets[DC].first; assert(Offset && "DeclContext has no lexical decls in storage"); @@ -2084,7 +2084,7 @@ bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC, bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC, llvm::SmallVectorImpl &Decls) { - assert(DC->hasExternalVisibleStorage() && + assert(DC->hasExternalVisibleStorage() && "DeclContext has no visible decls in storage"); uint64_t Offset = DeclContextOffsets[DC].second; assert(Offset && "DeclContext has no visible decls in storage"); @@ -2102,7 +2102,7 @@ bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC, (void)RecCode; assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block"); if (Record.size() == 0) - return false; + return false; Decls.clear(); @@ -2143,7 +2143,7 @@ void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) { void PCHReader::PrintStats() { std::fprintf(stderr, "*** PCH Statistics:\n"); - unsigned NumTypesLoaded + unsigned NumTypesLoaded = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(), (Type *)0); unsigned NumDeclsLoaded @@ -2153,7 +2153,7 @@ void PCHReader::PrintStats() { = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), IdentifiersLoaded.end(), (IdentifierInfo *)0); - unsigned NumSelectorsLoaded + unsigned NumSelectorsLoaded = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), SelectorsLoaded.end(), Selector()); @@ -2245,7 +2245,7 @@ void PCHReader::InitializeSema(Sema &S) { IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) { // Try to find this name within our on-disk hash table - PCHIdentifierLookupTable *IdTable + PCHIdentifierLookupTable *IdTable = (PCHIdentifierLookupTable *)IdentifierLookupTable; std::pair Key(NameStart, NameEnd - NameStart); PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key); @@ -2258,7 +2258,7 @@ IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) { return *Pos; } -std::pair +std::pair PCHReader::ReadMethodPool(Selector Sel) { if (!MethodPoolLookupTable) return std::pair(); @@ -2286,7 +2286,7 @@ void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) { /// identifier. /// /// If the PCH reader is currently in a state where the given declaration IDs -/// cannot safely be resolved, they are queued until it is safe to resolve +/// cannot safely be resolved, they are queued until it is safe to resolve /// them. /// /// \param II an IdentifierInfo that refers to one or more globally-visible @@ -2298,8 +2298,8 @@ void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) { /// \param Nonrecursive should be true to indicate that the caller knows that /// this call is non-recursive, and therefore the globally-visible declarations /// will not be placed onto the pending queue. -void -PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II, +void +PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II, const llvm::SmallVectorImpl &DeclIDs, bool Nonrecursive) { if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) { @@ -2310,7 +2310,7 @@ PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II, PII.DeclIDs.push_back(DeclIDs[I]); return; } - + for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { NamedDecl *D = cast(GetDecl(DeclIDs[I])); if (SemaObj) { @@ -2331,12 +2331,12 @@ PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II, IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) { if (ID == 0) return 0; - + if (!IdentifierTableData || IdentifiersLoaded.empty()) { Error("no identifier table in PCH file"); return 0; } - + assert(PP && "Forgot to set Preprocessor ?"); if (!IdentifiersLoaded[ID - 1]) { uint32_t Offset = IdentifierOffsets[ID - 1]; @@ -2348,10 +2348,10 @@ IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) { const char *StrLenPtr = Str - 2; unsigned StrLen = (((unsigned) StrLenPtr[0]) | (((unsigned) StrLenPtr[1]) << 8)) - 1; - IdentifiersLoaded[ID - 1] + IdentifiersLoaded[ID - 1] = &PP->getIdentifierTable().get(Str, Str + StrLen); } - + return IdentifiersLoaded[ID - 1]; } @@ -2362,7 +2362,7 @@ void PCHReader::ReadSLocEntry(unsigned ID) { Selector PCHReader::DecodeSelector(unsigned ID) { if (ID == 0) return Selector(); - + if (!MethodPoolLookupTableData) return Selector(); @@ -2376,14 +2376,14 @@ Selector PCHReader::DecodeSelector(unsigned ID) { // Load this selector from the selector table. // FIXME: endianness portability issues with SelectorOffsets table PCHMethodPoolLookupTrait Trait(*this); - SelectorsLoaded[Index] + SelectorsLoaded[Index] = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0); } return SelectorsLoaded[Index]; } -DeclarationName +DeclarationName PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) { DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; switch (Kind) { @@ -2478,7 +2478,7 @@ SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) { /// \brief Record that the given label statement has been /// deserialized and has the given ID. void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) { - assert(LabelStmts.find(ID) == LabelStmts.end() && + assert(LabelStmts.find(ID) == LabelStmts.end() && "Deserialized label twice"); LabelStmts[ID] = S; @@ -2493,9 +2493,9 @@ void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) { // If we've already seen any address-label statements that point to // this label, resolve them now. typedef std::multimap::iterator AddrLabelIter; - std::pair AddrLabels + std::pair AddrLabels = UnresolvedAddrLabelExprs.equal_range(ID); - for (AddrLabelIter AddrLabel = AddrLabels.first; + for (AddrLabelIter AddrLabel = AddrLabels.first; AddrLabel != AddrLabels.second; ++AddrLabel) AddrLabel->second->setLabel(S); UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second); @@ -2542,7 +2542,7 @@ void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) { } -PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader) +PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader) : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) { Reader.CurrentlyLoadingTypeOrDecl = this; } @@ -2559,5 +2559,5 @@ PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() { } } - Reader.CurrentlyLoadingTypeOrDecl = Parent; + Reader.CurrentlyLoadingTypeOrDecl = Parent; } diff --git a/clang/lib/Frontend/PCHReaderDecl.cpp b/clang/lib/Frontend/PCHReaderDecl.cpp index cc8712acd0920a73a718dc031b7ad5f0faddd48e..03ac3aad229447a4c2bde28f33a96113b49114af 100644 --- a/clang/lib/Frontend/PCHReaderDecl.cpp +++ b/clang/lib/Frontend/PCHReaderDecl.cpp @@ -94,7 +94,7 @@ void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) { void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) { VisitDecl(ND); - ND->setDeclName(Reader.ReadDeclarationName(Record, Idx)); + ND->setDeclName(Reader.ReadDeclarationName(Record, Idx)); } void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) { @@ -163,9 +163,9 @@ public: #define ABSTRACT_TYPELOC(CLASS) #define TYPELOC(CLASS, PARENT, TYPE) \ - void Visit##CLASS(CLASS TyLoc); + void Visit##CLASS(CLASS TyLoc); #include "clang/AST/TypeLocNodes.def" - + void VisitTypeLoc(TypeLoc TyLoc) { assert(0 && "A type loc wrapper was not handled!"); } @@ -447,10 +447,10 @@ void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) { Params.reserve(NumParams); for (unsigned I = 0; I != NumParams; ++I) Params.push_back(cast(Reader.GetDecl(Record[Idx++]))); - BD->setParams(*Reader.getContext(), Params.data(), NumParams); + BD->setParams(*Reader.getContext(), Params.data(), NumParams); } -std::pair +std::pair PCHDeclReader::VisitDeclContext(DeclContext *DC) { uint64_t LexicalOffset = Record[Idx++]; uint64_t VisibleOffset = Record[Idx++]; @@ -464,13 +464,13 @@ PCHDeclReader::VisitDeclContext(DeclContext *DC) { /// \brief Reads attributes from the current stream position. Attr *PCHReader::ReadAttributes() { unsigned Code = DeclsCursor.ReadCode(); - assert(Code == llvm::bitc::UNABBREV_RECORD && + assert(Code == llvm::bitc::UNABBREV_RECORD && "Expected unabbreviated record"); (void)Code; - + RecordData Record; unsigned Idx = 0; unsigned RecCode = DeclsCursor.ReadRecord(Code, Record); - assert(RecCode == pch::DECL_ATTR && "Expected attribute record"); + assert(RecCode == pch::DECL_ATTR && "Expected attribute record"); (void)RecCode; #define SIMPLE_ATTR(Name) \ @@ -501,12 +501,12 @@ Attr *PCHReader::ReadAttributes() { SIMPLE_ATTR(AnalyzerNoReturn); STRING_ATTR(Annotate); STRING_ATTR(AsmLabel); - + case Attr::Blocks: New = ::new (*Context) BlocksAttr( (BlocksAttr::BlocksAttrTypes)Record[Idx++]); break; - + case Attr::Cleanup: New = ::new (*Context) CleanupAttr( cast(GetDecl(Record[Idx++]))); @@ -519,7 +519,7 @@ Attr *PCHReader::ReadAttributes() { SIMPLE_ATTR(Deprecated); UNSIGNED_ATTR(Destructor); SIMPLE_ATTR(FastCall); - + case Attr::Format: { std::string Type = ReadString(Record, Idx); unsigned FormatIdx = Record[Idx++]; @@ -527,13 +527,13 @@ Attr *PCHReader::ReadAttributes() { New = ::new (*Context) FormatAttr(Type, FormatIdx, FirstArg); break; } - + case Attr::FormatArg: { unsigned FormatIdx = Record[Idx++]; New = ::new (*Context) FormatArgAttr(FormatIdx); break; } - + case Attr::Sentinel: { int sentinel = Record[Idx++]; int nullPos = Record[Idx++]; @@ -542,7 +542,7 @@ Attr *PCHReader::ReadAttributes() { } SIMPLE_ATTR(GNUInline); - + case Attr::IBOutletKind: New = ::new (*Context) IBOutletAttr(); break; @@ -552,7 +552,7 @@ Attr *PCHReader::ReadAttributes() { SIMPLE_ATTR(NoInline); SIMPLE_ATTR(NoReturn); SIMPLE_ATTR(NoThrow); - + case Attr::NonNull: { unsigned Size = Record[Idx++]; llvm::SmallVector ArgNums; @@ -561,7 +561,7 @@ Attr *PCHReader::ReadAttributes() { New = ::new (*Context) NonNullAttr(ArgNums.data(), Size); break; } - + case Attr::ReqdWorkGroupSize: { unsigned X = Record[Idx++]; unsigned Y = Record[Idx++]; @@ -585,7 +585,7 @@ Attr *PCHReader::ReadAttributes() { SIMPLE_ATTR(Unavailable); SIMPLE_ATTR(Unused); SIMPLE_ATTR(Used); - + case Attr::Visibility: New = ::new (*Context) VisibilityAttr( (VisibilityAttr::VisibilityTypes)Record[Idx++]); @@ -624,7 +624,7 @@ Attr *PCHReader::ReadAttributes() { /// \brief Note that we have loaded the declaration with the given /// Index. -/// +/// /// This routine notes that this declaration has already been loaded, /// so that future GetDecl calls will return this declaration rather /// than trying to load a new declaration. @@ -656,7 +656,7 @@ Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) { // Note that we are loading a declaration record. LoadingTypeOrDecl Loading(*this); - + DeclsCursor.JumpToBit(Offset); RecordData Record; unsigned Code = DeclsCursor.ReadCode(); @@ -689,11 +689,11 @@ Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) { 0, llvm::APSInt()); break; case pch::DECL_FUNCTION: - D = FunctionDecl::Create(*Context, 0, SourceLocation(), DeclarationName(), + D = FunctionDecl::Create(*Context, 0, SourceLocation(), DeclarationName(), QualType(), 0); break; case pch::DECL_OBJC_METHOD: - D = ObjCMethodDecl::Create(*Context, SourceLocation(), SourceLocation(), + D = ObjCMethodDecl::Create(*Context, SourceLocation(), SourceLocation(), Selector(), QualType(), 0); break; case pch::DECL_OBJC_INTERFACE: @@ -707,7 +707,7 @@ Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) { D = ObjCProtocolDecl::Create(*Context, 0, SourceLocation(), 0); break; case pch::DECL_OBJC_AT_DEFS_FIELD: - D = ObjCAtDefsFieldDecl::Create(*Context, 0, SourceLocation(), 0, + D = ObjCAtDefsFieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0); break; case pch::DECL_OBJC_CLASS: @@ -733,11 +733,11 @@ Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) { break; case pch::DECL_OBJC_PROPERTY_IMPL: D = ObjCPropertyImplDecl::Create(*Context, 0, SourceLocation(), - SourceLocation(), 0, + SourceLocation(), 0, ObjCPropertyImplDecl::Dynamic, 0); break; case pch::DECL_FIELD: - D = FieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, 0, + D = FieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, 0, false); break; case pch::DECL_VAR: @@ -750,7 +750,7 @@ Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) { break; case pch::DECL_PARM_VAR: - D = ParmVarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, + D = ParmVarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, VarDecl::None, 0); break; case pch::DECL_ORIGINAL_PARM_VAR: diff --git a/clang/lib/Frontend/PCHReaderStmt.cpp b/clang/lib/Frontend/PCHReaderStmt.cpp index dfcc794a5dc52823556d3aa918c935332c914f48..45e2bfb1794d68e4d5b45ce385734d58a135a333 100644 --- a/clang/lib/Frontend/PCHReaderStmt.cpp +++ b/clang/lib/Frontend/PCHReaderStmt.cpp @@ -106,7 +106,7 @@ namespace { unsigned VisitObjCMessageExpr(ObjCMessageExpr *E); unsigned VisitObjCSuperExpr(ObjCSuperExpr *E); unsigned VisitObjCIsaExpr(ObjCIsaExpr *E); - + unsigned VisitObjCForCollectionStmt(ObjCForCollectionStmt *); unsigned VisitObjCAtCatchStmt(ObjCAtCatchStmt *); unsigned VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *); @@ -132,7 +132,7 @@ unsigned PCHStmtReader::VisitNullStmt(NullStmt *S) { unsigned PCHStmtReader::VisitCompoundStmt(CompoundStmt *S) { VisitStmt(S); unsigned NumStmts = Record[Idx++]; - S->setStmts(*Reader.getContext(), + S->setStmts(*Reader.getContext(), StmtStack.data() + StmtStack.size() - NumStmts, NumStmts); S->setLBracLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); S->setRBracLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); @@ -195,7 +195,7 @@ unsigned PCHStmtReader::VisitSwitchStmt(SwitchStmt *S) { PrevSC->setNextSwitchCase(SC); else S->setSwitchCaseList(SC); - + // Retain this SwitchCase, since SwitchStmt::addSwitchCase() would // normally retain it (but we aren't calling addSwitchCase). SC->Retain(); @@ -298,8 +298,8 @@ unsigned PCHStmtReader::VisitAsmStmt(AsmStmt *S) { S->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); S->setVolatile(Record[Idx++]); S->setSimple(Record[Idx++]); - - unsigned StackIdx + + unsigned StackIdx = StmtStack.size() - (NumOutputs*2 + NumInputs*2 + NumClobbers + 1); S->setAsmString(cast_or_null(StmtStack[StackIdx++])); @@ -372,12 +372,12 @@ unsigned PCHStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) { unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) { VisitExpr(E); unsigned Len = Record[Idx++]; - assert(Record[Idx] == E->getNumConcatenated() && + assert(Record[Idx] == E->getNumConcatenated() && "Wrong number of concatenated tokens!"); ++Idx; E->setWide(Record[Idx++]); - // Read string data + // Read string data llvm::SmallVector Str(&Record[Idx], &Record[Idx] + Len); E->setStrData(*Reader.getContext(), Str.data(), Len); Idx += Len; @@ -536,7 +536,7 @@ unsigned PCHStmtReader::VisitInitListExpr(InitListExpr *E) { unsigned NumInits = Record[Idx++]; E->reserveInits(NumInits); for (unsigned I = 0; I != NumInits; ++I) - E->updateInit(I, + E->updateInit(I, cast(StmtStack[StmtStack.size() - NumInits - 1 + I])); E->setSyntacticForm(cast_or_null(StmtStack.back())); E->setLBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); @@ -563,11 +563,11 @@ unsigned PCHStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) { switch ((pch::DesignatorTypes)Record[Idx++]) { case pch::DESIG_FIELD_DECL: { FieldDecl *Field = cast(Reader.GetDecl(Record[Idx++])); - SourceLocation DotLoc + SourceLocation DotLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); - SourceLocation FieldLoc + SourceLocation FieldLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); - Designators.push_back(Designator(Field->getIdentifier(), DotLoc, + Designators.push_back(Designator(Field->getIdentifier(), DotLoc, FieldLoc)); Designators.back().setField(Field); break; @@ -575,14 +575,14 @@ unsigned PCHStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) { case pch::DESIG_FIELD_NAME: { const IdentifierInfo *Name = Reader.GetIdentifierInfo(Record, Idx); - SourceLocation DotLoc + SourceLocation DotLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); - SourceLocation FieldLoc + SourceLocation FieldLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); Designators.push_back(Designator(Name, DotLoc, FieldLoc)); break; } - + case pch::DESIG_ARRAY: { unsigned Index = Record[Idx++]; SourceLocation LBracketLoc @@ -669,7 +669,7 @@ unsigned PCHStmtReader::VisitGNUNullExpr(GNUNullExpr *E) { unsigned PCHStmtReader::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { VisitExpr(E); unsigned NumExprs = Record[Idx++]; - E->setExprs(*Reader.getContext(), + E->setExprs(*Reader.getContext(), (Expr **)&StmtStack[StmtStack.size() - NumExprs], NumExprs); E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); @@ -766,7 +766,7 @@ unsigned PCHStmtReader::VisitObjCMessageExpr(ObjCMessageExpr *E) { E->setRightLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setSelector(Reader.GetSelector(Record, Idx)); E->setMethodDecl(cast_or_null(Reader.GetDecl(Record[Idx++]))); - + E->setReceiver( cast_or_null(StmtStack[StmtStack.size() - E->getNumArgs() - 1])); if (!E->getReceiver()) { @@ -896,8 +896,8 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { Finished = true; break; - case pch::STMT_NULL_PTR: - S = 0; + case pch::STMT_NULL_PTR: + S = 0; break; case pch::STMT_NULL: @@ -935,7 +935,7 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::STMT_DO: S = new (Context) DoStmt(Empty); break; - + case pch::STMT_FOR: S = new (Context) ForStmt(Empty); break; @@ -943,7 +943,7 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::STMT_GOTO: S = new (Context) GotoStmt(Empty); break; - + case pch::STMT_INDIRECT_GOTO: S = new (Context) IndirectGotoStmt(Empty); break; @@ -971,25 +971,25 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::EXPR_PREDEFINED: S = new (Context) PredefinedExpr(Empty); break; - - case pch::EXPR_DECL_REF: - S = new (Context) DeclRefExpr(Empty); + + case pch::EXPR_DECL_REF: + S = new (Context) DeclRefExpr(Empty); break; - - case pch::EXPR_INTEGER_LITERAL: + + case pch::EXPR_INTEGER_LITERAL: S = new (Context) IntegerLiteral(Empty); break; - + case pch::EXPR_FLOATING_LITERAL: S = new (Context) FloatingLiteral(Empty); break; - + case pch::EXPR_IMAGINARY_LITERAL: S = new (Context) ImaginaryLiteral(Empty); break; case pch::EXPR_STRING_LITERAL: - S = StringLiteral::CreateEmpty(*Context, + S = StringLiteral::CreateEmpty(*Context, Record[PCHStmtReader::NumExprFields + 1]); break; @@ -1056,7 +1056,7 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::EXPR_DESIGNATED_INIT: S = DesignatedInitExpr::CreateEmpty(*Context, Record[PCHStmtReader::NumExprFields] - 1); - + break; case pch::EXPR_IMPLICIT_VALUE_INIT: @@ -1090,7 +1090,7 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::EXPR_SHUFFLE_VECTOR: S = new (Context) ShuffleVectorExpr(Empty); break; - + case pch::EXPR_BLOCK: S = new (Context) BlockExpr(Empty); break; @@ -1098,7 +1098,7 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::EXPR_BLOCK_DECL_REF: S = new (Context) BlockDeclRefExpr(Empty); break; - + case pch::EXPR_OBJC_STRING_LITERAL: S = new (Context) ObjCStringLiteral(Empty); break; @@ -1147,7 +1147,7 @@ Stmt *PCHReader::ReadStmt(llvm::BitstreamCursor &Cursor) { case pch::STMT_OBJC_AT_THROW: S = new (Context) ObjCAtThrowStmt(Empty); break; - + case pch::EXPR_CXX_OPERATOR_CALL: S = new (Context) CXXOperatorCallExpr(*Context, Empty); break; diff --git a/clang/lib/Frontend/PCHWriter.cpp b/clang/lib/Frontend/PCHWriter.cpp index 86a52fcf52c83d30ad18b7d2bcceca2be07c2c83..a6918e4c850aee00f74a8b472d4a562ff1b1f87b 100644 --- a/clang/lib/Frontend/PCHWriter.cpp +++ b/clang/lib/Frontend/PCHWriter.cpp @@ -13,7 +13,7 @@ #include "clang/Frontend/PCHWriter.h" #include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema -#include "../Sema/IdentifierResolver.h" // FIXME: move header +#include "../Sema/IdentifierResolver.h" // FIXME: move header #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclContextInternals.h" @@ -50,7 +50,7 @@ namespace { /// \brief Type code that corresponds to the record generated. pch::TypeCode Code; - PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record) + PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record) : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { } void VisitArrayType(const ArrayType *T); @@ -92,7 +92,7 @@ void PCHTypeWriter::VisitPointerType(const PointerType *T) { } void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { - Writer.AddTypeRef(T->getPointeeType(), Record); + Writer.AddTypeRef(T->getPointeeType(), Record); Code = pch::TYPE_BLOCK_POINTER; } @@ -107,8 +107,8 @@ void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { } void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { - Writer.AddTypeRef(T->getPointeeType(), Record); - Writer.AddTypeRef(QualType(T->getClass(), 0), Record); + Writer.AddTypeRef(T->getPointeeType(), Record); + Writer.AddTypeRef(QualType(T->getClass(), 0), Record); Code = pch::TYPE_MEMBER_POINTER; } @@ -211,7 +211,7 @@ void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) { void PCHTypeWriter::VisitTagType(const TagType *T) { Writer.AddDeclRef(T->getDecl(), Record); - assert(!T->isBeingDefined() && + assert(!T->isBeingDefined() && "Cannot serialize in the middle of a type definition"); } @@ -231,7 +231,7 @@ void PCHTypeWriter::VisitElaboratedType(const ElaboratedType *T) { Code = pch::TYPE_ELABORATED; } -void +void PCHTypeWriter::VisitTemplateSpecializationType( const TemplateSpecializationType *T) { // FIXME: Serialize this type (C++ only) @@ -254,7 +254,7 @@ void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { void PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { - Writer.AddTypeRef(T->getPointeeType(), Record); + Writer.AddTypeRef(T->getPointeeType(), Record); Record.push_back(T->getNumProtocols()); for (ObjCInterfaceType::qual_iterator I = T->qual_begin(), E = T->qual_end(); I != E; ++I) @@ -362,14 +362,14 @@ static void AddStmtsExprs(llvm::BitstreamWriter &Stream, RECORD(STMT_OBJC_AT_THROW); #undef RECORD } - + void PCHWriter::WriteBlockInfoBlock() { RecordData Record; Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3); - + #define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record) #define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record) - + // PCH Top-Level Block. BLOCK(PCH_BLOCK); RECORD(ORIGINAL_FILE_NAME); @@ -392,7 +392,7 @@ void PCHWriter::WriteBlockInfoBlock() { RECORD(STAT_CACHE); RECORD(EXT_VECTOR_DECLS); RECORD(COMMENT_RANGES); - + // SourceManager Block. BLOCK(SOURCE_MANAGER_BLOCK); RECORD(SM_SLOC_FILE_ENTRY); @@ -401,7 +401,7 @@ void PCHWriter::WriteBlockInfoBlock() { RECORD(SM_SLOC_INSTANTIATION_ENTRY); RECORD(SM_LINE_TABLE); RECORD(SM_HEADER_FILE_INFO); - + // Preprocessor Block. BLOCK(PREPROCESSOR_BLOCK); RECORD(PP_MACRO_OBJECT_LIKE); @@ -475,7 +475,7 @@ void PCHWriter::WriteBlockInfoBlock() { /// \brief Adjusts the given filename to only write out the portion of the /// filename that is not part of the system root directory. -/// +/// /// \param Filename the file name to adjust. /// /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and @@ -483,29 +483,29 @@ void PCHWriter::WriteBlockInfoBlock() { /// /// \returns either the original filename (if it needs no adjustment) or the /// adjusted filename (which points into the @p Filename parameter). -static const char * +static const char * adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) { assert(Filename && "No file name to adjust?"); - + if (!isysroot) return Filename; - + // Verify that the filename and the system root have the same prefix. unsigned Pos = 0; for (; Filename[Pos] && isysroot[Pos]; ++Pos) if (Filename[Pos] != isysroot[Pos]) return Filename; // Prefixes don't match. - + // We hit the end of the filename before we hit the end of the system root. if (!Filename[Pos]) return Filename; - + // If the file name has a '/' at the current position, skip over the '/'. // We distinguish sysroot-based includes from absolute includes by the // absence of '/' at the beginning of sysroot-based includes. if (Filename[Pos] == '/') ++Pos; - + return Filename + Pos; } @@ -524,7 +524,7 @@ void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) { MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev); - + RecordData Record; Record.push_back(pch::METADATA); Record.push_back(pch::VERSION_MAJOR); @@ -534,7 +534,7 @@ void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) { Record.push_back(isysroot != 0); const std::string &TripleStr = Target.getTriple().getTriple(); Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr); - + // Original file name SourceManager &SM = Context.getSourceManager(); if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { @@ -545,7 +545,7 @@ void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) { llvm::sys::Path MainFilePath(MainFile->getName()); std::string MainFileName; - + if (!MainFilePath.isAbsolute()) { llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory(); P.appendComponent(MainFilePath.str()); @@ -555,7 +555,7 @@ void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) { } const char *MainFileNameStr = MainFileName.c_str(); - MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, + MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, isysroot); RecordData Record; Record.push_back(pch::ORIGINAL_FILE_NAME); @@ -579,11 +579,11 @@ void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) { Record.push_back(LangOpts.CPlusPlus); // C++ Support Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords. - + Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled. Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled. Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled - + Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings Record.push_back(LangOpts.WritableStrings); // Allow writable strings Record.push_back(LangOpts.LaxVectorConversions); @@ -610,7 +610,7 @@ void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) { // may be ripped out at any time. Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined. - Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be + Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be // defined. Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as // opposed to __DYNAMIC__). @@ -641,15 +641,15 @@ class VISIBILITY_HIDDEN PCHStatCacheTrait { public: typedef const char * key_type; typedef key_type key_type_ref; - + typedef std::pair data_type; typedef const data_type& data_type_ref; static unsigned ComputeHash(const char *path) { return BernsteinHash(path); } - - std::pair + + std::pair EmitKeyDataLength(llvm::raw_ostream& Out, const char *path, data_type_ref Data) { unsigned StrLen = strlen(path); @@ -660,19 +660,19 @@ public: clang::io::Emit8(Out, DataLen); return std::make_pair(StrLen + 1, DataLen); } - + void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) { Out.write(path, KeyLen); } - + void EmitData(llvm::raw_ostream& Out, key_type_ref, data_type_ref Data, unsigned DataLen) { using namespace clang::io; uint64_t Start = Out.tell(); (void)Start; - + // Result of stat() Emit8(Out, Data.first? 1 : 0); - + if (Data.first == 0) { Emit32(Out, (uint32_t) Data.second.st_ino); Emit32(Out, (uint32_t) Data.second.st_dev); @@ -693,16 +693,16 @@ void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls, // stat() call. OnDiskChainedHashTableGenerator Generator; unsigned NumStatEntries = 0; - for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), + for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), StatEnd = StatCalls.end(); Stat != StatEnd; ++Stat, ++NumStatEntries) { const char *Filename = Stat->first(); Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); Generator.insert(Filename, Stat->second); } - + // Create the on-disk hash table in a buffer. - llvm::SmallString<4096> StatCacheData; + llvm::SmallString<4096> StatCacheData; uint32_t BucketOffset; { llvm::raw_svector_ostream Out(StatCacheData); @@ -821,16 +821,16 @@ void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, if (FilenameLen) Record.insert(Record.end(), Filename, Filename + FilenameLen); } - + // Emit the line entries for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); L != LEnd; ++L) { // Emit the file ID Record.push_back(L->first); - + // Emit the line entries Record.push_back(L->second.size()); - for (std::vector::iterator LE = L->second.begin(), + for (std::vector::iterator LE = L->second.begin(), LEEnd = L->second.end(); LE != LEEnd; ++LE) { Record.push_back(LE->FileOffset); @@ -844,9 +844,9 @@ void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, } // Write out entries for all of the header files we know about. - HeaderSearch &HS = PP.getHeaderSearchInfo(); + HeaderSearch &HS = PP.getHeaderSearchInfo(); Record.clear(); - for (HeaderSearch::header_file_iterator I = HS.header_file_begin(), + for (HeaderSearch::header_file_iterator I = HS.header_file_begin(), E = HS.header_file_end(); I != E; ++I) { Record.push_back(I->isImport); @@ -862,7 +862,7 @@ void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, std::vector SLocEntryOffsets; RecordData PreloadSLocs; SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1); - for (SourceManager::sloc_entry_iterator + for (SourceManager::sloc_entry_iterator SLoc = SourceMgr.sloc_entry_begin() + 1, SLocEnd = SourceMgr.sloc_entry_end(); SLoc != SLocEnd; ++SLoc) { @@ -892,7 +892,7 @@ void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, if (Content->Entry) { // The source location entry is a file. The blob associated // with this entry is the file name. - + // Turn the file name into an absolute path, if it isn't already. const char *Filename = Content->Entry->getName(); llvm::sys::Path FilePath(Filename, strlen(Filename)); @@ -903,7 +903,7 @@ void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, FilenameStr = P.str(); Filename = FilenameStr.c_str(); } - + Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); @@ -962,13 +962,13 @@ void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); - + Record.clear(); Record.push_back(pch::SOURCE_LOCATION_OFFSETS); Record.push_back(SLocEntryOffsets.size()); Record.push_back(SourceMgr.getNextOffset()); Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, - (const char *)&SLocEntryOffsets.front(), + (const char *)&SLocEntryOffsets.front(), SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0])); // Write the source location entry preloads array, telling the PCH @@ -995,12 +995,12 @@ void PCHWriter::WritePreprocessor(const Preprocessor &PP) { // Enter the preprocessor block. Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2); - + // If the PCH file contains __DATE__ or __TIME__ emit a warning about this. // FIXME: use diagnostics subsystem for localization etc. if (PP.SawDateOrTime()) fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); - + // Loop over all the macro definitions that are live at the end of the file, // emitting each to the PP section. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end(); @@ -1019,13 +1019,13 @@ void PCHWriter::WritePreprocessor(const Preprocessor &PP) { MacroOffsets[I->first] = Stream.GetCurrentBitNo(); Record.push_back(MI->getDefinitionLoc().getRawEncoding()); Record.push_back(MI->isUsed()); - + unsigned Code; if (MI->isObjectLike()) { Code = pch::PP_MACRO_OBJECT_LIKE; } else { Code = pch::PP_MACRO_FUNCTION_LIKE; - + Record.push_back(MI->isC99Varargs()); Record.push_back(MI->isGNUVarargs()); Record.push_back(MI->getNumArgs()); @@ -1042,19 +1042,19 @@ void PCHWriter::WritePreprocessor(const Preprocessor &PP) { // tokens in it because they are created by the parser, and thus can't be // in a macro definition. const Token &Tok = MI->getReplacementToken(TokNo); - + Record.push_back(Tok.getLocation().getRawEncoding()); Record.push_back(Tok.getLength()); // FIXME: When reading literal tokens, reconstruct the literal pointer if // it is needed. AddIdentifierRef(Tok.getIdentifierInfo(), Record); - + // FIXME: Should translate token kind to a stable encoding. Record.push_back(Tok.getKind()); // FIXME: Should translate token flags to a stable encoding. Record.push_back(Tok.getFlags()); - + Stream.EmitRecord(pch::PP_TOKEN, Record); Record.clear(); } @@ -1065,18 +1065,18 @@ void PCHWriter::WritePreprocessor(const Preprocessor &PP) { void PCHWriter::WriteComments(ASTContext &Context) { using namespace llvm; - + if (Context.Comments.empty()) return; - + BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev(); CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES)); CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev); - + RecordData Record; Record.push_back(pch::COMMENT_RANGES); - Stream.EmitRecordWithBlob(CommentCode, Record, + Stream.EmitRecordWithBlob(CommentCode, Record, (const char*)&Context.Comments[0], Context.Comments.size() * sizeof(SourceRange)); } @@ -1090,7 +1090,7 @@ void PCHWriter::WriteType(const Type *T) { pch::TypeID &ID = TypeIDs[T]; if (ID == 0) // we haven't seen this type before. ID = NextTypeID++; - + // Record the offset for this type. if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS) TypeOffsets.push_back(Stream.GetCurrentBitNo()); @@ -1100,7 +1100,7 @@ void PCHWriter::WriteType(const Type *T) { } RecordData Record; - + // Emit the type's representation. PCHTypeWriter W(*this, Record); switch (T->getTypeClass()) { @@ -1154,7 +1154,7 @@ void PCHWriter::WriteTypesBlock(ASTContext &Context) { /// /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the /// bistream, or 0 if no block was written. -uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context, +uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC) { if (DC->decls_empty()) return 0; @@ -1206,7 +1206,7 @@ uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context, AddDeclarationName(D->first, Record); DeclContext::lookup_result Result = D->second.getLookupResult(Context); Record.push_back(Result.second - Result.first); - for(; Result.first != Result.second; ++Result.first) + for (; Result.first != Result.second; ++Result.first) AddDeclRef(*Result.first, Record); } @@ -1230,12 +1230,12 @@ class VISIBILITY_HIDDEN PCHMethodPoolTrait { public: typedef Selector key_type; typedef key_type key_type_ref; - + typedef std::pair data_type; typedef const data_type& data_type_ref; explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { } - + static unsigned ComputeHash(Selector Sel) { unsigned N = Sel.getNumArgs(); if (N == 0) @@ -1246,27 +1246,27 @@ public: R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R); return R; } - - std::pair + + std::pair EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel, data_type_ref Methods) { unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); clang::io::Emit16(Out, KeyLen); unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts - for (const ObjCMethodList *Method = &Methods.first; Method; + for (const ObjCMethodList *Method = &Methods.first; Method; Method = Method->Next) if (Method->Method) DataLen += 4; - for (const ObjCMethodList *Method = &Methods.second; Method; + for (const ObjCMethodList *Method = &Methods.second; Method; Method = Method->Next) if (Method->Method) DataLen += 4; clang::io::Emit16(Out, DataLen); return std::make_pair(KeyLen, DataLen); } - + void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) { - uint64_t Start = Out.tell(); + uint64_t Start = Out.tell(); assert((Start >> 32) == 0 && "Selector key offset too large"); Writer.SetSelectorOffset(Sel, Start); unsigned N = Sel.getNumArgs(); @@ -1274,32 +1274,32 @@ public: if (N == 0) N = 1; for (unsigned I = 0; I != N; ++I) - clang::io::Emit32(Out, + clang::io::Emit32(Out, Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); } - + void EmitData(llvm::raw_ostream& Out, key_type_ref, data_type_ref Methods, unsigned DataLen) { uint64_t Start = Out.tell(); (void)Start; unsigned NumInstanceMethods = 0; - for (const ObjCMethodList *Method = &Methods.first; Method; + for (const ObjCMethodList *Method = &Methods.first; Method; Method = Method->Next) if (Method->Method) ++NumInstanceMethods; unsigned NumFactoryMethods = 0; - for (const ObjCMethodList *Method = &Methods.second; Method; + for (const ObjCMethodList *Method = &Methods.second; Method; Method = Method->Next) if (Method->Method) ++NumFactoryMethods; clang::io::Emit16(Out, NumInstanceMethods); clang::io::Emit16(Out, NumFactoryMethods); - for (const ObjCMethodList *Method = &Methods.first; Method; + for (const ObjCMethodList *Method = &Methods.first; Method; Method = Method->Next) if (Method->Method) clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); - for (const ObjCMethodList *Method = &Methods.second; Method; + for (const ObjCMethodList *Method = &Methods.second; Method; Method = Method->Next) if (Method->Method) clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); @@ -1321,13 +1321,13 @@ void PCHWriter::WriteMethodPool(Sema &SemaRef) { bool Empty = true; { OnDiskChainedHashTableGenerator Generator; - + // Create the on-disk hash table representation. Start by // iterating through the instance method pool. PCHMethodPoolTrait::key_type Key; unsigned NumSelectorsInMethodPool = 0; for (llvm::DenseMap::iterator - Instance = SemaRef.InstanceMethodPool.begin(), + Instance = SemaRef.InstanceMethodPool.begin(), InstanceEnd = SemaRef.InstanceMethodPool.end(); Instance != InstanceEnd; ++Instance) { // Check whether there is a factory method with the same @@ -1337,7 +1337,7 @@ void PCHWriter::WriteMethodPool(Sema &SemaRef) { if (Factory == SemaRef.FactoryMethodPool.end()) Generator.insert(Instance->first, - std::make_pair(Instance->second, + std::make_pair(Instance->second, ObjCMethodList())); else Generator.insert(Instance->first, @@ -1350,7 +1350,7 @@ void PCHWriter::WriteMethodPool(Sema &SemaRef) { // Now iterate through the factory method pool, to pick up any // selectors that weren't already in the instance method pool. for (llvm::DenseMap::iterator - Factory = SemaRef.FactoryMethodPool.begin(), + Factory = SemaRef.FactoryMethodPool.begin(), FactoryEnd = SemaRef.FactoryMethodPool.end(); Factory != FactoryEnd; ++Factory) { // Check whether there is an instance method with the same @@ -1371,7 +1371,7 @@ void PCHWriter::WriteMethodPool(Sema &SemaRef) { return; // Create the on-disk hash table in a buffer. - llvm::SmallString<4096> MethodPool; + llvm::SmallString<4096> MethodPool; uint32_t BucketOffset; SelectorOffsets.resize(SelVector.size()); { @@ -1444,25 +1444,25 @@ class VISIBILITY_HIDDEN PCHIdentifierTableTrait { public: typedef const IdentifierInfo* key_type; typedef key_type key_type_ref; - + typedef pch::IdentID data_type; typedef data_type data_type_ref; - - PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP) + + PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP) : Writer(Writer), PP(PP) { } static unsigned ComputeHash(const IdentifierInfo* II) { return clang::BernsteinHash(II->getName()); } - - std::pair - EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II, + + std::pair + EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II, pch::IdentID ID) { unsigned KeyLen = strlen(II->getName()) + 1; unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 if (isInterestingIdentifier(II)) { DataLen += 2; // 2 bytes for builtin ID, flags - if (II->hasMacroDefinition() && + if (II->hasMacroDefinition() && !PP.getMacroInfo(const_cast(II))->isBuiltinMacro()) DataLen += 4; for (IdentifierResolver::iterator D = IdentifierResolver::begin(II), @@ -1477,16 +1477,16 @@ public: clang::io::Emit16(Out, KeyLen); return std::make_pair(KeyLen, DataLen); } - - void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II, + + void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II, unsigned KeyLen) { // Record the location of the key data. This is used when generating // the mapping from persistent IDs to strings. Writer.SetIdentifierOffset(II, Out.tell()); Out.write(II->getName(), KeyLen); } - - void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II, + + void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II, pch::IdentID ID, unsigned) { if (!isInterestingIdentifier(II)) { clang::io::Emit32(Out, ID << 1); @@ -1495,8 +1495,8 @@ public: clang::io::Emit32(Out, (ID << 1) | 0x01); uint32_t Bits = 0; - bool hasMacroDefinition = - II->hasMacroDefinition() && + bool hasMacroDefinition = + II->hasMacroDefinition() && !PP.getMacroInfo(const_cast(II))->isBuiltinMacro(); Bits = (uint32_t)II->getObjCOrBuiltinID(); Bits = (Bits << 1) | hasMacroDefinition; @@ -1514,7 +1514,7 @@ public: // "stat"), but IdentifierResolver::AddDeclToIdentifierChain() // adds declarations to the end of the list (so we need to see the // struct "status" before the function "status"). - llvm::SmallVector Decls(IdentifierResolver::begin(II), + llvm::SmallVector Decls(IdentifierResolver::begin(II), IdentifierResolver::end()); for (llvm::SmallVector::reverse_iterator D = Decls.rbegin(), DEnd = Decls.rend(); @@ -1536,7 +1536,7 @@ void PCHWriter::WriteIdentifierTable(Preprocessor &PP) { // strings. { OnDiskChainedHashTableGenerator Generator; - + // Look for any identifiers that were named while processing the // headers, but are otherwise not needed. We add these to the hash // table to enable checking of the predefines buffer in the case @@ -1557,7 +1557,7 @@ void PCHWriter::WriteIdentifierTable(Preprocessor &PP) { } // Create the on-disk hash table in a buffer. - llvm::SmallString<4096> IdentifierTable; + llvm::SmallString<4096> IdentifierTable; uint32_t BucketOffset; { PCHIdentifierTableTrait Trait(*this, PP); @@ -1617,7 +1617,7 @@ void PCHWriter::WriteAttributeRecord(const Attr *Attr) { case Attr::AlwaysInline: break; - + case Attr::AnalyzerNoReturn: break; @@ -1676,7 +1676,7 @@ void PCHWriter::WriteAttributeRecord(const Attr *Attr) { Record.push_back(Sentinel->getNullPos()); break; } - + case Attr::GNUInline: case Attr::IBOutletKind: case Attr::Malloc: @@ -1706,14 +1706,14 @@ void PCHWriter::WriteAttributeRecord(const Attr *Attr) { case Attr::Packed: break; - + case Attr::Pure: break; case Attr::Regparm: Record.push_back(cast(Attr)->getNumParams()); break; - + case Attr::ReqdWorkGroupSize: Record.push_back(cast(Attr)->getXDim()); Record.push_back(cast(Attr)->getYDim()); @@ -1733,7 +1733,7 @@ void PCHWriter::WriteAttributeRecord(const Attr *Attr) { case Attr::Visibility: // FIXME: stable encoding - Record.push_back(cast(Attr)->getVisibility()); + Record.push_back(cast(Attr)->getVisibility()); break; case Attr::WarnUnusedResult: @@ -1765,8 +1765,8 @@ void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { SelectorOffsets[ID - 1] = Offset; } -PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream) - : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS), +PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream) + : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS), NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), NumVisibleDeclContexts(0) { } @@ -1782,7 +1782,7 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, Stream.Emit((unsigned)'P', 8); Stream.Emit((unsigned)'C', 8); Stream.Emit((unsigned)'H', 8); - + WriteBlockInfoBlock(); // The translation unit is the first declaration we'll emit. @@ -1816,7 +1816,7 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, RecordData LocallyScopedExternalDecls; // FIXME: This is filling in the PCH file in densemap order which is // nondeterminstic! - for (llvm::DenseMap::iterator + for (llvm::DenseMap::iterator TD = SemaRef.LocallyScopedExternalDecls.begin(), TDEnd = SemaRef.LocallyScopedExternalDecls.end(); TD != TDEnd; ++TD) @@ -1836,10 +1836,10 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, WriteStatCache(*StatCalls, isysroot); WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); WritePreprocessor(PP); - WriteComments(Context); + WriteComments(Context); // Write the record of special types. Record.clear(); - + AddTypeRef(Context.getBuiltinVaListType(), Record); AddTypeRef(Context.getObjCIdType(), Record); AddTypeRef(Context.getObjCSelType(), Record); @@ -1853,7 +1853,7 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, AddTypeRef(Context.ObjCIdRedefinitionType, Record); AddTypeRef(Context.ObjCClassRedefinitionType, Record); Stream.EmitRecord(pch::SPECIAL_TYPES, Record); - + // Keep writing types and declarations until all types and // declarations have been written. do { @@ -1876,9 +1876,9 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, Record.push_back(pch::TYPE_OFFSET); Record.push_back(TypeOffsets.size()); Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, - (const char *)&TypeOffsets.front(), + (const char *)&TypeOffsets.front(), TypeOffsets.size() * sizeof(TypeOffsets[0])); - + // Write the declaration offsets array Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET)); @@ -1889,7 +1889,7 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, Record.push_back(pch::DECL_OFFSET); Record.push_back(DeclOffsets.size()); Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, - (const char *)&DeclOffsets.front(), + (const char *)&DeclOffsets.front(), DeclOffsets.size() * sizeof(DeclOffsets[0])); // Write the record containing external, unnamed definitions. @@ -1902,13 +1902,13 @@ void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls, // Write the record containing locally-scoped external definitions. if (!LocallyScopedExternalDecls.empty()) - Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS, + Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS, LocallyScopedExternalDecls); // Write the record containing ext_vector type names. if (!ExtVectorDecls.empty()) Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls); - + // Some simple statistics Record.clear(); Record.push_back(NumStatements); @@ -2032,7 +2032,7 @@ void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) { } pch::DeclID &ID = DeclIDs[D]; - if (ID == 0) { + if (ID == 0) { // We haven't seen this declaration before. Give it a new ID and // enqueue it in the list of declarations to emit. ID = DeclIDs.size(); diff --git a/clang/lib/Frontend/PCHWriterDecl.cpp b/clang/lib/Frontend/PCHWriterDecl.cpp index eed888382aca37d5467b649579e8f6e7aa306005..7a15abf0a01c6074e7ce60ff51685a232c94a193 100644 --- a/clang/lib/Frontend/PCHWriterDecl.cpp +++ b/clang/lib/Frontend/PCHWriterDecl.cpp @@ -35,8 +35,8 @@ namespace { pch::DeclCode Code; unsigned AbbrevToUse; - PCHDeclWriter(PCHWriter &Writer, ASTContext &Context, - PCHWriter::RecordData &Record) + PCHDeclWriter(PCHWriter &Writer, ASTContext &Context, + PCHWriter::RecordData &Record) : Writer(Writer), Context(Context), Record(Record) { } @@ -59,7 +59,7 @@ namespace { void VisitOriginalParmVarDecl(OriginalParmVarDecl *D); void VisitFileScopeAsmDecl(FileScopeAsmDecl *D); void VisitBlockDecl(BlockDecl *D); - void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset, + void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset, uint64_t VisibleOffset); void VisitObjCMethodDecl(ObjCMethodDecl *D); void VisitObjCContainerDecl(ObjCContainerDecl *D); @@ -161,9 +161,9 @@ public: #define ABSTRACT_TYPELOC(CLASS) #define TYPELOC(CLASS, PARENT, TYPE) \ - void Visit##CLASS(CLASS TyLoc); + void Visit##CLASS(CLASS TyLoc); #include "clang/AST/TypeLocNodes.def" - + void VisitTypeLoc(TypeLoc TyLoc) { assert(0 && "A type loc wrapper was not handled!"); } @@ -210,7 +210,7 @@ void PCHDeclWriter::VisitDeclaratorDecl(DeclaratorDecl *D) { Writer.AddTypeRef(QualType(), Record); return; } - + Writer.AddTypeRef(DInfo->getTypeLoc().getSourceType(), Record); TypeLocWriter TLW(Writer, Record); for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) @@ -243,7 +243,7 @@ void PCHDeclWriter::VisitFunctionDecl(FunctionDecl *D) { void PCHDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) { VisitNamedDecl(D); // FIXME: convert to LazyStmtPtr? - // Unlike C/C++, method bodies will never be in header files. + // Unlike C/C++, method bodies will never be in header files. Record.push_back(D->getBody() != 0); if (D->getBody() != 0) { Writer.AddStmt(D->getBody()); @@ -254,13 +254,13 @@ void PCHDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) { Record.push_back(D->isVariadic()); Record.push_back(D->isSynthesized()); // FIXME: stable encoding for @required/@optional - Record.push_back(D->getImplementationControl()); + Record.push_back(D->getImplementationControl()); // FIXME: stable encoding for in/out/inout/bycopy/byref/oneway - Record.push_back(D->getObjCDeclQualifier()); + Record.push_back(D->getObjCDeclQualifier()); Writer.AddTypeRef(D->getResultType(), Record); Writer.AddSourceLocation(D->getLocEnd(), Record); Record.push_back(D->param_size()); - for (ObjCMethodDecl::param_iterator P = D->param_begin(), + for (ObjCMethodDecl::param_iterator P = D->param_begin(), PEnd = D->param_end(); P != PEnd; ++P) Writer.AddDeclRef(*P, Record); Code = pch::DECL_OBJC_METHOD; @@ -277,12 +277,12 @@ void PCHDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record); Writer.AddDeclRef(D->getSuperClass(), Record); Record.push_back(D->protocol_size()); - for (ObjCInterfaceDecl::protocol_iterator P = D->protocol_begin(), + for (ObjCInterfaceDecl::protocol_iterator P = D->protocol_begin(), PEnd = D->protocol_end(); P != PEnd; ++P) Writer.AddDeclRef(*P, Record); Record.push_back(D->ivar_size()); - for (ObjCInterfaceDecl::ivar_iterator I = D->ivar_begin(), + for (ObjCInterfaceDecl::ivar_iterator I = D->ivar_begin(), IEnd = D->ivar_end(); I != IEnd; ++I) Writer.AddDeclRef(*I, Record); Writer.AddDeclRef(D->getCategoryList(), Record); @@ -297,7 +297,7 @@ void PCHDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { void PCHDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) { VisitFieldDecl(D); // FIXME: stable encoding for @public/@private/@protected/@package - Record.push_back(D->getAccessControl()); + Record.push_back(D->getAccessControl()); Code = pch::DECL_OBJC_IVAR; } @@ -306,7 +306,7 @@ void PCHDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { Record.push_back(D->isForwardDecl()); Writer.AddSourceLocation(D->getLocEnd(), Record); Record.push_back(D->protocol_size()); - for (ObjCProtocolDecl::protocol_iterator + for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I) Writer.AddDeclRef(*I, Record); Code = pch::DECL_OBJC_PROTOCOL; @@ -328,7 +328,7 @@ void PCHDeclWriter::VisitObjCClassDecl(ObjCClassDecl *D) { void PCHDeclWriter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { VisitDecl(D); Record.push_back(D->protocol_size()); - for (ObjCProtocolDecl::protocol_iterator + for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I) Writer.AddDeclRef(*I, Record); Code = pch::DECL_OBJC_FORWARD_PROTOCOL; @@ -338,7 +338,7 @@ void PCHDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { VisitObjCContainerDecl(D); Writer.AddDeclRef(D->getClassInterface(), Record); Record.push_back(D->protocol_size()); - for (ObjCProtocolDecl::protocol_iterator + for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I) Writer.AddDeclRef(*I, Record); Writer.AddDeclRef(D->getNextClassCategory(), Record); @@ -424,8 +424,8 @@ void PCHDeclWriter::VisitParmVarDecl(ParmVarDecl *D) { VisitVarDecl(D); Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding Code = pch::DECL_PARM_VAR; - - + + // If the assumptions about the DECL_PARM_VAR abbrev are true, use it. Here // we dynamically check for the properties that we optimize for, but don't // know are true of all PARM_VAR_DECLs. @@ -483,7 +483,7 @@ void PCHDeclWriter::VisitBlockDecl(BlockDecl *D) { /// that there are no declarations visible from this context. Note /// that this value will not be emitted for non-primary declaration /// contexts. -void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset, +void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset, uint64_t VisibleOffset) { Record.push_back(LexicalOffset); Record.push_back(VisibleOffset); @@ -509,7 +509,7 @@ void PCHWriter::WriteDeclsBlockAbbrevs() { Abv->Add(BitCodeAbbrevOp(0)); // isImplicit Abv->Add(BitCodeAbbrevOp(0)); // isUsed Abv->Add(BitCodeAbbrevOp(AS_none)); // C++ AccessSpecifier - + // NamedDecl Abv->Add(BitCodeAbbrevOp(0)); // NameKind = Identifier Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name @@ -526,7 +526,7 @@ void PCHWriter::WriteDeclsBlockAbbrevs() { Abv->Add(BitCodeAbbrevOp(0)); // HasInit // ParmVarDecl Abv->Add(BitCodeAbbrevOp(0)); // ObjCDeclQualifier - + ParmVarDeclAbbrev = Stream.EmitAbbrev(Abv); } @@ -537,7 +537,7 @@ void PCHWriter::WriteDeclsBlock(ASTContext &Context) { // Output the abbreviations that we will use in this block. WriteDeclsBlockAbbrevs(); - + // Emit all of the declarations. RecordData Record; PCHDeclWriter W(*this, Context, Record); @@ -588,14 +588,14 @@ void PCHWriter::WriteDeclsBlock(ASTContext &Context) { exit(-1); } Stream.EmitRecord(W.Code, Record, W.AbbrevToUse); - + // If the declaration had any attributes, write them now. if (D->hasAttrs()) WriteAttributeRecord(D->getAttrs()); // Flush any expressions that were written as part of this declaration. FlushStmts(); - + // Note external declarations so that we can add them to a record // in the PCH file later. if (isa(D)) diff --git a/clang/lib/Frontend/PCHWriterStmt.cpp b/clang/lib/Frontend/PCHWriterStmt.cpp index 1f81529135df330384618cd1c3575062e282675d..a34c9923fc771755c8a0d286a723104d692dd627 100644 --- a/clang/lib/Frontend/PCHWriterStmt.cpp +++ b/clang/lib/Frontend/PCHWriterStmt.cpp @@ -86,7 +86,7 @@ namespace { void VisitShuffleVectorExpr(ShuffleVectorExpr *E); void VisitBlockExpr(BlockExpr *E); void VisitBlockDeclRefExpr(BlockDeclRefExpr *E); - + // Objective-C Expressions void VisitObjCStringLiteral(ObjCStringLiteral *E); void VisitObjCEncodeExpr(ObjCEncodeExpr *E); @@ -99,8 +99,8 @@ namespace { void VisitObjCMessageExpr(ObjCMessageExpr *E); void VisitObjCSuperExpr(ObjCSuperExpr *E); void VisitObjCIsaExpr(ObjCIsaExpr *E); - - // Objective-C Statements + + // Objective-C Statements void VisitObjCForCollectionStmt(ObjCForCollectionStmt *); void VisitObjCAtCatchStmt(ObjCAtCatchStmt *); void VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *); @@ -108,12 +108,12 @@ namespace { void VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *); void VisitObjCAtThrowStmt(ObjCAtThrowStmt *); - // C++ Statements + // C++ Statements void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); }; } -void PCHStmtWriter::VisitStmt(Stmt *S) { +void PCHStmtWriter::VisitStmt(Stmt *S) { } void PCHStmtWriter::VisitNullStmt(NullStmt *S) { @@ -181,7 +181,7 @@ void PCHStmtWriter::VisitSwitchStmt(SwitchStmt *S) { Writer.WriteSubStmt(S->getCond()); Writer.WriteSubStmt(S->getBody()); Writer.AddSourceLocation(S->getSwitchLoc(), Record); - for (SwitchCase *SC = S->getSwitchCaseList(); SC; + for (SwitchCase *SC = S->getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) Record.push_back(Writer.getSwitchCaseID(SC)); Code = pch::STMT_SWITCH; @@ -345,7 +345,7 @@ void PCHStmtWriter::VisitStringLiteral(StringLiteral *E) { // StringLiteral. However, we can't do so now because we have no // provision for coping with abbreviations when we're jumping around // the PCH file during deserialization. - Record.insert(Record.end(), + Record.insert(Record.end(), E->getStrData(), E->getStrData() + E->getByteLength()); for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I) Writer.AddSourceLocation(E->getStrTokenLoc(I), Record); @@ -376,7 +376,7 @@ void PCHStmtWriter::VisitUnaryOperator(UnaryOperator *E) { Code = pch::EXPR_UNARY_OPERATOR; } -void PCHStmtWriter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { +void PCHStmtWriter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { VisitExpr(E); Record.push_back(E->isSizeOf()); if (E->isArgumentType()) @@ -635,7 +635,7 @@ void PCHStmtWriter::VisitObjCStringLiteral(ObjCStringLiteral *E) { Code = pch::EXPR_OBJC_STRING_LITERAL; } -void PCHStmtWriter::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { +void PCHStmtWriter::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { VisitExpr(E); Writer.AddTypeRef(E->getEncodedType(), Record); Writer.AddSourceLocation(E->getAtLoc(), Record); @@ -682,7 +682,7 @@ void PCHStmtWriter::VisitObjCImplicitSetterGetterRefExpr( VisitExpr(E); Writer.AddDeclRef(E->getGetterMethod(), Record); Writer.AddDeclRef(E->getSetterMethod(), Record); - + // NOTE: InterfaceDecl and Base are mutually exclusive. Writer.AddDeclRef(E->getInterfaceDecl(), Record); Writer.WriteSubStmt(E->getBase()); @@ -779,7 +779,7 @@ void PCHStmtWriter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { //===----------------------------------------------------------------------===// unsigned PCHWriter::RecordSwitchCaseID(SwitchCase *S) { - assert(SwitchCaseIDs.find(S) == SwitchCaseIDs.end() && + assert(SwitchCaseIDs.find(S) == SwitchCaseIDs.end() && "SwitchCase recorded twice"); unsigned NextID = SwitchCaseIDs.size(); SwitchCaseIDs[S] = NextID; @@ -787,7 +787,7 @@ unsigned PCHWriter::RecordSwitchCaseID(SwitchCase *S) { } unsigned PCHWriter::getSwitchCaseID(SwitchCase *S) { - assert(SwitchCaseIDs.find(S) != SwitchCaseIDs.end() && + assert(SwitchCaseIDs.find(S) != SwitchCaseIDs.end() && "SwitchCase hasn't been seen yet"); return SwitchCaseIDs[S]; } @@ -798,7 +798,7 @@ unsigned PCHWriter::GetLabelID(LabelStmt *S) { std::map::iterator Pos = LabelIDs.find(S); if (Pos != LabelIDs.end()) return Pos->second; - + unsigned NextID = LabelIDs.size(); LabelIDs[S] = NextID; return NextID; @@ -810,17 +810,17 @@ void PCHWriter::WriteSubStmt(Stmt *S) { RecordData Record; PCHStmtWriter Writer(*this, Record); ++NumStatements; - + if (!S) { Stream.EmitRecord(pch::STMT_NULL_PTR, Record); return; } - + Writer.Code = pch::STMT_NULL_PTR; Writer.Visit(S); - assert(Writer.Code != pch::STMT_NULL_PTR && + assert(Writer.Code != pch::STMT_NULL_PTR && "Unhandled expression writing PCH file"); - Stream.EmitRecord(Writer.Code, Record); + Stream.EmitRecord(Writer.Code, Record); } /// \brief Flush all of the statements that have been added to the @@ -828,31 +828,31 @@ void PCHWriter::WriteSubStmt(Stmt *S) { void PCHWriter::FlushStmts() { RecordData Record; PCHStmtWriter Writer(*this, Record); - + for (unsigned I = 0, N = StmtsToEmit.size(); I != N; ++I) { ++NumStatements; Stmt *S = StmtsToEmit[I]; - + if (!S) { Stream.EmitRecord(pch::STMT_NULL_PTR, Record); continue; } - + Writer.Code = pch::STMT_NULL_PTR; Writer.Visit(S); - assert(Writer.Code != pch::STMT_NULL_PTR && + assert(Writer.Code != pch::STMT_NULL_PTR && "Unhandled expression writing PCH file"); - Stream.EmitRecord(Writer.Code, Record); - - assert(N == StmtsToEmit.size() && + Stream.EmitRecord(Writer.Code, Record); + + assert(N == StmtsToEmit.size() && "Substatement writen via AddStmt rather than WriteSubStmt!"); - + // Note that we are at the end of a full expression. Any // expression records that follow this one are part of a different // expression. Record.clear(); Stream.EmitRecord(pch::STMT_STOP, Record); } - + StmtsToEmit.clear(); } diff --git a/clang/lib/Frontend/PlistDiagnostics.cpp b/clang/lib/Frontend/PlistDiagnostics.cpp index 26fc08019d1de1b63bac4f4836991db968f7bd11..a83dca0a5ffa98c2793509e58980c2f4de6d6843 100644 --- a/clang/lib/Frontend/PlistDiagnostics.cpp +++ b/clang/lib/Frontend/PlistDiagnostics.cpp @@ -45,19 +45,19 @@ namespace { PathDiagnosticClientFactory *pf); ~PlistDiagnostics(); void HandlePathDiagnostic(const PathDiagnostic* D); - + PathGenerationScheme getGenerationScheme() const; bool supportsLogicalOpControlFlow() const { return true; } bool supportsAllBlockEdges() const { return true; } virtual bool useVerboseDescription() const { return false; } - }; + }; } // end anonymous namespace PlistDiagnostics::PlistDiagnostics(const std::string& output, const LangOptions &LO, PathDiagnosticClientFactory *pf) : OutputFile(output), LangOpts(LO), PF(pf) { - + if (PF) SubPDC.reset(PF->createPathDiagnosticClient(&FilesMade)); } @@ -73,7 +73,7 @@ PathDiagnosticClient::PathGenerationScheme PlistDiagnostics::getGenerationScheme() const { if (const PathDiagnosticClient *PD = SubPDC.get()) return PD->getGenerationScheme(); - + return Extensive; } @@ -110,7 +110,7 @@ static void EmitLocation(llvm::raw_ostream& o, const SourceManager &SM, // Add in the length of the token, so that we cover multi-char tokens. unsigned offset = extend ? Lexer::MeasureTokenLength(Loc, SM, LangOpts) - 1 : 0; - + Indent(o, indent) << "\n"; Indent(o, indent) << " line" << Loc.getInstantiationLineNumber() << "\n"; @@ -133,7 +133,7 @@ static void EmitRange(llvm::raw_ostream& o, const SourceManager &SM, PathDiagnosticRange R, const FIDMap &FM, unsigned indent) { Indent(o, indent) << "\n"; - EmitLocation(o, SM, LangOpts, R.getBegin(), FM, indent+1); + EmitLocation(o, SM, LangOpts, R.getBegin(), FM, indent+1); EmitLocation(o, SM, LangOpts, R.getEnd(), FM, indent+1, !R.isPoint); Indent(o, indent) << "\n"; } @@ -162,12 +162,12 @@ static void ReportControlFlow(llvm::raw_ostream& o, const SourceManager &SM, const LangOptions &LangOpts, unsigned indent) { - + Indent(o, indent) << "\n"; ++indent; - + Indent(o, indent) << "kindcontrol\n"; - + // Emit edges. Indent(o, indent) << "edges\n"; ++indent; @@ -187,39 +187,39 @@ static void ReportControlFlow(llvm::raw_ostream& o, --indent; Indent(o, indent) << "\n"; --indent; - + // Output any helper text. const std::string& s = P.getString(); if (!s.empty()) { Indent(o, indent) << "alternate"; EmitString(o, s) << '\n'; } - + --indent; - Indent(o, indent) << "\n"; + Indent(o, indent) << "\n"; } -static void ReportEvent(llvm::raw_ostream& o, const PathDiagnosticPiece& P, +static void ReportEvent(llvm::raw_ostream& o, const PathDiagnosticPiece& P, const FIDMap& FM, const SourceManager &SM, const LangOptions &LangOpts, unsigned indent) { - + Indent(o, indent) << "\n"; ++indent; Indent(o, indent) << "kindevent\n"; - + // Output the location. FullSourceLoc L = P.getLocation().asLocation(); - + Indent(o, indent) << "location\n"; EmitLocation(o, SM, LangOpts, L, FM, indent); - + // Output the ranges (if any). PathDiagnosticPiece::range_iterator RI = P.ranges_begin(), RE = P.ranges_end(); - + if (RI != RE) { Indent(o, indent) << "ranges\n"; Indent(o, indent) << "\n"; @@ -229,13 +229,13 @@ static void ReportEvent(llvm::raw_ostream& o, const PathDiagnosticPiece& P, --indent; Indent(o, indent) << "\n"; } - + // Output the text. assert(!P.getString().empty()); Indent(o, indent) << "extended_message\n"; Indent(o, indent); EmitString(o, P.getString()) << '\n'; - + // Output the short text. // FIXME: Really use a short string. Indent(o, indent) << "message\n"; @@ -251,10 +251,10 @@ static void ReportMacro(llvm::raw_ostream& o, const FIDMap& FM, const SourceManager &SM, const LangOptions &LangOpts, unsigned indent) { - + for (PathDiagnosticMacroPiece::const_iterator I=P.begin(), E=P.end(); I!=E; ++I) { - + switch ((*I)->getKind()) { default: break; @@ -266,16 +266,16 @@ static void ReportMacro(llvm::raw_ostream& o, ReportMacro(o, cast(**I), FM, SM, LangOpts, indent); break; - } - } + } + } } -static void ReportDiag(llvm::raw_ostream& o, const PathDiagnosticPiece& P, +static void ReportDiag(llvm::raw_ostream& o, const PathDiagnosticPiece& P, const FIDMap& FM, const SourceManager &SM, const LangOptions &LangOpts) { unsigned indent = 4; - + switch (P.getKind()) { case PathDiagnosticPiece::ControlFlow: ReportControlFlow(o, cast(P), FM, SM, @@ -295,38 +295,38 @@ static void ReportDiag(llvm::raw_ostream& o, const PathDiagnosticPiece& P, void PlistDiagnostics::HandlePathDiagnostic(const PathDiagnostic* D) { if (!D) return; - + if (D->empty()) { delete D; return; } - + // We need to flatten the locations (convert Stmt* to locations) because // the referenced statements may be freed by the time the diagnostics // are emitted. - const_cast(D)->flattenLocations(); + const_cast(D)->flattenLocations(); BatchedDiags.push_back(D); } -PlistDiagnostics::~PlistDiagnostics() { +PlistDiagnostics::~PlistDiagnostics() { // Build up a set of FIDs that we use by scanning the locations and // ranges of the diagnostics. FIDMap FM; llvm::SmallVector Fids; const SourceManager* SM = 0; - - if (!BatchedDiags.empty()) + + if (!BatchedDiags.empty()) SM = &(*BatchedDiags.begin())->begin()->getLocation().getManager(); for (std::vector::iterator DI = BatchedDiags.begin(), DE = BatchedDiags.end(); DI != DE; ++DI) { - + const PathDiagnostic *D = *DI; - + for (PathDiagnostic::const_iterator I=D->begin(), E=D->end(); I!=E; ++I) { AddFID(FM, Fids, SM, I->getLocation().asLocation()); - + for (PathDiagnosticPiece::range_iterator RI=I->ranges_begin(), RE=I->ranges_end(); RI!=RE; ++RI) { AddFID(FM, Fids, SM, RI->getBegin()); @@ -342,84 +342,84 @@ PlistDiagnostics::~PlistDiagnostics() { llvm::errs() << "warning: could not creat file: " << OutputFile << '\n'; return; } - + // Write the plist header. o << "\n" "\n" "\n"; - + // Write the root object: a containing... // - "files", an mapping from FIDs to file names - // - "diagnostics", an containing the path diagnostics + // - "diagnostics", an containing the path diagnostics o << "\n" " files\n" " \n"; - + for (llvm::SmallVectorImpl::iterator I=Fids.begin(), E=Fids.end(); I!=E; ++I) { o << " "; EmitString(o, SM->getFileEntryForID(*I)->getName()) << '\n'; } - + o << " \n" " diagnostics\n" " \n"; - + for (std::vector::iterator DI=BatchedDiags.begin(), DE = BatchedDiags.end(); DI!=DE; ++DI) { - + o << " \n" " path\n"; - + const PathDiagnostic *D = *DI; // Create an owning smart pointer for 'D' just so that we auto-free it // when we exit this method. llvm::OwningPtr OwnedD(const_cast(D)); - + o << " \n"; for (PathDiagnostic::const_iterator I=D->begin(), E=D->end(); I != E; ++I) ReportDiag(o, *I, FM, *SM, LangOpts); - + o << " \n"; - - // Output the bug type and bug category. + + // Output the bug type and bug category. o << " description"; EmitString(o, D->getDescription()) << '\n'; o << " category"; EmitString(o, D->getCategory()) << '\n'; o << " type"; EmitString(o, D->getBugType()) << '\n'; - + // Output the location of the bug. o << " location\n"; EmitLocation(o, *SM, LangOpts, D->getLocation(), FM, 2); - + // Output the diagnostic to the sub-diagnostic client, if any. if (PF) { if (!SubPDC.get()) SubPDC.reset(PF->createPathDiagnosticClient(&FilesMade)); - + FilesMade.clear(); - SubPDC->HandlePathDiagnostic(OwnedD.take()); + SubPDC->HandlePathDiagnostic(OwnedD.take()); SubPDC.reset(0); - + if (!FilesMade.empty()) { o << " " << PF->getName() << "_files\n"; o << " \n"; for (size_t i = 0, n = FilesMade.size(); i < n ; ++i) o << " " << FilesMade[i] << "\n"; - o << " \n"; + o << " \n"; } } - + // Close up the entry. o << " \n"; } o << " \n"; - + // Finish. o << "\n"; } diff --git a/clang/lib/Frontend/PrintParserCallbacks.cpp b/clang/lib/Frontend/PrintParserCallbacks.cpp index 126cdd3fdd4d2377154cdf9171772bf6584611bf..b537025aec20fd8e85119d43009247a8bcdeaacf 100644 --- a/clang/lib/Frontend/PrintParserCallbacks.cpp +++ b/clang/lib/Frontend/PrintParserCallbacks.cpp @@ -39,7 +39,7 @@ namespace { Out << ""; } Out << "\n"; - + // Pass up to EmptyActions so that the symbol table is maintained right. return MinimalAction::ActOnDeclarator(S, D); } @@ -69,16 +69,16 @@ namespace { AttributeList *AttrList) { Out << __FUNCTION__ << "\n"; return MinimalAction::ActOnStartClassInterface(AtInterfaceLoc, - ClassName, ClassLoc, + ClassName, ClassLoc, SuperName, SuperLoc, ProtoRefs, NumProtocols, EndProtoLoc, AttrList); } - /// ActOnForwardClassDeclaration - - /// Scope will always be top level file scope. + /// ActOnForwardClassDeclaration - + /// Scope will always be top level file scope. Action::DeclPtrTy ActOnForwardClassDeclaration(SourceLocation AtClassLoc, - IdentifierInfo **IdentList, + IdentifierInfo **IdentList, unsigned NumElts) { Out << __FUNCTION__ << "\n"; return MinimalAction::ActOnForwardClassDeclaration(AtClassLoc, IdentList, @@ -101,13 +101,13 @@ namespace { Out << "\n"; return DeclPtrTy(); } - - /// AddInitializerToDecl - This action is called immediately after - /// ParseDeclarator (when an initializer is present). The code is factored + + /// AddInitializerToDecl - This action is called immediately after + /// ParseDeclarator (when an initializer is present). The code is factored /// this way to make sure we are able to handle the following: /// void func() { int xx = xx; } /// This allows ActOnDeclarator to register "xx" prior to parsing the - /// initializer. The declaration above should still result in a warning, + /// initializer. The declaration above should still result in a warning, /// since the reference to "xx" is uninitialized. virtual void AddInitializerToDecl(DeclPtrTy Dcl, ExprArg Init) { Out << __FUNCTION__ << "\n"; @@ -142,7 +142,7 @@ namespace { virtual void ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) { Out << __FUNCTION__ << "\n"; } - + /// ActOnFunctionDefBody - This is called when a function body has completed /// parsing. Decl is the DeclTy returned by ParseStartOfFunctionDef. virtual DeclPtrTy ActOnFinishFunctionBody(DeclPtrTy Decl, StmtArg Body) { @@ -155,14 +155,14 @@ namespace { Out << __FUNCTION__ << "\n"; return DeclPtrTy(); } - + /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with /// no declarator (e.g. "struct foo;") is parsed. virtual DeclPtrTy ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { Out << __FUNCTION__ << "\n"; return DeclPtrTy(); } - + /// ActOnLinkageSpec - Parsed a C++ linkage-specification that /// contained braces. Lang/StrSize contains the language string that /// was parsed at location Loc. Decls/NumDecls provides the @@ -170,12 +170,12 @@ namespace { virtual DeclPtrTy ActOnLinkageSpec(SourceLocation Loc, SourceLocation LBrace, SourceLocation RBrace, const char *Lang, - unsigned StrSize, + unsigned StrSize, DeclPtrTy *Decls, unsigned NumDecls) { Out << __FUNCTION__ << "\n"; return DeclPtrTy(); } - + /// ActOnLinkageSpec - Parsed a C++ linkage-specification without /// braces. Lang/StrSize contains the language string that was /// parsed at location Loc. D is the declaration parsed. @@ -183,16 +183,16 @@ namespace { unsigned StrSize, DeclPtrTy D) { return DeclPtrTy(); } - + //===------------------------------------------------------------------===// // Type Parsing Callbacks. //===------------------------------------------------------------------===// - + virtual TypeResult ActOnTypeName(Scope *S, Declarator &D) { Out << __FUNCTION__ << "\n"; return TypeResult(); } - + virtual DeclPtrTy ActOnTag(Scope *S, unsigned TagType, TagUseKind TUK, SourceLocation KWLoc, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, @@ -204,22 +204,22 @@ namespace { Out << __FUNCTION__ << "\n"; return DeclPtrTy(); } - + /// Act on @defs() element found when parsing a structure. ClassName is the - /// name of the referenced class. + /// name of the referenced class. virtual void ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, llvm::SmallVectorImpl &Decls) { Out << __FUNCTION__ << "\n"; } - virtual DeclPtrTy ActOnField(Scope *S, DeclPtrTy TagD, + virtual DeclPtrTy ActOnField(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, Declarator &D, ExprTy *BitfieldWidth) { Out << __FUNCTION__ << "\n"; return DeclPtrTy(); } - + virtual DeclPtrTy ActOnIvar(Scope *S, SourceLocation DeclStart, DeclPtrTy IntfDecl, Declarator &D, ExprTy *BitfieldWidth, @@ -227,14 +227,14 @@ namespace { Out << __FUNCTION__ << "\n"; return DeclPtrTy(); } - + virtual void ActOnFields(Scope* S, SourceLocation RecLoc, DeclPtrTy TagDecl, - DeclPtrTy *Fields, unsigned NumFields, + DeclPtrTy *Fields, unsigned NumFields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList) { Out << __FUNCTION__ << "\n"; } - + virtual DeclPtrTy ActOnEnumConstant(Scope *S, DeclPtrTy EnumDecl, DeclPtrTy LastEnumConstant, SourceLocation IdLoc,IdentifierInfo *Id, @@ -272,12 +272,12 @@ namespace { Out << __FUNCTION__ << "\n"; return StmtEmpty(); } - + virtual OwningStmtResult ActOnExprStmt(FullExprArg Expr) { Out << __FUNCTION__ << "\n"; return OwningStmtResult(*this, Expr->release()); } - + /// ActOnCaseStmt - Note that this handles the GNU 'case 1 ... 4' extension, /// which can specify an RHS value. virtual OwningStmtResult ActOnCaseStmt(SourceLocation CaseLoc, @@ -303,7 +303,7 @@ namespace { return StmtEmpty(); } - virtual OwningStmtResult ActOnIfStmt(SourceLocation IfLoc, + virtual OwningStmtResult ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, StmtArg ThenVal, SourceLocation ElseLoc, StmtArg ElseVal) { @@ -329,7 +329,7 @@ namespace { return StmtEmpty(); } virtual OwningStmtResult ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, - SourceLocation WhileLoc, + SourceLocation WhileLoc, SourceLocation LPLoc, ExprArg Cond, SourceLocation RPLoc){ Out << __FUNCTION__ << "\n"; @@ -490,12 +490,12 @@ namespace { return ExprEmpty(); } - virtual OwningExprResult ActOnCharacterConstant(const Token &) { + virtual OwningExprResult ActOnCharacterConstant(const Token &) { Out << __FUNCTION__ << "\n"; return ExprEmpty(); } - virtual OwningExprResult ActOnNumericConstant(const Token &) { + virtual OwningExprResult ActOnNumericConstant(const Token &) { Out << __FUNCTION__ << "\n"; return ExprEmpty(); } @@ -515,7 +515,7 @@ namespace { } // Postfix Expressions. - virtual OwningExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, + virtual OwningExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, ExprArg Input) { Out << __FUNCTION__ << "\n"; @@ -574,7 +574,7 @@ namespace { Out << __FUNCTION__ << "\n"; return ExprEmpty(); } - virtual OwningExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, + virtual OwningExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty, SourceLocation RParenLoc, ExprArg Op) { Out << __FUNCTION__ << "\n"; @@ -726,8 +726,7 @@ namespace { } virtual void ActOnStartDelayedCXXMethodDeclaration(Scope *S, - DeclPtrTy Method) - { + DeclPtrTy Method) { Out << __FUNCTION__ << "\n"; } diff --git a/clang/lib/Frontend/PrintPreprocessedOutput.cpp b/clang/lib/Frontend/PrintPreprocessedOutput.cpp index d63d9cbba989a15a7dd8735919a3c09fe6275ab0..492b31a0ec395a1c88ff0cb6351ca1a56fa1c783 100644 --- a/clang/lib/Frontend/PrintPreprocessedOutput.cpp +++ b/clang/lib/Frontend/PrintPreprocessedOutput.cpp @@ -32,12 +32,12 @@ using namespace clang; static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI, Preprocessor &PP, llvm::raw_ostream &OS) { OS << "#define " << II.getName(); - + if (MI.isFunctionLike()) { OS << '('; if (MI.arg_empty()) ; - else if (MI.getNumArgs() == 1) + else if (MI.getNumArgs() == 1) OS << (*MI.arg_begin())->getName(); else { MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end(); @@ -45,7 +45,7 @@ static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI, while (AI != E) OS << ',' << (*AI++)->getName(); } - + if (MI.isVariadic()) { if (!MI.arg_empty()) OS << ','; @@ -53,18 +53,18 @@ static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI, } OS << ')'; } - + // GCC always emits a space, even if the macro body is empty. However, do not // want to emit two spaces if the first token has a leading space. if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace()) OS << ' '; - + llvm::SmallVector SpellingBuffer; for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end(); I != E; ++I) { if (I->hasLeadingSpace()) OS << ' '; - + // Make sure we have enough space in the spelling buffer. if (I->getLength() < SpellingBuffer.size()) SpellingBuffer.resize(I->getLength()); @@ -105,14 +105,14 @@ public: FileType = SrcMgr::C_User; Initialized = false; } - + void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; } bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; } - + virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType); virtual void Ident(SourceLocation Loc, const std::string &str); - virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, + virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, const std::string &Str); @@ -122,12 +122,12 @@ public: return ConcatInfo.AvoidConcat(PrevTok, Tok); } void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0); - + void HandleNewlinesInToken(const char *TokStr, unsigned Len); - + /// MacroDefined - This hook is called whenever a macro definition is seen. void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI); - + }; } // end anonymous namespace @@ -143,7 +143,7 @@ void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo, OS << '#' << ' ' << LineNo << ' ' << '"'; OS.write(&CurFilename[0], CurFilename.size()); OS << '"'; - + if (ExtraLen) OS.write(Extra, ExtraLen); @@ -163,12 +163,12 @@ bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) { if (DisableLineMarkers) { if (LineNo == CurLine) return false; - + CurLine = LineNo; - + if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine) return true; - + OS << '\n'; EmittedTokensOnThisLine = false; EmittedMacroOnThisLine = false; @@ -188,9 +188,9 @@ bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) { } } else { WriteLineInfo(LineNo, 0, 0); - } + } - CurLine = LineNo; + CurLine = LineNo; return true; } @@ -210,12 +210,12 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, MoveToLine(IncludeLoc); } else if (Reason == PPCallbacks::SystemHeaderPragma) { MoveToLine(Loc); - + // TODO GCC emits the # directive for this directive on the line AFTER the // directive and emits a bunch of spaces that aren't needed. Emulate this // strange behavior. } - + Loc = SourceMgr.getInstantiationLoc(Loc); // FIXME: Should use presumed line #! CurLine = SourceMgr.getInstantiationLineNumber(Loc); @@ -239,8 +239,8 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, case PPCallbacks::ExitFile: WriteLineInfo(CurLine, " 2", 2); break; - case PPCallbacks::SystemHeaderPragma: - case PPCallbacks::RenameFile: + case PPCallbacks::SystemHeaderPragma: + case PPCallbacks::RenameFile: WriteLineInfo(CurLine); break; } @@ -250,7 +250,7 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, /// void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) { MoveToLine(Loc); - + OS.write("#ident ", strlen("#ident ")); OS.write(&S[0], S.size()); EmittedTokensOnThisLine = true; @@ -263,7 +263,7 @@ void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II, if (!DumpDefines || // Ignore __FILE__ etc. MI->isBuiltinMacro()) return; - + MoveToLine(MI->getDefinitionLoc()); PrintMacroDefinition(*II, *MI, PP, OS); EmittedMacroOnThisLine = true; @@ -271,14 +271,14 @@ void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II, void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc, - const IdentifierInfo *Kind, + const IdentifierInfo *Kind, const std::string &Str) { MoveToLine(Loc); OS << "#pragma comment(" << Kind->getName(); - + if (!Str.empty()) { OS << ", \""; - + for (unsigned i = 0, e = Str.size(); i != e; ++i) { unsigned char Char = Str[i]; if (isprint(Char) && Char != '\\' && Char != '"') @@ -291,7 +291,7 @@ void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc, } OS << '"'; } - + OS << ')'; EmittedTokensOnThisLine = true; } @@ -307,12 +307,12 @@ bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) { // newline characters. if (!MoveToLine(Tok.getLocation())) return false; - + // Print out space characters so that the first token on a line is // indented for easy reading. const SourceManager &SourceMgr = PP.getSourceManager(); unsigned ColNo = SourceMgr.getInstantiationColumnNumber(Tok.getLocation()); - + // This hack prevents stuff like: // #define HASH # // HASH define foo bar @@ -321,11 +321,11 @@ bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) { // -fpreprocessed mode. if (ColNo <= 1 && Tok.is(tok::hash)) OS << ' '; - + // Otherwise, indent the appropriate number of spaces. for (; ColNo > 1; --ColNo) OS << ' '; - + return true; } @@ -336,18 +336,18 @@ void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr, if (*TokStr != '\n' && *TokStr != '\r') continue; - + ++NumNewlines; - + // If we have \n\r or \r\n, skip both and count as one line. if (Len != 1 && (TokStr[1] == '\n' || TokStr[1] == '\r') && TokStr[0] != TokStr[1]) ++TokStr, --Len; } - + if (NumNewlines == 0) return; - + CurLine += NumNewlines; } @@ -356,7 +356,7 @@ namespace { struct UnknownPragmaHandler : public PragmaHandler { const char *Prefix; PrintPPOutputPPCallbacks *Callbacks; - + UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks) : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {} virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) { @@ -364,7 +364,7 @@ struct UnknownPragmaHandler : public PragmaHandler { // newline characters. Callbacks->MoveToLine(PragmaTok.getLocation()); Callbacks->OS.write(Prefix, strlen(Prefix)); - + // Read and print all of the pragma tokens. while (PragmaTok.isNot(tok::eom)) { if (PragmaTok.hasLeadingSpace()) @@ -385,11 +385,11 @@ static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, char Buffer[256]; Token PrevTok; while (1) { - + // If this token is at the start of a line, emit newlines if needed. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) { // done. - } else if (Tok.hasLeadingSpace() || + } else if (Tok.hasLeadingSpace() || // If we haven't emitted a token on this line yet, PrevTok isn't // useful to look at and no concatenation could happen anyway. (Callbacks->hasEmittedTokensOnThisLine() && @@ -397,7 +397,7 @@ static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, Callbacks->AvoidConcat(PrevTok, Tok))) { OS << ' '; } - + if (IdentifierInfo *II = Tok.getIdentifierInfo()) { OS.write(II->getName(), II->getLength()); } else if (Tok.isLiteral() && !Tok.needsCleaning() && @@ -407,24 +407,24 @@ static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, const char *TokPtr = Buffer; unsigned Len = PP.getSpelling(Tok, TokPtr); OS.write(TokPtr, Len); - + // Tokens that can contain embedded newlines need to adjust our current - // line number. + // line number. if (Tok.getKind() == tok::comment) Callbacks->HandleNewlinesInToken(TokPtr, Len); } else { std::string S = PP.getSpelling(Tok); OS.write(&S[0], S.size()); - + // Tokens that can contain embedded newlines need to adjust our current - // line number. + // line number. if (Tok.getKind() == tok::comment) Callbacks->HandleNewlinesInToken(&S[0], S.size()); } Callbacks->SetEmittedTokensOnThisLine(); - + if (Tok.is(tok::eof)) break; - + PrevTok = Tok; PP.Lex(Tok); } @@ -456,7 +456,7 @@ void clang::DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) { for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) { MacroInfo &MI = *MacrosByID[i].second; - // Ignore computed macros like __LINE__ and friends. + // Ignore computed macros like __LINE__ and friends. if (MI.isBuiltinMacro()) continue; PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS); diff --git a/clang/lib/Frontend/RewriteBlocks.cpp b/clang/lib/Frontend/RewriteBlocks.cpp index b927d18b3e2b7acb9d05b0506cb067796a0883d0..b29f9eac49dfd9839ed8a278b76a5123c5648c6f 100644 --- a/clang/lib/Frontend/RewriteBlocks.cpp +++ b/clang/lib/Frontend/RewriteBlocks.cpp @@ -43,28 +43,28 @@ class RewriteBlocks : public ASTConsumer { llvm::SmallVector Blocks; llvm::SmallVector BlockDeclRefs; llvm::DenseMap BlockCallExprs; - + // Block related declarations. llvm::SmallPtrSet BlockByCopyDecls; llvm::SmallPtrSet BlockByRefDecls; llvm::SmallPtrSet ImportedBlockDecls; llvm::DenseMap RewrittenBlockExprs; - + // The function/method we are rewriting. FunctionDecl *CurFunctionDef; ObjCMethodDecl *CurMethodDef; - + bool IsHeader; - + std::string Preamble; public: - RewriteBlocks(std::string inFile, Diagnostic &D, + RewriteBlocks(std::string inFile, Diagnostic &D, const LangOptions &LOpts); ~RewriteBlocks() { - // Get the buffer corresponding to MainFileID. + // Get the buffer corresponding to MainFileID. // If we haven't changed it, then we are done. - if (const RewriteBuffer *RewriteBuf = + if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { std::string S(RewriteBuf->begin(), RewriteBuf->end()); printf("%s\n", S.c_str()); @@ -72,7 +72,7 @@ public: printf("No changes\n"); } } - + void Initialize(ASTContext &context); void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen); @@ -86,51 +86,51 @@ public: } void HandleTopLevelSingleDecl(Decl *D); void HandleDeclInMainFile(Decl *D); - - // Top level + + // Top level Stmt *RewriteFunctionBody(Stmt *S); void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); - + // Block specific rewrite rules. std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0); - + void RewriteBlockCall(CallExpr *Exp); void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); - - std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, + + std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, const char *funcName, std::string Tag); - std::string SynthesizeBlockFunc(BlockExpr *CE, int i, + std::string SynthesizeBlockFunc(BlockExpr *CE, int i, const char *funcName, std::string Tag); - std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, + std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, bool hasCopyDisposeHelpers); std::string SynthesizeBlockCall(CallExpr *Exp); void SynthesizeBlockLiterals(SourceLocation FunLocStart, const char *FunName); - + void CollectBlockDeclRefInfo(BlockExpr *Exp); void GetBlockCallExprs(Stmt *S); void GetBlockDeclRefExprs(Stmt *S); - + // We avoid calling Type::isBlockPointerType(), since it operates on the // canonical type. We only care if the top-level type is a closure pointer. bool isBlockPointerType(QualType T) { return isa(T); } - + // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) return false; - + QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); - + if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || OCT == Context->getCanonicalType(Context->getObjCClassType())) return true; - + if (const PointerType *PT = OCT->getAs()) { - if (isa(PT->getPointeeType()) || + if (isa(PT->getPointeeType()) || PT->getPointeeType()->isObjCQualifiedIdType()) return true; } @@ -145,34 +145,34 @@ public: void RewriteFunctionProtoType(QualType funcType, NamedDecl *D); void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); void RewriteCastExpr(CastExpr *CE); - + bool PointerTypeTakesAnyBlockArguments(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); }; - + } static bool IsHeaderFile(const std::string &Filename) { std::string::size_type DotPos = Filename.rfind('.'); - + if (DotPos == std::string::npos) { // no file extension - return false; + return false; } - + std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); // C header: .h // C++ header: .hh or .H; return Ext == "h" || Ext == "hh" || Ext == "H"; -} +} RewriteBlocks::RewriteBlocks(std::string inFile, - Diagnostic &D, const LangOptions &LOpts) : + Diagnostic &D, const LangOptions &LOpts) : Diags(D), LangOpts(LOpts) { IsHeader = IsHeaderFile(inFile); CurFunctionDef = 0; CurMethodDef = 0; - RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, + RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, "rewriting failed"); } @@ -185,15 +185,15 @@ ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile, void RewriteBlocks::Initialize(ASTContext &context) { Context = &context; SM = &Context->getSourceManager(); - + // Get the ID and start/end of the main file. MainFileID = SM->getMainFileID(); const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); MainFileStart = MainBuf->getBufferStart(); MainFileEnd = MainBuf->getBufferEnd(); - + Rewrite.setSourceMgr(Context->getSourceManager(), LangOpts); - + if (IsHeader) Preamble = "#pragma once\n"; Preamble += "#ifndef BLOCK_IMPL\n"; @@ -208,7 +208,7 @@ void RewriteBlocks::Initialize(ASTContext &context) { Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n"; Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n"; Preamble += "};\n"; - if (LangOpts.Microsoft) + if (LangOpts.Microsoft) Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n"; else Preamble += "#define __OBJC_RW_EXTERN extern\n"; @@ -220,14 +220,13 @@ void RewriteBlocks::Initialize(ASTContext &context) { Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n"; Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n"; Preamble += "#endif\n"; - - InsertText(SM->getLocForStartOfFile(MainFileID), + + InsertText(SM->getLocForStartOfFile(MainFileID), Preamble.c_str(), Preamble.size()); } -void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData, - unsigned StrLen) -{ +void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData, + unsigned StrLen) { if (!Rewrite.InsertText(Loc, StrData, StrLen)) return; Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); @@ -243,14 +242,14 @@ void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength, void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { bool haveBlockPtrs = false; - for (ObjCMethodDecl::param_iterator I = Method->param_begin(), + for (ObjCMethodDecl::param_iterator I = Method->param_begin(), E = Method->param_end(); I != E; ++I) if (isBlockPointerType((*I)->getType())) haveBlockPtrs = true; - + if (!haveBlockPtrs) return; - + // Do a fuzzy rewrite. // We have 1 or more arguments that have closure pointers. SourceLocation Loc = Method->getLocStart(); @@ -260,7 +259,7 @@ void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { const char *methodPtr = startBuf; std::string Tag = "struct __block_impl *"; - + while (*methodPtr++ && (methodPtr != endBuf)) { switch (*methodPtr) { case ':': @@ -269,13 +268,13 @@ void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { const char *scanType = ++methodPtr; bool foundBlockPointer = false; unsigned parenCount = 1; - + while (parenCount) { switch (*scanType) { - case '(': - parenCount++; + case '(': + parenCount++; break; - case ')': + case ')': parenCount--; break; case '^': @@ -289,7 +288,7 @@ void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { Loc = Loc.getFileLocWithOffset(methodPtr-startBuf); assert((Loc.isValid()) && "Invalid Loc"); ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size()); - + // Advance startBuf. Since the underlying buffer has changed, // it's very important to advance startBuf (so we can correctly // compute a relative Loc the next time around). @@ -305,34 +304,34 @@ void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { } void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { - for (ObjCInterfaceDecl::instmeth_iterator - I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end(); + for (ObjCInterfaceDecl::instmeth_iterator + I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end(); I != E; ++I) RewriteMethodDecl(*I); - for (ObjCInterfaceDecl::classmeth_iterator + for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end(); I != E; ++I) RewriteMethodDecl(*I); } void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { - for (ObjCCategoryDecl::instmeth_iterator - I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end(); + for (ObjCCategoryDecl::instmeth_iterator + I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end(); I != E; ++I) RewriteMethodDecl(*I); - for (ObjCCategoryDecl::classmeth_iterator + for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end(); I != E; ++I) RewriteMethodDecl(*I); } void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { - for (ObjCProtocolDecl::instmeth_iterator - I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); + for (ObjCProtocolDecl::instmeth_iterator + I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); I != E; ++I) RewriteMethodDecl(*I); - for (ObjCProtocolDecl::classmeth_iterator - I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); + for (ObjCProtocolDecl::classmeth_iterator + I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); I != E; ++I) RewriteMethodDecl(*I); } @@ -347,10 +346,10 @@ void RewriteBlocks::HandleTopLevelSingleDecl(Decl *D) { // if we rewrote the #include/#import. SourceLocation Loc = D->getLocation(); Loc = SM->getInstantiationLoc(Loc); - + // If this is for a builtin, ignore it. if (Loc.isInvalid()) return; - + if (ObjCInterfaceDecl *MD = dyn_cast(D)) RewriteInterfaceDecl(MD); else if (ObjCCategoryDecl *CD = dyn_cast(D)) @@ -374,7 +373,7 @@ std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i, funcName + "_" + "block_func_" + utostr(i); BlockDecl *BD = CE->getBlockDecl(); - + if (isa(AFT)) { S += "()"; } else if (BD->param_empty()) { @@ -400,19 +399,19 @@ std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i, S += ')'; } S += " {\n"; - + // Create local declarations to avoid rewriting all closure decl ref exprs. // First, emit a declaration for all "by ref" decls. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); Context->getPointerType((*I)->getType()).getAsStringInternal(Name, Context->PrintingPolicy); S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; - } + } // Next, emit a declaration for all "by copy" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); @@ -420,7 +419,7 @@ std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i, // // void (^myImportedClosure)(void); // myImportedClosure = ^(void) { setGlobalInt(x + y); }; - // + // // void (^anotherClosure)(void); // anotherClosure = ^(void) { // myImportedClosure(); // import and invoke the closure @@ -445,13 +444,13 @@ std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, std::string Tag) { std::string StructRef = "struct " + Tag; std::string S = "static void __"; - + S += funcName; S += "_block_copy_" + utostr(i); S += "(" + StructRef; S += "*dst, " + StructRef; S += "*src) {"; - for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), + for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), E = ImportedBlockDecls.end(); I != E; ++I) { S += "_Block_copy_assign(&dst->"; S += (*I)->getNameAsString(); @@ -464,13 +463,13 @@ std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, S += "_block_dispose_" + utostr(i); S += "(" + StructRef; S += "*src) {"; - for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), + for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), E = ImportedBlockDecls.end(); I != E; ++I) { S += "_Block_destroy(src->"; S += (*I)->getNameAsString(); S += ");"; } - S += "}\n"; + S += "}\n"; return S; } @@ -478,20 +477,20 @@ std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, bool hasCopyDisposeHelpers) { std::string S = "struct " + Tag; std::string Constructor = " " + Tag; - + S += " {\n struct __block_impl impl;\n"; - + if (hasCopyDisposeHelpers) S += " void *copy;\n void *dispose;\n"; - + Constructor += "(void *fp"; - + if (hasCopyDisposeHelpers) Constructor += ", void *copyHelp, void *disposeHelp"; - + if (BlockDeclRefs.size()) { // Output all "by copy" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); @@ -500,7 +499,7 @@ std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; - // + // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure @@ -517,7 +516,7 @@ std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, S += FieldName + ";\n"; } // Output all "by ref" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); @@ -526,7 +525,7 @@ std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; - // + // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure @@ -549,12 +548,12 @@ std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, Constructor += ", int flags=0) {\n"; Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof("; Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n"; - + if (hasCopyDisposeHelpers) Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n"; - + // Initialize all "by copy" arguments. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); Constructor += " "; @@ -565,7 +564,7 @@ std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, Constructor += Name + ";\n"; } // Initialize all "by ref" arguments. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); Constructor += " "; @@ -599,21 +598,21 @@ void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart, CollectBlockDeclRefInfo(Blocks[i]); std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i); - - std::string CI = SynthesizeBlockImpl(Blocks[i], Tag, + + std::string CI = SynthesizeBlockImpl(Blocks[i], Tag, ImportedBlockDecls.size() > 0); InsertText(FunLocStart, CI.c_str(), CI.size()); std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag); - + InsertText(FunLocStart, CF.c_str(), CF.size()); if (ImportedBlockDecls.size()) { std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag); InsertText(FunLocStart, HF.c_str(), HF.size()); } - + BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByCopyDecls.clear(); @@ -627,7 +626,7 @@ void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart, void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); const char *FuncName = FD->getNameAsCString(); - + SynthesizeBlockLiterals(FunLocStart, FuncName); } @@ -638,7 +637,7 @@ void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { std::string::size_type loc = 0; while ((loc = FuncName.find(":", loc)) != std::string::npos) FuncName.replace(loc, 1, "_"); - + SynthesizeBlockLiterals(FunLocStart, FuncName.c_str()); } @@ -668,7 +667,7 @@ void RewriteBlocks::GetBlockCallExprs(Stmt *S) { else GetBlockCallExprs(*CI); } - + if (CallExpr *CE = dyn_cast(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { BlockCallExprs[dyn_cast(CE->getCallee())] = CE; @@ -681,7 +680,7 @@ std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) { // Navigate to relevant type information. const char *closureName = 0; const BlockPointerType *CPT = 0; - + if (const DeclRefExpr *DRE = dyn_cast(Exp->getCallee())) { closureName = DRE->getDecl()->getNameAsCString(); CPT = DRE->getType()->getAs(); @@ -699,20 +698,20 @@ std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) { assert(FT && "RewriteBlockClass: Bad type"); const FunctionProtoType *FTP = dyn_cast(FT); // FTP will be null for closures that don't take arguments. - + // Build a closure call - start with a paren expr to enforce precedence. std::string BlockCall = "("; - // Synthesize the cast. + // Synthesize the cast. BlockCall += "(" + Exp->getType().getAsString() + "(*)"; BlockCall += "(struct __block_impl *"; if (FTP) { - for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), + for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), E = FTP->arg_type_end(); I && (I != E); ++I) BlockCall += ", " + (*I).getAsString(); } BlockCall += "))"; // close the argument list and paren expression. - + // Invoke the closure. We need to cast it since the declaration type is // bogus (it's a function pointer type) BlockCall += "((struct __block_impl *)"; @@ -722,11 +721,11 @@ std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) { PrintingPolicy(LangOpts)); BlockCall += closureExprBuf.str(); BlockCall += ")->FuncPtr)"; - + // Add the arguments. BlockCall += "((struct __block_impl *)"; BlockCall += closureExprBuf.str(); - for (CallExpr::arg_iterator I = Exp->arg_begin(), + for (CallExpr::arg_iterator I = Exp->arg_begin(), E = Exp->arg_end(); I != E; ++I) { std::string syncExprBufS; llvm::raw_string_ostream Buf(syncExprBufS); @@ -738,11 +737,11 @@ std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) { void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) { std::string BlockCall = SynthesizeBlockCall(Exp); - + const char *startBuf = SM->getCharacterData(Exp->getLocStart()); const char *endBuf = SM->getCharacterData(Exp->getLocEnd()); - ReplaceText(Exp->getLocStart(), endBuf-startBuf, + ReplaceText(Exp->getLocStart(), endBuf-startBuf, BlockCall.c_str(), BlockCall.size()); } @@ -754,19 +753,19 @@ void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) { void RewriteBlocks::RewriteCastExpr(CastExpr *CE) { SourceLocation LocStart = CE->getLocStart(); SourceLocation LocEnd = CE->getLocEnd(); - + if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) return; - + const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); - + // advance the location to startArgList. const char *argPtr = startBuf; - + while (*argPtr++ && (argPtr < endBuf)) { switch (*argPtr) { - case '^': + case '^': // Replace the '^' with '*'. LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf); ReplaceText(LocStart, 1, "*", 1); @@ -779,31 +778,31 @@ void RewriteBlocks::RewriteCastExpr(CastExpr *CE) { void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { SourceLocation DeclLoc = FD->getLocation(); unsigned parenCount = 0; - + // We have 1 or more arguments that have closure pointers. const char *startBuf = SM->getCharacterData(DeclLoc); const char *startArgList = strchr(startBuf, '('); - + assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); - + parenCount++; // advance the location to startArgList. DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf); assert((DeclLoc.isValid()) && "Invalid DeclLoc"); - + const char *argPtr = startArgList; - + while (*argPtr++ && parenCount) { switch (*argPtr) { - case '^': + case '^': // Replace the '^' with '*'. DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList); ReplaceText(DeclLoc, 1, "*", 1); break; - case '(': - parenCount++; + case '(': + parenCount++; break; - case ')': + case ')': parenCount--; break; } @@ -822,7 +821,7 @@ bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) { FTP = BPT->getPointeeType()->getAsFunctionProtoType(); } if (FTP) { - for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), + for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), E = FTP->arg_type_end(); I != E; ++I) if (isBlockPointerType(*I)) return true; @@ -830,15 +829,15 @@ bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) { return false; } -void RewriteBlocks::GetExtentOfArgList(const char *Name, +void RewriteBlocks::GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen) { const char *argPtr = strchr(Name, '('); assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); - + LParen = argPtr; // output the start. argPtr++; // skip past the left paren. unsigned parenCount = 1; - + while (*argPtr && parenCount) { switch (*argPtr) { case '(': parenCount++; break; @@ -855,7 +854,7 @@ void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) { if (FunctionDecl *FD = dyn_cast(ND)) { RewriteBlockPointerFunctionArgs(FD); return; - } + } // Handle Variables and Typedefs. SourceLocation DeclLoc = ND->getLocation(); QualType DeclT; @@ -865,15 +864,15 @@ void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) { DeclT = TDD->getUnderlyingType(); else if (FieldDecl *FD = dyn_cast(ND)) DeclT = FD->getType(); - else + else assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled"); - + const char *startBuf = SM->getCharacterData(DeclLoc); const char *endBuf = startBuf; // scan backward (from the decl location) for the end of the previous decl. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) startBuf--; - + // *startBuf != '^' if we are dealing with a pointer to function that // may take block argument types (which will be handled below). if (*startBuf == '^') { @@ -898,7 +897,7 @@ void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) { return; } -void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) { +void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Add initializers for any closure decl refs. GetBlockDeclRefExprs(Exp->getBody()); if (BlockDeclRefs.size()) { @@ -925,7 +924,7 @@ std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) CollectBlockDeclRefInfo(Exp); std::string FuncName; - + if (CurFunctionDef) FuncName = std::string(CurFunctionDef->getNameAsString()); else if (CurMethodDef) { @@ -936,27 +935,27 @@ std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) FuncName.replace(loc, 1, "_"); } else if (VD) FuncName = std::string(VD->getNameAsString()); - + std::string BlockNumber = utostr(Blocks.size()-1); - + std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber; std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; - + std::string FunkTypeStr; - + // Get a pointer to the function type so we can cast appropriately. Context->getPointerType(QualType(Exp->getFunctionType(),0)) .getAsStringInternal(FunkTypeStr, Context->PrintingPolicy); - + // Rewrite the closure block with a compound literal. The first cast is // to prevent warnings from the C compiler. std::string Init = "(" + FunkTypeStr; - + Init += ")&" + Tag; - + // Initialize the block function. Init += "((void*)" + Func; - + if (ImportedBlockDecls.size()) { std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber; Init += ",(void*)" + Buf; @@ -966,7 +965,7 @@ std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { // Output all "by copy" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { Init += ","; if (isObjCType((*I)->getType())) { @@ -981,7 +980,7 @@ std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) } } // Output all "by ref" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { Init += ",&"; Init += (*I)->getNameAsString(); @@ -1007,7 +1006,7 @@ Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) { if (*CI) { if (BlockExpr *CBE = dyn_cast(*CI)) { RewriteFunctionBody(CBE->getBody()); - + // We've just rewritten the block body in place. // Now we snarf the rewritten text and stash it away for later use. std::string S = Rewrite.getRewritenText(CBE->getSourceRange()); @@ -1030,18 +1029,18 @@ Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) { if (DeclStmt *DS = dyn_cast(S)) { for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { - + Decl *SD = *DI; if (ValueDecl *ND = dyn_cast(SD)) { if (isBlockPointerType(ND->getType())) RewriteBlockPointerDecl(ND); - else if (ND->getType()->isFunctionPointerType()) + else if (ND->getType()->isFunctionPointerType()) CheckFunctionPointerDecl(ND->getType(), ND); } if (TypedefDecl *TD = dyn_cast(SD)) { if (isBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); - else if (TD->getUnderlyingType()->isFunctionPointerType()) + else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); } } @@ -1055,9 +1054,9 @@ Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) { return S; } -void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) { +void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) { if (FunctionProtoType *fproto = dyn_cast(funcType)) { - for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), + for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), E = fproto->arg_type_end(); I && (I != E); ++I) if (isBlockPointerType(*I)) { // All the args are checked/rewritten. Don't call twice! @@ -1090,7 +1089,7 @@ void RewriteBlocks::HandleDeclInMainFile(Decl *D) { // and any copy/dispose helper functions. InsertBlockLiteralsWithinFunction(FD); CurFunctionDef = 0; - } + } return; } if (ObjCMethodDecl *MD = dyn_cast(D)) { @@ -1116,7 +1115,7 @@ void RewriteBlocks::HandleDeclInMainFile(Decl *D) { std::string Init = SynthesizeBlockInitExpr(CBE, VD); // Do the rewrite, using S.size() which contains the rewritten size. ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size()); - SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), + SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getNameAsCString()); } else if (CastExpr *CE = dyn_cast(VD->getInit())) { RewriteCastExpr(CE); @@ -1135,13 +1134,13 @@ void RewriteBlocks::HandleDeclInMainFile(Decl *D) { if (TypedefDecl *TD = dyn_cast(D)) { if (isBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); - else if (TD->getUnderlyingType()->isFunctionPointerType()) + else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); return; } if (RecordDecl *RD = dyn_cast(D)) { if (RD->isDefinition()) { - for (RecordDecl::field_iterator i = RD->field_begin(), + for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i) { FieldDecl *FD = *i; if (isBlockPointerType(FD->getType())) diff --git a/clang/lib/Frontend/RewriteMacros.cpp b/clang/lib/Frontend/RewriteMacros.cpp index 30cd6ff494d098f9442a71be8c7d9d5c9ed503f7..d92f5c78e690688133964887365875ed83badfd7 100644 --- a/clang/lib/Frontend/RewriteMacros.cpp +++ b/clang/lib/Frontend/RewriteMacros.cpp @@ -31,14 +31,14 @@ static bool isSameToken(Token &RawTok, Token &PPTok) { if (PPTok.getKind() == RawTok.getKind() && PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo()) return true; - + // Otherwise, if they are different but have the same identifier info, they // are also considered to be the same. This allows keywords and raw lexed // identifiers with the same name to be treated the same. if (PPTok.getIdentifierInfo() && PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo()) return true; - + return false; } @@ -48,11 +48,11 @@ static bool isSameToken(Token &RawTok, Token &PPTok) { static const Token &GetNextRawTok(const std::vector &RawTokens, unsigned &CurTok, bool ReturnComment) { assert(CurTok < RawTokens.size() && "Overran eof!"); - + // If the client doesn't want comments and we have one, skip it. if (!ReturnComment && RawTokens[CurTok].is(tok::comment)) ++CurTok; - + return RawTokens[CurTok++]; } @@ -62,24 +62,24 @@ static const Token &GetNextRawTok(const std::vector &RawTokens, static void LexRawTokensFromMainFile(Preprocessor &PP, std::vector &RawTokens) { SourceManager &SM = PP.getSourceManager(); - + // Create a lexer to lex all the tokens of the main file in raw mode. Even // though it is in raw mode, it will not return comments. Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions()); // Switch on comment lexing because we really do want them. RawLex.SetCommentRetentionState(true); - + Token RawTok; do { RawLex.LexFromRawLexer(RawTok); - + // If we have an identifier with no identifier info for our raw token, look // up the indentifier info. This is important for equality comparison of // identifier tokens. if (RawTok.is(tok::identifier) && !RawTok.getIdentifierInfo()) RawTok.setIdentifierInfo(PP.LookUpIdentifierInfo(RawTok)); - + RawTokens.push_back(RawTok); } while (RawTok.isNot(tok::eof)); } @@ -88,7 +88,7 @@ static void LexRawTokensFromMainFile(Preprocessor &PP, /// RewriteMacrosInInput - Implement -rewrite-macros mode. void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { SourceManager &SM = PP.getSourceManager(); - + Rewriter Rewrite; Rewrite.setSourceMgr(SM, PP.getLangOptions()); RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID()); @@ -98,12 +98,12 @@ void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { unsigned CurRawTok = 0; Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false); - + // Get the first preprocessing token. PP.EnterMainSourceFile(); Token PPTok; PP.Lex(PPTok); - + // Preprocess the input file in parallel with raw lexing the main file. Ignore // all tokens that are preprocessed from a file other than the main file (e.g. // a header). If we see tokens that are in the preprocessed file but not the @@ -118,7 +118,7 @@ void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { PP.Lex(PPTok); continue; } - + // If the raw file hits a preprocessor directive, they will be extra tokens // in the raw file that don't exist in the preprocsesed file. However, we // choose to preserve them in the output file and otherwise handle them @@ -139,7 +139,7 @@ void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//"); } } - + // Otherwise, if this is a #include or some other directive, just leave it // in the file by skipping over the line. RawTok = GetNextRawTok(RawTokens, CurRawTok, false); @@ -147,7 +147,7 @@ void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { RawTok = GetNextRawTok(RawTokens, CurRawTok, false); continue; } - + // Okay, both tokens are from the same file. Get their offsets from the // start of the file. unsigned PPOffs = SM.getFileOffset(PPLoc); @@ -174,20 +174,20 @@ void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { RawTok = GetNextRawTok(RawTokens, CurRawTok, true); RawOffs = SM.getFileOffset(RawTok.getLocation()); - + if (RawTok.is(tok::comment)) { // Skip past the comment. RawTok = GetNextRawTok(RawTokens, CurRawTok, false); break; } - + } while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() && (PPOffs != RawOffs || !isSameToken(RawTok, PPTok))); RB.InsertTextBefore(EndPos, "*/"); continue; } - + // Otherwise, there was a replacement an expansion. Insert the new token // in the output buffer. Insert the whole run of new tokens at once to get // them in the right order. @@ -205,7 +205,7 @@ void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) { // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. - if (const RewriteBuffer *RewriteBuf = + if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(SM.getMainFileID())) { //printf("Changed:\n"); *OS << std::string(RewriteBuf->begin(), RewriteBuf->end()); diff --git a/clang/lib/Frontend/RewriteObjC.cpp b/clang/lib/Frontend/RewriteObjC.cpp index 8d5f4992aea827d80f7e5b37998da60ab793d605..323804744d384e3e1c3d788c1bc992995e8863c4 100644 --- a/clang/lib/Frontend/RewriteObjC.cpp +++ b/clang/lib/Frontend/RewriteObjC.cpp @@ -35,14 +35,14 @@ namespace { const LangOptions &LangOpts; unsigned RewriteFailedDiag; unsigned TryFinallyContainsReturnDiag; - + ASTContext *Context; SourceManager *SM; TranslationUnitDecl *TUDecl; FileID MainFileID; const char *MainFileStart, *MainFileEnd; SourceLocation LastIncLoc; - + llvm::SmallVector ClassImplementation; llvm::SmallVector CategoryImplementation; llvm::SmallPtrSet ObjCSynthesizedStructs; @@ -53,9 +53,9 @@ namespace { llvm::SmallVector ObjCBcLabelNo; // Remember all the @protocol() expressions. llvm::SmallPtrSet ProtocolExprDecls; - + unsigned NumObjCStringLiterals; - + FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; @@ -66,25 +66,25 @@ namespace { FunctionDecl *SelGetUidFunctionDecl; FunctionDecl *CFStringFunctionDecl; FunctionDecl *SuperContructorFunctionDecl; - + // ObjC string constant support. VarDecl *ConstantStringClassReference; RecordDecl *NSStringRecord; - + // ObjC foreach break/continue generation support. int BcLabelCount; - + // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; - + TypeDecl *ProtocolTypeDecl; QualType getProtocolType(); - + // Needed for header files being rewritten bool IsHeader; - + std::string InFileName; llvm::raw_ostream* OutFile; @@ -96,7 +96,7 @@ namespace { llvm::SmallVector Blocks; llvm::SmallVector BlockDeclRefs; llvm::DenseMap BlockCallExprs; - + // Block related declarations. llvm::SmallPtrSet BlockByCopyDecls; llvm::SmallPtrSet BlockByRefDecls; @@ -109,7 +109,7 @@ namespace { // This maps a property to it's synthesied message expression. // This allows us to rewrite chained getters (e.g. o.a.b.c). llvm::DenseMap PropGetters; - + // 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. @@ -117,9 +117,9 @@ namespace { FunctionDecl *CurFunctionDef; VarDecl *GlobalVarDecl; - + bool DisableReplaceStmt; - + static const int OBJC_ABI_VERSION =7 ; public: virtual void Initialize(ASTContext &context); @@ -136,12 +136,12 @@ namespace { bool silenceMacroWarn); ~RewriteObjC() {} - + virtual void HandleTranslationUnit(ASTContext &C); - + void ReplaceStmt(Stmt *Old, Stmt *New) { Stmt *ReplacingStmt = ReplacedNodes[Old]; - + if (ReplacingStmt) return; // We can't rewrite the same node twice. @@ -191,15 +191,15 @@ namespace { InsertAfter) || SilenceRewriteMacroWarning) return; - + Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); } - + void RemoveText(SourceLocation Loc, unsigned StrLen) { // If removal succeeded or warning disabled return with no warning. if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning) return; - + Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); } @@ -210,10 +210,10 @@ namespace { llvm::StringRef(NewStr, NewLength)) || SilenceRewriteMacroWarning) return; - + Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); } - + // Syntactic Rewriting. void RewritePrologue(SourceLocation Loc); void RewriteInclude(); @@ -238,18 +238,18 @@ namespace { QualType getSuperStructType(); QualType getConstantStringStructType(); bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); - + // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); void CollectPropertySetters(Stmt *S); - + Stmt *CurrentBody; ParentMap *PropParentMap; // created lazily. - + Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart); Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr); - Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt, + Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt, SourceRange SrcRange); Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); @@ -263,13 +263,13 @@ namespace { Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, SourceLocation OrigEnd); - CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, + CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, Expr **args, unsigned nargs); Stmt *SynthMessageExpr(ObjCMessageExpr *Exp); Stmt *RewriteBreakStmt(BreakStmt *S); Stmt *RewriteContinueStmt(ContinueStmt *S); void SynthCountByEnumWithState(std::string &buf); - + void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); void SynthMsgSendStretFunctionDecl(); @@ -279,14 +279,14 @@ namespace { void SynthGetMetaClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperContructorFunctionDecl(); - + // Metadata emission. void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result); - + void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, std::string &Result); - + template void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, MethodIterator MethodEnd, @@ -294,69 +294,69 @@ namespace { const char *prefix, const char *ClassName, std::string &Result); - + void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, const char *prefix, const char *ClassName, std::string &Result); void RewriteObjCProtocolListMetaData(const ObjCList &Prots, - const char *prefix, + const char *prefix, const char *ClassName, std::string &Result); void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); - void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, - ObjCIvarDecl *ivar, + void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, + ObjCIvarDecl *ivar, std::string &Result); void RewriteImplementations(); void SynthesizeMetaDataIntoBuffer(std::string &Result); - + // Block rewriting. - void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); + void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); - + void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); - - // Block specific rewrite rules. + + // Block specific rewrite rules. void RewriteBlockCall(CallExpr *Exp); void RewriteBlockPointerDecl(NamedDecl *VD); Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); - - std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, + + std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, const char *funcName, std::string Tag); - std::string SynthesizeBlockFunc(BlockExpr *CE, int i, + std::string SynthesizeBlockFunc(BlockExpr *CE, int i, const char *funcName, std::string Tag); - std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, + std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, bool hasCopyDisposeHelpers); Stmt *SynthesizeBlockCall(CallExpr *Exp); void SynthesizeBlockLiterals(SourceLocation FunLocStart, const char *FunName); - + void CollectBlockDeclRefInfo(BlockExpr *Exp); void GetBlockCallExprs(Stmt *S); void GetBlockDeclRefExprs(Stmt *S); - + // We avoid calling Type::isBlockPointerType(), since it operates on the // canonical type. We only care if the top-level type is a closure pointer. bool isTopLevelBlockPointerType(QualType T) { return isa(T); } - + // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) return false; - + QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); - + if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || OCT == Context->getCanonicalType(Context->getObjCClassType())) return true; - + if (const PointerType *PT = OCT->getAs()) { - if (isa(PT->getPointeeType()) || + if (isa(PT->getPointeeType()) || PT->getPointeeType()->isObjCQualifiedIdType()) return true; } @@ -366,12 +366,12 @@ namespace { void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); void RewriteCastExpr(CStyleCastExpr *CE); - + FunctionDecl *SynthBlockInitFunctionDecl(const char *name); Stmt *SynthBlockInitExpr(BlockExpr *Exp); - + void QuoteDoublequotes(std::string &From, std::string &To) { - for(unsigned i = 0; i < From.length(); i++) { + for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') To += "\\\""; else @@ -381,10 +381,10 @@ namespace { }; } -void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType, - NamedDecl *D) { +void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType, + NamedDecl *D) { if (FunctionProtoType *fproto = dyn_cast(funcType)) { - for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), + for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), E = fproto->arg_type_end(); I && (I != E); ++I) if (isTopLevelBlockPointerType(*I)) { // All the args are checked/rewritten. Don't call twice! @@ -402,17 +402,17 @@ void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { static bool IsHeaderFile(const std::string &Filename) { std::string::size_type DotPos = Filename.rfind('.'); - + if (DotPos == std::string::npos) { // no file extension - return false; + return false; } - + std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); // C header: .h // C++ header: .hh or .H; return Ext == "h" || Ext == "hh" || Ext == "H"; -} +} RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS, Diagnostic &D, const LangOptions &LOpts, @@ -420,16 +420,16 @@ RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS, : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS), SilenceRewriteMacroWarning(silenceMacroWarn) { IsHeader = IsHeaderFile(inFile); - RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, + RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, "rewriting sub-expression within a macro (may not be correct)"); - TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning, + TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning, "rewriter doesn't support user-specified control flow semantics " "for @try/@finally (code may not execute properly)"); } ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile, llvm::raw_ostream* OS, - Diagnostic &Diags, + Diagnostic &Diags, const LangOptions &LOpts, bool SilenceRewriteMacroWarning) { return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning); @@ -462,15 +462,15 @@ void RewriteObjC::Initialize(ASTContext &context) { PropParentMap = 0; CurrentBody = 0; DisableReplaceStmt = false; - + // Get the ID and start/end of the main file. MainFileID = SM->getMainFileID(); const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); MainFileStart = MainBuf->getBufferStart(); MainFileEnd = MainBuf->getBufferEnd(); - + Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions()); - + // declaring objc_selector outside the parameter list removes a silly // scope related warning... if (IsHeader) @@ -574,7 +574,7 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { // if we rewrote the #include/#import. SourceLocation Loc = D->getLocation(); Loc = SM->getInstantiationLoc(Loc); - + // If this is for a builtin, ignore it. if (Loc.isInvalid()) return; @@ -593,7 +593,7 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { RewriteCategoryDecl(CD); } else if (ObjCProtocolDecl *PD = dyn_cast(D)) { RewriteProtocolDecl(PD); - } else if (ObjCForwardProtocolDecl *FP = + } else if (ObjCForwardProtocolDecl *FP = dyn_cast(D)){ RewriteForwardProtocolDecl(FP); } else if (LinkageSpecDecl *LSD = dyn_cast(D)) { @@ -619,7 +619,7 @@ void RewriteObjC::RewriteInclude() { const char *MainBufEnd = MainBuf.second; size_t ImportLen = strlen("import"); size_t IncludeLen = strlen("include"); - + // Loop over the whole file, looking for includes. for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { if (*BufPtr == '#') { @@ -630,7 +630,7 @@ void RewriteObjC::RewriteInclude() { return; if (!strncmp(BufPtr, "import", ImportLen)) { // replace import with include - SourceLocation ImportLoc = + SourceLocation ImportLoc = LocStart.getFileLocWithOffset(BufPtr-MainBufStart); ReplaceText(ImportLoc, ImportLen, "include", IncludeLen); BufPtr += ImportLen; @@ -643,27 +643,27 @@ void RewriteObjC::RewriteTabs() { std::pair MainBuf = SM->getBufferData(MainFileID); const char *MainBufStart = MainBuf.first; const char *MainBufEnd = MainBuf.second; - + // Loop over the whole file, looking for tabs. for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) { if (*BufPtr != '\t') continue; - + // Okay, we found a tab. This tab will turn into at least one character, // but it depends on which 'virtual column' it is in. Compute that now. unsigned VCol = 0; while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' && BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r') ++VCol; - + // Okay, now that we know the virtual column, we know how many spaces to // insert. We assume 8-character tab-stops. unsigned Spaces = 8-(VCol & 7); - + // Get the location of the tab. SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID); TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart); - + // Rewrite the single tab character into a sequence of spaces. ReplaceText(TabLoc, 1, " ", Spaces); } @@ -693,35 +693,35 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) return; // FIXME: is this correct? - + // Generate the 'getter' function. ObjCPropertyDecl *PD = PID->getPropertyDecl(); ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface(); ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); - + if (!OID) return; - + std::string Getr; RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. - // FIXME: deal with code generation implications for various property - // attributes (copy, retain, nonatomic). + // FIXME: deal with code generation implications for various property + // attributes (copy, retain, nonatomic). // See objc-act.c:objc_synthesize_new_getter() for details. Getr += "return " + getIvarAccessString(ClassDecl, OID); Getr += "; }"; InsertText(onePastSemiLoc, Getr.c_str(), Getr.size()); if (PD->isReadOnly()) return; - + // Generate the 'setter' function. std::string Setr; RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. - // FIXME: deal with code generation implications for various property - // attributes (copy, retain, nonatomic). + // FIXME: deal with code generation implications for various property + // attributes (copy, retain, nonatomic). // See objc-act.c:objc_synthesize_new_setter() for details. Setr += getIvarAccessString(ClassDecl, OID) + " = "; Setr += PD->getNameAsCString(); @@ -734,7 +734,7 @@ void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) { SourceLocation startLoc = ClassDecl->getLocation(); const char *startBuf = SM->getCharacterData(startLoc); const char *semiPtr = strchr(startBuf, ';'); - + // Translate to typedef's that forward reference structs with the same name // as the class. As a convenience, we include the original declaration // as a comment. @@ -755,16 +755,16 @@ void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) { typedefString += ForwardDecl->getNameAsString(); typedefString += ";\n#endif\n"; } - + // Replace the @class with typedefs corresponding to the classes. - ReplaceText(startLoc, semiPtr-startBuf+1, + ReplaceText(startLoc, semiPtr-startBuf+1, typedefString.c_str(), typedefString.size()); } void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { SourceLocation LocStart = Method->getLocStart(); SourceLocation LocEnd = Method->getLocEnd(); - + if (SM->getInstantiationLineNumber(LocEnd) > SM->getInstantiationLineNumber(LocStart)) { InsertText(LocStart, "#if 0\n", 6); @@ -774,26 +774,25 @@ void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { } } -void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) -{ +void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) { SourceLocation Loc = prop->getLocation(); - + ReplaceText(Loc, 0, "// ", 3); - + // FIXME: handle properties that are declared across multiple lines. } void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { SourceLocation LocStart = CatDecl->getLocStart(); - + // FIXME: handle category headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// ", 3); - - for (ObjCCategoryDecl::instmeth_iterator - I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end(); + + for (ObjCCategoryDecl::instmeth_iterator + I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end(); I != E; ++I) RewriteMethodDeclaration(*I); - for (ObjCCategoryDecl::classmeth_iterator + for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end(); I != E; ++I) RewriteMethodDeclaration(*I); @@ -804,14 +803,14 @@ void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { std::pair MainBuf = SM->getBufferData(MainFileID); - + SourceLocation LocStart = PDecl->getLocStart(); - + // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// ", 3); - - for (ObjCProtocolDecl::instmeth_iterator - I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); + + for (ObjCProtocolDecl::instmeth_iterator + I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); I != E; ++I) RewriteMethodDeclaration(*I); for (ObjCProtocolDecl::classmeth_iterator @@ -832,14 +831,14 @@ void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf); ReplaceText(OptionalLoc, strlen("@optional"), CommentedOptional.c_str(), CommentedOptional.size()); - + } else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { std::string CommentedRequired = "/* @required */"; SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf); ReplaceText(OptionalLoc, strlen("@required"), CommentedRequired.c_str(), CommentedRequired.size()); - + } } } @@ -852,7 +851,7 @@ void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) { ReplaceText(LocStart, 0, "// ", 3); } -void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, +void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, std::string &ResultStr) { //fprintf(stderr,"In RewriteObjCMethodDecl\n"); const FunctionType *FPRetType = 0; @@ -876,24 +875,24 @@ void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, } else ResultStr += OMD->getResultType().getAsString(); ResultStr += " "; - + // Unique method name std::string NameStr; - + if (OMD->isInstanceMethod()) NameStr += "_I_"; else NameStr += "_C_"; - + NameStr += OMD->getClassInterface()->getNameAsString(); NameStr += "_"; - - if (ObjCCategoryImplDecl *CID = + + if (ObjCCategoryImplDecl *CID = dyn_cast(OMD->getDeclContext())) { NameStr += CID->getNameAsString(); NameStr += "_"; } - // Append selector names, replacing ':' with '_' + // Append selector names, replacing ':' with '_' { std::string selString = OMD->getSelector().getAsString(); int len = selString.size(); @@ -905,10 +904,10 @@ void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, // Remember this name for metadata emission MethodInternalNames[OMD] = NameStr; ResultStr += NameStr; - + // Rewrite arguments ResultStr += "("; - + // invisible arguments if (OMD->isInstanceMethod()) { QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface()); @@ -923,11 +922,11 @@ void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, } else ResultStr += Context->getObjCClassType().getAsString(); - + ResultStr += " self, "; ResultStr += Context->getObjCSelType().getAsString(); ResultStr += " _cmd"; - + // Method arguments. for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), E = OMD->param_end(); PI != E; ++PI) { @@ -951,10 +950,10 @@ void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, if (OMD->isVariadic()) ResultStr += ", ..."; ResultStr += ") "; - + if (FPRetType) { ResultStr += ")"; // close the precedence "scope" for "*". - + // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast(FPRetType)) { ResultStr += "("; @@ -976,12 +975,12 @@ void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, void RewriteObjC::RewriteImplementationDecl(Decl *OID) { ObjCImplementationDecl *IMD = dyn_cast(OID); ObjCCategoryImplDecl *CID = dyn_cast(OID); - + if (IMD) InsertText(IMD->getLocStart(), "// ", 3); else InsertText(CID->getLocStart(), "// ", 3); - + for (ObjCCategoryImplDecl::instmeth_iterator I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(), E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); @@ -997,7 +996,7 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { ReplaceText(LocStart, endBuf-startBuf, ResultStr.c_str(), ResultStr.size()); } - + for (ObjCCategoryImplDecl::classmeth_iterator I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(), E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); @@ -1007,15 +1006,15 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { RewriteObjCMethodDecl(OMD, ResultStr); SourceLocation LocStart = OMD->getLocStart(); SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); - + const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); ReplaceText(LocStart, endBuf-startBuf, - ResultStr.c_str(), ResultStr.size()); + ResultStr.c_str(), ResultStr.size()); } for (ObjCCategoryImplDecl::propimpl_iterator I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(), - E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); + E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) { RewritePropertyImplDecl(*I, IMD, CID); } @@ -1023,7 +1022,7 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { if (IMD) InsertText(IMD->getLocEnd(), "// ", 3); else - InsertText(CID->getLocEnd(), "// ", 3); + InsertText(CID->getLocEnd(), "// ", 3); } void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { @@ -1043,16 +1042,16 @@ void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { ObjCForwardDecls.insert(ClassDecl); } SynthesizeObjCInternalStruct(ClassDecl, ResultStr); - - for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(), + + for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(), E = ClassDecl->prop_end(); I != E; ++I) RewriteProperty(*I); - for (ObjCInterfaceDecl::instmeth_iterator + for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end(); I != E; ++I) RewriteMethodDeclaration(*I); - for (ObjCInterfaceDecl::classmeth_iterator - I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end(); + for (ObjCInterfaceDecl::classmeth_iterator + I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end(); I != E; ++I) RewriteMethodDeclaration(*I); @@ -1069,20 +1068,20 @@ Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt, ObjCPropertyDecl *PDecl = PropRefExpr->getProperty(); llvm::SmallVector ExprVec; ExprVec.push_back(newStmt); - + Stmt *Receiver = PropRefExpr->getBase(); ObjCPropertyRefExpr *PRE = dyn_cast(Receiver); if (PRE && PropGetters[PRE]) { // This allows us to handle chain/nested property getters. Receiver = PropGetters[PRE]; } - MsgExpr = new (Context) ObjCMessageExpr(dyn_cast(Receiver), - PDecl->getSetterName(), PDecl->getType(), - PDecl->getSetterMethodDecl(), - SourceLocation(), SourceLocation(), + MsgExpr = new (Context) ObjCMessageExpr(dyn_cast(Receiver), + PDecl->getSetterName(), PDecl->getType(), + PDecl->getSetterMethodDecl(), + SourceLocation(), SourceLocation(), &ExprVec[0], 1); Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr); - + // Now do the actual rewrite. ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange); //delete BinOp; @@ -1097,18 +1096,18 @@ Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) { // This allows us to reuse all the fun and games in SynthMessageExpr(). ObjCMessageExpr *MsgExpr; ObjCPropertyDecl *PDecl = PropRefExpr->getProperty(); - + Stmt *Receiver = PropRefExpr->getBase(); - + ObjCPropertyRefExpr *PRE = dyn_cast(Receiver); if (PRE && PropGetters[PRE]) { // This allows us to handle chain/nested property getters. Receiver = PropGetters[PRE]; } - MsgExpr = new (Context) ObjCMessageExpr(dyn_cast(Receiver), - PDecl->getGetterName(), PDecl->getType(), - PDecl->getGetterMethodDecl(), - SourceLocation(), SourceLocation(), + MsgExpr = new (Context) ObjCMessageExpr(dyn_cast(Receiver), + PDecl->getGetterName(), PDecl->getType(), + PDecl->getGetterMethodDecl(), + SourceLocation(), SourceLocation(), 0, 0); Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr); @@ -1127,7 +1126,7 @@ Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) { return PropRefExpr; // return the original... } else { ReplaceStmt(PropRefExpr, ReplacingStmt); - // delete PropRefExpr; elsewhere... + // delete PropRefExpr; elsewhere... // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references // to things that stay around. Context->Deallocate(MsgExpr); @@ -1135,7 +1134,7 @@ Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) { } } -Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, +Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart) { ObjCIvarDecl *D = IV->getDecl(); if (CurMethodDef) { @@ -1144,10 +1143,10 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, dyn_cast(pType->getPointeeType()); // lookup which class implements the instance variable. ObjCInterfaceDecl *clsDeclared = 0; - iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), + 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"; @@ -1156,7 +1155,7 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation(), II); assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); - CastExpr *castExpr = new (Context) CStyleCastExpr(castT, + CastExpr *castExpr = new (Context) CStyleCastExpr(castT, CastExpr::CK_Unknown, IV->getBase(), castT,SourceLocation(), @@ -1165,7 +1164,7 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(), IV->getBase()->getLocEnd(), castExpr); - if (IV->isFreeIvar() && + if (IV->isFreeIvar() && CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) { MemberExpr *ME = new (Context) MemberExpr(PE, true, D, IV->getLocation(), @@ -1174,27 +1173,27 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, // delete IV; leak for now, see RewritePropertySetter() usage for more info. return ME; } - + ReplaceStmt(IV->getBase(), PE); // Cannot delete IV->getBase(), since PE points to it. // Replace the old base with the cast. This is important when doing // embedded rewrites. For example, [newInv->_container addObject:0]. - IV->setBase(PE); + IV->setBase(PE); return 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 (const PointerType *pType = IV->getBase()->getType()->getAs()) { ObjCInterfaceType *iFaceDecl = dyn_cast(pType->getPointeeType()); // lookup which class implements the instance variable. ObjCInterfaceDecl *clsDeclared = 0; - iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), + 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"; @@ -1203,7 +1202,7 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation(), II); assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); - CastExpr *castExpr = new (Context) CStyleCastExpr(castT, + CastExpr *castExpr = new (Context) CStyleCastExpr(castT, CastExpr::CK_Unknown, IV->getBase(), castT, SourceLocation(), @@ -1215,7 +1214,7 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, // Cannot delete IV->getBase(), since PE points to it. // Replace the old base with the cast. This is important when doing // embedded rewrites. For example, [newInv->_container addObject:0]. - IV->setBase(PE); + IV->setBase(PE); return IV; } } @@ -1225,10 +1224,10 @@ Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, /// SynthCountByEnumWithState - To print: /// ((unsigned int (*) /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) -/// (void *)objc_msgSend)((id)l_collection, +/// (void *)objc_msgSend)((id)l_collection, /// sel_registerName( -/// "countByEnumeratingWithState:objects:count:"), -/// &enumState, +/// "countByEnumeratingWithState:objects:count:"), +/// &enumState, /// (id *)items, (unsigned int)16) /// void RewriteObjC::SynthCountByEnumWithState(std::string &buf) { @@ -1250,7 +1249,7 @@ Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) { return S; // replace break with goto __break_label std::string buf; - + SourceLocation startLoc = S->getLocStart(); buf = "goto __break_label_"; buf += utostr(ObjCBcLabelNo.back()); @@ -1267,39 +1266,39 @@ Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) { return S; // replace continue with goto __continue_label std::string buf; - + SourceLocation startLoc = S->getLocStart(); buf = "goto __continue_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size()); - + return 0; } /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. /// It rewrites: /// for ( type elem in collection) { stmts; } - + /// Into: /// { -/// type elem; +/// type elem; /// struct __objcFastEnumerationState enumState = { 0 }; /// id items[16]; /// id l_collection = (id)collection; -/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState +/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState /// objects:items count:16]; /// if (limit) { /// unsigned long startMutations = *enumState.mutationsPtr; /// do { /// unsigned long counter = 0; /// do { -/// if (startMutations != *enumState.mutationsPtr) +/// if (startMutations != *enumState.mutationsPtr) /// objc_enumerationMutation(l_collection); /// elem = (type)enumState.itemsPtr[counter++]; /// stmts; /// __continue_label: ; /// } while (counter < limit); -/// } while (limit = [l_collection countByEnumeratingWithState:&enumState +/// } while (limit = [l_collection countByEnumeratingWithState:&enumState /// objects:items count:16]); /// elem = nil; /// __break_label: ; @@ -1311,11 +1310,11 @@ Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) { Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, SourceLocation OrigEnd) { assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); - assert(isa(Stmts.back()) && + assert(isa(Stmts.back()) && "ObjCForCollectionStmt Statement stack mismatch"); - assert(!ObjCBcLabelNo.empty() && + assert(!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"); - + SourceLocation startLoc = S->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); const char *elementName; @@ -1336,10 +1335,10 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, else { DeclRefExpr *DR = cast(S->getElement()); elementName = DR->getDecl()->getNameAsCString(); - elementTypeAsString + elementTypeAsString = cast(DR->getDecl())->getType().getAsString(); } - + // struct __objcFastEnumerationState enumState = { 0 }; buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; // id items[16]; @@ -1358,8 +1357,8 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) startCollectionBuf++; startCollectionBuf += 3; - - // Replace: "for (type element in" with string constructed thus far. + + // Replace: "for (type element in" with string constructed thus far. ReplaceText(startLoc, startCollectionBuf - startBuf, buf.c_str(), buf.size()); // Replace ')' in for '(' type elem in collection ')' with ';' @@ -1367,17 +1366,17 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, const char *rparenBuf = SM->getCharacterData(rightParenLoc); SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf); buf = ";\n\t"; - + // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState // objects:items count:16]; // which is synthesized into: - // unsigned int limit = + // unsigned int limit = // ((unsigned int (*) // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) - // (void *)objc_msgSend)((id)l_collection, + // (void *)objc_msgSend)((id)l_collection, // sel_registerName( - // "countByEnumeratingWithState:objects:count:"), - // (struct __objcFastEnumerationState *)&state, + // "countByEnumeratingWithState:objects:count:"), + // (struct __objcFastEnumerationState *)&state, // (id *)items, (unsigned int)16); buf += "unsigned long limit =\n\t\t"; SynthCountByEnumWithState(buf); @@ -1387,7 +1386,7 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, /// do { /// unsigned long counter = 0; /// do { - /// if (startMutations != *enumState.mutationsPtr) + /// if (startMutations != *enumState.mutationsPtr) /// objc_enumerationMutation(l_collection); /// elem = (type)enumState.itemsPtr[counter++]; buf += "if (limit) {\n\t"; @@ -1403,10 +1402,10 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, buf += ")enumState.itemsPtr[counter++];"; // Replace ')' in for '(' type elem in collection ')' with all of these. ReplaceText(lparenLoc, 1, buf.c_str(), buf.size()); - + /// __continue_label: ; /// } while (counter < limit); - /// } while (limit = [l_collection countByEnumeratingWithState:&enumState + /// } while (limit = [l_collection countByEnumeratingWithState:&enumState /// objects:items count:16]); /// elem = nil; /// __break_label: ; @@ -1414,7 +1413,7 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, /// else /// elem = nil; /// } - /// + /// buf = ";\n\t"; buf += "__continue_label_"; buf += utostr(ObjCBcLabelNo.back()); @@ -1434,7 +1433,7 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, buf += elementName; buf += " = ((id)0);\n"; buf += "}\n"; - + // Insert all these *after* the statement body. // FIXME: If this should support Obj-C++, support CXXTryStmt if (isa(S->getBody())) { @@ -1459,7 +1458,7 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, return 0; } -/// RewriteObjCSynchronizedStmt - +/// RewriteObjCSynchronizedStmt - /// This routine rewrites @synchronized(expr) stmt; /// into: /// objc_sync_enter(expr); @@ -1469,16 +1468,16 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - + assert((*startBuf == '@') && "bogus @synchronized location"); - - std::string buf; + + std::string buf; buf = "objc_sync_enter((id)"; const char *lparenBuf = startBuf; while (*lparenBuf != '(') lparenBuf++; ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size()); - // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since - // the sync expression is typically a message expression that's already + // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since + // the sync expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). SourceLocation endLoc = S->getSynchBody()->getLocStart(); const char *endBuf = SM->getCharacterData(endLoc); @@ -1495,7 +1494,7 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { ReplaceText(rparenLoc, 1, buf.c_str(), buf.size()); startLoc = S->getSynchBody()->getLocEnd(); startBuf = SM->getCharacterData(startLoc); - + assert((*startBuf == '}') && "bogus @synchronized block"); SourceLocation lastCurlyLoc = startLoc; buf = "}\nelse {\n"; @@ -1504,9 +1503,9 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { buf += "{ /* implicit finally clause */\n"; buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; buf += " objc_sync_exit("; - Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), + Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, - S->getSynchExpr(), + S->getSynchExpr(), Context->getObjCIdType(), SourceLocation(), SourceLocation()); @@ -1519,21 +1518,21 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { buf += " if (_rethrow) objc_exception_throw(_rethrow);\n"; buf += "}\n"; buf += "}"; - + ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size()); return 0; } -void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) { +void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) { // Perform a bottom up traversal of all children. for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; ++CI) if (*CI) WarnAboutReturnGotoContinueOrBreakStmts(*CI); - if (isa(S) || isa(S) || + if (isa(S) || isa(S) || isa(S) || isa(S)) { - Diags.Report(Context->getFullLoc(S->getLocStart()), + Diags.Report(Context->getFullLoc(S->getLocStart()), TryFinallyContainsReturnDiag); } return; @@ -1543,7 +1542,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - + assert((*startBuf == '@') && "bogus @try location"); std::string buf; @@ -1556,12 +1555,12 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; ReplaceText(startLoc, 4, buf.c_str(), buf.size()); - + startLoc = S->getTryBody()->getLocEnd(); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '}') && "bogus @try block"); - + SourceLocation lastCurlyLoc = startLoc; ObjCAtCatchStmt *catchList = S->getCatchStmts(); if (catchList) { @@ -1572,7 +1571,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf += " if (_setjmp(_stack.buf))\n"; buf += " _rethrow = objc_exception_extract(&_stack);\n"; buf += " else { /* @catch continue */"; - + InsertText(startLoc, buf.c_str(), buf.size()); } else { /* no catch list */ buf = "}\nelse {\n"; @@ -1585,15 +1584,15 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { while (catchList) { ParmVarDecl *catchDecl = catchList->getCatchParamDecl(); - if (catchList == S->getCatchStmts()) + if (catchList == S->getCatchStmts()) buf = "if ("; // we are generating code for the first catch clause else buf = "else if ("; startLoc = catchList->getLocStart(); startBuf = SM->getCharacterData(startLoc); - + assert((*startBuf == '@') && "bogus @catch location"); - + const char *lParenLoc = strchr(startBuf, '('); if (catchList->hasEllipsis()) { @@ -1604,7 +1603,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' && "bogus @catch paren location"); assert((*bodyBuf == '{') && "bogus @catch body location"); - + buf += "1) { id _tmp = _caught;"; Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf); } else if (catchDecl) { @@ -1613,9 +1612,9 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf += "1) { "; ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size()); sawIdTypedCatch = true; - } else if (const PointerType *pType = t->getAs()) { + } else if (const PointerType *pType = t->getAs()) { ObjCInterfaceType *cls; // Should be a pointer to a class. - + cls = dyn_cast(pType->getPointeeType().getTypePtr()); if (cls) { buf += "objc_exception_match((struct objc_class *)objc_getClass(\""; @@ -1632,9 +1631,9 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { const char *rParenBuf = SM->getCharacterData(rParenLoc); assert((*rParenBuf == ')') && "bogus @catch paren location"); assert((*bodyBuf == '{') && "bogus @catch body location"); - + buf = " = _caught;"; - // Here we replace ") {" with "= _caught;" (which initializes and + // Here we replace ") {" with "= _caught;" (which initializes and // declares the @catch parameter). ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size()); } else { @@ -1648,7 +1647,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { SourceLocation bodyLoc = lastCatchBody->getLocEnd(); assert(*SM->getCharacterData(bodyLoc) == '}' && "bogus @catch body location"); - + // Insert the last (implicit) else clause *before* the right curly brace. bodyLoc = bodyLoc.getFileLocWithOffset(-1); buf = "} /* last catch end */\n"; @@ -1659,7 +1658,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { if (!S->getFinallyStmt()) buf += "}\n"; InsertText(bodyLoc, buf.c_str(), buf.size()); - + // Set lastCurlyLoc lastCurlyLoc = lastCatchBody->getLocEnd(); } @@ -1667,28 +1666,28 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { startLoc = finalStmt->getLocStart(); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @finally start"); - + buf = "/* @finally */"; ReplaceText(startLoc, 8, buf.c_str(), buf.size()); - + Stmt *body = finalStmt->getFinallyBody(); SourceLocation startLoc = body->getLocStart(); SourceLocation endLoc = body->getLocEnd(); assert(*SM->getCharacterData(startLoc) == '{' && "bogus @finally body location"); - assert(*SM->getCharacterData(endLoc) == '}' && + assert(*SM->getCharacterData(endLoc) == '}' && "bogus @finally body location"); - + startLoc = startLoc.getFileLocWithOffset(1); buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; InsertText(startLoc, buf.c_str(), buf.size()); endLoc = endLoc.getFileLocWithOffset(-1); buf = " if (_rethrow) objc_exception_throw(_rethrow);\n"; InsertText(endLoc, buf.c_str(), buf.size()); - + // Set lastCurlyLoc lastCurlyLoc = body->getLocEnd(); - + // Now check for any return/continue/go statements within the @try. WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody()); } else { /* no finally clause - make sure we synthesize an implicit one */ @@ -1713,14 +1712,14 @@ Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) { return 0; } -// This can't be done with ReplaceStmt(S, ThrowExpr), since -// the throw expression is typically a message expression that's already +// This can't be done with ReplaceStmt(S, ThrowExpr), since +// the throw expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - + assert((*startBuf == '@') && "bogus @throw location"); std::string buf; @@ -1729,12 +1728,12 @@ Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { buf = "objc_exception_throw("; else // add an implicit argument buf = "objc_exception_throw(_caught"; - + // handle "@ throw" correctly. const char *wBuf = strchr(startBuf, 'w'); assert((*wBuf == 'w') && "@throw: can't find 'w'"); ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size()); - + const char *semiBuf = strchr(startBuf, ';'); assert((*semiBuf == ';') && "@throw: can't find ';'"); SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf); @@ -1752,7 +1751,7 @@ Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { StrEncoding.length(), false,StrType, SourceLocation()); ReplaceStmt(Exp, Replacement); - + // Replace this subexpr in the parent. // delete Exp; leak for now, see RewritePropertySetter() usage for more info. return Replacement; @@ -1765,7 +1764,7 @@ Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { // Create a call to sel_registerName("selName"). llvm::SmallVector SelExprs; QualType argType = Context->getPointerType(Context->CharTy); - SelExprs.push_back(StringLiteral::Create(*Context, + SelExprs.push_back(StringLiteral::Create(*Context, Exp->getSelector().getAsString().c_str(), Exp->getSelector().getAsString().size(), false, argType, SourceLocation())); @@ -1780,19 +1779,19 @@ CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl( FunctionDecl *FD, Expr **args, unsigned nargs) { // Get the type, we will need to reference it in a couple spots. QualType msgSendType = FD->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation()); - + // Now, we cast the reference to a pointer to the objc_msgSend type. QualType pToFunc = Context->getPointerType(msgSendType); - ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, + ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, CastExpr::CK_Unknown, - DRE, + DRE, /*isLvalue=*/false); - + const FunctionType *FT = msgSendType->getAsFunctionType(); - + return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(), SourceLocation()); } @@ -1834,7 +1833,7 @@ void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { QualType Type = E->getType(); if (needToScanForQualifiers(Type)) { SourceLocation Loc, EndLoc; - + if (const CStyleCastExpr *ECE = dyn_cast(E)) { Loc = ECE->getLParenLoc(); EndLoc = ECE->getRParenLoc(); @@ -1881,10 +1880,10 @@ void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { } else return; - + if (needToScanForQualifiers(Type)) { // Since types are unique, we need to scan the buffer. - + const char *endBuf = SM->getCharacterData(Loc); const char *startBuf = endBuf; while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) @@ -1907,16 +1906,16 @@ void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { for (unsigned i = 0; i < proto->getNumArgs(); i++) { if (needToScanForQualifiers(proto->getArgType(i))) { // Since types are unique, we need to scan the buffer. - + const char *endBuf = startBuf; // scan forward (from the decl location) for argument types. scanToNextArgument(endBuf); const char *startRef = 0, *endRef = 0; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. - SourceLocation LessLoc = + SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startFuncBuf); - SourceLocation GreaterLoc = + SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startFuncBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*", 2); @@ -1944,7 +1943,7 @@ void RewriteObjC::SynthSelGetUidFunctionDecl() { &ArgTys[0], ArgTys.size(), false /*isVariadic*/, 0); SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), SelGetUidIdent, getFuncType, 0, FunctionDecl::Extern, false); } @@ -1973,7 +1972,7 @@ void RewriteObjC::SynthSuperContructorFunctionDecl() { &ArgTys[0], ArgTys.size(), false, 0); SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), msgSendIdent, msgSendType, 0, FunctionDecl::Extern, false); } @@ -2014,7 +2013,7 @@ void RewriteObjC::SynthMsgSendSuperFunctionDecl() { &ArgTys[0], ArgTys.size(), true /*isVariadic*/, 0); MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), msgSendIdent, msgSendType, 0, FunctionDecl::Extern, false); } @@ -2033,15 +2032,15 @@ void RewriteObjC::SynthMsgSendStretFunctionDecl() { &ArgTys[0], ArgTys.size(), true /*isVariadic*/, 0); MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), msgSendIdent, msgSendType, 0, FunctionDecl::Extern, false); } -// SynthMsgSendSuperStretFunctionDecl - +// SynthMsgSendSuperStretFunctionDecl - // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...); void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() { - IdentifierInfo *msgSendIdent = + IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper_stret"); llvm::SmallVector ArgTys; RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, @@ -2057,7 +2056,7 @@ void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() { &ArgTys[0], ArgTys.size(), true /*isVariadic*/, 0); MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), msgSendIdent, msgSendType, 0, FunctionDecl::Extern, false); } @@ -2076,7 +2075,7 @@ void RewriteObjC::SynthMsgSendFpretFunctionDecl() { &ArgTys[0], ArgTys.size(), true /*isVariadic*/, 0); MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), msgSendIdent, msgSendType, 0, FunctionDecl::Extern, false); } @@ -2091,7 +2090,7 @@ void RewriteObjC::SynthGetClassFunctionDecl() { &ArgTys[0], ArgTys.size(), false /*isVariadic*/, 0); GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), getClassIdent, getClassType, 0, FunctionDecl::Extern, false); } @@ -2106,7 +2105,7 @@ void RewriteObjC::SynthGetMetaClassFunctionDecl() { &ArgTys[0], ArgTys.size(), false /*isVariadic*/, 0); GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), getClassIdent, getClassType, 0, FunctionDecl::Extern, false); } @@ -2140,19 +2139,19 @@ Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { Preamble += ","; // The minus 2 removes the begin/end double quotes. Preamble += utostr(prettyBuf.str().size()-2) + "};\n"; - - VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), - &Context->Idents.get(S.c_str()), strType, 0, + + VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), + &Context->Idents.get(S.c_str()), strType, 0, VarDecl::Static); DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation()); Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf, - Context->getPointerType(DRE->getType()), + Context->getPointerType(DRE->getType()), SourceLocation()); // cast to NSConstantString * - CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), + CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), CastExpr::CK_Unknown, - Unop, Exp->getType(), - SourceLocation(), + Unop, Exp->getType(), + SourceLocation(), SourceLocation()); ReplaceStmt(Exp, cast); // delete Exp; leak for now, see RewritePropertySetter() usage for more info. @@ -2162,9 +2161,9 @@ Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) { // check if we are sending a message to 'super' if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0; - + if (ObjCSuperExpr *Super = dyn_cast(recExpr)) { - const ObjCObjectPointerType *OPT = + const ObjCObjectPointerType *OPT = Super->getType()->getAsObjCObjectPointerType(); assert(OPT); const ObjCInterfaceType *IT = OPT->getInterfaceType(); @@ -2177,24 +2176,24 @@ ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) { QualType RewriteObjC::getSuperStructType() { if (!SuperStructDecl) { SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, - SourceLocation(), + SourceLocation(), &Context->Idents.get("objc_super")); QualType FieldTypes[2]; - + // struct objc_object *receiver; - FieldTypes[0] = Context->getObjCIdType(); + FieldTypes[0] = Context->getObjCIdType(); // struct objc_class *super; - FieldTypes[1] = Context->getObjCClassType(); + FieldTypes[1] = Context->getObjCClassType(); // Create fields for (unsigned i = 0; i < 2; ++i) { - SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, - SourceLocation(), 0, + SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, + SourceLocation(), 0, FieldTypes[i], 0, /*BitWidth=*/0, /*Mutable=*/false)); } - + SuperStructDecl->completeDefinition(*Context); } return Context->getTagDeclType(SuperStructDecl); @@ -2203,23 +2202,23 @@ QualType RewriteObjC::getSuperStructType() { QualType RewriteObjC::getConstantStringStructType() { if (!ConstantStringDecl) { ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, - SourceLocation(), + SourceLocation(), &Context->Idents.get("__NSConstantStringImpl")); QualType FieldTypes[4]; - + // struct objc_object *receiver; - FieldTypes[0] = Context->getObjCIdType(); + FieldTypes[0] = Context->getObjCIdType(); // int flags; - FieldTypes[1] = Context->IntTy; + FieldTypes[1] = Context->IntTy; // char *str; - FieldTypes[2] = Context->getPointerType(Context->CharTy); + FieldTypes[2] = Context->getPointerType(Context->CharTy); // long length; - FieldTypes[3] = Context->LongTy; + FieldTypes[3] = Context->LongTy; // Create fields for (unsigned i = 0; i < 4; ++i) { - ConstantStringDecl->addDecl(FieldDecl::Create(*Context, - ConstantStringDecl, + ConstantStringDecl->addDecl(FieldDecl::Create(*Context, + ConstantStringDecl, SourceLocation(), 0, FieldTypes[i], 0, /*BitWidth=*/0, @@ -2248,7 +2247,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { SynthGetClassFunctionDecl(); if (!GetMetaClassFunctionDecl) SynthGetMetaClassFunctionDecl(); - + // default to objc_msgSend(). FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; // May need to use objc_msgSend_stret() as well. @@ -2260,11 +2259,11 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { else if (resultType->isRealFloatingType()) MsgSendFlavor = MsgSendFpretFunctionDecl; } - + // Synthesize a call to objc_msgSend(). llvm::SmallVector MsgExprs; IdentifierInfo *clsName = Exp->getClassName(); - + // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend(). if (clsName) { // class message. // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle @@ -2274,17 +2273,17 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { if (MsgSendStretFlavor) MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); - - ObjCInterfaceDecl *SuperDecl = + + ObjCInterfaceDecl *SuperDecl = CurMethodDef->getClassInterface()->getSuperClass(); llvm::SmallVector InitExprs; - + // set the receiver to self, the first argument to all methods. InitExprs.push_back( - new (Context) CStyleCastExpr(Context->getObjCIdType(), + new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, - new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), + new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), Context->getObjCIdType(), SourceLocation()), Context->getObjCIdType(), @@ -2293,29 +2292,29 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { llvm::SmallVector ClsExprs; QualType argType = Context->getPointerType(Context->CharTy); ClsExprs.push_back(StringLiteral::Create(*Context, - SuperDecl->getIdentifier()->getName(), + SuperDecl->getIdentifier()->getName(), SuperDecl->getIdentifier()->getLength(), false, argType, SourceLocation())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl, - &ClsExprs[0], + &ClsExprs[0], ClsExprs.size()); // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using objc_getClass(). - new (Context) CStyleCastExpr(Context->getObjCIdType(), + new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, Cls, Context->getObjCIdType(), - SourceLocation(), SourceLocation())); + SourceLocation(), SourceLocation())); // struct objc_super QualType superType = getSuperStructType(); Expr *SuperRep; - + if (LangOpts.Microsoft) { SynthSuperContructorFunctionDecl(); // Simulate a contructor call... - DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, + DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, superType, SourceLocation()); SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], - InitExprs.size(), + InitExprs.size(), superType, SourceLocation()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own @@ -2324,22 +2323,22 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) // SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf, - Context->getPointerType(SuperRep->getType()), + Context->getPointerType(SuperRep->getType()), SourceLocation()); - SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType), - CastExpr::CK_Unknown, SuperRep, + SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType), + CastExpr::CK_Unknown, SuperRep, Context->getPointerType(superType), - SourceLocation(), SourceLocation()); - } else { + SourceLocation(), SourceLocation()); + } else { // (struct objc_super) { } - InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(), - &InitExprs[0], InitExprs.size(), + InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(), + &InitExprs[0], InitExprs.size(), SourceLocation()); SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false); // struct objc_super * SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf, - Context->getPointerType(SuperRep->getType()), + Context->getPointerType(SuperRep->getType()), SourceLocation()); } MsgExprs.push_back(SuperRep); @@ -2347,12 +2346,12 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { llvm::SmallVector ClsExprs; QualType argType = Context->getPointerType(Context->CharTy); ClsExprs.push_back(StringLiteral::Create(*Context, - clsName->getName(), + clsName->getName(), clsName->getLength(), false, argType, SourceLocation())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, - &ClsExprs[0], + &ClsExprs[0], ClsExprs.size()); MsgExprs.push_back(Cls); } @@ -2364,44 +2363,44 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { if (MsgSendStretFlavor) MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); - + llvm::SmallVector InitExprs; - + InitExprs.push_back( - new (Context) CStyleCastExpr(Context->getObjCIdType(), + new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, - new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), + new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), Context->getObjCIdType(), SourceLocation()), Context->getObjCIdType(), SourceLocation(), SourceLocation())); // set the 'receiver'. - + llvm::SmallVector ClsExprs; QualType argType = Context->getPointerType(Context->CharTy); - ClsExprs.push_back(StringLiteral::Create(*Context, - SuperDecl->getIdentifier()->getName(), + ClsExprs.push_back(StringLiteral::Create(*Context, + SuperDecl->getIdentifier()->getName(), SuperDecl->getIdentifier()->getLength(), false, argType, SourceLocation())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, - &ClsExprs[0], + &ClsExprs[0], ClsExprs.size()); // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using objc_getClass(). - new (Context) CStyleCastExpr(Context->getObjCIdType(), + new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, - Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation())); + Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation())); // struct objc_super QualType superType = getSuperStructType(); Expr *SuperRep; - + if (LangOpts.Microsoft) { SynthSuperContructorFunctionDecl(); // Simulate a contructor call... - DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, + DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, superType, SourceLocation()); SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], - InitExprs.size(), + InitExprs.size(), superType, SourceLocation()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own @@ -2410,16 +2409,16 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) // SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf, - Context->getPointerType(SuperRep->getType()), + Context->getPointerType(SuperRep->getType()), SourceLocation()); - SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType), + SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType), CastExpr::CK_Unknown, SuperRep, Context->getPointerType(superType), - SourceLocation(), SourceLocation()); + SourceLocation(), SourceLocation()); } else { // (struct objc_super) { } - InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(), - &InitExprs[0], InitExprs.size(), + InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(), + &InitExprs[0], InitExprs.size(), SourceLocation()); SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false); } @@ -2429,9 +2428,9 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { // Foo *. while (CStyleCastExpr *CE = dyn_cast(recExpr)) recExpr = CE->getSubExpr(); - recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), + recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, recExpr, - Context->getObjCIdType(), + Context->getObjCIdType(), SourceLocation(), SourceLocation()); MsgExprs.push_back(recExpr); } @@ -2439,14 +2438,14 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { // Create a call to sel_registerName("selName"), it will be the 2nd argument. llvm::SmallVector SelExprs; QualType argType = Context->getPointerType(Context->CharTy); - SelExprs.push_back(StringLiteral::Create(*Context, + SelExprs.push_back(StringLiteral::Create(*Context, Exp->getSelector().getAsString().c_str(), Exp->getSelector().getAsString().size(), false, argType, SourceLocation())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, &SelExprs[0], SelExprs.size()); MsgExprs.push_back(SelExp); - + // Now push any user supplied arguments. for (unsigned i = 0; i < Exp->getNumArgs(); i++) { Expr *userExpr = Exp->getArg(i); @@ -2457,7 +2456,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { ? Context->getObjCIdType() : ICE->getType(); userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown, - userExpr, type, SourceLocation(), + userExpr, type, SourceLocation(), SourceLocation()); } // Make id cast into an 'id' cast. @@ -2465,12 +2464,12 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { if (CE->getType()->isObjCQualifiedIdType()) { while ((CE = dyn_cast(userExpr))) userExpr = CE->getSubExpr(); - userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), + userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), CastExpr::CK_Unknown, - userExpr, Context->getObjCIdType(), + userExpr, Context->getObjCIdType(), SourceLocation(), SourceLocation()); } - } + } MsgExprs.push_back(userExpr); // We've transferred the ownership to MsgExprs. For now, we *don't* null // out the argument in the original expression (since we aren't deleting @@ -2481,7 +2480,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { CastExpr *cast; llvm::SmallVector ArgTypes; QualType returnType; - + // Push 'id' and 'SEL', the 2 implicit arguments. if (MsgSendFlavor == MsgSendSuperFunctionDecl) ArgTypes.push_back(Context->getPointerType(getSuperStructType())); @@ -2493,7 +2492,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), E = OMD->param_end(); PI != E; ++PI) { QualType t = (*PI)->getType()->isObjCQualifiedIdType() - ? Context->getObjCIdType() + ? Context->getObjCIdType() : (*PI)->getType(); // Make sure we convert "t (^)(...)" to "t (*)(...)". if (isTopLevelBlockPointerType(t)) { @@ -2509,36 +2508,36 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { } // 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, msgSendType, + DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation()); - // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). + // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). // If we don't do this cast, we get the following bizarre warning/note: // xx.m:13: warning: function called through a non-compatible type // xx.m:13: note: if this code is reached, the program will abort - cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), - CastExpr::CK_Unknown, DRE, + cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), + CastExpr::CK_Unknown, DRE, Context->getPointerType(Context->VoidTy), SourceLocation(), SourceLocation()); - + // Now do the "normal" pointer to function cast. - QualType castType = Context->getFunctionType(returnType, + QualType castType = Context->getFunctionType(returnType, &ArgTypes[0], ArgTypes.size(), // If we don't have a method decl, force a variadic cast. Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0); castType = Context->getPointerType(castType); - cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast, - castType, SourceLocation(), + cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast, + castType, SourceLocation(), SourceLocation()); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); - + const FunctionType *FT = msgSendType->getAsFunctionType(); CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0], - MsgExprs.size(), + MsgExprs.size(), FT->getResultType(), SourceLocation()); Stmt *ReplacingStmt = CE; if (MsgSendStretFlavor) { @@ -2546,33 +2545,33 @@ 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. - + // Create a reference to the objc_msgSend_stret() declaration. - DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType, + DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType, SourceLocation()); // Need to cast objc_msgSend_stret to "void *" (see above comment). - cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), - CastExpr::CK_Unknown, STDRE, + cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), + CastExpr::CK_Unknown, STDRE, Context->getPointerType(Context->VoidTy), SourceLocation(), SourceLocation()); // Now do the "normal" pointer to function cast. - castType = Context->getFunctionType(returnType, + castType = Context->getFunctionType(returnType, &ArgTypes[0], ArgTypes.size(), Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0); castType = Context->getPointerType(castType); cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast, castType, SourceLocation(), SourceLocation()); - + // Don't forget the parens to enforce the proper binding. PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); - + FT = msgSendType->getAsFunctionType(); CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0], - MsgExprs.size(), + MsgExprs.size(), FT->getResultType(), SourceLocation()); - + // Build sizeof(returnType) - SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true, + SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true, returnType, Context->getSizeType(), SourceLocation(), SourceLocation()); @@ -2580,33 +2579,33 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases. // For X86 it is more complicated and some kind of target specific routine // is needed to decide what to do. - unsigned IntSize = + unsigned IntSize = static_cast(Context->getTypeSize(Context->IntTy)); - IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8), + IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8), Context->IntTy, SourceLocation()); - BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit, - BinaryOperator::LE, - Context->IntTy, + BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit, + BinaryOperator::LE, + Context->IntTy, SourceLocation()); // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...)) - ConditionalOperator *CondExpr = + ConditionalOperator *CondExpr = new (Context) ConditionalOperator(lessThanExpr, SourceLocation(), CE, SourceLocation(), STCE, returnType); ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr); } - // delete Exp; leak for now, see RewritePropertySetter() usage for more info. + // delete Exp; leak for now, see RewritePropertySetter() usage for more info. return ReplacingStmt; } Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { Stmt *ReplacingStmt = SynthMessageExpr(Exp); - + // Now do the actual rewrite. ReplaceStmt(Exp, ReplacingStmt); - - // delete Exp; leak for now, see RewritePropertySetter() usage for more info. + + // delete Exp; leak for now, see RewritePropertySetter() usage for more info. return ReplacingStmt; } @@ -2614,7 +2613,7 @@ Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { QualType RewriteObjC::getProtocolType() { if (!ProtocolTypeDecl) { ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl, - SourceLocation(), + SourceLocation(), &Context->Idents.get("Protocol"), Context->getObjCIdType()); } @@ -2628,24 +2627,24 @@ QualType RewriteObjC::getProtocolType() { Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString(); IdentifierInfo *ID = &Context->Idents.get(Name); - VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), + VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), ID, QualType()/*UNUSED*/, 0, VarDecl::Extern); DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation()); Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf, Context->getPointerType(DRE->getType()), SourceLocation()); - CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(), - CastExpr::CK_Unknown, - DerefExpr, DerefExpr->getType(), + CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(), + CastExpr::CK_Unknown, + DerefExpr, DerefExpr->getType(), SourceLocation(), SourceLocation()); ReplaceStmt(Exp, castExpr); ProtocolExprDecls.insert(Exp->getProtocol()); - // delete Exp; leak for now, see RewritePropertySetter() usage for more info. + // delete Exp; leak for now, see RewritePropertySetter() usage for more info. return castExpr; - + } -bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf, +bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf, const char *endBuf) { while (startBuf < endBuf) { if (*startBuf == '#') { @@ -2676,7 +2675,7 @@ bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf, void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result) { assert(CDecl && "Class missing in SynthesizeObjCInternalStruct"); - assert(CDecl->getNameAsCString() && + assert(CDecl->getNameAsCString() && "Name missing in SynthesizeObjCInternalStruct"); // Do not synthesize more than once. if (ObjCSynthesizedStructs.count(CDecl)) @@ -2685,10 +2684,10 @@ void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, int NumIvars = CDecl->ivar_size(); SourceLocation LocStart = CDecl->getLocStart(); SourceLocation LocEnd = CDecl->getLocEnd(); - + 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->isForwardDecl() || NumIvars == 0) && @@ -2697,8 +2696,8 @@ void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size()); return; } - - // FIXME: This has potential of causing problem. If + + // FIXME: This has potential of causing problem. If // SynthesizeObjCInternalStruct is ever called recursively. Result += "\nstruct "; Result += CDecl->getNameAsString(); @@ -2707,7 +2706,7 @@ void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, if (NumIvars > 0) { const char *cursor = strchr(startBuf, '{'); - assert((cursor && endBuf) + assert((cursor && endBuf) && "SynthesizeObjCInternalStruct - malformed @interface"); // If the buffer contains preprocessor directives, we do more fine-grained // rewrites. This is intended to fix code that looks like (which occurs in @@ -2725,7 +2724,7 @@ void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, // // This clause is segregated to avoid breaking the common case. if (BufferContainsPPDirectives(startBuf, cursor)) { - SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() : + SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() : CDecl->getClassLoc(); const char *endHeader = SM->getCharacterData(L); endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts); @@ -2747,14 +2746,14 @@ void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, Result += "_IMPL "; Result += RCDecl->getNameAsString(); Result += "_IVARS;\n"; - + // insert the super class structure definition. SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1); InsertText(OnePastCurly, Result.c_str(), Result.size()); } cursor++; // past '{' - + // Now comment out any visibility specifiers. while (cursor < endBuf) { if (*cursor == '@') { @@ -2813,7 +2812,7 @@ void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, const char *ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; - + static bool objc_impl_method = false; if (!objc_impl_method) { /* struct _objc_method { @@ -2827,12 +2826,12 @@ void RewriteObjC::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; @@ -2895,13 +2894,13 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, 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)) return; - + if (PDecl->instmeth_begin() != PDecl->instmeth_end()) { unsigned NumMethods = std::distance(PDecl->instmeth_begin(), PDecl->instmeth_end()); @@ -2918,10 +2917,10 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, 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(); + for (ObjCProtocolDecl::instmeth_iterator + I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); I != E; ++I) { if (I == PDecl->instmeth_begin()) Result += "\t ,{{(struct objc_selector *)\""; @@ -2936,7 +2935,7 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, } Result += "\t }\n};\n"; } - + // Output class methods declared in this protocol. unsigned NumMethods = std::distance(PDecl->classmeth_begin(), PDecl->classmeth_end()); @@ -2956,9 +2955,9 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, "{\n\t"; Result += utostr(NumMethods); Result += "\n"; - + // Output instance methods declared in this protocol. - for (ObjCProtocolDecl::classmeth_iterator + for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); I != E; ++I) { if (I == PDecl->classmeth_begin()) @@ -2983,7 +2982,7 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, struct _objc_protocol **protocol_list; struct _objc_protocol_method_list *instance_methods; struct _objc_protocol_method_list *class_methods; - }; + }; */ static bool objc_protocol = false; if (!objc_protocol) { @@ -2994,10 +2993,10 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, 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\")))= " @@ -3019,7 +3018,7 @@ RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, else Result += "0\n"; Result += "};\n"; - + // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl)) assert(false && "protocol already synthesized"); @@ -3031,7 +3030,7 @@ RewriteObjCProtocolListMetaData(const ObjCList &Protocols, const char *prefix, const char *ClassName, std::string &Result) { if (Protocols.empty()) return; - + for (unsigned i = 0; i != Protocols.size(); i++) RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result); @@ -3055,11 +3054,11 @@ RewriteObjCProtocolListMetaData(const ObjCList &Protocols, "{\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(); @@ -3069,24 +3068,24 @@ RewriteObjCProtocolListMetaData(const ObjCList &Protocols, } -/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category +/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category /// implementation. void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); // Find category declaration for this implementation. ObjCCategoryDecl *CDecl; - for (CDecl = ClassDecl->getCategoryList(); CDecl; + for (CDecl = ClassDecl->getCategoryList(); CDecl; CDecl = CDecl->getNextClassCategory()) if (CDecl->getIdentifier() == IDecl->getIdentifier()) break; - + std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += '_'; FullCategoryName += IDecl->getNameAsString(); - + // Build _objc_method_list for class's instance methods if needed - llvm::SmallVector + llvm::SmallVector InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end()); // If any of our property implementations have associated getters or @@ -3111,12 +3110,12 @@ void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), true, "CATEGORY_", FullCategoryName.c_str(), Result); - + // Build _objc_method_list for class's class methods if needed RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), false, "CATEGORY_", FullCategoryName.c_str(), Result); - + // Protocols referenced in class declaration? // Null CDecl is case of a category implementation with no category interface if (CDecl) @@ -3130,11 +3129,11 @@ void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, struct _objc_protocol_list *protocols; // Objective-C 1.0 extensions uint32_t size; // sizeof (struct _objc_category) - struct _objc_property_list *instance_properties; // category's own + struct _objc_property_list *instance_properties; // category's own // @property decl. - }; + }; */ - + static bool objc_category = false; if (!objc_category) { Result += "\nstruct _objc_category {\n"; @@ -3143,7 +3142,7 @@ void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, Result += "\tstruct _objc_method_list *instance_methods;\n"; Result += "\tstruct _objc_method_list *class_methods;\n"; Result += "\tstruct _objc_protocol_list *protocols;\n"; - Result += "\tunsigned int size;\n"; + Result += "\tunsigned int size;\n"; Result += "\tstruct _objc_property_list *instance_properties;\n"; Result += "};\n"; objc_category = true; @@ -3155,7 +3154,7 @@ void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, 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_"; @@ -3172,9 +3171,9 @@ void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, } else Result += "\t, 0\n"; - + if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) { - Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_"; + Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_"; Result += FullCategoryName; Result += "\n"; } @@ -3185,8 +3184,8 @@ void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, /// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of /// ivar offset. -void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, - ObjCIvarDecl *ivar, +void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, + ObjCIvarDecl *ivar, std::string &Result) { if (ivar->isBitField()) { // FIXME: The hack below doesn't work for bitfields. For now, we simply @@ -3210,17 +3209,17 @@ void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); - + // Explictly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) { - // FIXME: Implementation of a class with no @interface (legacy) doese not + // FIXME: Implementation of a class with no @interface (legacy) doese not // produce correct synthesis as yet. SynthesizeObjCInternalStruct(CDecl, Result); } - + // Build _objc_ivar_list metadata for classes ivars if needed unsigned NumIvars = !IDecl->ivar_empty() - ? IDecl->ivar_size() + ? IDecl->ivar_size() : (CDecl ? CDecl->ivar_size() : 0); if (NumIvars > 0) { static bool objc_ivar = false; @@ -3229,23 +3228,23 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, char *ivar_name; char *ivar_type; int ivar_offset; - }; + }; */ Result += "\nstruct _objc_ivar {\n"; Result += "\tchar *ivar_name;\n"; 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]; - }; + }; */ - Result += "\nstatic struct {\n"; + Result += "\nstatic struct {\n"; Result += "\tint ivar_count;\n"; Result += "\tstruct _objc_ivar ivar_list["; Result += utostr(NumIvars); @@ -3255,11 +3254,11 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, "{\n\t"; Result += utostr(NumIvars); Result += "\n"; - + ObjCInterfaceDecl::ivar_iterator IVI, IVE; llvm::SmallVector IVars; if (!IDecl->ivar_empty()) { - for (ObjCImplementationDecl::ivar_iterator + for (ObjCImplementationDecl::ivar_iterator IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end(); IV != IVEnd; ++IV) IVars.push_back(*IV); @@ -3291,12 +3290,12 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result); Result += "}\n"; } - + Result += "\t }\n};\n"; } - + // Build _objc_method_list for class's instance methods if needed - llvm::SmallVector + llvm::SmallVector InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end()); // If any of our property implementations have associated getters or @@ -3320,15 +3319,15 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, } RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), true, "", IDecl->getNameAsCString(), Result); - + // Build _objc_method_list for class's class methods if needed RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), false, "", IDecl->getNameAsCString(), Result); - + // Protocols referenced in class declaration? RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CLASS", CDecl->getNameAsCString(), Result); - + // Declaration of class/meta-class metadata /* struct _objc_class { struct _objc_class *isa; // or const char *root_class_name when metadata @@ -3343,7 +3342,7 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, struct objc_protocol_list *protocols; const char *ivar_layout; struct _objc_class_ext *ext; - }; + }; */ static bool objc_class = false; if (!objc_class) { @@ -3363,7 +3362,7 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, Result += "};\n"; objc_class = true; } - + // Meta-class metadata generation. ObjCInterfaceDecl *RootClass = 0; ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); @@ -3372,7 +3371,7 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, SuperClass = SuperClass->getSuperClass(); } SuperClass = CDecl->getSuperClass(); - + Result += "\nstatic struct _objc_class _OBJC_METACLASS_"; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= " @@ -3398,7 +3397,7 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, if (IDecl->classmeth_begin() != IDecl->classmeth_end()) { Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_"; Result += IDecl->getNameAsString(); - Result += "\n"; + Result += "\n"; } else Result += ", 0\n"; @@ -3410,7 +3409,7 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, else Result += "\t,0,0,0,0\n"; Result += "};\n"; - + // class metadata generation. Result += "\nstatic struct _objc_class _OBJC_CLASS_"; Result += CDecl->getNameAsString(); @@ -3451,7 +3450,7 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, if (IDecl->instmeth_begin() != IDecl->instmeth_end()) { Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_"; Result += CDecl->getNameAsString(); - Result += ", 0\n\t"; + Result += ", 0\n\t"; } else Result += ",0,0"; @@ -3471,25 +3470,25 @@ void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, void RewriteObjC::RewriteImplementations() { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); - + // Rewrite implemented methods for (int i = 0; i < ClsDefCount; i++) RewriteImplementationDecl(ClassImplementation[i]); - + for (int i = 0; i < CatDefCount; i++) RewriteImplementationDecl(CategoryImplementation[i]); } - + void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); // This is needed for determining instance variable offsets. - Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n"; + Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n"; // 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); @@ -3503,9 +3502,9 @@ void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { short cls_def_cnt; short cat_def_cnt; void *defs[cls_def_cnt + cat_def_cnt]; - }; + }; */ - + Result += "\nstruct _objc_symtab {\n"; Result += "\tlong sel_ref_cnt;\n"; Result += "\tSEL *refs;\n"; @@ -3513,17 +3512,17 @@ void RewriteObjC::SynthesizeMetaDataIntoBuffer(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) + Result += "\t0, 0, " + utostr(ClsDefCount) + ", " + utostr(CatDefCount) + "\n"; for (int i = 0; i < ClsDefCount; i++) { Result += "\t,&_OBJC_CLASS_"; Result += ClassImplementation[i]->getNameAsString(); Result += "\n"; } - + for (int i = 0; i < CatDefCount; i++) { Result += "\t,&_OBJC_CATEGORY_"; Result += CategoryImplementation[i]->getClassInterface()->getNameAsString(); @@ -3531,11 +3530,11 @@ void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { Result += CategoryImplementation[i]->getNameAsString(); Result += "\n"; } - + Result += "};\n\n"; - + // Write objc_module metadata - + /* struct _objc_module { long version; @@ -3544,7 +3543,7 @@ void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { struct _objc_symtab *symtab; } */ - + Result += "\nstruct _objc_module {\n"; Result += "\tlong version;\n"; Result += "\tlong size;\n"; @@ -3553,7 +3552,7 @@ void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { Result += "};\n\n"; Result += "static struct _objc_module " "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n"; - Result += "\t" + utostr(OBJC_ABI_VERSION) + + Result += "\t" + utostr(OBJC_ABI_VERSION) + ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n"; Result += "};\n\n"; @@ -3561,7 +3560,7 @@ void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { if (ProtocolExprDecls.size()) { Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n"; Result += "#pragma data_seg(push, \".objc_protocol$B\")\n"; - for (llvm::SmallPtrSet::iterator I = ProtocolExprDecls.begin(), + for (llvm::SmallPtrSet::iterator I = ProtocolExprDecls.begin(), E = ProtocolExprDecls.end(); I != E; ++I) { Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_"; Result += (*I)->getNameAsString(); @@ -3589,9 +3588,9 @@ std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, funcName + "_" + "block_func_" + utostr(i); BlockDecl *BD = CE->getBlockDecl(); - + if (isa(AFT)) { - // No user-supplied arguments. Still need to pass in a pointer to the + // No user-supplied arguments. Still need to pass in a pointer to the // block (to reference imported block decl refs). S += "(" + StructRef + " *__cself)"; } else if (BD->param_empty()) { @@ -3617,19 +3616,19 @@ std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, S += ')'; } S += " {\n"; - + // Create local declarations to avoid rewriting all closure decl ref exprs. // First, emit a declaration for all "by ref" decls. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); - Context->getPointerType((*I)->getType()).getAsStringInternal(Name, + Context->getPointerType((*I)->getType()).getAsStringInternal(Name, Context->PrintingPolicy); S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; - } + } // Next, emit a declaration for all "by copy" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); @@ -3637,7 +3636,7 @@ std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, // // void (^myImportedClosure)(void); // myImportedClosure = ^(void) { setGlobalInt(x + y); }; - // + // // void (^anotherClosure)(void); // anotherClosure = ^(void) { // myImportedClosure(); // import and invoke the closure @@ -3662,13 +3661,13 @@ std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, std::string Tag) { std::string StructRef = "struct " + Tag; std::string S = "static void __"; - + S += funcName; S += "_block_copy_" + utostr(i); S += "(" + StructRef; S += "*dst, " + StructRef; S += "*src) {"; - for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), + for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), E = ImportedBlockDecls.end(); I != E; ++I) { S += "_Block_object_assign((void*)&dst->"; S += (*I)->getNameAsString(); @@ -3681,13 +3680,13 @@ std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, S += "_block_dispose_" + utostr(i); S += "(" + StructRef; S += "*src) {"; - for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), + for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(), E = ImportedBlockDecls.end(); I != E; ++I) { S += "_Block_object_dispose((void*)src->"; S += (*I)->getNameAsString(); S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);"; } - S += "}\n"; + S += "}\n"; return S; } @@ -3695,20 +3694,20 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, bool hasCopyDisposeHelpers) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; - + S += " {\n struct __block_impl impl;\n"; - + if (hasCopyDisposeHelpers) S += " void *copy;\n void *dispose;\n"; - + Constructor += "(void *fp"; - + if (hasCopyDisposeHelpers) Constructor += ", void *copyHelp, void *disposeHelp"; - + if (BlockDeclRefs.size()) { // Output all "by copy" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); @@ -3717,7 +3716,7 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; - // + // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure @@ -3734,7 +3733,7 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, S += FieldName + ";\n"; } // Output all "by ref" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); @@ -3743,7 +3742,7 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; - // + // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure @@ -3753,9 +3752,9 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, S += "struct __block_impl *"; Constructor += ", void *" + ArgName; } else { - Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName, + Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName, Context->PrintingPolicy); - Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName, + Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName, Context->PrintingPolicy); Constructor += ", " + ArgName; } @@ -3769,12 +3768,12 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; Constructor += " impl.Size = sizeof("; Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n"; - + if (hasCopyDisposeHelpers) Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n"; - + // Initialize all "by copy" arguments. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); Constructor += " "; @@ -3785,7 +3784,7 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, Constructor += Name + ";\n"; } // Initialize all "by ref" arguments. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); Constructor += " "; @@ -3822,21 +3821,21 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, CollectBlockDeclRefInfo(Blocks[i]); std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i); - - std::string CI = SynthesizeBlockImpl(Blocks[i], Tag, + + std::string CI = SynthesizeBlockImpl(Blocks[i], Tag, ImportedBlockDecls.size() > 0); InsertText(FunLocStart, CI.c_str(), CI.size()); std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag); - + InsertText(FunLocStart, CF.c_str(), CF.size()); if (ImportedBlockDecls.size()) { std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag); InsertText(FunLocStart, HF.c_str(), HF.size()); } - + BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByCopyDecls.clear(); @@ -3850,7 +3849,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); const char *FuncName = FD->getNameAsCString(); - + SynthesizeBlockLiterals(FunLocStart, FuncName); } @@ -3864,7 +3863,7 @@ void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { std::string::size_type loc = 0; while ((loc = FuncName.find(":", loc)) != std::string::npos) FuncName.replace(loc, 1, "_"); - + SynthesizeBlockLiterals(FunLocStart, FuncName.c_str()); } @@ -3894,7 +3893,7 @@ void RewriteObjC::GetBlockCallExprs(Stmt *S) { else GetBlockCallExprs(*CI); } - + if (CallExpr *CE = dyn_cast(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { BlockCallExprs[dyn_cast(CE->getCallee())] = CE; @@ -3907,7 +3906,7 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) { // Navigate to relevant type information. const char *closureName = 0; const BlockPointerType *CPT = 0; - + if (const DeclRefExpr *DRE = dyn_cast(Exp->getCallee())) { closureName = DRE->getDecl()->getNameAsCString(); CPT = DRE->getType()->getAs(); @@ -3925,7 +3924,7 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) { assert(FT && "RewriteBlockClass: Bad type"); const FunctionProtoType *FTP = dyn_cast(FT); // FTP will be null for closures that don't take arguments. - + RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, SourceLocation(), &Context->Idents.get("__block_impl")); @@ -3933,11 +3932,11 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) { // Generate a funky cast. llvm::SmallVector ArgTypes; - + // Push the block argument type. ArgTypes.push_back(PtrBlock); if (FTP) { - for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), + for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), E = FTP->arg_type_end(); I && (I != E); ++I) { QualType t = *I; // Make sure we convert "t (^)(...)" to "t (*)(...)". @@ -3949,12 +3948,12 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) { } } // Now do the pointer to function cast. - QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(), + QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0); - + PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType); - - CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, + + CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, CastExpr::CK_Unknown, Exp->getCallee(), PtrBlock, SourceLocation(), @@ -3963,25 +3962,25 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) { ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), BlkCast); //PE->dump(); - + FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(), - &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0, + &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0, /*BitWidth=*/0, /*Mutable=*/true); MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), FD->getType()); - + CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, CastExpr::CK_Unknown, ME, PtrToFuncCastType, SourceLocation(), SourceLocation()); PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); - + llvm::SmallVector BlkExprs; // Add the implicit argument. BlkExprs.push_back(BlkCast); // Add the user arguments. - for (CallExpr::arg_iterator I = Exp->arg_begin(), + for (CallExpr::arg_iterator I = Exp->arg_begin(), E = Exp->arg_end(); I != E; ++I) { BlkExprs.push_back(*I); } @@ -4003,7 +4002,7 @@ void RewriteObjC::RewriteBlockCall(CallExpr *Exp) { // int main() { // __block Foo *f; // __block int i; -// +// // void (^myblock)() = ^() { // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten). // i = 77; @@ -4030,16 +4029,16 @@ void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) { // Need to avoid trying to rewrite casts contained in macros. if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) return; - + const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); - + // advance the location to startArgList. const char *argPtr = startBuf; - + while (*argPtr++ && (argPtr < endBuf)) { switch (*argPtr) { - case '^': + case '^': // Replace the '^' with '*'. LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf); ReplaceText(LocStart, 1, "*", 1); @@ -4052,31 +4051,31 @@ void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) { void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { SourceLocation DeclLoc = FD->getLocation(); unsigned parenCount = 0; - + // We have 1 or more arguments that have closure pointers. const char *startBuf = SM->getCharacterData(DeclLoc); const char *startArgList = strchr(startBuf, '('); - + assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); - + parenCount++; // advance the location to startArgList. DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf); assert((DeclLoc.isValid()) && "Invalid DeclLoc"); - + const char *argPtr = startArgList; - + while (*argPtr++ && parenCount) { switch (*argPtr) { - case '^': + case '^': // Replace the '^' with '*'. DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList); ReplaceText(DeclLoc, 1, "*", 1); break; - case '(': - parenCount++; + case '(': + parenCount++; break; - case ')': + case ')': parenCount--; break; } @@ -4095,7 +4094,7 @@ bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) { FTP = BPT->getPointeeType()->getAsFunctionProtoType(); } if (FTP) { - for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), + for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), E = FTP->arg_type_end(); I != E; ++I) if (isTopLevelBlockPointerType(*I)) return true; @@ -4107,11 +4106,11 @@ void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen) { const char *argPtr = strchr(Name, '('); assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); - + LParen = argPtr; // output the start. argPtr++; // skip past the left paren. unsigned parenCount = 1; - + while (*argPtr && parenCount) { switch (*argPtr) { case '(': parenCount++; break; @@ -4128,7 +4127,7 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (FunctionDecl *FD = dyn_cast(ND)) { RewriteBlockPointerFunctionArgs(FD); return; - } + } // Handle Variables and Typedefs. SourceLocation DeclLoc = ND->getLocation(); QualType DeclT; @@ -4138,15 +4137,15 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { DeclT = TDD->getUnderlyingType(); else if (FieldDecl *FD = dyn_cast(ND)) DeclT = FD->getType(); - else + else assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled"); - + const char *startBuf = SM->getCharacterData(DeclLoc); const char *endBuf = startBuf; // scan backward (from the decl location) for the end of the previous decl. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) startBuf--; - + // *startBuf != '^' if we are dealing with a pointer to function that // may take block argument types (which will be handled below). if (*startBuf == '^') { @@ -4171,7 +4170,7 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { return; } -void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { +void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Add initializers for any closure decl refs. GetBlockDeclRefExprs(Exp->getBody()); if (BlockDeclRefs.size()) { @@ -4196,7 +4195,7 @@ void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) { IdentifierInfo *ID = &Context->Idents.get(name); QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy); - return FunctionDecl::Create(*Context, TUDecl,SourceLocation(), + return FunctionDecl::Create(*Context, TUDecl,SourceLocation(), ID, FType, 0, FunctionDecl::Extern, false, false); } @@ -4206,7 +4205,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) { CollectBlockDeclRefInfo(Exp); std::string FuncName; - + if (CurFunctionDef) FuncName = CurFunctionDef->getNameAsString(); else if (CurMethodDef) { @@ -4217,58 +4216,58 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) { FuncName.replace(loc, 1, "_"); } else if (GlobalVarDecl) FuncName = std::string(GlobalVarDecl->getNameAsString()); - + std::string BlockNumber = utostr(Blocks.size()-1); - + std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber; std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; - + // Get a pointer to the function type so we can cast appropriately. QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0)); FunctionDecl *FD; Expr *NewRep; - + // Simulate a contructor call... FD = SynthBlockInitFunctionDecl(Tag.c_str()); DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation()); - + llvm::SmallVector InitExprs; - + // Initialize the block function. FD = SynthBlockInitFunctionDecl(Func.c_str()); DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); - CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, - CastExpr::CK_Unknown, Arg, + CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, + CastExpr::CK_Unknown, Arg, Context->VoidPtrTy, SourceLocation(), SourceLocation()); - InitExprs.push_back(castExpr); - + InitExprs.push_back(castExpr); + if (ImportedBlockDecls.size()) { std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber; FD = SynthBlockInitFunctionDecl(Buf.c_str()); Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); - castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, - CastExpr::CK_Unknown, Arg, + castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, + CastExpr::CK_Unknown, Arg, Context->VoidPtrTy, SourceLocation(), SourceLocation()); - InitExprs.push_back(castExpr); - + InitExprs.push_back(castExpr); + Buf = "__" + FuncName + "_block_dispose_" + BlockNumber; FD = SynthBlockInitFunctionDecl(Buf.c_str()); Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); - castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, - CastExpr::CK_Unknown, Arg, + castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, + CastExpr::CK_Unknown, Arg, Context->VoidPtrTy, SourceLocation(), SourceLocation()); - InitExprs.push_back(castExpr); + InitExprs.push_back(castExpr); } // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; // Output all "by copy" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { if (isObjCType((*I)->getType())) { // FIXME: Conform to ABI ([[obj retain] autorelease]). @@ -4277,34 +4276,34 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) { } else if (isTopLevelBlockPointerType((*I)->getType())) { FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); - Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, - CastExpr::CK_Unknown, Arg, - Context->VoidPtrTy, + Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, + CastExpr::CK_Unknown, Arg, + Context->VoidPtrTy, SourceLocation(), SourceLocation()); } else { FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); } - InitExprs.push_back(Exp); + InitExprs.push_back(Exp); } // Output all "by ref" declarations. - for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), + for (llvm::SmallPtrSet::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, - Context->getPointerType(Exp->getType()), + Context->getPointerType(Exp->getType()), SourceLocation()); - InitExprs.push_back(Exp); + InitExprs.push_back(Exp); } } NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(), FType, SourceLocation()); NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf, - Context->getPointerType(NewRep->getType()), + Context->getPointerType(NewRep->getType()), SourceLocation()); - NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep, + NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep, FType, SourceLocation(), SourceLocation()); BlockDeclRefs.clear(); @@ -4340,33 +4339,33 @@ void RewriteObjC::CollectPropertySetters(Stmt *S) { } Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { - if (isa(S) || isa(S) || + if (isa(S) || isa(S) || isa(S) || isa(S)) Stmts.push_back(S); else if (isa(S)) { Stmts.push_back(S); ObjCBcLabelNo.push_back(++BcLabelCount); } - + SourceRange OrigStmtRange = S->getSourceRange(); - + // Perform a bottom up rewrite of all children. for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; ++CI) if (*CI) { Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI); - if (newStmt) + if (newStmt) *CI = newStmt; } - + if (BlockExpr *BE = dyn_cast(S)) { // Rewrite the block body in place. RewriteFunctionBodyOrGlobalInitializer(BE->getBody()); - + // Now we snarf the rewritten text and stash it away for later use. std::string Str = Rewrite.getRewritenText(BE->getSourceRange()); RewrittenBlockExprs[BE] = Str; - + Stmt *blockTranscribed = SynthBlockInitExpr(BE); //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); @@ -4375,7 +4374,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // Handle specific things. if (ObjCEncodeExpr *AtEncode = dyn_cast(S)) return RewriteAtEncode(AtEncode); - + if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast(S)) return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin()); @@ -4388,7 +4387,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // Save the source range. Even if we disable the replacement, the // rewritten node will have been inserted into the tree. If the synthesized // node is at the 'end', the rewriter will fail. Consider this: - // self.errorHandler = handler ? handler : + // self.errorHandler = handler ? handler : // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; }; SourceRange SrcRange = BinOp->getSourceRange(); Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS()); @@ -4422,7 +4421,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // can be used as the setter argument. ReplaceStmt() will still 'see' // the original RHS (since we haven't altered BinOp). // - // This implies the Rewrite* routines can no longer delete the original + // This implies the Rewrite* routines can no longer delete the original // node. As a result, we now leak the original AST nodes. // return RewritePropertySetter(BinOp, dyn_cast(newStmt), SrcRange); @@ -4432,25 +4431,25 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { } if (ObjCSelectorExpr *AtSelector = dyn_cast(S)) return RewriteAtSelector(AtSelector); - + if (ObjCStringLiteral *AtString = dyn_cast(S)) return RewriteObjCStringLiteral(AtString); - + if (ObjCMessageExpr *MessExpr = dyn_cast(S)) { #if 0 // Before we rewrite it, put the original message expression in a comment. SourceLocation startLoc = MessExpr->getLocStart(); SourceLocation endLoc = MessExpr->getLocEnd(); - + const char *startBuf = SM->getCharacterData(startLoc); const char *endBuf = SM->getCharacterData(endLoc); - + std::string messString; messString += "// "; messString.append(startBuf, endBuf-startBuf+1); messString += "\n"; - - // FIXME: Missing definition of + + // FIXME: Missing definition of // InsertText(clang::SourceLocation, char const*, unsigned int). // InsertText(startLoc, messString.c_str(), messString.size()); // Tried this, but it didn't work either... @@ -4458,7 +4457,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { #endif return RewriteMessageExpr(MessExpr); } - + if (ObjCAtTryStmt *StmtTry = dyn_cast(S)) return RewriteObjCTryStmt(StmtTry); @@ -4467,13 +4466,13 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ObjCAtThrowStmt *StmtThrow = dyn_cast(S)) return RewriteObjCThrowStmt(StmtThrow); - + if (ObjCProtocolExpr *ProtocolExp = dyn_cast(S)) return RewriteObjCProtocolExpr(ProtocolExp); - - if (ObjCForCollectionStmt *StmtForCollection = + + if (ObjCForCollectionStmt *StmtForCollection = dyn_cast(S)) - return RewriteObjCForCollectionStmt(StmtForCollection, + return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtRange.getEnd()); if (BreakStmt *StmtBreakStmt = dyn_cast(S)) @@ -4481,15 +4480,15 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ContinueStmt *StmtContinueStmt = dyn_cast(S)) return RewriteContinueStmt(StmtContinueStmt); - - // Need to check for protocol refs (id

, Foo

*) in variable decls + + // Need to check for protocol refs (id

, Foo

*) in variable decls // and cast exprs. if (DeclStmt *DS = dyn_cast(S)) { // FIXME: What we're doing here is modifying the type-specifier that // precedes the first Decl. In the future the DeclGroup should have - // a separate type-specifier that we can rewrite. + // a separate type-specifier that we can rewrite. RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); - + // Blocks rewrite rules. for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { @@ -4497,26 +4496,26 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ValueDecl *ND = dyn_cast(SD)) { if (isTopLevelBlockPointerType(ND->getType())) RewriteBlockPointerDecl(ND); - else if (ND->getType()->isFunctionPointerType()) + else if (ND->getType()->isFunctionPointerType()) CheckFunctionPointerDecl(ND->getType(), ND); } if (TypedefDecl *TD = dyn_cast(SD)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); - else if (TD->getUnderlyingType()->isFunctionPointerType()) + else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); } } } - + if (CStyleCastExpr *CE = dyn_cast(S)) RewriteObjCQualifiedInterfaceTypes(CE); - - if (isa(S) || isa(S) || + + if (isa(S) || isa(S) || isa(S) || isa(S)) { assert(!Stmts.empty() && "Statement stack is empty"); - assert ((isa(Stmts.back()) || isa(Stmts.back()) || - isa(Stmts.back()) || isa(Stmts.back())) + assert ((isa(Stmts.back()) || isa(Stmts.back()) || + isa(Stmts.back()) || isa(Stmts.back())) && "Statement stack mismatch"); Stmts.pop_back(); } @@ -4560,7 +4559,7 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { if (FunctionDecl *FD = dyn_cast(D)) { if (FD->isOverloadedOperator()) return; - + // Since function prototypes don't have ParmDecl's, we check the function // prototype. This enables us to rewrite function declarations and // definitions using the same code. @@ -4583,7 +4582,7 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { // and any copy/dispose helper functions. InsertBlockLiteralsWithinFunction(FD); CurFunctionDef = 0; - } + } return; } if (ObjCMethodDecl *MD = dyn_cast(D)) { @@ -4631,7 +4630,7 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { delete PropParentMap; PropParentMap = 0; } - SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), + SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getNameAsCString()); GlobalVarDecl = 0; @@ -4645,13 +4644,13 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { if (TypedefDecl *TD = dyn_cast(D)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); - else if (TD->getUnderlyingType()->isFunctionPointerType()) + else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); return; } if (RecordDecl *RD = dyn_cast(D)) { if (RD->isDefinition()) { - for (RecordDecl::field_iterator i = RD->field_begin(), + for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i) { FieldDecl *FD = *i; if (isTopLevelBlockPointerType(FD->getType())) @@ -4665,29 +4664,29 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { void RewriteObjC::HandleTranslationUnit(ASTContext &C) { // Get the top-level buffer that this corresponds to. - + // Rewrite tabs if we care. //RewriteTabs(); - + if (Diags.hasErrorOccurred()) return; - + RewriteInclude(); - + // Here's a great place to add any extra declarations that may be needed. // Write out meta data for each @protocol(). - for (llvm::SmallPtrSet::iterator I = ProtocolExprDecls.begin(), + for (llvm::SmallPtrSet::iterator I = ProtocolExprDecls.begin(), E = ProtocolExprDecls.end(); I != E; ++I) RewriteObjCProtocolMetaData(*I, "", "", Preamble); - InsertText(SM->getLocForStartOfFile(MainFileID), + InsertText(SM->getLocForStartOfFile(MainFileID), Preamble.c_str(), Preamble.size(), false); if (ClassImplementation.size() || CategoryImplementation.size()) RewriteImplementations(); // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. - if (const RewriteBuffer *RewriteBuf = + if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { //printf("Changed:\n"); *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); diff --git a/clang/lib/Frontend/RewriteTest.cpp b/clang/lib/Frontend/RewriteTest.cpp index f9eb58f86740dbfe7c17c6a34c78fbe00662e161..0414678fb6181a0ecf6b3b08d733bc88a3dddb87 100644 --- a/clang/lib/Frontend/RewriteTest.cpp +++ b/clang/lib/Frontend/RewriteTest.cpp @@ -30,8 +30,8 @@ void clang::DoRewriteTest(Preprocessor &PP, llvm::raw_ostream* OS) { Rewriter.AddTokenBefore(I, ""); Rewriter.AddTokenAfter(I, ""); } - - + + // Print out the output. for (TokenRewriter::token_iterator I = Rewriter.token_begin(), E = Rewriter.token_end(); I != E; ++I) diff --git a/clang/lib/Frontend/StmtXML.cpp b/clang/lib/Frontend/StmtXML.cpp index b6d04810bfa18e0af273dd49f6785d7b9b018754..4a3c0bf1c60f019c3732dc0d32a1938ccb69ef46 100644 --- a/clang/lib/Frontend/StmtXML.cpp +++ b/clang/lib/Frontend/StmtXML.cpp @@ -32,25 +32,18 @@ namespace { //static const char *getOpcodeStr(BinaryOperator::Opcode Op); - void addSpecialAttribute(const char* pName, StringLiteral* Str) - { + void addSpecialAttribute(const char* pName, StringLiteral* Str) { Doc.addAttribute(pName, Doc.escapeString(Str->getStrData(), Str->getByteLength())); } - void addSpecialAttribute(const char* pName, SizeOfAlignOfExpr* S) - { + void addSpecialAttribute(const char* pName, SizeOfAlignOfExpr* S) { if (S->isArgumentType()) - { Doc.addAttribute(pName, S->getArgumentType()); - } } - void addSpecialAttribute(const char* pName, CXXTypeidExpr* S) - { + void addSpecialAttribute(const char* pName, CXXTypeidExpr* S) { if (S->isTypeOperand()) - { Doc.addAttribute(pName, S->getTypeOperand()); - } } @@ -58,29 +51,21 @@ namespace { StmtXML(DocumentXML& doc) : Doc(doc) { } - + void DumpSubTree(Stmt *S) { - if (S) - { + if (S) { Visit(S); - if (DeclStmt* DS = dyn_cast(S)) - { - for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); - DI != DE; ++DI) - { + if (DeclStmt* DS = dyn_cast(S)) { + for (DeclStmt::decl_iterator DI = DS->decl_begin(), + DE = DS->decl_end(); DI != DE; ++DI) { Doc.PrintDecl(*DI); } - } - else - { + } else { if (CXXConditionDeclExpr* CCDE = dyn_cast(S)) - { Doc.PrintDecl(CCDE->getVarDecl()); - } - for (Stmt::child_iterator i = S->child_begin(), e = S->child_end(); i != e; ++i) - { + for (Stmt::child_iterator i = S->child_begin(), e = S->child_end(); + i != e; ++i) DumpSubTree(*i); - } } Doc.toParent(); } else { @@ -93,12 +78,12 @@ namespace { void Visit##CLASS(CLASS* S) \ { \ typedef CLASS tStmtType; \ - Doc.addSubNode(NAME); + Doc.addSubNode(NAME); -#define ATTRIBUTE_XML( FN, NAME ) Doc.addAttribute(NAME, S->FN); +#define ATTRIBUTE_XML( FN, NAME ) Doc.addAttribute(NAME, S->FN); #define TYPE_ATTRIBUTE_XML( FN ) ATTRIBUTE_XML(FN, "type") -#define ATTRIBUTE_OPT_XML( FN, NAME ) Doc.addAttributeOptional(NAME, S->FN); -#define ATTRIBUTE_SPECIAL_XML( FN, NAME ) addSpecialAttribute(NAME, S); +#define ATTRIBUTE_OPT_XML( FN, NAME ) Doc.addAttributeOptional(NAME, S->FN); +#define ATTRIBUTE_SPECIAL_XML( FN, NAME ) addSpecialAttribute(NAME, S); #define ATTRIBUTE_FILE_LOCATION_XML Doc.addLocationRange(S->getSourceRange()); @@ -107,14 +92,14 @@ namespace { const char* pAttributeName = NAME; \ const bool optional = false; \ switch (S->FN) { \ - default: assert(0 && "unknown enum value"); + default: assert(0 && "unknown enum value"); #define ATTRIBUTE_ENUM_OPT_XML( FN, NAME ) \ { \ const char* pAttributeName = NAME; \ const bool optional = true; \ switch (S->FN) { \ - default: assert(0 && "unknown enum value"); + default: assert(0 && "unknown enum value"); #define ENUM_XML( VALUE, NAME ) case VALUE: if ((!optional) || NAME[0]) Doc.addAttribute(pAttributeName, NAME); break; #define END_ENUM_XML } } @@ -133,7 +118,7 @@ namespace { void VisitDeclStmt(DeclStmt *Node); void VisitLabelStmt(LabelStmt *Node); void VisitGotoStmt(GotoStmt *Node); - + // Exprs void VisitExpr(Expr *Node); void VisitDeclRefExpr(DeclRefExpr *Node); @@ -156,7 +141,7 @@ namespace { void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node); void VisitCXXThisExpr(CXXThisExpr *Node); void VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node); - + // ObjC void VisitObjCEncodeExpr(ObjCEncodeExpr *Node); void VisitObjCMessageExpr(ObjCMessageExpr* Node); @@ -175,27 +160,22 @@ namespace { // Stmt printing methods. //===----------------------------------------------------------------------===// #if (0) -void StmtXML::VisitStmt(Stmt *Node) -{ +void StmtXML::VisitStmt(Stmt *Node) { // nothing special to do } -void StmtXML::VisitDeclStmt(DeclStmt *Node) -{ +void StmtXML::VisitDeclStmt(DeclStmt *Node) { for (DeclStmt::decl_iterator DI = Node->decl_begin(), DE = Node->decl_end(); - DI != DE; ++DI) - { + DI != DE; ++DI) { Doc.PrintDecl(*DI); } } -void StmtXML::VisitLabelStmt(LabelStmt *Node) -{ +void StmtXML::VisitLabelStmt(LabelStmt *Node) { Doc.addAttribute("name", Node->getName()); } -void StmtXML::VisitGotoStmt(GotoStmt *Node) -{ +void StmtXML::VisitGotoStmt(GotoStmt *Node) { Doc.addAttribute("name", Node->getLabel()->getName()); } @@ -336,9 +316,7 @@ void StmtXML::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *Node) { Doc.addAttribute("is_sizeof", Node->isSizeOf() ? "sizeof" : "alignof"); Doc.addAttribute("is_type", Node->isArgumentType() ? "1" : "0"); if (Node->isArgumentType()) - { DumpTypeExpr(Node->getArgumentType()); - } } void StmtXML::VisitMemberExpr(MemberExpr *Node) { @@ -415,7 +393,7 @@ void StmtXML::VisitObjCMessageExpr(ObjCMessageExpr* Node) { DumpExpr(Node); Doc.addAttribute("selector", Node->getSelector().getAsString()); IdentifierInfo* clsName = Node->getClassName(); - if (clsName) + if (clsName) Doc.addAttribute("class", clsName->getName()); } diff --git a/clang/lib/Frontend/TextDiagnosticBuffer.cpp b/clang/lib/Frontend/TextDiagnosticBuffer.cpp index a4518ee7e6896cc6309d2081b9d9ac3f51993541..34bc3c796aa8313ad324098f2832ceb8a4810c0c 100644 --- a/clang/lib/Frontend/TextDiagnosticBuffer.cpp +++ b/clang/lib/Frontend/TextDiagnosticBuffer.cpp @@ -17,7 +17,7 @@ using namespace clang; /// HandleDiagnostic - Store the errors, warnings, and notes that are /// reported. -/// +/// void TextDiagnosticBuffer::HandleDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info) { llvm::SmallString<100> StrC; diff --git a/clang/lib/Frontend/TextDiagnosticPrinter.cpp b/clang/lib/Frontend/TextDiagnosticPrinter.cpp index 973a47f7794a27915d69be7d4f45a95d0e6ae059..63d9a50b368bb7b60039a99fb0cd5e4f1abb2df8 100644 --- a/clang/lib/Frontend/TextDiagnosticPrinter.cpp +++ b/clang/lib/Frontend/TextDiagnosticPrinter.cpp @@ -436,7 +436,7 @@ void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc, /// greater than or equal to Idx or, if no such character exists, /// returns the end of the string. static unsigned skipWhitespace(unsigned Idx, - const llvm::SmallVectorImpl &Str, + const llvm::SmallVectorImpl &Str, unsigned Length) { while (Idx < Length && isspace(Str[Idx])) ++Idx; @@ -536,7 +536,7 @@ unsigned findEndOfWord(unsigned Start, /// \returns true if word-wrapping was required, or false if the /// string fit on the first line. static bool PrintWordWrapped(llvm::raw_ostream &OS, - const llvm::SmallVectorImpl &Str, + const llvm::SmallVectorImpl &Str, unsigned Columns, unsigned Column = 0, unsigned Indentation = WordWrapIndentation) { diff --git a/clang/lib/Frontend/TypeXML.cpp b/clang/lib/Frontend/TypeXML.cpp index f32fbbd2413ba03bc88f1f312ccff308ff02ab69..8bd05443a7fef8ce941bcd1d1755739fe380cc85 100644 --- a/clang/lib/Frontend/TypeXML.cpp +++ b/clang/lib/Frontend/TypeXML.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements the XML document class, which provides the means to +// This file implements the XML document class, which provides the means to // dump out the AST in a XML form that exposes type details and other fields. // //===----------------------------------------------------------------------===// @@ -21,38 +21,36 @@ namespace clang { namespace XML { namespace { -//--------------------------------------------------------- -class TypeWriter : public TypeVisitor -{ +//--------------------------------------------------------- +class TypeWriter : public TypeVisitor { DocumentXML& Doc; public: TypeWriter(DocumentXML& doc) : Doc(doc) {} #define NODE_XML( CLASS, NAME ) \ - void Visit##CLASS(CLASS* T) \ - { \ - Doc.addSubNode(NAME); + void Visit##CLASS(CLASS* T) { \ + Doc.addSubNode(NAME); #define ID_ATTRIBUTE_XML // done by the Document class itself -#define ATTRIBUTE_XML( FN, NAME ) Doc.addAttribute(NAME, T->FN); +#define ATTRIBUTE_XML( FN, NAME ) Doc.addAttribute(NAME, T->FN); #define TYPE_ATTRIBUTE_XML( FN ) ATTRIBUTE_XML(FN, "type") #define CONTEXT_ATTRIBUTE_XML( FN ) ATTRIBUTE_XML(FN, "context") -#define ATTRIBUTE_OPT_XML( FN, NAME ) Doc.addAttributeOptional(NAME, T->FN); +#define ATTRIBUTE_OPT_XML( FN, NAME ) Doc.addAttributeOptional(NAME, T->FN); #define ATTRIBUTE_ENUM_XML( FN, NAME ) \ { \ const char* pAttributeName = NAME; \ const bool optional = false; \ switch (T->FN) { \ - default: assert(0 && "unknown enum value"); + default: assert(0 && "unknown enum value"); #define ATTRIBUTE_ENUM_OPT_XML( FN, NAME ) \ { \ const char* pAttributeName = NAME; \ const bool optional = true; \ switch (T->FN) { \ - default: assert(0 && "unknown enum value"); + default: assert(0 && "unknown enum value"); #define ENUM_XML( VALUE, NAME ) case VALUE: if ((!optional) || NAME[0]) Doc.addAttribute(pAttributeName, NAME); break; #define END_ENUM_XML } } @@ -62,22 +60,19 @@ public: }; -//--------------------------------------------------------- +//--------------------------------------------------------- } // anon clang } // NS XML -//--------------------------------------------------------- -class DocumentXML::TypeAdder : public TypeVisitor -{ +//--------------------------------------------------------- +class DocumentXML::TypeAdder : public TypeVisitor { DocumentXML& Doc; - void addIfType(const Type* pType) - { + void addIfType(const Type* pType) { Doc.addTypeRecursively(pType); } - void addIfType(const QualType& pType) - { + void addIfType(const QualType& pType) { Doc.addTypeRecursively(pType); } @@ -88,40 +83,37 @@ public: #define NODE_XML( CLASS, NAME ) \ void Visit##CLASS(CLASS* T) \ - { - -#define ID_ATTRIBUTE_XML -#define TYPE_ATTRIBUTE_XML( FN ) Doc.addTypeRecursively(T->FN); -#define CONTEXT_ATTRIBUTE_XML( FN ) -#define ATTRIBUTE_XML( FN, NAME ) addIfType(T->FN); -#define ATTRIBUTE_OPT_XML( FN, NAME ) -#define ATTRIBUTE_ENUM_XML( FN, NAME ) -#define ATTRIBUTE_ENUM_OPT_XML( FN, NAME ) -#define ENUM_XML( VALUE, NAME ) -#define END_ENUM_XML + { + +#define ID_ATTRIBUTE_XML +#define TYPE_ATTRIBUTE_XML( FN ) Doc.addTypeRecursively(T->FN); +#define CONTEXT_ATTRIBUTE_XML( FN ) +#define ATTRIBUTE_XML( FN, NAME ) addIfType(T->FN); +#define ATTRIBUTE_OPT_XML( FN, NAME ) +#define ATTRIBUTE_ENUM_XML( FN, NAME ) +#define ATTRIBUTE_ENUM_OPT_XML( FN, NAME ) +#define ENUM_XML( VALUE, NAME ) +#define END_ENUM_XML #define END_NODE_XML } #include "clang/Frontend/TypeXML.def" }; -//--------------------------------------------------------- -void DocumentXML::addParentTypes(const Type* pType) -{ +//--------------------------------------------------------- +void DocumentXML::addParentTypes(const Type* pType) { TypeAdder(*this).Visit(const_cast(pType)); } -//--------------------------------------------------------- -void DocumentXML::writeTypeToXML(const Type* pType) -{ +//--------------------------------------------------------- +void DocumentXML::writeTypeToXML(const Type* pType) { XML::TypeWriter(*this).Visit(const_cast(pType)); } -//--------------------------------------------------------- -void DocumentXML::writeTypeToXML(const QualType& pType) -{ +//--------------------------------------------------------- +void DocumentXML::writeTypeToXML(const QualType& pType) { XML::TypeWriter(*this).VisitQualType(const_cast(&pType)); } -//--------------------------------------------------------- +//--------------------------------------------------------- } // NS clang diff --git a/clang/lib/Frontend/Warnings.cpp b/clang/lib/Frontend/Warnings.cpp index 87178e93b4473917e9320f184954fac7fb74c94e..7b01b0fb74168d67bd04c28294197e7663319291 100644 --- a/clang/lib/Frontend/Warnings.cpp +++ b/clang/lib/Frontend/Warnings.cpp @@ -47,7 +47,7 @@ bool clang::ProcessWarningOptions(Diagnostic &Diags, Diags.setExtensionHandlingBehavior(Diagnostic::Ext_Warn); else Diags.setExtensionHandlingBehavior(Diagnostic::Ext_Ignore); - + // FIXME: -Wfatal-errors / -Wfatal-errors=foo for (unsigned i = 0, e = Warnings.size(); i != e; ++i) { @@ -55,7 +55,7 @@ bool clang::ProcessWarningOptions(Diagnostic &Diags, const char *OptStart = &Opt[0]; const char *OptEnd = OptStart+Opt.size(); assert(*OptEnd == 0 && "Expect null termination for lower-bound search"); - + // Check to see if this warning starts with "no-", if so, this is a negative // form of the option. bool isPositive = true; @@ -74,7 +74,7 @@ bool clang::ProcessWarningOptions(Diagnostic &Diags, Diags.setSuppressSystemWarnings(!isPositive); continue; } - + // -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 (OptEnd-OptStart >= 5 && memcmp(OptStart, "error", 5) == 0) { @@ -88,21 +88,21 @@ bool clang::ProcessWarningOptions(Diagnostic &Diags, } Specifier = OptStart+6; } - + if (Specifier == 0) { Diags.setWarningsAsErrors(isPositive); continue; } - + // -Werror=foo maps foo to Error, -Wno-error=foo maps it to Warning. Mapping = isPositive ? diag::MAP_ERROR : diag::MAP_WARNING_NO_WERROR; OptStart = Specifier; } - + if (Diags.setDiagnosticGroupMapping(OptStart, Mapping)) Diags.Report(FullSourceLoc(), diag::warn_unknown_warning_option) << ("-W" + Opt); } - + return false; } diff --git a/clang/lib/Headers/stdarg.h b/clang/lib/Headers/stdarg.h index c436ced97c5faeb8da32f290e31b6d5cb8f9d561..bbbaff93e242ec90567fb2c64bf8470cc1473816 100644 --- a/clang/lib/Headers/stdarg.h +++ b/clang/lib/Headers/stdarg.h @@ -34,7 +34,7 @@ typedef __builtin_va_list va_list; /* GCC always defines __va_copy, but does not define va_copy unless in c99 mode * or -ansi is not specified, since it was not part of C90. */ -#define __va_copy(d,s) __builtin_va_copy(d,s) +#define __va_copy(d,s) __builtin_va_copy(d,s) #if __STDC_VERSION__ >= 199900L || !defined(__STRICT_ANSI__) #define va_copy(dest, src) __builtin_va_copy(dest, src) diff --git a/clang/lib/Index/ASTLocation.cpp b/clang/lib/Index/ASTLocation.cpp index f010a2bcc8404f1dc60260066d5a68c1d9bfdbf7..d6f5cc7cfbaec851829b44b944d3d8474e95c3e3 100644 --- a/clang/lib/Index/ASTLocation.cpp +++ b/clang/lib/Index/ASTLocation.cpp @@ -32,7 +32,7 @@ static Decl *getDeclFromExpr(Stmt *E) { return getDeclFromExpr(CE->getCallee()); if (CastExpr *CE = dyn_cast(E)) return getDeclFromExpr(CE->getSubExpr()); - + return 0; } @@ -41,7 +41,7 @@ Decl *ASTLocation::getReferencedDecl() { return 0; if (isDecl()) return getDecl(); - + assert(getStmt()); return getDeclFromExpr(getStmt()); } @@ -49,17 +49,17 @@ Decl *ASTLocation::getReferencedDecl() { static bool isContainedInStatement(Stmt *Node, Stmt *Parent) { assert(Node && Parent && "Passed null Node or Parent"); - + if (Node == Parent) return true; - + for (Stmt::child_iterator I = Parent->child_begin(), E = Parent->child_end(); I != E; ++I) { if (*I) if (isContainedInStatement(Node, *I)) return true; } - + return false; } @@ -76,7 +76,7 @@ Decl *ASTLocation::FindImmediateParent(Decl *D, Stmt *Node) { if (FunctionDecl *FD = dyn_cast(D)) { if (!FD->isThisDeclarationADefinition()) return 0; - + for (DeclContext::decl_iterator I = FD->decls_begin(), E = FD->decls_end(); I != E; ++I) { Decl *Child = FindImmediateParent(*I, Node); @@ -138,7 +138,7 @@ void ASTLocation::print(llvm::raw_ostream &OS) const { OS << "[Decl: " << getDecl()->getDeclKindName() << " "; if (const NamedDecl *ND = dyn_cast(getDecl())) OS << ND->getNameAsString(); - + if (getStmt()) { ASTContext &Ctx = getDecl()->getASTContext(); OS << " | Stmt: " << getStmt()->getStmtClassName() << " "; @@ -146,7 +146,7 @@ void ASTLocation::print(llvm::raw_ostream &OS) const { } OS << "] <"; - + SourceRange Range = getSourceRange(); SourceManager &SourceMgr = getDecl()->getASTContext().getSourceManager(); Range.getBegin().print(OS, SourceMgr); diff --git a/clang/lib/Index/Analyzer.cpp b/clang/lib/Index/Analyzer.cpp index 1dd2178ad4e7a10df94731dab589448e14c5a1dc..cda2c505fd8b07ec5ae03b82ee01e3e988b3379a 100644 --- a/clang/lib/Index/Analyzer.cpp +++ b/clang/lib/Index/Analyzer.cpp @@ -36,11 +36,11 @@ namespace { class VISIBILITY_HIDDEN DeclEntityAnalyzer : public TranslationUnitHandler { Entity Ent; TULocationHandler &TULocHandler; - + public: DeclEntityAnalyzer(Entity ent, TULocationHandler &handler) : Ent(ent), TULocHandler(handler) { } - + virtual void Handle(TranslationUnit *TU) { assert(TU && "Passed null translation unit"); @@ -60,11 +60,11 @@ public: class VISIBILITY_HIDDEN RefEntityAnalyzer : public TranslationUnitHandler { Entity Ent; TULocationHandler &TULocHandler; - + public: RefEntityAnalyzer(Entity ent, TULocationHandler &handler) : Ent(ent), TULocHandler(handler) { } - + virtual void Handle(TranslationUnit *TU) { assert(TU && "Passed null translation unit"); @@ -115,12 +115,12 @@ public: IFaceEnt = Entity::get(IFD, Prog); GlobSel = GlobalSelector::get(MD->getSelector(), Prog); IsInstanceMethod = MD->isInstanceMethod(); - + for (ObjCInterfaceDecl *Cls = IFD->getSuperClass(); Cls; Cls = Cls->getSuperClass()) HierarchyEntities.insert(Entity::get(Cls, Prog)); } - + virtual void Handle(TranslationUnit *TU) { assert(TU && "Passed null translation unit"); @@ -150,7 +150,7 @@ public: // FIXME: Finding @selector references should be through another Analyzer // method, like FindSelectors. if (isa(ASTLoc.getStmt())) - return false; + return false; ObjCInterfaceDecl *MsgD = 0; ObjCMessageExpr *Msg = cast(ASTLoc.getStmt()); @@ -181,7 +181,7 @@ public: MsgD = Msg->getClassInfo().first; // FIXME: Case when we only have an identifier. - assert(MsgD && "Identifier only"); + assert(MsgD && "Identifier only"); } assert(MsgD); @@ -233,7 +233,7 @@ class VISIBILITY_HIDDEN MessageAnalyzer : public TranslationUnitHandler { /// \brief Super classes of the ObjCInterface. typedef llvm::SmallSet EntitiesSetTy; EntitiesSetTy HierarchyEntities; - + /// \brief The interface in the message interface hierarchy that "intercepts" /// the selector. Entity ReceiverIFaceEnt; @@ -254,7 +254,7 @@ public: CanBeClassMethod = true; MsgD = Msg->getClassInfo().first; // FIXME: Case when we only have an identifier. - assert(MsgD && "Identifier only"); + assert(MsgD && "Identifier only"); break; } @@ -276,7 +276,7 @@ public: CanBeInstanceMethod = true; break; } - + assert(CanBeInstanceMethod || CanBeClassMethod); Selector sel = Msg->getSelector(); @@ -304,7 +304,7 @@ public: break; } } - + if (isReceiver) { ReceiverIFaceEnt = Entity::get(Cls, Prog); break; @@ -312,7 +312,7 @@ public: } } } - + virtual void Handle(TranslationUnit *TU) { assert(TU && "Passed null translation unit"); ASTContext &Ctx = TU->getASTContext(); @@ -406,7 +406,7 @@ void Analyzer::FindDeclarations(Decl *D, TULocationHandler &Handler) { Entity Ent = Entity::get(D, Prog); if (Ent.isInvalid()) return; - + DeclEntityAnalyzer DEA(Ent, Handler); Idxer.GetTranslationUnitsFor(Ent, DEA); } @@ -423,7 +423,7 @@ void Analyzer::FindReferences(Decl *D, TULocationHandler &Handler) { Entity Ent = Entity::get(D, Prog); if (Ent.isInvalid()) return; - + RefEntityAnalyzer REA(Ent, Handler); Idxer.GetTranslationUnitsFor(Ent, REA); } diff --git a/clang/lib/Index/DeclReferenceMap.cpp b/clang/lib/Index/DeclReferenceMap.cpp index 1e6ae21a6467a29b0e28f75cce0978bca7eb637d..0aee2a40ecd1f2e1f27232f1d6e4cff36da98fda 100644 --- a/clang/lib/Index/DeclReferenceMap.cpp +++ b/clang/lib/Index/DeclReferenceMap.cpp @@ -63,16 +63,16 @@ DeclReferenceMap::DeclReferenceMap(ASTContext &Ctx) { DeclReferenceMap::astlocation_iterator DeclReferenceMap::refs_begin(NamedDecl *D) const { NamedDecl *Prim = cast(D->getCanonicalDecl()); - return astlocation_iterator(Map.lower_bound(Prim)); + return astlocation_iterator(Map.lower_bound(Prim)); } DeclReferenceMap::astlocation_iterator DeclReferenceMap::refs_end(NamedDecl *D) const { NamedDecl *Prim = cast(D->getCanonicalDecl()); - return astlocation_iterator(Map.upper_bound(Prim)); + return astlocation_iterator(Map.upper_bound(Prim)); } bool DeclReferenceMap::refs_empty(NamedDecl *D) const { NamedDecl *Prim = cast(D->getCanonicalDecl()); - return refs_begin(Prim) == refs_end(Prim); + return refs_begin(Prim) == refs_end(Prim); } diff --git a/clang/lib/Index/Entity.cpp b/clang/lib/Index/Entity.cpp index 245fc9a5551a9cf2691b85be700f59ade5c3d933..77d7a84da4db71a863dd20f3f64e84bb75ed89fd 100644 --- a/clang/lib/Index/Entity.cpp +++ b/clang/lib/Index/Entity.cpp @@ -41,10 +41,10 @@ class EntityGetter : public DeclVisitor { public: EntityGetter(Program &prog, ProgramImpl &progImpl) : Prog(prog), ProgImpl(progImpl) { } - + Entity VisitNamedDecl(NamedDecl *D); Entity VisitVarDecl(VarDecl *D); - Entity VisitFunctionDecl(FunctionDecl *D); + Entity VisitFunctionDecl(FunctionDecl *D); }; } @@ -80,12 +80,12 @@ Entity EntityGetter::VisitNamedDecl(NamedDecl *D) { // Treats other DeclarationNames as internal Decls for now.. if (LocalSel.isNull()) return Entity(D); - + Selector GlobSel = (uintptr_t)GlobalSelector::get(LocalSel, Prog).getAsOpaquePtr(); GlobName = DeclarationName(GlobSel); } - + assert(GlobName); unsigned IdNS = D->getIdentifierNamespace(); @@ -105,7 +105,7 @@ Entity EntityGetter::VisitNamedDecl(NamedDecl *D) { EntityImpl *New = new (Buf) EntityImpl(Parent, GlobName, IdNS, isObjCInstanceMethod); Entities.InsertNode(New, InsertPos); - + return Entity(New); } @@ -113,7 +113,7 @@ Entity EntityGetter::VisitVarDecl(VarDecl *D) { // If it's static it cannot be referred to by another translation unit. if (D->getStorageClass() == VarDecl::Static) return Entity(D); - + return VisitNamedDecl(D); } @@ -121,7 +121,7 @@ Entity EntityGetter::VisitFunctionDecl(FunctionDecl *D) { // If it's static it cannot be refered to by another translation unit. if (D->getStorageClass() == FunctionDecl::Static) return Entity(D); - + return VisitNamedDecl(D); } @@ -188,18 +188,18 @@ Entity::Entity(Decl *D) : Val(D->getCanonicalDecl()) { } Decl *Entity::getDecl(ASTContext &AST) const { if (isInvalid()) return 0; - + if (Decl *D = Val.dyn_cast()) // Check that the passed AST is actually the one that this Decl belongs to. return (&D->getASTContext() == &AST) ? D : 0; - + return Val.get()->getDecl(AST); } std::string Entity::getPrintableName() const { if (isInvalid()) return "<< Invalid >>"; - + if (Decl *D = Val.dyn_cast()) { if (NamedDecl *ND = dyn_cast(D)) return ND->getNameAsString(); @@ -219,7 +219,7 @@ Entity Entity::get(Decl *D, Program &Prog) { return EntityImpl::get(D, Prog, ProgImpl); } -unsigned +unsigned llvm::DenseMapInfo::getHashValue(Entity E) { return DenseMapInfo::getHashValue(E.getAsOpaquePtr()); } diff --git a/clang/lib/Index/EntityImpl.h b/clang/lib/Index/EntityImpl.h index b4a883a3bf8da793c975b068b9816fa2e210cd97..cbce934bf7777709efca6ac3f007fff5a1510ae4 100644 --- a/clang/lib/Index/EntityImpl.h +++ b/clang/lib/Index/EntityImpl.h @@ -30,7 +30,7 @@ class EntityImpl : public llvm::FoldingSetNode { /// \brief Identifier namespace. unsigned IdNS; - + /// \brief If Name is a selector, this keeps track whether it's for an /// instance method. bool IsObjCInstanceMethod; @@ -47,7 +47,7 @@ public: /// \brief Get an Entity associated with the given Decl. /// \returns Null if an Entity cannot refer to this Decl. static Entity get(Decl *D, Program &Prog, ProgramImpl &ProgImpl); - + std::string getPrintableName(); void Profile(llvm::FoldingSetNodeID &ID) const { diff --git a/clang/lib/Index/GlobalSelector.cpp b/clang/lib/Index/GlobalSelector.cpp index a1ec929901b544d564be3a0b20581f9b2d712913..f3ec41d44ffeb8b395fbf30aa32bd34309e4140e 100644 --- a/clang/lib/Index/GlobalSelector.cpp +++ b/clang/lib/Index/GlobalSelector.cpp @@ -41,7 +41,7 @@ Selector GlobalSelector::getSelector(ASTContext &AST) const { std::string GlobalSelector::getPrintableName() const { if (isInvalid()) return "<< Invalid >>"; - + Selector GlobSel = Selector(reinterpret_cast(Val)); return GlobSel.getAsString(); } @@ -67,7 +67,7 @@ GlobalSelector GlobalSelector::get(Selector Sel, Program &Prog) { return GlobalSelector(GlobSel.getAsOpaquePtr()); } -unsigned +unsigned llvm::DenseMapInfo::getHashValue(GlobalSelector Sel) { return DenseMapInfo::getHashValue(Sel.getAsOpaquePtr()); } diff --git a/clang/lib/Index/Indexer.cpp b/clang/lib/Index/Indexer.cpp index 75dfbd584cc47a393a9d6a1d4a428d00014fd3d5..57bfc5b4fbfd2afa6386a668d1f4039f283786eb 100644 --- a/clang/lib/Index/Indexer.cpp +++ b/clang/lib/Index/Indexer.cpp @@ -25,7 +25,7 @@ namespace { class EntityIndexer : public EntityHandler { TranslationUnit *TU; Indexer::MapTy ⤅ - + public: EntityIndexer(TranslationUnit *tu, Indexer::MapTy &map) : TU(tu), Map(map) { } @@ -64,7 +64,7 @@ void Indexer::IndexAST(TranslationUnit *TU) { CtxTUMap[&Ctx] = TU; EntityIndexer Idx(TU, Map); Prog.FindEntities(Ctx, Idx); - + SelectorIndexer SelIdx(Prog, TU, SelMap); SelIdx.Visit(Ctx.getTranslationUnitDecl()); } @@ -84,7 +84,7 @@ void Indexer::GetTranslationUnitsFor(Entity Ent, MapTy::iterator I = Map.find(Ent); if (I == Map.end()) return; - + TUSetTy &Set = I->second; for (TUSetTy::iterator I = Set.begin(), E = Set.end(); I != E; ++I) Handler.Handle(*I); @@ -97,7 +97,7 @@ void Indexer::GetTranslationUnitsFor(GlobalSelector Sel, SelMapTy::iterator I = SelMap.find(Sel); if (I == SelMap.end()) return; - + TUSetTy &Set = I->second; for (TUSetTy::iterator I = Set.begin(), E = Set.end(); I != E; ++I) Handler.Handle(*I); diff --git a/clang/lib/Index/ProgramImpl.h b/clang/lib/Index/ProgramImpl.h index 1fbff9b325606db333d3e9f98657fc4a227cde43..57b9ce3115e908b65866d6b1e2b639d7857bcf52 100644 --- a/clang/lib/Index/ProgramImpl.h +++ b/clang/lib/Index/ProgramImpl.h @@ -30,16 +30,16 @@ public: private: EntitySetTy Entities; llvm::BumpPtrAllocator BumpAlloc; - + IdentifierTable Identifiers; SelectorTable Selectors; ProgramImpl(const ProgramImpl&); // do not implement ProgramImpl &operator=(const ProgramImpl &); // do not implement - + public: ProgramImpl() : Identifiers(LangOptions()) { } - + EntitySetTy &getEntities() { return Entities; } IdentifierTable &getIdents() { return Identifiers; } SelectorTable &getSelectors() { return Selectors; } diff --git a/clang/lib/Index/ResolveLocation.cpp b/clang/lib/Index/ResolveLocation.cpp index ce8512ddf393e47a37ec9743f7bcad26e03e1edf..281f4d9df12b8305a4f65a35d4a281d3bf14f49d 100644 --- a/clang/lib/Index/ResolveLocation.cpp +++ b/clang/lib/Index/ResolveLocation.cpp @@ -119,7 +119,7 @@ StmtLocResolver::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) { Nodes.push_back(Node->getArg(0)); Nodes.push_back(Node->getCallee()); Nodes.push_back(Node->getArg(1)); - + for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { RangePos RP = CheckRange(Nodes[i]); if (RP == AfterLoc) @@ -201,9 +201,9 @@ ASTLocation DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) { if (RP == ContainsLoc) return Visit(*I); } - + // We didn't find the location in the parameters and we didn't get passed it. - + if (!D->isThisDeclarationADefinition()) return ASTLocation(D); @@ -214,7 +214,7 @@ ASTLocation DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) { I = D->decls_begin(), E = D->decls_end(); I != E; ++I) { if (isa(*I)) continue; // We already searched through the parameters. - + RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; @@ -223,7 +223,7 @@ ASTLocation DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) { } // We didn't find a declaration that corresponds to the source location. - + // Finally, search through the body of the function. Stmt *Body = D->getBody(); assert(Body && "Expected definition"); @@ -325,10 +325,10 @@ LocResolverBase::RangePos LocResolverBase::CheckRange(SourceRange Range) { Ctx.getLangOptions()); Range.setEnd(Range.getEnd().getFileLocWithOffset(TokSize-1)); - SourceManager &SourceMgr = Ctx.getSourceManager(); + SourceManager &SourceMgr = Ctx.getSourceManager(); if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc)) return BeforeLoc; - + if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin())) return AfterLoc; @@ -367,6 +367,6 @@ void LocResolverBase::print(Stmt *Node) { ASTLocation idx::ResolveLocationInAST(ASTContext &Ctx, SourceLocation Loc) { if (Loc.isInvalid()) return ASTLocation(); - + return DeclLocResolver(Ctx, Loc).Visit(Ctx.getTranslationUnitDecl()); } diff --git a/clang/lib/Lex/HeaderMap.cpp b/clang/lib/Lex/HeaderMap.cpp index 4c8b70eb782130ee360d7cfdfdd6414619c870eb..c9a10dc02707cb73ded3309a92fd9d65dcb5c394 100644 --- a/clang/lib/Lex/HeaderMap.cpp +++ b/clang/lib/Lex/HeaderMap.cpp @@ -28,8 +28,8 @@ using namespace clang; enum { HMAP_HeaderMagicNumber = ('h' << 24) | ('m' << 16) | ('a' << 8) | 'p', HMAP_HeaderVersion = 1, - - HMAP_EmptyBucketKey = 0 + + HMAP_EmptyBucketKey = 0 }; namespace clang { @@ -58,7 +58,7 @@ struct HMapHeader { /// linear probing based on this function. static inline unsigned HashHMapKey(const char *S, const char *End) { unsigned Result = 0; - + for (; S != End; S++) Result += tolower(*S) * 13; return Result; @@ -78,27 +78,27 @@ const HeaderMap *HeaderMap::Create(const FileEntry *FE) { // If the file is too small to be a header map, ignore it. unsigned FileSize = FE->getSize(); if (FileSize <= sizeof(HMapHeader)) return 0; - - llvm::OwningPtr FileBuffer( + + llvm::OwningPtr FileBuffer( llvm::MemoryBuffer::getFile(FE->getName(), 0, FE->getSize())); if (FileBuffer == 0) return 0; // Unreadable file? const char *FileStart = FileBuffer->getBufferStart(); // We know the file is at least as big as the header, check it now. const HMapHeader *Header = reinterpret_cast(FileStart); - + // Sniff it to see if it's a headermap by checking the magic number and // version. bool NeedsByteSwap; - if (Header->Magic == HMAP_HeaderMagicNumber && + if (Header->Magic == HMAP_HeaderMagicNumber && Header->Version == HMAP_HeaderVersion) NeedsByteSwap = false; else if (Header->Magic == llvm::ByteSwap_32(HMAP_HeaderMagicNumber) && Header->Version == llvm::ByteSwap_16(HMAP_HeaderVersion)) NeedsByteSwap = true; // Mixed endianness headermap. - else + else return 0; // Not a header map. - + if (Header->Reserved != 0) return 0; // Okay, everything looks good, create the header map. @@ -137,11 +137,11 @@ const HMapHeader &HeaderMap::getHeader() const { HMapBucket HeaderMap::getBucket(unsigned BucketNo) const { HMapBucket Result; Result.Key = HMAP_EmptyBucketKey; - - const HMapBucket *BucketArray = + + const HMapBucket *BucketArray = reinterpret_cast(FileBuffer->getBufferStart() + sizeof(HMapHeader)); - + const HMapBucket *BucketPtr = BucketArray+BucketNo; if ((char*)(BucketPtr+1) > FileBuffer->getBufferEnd()) { Result.Prefix = 0; @@ -161,11 +161,11 @@ HMapBucket HeaderMap::getBucket(unsigned BucketNo) const { const char *HeaderMap::getString(unsigned StrTabIdx) const { // Add the start of the string table to the idx. StrTabIdx += getEndianAdjustedWord(getHeader().StringsOffset); - + // Check for invalid index. if (StrTabIdx >= FileBuffer->getBufferSize()) return 0; - + // Otherwise, we have a valid pointer into the file. Just return it. We know // that the "string" can not overrun the end of the file, because the buffer // is nul terminated by virtue of being a MemoryBuffer. @@ -191,15 +191,15 @@ static bool StringsEqualWithoutCase(const char *S1, const char *S2, void HeaderMap::dump() const { const HMapHeader &Hdr = getHeader(); unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets); - - fprintf(stderr, "Header Map %s:\n %d buckets, %d entries\n", + + fprintf(stderr, "Header Map %s:\n %d buckets, %d entries\n", getFileName(), NumBuckets, getEndianAdjustedWord(Hdr.NumEntries)); - + for (unsigned i = 0; i != NumBuckets; ++i) { HMapBucket B = getBucket(i); if (B.Key == HMAP_EmptyBucketKey) continue; - + const char *Key = getString(B.Key); const char *Prefix = getString(B.Prefix); const char *Suffix = getString(B.Suffix); @@ -219,22 +219,22 @@ const FileEntry *HeaderMap::LookupFile(const char *FilenameStart, // Don't probe infinitely. if (NumBuckets & (NumBuckets-1)) return 0; - + // Linearly probe the hash table. for (unsigned Bucket = HashHMapKey(FilenameStart, FilenameEnd);; ++Bucket) { HMapBucket B = getBucket(Bucket & (NumBuckets-1)); if (B.Key == HMAP_EmptyBucketKey) return 0; // Hash miss. - + // See if the key matches. If not, probe on. const char *Key = getString(B.Key); unsigned BucketKeyLen = strlen(Key); if (BucketKeyLen != unsigned(FilenameEnd-FilenameStart)) continue; - + // See if the actual strings equal. if (!StringsEqualWithoutCase(FilenameStart, Key, BucketKeyLen)) continue; - + // If so, we have a match in the hash table. Construct the destination // path. llvm::SmallString<1024> DestPath; diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp index 9023b11022b1b37bf6631c3b5e22285e572a4a91..2b9b7c977ceb33216a18412392a6d098c9b684c1 100644 --- a/clang/lib/Lex/HeaderSearch.cpp +++ b/clang/lib/Lex/HeaderSearch.cpp @@ -35,7 +35,7 @@ HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) { HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) { SystemDirIdx = 0; NoCurDirSearch = false; - + ExternalLookup = 0; NumIncluded = 0; NumMultiIncludeFileOptzn = 0; @@ -47,7 +47,7 @@ HeaderSearch::~HeaderSearch() { for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) delete HeaderMaps[i].second; } - + void HeaderSearch::PrintStats() { fprintf(stderr, "\n*** HeaderSearch Stats:\n"); fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size()); @@ -61,11 +61,11 @@ void HeaderSearch::PrintStats() { fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles); fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles); fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes); - + fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded); fprintf(stderr, " %d #includes skipped due to" " the multi-include optimization.\n", NumMultiIncludeFileOptzn); - + fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups); fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups); } @@ -79,15 +79,15 @@ const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) // Pointer equality comparison of FileEntries works because they are // already uniqued by inode. - if (HeaderMaps[i].first == FE) + if (HeaderMaps[i].first == FE) return HeaderMaps[i].second; } - + if (const HeaderMap *HM = HeaderMap::Create(FE)) { HeaderMaps.push_back(std::make_pair(FE, HM)); return HM; } - + return 0; } @@ -121,10 +121,10 @@ const FileEntry *DirectoryLookup::LookupFile(const char *FilenameStart, TmpDir.append(FilenameStart, FilenameEnd); return HS.getFileMgr().getFile(TmpDir.begin(), TmpDir.end()); } - + if (isFramework()) return DoFrameworkLookup(FilenameStart, FilenameEnd, HS); - + assert(isHeaderMap() && "Unknown directory lookup"); return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr()); } @@ -136,63 +136,63 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart, const char *FilenameEnd, HeaderSearch &HS) const { FileManager &FileMgr = HS.getFileMgr(); - + // Framework names must have a '/' in the filename. const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/'); if (SlashPos == FilenameEnd) return 0; - + // Find out if this is the home for the specified framework, by checking // HeaderSearch. Possible answer are yes/no and unknown. - const DirectoryEntry *&FrameworkDirCache = + const DirectoryEntry *&FrameworkDirCache = HS.LookupFrameworkCache(FilenameStart, SlashPos); - + // If it is known and in some other directory, fail. if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir()) return 0; - + // Otherwise, construct the path to this framework dir. - + // FrameworkName = "/System/Library/Frameworks/" llvm::SmallString<1024> FrameworkName; FrameworkName += getFrameworkDir()->getName(); if (FrameworkName.empty() || FrameworkName.back() != '/') FrameworkName.push_back('/'); - + // FrameworkName = "/System/Library/Frameworks/Cocoa" FrameworkName.append(FilenameStart, SlashPos); - + // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" FrameworkName += ".framework/"; - + // If the cache entry is still unresolved, query to see if the cache entry is // still unresolved. If so, check its existence now. if (FrameworkDirCache == 0) { HS.IncrementFrameworkLookupCount(); - + // If the framework dir doesn't exist, we fail. // FIXME: It's probably more efficient to query this with FileMgr.getDir. - if (!llvm::sys::Path(std::string(FrameworkName.begin(), + if (!llvm::sys::Path(std::string(FrameworkName.begin(), FrameworkName.end())).exists()) return 0; - + // Otherwise, if it does, remember that this is the right direntry for this // framework. FrameworkDirCache = getFrameworkDir(); } - + // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" unsigned OrigSize = FrameworkName.size(); - + FrameworkName += "Headers/"; FrameworkName.append(SlashPos+1, FilenameEnd); if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(), FrameworkName.end())) { return FE; } - + // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" const char *Private = "Private"; - FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, + FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, Private+strlen(Private)); return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end()); } @@ -209,7 +209,7 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart, /// non-null, indicates where the #including file is, in case a relative search /// is needed. const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart, - const char *FilenameEnd, + const char *FilenameEnd, bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, @@ -220,11 +220,11 @@ const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart, // If this was an #include_next "/absolute/file", fail. if (FromDir) return 0; - + // Otherwise, just return the file. return FileMgr.getFile(FilenameStart, FilenameEnd); } - + // Step #0, unless disabled, check to see if the file is in the #includer's // directory. This has to be based on CurFileEnt, not CurDir, because // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and @@ -249,17 +249,17 @@ const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart, return FE; } } - + CurDir = 0; // If this is a system #include, ignore the user #include locs. unsigned i = isAngled ? SystemDirIdx : 0; - + // If this is a #include_next request, start searching after the directory the // file was found in. if (FromDir) i = FromDir-&SearchDirs[0]; - + // Cache all of the lookups performed by this method. Many headers are // multiply included, and the "pragma once" optimization prevents them from // being relex/pp'd, but they would still have to search through a @@ -279,23 +279,23 @@ const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart, // start point value. CacheLookup.first = i+1; } - + // Check each directory in sequence to see if it contains this file. for (; i != SearchDirs.size(); ++i) { - const FileEntry *FE = + const FileEntry *FE = SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this); if (!FE) continue; - + CurDir = &SearchDirs[i]; - + // This file is a system header or C++ unfriendly if the dir is. getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic(); - + // Remember this location for the next lookup we do. CacheLookup.second = i; return FE; } - + // Otherwise, didn't find it. Remember we didn't find this. CacheLookup.second = SearchDirs.size(); return 0; @@ -311,20 +311,20 @@ LookupSubframeworkHeader(const char *FilenameStart, const char *FilenameEnd, const FileEntry *ContextFileEnt) { assert(ContextFileEnt && "No context file?"); - + // Framework names must have a '/' in the filename. Find it. const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/'); if (SlashPos == FilenameEnd) return 0; - + // Look up the base framework name of the ContextFileEnt. const char *ContextName = ContextFileEnt->getName(); - + // If the context info wasn't a framework, couldn't be a subframework. const char *FrameworkPos = strstr(ContextName, ".framework/"); if (FrameworkPos == 0) return 0; - - llvm::SmallString<1024> FrameworkName(ContextName, + + llvm::SmallString<1024> FrameworkName(ContextName, FrameworkPos+strlen(".framework/")); // Append Frameworks/HIToolbox.framework/ @@ -334,28 +334,28 @@ LookupSubframeworkHeader(const char *FilenameStart, llvm::StringMapEntry &CacheLookup = FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos); - + // Some other location? if (CacheLookup.getValue() && CacheLookup.getKeyLength() == FrameworkName.size() && memcmp(CacheLookup.getKeyData(), &FrameworkName[0], CacheLookup.getKeyLength()) != 0) return 0; - + // Cache subframework. if (CacheLookup.getValue() == 0) { ++NumSubFrameworkLookups; - + // If the framework dir doesn't exist, we fail. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(), FrameworkName.end()); if (Dir == 0) return 0; - + // Otherwise, if it does, remember that this is the right direntry for this // framework. CacheLookup.setValue(Dir); } - + const FileEntry *FE = 0; // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" @@ -364,7 +364,7 @@ LookupSubframeworkHeader(const char *FilenameStart, HeadersFilename.append(SlashPos+1, FilenameEnd); if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end()))) { - + // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" HeadersFilename = FrameworkName; HeadersFilename += "PrivateHeaders/"; @@ -372,7 +372,7 @@ LookupSubframeworkHeader(const char *FilenameStart, if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end()))) return 0; } - + // This file is a system header or C++ unfriendly if the old file is. // // Note that the temporary 'DirInfo' is required here, as either call to @@ -394,7 +394,7 @@ HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { if (FE->getUID() >= FileInfo.size()) FileInfo.resize(FE->getUID()+1); return FileInfo[FE->getUID()]; -} +} void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) { if (UID >= FileInfo.size()) @@ -410,13 +410,13 @@ bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){ // Get information about this file. HeaderFileInfo &FileInfo = getFileInfo(File); - + // If this is a #import directive, check that we have not already imported // this header. if (isImport) { // If this has already been imported, don't import it again. FileInfo.isImport = true; - + // Has this already been #import'ed or #include'd? if (FileInfo.NumIncludes) return false; } else { @@ -425,19 +425,19 @@ bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){ if (FileInfo.isImport) return false; } - + // Next, check to see if the file is wrapped with #ifndef guards. If so, and // if the macro that guards it is defined, we know the #include has no effect. - if (const IdentifierInfo *ControllingMacro + if (const IdentifierInfo *ControllingMacro = FileInfo.getControllingMacro(ExternalLookup)) if (ControllingMacro->hasMacroDefinition()) { ++NumMultiIncludeFileOptzn; return false; } - + // Increment the number of times this file has been included. ++FileInfo.NumIncludes; - + return true; } diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index 974b6900b76db8d9a57564b642e1ce1b18dd296e..23ba6e1ca79befd7e218874aa34a05fa79a90453 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -39,7 +39,7 @@ static void InitCharacterInfo(); // Token Class Implementation //===----------------------------------------------------------------------===// -/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. +/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const { if (IdentifierInfo *II = getIdentifierInfo()) return II->getObjCKeywordID() == objcKey; @@ -57,35 +57,35 @@ tok::ObjCKeywordKind Token::getObjCKeywordID() const { // Lexer Class Implementation //===----------------------------------------------------------------------===// -void Lexer::InitLexer(const char *BufStart, const char *BufPtr, +void Lexer::InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd) { InitCharacterInfo(); - + BufferStart = BufStart; BufferPtr = BufPtr; BufferEnd = BufEnd; - + assert(BufEnd[0] == 0 && "We assume that the input buffer has a null character at the end" " to simplify lexing!"); - + Is_PragmaLexer = false; // Start of the file is a start of line. IsAtStartOfLine = true; - + // We are not after parsing a #. ParsingPreprocessorDirective = false; - + // We are not after parsing #include. ParsingFilename = false; - + // We are not in raw mode. Raw mode disables diagnostics and interpretation // of tokens (e.g. identifiers, thus disabling macro expansion). It is used // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block // or otherwise skipping over tokens. LexingRawMode = false; - + // Default to not keeping comments. ExtendedTokenMode = 0; } @@ -98,12 +98,12 @@ Lexer::Lexer(FileID FID, Preprocessor &PP) : PreprocessorLexer(&PP, FID), FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)), Features(PP.getLangOptions()) { - + const llvm::MemoryBuffer *InputFile = PP.getSourceManager().getBuffer(FID); - + InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(), InputFile->getBufferEnd()); - + // Default to keeping comments if the preprocessor wants them. SetCommentRetentionState(PP.getCommentRetentionState()); } @@ -116,7 +116,7 @@ Lexer::Lexer(SourceLocation fileloc, const LangOptions &features, : FileLoc(fileloc), Features(features) { InitLexer(BufStart, BufPtr, BufEnd); - + // We *are* in raw mode. LexingRawMode = true; } @@ -128,9 +128,9 @@ Lexer::Lexer(FileID FID, const SourceManager &SM, const LangOptions &features) : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) { const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID); - InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(), + InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(), FromFile->getBufferEnd()); - + // We *are* in raw mode. LexingRawMode = true; } @@ -150,7 +150,7 @@ Lexer::Lexer(FileID FID, const SourceManager &SM, const LangOptions &features) /// interface that could handle this stuff. This would pull GetMappedTokenLoc /// out of the critical path of the lexer! /// -Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, +Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation InstantiationLocStart, SourceLocation InstantiationLocEnd, unsigned TokLen, Preprocessor &PP) { @@ -159,12 +159,12 @@ Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, // Create the lexer as if we were going to lex the file normally. FileID SpellingFID = SM.getFileID(SpellingLoc); Lexer *L = new Lexer(SpellingFID, PP); - + // Now that the lexer is created, change the start/end locations so that we // just lex the subsection of the file that we want. This is lexing from a // scratch buffer. const char *StrData = SM.getCharacterData(SpellingLoc); - + L->BufferPtr = StrData; L->BufferEnd = StrData+TokLen; assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!"); @@ -174,11 +174,11 @@ Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID), InstantiationLocStart, InstantiationLocEnd, TokLen); - + // Ensure that the lexer thinks it is inside a directive, so that end \n will // return an EOM token. L->ParsingPreprocessorDirective = true; - + // This lexer really is for _Pragma. L->Is_PragmaLexer = true; return L; @@ -220,7 +220,7 @@ unsigned Lexer::MeasureTokenLength(SourceLocation Loc, const LangOptions &LangOpts) { // TODO: this could be special cased for common tokens like identifiers, ')', // etc to make this faster, if it mattered. Just look at StrData[0] to handle - // all obviously single-char tokens. This could use + // all obviously single-char tokens. This could use // Lexer::isObviouslySimpleCharacter for example to handle identifiers or // something. @@ -365,7 +365,7 @@ static inline bool isWhitespace(unsigned char c) { /// isNumberBody - Return true if this is the body character of an /// preprocessing number, which is [a-zA-Z0-9_.]. static inline bool isNumberBody(unsigned char c) { - return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ? + return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ? true : false; } @@ -386,22 +386,22 @@ static SourceLocation GetMappedTokenLoc(Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen) { assert(FileLoc.isMacroID() && "Must be an instantiation"); - + // Otherwise, we're lexing "mapped tokens". This is used for things like // _Pragma handling. Combine the instantiation location of FileLoc with the // spelling location. SourceManager &SM = PP.getSourceManager(); - + // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose // characters come from spelling(FileLoc)+Offset. SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc); SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo); - + // Figure out the expansion loc range, which is the range covered by the // original _Pragma(...) sequence. std::pair II = SM.getImmediateInstantiationRange(FileLoc); - + return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen); } @@ -417,7 +417,7 @@ SourceLocation Lexer::getSourceLocation(const char *Loc, unsigned CharNo = Loc-BufferStart; if (FileLoc.isFileID()) return FileLoc.getFileLocWithOffset(CharNo); - + // Otherwise, this is the _Pragma lexer case, which pretends that all of the // tokens are lexed from where the _Pragma was defined. assert(PP && "This doesn't work on raw lexers"); @@ -458,13 +458,13 @@ static char GetTrigraphCharForLetter(char Letter) { static char DecodeTrigraphChar(const char *CP, Lexer *L) { char Res = GetTrigraphCharForLetter(*CP); if (!Res || !L) return Res; - + if (!L->getFeatures().Trigraphs) { if (!L->isLexingRawMode()) L->Diag(CP-2, diag::trigraph_ignored); return 0; } - + if (!L->isLexingRawMode()) L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res; return Res; @@ -472,12 +472,12 @@ static char DecodeTrigraphChar(const char *CP, Lexer *L) { /// getEscapedNewLineSize - Return the size of the specified escaped newline, /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a -/// trigraph equivalent on entry to this function. +/// trigraph equivalent on entry to this function. unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { unsigned Size = 0; while (isWhitespace(Ptr[Size])) { ++Size; - + if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r') continue; @@ -485,10 +485,10 @@ unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') && Ptr[Size-1] != Ptr[Size]) ++Size; - + return Size; - } - + } + // Not an escaped newline, must be a \t or something else. return 0; } @@ -509,7 +509,7 @@ const char *Lexer::SkipEscapedNewLines(const char *P) { } else { return P; } - + unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape); if (NewLineSize == 0) return P; P = AfterEscape+NewLineSize; @@ -543,7 +543,7 @@ char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size, Slash: // Common case, backslash-char where the char is not whitespace. if (!isWhitespace(Ptr[0])) return '\\'; - + // See if we have optional whitespace characters between the slash and // newline. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { @@ -553,18 +553,18 @@ Slash: // Warn if there was whitespace between the backslash and newline. if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode()) Diag(Ptr, diag::backslash_newline_space); - + // Found backslash. Parse the char after it. Size += EscapedNewLineSize; Ptr += EscapedNewLineSize; // Use slow version to accumulate a correct size field. return getCharAndSizeSlow(Ptr, Size, Tok); } - + // Otherwise, this is not an escaped newline, just return the slash. return '\\'; } - + // If this is a trigraph, process it. if (Ptr[0] == '?' && Ptr[1] == '?') { // If this is actually a legal trigraph (not something like "??x"), emit @@ -579,7 +579,7 @@ Slash: return C; } } - + // If this is neither, return a single character. ++Size; return *Ptr; @@ -601,21 +601,21 @@ char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, Slash: // Common case, backslash-char where the char is not whitespace. if (!isWhitespace(Ptr[0])) return '\\'; - + // See if we have optional whitespace characters followed by a newline. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { // Found backslash. Parse the char after it. Size += EscapedNewLineSize; Ptr += EscapedNewLineSize; - + // Use slow version to accumulate a correct size field. return getCharAndSizeSlowNoWarn(Ptr, Size, Features); } - + // Otherwise, this is not an escaped newline, just return the slash. return '\\'; } - + // If this is a trigraph, process it. if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') { // If this is actually a legal trigraph (not something like "??x"), return @@ -627,7 +627,7 @@ Slash: return C; } } - + // If this is neither, return a single character. ++Size; return *Ptr; @@ -653,34 +653,34 @@ void Lexer::LexIdentifier(Token &Result, const char *CurPtr) { FinishIdentifier: const char *IdStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::identifier); - + // If we are in raw mode, return this identifier raw. There is no need to // look up identifier information or attempt to macro expand it. if (LexingRawMode) return; - + // Fill in Result.IdentifierInfo, looking up the identifier in the // identifier table. IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart); - + // Change the kind of this identifier to the appropriate token kind, e.g. // turning "for" into a keyword. Result.setKind(II->getTokenID()); - + // Finally, now that we know we have an identifier, pass this off to the // preprocessor, which may macro expand it or something. if (II->isHandleIdentifierCase()) PP->HandleIdentifier(Result); return; } - + // Otherwise, $,\,? in identifier found. Enter slower path. - + C = getCharAndSize(CurPtr, Size); while (1) { if (C == '$') { // If we hit a $ and they are not supported in identifiers, we are done. if (!Features.DollarIdents) goto FinishIdentifier; - + // Otherwise, emit a diagnostic and continue. if (!isLexingRawMode()) Diag(CurPtr, diag::ext_dollar_in_identifier); @@ -716,7 +716,7 @@ void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { PrevCh = C; C = getCharAndSize(CurPtr, Size); } - + // If we fell out, check for a sign, due to 1e+12. If we have one, continue. if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); @@ -724,7 +724,7 @@ void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { // If we have a hex FP constant, continue. if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); - + // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::numeric_constant); @@ -735,7 +735,7 @@ void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { /// either " or L". void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) { const char *NulCharacter = 0; // Does this string contain the \0 character? - + char C = getAndAdvanceChar(CurPtr, Result); while (C != '"') { // Skip escaped characters. @@ -753,7 +753,7 @@ void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) { } C = getAndAdvanceChar(CurPtr, Result); } - + // If a nul character existed in the string, warn about it. if (NulCharacter && !isLexingRawMode()) Diag(NulCharacter, diag::null_in_string); @@ -787,11 +787,11 @@ void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) { } C = getAndAdvanceChar(CurPtr, Result); } - + // If a nul character existed in the string, warn about it. if (NulCharacter && !isLexingRawMode()) Diag(NulCharacter, diag::null_in_string); - + // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::angle_string_literal); @@ -816,7 +816,7 @@ void Lexer::LexCharConstant(Token &Result, const char *CurPtr) { // FIXME: UCN's. C = getAndAdvanceChar(CurPtr, Result); } - + if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') { ++CurPtr; } else { @@ -838,7 +838,7 @@ void Lexer::LexCharConstant(Token &Result, const char *CurPtr) { C = getAndAdvanceChar(CurPtr, Result); } while (C != '\''); } - + if (NulCharacter && !isLexingRawMode()) Diag(NulCharacter, diag::null_in_char); @@ -860,17 +860,17 @@ bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) { // Skip horizontal whitespace very aggressively. while (isHorizontalWhitespace(Char)) Char = *++CurPtr; - + // Otherwise if we have something other than whitespace, we're done. if (Char != '\n' && Char != '\r') break; - + if (ParsingPreprocessorDirective) { // End of preprocessor directive line, let LexTokenInternal handle this. BufferPtr = CurPtr; return false; } - + // ok, but handle newline. // The returned token is at the start of the line. Result.setFlag(Token::StartOfLine); @@ -889,7 +889,7 @@ bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } - + BufferPtr = CurPtr; return false; } @@ -903,12 +903,12 @@ bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { // extension warning. if (!Features.BCPLComment && !isLexingRawMode()) { Diag(BufferPtr, diag::ext_bcpl_comment); - + // Mark them enabled so we only emit one warning for this translation // unit. Features.BCPLComment = true; } - + // Scan over the body of the comment. The common case, when scanning, is that // the comment contains normal ascii characters with nothing interesting in // them. As such, optimize for this case with the inner loop. @@ -918,7 +918,7 @@ bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character. // If we find a \n character, scan backwards, checking to see if it's an // escaped newline, like we do for block comments. - + // Skip over characters in the fast loop. while (C != 0 && // Potentially EOF. C != '\\' && // Potentially escaped newline. @@ -929,7 +929,7 @@ bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { // If this is a newline, we're done. if (C == '\n' || C == '\r') break; // Found the newline? Break out! - + // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to // properly decode the character. Read it in raw mode to avoid emitting // diagnostics about things like trigraphs. If we see an escaped newline, @@ -947,7 +947,7 @@ bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { --CurPtr; C = 'x'; // doesn't matter what this is. } - + // If we read multiple characters, and one of those characters was a \r or // \n, then we had an escaped newline within the comment. Emit diagnostic // unless the next line is also a // comment. @@ -963,21 +963,21 @@ bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/') break; } - + if (!isLexingRawMode()) Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment); break; } } - + if (CurPtr == BufferEnd+1) { --CurPtr; break; } } while (C != '\n' && C != '\r'); // Found but did not consume the newline. if (PP) - PP->HandleComment(SourceRange(getSourceLocation(BufferPtr), + PP->HandleComment(SourceRange(getSourceLocation(BufferPtr), getSourceLocation(CurPtr))); - + // If we are returning comments as tokens, return this comment as a token. if (inKeepCommentMode()) return SaveBCPLComment(Result, CurPtr); @@ -988,14 +988,14 @@ bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { BufferPtr = CurPtr; return false; } - + // Otherwise, eat the \n character. We don't care if this is a \n\r or // \r\n sequence. This is an efficiency hack (because we know the \n can't // contribute to another token), it isn't needed for correctness. Note that // this is ok even in KeepWhitespaceMode, because we would have returned the /// comment above in that mode. ++CurPtr; - + // The next returned token is at the start of the line. Result.setFlag(Token::StartOfLine); // No leading whitespace seen so far. @@ -1010,17 +1010,17 @@ bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) { // If we're not in a preprocessor directive, just return the // comment // directly. FormTokenWithChars(Result, CurPtr, tok::comment); - + if (!ParsingPreprocessorDirective) return true; - + // If this BCPL-style comment is in a macro definition, transmogrify it into // a C-style block comment. std::string Spelling = PP->getSpelling(Result); assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?"); Spelling[1] = '*'; // Change prefix to "/*". Spelling += "*/"; // add suffix. - + Result.setKind(tok::comment); PP->CreateString(&Spelling[0], Spelling.size(), Result, Result.getLocation()); @@ -1030,13 +1030,13 @@ bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) { /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline /// character (either \n or \r) is part of an escaped newline sequence. Issue a /// diagnostic if so. We know that the newline is inside of a block comment. -static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, +static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L) { assert(CurPtr[0] == '\n' || CurPtr[0] == '\r'); - + // Back up off the newline. --CurPtr; - + // If this is a two-character newline sequence, skip the other character. if (CurPtr[0] == '\n' || CurPtr[0] == '\r') { // \n\n or \r\r -> not escaped newline. @@ -1045,7 +1045,7 @@ static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, // \n\r or \r\n -> skip the newline. --CurPtr; } - + // If we have horizontal whitespace, skip over it. We allow whitespace // between the slash and newline. bool HasSpace = false; @@ -1053,7 +1053,7 @@ static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, --CurPtr; HasSpace = true; } - + // If we have a slash, we know this is an escaped newline. if (*CurPtr == '\\') { if (CurPtr[-1] != '*') return false; @@ -1062,7 +1062,7 @@ static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' || CurPtr[-3] != '*') return false; - + // This is the trigraph ending the comment. Emit a stern warning! CurPtr -= 2; @@ -1076,15 +1076,15 @@ static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, if (!L->isLexingRawMode()) L->Diag(CurPtr, diag::trigraph_ends_block_comment); } - + // Warn about having an escaped newline between the */ characters. if (!L->isLexingRawMode()) L->Diag(CurPtr, diag::escaped_newline_block_comment_end); - + // If there was space between the backslash and newline, warn about it. if (HasSpace && !L->isLexingRawMode()) L->Diag(CurPtr, diag::backslash_newline_space); - + return true; } @@ -1120,23 +1120,23 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { if (!isLexingRawMode()) Diag(BufferPtr, diag::err_unterminated_block_comment); --CurPtr; - + // KeepWhitespaceMode should return this broken comment as a token. Since // it isn't a well formed comment, just return it as an 'unknown' token. if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } - + BufferPtr = CurPtr; return false; } - + // Check to see if the first character after the '/*' is another /. If so, // then this slash does not end the block comment, it is part of it. if (C == '/') C = *CurPtr++; - + while (1) { // Skip over all non-interesting characters until we find end of buffer or a // (probably ending) '/' character. @@ -1144,7 +1144,7 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { // While not aligned to a 16-byte boundary. while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0) C = *CurPtr++; - + if (C == '/') goto FoundSlash; #ifdef __SSE2__ @@ -1155,13 +1155,13 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { CurPtr += 16; #elif __ALTIVEC__ __vector unsigned char Slashes = { - '/', '/', '/', '/', '/', '/', '/', '/', + '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/' }; while (CurPtr+16 <= BufferEnd && !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes)) CurPtr += 16; -#else +#else // Scan for '/' quickly. Many block comments are very large. while (CurPtr[0] != '/' && CurPtr[1] != '/' && @@ -1171,20 +1171,20 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { CurPtr += 4; } #endif - + // It has to be one of the bytes scanned, increment to it and read one. C = *CurPtr++; } - + // Loop to scan the remainder. while (C != '/' && C != '\0') C = *CurPtr++; - + FoundSlash: if (C == '/') { if (CurPtr[-2] == '*') // We found the final */. We're done! break; - + if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) { if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) { // We found the final */, though it had an escaped newline between the @@ -1206,22 +1206,22 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { // after the /*, but this would involve lexing a lot of what really is the // comment, which surely would confuse the parser. --CurPtr; - + // KeepWhitespaceMode should return this broken comment as a token. Since // it isn't a well formed comment, just return it as an 'unknown' token. if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } - + BufferPtr = CurPtr; return false; } C = *CurPtr++; } - - if (PP) - PP->HandleComment(SourceRange(getSourceLocation(BufferPtr), + + if (PP) + PP->HandleComment(SourceRange(getSourceLocation(BufferPtr), getSourceLocation(CurPtr))); // If we are returning comments as tokens, return this comment as a token. @@ -1279,11 +1279,11 @@ std::string Lexer::ReadToEndOfLine() { // Okay, we found the end of the line. First, back up past the \0, \r, \n. assert(CurPtr[-1] == Char && "Trigraphs for newline?"); BufferPtr = CurPtr-1; - + // Next, lex the character, which should handle the EOM transition. Lex(Tmp); assert(Tmp.is(tok::eom) && "Unexpected token!"); - + // Finally, we're done, return the string we found. return Result; } @@ -1303,11 +1303,11 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { ParsingPreprocessorDirective = false; // Update the location of token as well as BufferPtr. FormTokenWithChars(Result, CurPtr, tok::eom); - + // Restore comment saving mode, in case it was disabled for directive. SetCommentRetentionState(PP->getCommentRetentionState()); return true; // Have a token. - } + } // If we are in raw mode, return this event as an EOF token. Let the caller // that put us in raw mode handle the event. @@ -1317,7 +1317,7 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { FormTokenWithChars(Result, BufferEnd, tok::eof); return true; } - + // Otherwise, issue diagnostics for unterminated #if and missing newline. // If we are in a #if directive, emit an error. @@ -1326,14 +1326,14 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { diag::err_pp_unterminated_conditional); ConditionalStack.pop_back(); } - + // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue // a pedwarn. if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) Diag(BufferEnd, diag::ext_no_newline_eof) << CodeModificationHint::CreateInsertion(getSourceLocation(BufferEnd), "\n"); - + BufferPtr = CurPtr; // Finally, let the preprocessor handle this. @@ -1346,27 +1346,27 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { /// lexer. unsigned Lexer::isNextPPTokenLParen() { assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?"); - + // Switch to 'skipping' mode. This will ensure that we can lex a token // without emitting diagnostics, disables macro expansion, and will cause EOF // to return an EOF token instead of popping the include stack. LexingRawMode = true; - + // Save state that can be changed while lexing so that we can restore it. const char *TmpBufferPtr = BufferPtr; bool inPPDirectiveMode = ParsingPreprocessorDirective; - + Token Tok; Tok.startToken(); LexTokenInternal(Tok); - + // Restore state that may have changed. BufferPtr = TmpBufferPtr; ParsingPreprocessorDirective = inPPDirectiveMode; - + // Restore the lexer back to non-skipping mode. LexingRawMode = false; - + if (Tok.is(tok::eof)) return 2; return Tok.is(tok::l_paren); @@ -1383,7 +1383,7 @@ LexNextToken: // New token, can't need cleaning yet. Result.clearFlag(Token::NeedsCleaning); Result.setIdentifierInfo(0); - + // CurPtr - Cache BufferPtr in an automatic variable. const char *CurPtr = BufferPtr; @@ -1392,7 +1392,7 @@ LexNextToken: ++CurPtr; while ((*CurPtr == ' ') || (*CurPtr == '\t')) ++CurPtr; - + // If we are keeping whitespace and other tokens, just return what we just // skipped. The next lexer invocation will return the token after the // whitespace. @@ -1400,17 +1400,17 @@ LexNextToken: FormTokenWithChars(Result, CurPtr, tok::unknown); return; } - + BufferPtr = CurPtr; Result.setFlag(Token::LeadingSpace); } - + unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below. - + // Read a character, advancing over it. char Char = getAndAdvanceChar(CurPtr, Result); tok::TokenKind Kind; - + switch (Char) { case 0: // Null. // Found end of file? @@ -1423,13 +1423,13 @@ LexNextToken: assert(PPCache && "Raw buffer::LexEndOfFile should return a token"); return PPCache->Lex(Result); } - + if (!isLexingRawMode()) Diag(CurPtr-1, diag::null_in_file); Result.setFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr)) return; // KeepWhitespaceMode - + goto LexNextToken; // GCC isn't tail call eliminating. case '\n': case '\r': @@ -1438,13 +1438,13 @@ LexNextToken: if (ParsingPreprocessorDirective) { // Done parsing the "line". ParsingPreprocessorDirective = false; - + // Restore comment saving mode, in case it was disabled for directive. SetCommentRetentionState(PP->getCommentRetentionState()); - + // Since we consumed a newline, we are back at the start of a line. IsAtStartOfLine = true; - + Kind = tok::eom; break; } @@ -1452,7 +1452,7 @@ LexNextToken: Result.setFlag(Token::StartOfLine); // No leading whitespace seen so far. Result.clearFlag(Token::LeadingSpace); - + if (SkipWhitespace(Result, CurPtr)) return; // KeepWhitespaceMode goto LexNextToken; // GCC isn't tail call eliminating. @@ -1467,7 +1467,7 @@ LexNextToken: SkipIgnoredUnits: CurPtr = BufferPtr; - + // If the next token is obviously a // or /* */ comment, skip it efficiently // too (without going through the big switch stmt). if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() && @@ -1489,7 +1489,7 @@ LexNextToken: // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexNumericConstant(Result, CurPtr); - + case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz"). // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); @@ -1504,7 +1504,7 @@ LexNextToken: if (Char == '\'') return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); // FALL THROUGH, treating L like the start of an identifier. - + // C99 6.4.2: Identifiers. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N': @@ -1527,10 +1527,10 @@ LexNextToken: MIOpt.ReadToken(); return LexIdentifier(Result, CurPtr); } - + Kind = tok::unknown; break; - + // C99 6.4.4: Character Constants. case '\'': // Notify MIOpt that we read a non-whitespace/non-comment token. @@ -1596,7 +1596,7 @@ LexNextToken: Kind = tok::amp; } break; - case '*': + case '*': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::starequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); @@ -1621,7 +1621,7 @@ LexNextToken: if (Char == '-') { // -- CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::minusminus; - } else if (Char == '>' && Features.CPlusPlus && + } else if (Char == '>' && Features.CPlusPlus && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->* CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); @@ -1662,20 +1662,20 @@ LexNextToken: getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') { if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) return; // KeepCommentMode - + // It is common for the tokens immediately after a // comment to be // whitespace (indentation for the next line). Instead of going through // the big switch, handle it efficiently now. goto SkipIgnoredUnits; } } - + if (Char == '*') { // /**/ comment. if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) return; // KeepCommentMode goto LexNextToken; // GCC isn't tail call eliminating. } - + if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::slashequal; @@ -1711,7 +1711,7 @@ LexNextToken: if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) { FormTokenWithChars(Result, CurPtr, tok::hash); PP->HandleDirective(Result); - + // As an optimization, if the preprocessor didn't switch lexers, tail // recurse. if (PP->isCurrentLexer(this)) { @@ -1724,10 +1724,10 @@ LexNextToken: } goto LexNextToken; // GCC isn't tail call eliminating. } - + return PP->Lex(Result); } - + Kind = tok::hash; } } else { @@ -1764,7 +1764,7 @@ LexNextToken: if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::greaterequal; - } else if (Char == '>' && + } else if (Char == '>' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') { CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); @@ -1805,7 +1805,7 @@ LexNextToken: } else if (Features.CPlusPlus && Char == ':') { Kind = tok::coloncolon; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); - } else { + } else { Kind = tok::colon; } break; @@ -1817,7 +1817,7 @@ LexNextToken: if (Char == '=') { Kind = tok::equalequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); - } else { + } else { Kind = tok::equal; } break; @@ -1842,7 +1842,7 @@ LexNextToken: if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) { FormTokenWithChars(Result, CurPtr, tok::hash); PP->HandleDirective(Result); - + // As an optimization, if the preprocessor didn't switch lexers, tail // recurse. if (PP->isCurrentLexer(this)) { @@ -1857,7 +1857,7 @@ LexNextToken: } return PP->Lex(Result); } - + Kind = tok::hash; } break; @@ -1869,7 +1869,7 @@ LexNextToken: else Kind = tok::unknown; break; - + case '\\': // FIXME: UCN's. // FALL THROUGH. @@ -1877,7 +1877,7 @@ LexNextToken: Kind = tok::unknown; break; } - + // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); diff --git a/clang/lib/Lex/LiteralSupport.cpp b/clang/lib/Lex/LiteralSupport.cpp index cb04e0030542c686c58643c22f0b2f0c4167e795..9f91e0450dfea118c1b624893d5e9a35f22f9be4 100644 --- a/clang/lib/Lex/LiteralSupport.cpp +++ b/clang/lib/Lex/LiteralSupport.cpp @@ -44,7 +44,7 @@ static unsigned ProcessCharEscape(const char *&ThisTokBuf, switch (ResultChar) { // These map to themselves. case '\\': case '\'': case '"': case '?': break; - + // These have fixed mappings. case 'a': // TODO: K&R: the meaning of '\\a' is different in traditional C @@ -83,7 +83,7 @@ static unsigned ProcessCharEscape(const char *&ThisTokBuf, HadError = 1; break; } - + // Hex escapes are a maximal series of hex digits. bool Overflow = false; for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) { @@ -99,12 +99,12 @@ static unsigned ProcessCharEscape(const char *&ThisTokBuf, unsigned CharWidth = IsWide ? PP.getTargetInfo().getWCharWidth() : PP.getTargetInfo().getCharWidth(); - + if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { Overflow = true; ResultChar &= ~0U >> (32-CharWidth); } - + // Check for overflow. if (Overflow) // Too many digits to fit in PP.Diag(Loc, diag::warn_hex_escape_too_large); @@ -125,19 +125,19 @@ static unsigned ProcessCharEscape(const char *&ThisTokBuf, ++NumDigits; } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 && ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7'); - + // Check for overflow. Reject '\777', but not L'\777'. unsigned CharWidth = IsWide ? PP.getTargetInfo().getWCharWidth() : PP.getTargetInfo().getCharWidth(); - + if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { PP.Diag(Loc, diag::warn_octal_escape_too_large); ResultChar &= ~0U >> (32-CharWidth); } break; } - + // Otherwise, these are not valid escapes. case '(': case '{': case '[': case '%': // GCC accepts these as extensions. We warn about them as such though. @@ -151,7 +151,7 @@ static unsigned ProcessCharEscape(const char *&ThisTokBuf, PP.Diag(Loc, diag::ext_unknown_escape) << "x"+llvm::utohexstr(ResultChar); break; } - + return ResultChar; } @@ -159,16 +159,16 @@ static unsigned ProcessCharEscape(const char *&ThisTokBuf, /// convert the UTF32 to UTF8. This is a subroutine of StringLiteralParser. /// When we decide to implement UCN's for character constants and identifiers, /// we will likely rework our support for UCN's. -static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, - char *&ResultBuf, bool &HadError, - SourceLocation Loc, bool IsWide, Preprocessor &PP) +static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, + char *&ResultBuf, bool &HadError, + SourceLocation Loc, bool IsWide, Preprocessor &PP) { // FIXME: Add a warning - UCN's are only valid in C++ & C99. // FIXME: Handle wide strings. - + // Save the beginning of the string (for error diagnostics). const char *ThisTokBegin = ThisTokBuf; - + // Skip the '\u' char's. ThisTokBuf += 2; @@ -178,7 +178,7 @@ static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, return; } typedef uint32_t UTF32; - + UTF32 UcnVal = 0; unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8); for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) { @@ -194,10 +194,10 @@ static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, HadError = 1; return; } - // Check UCN constraints (C99 6.4.3p2). + // Check UCN constraints (C99 6.4.3p2). if ((UcnVal < 0xa0 && (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, ` - || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF) + || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF) || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ { PP.Diag(Loc, diag::err_ucn_escape_invalid); HadError = 1; @@ -206,7 +206,7 @@ static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8. // The conversion below was inspired by: // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c - // First, we determine how many bytes the result will require. + // First, we determine how many bytes the result will require. typedef uint8_t UTF8; unsigned short bytesToWrite = 0; @@ -218,13 +218,13 @@ static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, bytesToWrite = 3; else bytesToWrite = 4; - + const unsigned byteMask = 0xBF; const unsigned byteMark = 0x80; - + // Once the bits are split out into bytes of UTF8, this is a mask OR-ed // into the first byte, depending on how many bytes follow. - static const UTF8 firstByteMark[5] = { + static const UTF8 firstByteMark[5] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0 }; // Finally, we write the bytes into ResultBuf. @@ -244,13 +244,13 @@ static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, /// decimal-constant integer-suffix /// octal-constant integer-suffix /// hexadecimal-constant integer-suffix -/// decimal-constant: +/// decimal-constant: /// nonzero-digit /// decimal-constant digit -/// octal-constant: +/// octal-constant: /// 0 /// octal-constant octal-digit -/// hexadecimal-constant: +/// hexadecimal-constant: /// hexadecimal-prefix hexadecimal-digit /// hexadecimal-constant hexadecimal-digit /// hexadecimal-prefix: one of @@ -272,7 +272,7 @@ static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, /// u U /// long-suffix: one of /// l L -/// long-long-suffix: one of +/// long-long-suffix: one of /// ll LL /// /// floating-constant: [C99 6.4.4.2] @@ -282,14 +282,14 @@ NumericLiteralParser:: NumericLiteralParser(const char *begin, const char *end, SourceLocation TokLoc, Preprocessor &pp) : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) { - + // This routine assumes that the range begin/end matches the regex for integer // and FP constants (specifically, the 'pp-number' regex), and assumes that // the byte at "*end" is both valid and not part of the regex. Because of // this, it doesn't have to check for 'overscan' in various places. assert(!isalnum(*end) && *end != '.' && *end != '_' && "Lexer didn't maximally munch?"); - + s = DigitsBegin = begin; saw_exponent = false; saw_period = false; @@ -299,7 +299,7 @@ NumericLiteralParser(const char *begin, const char *end, isFloat = false; isImaginary = false; hadError = false; - + if (*s == '0') { // parse radix ParseNumberStartingWithZero(TokLoc); if (hadError) @@ -318,7 +318,7 @@ NumericLiteralParser(const char *begin, const char *end, s++; saw_period = true; s = SkipDigits(s); - } + } if ((*s == 'e' || *s == 'E')) { // exponent const char *Exponent = s; s++; @@ -337,11 +337,11 @@ NumericLiteralParser(const char *begin, const char *end, } SuffixBegin = s; - + // Parse the suffix. At this point we can classify whether we have an FP or // integer constant. bool isFPConstant = isFloatingLiteral(); - + // Loop over all of the characters of the suffix. If we see something bad, // we break out of the loop. for (; s != ThisTokEnd; ++s) { @@ -362,7 +362,7 @@ NumericLiteralParser(const char *begin, const char *end, case 'L': if (isLong || isLongLong) break; // Cannot be repeated. if (isFloat) break; // LF invalid. - + // Check for long long. The L's need to be adjacent and the same case. if (s+1 != ThisTokEnd && s[1] == s[0]) { if (isFPConstant) break; // long long invalid for floats. @@ -377,7 +377,7 @@ NumericLiteralParser(const char *begin, const char *end, // Allow i8, i16, i32, i64, and i128. if (++s == ThisTokEnd) break; switch (*s) { - case '8': + case '8': s++; // i8 suffix break; case '1': @@ -414,7 +414,7 @@ NumericLiteralParser(const char *begin, const char *end, // If we reached here, there was an error. break; } - + // Report an error if there are any. if (s != ThisTokEnd) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin), @@ -429,12 +429,12 @@ NumericLiteralParser(const char *begin, const char *end, /// ParseNumberStartingWithZero - This method is called when the first character /// of the number is found to be a zero. This means it is either an octal /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or -/// a floating point number (01239.123e4). Eat the prefix, determining the +/// a floating point number (01239.123e4). Eat the prefix, determining the /// radix etc. void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { assert(s[0] == '0' && "Invalid method call"); s++; - + // Handle a hex number like 0x1234. if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) { s++; @@ -449,7 +449,7 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { s = SkipHexDigits(s); } // A binary exponent can appear with or with a '.'. If dotted, the - // binary exponent is required. + // binary exponent is required. if (*s == 'p' || *s == 'P') { const char *Exponent = s; s++; @@ -463,7 +463,7 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { return; } s = first_non_digit; - + if (!PP.getLangOptions().HexFloats) PP.Diag(TokLoc, diag::ext_hexconstant_invalid); } else if (saw_period) { @@ -473,7 +473,7 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { } return; } - + // Handle simple binary numbers 0b01010 if (*s == 'b' || *s == 'B') { // 0b101010 is a GCC extension. @@ -492,16 +492,16 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { // Other suffixes will be diagnosed by the caller. return; } - + // For now, the radix is set to 8. If we discover that we have a // floating point constant, the radix will change to 10. Octal floating - // point constants are not permitted (only decimal and hexadecimal). + // point constants are not permitted (only decimal and hexadecimal). radix = 8; DigitsBegin = s; s = SkipOctalDigits(s); if (s == ThisTokEnd) return; // Done, simple octal number like 01234 - + // If we have some other non-octal digit that *is* a decimal digit, see if // this is part of a floating point number like 094.123 or 09e1. if (isdigit(*s)) { @@ -511,7 +511,7 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { radix = 10; } } - + // If we have a hex digit other than 'e' (which denotes a FP exponent) then // the code is using an incorrect base. if (isxdigit(*s) && *s != 'e' && *s != 'E') { @@ -520,7 +520,7 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { hadError = true; return; } - + if (*s == '.') { s++; radix = 10; @@ -537,7 +537,7 @@ void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { if (first_non_digit != s) { s = first_non_digit; } else { - PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), + PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), diag::err_exponent_has_no_digits); hadError = true; return; @@ -557,7 +557,7 @@ bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { // handles the common cases that matter (small decimal integers and // hex/octal values which don't overflow). unsigned MaxBitsPerDigit = 1; - while ((1U << MaxBitsPerDigit) < radix) + while ((1U << MaxBitsPerDigit) < radix) MaxBitsPerDigit += 1; if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) { uint64_t N = 0; @@ -576,16 +576,16 @@ bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { llvm::APInt RadixVal(Val.getBitWidth(), radix); llvm::APInt CharVal(Val.getBitWidth(), 0); llvm::APInt OldVal = Val; - + bool OverflowOccurred = false; while (s < SuffixBegin) { unsigned C = HexDigitValue(*s++); - + // If this letter is out of bound for this radix, reject it. assert(C < radix && "NumericLiteralParser ctor should have rejected this"); - + CharVal = C; - + // Add the digit to the value in the appropriate radix. If adding in digits // made the value smaller, then this overflowed. OldVal = Val; @@ -606,23 +606,23 @@ llvm::APFloat NumericLiteralParser:: GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) { using llvm::APFloat; using llvm::StringRef; - + llvm::SmallVector floatChars; unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin); for (unsigned i = 0; i != n; ++i) floatChars.push_back(ThisTokBegin[i]); - + floatChars.push_back('\0'); - + APFloat V (Format, APFloat::fcZero, false); APFloat::opStatus status; - + status = V.convertFromString(StringRef(&floatChars[0], n), APFloat::rmNearestTiesToEven); - + if (isExact) *isExact = status == APFloat::opOK; - + return V; } @@ -631,16 +631,16 @@ CharLiteralParser::CharLiteralParser(const char *begin, const char *end, SourceLocation Loc, Preprocessor &PP) { // At this point we know that the character matches the regex "L?'.*'". HadError = false; - + // Determine if this is a wide character. IsWide = begin[0] == 'L'; if (IsWide) ++begin; - + // Skip over the entry quote. assert(begin[0] == '\'' && "Invalid token lexed"); ++begin; - // FIXME: The "Value" is an uint64_t so we can handle char literals of + // FIXME: The "Value" is an uint64_t so we can handle char literals of // upto 64-bits. // FIXME: This extensively assumes that 'char' is 8-bits. assert(PP.getTargetInfo().getCharWidth() == 8 && @@ -651,9 +651,9 @@ CharLiteralParser::CharLiteralParser(const char *begin, const char *end, assert(PP.getTargetInfo().getWCharWidth() <= 64 && "Assumes sizeof(wchar) on target is <= 64"); - // This is what we will use for overflow detection + // This is what we will use for overflow detection llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0); - + unsigned NumCharsSoFar = 0; while (begin[0] != '\'') { uint64_t ResultChar; @@ -676,7 +676,7 @@ CharLiteralParser::CharLiteralParser(const char *begin, const char *end, LitVal <<= 8; } } - + LitVal = LitVal + ResultChar; ++NumCharsSoFar; } @@ -697,7 +697,7 @@ CharLiteralParser::CharLiteralParser(const char *begin, const char *end, // Transfer the value from APInt to uint64_t Value = LitVal.getZExtValue(); - + // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1") // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple // character constants are not sign extended in the this implementation: @@ -752,7 +752,7 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, MaxTokenLength = StringToks[0].getLength(); SizeBound = StringToks[0].getLength()-2; // -2 for "". AnyWide = StringToks[0].is(tok::wide_string_literal); - + hadError = false; // Implement Translation Phase #6: concatenation of string literals @@ -761,20 +761,20 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, // The string could be shorter than this if it needs cleaning, but this is a // reasonable bound, which is all we need. SizeBound += StringToks[i].getLength()-2; // -2 for "". - + // Remember maximum string piece length. - if (StringToks[i].getLength() > MaxTokenLength) + if (StringToks[i].getLength() > MaxTokenLength) MaxTokenLength = StringToks[i].getLength(); - + // Remember if we see any wide strings. AnyWide |= StringToks[i].is(tok::wide_string_literal); } // Include space for the null terminator. ++SizeBound; - + // TODO: K&R warning: "traditional C rejects string constant concatenation" - + // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true. wchar_tByteWidth = ~0U; @@ -783,25 +783,25 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!"); wchar_tByteWidth /= 8; } - + // The output buffer size needs to be large enough to hold wide characters. // This is a worst-case assumption which basically corresponds to L"" "long". if (AnyWide) SizeBound *= wchar_tByteWidth; - + // Size the temporary buffer to hold the result string data. ResultBuf.resize(SizeBound); - + // Likewise, but for each string piece. llvm::SmallString<512> TokenBuf; TokenBuf.resize(MaxTokenLength); - + // Loop over all the strings, getting their spelling, and expanding them to // wide strings as appropriate. ResultPtr = &ResultBuf[0]; // Next byte to fill in. - + Pascal = false; - + for (unsigned i = 0, e = NumStringToks; i != e; ++i) { const char *ThisTokBuf = &TokenBuf[0]; // Get the spelling of the token, which eliminates trigraphs, etc. We know @@ -809,23 +809,23 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, // and 'spelled' tokens can only shrink. unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf); const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote. - + // TODO: Input character set mapping support. - + // Skip L marker for wide strings. bool ThisIsWide = false; if (ThisTokBuf[0] == 'L') { ++ThisTokBuf; ThisIsWide = true; } - + assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?"); ++ThisTokBuf; - + // Check if this is a pascal string if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd && ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') { - + // If the \p sequence is found in the first token, we have a pascal string // Otherwise, if we already have a pascal string, ignore the first \p if (i == 0) { @@ -834,7 +834,7 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, } else if (Pascal) ThisTokBuf += 2; } - + while (ThisTokBuf != ThisTokEnd) { // Is this a span of non-escape characters? if (ThisTokBuf[0] != '\\') { @@ -842,7 +842,7 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, do { ++ThisTokBuf; } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\'); - + // Copy the character span over. unsigned Len = ThisTokBuf-InStart; if (!AnyWide) { @@ -861,7 +861,7 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, } // Is this a Universal Character Name escape? if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') { - ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr, + ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr, hadError, StringToks[i].getLocation(), ThisIsWide, PP); continue; } @@ -869,17 +869,17 @@ StringLiteralParser(const Token *StringToks, unsigned NumStringToks, unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError, StringToks[i].getLocation(), ThisIsWide, PP); - + // Note: our internal rep of wide char tokens is always little-endian. *ResultPtr++ = ResultChar & 0xFF; - + if (AnyWide) { for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i) *ResultPtr++ = ResultChar >> i*8; } } } - + if (Pascal) { ResultBuf[0] = ResultPtr-&ResultBuf[0]-1; @@ -904,31 +904,31 @@ unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, // Get the spelling of the token. llvm::SmallString<16> SpellingBuffer; SpellingBuffer.resize(Tok.getLength()); - + const char *SpellingPtr = &SpellingBuffer[0]; unsigned TokLen = PP.getSpelling(Tok, SpellingPtr); assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet"); - + const char *SpellingStart = SpellingPtr; const char *SpellingEnd = SpellingPtr+TokLen; // Skip over the leading quote. assert(SpellingPtr[0] == '"' && "Should be a string literal!"); ++SpellingPtr; - + // Skip over bytes until we find the offset we're looking for. while (ByteNo) { assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!"); - + // Step over non-escapes simply. if (*SpellingPtr != '\\') { ++SpellingPtr; --ByteNo; continue; } - + // Otherwise, this is an escape character. Advance over it. bool HadError = false; ProcessCharEscape(SpellingPtr, SpellingEnd, HadError, @@ -936,6 +936,6 @@ unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, assert(!HadError && "This method isn't valid on erroneous strings"); --ByteNo; } - + return SpellingPtr-SpellingStart; } diff --git a/clang/lib/Lex/MacroArgs.cpp b/clang/lib/Lex/MacroArgs.cpp index cba69b7d79190836c5d5cd6906ef4e66b9e01143..c14d7c438d607f5b6d1d03467845375d322c84f8 100644 --- a/clang/lib/Lex/MacroArgs.cpp +++ b/clang/lib/Lex/MacroArgs.cpp @@ -23,18 +23,18 @@ MacroArgs *MacroArgs::create(const MacroInfo *MI, unsigned NumToks, bool VarargsElided) { assert(MI->isFunctionLike() && "Can't have args for an object-like macro!"); - + // Allocate memory for the MacroArgs object with the lexer tokens at the end. MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) + NumToks*sizeof(Token)); // Construct the macroargs object. new (Result) MacroArgs(NumToks, VarargsElided); - + // Copy the actual unexpanded tokens to immediately after the result ptr. if (NumToks) memcpy(const_cast(Result->getUnexpArgument(0)), UnexpArgTokens, NumToks*sizeof(Token)); - + return Result; } @@ -98,7 +98,7 @@ bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok, const std::vector & MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) { assert(Arg < NumUnexpArgTokens && "Invalid argument number!"); - + // If we have already computed this, return it. if (PreExpArgTokens.empty()) PreExpArgTokens.resize(NumUnexpArgTokens); @@ -108,12 +108,12 @@ MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) { const Token *AT = getUnexpArgument(Arg); unsigned NumToks = getArgLength(AT)+1; // Include the EOF. - + // Otherwise, we have to pre-expand this argument, populating Result. To do // this, we set up a fake TokenLexer to lex from the unexpanded argument // list. With this installed, we lex expanded tokens until we hit the EOF // token at the end of the unexp list. - PP.EnterTokenStream(AT, NumToks, false /*disable expand*/, + PP.EnterTokenStream(AT, NumToks, false /*disable expand*/, false /*owns tokens*/); // Lex all of the macro-expanded tokens into Result. @@ -122,7 +122,7 @@ MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) { Token &Tok = Result.back(); PP.Lex(Tok); } while (Result.back().isNot(tok::eof)); - + // Pop the token stream off the top of the stack. We know that the internal // pointer inside of it is to the "end" of the token stream, but the stack // will not otherwise be popped until the next token is lexed. The problem is @@ -145,18 +145,18 @@ Token MacroArgs::StringifyArgument(const Token *ArgToks, Tok.setKind(tok::string_literal); const Token *ArgTokStart = ArgToks; - + // Stringify all the tokens. llvm::SmallString<128> Result; Result += "\""; - + bool isFirst = true; for (; ArgToks->isNot(tok::eof); ++ArgToks) { const Token &Tok = *ArgToks; if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine())) Result += ' '; isFirst = false; - + // If this is a string or character constant, escape the token as specified // by 6.10.3.2p2. if (Tok.is(tok::string_literal) || // "foo" @@ -171,18 +171,18 @@ Token MacroArgs::StringifyArgument(const Token *ArgToks, Result.resize(CurStrLen+Tok.getLength()); const char *BufPtr = &Result[CurStrLen]; unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr); - + // If getSpelling returned a pointer to an already uniqued version of the // string instead of filling in BufPtr, memcpy it onto our string. if (BufPtr != &Result[CurStrLen]) memcpy(&Result[CurStrLen], BufPtr, ActualTokLen); - + // If the token was dirty, the spelling may be shorter than the token. if (ActualTokLen != Tok.getLength()) Result.resize(CurStrLen+ActualTokLen); } } - + // If the last character of the string is a \, and if it isn't escaped, this // is an invalid string literal, diagnose it as specified in C99. if (Result.back() == '\\') { @@ -199,27 +199,27 @@ Token MacroArgs::StringifyArgument(const Token *ArgToks, } } Result += '"'; - + // If this is the charify operation and the result is not a legal character // constant, diagnose it. if (Charify) { // First step, turn double quotes into single quotes: Result[0] = '\''; Result[Result.size()-1] = '\''; - + // Check for bogus character. bool isBad = false; if (Result.size() == 3) isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above. else isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x' - + if (isBad) { PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify); Result = "' '"; // Use something arbitrary, but legal. } } - + PP.CreateString(&Result[0], Result.size(), Tok); return Tok; } diff --git a/clang/lib/Lex/MacroArgs.h b/clang/lib/Lex/MacroArgs.h index 4b22fa18aa8b95703680c1b89b668ecb1971cee8..8dee5b3bc997bcc806ad5d0a4ddda2981b019146 100644 --- a/clang/lib/Lex/MacroArgs.h +++ b/clang/lib/Lex/MacroArgs.h @@ -20,7 +20,7 @@ namespace clang { class MacroInfo; class Preprocessor; class Token; - + /// MacroArgs - An instance of this class captures information about /// the formal arguments specified to a function-like macro invocation. class MacroArgs { @@ -45,7 +45,7 @@ class MacroArgs { /// if in strict mode and the C99 varargs macro had only a ... argument, this /// is false. bool VarargsElided; - + MacroArgs(unsigned NumToks, bool varargsElided) : NumUnexpArgTokens(NumToks), VarargsElided(varargsElided) {} ~MacroArgs() {} @@ -55,46 +55,46 @@ public: static MacroArgs *create(const MacroInfo *MI, const Token *UnexpArgTokens, unsigned NumArgTokens, bool VarargsElided); - + /// destroy - Destroy and deallocate the memory for this object. /// void destroy(); - + /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected /// by pre-expansion, return false. Otherwise, conservatively return true. bool ArgNeedsPreexpansion(const Token *ArgTok, Preprocessor &PP) const; - + /// getUnexpArgument - Return a pointer to the first token of the unexpanded /// token list for the specified formal. /// const Token *getUnexpArgument(unsigned Arg) const; - + /// getArgLength - Given a pointer to an expanded or unexpanded argument, /// return the number of tokens, not counting the EOF, that make up the /// argument. static unsigned getArgLength(const Token *ArgPtr); - + /// getPreExpArgument - Return the pre-expanded form of the specified /// argument. const std::vector & - getPreExpArgument(unsigned Arg, Preprocessor &PP); - + getPreExpArgument(unsigned Arg, Preprocessor &PP); + /// getStringifiedArgument - Compute, cache, and return the specified argument /// that has been 'stringified' as required by the # operator. const Token &getStringifiedArgument(unsigned ArgNo, Preprocessor &PP); - + /// getNumArguments - Return the number of arguments passed into this macro /// invocation. unsigned getNumArguments() const { return NumUnexpArgTokens; } - - + + /// isVarargsElidedUse - Return true if this is a C99 style varargs macro /// invocation and there was no argument specified for the "..." argument. If /// the argument was specified (even empty) or this isn't a C99 style varargs /// function, or if in strict mode and the C99 varargs macro had only a ... /// argument, this returns false. bool isVarargsElidedUse() const { return VarargsElided; } - + /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of /// tokens into the literal string token that should be produced by the C # /// preprocessor operator. If Charify is true, then it should be turned into diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp index df89450f5a5557b32ee9cf3480e238c8915ee479..fda884c4da4c32b0955813df695b04f9e5c0c72e 100644 --- a/clang/lib/Lex/MacroInfo.cpp +++ b/clang/lib/Lex/MacroInfo.cpp @@ -22,7 +22,7 @@ MacroInfo::MacroInfo(SourceLocation DefLoc) : Location(DefLoc) { IsBuiltinMacro = false; IsDisabled = false; IsUsed = true; - + ArgumentList = 0; NumArguments = 0; } @@ -44,32 +44,32 @@ bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP) const { for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end(); I != E; ++I, ++OI) if (*I != *OI) return false; - + // Check all the tokens. for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) { const Token &A = ReplacementTokens[i]; const Token &B = Other.ReplacementTokens[i]; if (A.getKind() != B.getKind()) return false; - + // If this isn't the first first token, check that the whitespace and // start-of-line characteristics match. if (i != 0 && (A.isAtStartOfLine() != B.isAtStartOfLine() || A.hasLeadingSpace() != B.hasLeadingSpace())) return false; - + // If this is an identifier, it is easy. if (A.getIdentifierInfo() || B.getIdentifierInfo()) { if (A.getIdentifierInfo() != B.getIdentifierInfo()) return false; continue; } - + // Otherwise, check the spelling. if (PP.getSpelling(A) != PP.getSpelling(B)) return false; } - + return true; } diff --git a/clang/lib/Lex/PPCaching.cpp b/clang/lib/Lex/PPCaching.cpp index 808787864bef0a8c406a1f1d661b3c25ade1e976..c3f0eeab584819b6b1fa15f4bcdaf250de30f0e7 100644 --- a/clang/lib/Lex/PPCaching.cpp +++ b/clang/lib/Lex/PPCaching.cpp @@ -36,7 +36,7 @@ void Preprocessor::CommitBacktrackedTokens() { } /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since -/// EnableBacktrackAtThisPos() was previously called. +/// EnableBacktrackAtThisPos() was previously called. void Preprocessor::Backtrack() { assert(!BacktrackPositions.empty() && "EnableBacktrackAtThisPos was not called!"); diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp index 1b6eb150f89c73e9e33e8eb9b4fbefa33e1997d0..196a77f6426ad9a50ab8df860772516e7e653dad 100644 --- a/clang/lib/Lex/PPDirectives.cpp +++ b/clang/lib/Lex/PPDirectives.cpp @@ -26,7 +26,7 @@ using namespace clang; MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { MacroInfo *MI; - + if (!MICache.empty()) { MI = MICache.back(); MICache.pop_back(); @@ -61,13 +61,13 @@ void Preprocessor::DiscardUntilEndOfDirective() { void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) { // Read the token, don't allow macro expansion on it. LexUnexpandedToken(MacroNameTok); - + // Missing macro name? if (MacroNameTok.is(tok::eom)) { Diag(MacroNameTok, diag::err_pp_missing_macro_name); return; } - + IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); if (II == 0) { std::string Spelling = getSpelling(MacroNameTok); @@ -93,7 +93,7 @@ void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) { // Okay, we got a good identifier node. Return it. return; } - + // Invalid macro name, read and discard the rest of the line. Then set the // token kind to tok::eom. MacroNameTok.setKind(tok::eom); @@ -112,12 +112,12 @@ void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) { Lex(Tmp); else LexUnexpandedToken(Tmp); - + // There should be no tokens after the directive, but we allow them as an // extension. while (Tmp.is(tok::comment)) // Skip comments in -C mode. LexUnexpandedToken(Tmp); - + if (Tmp.isNot(tok::eom)) { // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, // because it is more trouble than it is worth to insert /**/ and check that @@ -148,12 +148,12 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, FoundNonSkipPortion, FoundElse); - + if (CurPTHLexer) { PTHSkipExcludedConditionalBlock(); return; } - + // Enter raw mode to disable identifier lookup (and thus macro expansion), // disabling warnings, etc. CurPPLexer->LexingRawMode = true; @@ -163,7 +163,7 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, CurLexer->Lex(Tok); else CurPTHLexer->Lex(Tok); - + // If this is the end of the buffer, we have an error. if (Tok.is(tok::eof)) { // Emit errors for each unterminated conditional on the stack, including @@ -172,26 +172,26 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, Diag(CurPPLexer->ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional); CurPPLexer->ConditionalStack.pop_back(); - } - + } + // Just return and let the caller lex after this #include. break; } - + // If this token is not a preprocessor directive, just skip it. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) continue; - + // We just parsed a # character at the start of a line, so we're in // directive mode. Tell the lexer this so any newlines we see will be // converted into an EOM token (this terminates the macro). CurPPLexer->ParsingPreprocessorDirective = true; if (CurLexer) CurLexer->SetCommentRetentionState(false); - + // Read the next token, the directive flavor. LexUnexpandedToken(Tok); - + // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or // something bogus), skip it. if (Tok.isNot(tok::identifier)) { @@ -208,14 +208,14 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, // other common directives. const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation()); char FirstChar = RawCharData[0]; - if (FirstChar >= 'a' && FirstChar <= 'z' && + if (FirstChar >= 'a' && FirstChar <= 'z' && FirstChar != 'i' && FirstChar != 'e') { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); continue; } - + // Get the identifier name without trigraphs or embedded newlines. Note // that we can't use Tok.getIdentifierInfo() because its lookup is disabled // when skipping. @@ -240,7 +240,7 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, Directive[IdLen] = 0; FirstChar = Directive[0]; } - + if (FirstChar == 'i' && Directive[1] == 'f') { if ((IdLen == 2) || // "if" (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef" @@ -260,7 +260,7 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, bool InCond = CurPPLexer->popConditionalLevel(CondInfo); InCond = InCond; // Silence warning in no-asserts mode. assert(!InCond && "Can't be skipping if not in a conditional!"); - + // If we popped the outermost skipping block, we're done skipping! if (!CondInfo.WasSkipping) break; @@ -270,13 +270,13 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, // as a non-skipping conditional. DiscardUntilEndOfDirective(); // C99 6.10p4. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); - + // If this is a #else with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); - + // Note that we've seen a #else in this conditional. CondInfo.FoundElse = true; - + // If the conditional is at the top level, and the #if block wasn't // entered, enter the #else block now. if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { @@ -301,10 +301,10 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); CurPPLexer->LexingRawMode = true; } - + // If this is a #elif with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); - + // If this condition is true, enter it! if (ShouldEnter) { CondInfo.FoundNonSkip = true; @@ -312,7 +312,7 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, } } } - + CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); @@ -325,11 +325,11 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, } void Preprocessor::PTHSkipExcludedConditionalBlock() { - - while(1) { + + while (1) { assert(CurPTHLexer); assert(CurPTHLexer->LexingRawMode == false); - + // Skip to the next '#else', '#elif', or #endif. if (CurPTHLexer->SkipBlock()) { // We have reached an #endif. Both the '#' and 'endif' tokens @@ -340,12 +340,12 @@ void Preprocessor::PTHSkipExcludedConditionalBlock() { assert(!InCond && "Can't be skipping if not in a conditional!"); break; } - + // We have reached a '#else' or '#elif'. Lex the next token to get // the directive flavor. Token Tok; LexUnexpandedToken(Tok); - + // We can actually look up the IdentifierInfo here since we aren't in // raw mode. tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); @@ -357,32 +357,32 @@ void Preprocessor::PTHSkipExcludedConditionalBlock() { PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); // Note that we've seen a #else in this conditional. CondInfo.FoundElse = true; - + // If the #if block wasn't entered then enter the #else block now. if (!CondInfo.FoundNonSkip) { CondInfo.FoundNonSkip = true; - + // Scan until the eom token. CurPTHLexer->ParsingPreprocessorDirective = true; DiscardUntilEndOfDirective(); CurPTHLexer->ParsingPreprocessorDirective = false; - + break; } - + // Otherwise skip this block. continue; } - + assert(K == tok::pp_elif); PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); // If this is a #elif with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); - + // If this is in a skipping block or if we're already handled this #if - // block, don't bother parsing the condition. We just skip this block. + // block, don't bother parsing the condition. We just skip this block. if (CondInfo.FoundNonSkip) continue; @@ -417,7 +417,7 @@ const FileEntry *Preprocessor::LookupFile(const char *FilenameStart, if (!FromDir) { FileID FID = getCurrentFileLexer()->getFileID(); CurFileEnt = SourceMgr.getFileEntryForID(FID); - + // If there is no file entry associated with this file, it must be the // predefines buffer. Any other file is not lexed with a normal lexer, so // it won't be scanned for preprocessor directives. If we have the @@ -429,14 +429,14 @@ const FileEntry *Preprocessor::LookupFile(const char *FilenameStart, CurFileEnt = SourceMgr.getFileEntryForID(FID); } } - + // Do a standard file entry lookup. CurDir = CurDirLookup; const FileEntry *FE = HeaderInfo.LookupFile(FilenameStart, FilenameEnd, isAngled, FromDir, CurDir, CurFileEnt); if (FE) return FE; - + // Otherwise, see if this is a subframework header. If so, this is relative // to one of the headers on the #include stack. Walk the list of the current // headers on the #include stack and pass them to HeaderInfo. @@ -446,18 +446,18 @@ const FileEntry *Preprocessor::LookupFile(const char *FilenameStart, CurFileEnt))) return FE; } - + for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; if (IsFileLexer(ISEntry)) { - if ((CurFileEnt = + if ((CurFileEnt = SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd, CurFileEnt))) return FE; } } - + // Otherwise, we really couldn't find the file. return 0; } @@ -468,31 +468,31 @@ const FileEntry *Preprocessor::LookupFile(const char *FilenameStart, //===----------------------------------------------------------------------===// /// HandleDirective - This callback is invoked when the lexer sees a # token -/// at the start of a line. This consumes the directive, modifies the +/// at the start of a line. This consumes the directive, modifies the /// lexer/preprocessor state, and advances the lexer(s) so that the next token /// read is the correct one. void Preprocessor::HandleDirective(Token &Result) { // FIXME: Traditional: # with whitespace before it not recognized by K&R? - + // We just parsed a # character at the start of a line, so we're in directive // mode. Tell the lexer this so any newlines we see will be converted into an // EOM token (which terminates the directive). CurPPLexer->ParsingPreprocessorDirective = true; - + ++NumDirectives; - + // We are about to read a token. For the multiple-include optimization FA to - // work, we have to remember if we had read any tokens *before* this + // work, we have to remember if we had read any tokens *before* this // pp-directive. bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal(); - + // Save the '#' token in case we need to return it later. Token SavedHash = Result; - + // Read the next token, the directive flavor. This isn't expanded due to // C99 6.10.3p8. LexUnexpandedToken(Result); - + // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: // #define A(x) #x // A(abc @@ -501,7 +501,7 @@ void Preprocessor::HandleDirective(Token &Result) { // If so, the user is relying on non-portable behavior, emit a diagnostic. if (InMacroArgs) Diag(Result, diag::ext_embedded_directive); - + TryAgain: switch (Result.getKind()) { case tok::eom: @@ -518,7 +518,7 @@ TryAgain: default: IdentifierInfo *II = Result.getIdentifierInfo(); if (II == 0) break; // Not an identifier. - + // Ask what the preprocessor keyword ID is. switch (II->getPPKeywordID()) { default: break; @@ -535,13 +535,13 @@ TryAgain: return HandleElseDirective(Result); case tok::pp_endif: return HandleEndifDirective(Result); - + // C99 6.10.2 - Source File Inclusion. case tok::pp_include: return HandleIncludeDirective(Result); // Handle #include. case tok::pp___include_macros: return HandleIncludeMacrosDirective(Result); // Handle -imacros. - + // C99 6.10.3 - Macro Replacement. case tok::pp_define: return HandleDefineDirective(Result); @@ -551,21 +551,21 @@ TryAgain: // C99 6.10.4 - Line Control. case tok::pp_line: return HandleLineDirective(Result); - + // C99 6.10.5 - Error Directive. case tok::pp_error: return HandleUserDiagnosticDirective(Result, false); - + // C99 6.10.6 - Pragma Directive. case tok::pp_pragma: return HandlePragmaDirective(); - + // GNU Extensions. case tok::pp_import: return HandleImportDirective(Result); case tok::pp_include_next: return HandleIncludeNextDirective(Result); - + case tok::pp_warning: Diag(Result, diag::ext_pp_warning_directive); return HandleUserDiagnosticDirective(Result, true); @@ -582,7 +582,7 @@ TryAgain: } break; } - + // If this is a .S file, treat unknown # directives as non-preprocessor // directives. This is important because # may be a comment or introduce // various pseudo-ops. Just return the # token and push back the following @@ -590,7 +590,7 @@ TryAgain: if (getLangOptions().AsmPreprocessor) { Token *Toks = new Token[2]; // Return the # and the token after it. - Toks[0] = SavedHash; + Toks[0] = SavedHash; Toks[1] = Result; // Enter this token stream so that we re-lex the tokens. Make sure to // enable macro expansion, in case the token after the # is an identifier @@ -598,13 +598,13 @@ TryAgain: EnterTokenStream(Toks, 2, false, true); return; } - + // If we reached here, the preprocessing token is not valid! Diag(Result, diag::err_pp_invalid_directive); - + // Read the rest of the PP line. DiscardUntilEndOfDirective(); - + // Okay, we're done parsing the directive. } @@ -614,17 +614,17 @@ static bool GetLineValue(Token &DigitTok, unsigned &Val, unsigned DiagID, Preprocessor &PP) { if (DigitTok.isNot(tok::numeric_constant)) { PP.Diag(DigitTok, DiagID); - + if (DigitTok.isNot(tok::eom)) PP.DiscardUntilEndOfDirective(); return true; } - + llvm::SmallString<64> IntegerBuffer; IntegerBuffer.resize(DigitTok.getLength()); const char *DigitTokBegin = &IntegerBuffer[0]; unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin); - + // Verify that we have a simple digit-sequence, and compute the value. This // is always a simple digit string computed in decimal, so we do this manually // here. @@ -636,7 +636,7 @@ static bool GetLineValue(Token &DigitTok, unsigned &Val, PP.DiscardUntilEndOfDirective(); return true; } - + unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); if (NextVal < Val) { // overflow. PP.Diag(DigitTok, DiagID); @@ -645,21 +645,21 @@ static bool GetLineValue(Token &DigitTok, unsigned &Val, } Val = NextVal; } - - // Reject 0, this is needed both by #line numbers and flags. + + // Reject 0, this is needed both by #line numbers and flags. if (Val == 0) { PP.Diag(DigitTok, DiagID); PP.DiscardUntilEndOfDirective(); return true; } - + if (DigitTokBegin[0] == '0') PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal); - + return false; } -/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two +/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two /// acceptable forms are: /// # line digit-sequence /// # line digit-sequence "s-char-sequence" @@ -679,14 +679,14 @@ void Preprocessor::HandleLineDirective(Token &Tok) { unsigned LineLimit = Features.C99 ? 2147483648U : 32768U; if (LineNo >= LineLimit) Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; - + int FilenameID = -1; Token StrTok; Lex(StrTok); // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a // string followed by eom. - if (StrTok.is(tok::eom)) + if (StrTok.is(tok::eom)) ; // ok else if (StrTok.isNot(tok::string_literal)) { Diag(StrTok, diag::err_pp_line_invalid_filename); @@ -704,14 +704,14 @@ void Preprocessor::HandleLineDirective(Token &Tok) { } FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(), Literal.GetStringLength()); - + // Verify that there is nothing after the string, other than EOM. Because // of C99 6.10.4p5, macros that expand to empty tokens are ok. CheckEndOfDirective("line", true); } - + SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID); - + if (Callbacks) Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile, SrcMgr::C_User); @@ -731,21 +731,21 @@ static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, if (FlagVal == 1) { IsFileEntry = true; - + PP.Lex(FlagTok); if (FlagTok.is(tok::eom)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) return true; } else if (FlagVal == 2) { IsFileExit = true; - + SourceManager &SM = PP.getSourceManager(); // If we are leaving the current presumed file, check to make sure the // presumed include stack isn't empty! FileID CurFileID = SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first; PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); - + // If there is no include loc (main file) or if the include loc is in a // different physical file, then we aren't in a "1" line marker flag region. SourceLocation IncLoc = PLoc.getIncludeLoc(); @@ -755,7 +755,7 @@ static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, PP.DiscardUntilEndOfDirective(); return true; } - + PP.Lex(FlagTok); if (FlagTok.is(tok::eom)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) @@ -768,9 +768,9 @@ static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, PP.DiscardUntilEndOfDirective(); return true; } - + IsSystemHeader = true; - + PP.Lex(FlagTok); if (FlagTok.is(tok::eom)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) @@ -782,9 +782,9 @@ static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, PP.DiscardUntilEndOfDirective(); return true; } - + IsExternCHeader = true; - + PP.Lex(FlagTok); if (FlagTok.is(tok::eom)) return false; @@ -798,7 +798,7 @@ static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, /// one of the following forms: /// /// # 42 -/// # 42 "file" ('1' | '2')? +/// # 42 "file" ('1' | '2')? /// # 42 "file" ('1' | '2')? '3' '4'? /// void Preprocessor::HandleDigitDirective(Token &DigitTok) { @@ -808,17 +808,17 @@ void Preprocessor::HandleDigitDirective(Token &DigitTok) { if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, *this)) return; - + Token StrTok; Lex(StrTok); - + bool IsFileEntry = false, IsFileExit = false; bool IsSystemHeader = false, IsExternCHeader = false; int FilenameID = -1; // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a // string followed by eom. - if (StrTok.is(tok::eom)) + if (StrTok.is(tok::eom)) ; // ok else if (StrTok.isNot(tok::string_literal)) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); @@ -835,18 +835,18 @@ void Preprocessor::HandleDigitDirective(Token &DigitTok) { } FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(), Literal.GetStringLength()); - + // If a filename was present, read any flags that are present. - if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, + if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, IsSystemHeader, IsExternCHeader, *this)) return; } - + // Create a line note with this information. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, - IsFileEntry, IsFileExit, + IsFileEntry, IsFileExit, IsSystemHeader, IsExternCHeader); - + // If the preprocessor has callbacks installed, notify them of the #line // change. This is used so that the line marker comes out in -E mode for // example. @@ -861,7 +861,7 @@ void Preprocessor::HandleDigitDirective(Token &DigitTok) { FileKind = SrcMgr::C_ExternCSystem; else if (IsSystemHeader) FileKind = SrcMgr::C_System; - + Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind); } } @@ -869,7 +869,7 @@ void Preprocessor::HandleDigitDirective(Token &DigitTok) { /// HandleUserDiagnosticDirective - Handle a #warning or #error directive. /// -void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, +void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, bool isWarning) { // PTH doesn't emit #warning or #error directives. if (CurPTHLexer) @@ -892,11 +892,11 @@ void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { // Yes, this directive is an extension. Diag(Tok, diag::ext_pp_ident_directive); - + // Read the string argument. Token StrTok; Lex(StrTok); - + // If the token kind isn't a string, it's a malformed directive. if (StrTok.isNot(tok::string_literal) && StrTok.isNot(tok::wide_string_literal)) { @@ -905,7 +905,7 @@ void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { DiscardUntilEndOfDirective(); return; } - + // Verify that there is nothing after the string, other than EOM. CheckEndOfDirective("ident"); @@ -928,7 +928,7 @@ bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, const char *&BufEnd) { // Get the text form of the filename. assert(BufStart != BufEnd && "Can't have tokens with empty spellings!"); - + // Make sure the filename is or "x". bool isAngled; if (BufStart[0] == '<') { @@ -950,14 +950,14 @@ bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, BufStart = 0; return true; } - + // Diagnose #include "" as invalid. if (BufEnd-BufStart <= 2) { Diag(Loc, diag::err_pp_empty_filename); BufStart = 0; return ""; } - + // Skip the brackets. ++BufStart; --BufEnd; @@ -977,33 +977,33 @@ bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, static bool ConcatenateIncludeName(llvm::SmallVector &FilenameBuffer, Preprocessor &PP) { Token CurTok; - + PP.Lex(CurTok); while (CurTok.isNot(tok::eom)) { // Append the spelling of this token to the buffer. If there was a space // before it, add it now. if (CurTok.hasLeadingSpace()) FilenameBuffer.push_back(' '); - + // Get the spelling of the token, directly into FilenameBuffer if possible. unsigned PreAppendSize = FilenameBuffer.size(); FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); - + const char *BufPtr = &FilenameBuffer[PreAppendSize]; unsigned ActualLen = PP.getSpelling(CurTok, BufPtr); - + // If the token was spelled somewhere else, copy it into FilenameBuffer. if (BufPtr != &FilenameBuffer[PreAppendSize]) memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); - + // Resize FilenameBuffer to the correct size. if (CurTok.getLength() != ActualLen) FilenameBuffer.resize(PreAppendSize+ActualLen); - + // If we found the '>' marker, return success. if (CurTok.is(tok::greater)) return false; - + PP.Lex(CurTok); } @@ -1017,14 +1017,14 @@ static bool ConcatenateIncludeName(llvm::SmallVector &FilenameBuffer, /// file to be included from the lexer, then include it! This is a common /// routine with functionality shared between #include, #include_next and /// #import. LookupFrom is set when this is a #include_next directive, it -/// specifies the file to start searching from. +/// specifies the file to start searching from. void Preprocessor::HandleIncludeDirective(Token &IncludeTok, const DirectoryLookup *LookupFrom, bool isImport) { Token FilenameTok; CurPPLexer->LexIncludeFilename(FilenameTok); - + // Reserve a buffer to get the spelling. llvm::SmallVector FilenameBuffer; const char *FilenameStart, *FilenameEnd; @@ -1033,7 +1033,7 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, case tok::eom: // If the token kind is EOM, the error has already been diagnosed. return; - + case tok::angle_string_literal: case tok::string_literal: { FilenameBuffer.resize(FilenameTok.getLength()); @@ -1042,7 +1042,7 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, FilenameEnd = FilenameStart+Len; break; } - + case tok::less: // This could be a file coming from a macro expansion. In this // case, glue the tokens together into FilenameBuffer and interpret those. @@ -1057,7 +1057,7 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, DiscardUntilEndOfDirective(); return; } - + bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), FilenameStart, FilenameEnd); // If GetIncludeFilenameSpelling set the start ptr to null, there was an @@ -1066,7 +1066,7 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, DiscardUntilEndOfDirective(); return; } - + // Verify that there is nothing after the filename, other than EOM. Note that // we allow macros that expand to nothing after the filename, because this // falls into the category of "#include pp-tokens new-line" specified in @@ -1078,7 +1078,7 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, Diag(FilenameTok, diag::err_pp_include_too_deep); return; } - + // Search include directories. const DirectoryLookup *CurDir; const FileEntry *File = LookupFile(FilenameStart, FilenameEnd, @@ -1088,19 +1088,19 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, << std::string(FilenameStart, FilenameEnd); return; } - + // Ask HeaderInfo if we should enter this #include file. If not, #including // this file will have no effect. if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) return; - + // The #included file will be considered to be a system header if either it is // in a system include directory, or if the #includer is a system include // header. - SrcMgr::CharacteristicKind FileCharacter = + SrcMgr::CharacteristicKind FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), SourceMgr.getFileCharacteristic(FilenameTok.getLocation())); - + // Look up the file, create a File ID for it. FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(), FileCharacter); @@ -1118,7 +1118,7 @@ void Preprocessor::HandleIncludeDirective(Token &IncludeTok, /// void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) { Diag(IncludeNextTok, diag::ext_pp_include_next_directive); - + // #include_next is like #include, except that we start searching after // the current found directory. If we can't do this, issue a // diagnostic. @@ -1132,7 +1132,7 @@ void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) { // Start looking up in the next directory. ++Lookup; } - + return HandleIncludeDirective(IncludeNextTok, Lookup); } @@ -1141,7 +1141,7 @@ void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) { void Preprocessor::HandleImportDirective(Token &ImportTok) { if (!Features.ObjC1) // #import is standard for ObjC. Diag(ImportTok, diag::ext_pp_import_directive); - + return HandleIncludeDirective(ImportTok, 0, true); } @@ -1159,11 +1159,11 @@ void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) { DiscardUntilEndOfDirective(); return; } - + // Treat this as a normal #include for checking purposes. If this is // successful, it will push a new lexer onto the include stack. HandleIncludeDirective(IncludeMacrosTok, 0, false); - + Token TmpTok; do { Lex(TmpTok); @@ -1181,7 +1181,7 @@ void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) { /// parsing the arg list. bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) { llvm::SmallVector Arguments; - + Token Tok; while (1) { LexUnexpandedToken(Tok); @@ -1223,18 +1223,18 @@ bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) { // If this is already used as an argument, it is used multiple times (e.g. // #define X(A,A. - if (std::find(Arguments.begin(), Arguments.end(), II) != + if (std::find(Arguments.begin(), Arguments.end(), II) != Arguments.end()) { // C99 6.10.3p6 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; return true; } - + // Add the argument to the macro info. Arguments.push_back(II); - + // Lex the token after the identifier. LexUnexpandedToken(Tok); - + switch (Tok.getKind()) { default: // #define X(A B Diag(Tok, diag::err_pp_expected_comma_in_arg_list); @@ -1247,14 +1247,14 @@ bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) { case tok::ellipsis: // #define X(A... -> GCC extension // Diagnose extension. Diag(Tok, diag::ext_named_variadic_macro); - + // Lex the token after the identifier. LexUnexpandedToken(Tok); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; } - + MI->setIsGNUVarargs(); MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; @@ -1270,7 +1270,7 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { Token MacroNameTok; ReadMacroName(MacroNameTok, 1); - + // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eom)) return; @@ -1280,13 +1280,13 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { // If we are supposed to keep comments in #defines, reenable comment saving // mode. if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); - + // Create the new macro. MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation()); - + Token Tok; LexUnexpandedToken(Tok); - + // If this is a function-like macro definition, parse the argument list, // marking each of the identifiers as being used as macro arguments. Also, // check other constraints on the first token of the macro body. @@ -1310,13 +1310,13 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { // If this is a definition of a variadic C99 function-like macro, not using // the GNU named varargs extension, enabled __VA_ARGS__. - + // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. // This gets unpoisoned where it is allowed. assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); if (MI->isC99Varargs()) Ident__VA_ARGS__->setIsPoisoned(false); - + // Read the first token after the arg list for down below. LexUnexpandedToken(Tok); } else if (Features.C99) { @@ -1357,7 +1357,7 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { // Get the next token of the macro. LexUnexpandedToken(Tok); } - + } else { // Otherwise, read the body of a function-like macro. While we are at it, // check C99 6.10.3.2p1: ensure that # operators are followed by macro @@ -1367,15 +1367,15 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { if (Tok.isNot(tok::hash)) { MI->AddTokenToBody(Tok); - + // Get the next token of the macro. LexUnexpandedToken(Tok); continue; } - + // Get the next token of the macro. LexUnexpandedToken(Tok); - + // Check for a valid macro arg identifier. if (Tok.getIdentifierInfo() == 0 || MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { @@ -1389,24 +1389,24 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { } else { Diag(Tok, diag::err_pp_stringize_not_parameter); ReleaseMacroInfo(MI); - + // Disable __VA_ARGS__ again. Ident__VA_ARGS__->setIsPoisoned(true); return; } } - + // Things look ok, add the '#' and param name tokens to the macro. MI->AddTokenToBody(LastTok); MI->AddTokenToBody(Tok); LastTok = Tok; - + // Get the next token of the macro. LexUnexpandedToken(Tok); } } - - + + // Disable __VA_ARGS__ again. Ident__VA_ARGS__->setIsPoisoned(true); @@ -1425,14 +1425,14 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { return; } } - + // If this is the primary source file, remember that this macro hasn't been // used yet. if (isInPrimaryFile()) MI->setIsUsed(false); MI->setDefinitionEndLoc(LastTok.getLocation()); - + // Finally, if this identifier already had a macro defined for it, verify that // the macro bodies are identical and free the old definition. if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) { @@ -1452,12 +1452,12 @@ void Preprocessor::HandleDefineDirective(Token &DefineTok) { Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); } } - + ReleaseMacroInfo(OtherMI); } - + setMacroInfo(MacroNameTok.getIdentifierInfo(), MI); - + // If the callbacks want to know, tell them about the macro definition. if (Callbacks) Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI); @@ -1470,17 +1470,17 @@ void Preprocessor::HandleUndefDirective(Token &UndefTok) { Token MacroNameTok; ReadMacroName(MacroNameTok, 2); - + // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eom)) return; - + // Check to see if this is the last token on the #undef line. CheckEndOfDirective("undef"); - + // Okay, we finally have a valid identifier to undef. MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo()); - + // If the macro is not defined, this is a noop undef, just return. if (MI == 0) return; @@ -1513,7 +1513,7 @@ void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, Token MacroNameTok; ReadMacroName(MacroNameTok); - + // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eom)) { // Skip code until we get to #endif. This helps with recovery by not @@ -1522,7 +1522,7 @@ void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, /*Foundnonskip*/false, /*FoundElse*/false); return; } - + // Check to see if this is the last token on the #if[n]def line. CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef"); @@ -1541,7 +1541,7 @@ void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, // If there is a macro, process it. if (MI) // Mark it used. MI->setIsUsed(true); - + // Should we include the stuff contained by this directive? if (!MI == isIfndef) { // Yes, remember that we are inside a conditional, then lex the next token. @@ -1550,7 +1550,7 @@ void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, } else { // No, skip the contents of this block and return the first token after it. SkipExcludedConditionalBlock(DirectiveTok.getLocation(), - /*Foundnonskip*/false, + /*Foundnonskip*/false, /*FoundElse*/false); } } @@ -1560,11 +1560,11 @@ void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, void Preprocessor::HandleIfDirective(Token &IfToken, bool ReadAnyTokensBeforeDirective) { ++NumIf; - + // Parse and evaluation the conditional expression. IdentifierInfo *IfNDefMacro = 0; bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); - + // If this condition is equivalent to #ifndef X, and if this is the first // directive seen, handle it for the multiple-include optimization. @@ -1582,7 +1582,7 @@ void Preprocessor::HandleIfDirective(Token &IfToken, /*foundnonskip*/true, /*foundelse*/false); } else { // No, skip the contents of this block and return the first token after it. - SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, + SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); } } @@ -1591,21 +1591,21 @@ void Preprocessor::HandleIfDirective(Token &IfToken, /// void Preprocessor::HandleEndifDirective(Token &EndifToken) { ++NumEndif; - + // Check that this is the whole directive. CheckEndOfDirective("endif"); - + PPConditionalInfo CondInfo; if (CurPPLexer->popConditionalLevel(CondInfo)) { // No conditionals on the stack: this is an #endif without an #if. Diag(EndifToken, diag::err_pp_endif_without_if); return; } - + // If this the end of a top-level #endif, inform MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.ExitTopLevelConditional(); - + assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && "This code should only be reachable in the non-skipping case!"); } @@ -1613,23 +1613,23 @@ void Preprocessor::HandleEndifDirective(Token &EndifToken) { void Preprocessor::HandleElseDirective(Token &Result) { ++NumElse; - + // #else directive in a non-skipping conditional... start skipping. CheckEndOfDirective("else"); - + PPConditionalInfo CI; if (CurPPLexer->popConditionalLevel(CI)) { Diag(Result, diag::pp_err_else_without_if); return; } - + // If this is a top-level #else, inform the MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.EnterTopLevelConditional(); // If this is a #else with a #else before it, report the error. if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); - + // Finally, skip the rest of the contents of this block and return the first // token after it. return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, @@ -1638,7 +1638,7 @@ void Preprocessor::HandleElseDirective(Token &Result) { void Preprocessor::HandleElifDirective(Token &ElifToken) { ++NumElse; - + // #elif directive in a non-skipping conditional... start skipping. // We don't care what the condition is, because we will always skip it (since // the block immediately before it was included). @@ -1649,11 +1649,11 @@ void Preprocessor::HandleElifDirective(Token &ElifToken) { Diag(ElifToken, diag::pp_err_elif_without_if); return; } - + // If this is a top-level #elif, inform the MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.EnterTopLevelConditional(); - + // If this is a #elif with a #else before it, report the error. if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); diff --git a/clang/lib/Lex/PPExpressions.cpp b/clang/lib/Lex/PPExpressions.cpp index a7307c6b56eb43345bc56267f69f7b780f485adb..908385c5d392171d604f4dec7354f8e148c92c39 100644 --- a/clang/lib/Lex/PPExpressions.cpp +++ b/clang/lib/Lex/PPExpressions.cpp @@ -30,18 +30,18 @@ class PPValue { SourceRange Range; public: llvm::APSInt Val; - + // Default ctor - Construct an 'invalid' PPValue. PPValue(unsigned BitWidth) : Val(BitWidth) {} - + unsigned getBitWidth() const { return Val.getBitWidth(); } bool isUnsigned() const { return Val.isUnsigned(); } - + const SourceRange &getRange() const { return Range; } - + void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); } void setRange(SourceLocation B, SourceLocation E) { - Range.setBegin(B); Range.setEnd(E); + Range.setBegin(B); Range.setEnd(E); } void setBegin(SourceLocation L) { Range.setBegin(L); } void setEnd(SourceLocation L) { Range.setEnd(L); } @@ -82,7 +82,7 @@ struct DefinedTracker { static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP) { DT.State = DefinedTracker::Unknown; - + // If this token's spelling is a pp-identifier, check to see if it is // 'defined' or if it is a macro. Note that we check here because many // keywords are pp-identifiers, so we can't check the kind. @@ -113,13 +113,13 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, LParenLoc = PeekTok.getLocation(); PP.LexUnexpandedToken(PeekTok); } - + // If we don't have a pp-identifier now, this is an error. if ((II = PeekTok.getIdentifierInfo()) == 0) { PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier); return true; } - + // Otherwise, we got an identifier, is it defined to something? Result.Val = II->hasMacroDefinition(); Result.Val.setIsUnsigned(false); // Result is signed intmax_t. @@ -145,13 +145,13 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, Result.setEnd(PeekTok.getLocation()); PP.LexNonComment(PeekTok); } - + // Success, remember that we saw defined(X). DT.State = DefinedTracker::DefinedMacro; DT.TheMacro = II; return false; } - + switch (PeekTok.getKind()) { default: // Non-value token. PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr); @@ -166,11 +166,11 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, IntegerBuffer.resize(PeekTok.getLength()); const char *ThisTokBegin = &IntegerBuffer[0]; unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin); - NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, + NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, PeekTok.getLocation(), PP); if (Literal.hadError) return true; // a diagnostic was already reported. - + if (Literal.isFloatingLiteral() || Literal.isImaginary) { PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal); return true; @@ -191,7 +191,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, // Set the signedness of the result to match whether there was a U suffix // or not. Result.Val.setIsUnsigned(Literal.isUnsigned); - + // Detect overflow based on whether the value is signed. If signed // and if the value is too large, emit a warning "integer constant is so // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t @@ -203,7 +203,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, Result.Val.setIsUnsigned(true); } } - + // Consume the token. Result.setRange(PeekTok.getLocation()); PP.LexNonComment(PeekTok); @@ -214,7 +214,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, CharBuffer.resize(PeekTok.getLength()); const char *ThisTokBegin = &CharBuffer[0]; unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin); - CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, + CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, PeekTok.getLocation(), PP); if (Literal.hadError()) return true; // A diagnostic was already emitted. @@ -235,7 +235,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, Val = Literal.getValue(); // Set the signedness. Val.setIsUnsigned(!PP.getLangOptions().CharIsSigned); - + if (Result.Val.getBitWidth() > Val.getBitWidth()) { Result.Val = Val.extend(Result.Val.getBitWidth()); } else { @@ -264,7 +264,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, // Otherwise, we have something like (x+y), and we consumed '(x'. if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP)) return true; - + if (PeekTok.isNot(tok::r_paren)) { PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen) << Result.getRange(); @@ -290,21 +290,21 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, PP.LexNonComment(PeekTok); if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; Result.setBegin(Loc); - + // C99 6.5.3.3p3: The sign of the result matches the sign of the operand. Result.Val = -Result.Val; - + // -MININT is the only thing that overflows. Unsigned never overflows. bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue(); - + // If this operator is live and overflowed, report the issue. if (Overflow && ValueLive) PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange(); - + DT.State = DefinedTracker::Unknown; return false; } - + case tok::tilde: { SourceLocation Start = PeekTok.getLocation(); PP.LexNonComment(PeekTok); @@ -316,7 +316,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, DT.State = DefinedTracker::Unknown; return false; } - + case tok::exclaim: { SourceLocation Start = PeekTok.getLocation(); PP.LexNonComment(PeekTok); @@ -325,14 +325,14 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, Result.Val = !Result.Val; // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed. Result.Val.setIsUnsigned(false); - + if (DT.State == DefinedTracker::DefinedMacro) DT.State = DefinedTracker::NotDefinedMacro; else if (DT.State == DefinedTracker::NotDefinedMacro) DT.State = DefinedTracker::DefinedMacro; return false; } - + // FIXME: Handle #assert } } @@ -390,17 +390,17 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, << LHS.getRange(); return true; } - + while (1) { // If this token has a lower precedence than we are allowed to parse, return // it so that higher levels of the recursion can parse it. if (PeekPrec < MinPrec) return false; - + tok::TokenKind Operator = PeekTok.getKind(); - + // If this is a short-circuiting operator, see if the RHS of the operator is - // dead. Note that this cannot just clobber ValueLive. Consider + // dead. Note that this cannot just clobber ValueLive. Consider // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In // this example, the RHS of the && being dead does not make the rest of the // expr dead. @@ -434,7 +434,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, << RHS.getRange(); return true; } - + // Decide whether to include the next binop in this subexpression. For // example, when parsing x+y*z and looking at '*', we want to recursively // handle y*z as a single subexpression. We do this because the precedence @@ -451,16 +451,16 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, RHSPrec = getPrecedence(tok::comma); else // All others should munch while higher precedence. RHSPrec = ThisPrec+1; - + if (PeekPrec >= RHSPrec) { if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP)) return true; PeekPrec = getPrecedence(PeekTok.getKind()); } assert(PeekPrec <= ThisPrec && "Recursion didn't work!"); - + // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if - // either operand is unsigned. + // either operand is unsigned. llvm::APSInt Res(LHS.getBitWidth()); switch (Operator) { case tok::question: // No UAC for x and y in "x ? y : z". @@ -489,7 +489,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, LHS.Val.setIsUnsigned(Res.isUnsigned()); RHS.Val.setIsUnsigned(Res.isUnsigned()); } - + // FIXME: All of these should detect and report overflow?? bool Overflow = false; switch (Operator) { @@ -514,7 +514,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, return true; } break; - + case tok::star: Res = LHS.Val * RHS.Val; if (Res.isSigned() && LHS.Val != 0 && RHS.Val != 0) @@ -531,7 +531,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, Overflow = ShAmt >= LHS.Val.countLeadingZeros(); else Overflow = ShAmt >= LHS.Val.countLeadingOnes(); - + Res = LHS.Val << ShAmt; break; } @@ -607,7 +607,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, PP.Diag(OpLoc, diag::ext_pp_comma_expr) << LHS.getRange() << RHS.getRange(); Res = RHS.Val; // LHS = LHS,RHS -> RHS. - break; + break; case tok::question: { // Parse the : part of the expression. if (PeekTok.isNot(tok::colon)) { @@ -631,7 +631,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec, PeekTok, AfterColonLive, PP)) return true; - + // Now that we have the condition, the LHS and the RHS of the :, evaluate. Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val; RHS.setEnd(AfterColonVal.getRange().getEnd()); @@ -639,7 +639,7 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if // either operand is unsigned. Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned()); - + // Figure out the precedence of the token after the : part. PeekPrec = getPrecedence(PeekTok.getKind()); break; @@ -655,12 +655,12 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, if (Overflow && ValueLive) PP.Diag(OpLoc, diag::warn_pp_expr_overflow) << LHS.getRange() << RHS.getRange(); - + // Put the result back into 'LHS' for our next iteration. LHS.Val = Res; LHS.setEnd(RHS.getRange().getEnd()); } - + return false; } @@ -672,10 +672,10 @@ EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // Peek ahead one token. Token Tok; Lex(Tok); - + // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t. unsigned BitWidth = getTargetInfo().getIntMaxTWidth(); - + PPValue ResVal(BitWidth); DefinedTracker DT; if (EvaluateValue(ResVal, Tok, DT, true, *this)) { @@ -684,7 +684,7 @@ EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { DiscardUntilEndOfDirective(); return false; } - + // If we are at the end of the expression after just parsing a value, there // must be no (unparenthesized) binary operators involved, so we can exit // directly. @@ -693,10 +693,10 @@ EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // macro in IfNDefMacro. if (DT.State == DefinedTracker::NotDefinedMacro) IfNDefMacro = DT.TheMacro; - + return ResVal.Val != 0; } - + // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the // operator and the stuff after it. if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question), @@ -706,14 +706,14 @@ EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { DiscardUntilEndOfDirective(); return false; } - + // If we aren't at the tok::eom token, something bad happened, like an extra // ')' token. if (Tok.isNot(tok::eom)) { Diag(Tok, diag::err_pp_expected_eol); DiscardUntilEndOfDirective(); } - + return ResVal.Val != 0; } diff --git a/clang/lib/Lex/PPLexerChange.cpp b/clang/lib/Lex/PPLexerChange.cpp index 2a05ba336fcacf1e3fa01516b3e7fd6e7798668d..41ed991436b9e3b18093f4b96698d1ae032a6dd4 100644 --- a/clang/lib/Lex/PPLexerChange.cpp +++ b/clang/lib/Lex/PPLexerChange.cpp @@ -31,7 +31,7 @@ PPCallbacks::~PPCallbacks() {} bool Preprocessor::isInPrimaryFile() const { if (IsFileLexer()) return IncludeMacroStack.empty(); - + // If there are any stacked lexers, we're in a #include. assert(IsFileLexer(IncludeMacroStack[0]) && "Top level include stack isn't our primary lexer?"); @@ -47,7 +47,7 @@ bool Preprocessor::isInPrimaryFile() const { PreprocessorLexer *Preprocessor::getCurrentFileLexer() const { if (IsFileLexer()) return CurPPLexer; - + // Look for a stacked lexer. for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { const IncludeStackInfo& ISI = IncludeMacroStack[i-1]; @@ -68,7 +68,7 @@ PreprocessorLexer *Preprocessor::getCurrentFileLexer() const { void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir) { assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!"); ++NumEnteredSourceFiles; - + if (MaxIncludeStackDepth < IncludeMacroStack.size()) MaxIncludeStackDepth = IncludeMacroStack.size(); @@ -77,13 +77,13 @@ void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir) { return EnterSourceFileWithPTH(PL, CurDir); } EnterSourceFileWithLexer(new Lexer(FID, *this), CurDir); -} +} /// EnterSourceFileWithLexer - Add a source file to the top of the include stack /// and start lexing tokens from it instead of the current buffer. -void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, +void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *CurDir) { - + // Add the current lexer to the include stack. if (CurPPLexer || CurTokenLexer) PushIncludeMacroStack(); @@ -91,12 +91,12 @@ void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, CurLexer.reset(TheLexer); CurPPLexer = TheLexer; CurDirLookup = CurDir; - + // Notify the client, if desired, that we are in a new source file. if (Callbacks && !CurLexer->Is_PragmaLexer) { SrcMgr::CharacteristicKind FileType = SourceMgr.getFileCharacteristic(CurLexer->getFileLoc()); - + Callbacks->FileChanged(CurLexer->getFileLoc(), PPCallbacks::EnterFile, FileType); } @@ -104,9 +104,9 @@ void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, /// EnterSourceFileWithPTH - Add a source file to the top of the include stack /// and start getting tokens from it using the PTH cache. -void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, +void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *CurDir) { - + if (CurPPLexer || CurTokenLexer) PushIncludeMacroStack(); @@ -130,7 +130,7 @@ void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd, MacroArgs *Args) { PushIncludeMacroStack(); CurDirLookup = 0; - + if (NumCachedTokenLexers == 0) { CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this)); } else { @@ -174,18 +174,18 @@ void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks, bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { assert(!CurTokenLexer && "Ending a file when currently in a macro!"); - + // See if this file had a controlling macro. if (CurPPLexer) { // Not ending a macro, ignore it. - if (const IdentifierInfo *ControllingMacro = + if (const IdentifierInfo *ControllingMacro = CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) { // Okay, this has a controlling macro, remember in HeaderFileInfo. - if (const FileEntry *FE = + if (const FileEntry *FE = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) HeaderInfo.SetFileControllingMacro(FE, ControllingMacro); } } - + // If this is a #include'd file, pop it off the include stack and continue // lexing the #includer file. if (!IncludeMacroStack.empty()) { @@ -197,7 +197,7 @@ bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { SrcMgr::CharacteristicKind FileType = SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation()); Callbacks->FileChanged(CurPPLexer->getSourceLocation(), - PPCallbacks::ExitFile, FileType); + PPCallbacks::ExitFile, FileType); } // Client should lex another token. @@ -210,21 +210,21 @@ bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { // actually typed, which is goodness. if (CurLexer) { const char *EndPos = CurLexer->BufferEnd; - if (EndPos != CurLexer->BufferStart && + if (EndPos != CurLexer->BufferStart && (EndPos[-1] == '\n' || EndPos[-1] == '\r')) { --EndPos; - + // Handle \n\r and \r\n: - if (EndPos != CurLexer->BufferStart && + if (EndPos != CurLexer->BufferStart && (EndPos[-1] == '\n' || EndPos[-1] == '\r') && EndPos[-1] != EndPos[0]) --EndPos; } - + Result.startToken(); CurLexer->BufferPtr = EndPos; CurLexer->FormTokenWithChars(Result, EndPos, tok::eof); - + // We're done with the #included file. CurLexer.reset(); } else { @@ -232,12 +232,12 @@ bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { CurPTHLexer->getEOF(Result); CurPTHLexer.reset(); } - + CurPPLexer = 0; // This is the end of the top-level file. If the diag::pp_macro_not_used // diagnostic is enabled, look for macros that have not been used. - if (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) != + if (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored) { for (macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I) if (!I->second->isUsed()) @@ -267,15 +267,15 @@ bool Preprocessor::HandleEndOfTokenLexer(Token &Result) { /// state of the top-of-stack lexer is unknown. void Preprocessor::RemoveTopOfLexerStack() { assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load"); - + if (CurTokenLexer) { // Delete or cache the now-dead macro expander. if (NumCachedTokenLexers == TokenLexerCacheSize) CurTokenLexer.reset(); else TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take(); - } - + } + PopIncludeMacroStack(); } @@ -285,7 +285,7 @@ void Preprocessor::RemoveTopOfLexerStack() { void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { assert(CurTokenLexer && !CurPPLexer && "Pasted comment can only be formed from macro"); - + // We handle this by scanning for the closest real lexer, switching it to // raw mode and preprocessor mode. This will cause it to return \n as an // explicit EOM token. @@ -294,7 +294,7 @@ void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1); if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer. - + // Once we find a real lexer, mark it as raw mode (disabling macro // expansions) and preprocessor mode (return EOM). We know that the lexer // was *not* in raw mode before, because the macro that the comment came @@ -307,12 +307,12 @@ void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { FoundLexer->ParsingPreprocessorDirective = true; break; } - + // Okay, we either found and switched over the lexer, or we didn't find a // lexer. In either case, finish off the macro the comment came from, getting // the next token. if (!HandleEndOfTokenLexer(Tok)) Lex(Tok); - + // Discarding comments as long as we don't have EOF or EOM. This 'comments // out' the rest of the line, including any tokens that came from other macros // that were active, as in: @@ -321,22 +321,22 @@ void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { // which should lex to 'a' only: 'b' and 'c' should be removed. while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof)) Lex(Tok); - + // If we got an eom token, then we successfully found the end of the line. if (Tok.is(tok::eom)) { assert(FoundLexer && "Can't get end of line without an active lexer"); // Restore the lexer back to normal mode instead of raw mode. FoundLexer->LexingRawMode = false; - + // If the lexer was already in preprocessor mode, just return the EOM token // to finish the preprocessor line. if (LexerWasInPPMode) return; - + // Otherwise, switch out of PP mode and return the next lexed token. FoundLexer->ParsingPreprocessorDirective = false; return Lex(Tok); } - + // If we got an EOF token, then we reached the end of the token stream but // didn't find an explicit \n. This can only happen if there was no lexer // active (an active lexer would return EOM at EOF if there was no \n in diff --git a/clang/lib/Lex/PPMacroExpansion.cpp b/clang/lib/Lex/PPMacroExpansion.cpp index b57f68a5a5ddb53cbe8b0ceb4d7925f02cec482c..47056fc380db4da709e2b7bfb569f52d02b08ae9 100644 --- a/clang/lib/Lex/PPMacroExpansion.cpp +++ b/clang/lib/Lex/PPMacroExpansion.cpp @@ -39,7 +39,7 @@ void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) { static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ // Get the identifier. IdentifierInfo *Id = PP.getIdentifierInfo(Name); - + // Mark it as being a macro that is builtin. MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); MI->setIsBuiltinMacro(); @@ -57,12 +57,12 @@ void Preprocessor::RegisterBuiltinMacros() { Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); - + // GCC Extensions. Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); - + // Clang Extensions. Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); @@ -77,14 +77,14 @@ static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, // If the token isn't an identifier, it's always literally expanded. if (II == 0) return true; - + // If the identifier is a macro, and if that macro is enabled, it may be // expanded so it's not a trivial expansion. if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() && // Fast expanding "#define X X" is ok, because X would be disabled. II != MacroIdent) return false; - + // If this is an object-like macro invocation, it is safe to trivially expand // it. if (MI->isObjectLike()) return true; @@ -95,7 +95,7 @@ static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, I != E; ++I) if (*I == II) return false; // Identifier is a macro argument. - + return true; } @@ -112,7 +112,7 @@ bool Preprocessor::isNextPPTokenLParen() { Val = CurPTHLexer->isNextPPTokenLParen(); else Val = CurTokenLexer->isNextTokenLParen(); - + if (Val == 2) { // We have run off the end. If it's a source file we don't // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the @@ -127,10 +127,10 @@ bool Preprocessor::isNextPPTokenLParen() { Val = Entry.ThePTHLexer->isNextPPTokenLParen(); else Val = Entry.TheTokenLexer->isNextTokenLParen(); - + if (Val != 2) break; - + // Ran off the end of a source file? if (Entry.ThePPLexer) return false; @@ -145,72 +145,72 @@ bool Preprocessor::isNextPPTokenLParen() { /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be /// expanded as a macro, handle it and return the next token as 'Identifier'. -bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, +bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, MacroInfo *MI) { if (Callbacks) Callbacks->MacroExpands(Identifier, MI); - + // If this is a macro exapnsion in the "#if !defined(x)" line for the file, // then the macro could expand to different things in other contexts, we need // to disable the optimization in this case. if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); - + // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. if (MI->isBuiltinMacro()) { ExpandBuiltinMacro(Identifier); return false; } - + /// Args - If this is a function-like macro expansion, this contains, /// for each macro argument, the list of tokens that were provided to the /// invocation. MacroArgs *Args = 0; - + // Remember where the end of the instantiation occurred. For an object-like // macro, this is the identifier. For a function-like macro, this is the ')'. SourceLocation InstantiationEnd = Identifier.getLocation(); - + // If this is a function-like macro, read the arguments. if (MI->isFunctionLike()) { // C99 6.10.3p10: If the preprocessing token immediately after the the macro // name isn't a '(', this macro should not be expanded. if (!isNextPPTokenLParen()) return true; - + // Remember that we are now parsing the arguments to a macro invocation. // Preprocessor directives used inside macro arguments are not portable, and // this enables the warning. InMacroArgs = true; Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd); - + // Finished parsing args. InMacroArgs = false; - + // If there was an error parsing the arguments, bail out. if (Args == 0) return false; - + ++NumFnMacroExpanded; } else { ++NumMacroExpanded; } - + // Notice that this macro has been used. MI->setIsUsed(true); - + // If we started lexing a macro, enter the macro expansion body. - + // If this macro expands to no tokens, don't bother to push it onto the // expansion stack, only to take it right back off. if (MI->getNumTokens() == 0) { // No need for arg info. if (Args) Args->destroy(); - + // Ignore this macro use, just return the next token in the current // buffer. bool HadLeadingSpace = Identifier.hasLeadingSpace(); bool IsAtStartOfLine = Identifier.isAtStartOfLine(); - + Lex(Identifier); - + // If the identifier isn't on some OTHER line, inherit the leading // whitespace/first-on-a-line property of this token. This handles // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is @@ -221,12 +221,12 @@ bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, } ++NumFastMacroExpanded; return false; - + } else if (MI->getNumTokens() == 1 && isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), *this)) { // Otherwise, if this macro expands into a single trivially-expanded - // token: expand it now. This handles common cases like + // token: expand it now. This handles common cases like // "#define VAL 42". // No need for arg info. @@ -236,38 +236,38 @@ bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, // identifier to the expanded token. bool isAtStartOfLine = Identifier.isAtStartOfLine(); bool hasLeadingSpace = Identifier.hasLeadingSpace(); - + // Remember where the token is instantiated. SourceLocation InstantiateLoc = Identifier.getLocation(); - + // Replace the result token. Identifier = MI->getReplacementToken(0); - + // Restore the StartOfLine/LeadingSpace markers. Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); - + // Update the tokens location to include both its instantiation and physical // locations. SourceLocation Loc = SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc, InstantiationEnd,Identifier.getLength()); Identifier.setLocation(Loc); - + // If this is #define X X, we must mark the result as unexpandible. if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) if (getMacroInfo(NewII) == MI) Identifier.setFlag(Token::DisableExpand); - + // Since this is not an identifier token, it can't be macro expanded, so // we're done. ++NumFastMacroExpanded; return false; } - + // Start expanding the macro. EnterMacro(Identifier, InstantiationEnd, Args); - + // Now that the macro is at the top of the include stack, ask the // preprocessor to read the next token from it. Lex(Identifier); @@ -284,7 +284,7 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, // The number of fixed arguments to parse. unsigned NumFixedArgsLeft = MI->getNumArgs(); bool isVariadic = MI->isVariadic(); - + // Outer loop, while there are more arguments, keep reading them. Token Tok; @@ -292,7 +292,7 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, // an argument value in a macro could expand to ',' or '(' or ')'. LexUnexpandedToken(Tok); assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); - + // ArgTokens - Build up a list of tokens that make up each argument. Each // argument is separated by an EOF token. Use a SmallVector so we can avoid // heap allocations in the common case. @@ -302,19 +302,19 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, while (Tok.isNot(tok::r_paren)) { assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) && "only expect argument separators here"); - + unsigned ArgTokenStart = ArgTokens.size(); SourceLocation ArgStartLoc = Tok.getLocation(); - + // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note // that we already consumed the first one. unsigned NumParens = 0; - + while (1) { // Read arguments as unexpanded tokens. This avoids issues, e.g., where // an argument value in a macro could expand to ',' or '(' or ')'. LexUnexpandedToken(Tok); - + if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(" & "#if f(\n" Diag(MacroName, diag::err_unterm_macro_invoc); // Do not lose the EOF/EOM. Return it to the client. @@ -331,7 +331,7 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, } else if (Tok.is(tok::comma) && NumParens == 0) { // Comma ends this argument if there are more fixed arguments expected. // However, if this is a variadic macro, and this is part of the - // variadic part, then the comma is just an argument token. + // variadic part, then the comma is just an argument token. if (!isVariadic) break; if (NumFixedArgsLeft > 1) break; @@ -344,7 +344,7 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, // expanding from to be popped off the expansion stack. Doing so causes // them to be reenabled for expansion. Here we record whether any // identifiers we lex as macro arguments correspond to disabled macros. - // If so, we mark the token as noexpand. This is a subtle aspect of + // If so, we mark the token as noexpand. This is a subtle aspect of // C99 6.10.3.4p2. if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) if (!MI->isEnabled()) @@ -352,7 +352,7 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, } ArgTokens.push_back(Tok); } - + // If this was an empty argument list foo(), don't add this as an empty // argument. if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) @@ -363,18 +363,18 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, if (!isVariadic && NumFixedArgsLeft == 0) { if (ArgTokens.size() != ArgTokenStart) ArgStartLoc = ArgTokens[ArgTokenStart].getLocation(); - + // Emit the diagnostic at the macro name in case there is a missing ). // Emitting it at the , could be far away from the macro name. Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc); return 0; } - + // Empty arguments are standard in C99 and supported as an extension in // other modes. if (ArgTokens.size() == ArgTokenStart && !Features.C99) Diag(Tok, diag::ext_empty_fnmacro_arg); - + // Add a marker EOF token to the end of the token list for this argument. Token EOFTok; EOFTok.startToken(); @@ -386,19 +386,19 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, assert(NumFixedArgsLeft != 0 && "Too many arguments parsed"); --NumFixedArgsLeft; } - + // Okay, we either found the r_paren. Check to see if we parsed too few // arguments. unsigned MinArgsExpected = MI->getNumArgs(); - + // See MacroArgs instance var for description of this. bool isVarargsElided = false; - + if (NumActuals < MinArgsExpected) { // There are several cases where too few arguments is ok, handle them now. if (NumActuals == 0 && MinArgsExpected == 1) { // #define A(X) or #define A(...) ---> A() - + // If there is exactly one argument, and that argument is missing, // then we have an empty "()" argument empty list. This is fine, even if // the macro expects one argument (the argument is just empty). @@ -413,9 +413,9 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, // Remember this occurred, allowing us to elide the comma when used for // cases like: - // #define A(x, foo...) blah(a, ## foo) - // #define B(x, ...) blah(a, ## __VA_ARGS__) - // #define C(...) blah(a, ## __VA_ARGS__) + // #define A(x, foo...) blah(a, ## foo) + // #define B(x, ...) blah(a, ## __VA_ARGS__) + // #define C(...) blah(a, ## __VA_ARGS__) // A(x) B(x) C() isVarargsElided = true; } else { @@ -423,7 +423,7 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, Diag(Tok, diag::err_too_few_args_in_macro_invoc); return 0; } - + // Add a marker EOF token to the end of the token list for this argument. SourceLocation EndLoc = Tok.getLocation(); Tok.startToken(); @@ -435,14 +435,14 @@ MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, // If we expect two arguments, add both as empty. if (NumActuals == 0 && MinArgsExpected == 2) ArgTokens.push_back(Tok); - + } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) { // Emit the diagnostic at the macro name in case there is a missing ). // Emitting it at the , could be far away from the macro name. Diag(MacroName, diag::err_too_many_args_in_macro_invoc); return 0; } - + return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(), isVarargsElided); } @@ -454,15 +454,15 @@ static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP) { time_t TT = time(0); struct tm *TM = localtime(&TT); - + static const char * const Months[] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; - + char TmpBuffer[100]; - sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, + sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, TM->tm_year+1900); - + Token TmpTok; TmpTok.startToken(); PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok); @@ -478,7 +478,7 @@ static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, /// specified by the identifier. static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { const LangOptions &LangOpts = PP.getLangOptions(); - + switch (II->getLength()) { default: return false; case 6: @@ -510,12 +510,12 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // Figure out which token this is. IdentifierInfo *II = Tok.getIdentifierInfo(); assert(II && "Can't be a macro without id info!"); - + // If this is an _Pragma directive, expand it, invoke the pragma handler, then // lex the token after it. if (II == Ident_Pragma) return Handle_Pragma(Tok); - + ++NumBuiltinMacroExpanded; char TmpBuffer[100]; @@ -523,17 +523,17 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // Set up the return result. Tok.setIdentifierInfo(0); Tok.clearFlag(Token::NeedsCleaning); - + if (II == Ident__LINE__) { // C99 6.10.8: "__LINE__: The presumed line number (within the current // source file) of the current source line (an integer constant)". This can // be affected by #line. SourceLocation Loc = Tok.getLocation(); - + // Advance to the location of the first _, this might not be the first byte // of the token if it starts with an escaped newline. Loc = AdvanceToTokenCharacter(Loc, 0); - + // One wrinkle here is that GCC expands __LINE__ to location of the *end* of // a macro instantiation. This doesn't matter for object-like macros, but // can matter for a function-like macro that expands to contain __LINE__. @@ -541,7 +541,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // end of the instantiation history. Loc = SourceMgr.getInstantiationRange(Loc).second; PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); - + // __LINE__ expands to a simple numeric value. sprintf(TmpBuffer, "%u", PLoc.getLine()); Tok.setKind(tok::numeric_constant); @@ -561,7 +561,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { NextLoc = PLoc.getIncludeLoc(); } } - + // Escape this filename. Turn '\' -> '\\' '"' -> '\"' std::string FN = PLoc.getFilename(); FN = '"' + Lexer::Stringify(FN) + '"'; @@ -589,12 +589,12 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // Compute the presumed include depth of this token. This can be affected // by GNU line markers. unsigned Depth = 0; - + PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); for (; PLoc.isValid(); ++Depth) PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); - + // __INCLUDE_LEVEL__ expands to a simple numeric value. sprintf(TmpBuffer, "%u", Depth); Tok.setKind(tok::numeric_constant); @@ -608,10 +608,10 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // a macro, dig into the include stack. const FileEntry *CurFile = 0; PreprocessorLexer *TheLexer = getCurrentFileLexer(); - + if (TheLexer) CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); - + // If this file is older than the file it depends on, emit a diagnostic. const char *Result; if (CurFile) { @@ -629,7 +629,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation()); } else if (II == Ident__COUNTER__) { Diag(Tok, diag::ext_pp_counter); - + // __COUNTER__ expands to a simple numeric value. sprintf(TmpBuffer, "%u", CounterValue++); Tok.setKind(tok::numeric_constant); @@ -638,10 +638,10 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { II == Ident__has_builtin) { // The argument to these two builtins should be a parenthesized identifier. SourceLocation StartLoc = Tok.getLocation(); - + bool IsValid = false; IdentifierInfo *FeatureII = 0; - + // Read the '('. Lex(Tok); if (Tok.is(tok::l_paren)) { @@ -649,25 +649,25 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { Lex(Tok); if (Tok.is(tok::identifier)) { FeatureII = Tok.getIdentifierInfo(); - + // Read the ')'. Lex(Tok); if (Tok.is(tok::r_paren)) IsValid = true; } } - + bool Value = false; if (!IsValid) Diag(StartLoc, diag::err_feature_check_malformed); else if (II == Ident__has_builtin) { - // Check for a builtin is trivial. + // Check for a builtin is trivial. Value = FeatureII->getBuiltinID() != 0; } else { assert(II == Ident__has_feature && "Must be feature check"); Value = HasFeature(*this, FeatureII); } - + sprintf(TmpBuffer, "%d", (int)Value); Tok.setKind(tok::numeric_constant); CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation()); diff --git a/clang/lib/Lex/PTHLexer.cpp b/clang/lib/Lex/PTHLexer.cpp index 2b91cea5ed1f6a8f5b35eb9145497265ee5e7d97..36ace8be7e062608d0ff6b509bf06b7c8c40b080 100644 --- a/clang/lib/Lex/PTHLexer.cpp +++ b/clang/lib/Lex/PTHLexer.cpp @@ -37,7 +37,7 @@ PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D, const unsigned char *ppcond, PTHManager &PM) : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0), PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) { - + FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID); } @@ -47,25 +47,25 @@ LexNextToken: //===--------------------------------------==// // Read the raw token data. //===--------------------------------------==// - + // Shadow CurPtr into an automatic variable. - const unsigned char *CurPtrShadow = CurPtr; + const unsigned char *CurPtrShadow = CurPtr; // Read in the data for the token. unsigned Word0 = ReadLE32(CurPtrShadow); uint32_t IdentifierID = ReadLE32(CurPtrShadow); uint32_t FileOffset = ReadLE32(CurPtrShadow); - + tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF); Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF); uint32_t Len = Word0 >> 16; CurPtr = CurPtrShadow; - + //===--------------------------------------==// // Construct the token itself. //===--------------------------------------==// - + Tok.startToken(); Tok.setKind(TKind); Tok.setFlag(TFlags); @@ -80,57 +80,57 @@ LexNextToken: else if (IdentifierID) { MIOpt.ReadToken(); IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1); - + Tok.setIdentifierInfo(II); - + // Change the kind of this identifier to the appropriate token kind, e.g. // turning "for" into a keyword. Tok.setKind(II->getTokenID()); - + if (II->isHandleIdentifierCase()) PP->HandleIdentifier(Tok); return; } - + //===--------------------------------------==// // Process the token. //===--------------------------------------==// -#if 0 +#if 0 SourceManager& SM = PP->getSourceManager(); llvm::errs() << SM.getFileEntryForID(FileID)->getName() << ':' << SM.getLogicalLineNumber(Tok.getLocation()) << ':' << SM.getLogicalColumnNumber(Tok.getLocation()) << '\n'; -#endif +#endif if (TKind == tok::eof) { // Save the end-of-file token. EofToken = Tok; - + Preprocessor *PPCache = PP; - + assert(!ParsingPreprocessorDirective); assert(!LexingRawMode); - + // FIXME: Issue diagnostics similar to Lexer. if (PP->HandleEndOfFile(Tok, false)) return; - + assert(PPCache && "Raw buffer::LexEndOfFile should return a token"); return PPCache->Lex(Tok); } - + if (TKind == tok::hash && Tok.isAtStartOfLine()) { LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE; assert(!LexingRawMode); PP->HandleDirective(Tok); - + if (PP->isCurrentLexer(this)) goto LexNextToken; - + return PP->Lex(Tok); } - + if (TKind == tok::eom) { assert(ParsingPreprocessorDirective); ParsingPreprocessorDirective = false; @@ -154,7 +154,7 @@ void PTHLexer::DiscardToEndOfLine() { // We assume that if the preprocessor wishes to discard to the end of // the line that it also means to end the current preprocessor directive. ParsingPreprocessorDirective = false; - + // Skip tokens by only peeking at their token kind and the flags. // We don't need to actually reconstruct full tokens from the token buffer. // This saves some copies and it also reduces IdentifierInfo* lookup. @@ -163,7 +163,7 @@ void PTHLexer::DiscardToEndOfLine() { // Read the token kind. Are we at the end of the file? tok::TokenKind x = (tok::TokenKind) (uint8_t) *p; if (x == tok::eof) break; - + // Read the token flags. Are we at the start of the next line? Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1]; if (y & Token::StartOfLine) break; @@ -171,7 +171,7 @@ void PTHLexer::DiscardToEndOfLine() { // Skip to the next token. p += DISK_TOKEN_SIZE; } - + CurPtr = p; } @@ -179,18 +179,18 @@ void PTHLexer::DiscardToEndOfLine() { bool PTHLexer::SkipBlock() { assert(CurPPCondPtr && "No cached PP conditional information."); assert(LastHashTokPtr && "No known '#' token."); - + const unsigned char* HashEntryI = 0; - uint32_t Offset; + uint32_t Offset; uint32_t TableIdx; - + do { // Read the token offset from the side-table. Offset = ReadLE32(CurPPCondPtr); - - // Read the target table index from the side-table. + + // Read the target table index from the side-table. TableIdx = ReadLE32(CurPPCondPtr); - + // Compute the actual memory address of the '#' token data for this entry. HashEntryI = TokBuf + Offset; @@ -208,7 +208,7 @@ bool PTHLexer::SkipBlock() { // Read where we should jump to. uint32_t TmpOffset = ReadLE32(NextPPCondPtr); const unsigned char* HashEntryJ = TokBuf + TmpOffset; - + if (HashEntryJ <= LastHashTokPtr) { // Jump directly to the next entry in the side table. HashEntryI = HashEntryJ; @@ -218,23 +218,23 @@ bool PTHLexer::SkipBlock() { } } } - while (HashEntryI < LastHashTokPtr); + while (HashEntryI < LastHashTokPtr); assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'"); assert(TableIdx && "No jumping from #endifs."); - + // Update our side-table iterator. const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2); assert(NextPPCondPtr >= CurPPCondPtr); CurPPCondPtr = NextPPCondPtr; - + // Read where we should jump to. HashEntryI = TokBuf + ReadLE32(NextPPCondPtr); uint32_t NextIdx = ReadLE32(NextPPCondPtr); - + // By construction NextIdx will be zero if this is a #endif. This is useful // to know to obviate lexing another token. bool isEndif = NextIdx == 0; - + // This case can occur when we see something like this: // // #if ... @@ -243,7 +243,7 @@ bool PTHLexer::SkipBlock() { // // If we are skipping the first #if block it will be the case that CurPtr // already points 'elif'. Just return. - + if (CurPtr > HashEntryI) { assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE); // Did we reach a #endif? If so, go ahead and consume that token as well. @@ -251,13 +251,13 @@ bool PTHLexer::SkipBlock() { CurPtr += DISK_TOKEN_SIZE*2; else LastHashTokPtr = HashEntryI; - + return isEndif; } // Otherwise, we need to advance. Update CurPtr to point to the '#' token. CurPtr = HashEntryI; - + // Update the location of the last observed '#'. This is useful if we // are skipping multiple blocks. LastHashTokPtr = CurPtr; @@ -265,7 +265,7 @@ bool PTHLexer::SkipBlock() { // Skip the '#' token. assert(((tok::TokenKind)*CurPtr) == tok::hash); CurPtr += DISK_TOKEN_SIZE; - + // Did we reach a #endif? If so, go ahead and consume that token as well. if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; } @@ -297,12 +297,12 @@ class VISIBILITY_HIDDEN PTHFileData { public: PTHFileData(uint32_t tokenOff, uint32_t ppCondOff) : TokenOff(tokenOff), PPCondOff(ppCondOff) {} - - uint32_t getTokenOffset() const { return TokenOff; } - uint32_t getPPCondOffset() const { return PPCondOff; } + + uint32_t getTokenOffset() const { return TokenOff; } + uint32_t getPPCondOffset() const { return PPCondOff; } }; - - + + class VISIBILITY_HIDDEN PTHFileLookupCommonTrait { public: typedef std::pair internal_key_type; @@ -310,84 +310,84 @@ public: static unsigned ComputeHash(internal_key_type x) { return BernsteinHash(x.second); } - + static std::pair ReadKeyDataLength(const unsigned char*& d) { unsigned keyLen = (unsigned) ReadUnalignedLE16(d); unsigned dataLen = (unsigned) *(d++); return std::make_pair(keyLen, dataLen); } - + static internal_key_type ReadKey(const unsigned char* d, unsigned) { unsigned char k = *(d++); // Read the entry kind. return std::make_pair(k, (const char*) d); } }; - + class VISIBILITY_HIDDEN PTHFileLookupTrait : public PTHFileLookupCommonTrait { public: typedef const FileEntry* external_key_type; typedef PTHFileData data_type; - + static internal_key_type GetInternalKey(const FileEntry* FE) { return std::make_pair((unsigned char) 0x1, FE->getName()); } static bool EqualKey(internal_key_type a, internal_key_type b) { return a.first == b.first && strcmp(a.second, b.second) == 0; - } - - static PTHFileData ReadData(const internal_key_type& k, - const unsigned char* d, unsigned) { + } + + static PTHFileData ReadData(const internal_key_type& k, + const unsigned char* d, unsigned) { assert(k.first == 0x1 && "Only file lookups can match!"); uint32_t x = ::ReadUnalignedLE32(d); uint32_t y = ::ReadUnalignedLE32(d); - return PTHFileData(x, y); + return PTHFileData(x, y); } }; class VISIBILITY_HIDDEN PTHStringLookupTrait { public: - typedef uint32_t + typedef uint32_t data_type; typedef const std::pair external_key_type; typedef external_key_type internal_key_type; - + static bool EqualKey(const internal_key_type& a, const internal_key_type& b) { return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0 : false; } - + static unsigned ComputeHash(const internal_key_type& a) { return BernsteinHash(a.first, a.second); } - + // This hopefully will just get inlined and removed by the optimizer. static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + static std::pair ReadKeyDataLength(const unsigned char*& d) { return std::make_pair((unsigned) ReadUnalignedLE16(d), sizeof(uint32_t)); } - + static std::pair ReadKey(const unsigned char* d, unsigned n) { assert(n >= 2 && d[n-1] == '\0'); return std::make_pair((const char*) d, n-1); } - + static uint32_t ReadData(const internal_key_type& k, const unsigned char* d, unsigned) { return ::ReadUnalignedLE32(d); } }; - -} // end anonymous namespace + +} // end anonymous namespace typedef OnDiskChainedHashTable PTHFileLookup; typedef OnDiskChainedHashTable PTHStringIdLookup; @@ -398,7 +398,7 @@ typedef OnDiskChainedHashTable PTHStringIdLookup; PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup, const unsigned char* idDataTable, - IdentifierInfo** perIDCache, + IdentifierInfo** perIDCache, void* stringIdLookup, unsigned numIds, const unsigned char* spellingBase, const char* originalSourceFile) @@ -416,7 +416,7 @@ PTHManager::~PTHManager() { static void InvalidPTH(Diagnostic *Diags, Diagnostic::Level level, const char* Msg = 0) { - if (!Diags) return; + if (!Diags) return; if (!Msg) Msg = "Invalid or corrupted PTH file"; unsigned DiagID = Diags->getCustomDiagID(level, Msg); Diags->Report(FullSourceLoc(), DiagID); @@ -427,7 +427,7 @@ PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags, // Memory map the PTH file. llvm::OwningPtr File(llvm::MemoryBuffer::getFile(file.c_str())); - + if (!File) { if (Diags) { unsigned DiagID = Diags->getCustomDiagID(level, @@ -437,7 +437,7 @@ PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags, return 0; } - + // Get the buffer ranges and check if there are at least three 32-bit // words at the end of the file. const unsigned char* BufBeg = (unsigned char*)File->getBufferStart(); @@ -449,54 +449,54 @@ PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags, InvalidPTH(Diags, level); return 0; } - + // Read the PTH version. const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1); unsigned Version = ReadLE32(p); - + if (Version != PTHManager::Version) { InvalidPTH(Diags, level, - Version < PTHManager::Version + Version < PTHManager::Version ? "PTH file uses an older PTH format that is no longer supported" : "PTH file uses a newer PTH format that cannot be read"); return 0; } - // Compute the address of the index table at the end of the PTH file. + // Compute the address of the index table at the end of the PTH file. const unsigned char *PrologueOffset = p; - + if (PrologueOffset >= BufEnd) { InvalidPTH(Diags, level); return 0; } - + // Construct the file lookup table. This will be used for mapping from // FileEntry*'s to cached tokens. const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2; const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset); - + if (!(FileTable > BufBeg && FileTable < BufEnd)) { InvalidPTH(Diags, level); return 0; // FIXME: Proper error diagnostic? } - + llvm::OwningPtr FL(PTHFileLookup::Create(FileTable, BufBeg)); - + // Warn if the PTH file is empty. We still want to create a PTHManager // as the PTH could be used with -include-pth. if (FL->isEmpty()) InvalidPTH(Diags, level, "PTH file contains no cached source data"); - + // Get the location of the table mapping from persistent ids to the // data needed to reconstruct identifiers. const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0; const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset); - + if (!(IData >= BufBeg && IData < BufEnd)) { InvalidPTH(Diags, level); return 0; } - + // Get the location of the hashtable mapping between strings and // persistent IDs. const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1; @@ -508,7 +508,7 @@ PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags, llvm::OwningPtr SL(PTHStringIdLookup::Create(StringIdTable, BufBeg)); - + // Get the location of the spelling cache. const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3; const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset); @@ -516,19 +516,19 @@ PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags, InvalidPTH(Diags, level); return 0; } - + // Get the number of IdentifierInfos and pre-allocate the identifier cache. uint32_t NumIds = ReadLE32(IData); - + // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc() // so that we in the best case only zero out memory once when the OS returns // us new pages. IdentifierInfo** PerIDCache = 0; - + if (NumIds) { - PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache)); + PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache)); if (!PerIDCache) { - InvalidPTH(Diags, level, + InvalidPTH(Diags, level, "Could not allocate memory for processing PTH file"); return 0; } @@ -537,8 +537,8 @@ PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags, // Compute the address of the original source file. const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4; unsigned len = ReadUnalignedLE16(originalSourceBase); - if (!len) originalSourceBase = 0; - + if (!len) originalSourceBase = 0; + // Create the new PTHManager. return new PTHManager(File.take(), FL.take(), IData, PerIDCache, SL.take(), NumIds, spellingBase, @@ -551,7 +551,7 @@ IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) { const unsigned char* IDData = (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry); assert(IDData < (const unsigned char*)Buf->getBufferEnd()); - + // Allocate the object. std::pair *Mem = Alloc.Allocate >(); @@ -559,7 +559,7 @@ IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) { Mem->second = IDData; assert(IDData[0] != '\0'); IdentifierInfo *II = new ((void*) Mem) IdentifierInfo(); - + // Store the new IdentifierInfo in the cache. PerIDCache[PersistentID] = II; assert(II->getName() && II->getName()[0] != '\0'); @@ -584,18 +584,18 @@ PTHLexer *PTHManager::CreateLexer(FileID FID) { const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID); if (!FE) return 0; - + // Lookup the FileEntry object in our file lookup data structure. It will // return a variant that indicates whether or not there is an offset within // the PTH file that contains cached tokens. PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup); PTHFileLookup::iterator I = PFL.find(FE); - + if (I == PFL.end()) // No tokens available? return 0; - - const PTHFileData& FileData = *I; - + + const PTHFileData& FileData = *I; + const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart(); // Compute the offset of the token data within the buffer. const unsigned char* data = BufStart + FileData.getTokenOffset(); @@ -604,9 +604,9 @@ PTHLexer *PTHManager::CreateLexer(FileID FID) { const unsigned char* ppcond = BufStart + FileData.getPPCondOffset(); uint32_t Len = ReadLE32(ppcond); if (Len == 0) ppcond = 0; - + assert(PP && "No preprocessor set yet!"); - return new PTHLexer(*PP, FID, data, ppcond, *this); + return new PTHLexer(*PP, FID, data, ppcond, *this); } //===----------------------------------------------------------------------===// @@ -622,19 +622,19 @@ public: const mode_t mode; const time_t mtime; const off_t size; - + PTHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s) - : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {} - + : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {} + PTHStatData() : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {} }; - + class VISIBILITY_HIDDEN PTHStatLookupTrait : public PTHFileLookupCommonTrait { public: typedef const char* external_key_type; // const char* typedef PTHStatData data_type; - + static internal_key_type GetInternalKey(const char *path) { // The key 'kind' doesn't matter here because it is ignored in EqualKey. return std::make_pair((unsigned char) 0x0, path); @@ -644,17 +644,17 @@ public: // When doing 'stat' lookups we don't care about the kind of 'a' and 'b', // just the paths. return strcmp(a.second, b.second) == 0; - } - + } + static data_type ReadData(const internal_key_type& k, const unsigned char* d, - unsigned) { - + unsigned) { + if (k.first /* File or Directory */) { if (k.first == 0x1 /* File */) d += 4 * 2; // Skip the first 2 words. ino_t ino = (ino_t) ReadUnalignedLE32(d); dev_t dev = (dev_t) ReadUnalignedLE32(d); mode_t mode = (mode_t) ReadUnalignedLE16(d); - time_t mtime = (time_t) ReadUnalignedLE64(d); + time_t mtime = (time_t) ReadUnalignedLE64(d); return data_type(ino, dev, mode, mtime, (off_t) ReadUnalignedLE64(d)); } @@ -667,22 +667,22 @@ class VISIBILITY_HIDDEN PTHStatCache : public StatSysCallCache { typedef OnDiskChainedHashTable CacheTy; CacheTy Cache; -public: +public: PTHStatCache(PTHFileLookup &FL) : Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(), FL.getBase()) {} ~PTHStatCache() {} - + int stat(const char *path, struct stat *buf) { // Do the lookup for the file's data in the PTH file. CacheTy::iterator I = Cache.find(path); // If we don't get a hit in the PTH file just forward to 'stat'. if (I == Cache.end()) return ::stat(path, buf); - + const PTHStatData& Data = *I; - + if (!Data.hasStat) return 1; diff --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp index fbdbd0b6e76b16910fdbeb9f36c3c6d1993813f2..8b46f716910c943526839ecc8a7dd601fc92a068 100644 --- a/clang/lib/Lex/Pragma.cpp +++ b/clang/lib/Lex/Pragma.cpp @@ -44,9 +44,9 @@ PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name, bool IgnoreNull) const { PragmaHandler *NullHandler = 0; for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { - if (Handlers[i]->getName() == Name) + if (Handlers[i]->getName() == Name) return Handlers[i]; - + if (Handlers[i]->getName() == 0) NullHandler = Handlers[i]; } @@ -68,14 +68,14 @@ void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) { // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro // expand it, the user can have a STDC #define, that should not affect this. PP.LexUnexpandedToken(Tok); - + // Get the handler for this token. If there is no handler, ignore the pragma. PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false); if (Handler == 0) { PP.Diag(Tok, diag::warn_pragma_ignored); return; } - + // Otherwise, pass it down. Handler->HandlePragma(PP, Tok); } @@ -88,11 +88,11 @@ void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) { /// rest of the pragma, passing it to the registered pragma handlers. void Preprocessor::HandlePragmaDirective() { ++NumPragma; - + // Invoke the first level of pragma handlers which reads the namespace id. Token Tok; PragmaHandlers->HandlePragma(*this, Tok); - + // If the pragma handler didn't read the rest of the line, consume it now. if (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective) DiscardUntilEndOfDirective(); @@ -104,7 +104,7 @@ void Preprocessor::HandlePragmaDirective() { void Preprocessor::Handle_Pragma(Token &Tok) { // Remember the pragma token location. SourceLocation PragmaLoc = Tok.getLocation(); - + // Read the '('. Lex(Tok); if (Tok.isNot(tok::l_paren)) { @@ -118,7 +118,7 @@ void Preprocessor::Handle_Pragma(Token &Tok) { Diag(PragmaLoc, diag::err__Pragma_malformed); return; } - + // Remember the string. std::string StrVal = getSpelling(Tok); @@ -128,9 +128,9 @@ void Preprocessor::Handle_Pragma(Token &Tok) { Diag(PragmaLoc, diag::err__Pragma_malformed); return; } - + SourceLocation RParenLoc = Tok.getLocation(); - + // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1: // "The string literal is destringized by deleting the L prefix, if present, // deleting the leading and trailing double-quotes, replacing each escape @@ -140,14 +140,14 @@ void Preprocessor::Handle_Pragma(Token &Tok) { StrVal.erase(StrVal.begin()); assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && "Invalid string token!"); - + // Remove the front quote, replacing it with a space, so that the pragma // contents appear to have a space before them. StrVal[0] = ' '; - + // Replace the terminating quote with a \n. StrVal[StrVal.size()-1] = '\n'; - + // Remove escaped quotes and escapes. for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) { if (StrVal[i] == '\\' && @@ -157,7 +157,7 @@ void Preprocessor::Handle_Pragma(Token &Tok) { --e; } } - + // Plop the string (including the newline and trailing null) into a buffer // where we can lex it. Token TmpTok; @@ -174,7 +174,7 @@ void Preprocessor::Handle_Pragma(Token &Tok) { // With everything set up, lex this as a #pragma directive. HandlePragmaDirective(); - + // Finally, return whatever came after the pragma directive. return Lex(Tok); } @@ -188,7 +188,7 @@ void Preprocessor::HandlePragmaOnce(Token &OnceTok) { Diag(OnceTok, diag::pp_pragma_once_in_main_file); return; } - + // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. // Mark the file as a once-only file now. HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry()); @@ -217,27 +217,27 @@ void Preprocessor::HandlePragmaPoison(Token &PoisonTok) { if (CurPPLexer) CurPPLexer->LexingRawMode = true; LexUnexpandedToken(Tok); if (CurPPLexer) CurPPLexer->LexingRawMode = false; - + // If we reached the end of line, we're done. if (Tok.is(tok::eom)) return; - + // Can only poison identifiers. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_pp_invalid_poison); return; } - + // Look up the identifier info for the token. We disabled identifier lookup // by saying we're skipping contents, so we need to do this manually. IdentifierInfo *II = LookUpIdentifierInfo(Tok); - + // Already poisoned. if (II->isPoisoned()) continue; - + // If this is a macro identifier, emit a warning. if (II->hasMacroDefinition()) Diag(Tok, diag::pp_poisoning_existing_macro); - + // Finally, poison it! II->setIsPoisoned(); } @@ -250,25 +250,25 @@ void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file); return; } - + // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. PreprocessorLexer *TheLexer = getCurrentFileLexer(); - + // Mark the file as a system header. HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry()); - - + + PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); unsigned FilenameLen = strlen(PLoc.getFilename()); unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename(), FilenameLen); - + // Emit a line marker. This will change any source locations from this point // forward to realize they are in a system header. // Create a line note with this information. SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID, false, false, true, false); - + // Notify the client, if desired, that we are in a new source file. if (Callbacks) Callbacks->FileChanged(SysHeaderTok.getLocation(), @@ -284,11 +284,11 @@ void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { // If the token kind is EOM, the error has already been diagnosed. if (FilenameTok.is(tok::eom)) return; - + // Reserve a buffer to get the spelling. llvm::SmallVector FilenameBuffer; FilenameBuffer.resize(FilenameTok.getLength()); - + const char *FilenameStart = &FilenameBuffer[0]; unsigned Len = getSpelling(FilenameTok, FilenameStart); const char *FilenameEnd = FilenameStart+Len; @@ -298,7 +298,7 @@ void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { // error. if (FilenameStart == 0) return; - + // Search include directories for this file. const DirectoryLookup *CurDir; const FileEntry *File = LookupFile(FilenameStart, FilenameEnd, @@ -308,7 +308,7 @@ void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { << std::string(FilenameStart, FilenameEnd); return; } - + const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); // If this file is older than the file it depends on, emit a diagnostic. @@ -320,7 +320,7 @@ void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { Message += getSpelling(DependencyTok) + " "; Lex(DependencyTok); } - + Message.erase(Message.end()-1); Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; } @@ -339,23 +339,23 @@ void Preprocessor::HandlePragmaComment(Token &Tok) { Diag(CommentLoc, diag::err_pragma_comment_malformed); return; } - + // Read the identifier. Lex(Tok); if (Tok.isNot(tok::identifier)) { Diag(CommentLoc, diag::err_pragma_comment_malformed); return; } - + // Verify that this is one of the 5 whitelisted options. // FIXME: warn that 'exestr' is deprecated. const IdentifierInfo *II = Tok.getIdentifierInfo(); - if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") && + if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") && !II->isStr("linker") && !II->isStr("user")) { Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind); return; } - + // Read the optional string if present. Lex(Tok); std::string ArgumentString; @@ -390,13 +390,13 @@ void Preprocessor::HandlePragmaComment(Token &Tok) { ArgumentString = std::string(Literal.GetString(), Literal.GetString()+Literal.GetStringLength()); } - + // FIXME: If the kind is "compiler" warn if the string is present (it is // ignored). // FIXME: 'lib' requires a comment string. // FIXME: 'linker' requires a comment string, and has a specific list of // things that are allowable. - + if (Tok.isNot(tok::r_paren)) { Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); return; @@ -407,7 +407,7 @@ void Preprocessor::HandlePragmaComment(Token &Tok) { Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); return; } - + // If the pragma is lexically sound, notify any interested PPCallbacks. if (Callbacks) Callbacks->PragmaComment(CommentLoc, II, ArgumentString); @@ -419,14 +419,14 @@ void Preprocessor::HandlePragmaComment(Token &Tok) { /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. /// If 'Namespace' is non-null, then it is a token required to exist on the /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". -void Preprocessor::AddPragmaHandler(const char *Namespace, +void Preprocessor::AddPragmaHandler(const char *Namespace, PragmaHandler *Handler) { PragmaNamespace *InsertNS = PragmaHandlers; - + // If this is specified to be in a namespace, step down into it. if (Namespace) { IdentifierInfo *NSID = getIdentifierInfo(Namespace); - + // If there is already a pragma handler with the name of this namespace, // we either have an error (directive with the same name as a namespace) or // we already have the namespace to insert into. @@ -441,7 +441,7 @@ void Preprocessor::AddPragmaHandler(const char *Namespace, PragmaHandlers->AddPragma(InsertNS); } } - + // Check to make sure we don't already have a pragma for this identifier. assert(!InsertNS->FindHandler(Handler->getName()) && "Pragma handler already exists for this identifier!"); @@ -455,7 +455,7 @@ void Preprocessor::AddPragmaHandler(const char *Namespace, void Preprocessor::RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler) { PragmaNamespace *NS = PragmaHandlers; - + // If this is specified to be in a namespace, step down into it. if (Namespace) { IdentifierInfo *NSID = getIdentifierInfo(Namespace); @@ -467,7 +467,7 @@ void Preprocessor::RemovePragmaHandler(const char *Namespace, } NS->RemovePragmaHandler(Handler); - + // If this is a non-default namespace and it is now empty, remove // it. if (NS != PragmaHandlers && NS->IsEmpty()) @@ -516,7 +516,7 @@ struct PragmaDependencyHandler : public PragmaHandler { PP.HandlePragmaDependency(DepToken); } }; - + /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"' /// Since clang's diagnostic supports extended functionality beyond GCC's /// the constructor takes a clangMode flag to tell it whether or not to allow @@ -538,7 +538,7 @@ public: return; } IdentifierInfo *II = Tok.getIdentifierInfo(); - + diag::Mapping Map; if (II->isStr("warning")) Map = diag::MAP_WARNING; @@ -550,14 +550,14 @@ public: Map = diag::MAP_FATAL; else if (ClangMode) { if (II->isStr("pop")) { - if(!PP.getDiagnostics().popMappings()) + if (!PP.getDiagnostics().popMappings()) PP.Diag(Tok, diag::warn_pragma_diagnostic_clang_cannot_ppp); return; } if (II->isStr("push")) { PP.getDiagnostics().pushMappings(); - return; + return; } PP.Diag(Tok, diag::warn_pragma_diagnostic_clang_invalid); @@ -566,7 +566,7 @@ public: PP.Diag(Tok, diag::warn_pragma_diagnostic_gcc_invalid); return; } - + PP.LexUnexpandedToken(Tok); // We need at least one string. @@ -574,7 +574,7 @@ public: PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); return; } - + // String concatenation allows multiple strings, which can even come from // macro expansion. // "foo " "bar" "Baz" @@ -583,12 +583,12 @@ public: StrToks.push_back(Tok); PP.LexUnexpandedToken(Tok); } - + if (Tok.isNot(tok::eom)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); return; } - + // Concatenate and parse the strings. StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP); assert(!Literal.AnyWide && "Didn't allow wide strings in"); @@ -610,14 +610,14 @@ public: diag::warn_pragma_diagnostic_invalid_option); return; } - + if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.c_str()+2, Map)) PP.Diag(StrToks[0].getLocation(), diag::warn_pragma_diagnostic_unknown_warning) << WarningName; } }; - + /// PragmaCommentHandler - "#pragma comment ...". struct PragmaCommentHandler : public PragmaHandler { PragmaCommentHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} @@ -625,13 +625,13 @@ struct PragmaCommentHandler : public PragmaHandler { PP.HandlePragmaComment(CommentTok); } }; - + // Pragma STDC implementations. enum STDCSetting { STDC_ON, STDC_OFF, STDC_DEFAULT, STDC_INVALID }; - + static STDCSetting LexOnOffSwitch(Preprocessor &PP) { Token Tok; PP.LexUnexpandedToken(Tok); @@ -659,7 +659,7 @@ static STDCSetting LexOnOffSwitch(Preprocessor &PP) { PP.Diag(Tok, diag::ext_stdc_pragma_syntax_eom); return Result; } - + /// PragmaSTDC_FP_CONTRACTHandler - "#pragma STDC FP_CONTRACT ...". struct PragmaSTDC_FP_CONTRACTHandler : public PragmaHandler { PragmaSTDC_FP_CONTRACTHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} @@ -671,7 +671,7 @@ struct PragmaSTDC_FP_CONTRACTHandler : public PragmaHandler { LexOnOffSwitch(PP); } }; - + /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...". struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { PragmaSTDC_FENV_ACCESSHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} @@ -680,7 +680,7 @@ struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported); } }; - + /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...". struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { PragmaSTDC_CX_LIMITED_RANGEHandler(const IdentifierInfo *ID) @@ -689,7 +689,7 @@ struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { LexOnOffSwitch(PP); } }; - + /// PragmaSTDC_UnknownHandler - "#pragma STDC ...". struct PragmaSTDC_UnknownHandler : public PragmaHandler { PragmaSTDC_UnknownHandler() : PragmaHandler(0) {} @@ -698,7 +698,7 @@ struct PragmaSTDC_UnknownHandler : public PragmaHandler { PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored); } }; - + } // end anonymous namespace @@ -707,7 +707,7 @@ struct PragmaSTDC_UnknownHandler : public PragmaHandler { void Preprocessor::RegisterBuiltinPragmas() { AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once"))); AddPragmaHandler(0, new PragmaMarkHandler(getIdentifierInfo("mark"))); - + // #pragma GCC ... AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison"))); AddPragmaHandler("GCC", new PragmaSystemHeaderHandler( @@ -735,7 +735,7 @@ void Preprocessor::RegisterBuiltinPragmas() { AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler( getIdentifierInfo("CX_LIMITED_RANGE"))); AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); - + // MS extensions. if (Features.Microsoft) AddPragmaHandler(0, new PragmaCommentHandler(getIdentifierInfo("comment"))); diff --git a/clang/lib/Lex/Preprocessor.cpp b/clang/lib/Lex/Preprocessor.cpp index 4b1cd63187644526ff9d4bfd26835c42ce102174..bfa090a09e870d2d1a0f58fa6e4cf057d3441a95 100644 --- a/clang/lib/Lex/Preprocessor.cpp +++ b/clang/lib/Lex/Preprocessor.cpp @@ -46,7 +46,7 @@ using namespace clang; PreprocessorFactory::~PreprocessorFactory() {} Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, - TargetInfo &target, SourceManager &SM, + TargetInfo &target, SourceManager &SM, HeaderSearch &Headers, IdentifierInfoLookup* IILookup) : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()), @@ -54,20 +54,20 @@ Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, BuiltinInfo(Target), CurPPLexer(0), CurDirLookup(0), Callbacks(0) { ScratchBuf = new ScratchBuffer(SourceMgr); CounterValue = 0; // __COUNTER__ starts at 0. - + // Clear stats. NumDirectives = NumDefined = NumUndefined = NumPragma = 0; NumIf = NumElse = NumEndif = 0; NumEnteredSourceFiles = 0; NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; - MaxIncludeStackDepth = 0; + MaxIncludeStackDepth = 0; NumSkipped = 0; // Default to discarding comments. KeepComments = false; KeepMacroComments = false; - + // Macro expansion is enabled. DisableMacroExpansion = false; InMacroArgs = false; @@ -78,11 +78,11 @@ Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. // This gets unpoisoned where it is allowed. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); - + // Initialize the pragma handlers. PragmaHandlers = new PragmaNamespace(0); RegisterBuiltinPragmas(); - + // Initialize builtin macros like __LINE__ and friends. RegisterBuiltinMacros(); } @@ -106,11 +106,11 @@ Preprocessor::~Preprocessor() { I->second->Destroy(BP); I->first->setHasMacroDefinition(false); } - + // Free any cached macro expanders. for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) delete TokenLexerCache[i]; - + // Release pragma information. delete PragmaHandlers; @@ -128,9 +128,9 @@ void Preprocessor::setPTHManager(PTHManager* pm) { void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" << getSpelling(Tok) << "'"; - + if (!DumpFlags) return; - + llvm::errs() << "\t"; if (Tok.isAtStartOfLine()) llvm::errs() << " [StartOfLine]"; @@ -143,7 +143,7 @@ void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { llvm::errs() << " [UnClean='" << std::string(Start, Start+Tok.getLength()) << "']"; } - + llvm::errs() << "\tLoc=<"; DumpLocation(Tok.getLocation()); llvm::errs() << ">"; @@ -201,10 +201,10 @@ std::string Preprocessor::getSpelling(const Token &Tok) const { const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation()); if (!Tok.needsCleaning()) return std::string(TokStart, TokStart+Tok.getLength()); - + std::string Result; Result.reserve(Tok.getLength()); - + // Otherwise, hard case, relex the characters into the string. for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength(); Ptr != End; ) { @@ -230,7 +230,7 @@ std::string Preprocessor::getSpelling(const Token &Tok) const { unsigned Preprocessor::getSpelling(const Token &Tok, const char *&Buffer) const { assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); - + // If this token is an identifier, just return the string from the identifier // table, which is very quick. if (const IdentifierInfo *II = Tok.getIdentifierInfo()) { @@ -240,10 +240,10 @@ unsigned Preprocessor::getSpelling(const Token &Tok, // Otherwise, compute the start of the token in the input lexer buffer. const char *TokStart = 0; - + if (Tok.isLiteral()) TokStart = Tok.getLiteralData(); - + if (TokStart == 0) TokStart = SourceMgr.getCharacterData(Tok.getLocation()); @@ -252,7 +252,7 @@ unsigned Preprocessor::getSpelling(const Token &Tok, Buffer = TokStart; return Tok.getLength(); } - + // Otherwise, hard case, relex the characters into the string. char *OutBuf = const_cast(Buffer); for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength(); @@ -263,7 +263,7 @@ unsigned Preprocessor::getSpelling(const Token &Tok, } assert(unsigned(OutBuf-Buffer) != Tok.getLength() && "NeedsCleaning flag set on something that didn't need cleaning!"); - + return OutBuf-Buffer; } @@ -273,15 +273,15 @@ unsigned Preprocessor::getSpelling(const Token &Tok, void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, SourceLocation InstantiationLoc) { Tok.setLength(Len); - + const char *DestPtr; SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr); - + if (InstantiationLoc.isValid()) Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc, InstantiationLoc, Len); Tok.setLocation(Loc); - + // If this is a literal token, set the pointer data. if (Tok.isLiteral()) Tok.setLiteralData(DestPtr); @@ -290,19 +290,19 @@ void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, /// AdvanceToTokenCharacter - Given a location that specifies the start of a /// token, return a new location that specifies a character within the token. -SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart, +SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart, unsigned CharNo) { // Figure out how many physical characters away the specified instantiation // character is. This needs to take into consideration newlines and // trigraphs. const char *TokPtr = SourceMgr.getCharacterData(TokStart); - + // If they request the first char of the token, we're trivially done. if (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)) return TokStart; - + unsigned PhysOffset = 0; - + // The usual case is that tokens don't contain anything interesting. Skip // over the uninteresting characters. If a token only consists of simple // chars, this method is extremely fast. @@ -311,7 +311,7 @@ SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart, return TokStart.getFileLocWithOffset(PhysOffset); ++TokPtr, --CharNo, ++PhysOffset; } - + // If we have a character that may be a trigraph or escaped newline, use a // lexer to parse it correctly. for (; CharNo; --CharNo) { @@ -320,14 +320,14 @@ SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart, TokPtr += Size; PhysOffset += Size; } - + // Final detail: if we end up on an escaped newline, we want to return the // location of the actual byte of the token. For example foo\bar // advanced by 3 should return the location of b, not of \\. One compounding // detail of this is that the escape may be made by a trigraph. if (!Lexer::isObviouslySimpleCharacter(*TokPtr)) PhysOffset = Lexer::SkipEscapedNewLines(TokPtr)-TokPtr; - + return TokStart.getFileLocWithOffset(PhysOffset); } @@ -364,33 +364,33 @@ void Preprocessor::EnterMainSourceFile() { // information) and predefined macros aren't guaranteed to be set properly. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); FileID MainFileID = SourceMgr.getMainFileID(); - + // Enter the main file source buffer. EnterSourceFile(MainFileID, 0); - + // Tell the header info that the main file was entered. If the file is later // #imported, it won't be re-entered. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) HeaderInfo.IncrementIncludeCount(FE); - + std::vector PrologFile; PrologFile.reserve(4080); - + // FIXME: Don't make a copy. PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end()); - + // Memory buffer must end with a null byte! PrologFile.push_back(0); // Now that we have emitted the predefined macros, #includes, etc into // PrologFile, preprocess it to populate the initial preprocessor state. - llvm::MemoryBuffer *SB = + llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(), ""); assert(SB && "Cannot fail to create predefined source buffer"); FileID FID = SourceMgr.createFileIDForMemBuffer(SB); assert(!FID.isInvalid() && "Could not create FileID for predefines?"); - + // Start parsing the predefines. EnterSourceFile(FID, 0); } @@ -406,7 +406,7 @@ IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier, const char *BufPtr) { assert(Identifier.is(tok::identifier) && "Not an identifier!"); assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!"); - + // Look up this token, see if it is a macro, or if it is a language keyword. IdentifierInfo *II; if (BufPtr && !Identifier.needsCleaning()) { @@ -436,7 +436,7 @@ IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier, void Preprocessor::HandleIdentifier(Token &Identifier) { assert(Identifier.getIdentifierInfo() && "Can't handle identifiers without identifier info!"); - + IdentifierInfo &II = *Identifier.getIdentifierInfo(); // If this identifier was poisoned, and if it was not produced from a macro @@ -447,7 +447,7 @@ void Preprocessor::HandleIdentifier(Token &Identifier) { else Diag(Identifier, diag::ext_pp_bad_vaargs_use); } - + // If this is a macro to be expanded, do it. if (MacroInfo *MI = getMacroInfo(&II)) { if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) { diff --git a/clang/lib/Lex/PreprocessorLexer.cpp b/clang/lib/Lex/PreprocessorLexer.cpp index f9dfad9c808ec505b55e4dfefbc581636e1bc743..e005c494763cb60fbe0a3adc160129a25a3d8542 100644 --- a/clang/lib/Lex/PreprocessorLexer.cpp +++ b/clang/lib/Lex/PreprocessorLexer.cpp @@ -26,13 +26,13 @@ void PreprocessorLexer::LexIncludeFilename(Token &FilenameTok) { // We are now parsing a filename! ParsingFilename = true; - + // Lex the filename. IndirectLex(FilenameTok); // We should have obtained the filename now. ParsingFilename = false; - + // No filename? if (FilenameTok.is(tok::eom)) PP->Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); diff --git a/clang/lib/Lex/ScratchBuffer.cpp b/clang/lib/Lex/ScratchBuffer.cpp index 28f3d7ff45b2e3124965101441d377f050cab4d6..0e98c1751985522a5ee478f4ff4b8729972990a6 100644 --- a/clang/lib/Lex/ScratchBuffer.cpp +++ b/clang/lib/Lex/ScratchBuffer.cpp @@ -38,16 +38,16 @@ SourceLocation ScratchBuffer::getToken(const char *Buf, unsigned Len, // Prefix the token with a \n, so that it looks like it is the first thing on // its own virtual line in caret diagnostics. CurBuffer[BytesUsed++] = '\n'; - + // Return a pointer to the character data. DestPtr = CurBuffer+BytesUsed; - + // Copy the token data into the buffer. memcpy(CurBuffer+BytesUsed, Buf, Len); // Remember that we used these bytes. BytesUsed += Len+1; - + // Add a NUL terminator to the token. This keeps the tokens separated, in // case they get relexed, and puts them on their own virtual lines in case a // diagnostic points to one. @@ -62,8 +62,8 @@ void ScratchBuffer::AllocScratchBuffer(unsigned RequestLen) { // support gigantic tokens, which almost certainly won't happen. :) if (RequestLen < ScratchBufSize) RequestLen = ScratchBufSize; - - llvm::MemoryBuffer *Buf = + + llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getNewMemBuffer(RequestLen, ""); FileID FID = SourceMgr.createFileIDForMemBuffer(Buf); BufferStartLoc = SourceMgr.getLocForStartOfFile(FID); diff --git a/clang/lib/Lex/TokenConcatenation.cpp b/clang/lib/Lex/TokenConcatenation.cpp index be13b274574a6c529c07458e6111c3223889c387..ade7f8516ea7b5baa158a65778fe9ef3182fcec5 100644 --- a/clang/lib/Lex/TokenConcatenation.cpp +++ b/clang/lib/Lex/TokenConcatenation.cpp @@ -13,7 +13,7 @@ #include "clang/Lex/TokenConcatenation.h" #include "clang/Lex/Preprocessor.h" -using namespace clang; +using namespace clang; /// StartsWithL - Return true if the spelling of this token starts with 'L'. @@ -22,14 +22,14 @@ bool TokenConcatenation::StartsWithL(const Token &Tok) const { SourceManager &SM = PP.getSourceManager(); return *SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation())) == 'L'; } - + if (Tok.getLength() < 256) { char Buffer[256]; const char *TokPtr = Buffer; PP.getSpelling(Tok, TokPtr); return TokPtr[0] == 'L'; } - + return PP.getSpelling(Tok)[0] == 'L'; } @@ -42,21 +42,21 @@ bool TokenConcatenation::IsIdentifierL(const Token &Tok) const { SourceManager &SM = PP.getSourceManager(); return *SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation())) == 'L'; } - + if (Tok.getLength() < 256) { char Buffer[256]; const char *TokPtr = Buffer; - if (PP.getSpelling(Tok, TokPtr) != 1) + if (PP.getSpelling(Tok, TokPtr) != 1) return false; return TokPtr[0] == 'L'; } - + return PP.getSpelling(Tok) == "L"; } TokenConcatenation::TokenConcatenation(Preprocessor &pp) : PP(pp) { memset(TokenInfo, 0, sizeof(TokenInfo)); - + // These tokens have custom code in AvoidConcat. TokenInfo[tok::identifier ] |= aci_custom; TokenInfo[tok::numeric_constant] |= aci_custom_firstchar; @@ -72,7 +72,7 @@ TokenConcatenation::TokenConcatenation(Preprocessor &pp) : PP(pp) { TokenInfo[tok::colon ] |= aci_custom_firstchar; TokenInfo[tok::hash ] |= aci_custom_firstchar; TokenInfo[tok::arrow ] |= aci_custom_firstchar; - + // These tokens change behavior if followed by an '='. TokenInfo[tok::amp ] |= aci_avoid_equal; // &= TokenInfo[tok::plus ] |= aci_avoid_equal; // += @@ -130,29 +130,29 @@ bool TokenConcatenation::AvoidConcat(const Token &PrevTok, // source. If they were, it must be okay to stick them together: if there // were an issue, the tokens would have been lexed differently. if (PrevTok.getLocation().isFileID() && Tok.getLocation().isFileID() && - PrevTok.getLocation().getFileLocWithOffset(PrevTok.getLength()) == + PrevTok.getLocation().getFileLocWithOffset(PrevTok.getLength()) == Tok.getLocation()) return false; - + tok::TokenKind PrevKind = PrevTok.getKind(); if (PrevTok.getIdentifierInfo()) // Language keyword or named operator. PrevKind = tok::identifier; - + // Look up information on when we should avoid concatenation with prevtok. unsigned ConcatInfo = TokenInfo[PrevKind]; - + // If prevtok never causes a problem for anything after it, return quickly. if (ConcatInfo == 0) return false; - + if (ConcatInfo & aci_avoid_equal) { // If the next token is '=' or '==', avoid concatenation. if (Tok.is(tok::equal) || Tok.is(tok::equalequal)) return true; ConcatInfo &= ~aci_avoid_equal; } - + if (ConcatInfo == 0) return false; - + // Basic algorithm: we look at the first character of the second token, and // determine whether it, if appended to the first token, would form (or // would contribute) to a larger token if concatenated. @@ -162,10 +162,10 @@ bool TokenConcatenation::AvoidConcat(const Token &PrevTok, } else { FirstChar = GetFirstChar(PP, Tok); } - + switch (PrevKind) { default: assert(0 && "InitAvoidConcatTokenInfo built wrong"); - case tok::identifier: // id+id or id+number or id+L"foo". + case tok::identifier: // id+id or id+number or id+L"foo". // id+'.'... will not append. if (Tok.is(tok::numeric_constant)) return GetFirstChar(PP, Tok) != '.'; @@ -173,18 +173,18 @@ bool TokenConcatenation::AvoidConcat(const Token &PrevTok, if (Tok.getIdentifierInfo() || Tok.is(tok::wide_string_literal) /* || Tok.is(tok::wide_char_literal)*/) return true; - + // If this isn't identifier + string, we're done. if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal)) return false; - + // FIXME: need a wide_char_constant! - + // If the string was a wide string L"foo" or wide char L'f', it would // concat with the previous identifier into fooL"bar". Avoid this. if (StartsWithL(Tok)) return true; - + // Otherwise, this is a narrow character or string. If the *identifier* // is a literal 'L', avoid pasting L "foo" -> L"foo". return IsIdentifierL(PrevTok); diff --git a/clang/lib/Lex/TokenLexer.cpp b/clang/lib/Lex/TokenLexer.cpp index f9f93867c853259d3e45e390134a8f9ee6c78415..f006f5ae55bb005ff62b500191a3a5b92644aa77 100644 --- a/clang/lib/Lex/TokenLexer.cpp +++ b/clang/lib/Lex/TokenLexer.cpp @@ -27,11 +27,11 @@ void TokenLexer::Init(Token &Tok, SourceLocation ILEnd, MacroArgs *Actuals) { // If the client is reusing a TokenLexer, make sure to free any memory // associated with it. destroy(); - + Macro = PP.getMacroInfo(Tok.getIdentifierInfo()); ActualArgs = Actuals; CurToken = 0; - + InstantiateLocStart = Tok.getLocation(); InstantiateLocEnd = ILEnd; AtStartOfLine = Tok.isAtStartOfLine(); @@ -45,7 +45,7 @@ void TokenLexer::Init(Token &Tok, SourceLocation ILEnd, MacroArgs *Actuals) { // Tokens to point to the expanded tokens. if (Macro->isFunctionLike() && Macro->getNumArgs()) ExpandFunctionArguments(); - + // Mark the macro as currently disabled, so that it is not recursively // expanded. The macro must be disabled only after argument pre-expansion of // function-like macro arguments occurs. @@ -61,7 +61,7 @@ void TokenLexer::Init(const Token *TokArray, unsigned NumToks, // If the client is reusing a TokenLexer, make sure to free any memory // associated with it. destroy(); - + Macro = 0; ActualArgs = 0; Tokens = TokArray; @@ -72,7 +72,7 @@ void TokenLexer::Init(const Token *TokArray, unsigned NumToks, InstantiateLocStart = InstantiateLocEnd = SourceLocation(); AtStartOfLine = false; HasLeadingSpace = false; - + // Set HasLeadingSpace/AtStartOfLine so that the first token will be // returned unmodified. if (NumToks != 0) { @@ -90,7 +90,7 @@ void TokenLexer::destroy() { Tokens = 0; OwnsTokens = false; } - + // TokenLexer owns its formal arguments. if (ActualArgs) ActualArgs->destroy(); } @@ -99,17 +99,17 @@ void TokenLexer::destroy() { /// return preexpanded tokens from Tokens. void TokenLexer::ExpandFunctionArguments() { llvm::SmallVector ResultToks; - + // Loop through 'Tokens', expanding them into ResultToks. Keep // track of whether we change anything. If not, no need to keep them. If so, // we install the newly expanded sequence as the new 'Tokens' list. bool MadeChange = false; - + // NextTokGetsSpace - When this is true, the next token appended to the // output list will get a leading space, regardless of whether it had one to // begin with or not. This is used for placemarker support. bool NextTokGetsSpace = false; - + for (unsigned i = 0, e = NumTokens; i != e; ++i) { // If we found the stringify operator, get the argument stringified. The // preprocessor already verified that the following token is a macro name @@ -118,7 +118,7 @@ void TokenLexer::ExpandFunctionArguments() { if (CurTok.is(tok::hash) || CurTok.is(tok::hashat)) { int ArgNo = Macro->getArgumentNum(Tokens[i+1].getIdentifierInfo()); assert(ArgNo != -1 && "Token following # is not an argument?"); - + Token Res; if (CurTok.is(tok::hash)) // Stringify Res = ActualArgs->getStringifiedArgument(ArgNo, PP); @@ -127,19 +127,19 @@ void TokenLexer::ExpandFunctionArguments() { Res = MacroArgs::StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true); } - + // The stringified/charified string leading space flag gets set to match // the #/#@ operator. if (CurTok.hasLeadingSpace() || NextTokGetsSpace) Res.setFlag(Token::LeadingSpace); - + ResultToks.push_back(Res); MadeChange = true; ++i; // Skip arg name. NextTokGetsSpace = false; continue; } - + // Otherwise, if this is not an argument token, just add the token to the // output buffer. IdentifierInfo *II = CurTok.getIdentifierInfo(); @@ -154,17 +154,17 @@ void TokenLexer::ExpandFunctionArguments() { } continue; } - + // An argument is expanded somehow, the result is different than the // input. MadeChange = true; // Otherwise, this is a use of the argument. Find out if there is a paste // (##) operator before or after the argument. - bool PasteBefore = + bool PasteBefore = !ResultToks.empty() && ResultToks.back().is(tok::hashhash); bool PasteAfter = i+1 != e && Tokens[i+1].is(tok::hashhash); - + // If it is not the LHS/RHS of a ## operator, we must pre-expand the // argument and substitute the expanded tokens into the result. This is // C99 6.10.3.1p1. @@ -178,13 +178,13 @@ void TokenLexer::ExpandFunctionArguments() { ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0]; else ResultArgToks = ArgTok; // Use non-preexpanded tokens. - + // If the arg token expanded into anything, append it. if (ResultArgToks->isNot(tok::eof)) { unsigned FirstResult = ResultToks.size(); unsigned NumToks = MacroArgs::getArgLength(ResultArgToks); ResultToks.append(ResultArgToks, ResultArgToks+NumToks); - + // If any tokens were substituted from the argument, the whitespace // before the first token should match the whitespace of the arg // identifier. @@ -199,7 +199,7 @@ void TokenLexer::ExpandFunctionArguments() { } continue; } - + // Okay, we have a token that is either the LHS or RHS of a paste (##) // argument. It gets substituted as its non-pre-expanded tokens. const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo); @@ -217,9 +217,9 @@ void TokenLexer::ExpandFunctionArguments() { PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma); ResultToks.pop_back(); } - + ResultToks.append(ArgToks, ArgToks+NumToks); - + // If this token (the macro argument) was supposed to get leading // whitespace, transfer this information onto the first token of the // expansion. @@ -233,11 +233,11 @@ void TokenLexer::ExpandFunctionArguments() { if ((CurTok.hasLeadingSpace() || NextTokGetsSpace) && !PasteBefore) ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace); - + NextTokGetsSpace = false; continue; } - + // If an empty argument is on the LHS or RHS of a paste, the standard (C99 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We // implement this by eating ## operators when a LHS or RHS expands to @@ -250,13 +250,13 @@ void TokenLexer::ExpandFunctionArguments() { ++i; continue; } - + // If this is on the RHS of a paste operator, we've already copied the // paste operator to the ResultToks list. Remove it. assert(PasteBefore && ResultToks.back().is(tok::hashhash)); NextTokGetsSpace |= ResultToks.back().hasLeadingSpace(); ResultToks.pop_back(); - + // If this is the __VA_ARGS__ token, and if the argument wasn't provided, // and if the macro had at least one real argument, and if the token before // the ## was a comma, remove the comma. @@ -271,7 +271,7 @@ void TokenLexer::ExpandFunctionArguments() { } continue; } - + // If anything changed, install this as the new Tokens list. if (MadeChange) { assert(!OwnsTokens && "This would leak if we already own the token list"); @@ -284,7 +284,7 @@ void TokenLexer::ExpandFunctionArguments() { if (NumTokens) memcpy(Res, &ResultToks[0], NumTokens*sizeof(Token)); Tokens = Res; - + // The preprocessor bump pointer owns these tokens, not us. OwnsTokens = false; } @@ -309,16 +309,16 @@ void TokenLexer::Lex(Token &Tok) { // whatever is next. return PPCache.Lex(Tok); } - + // If this is the first token of the expanded result, we inherit spacing // properties later. bool isFirstToken = CurToken == 0; - + // Get the next token to return. Tok = Tokens[CurToken++]; - + bool TokenIsFromPaste = false; - + // If this token is followed by a token paste (##) operator, paste the tokens! if (!isAtEnd() && Tokens[CurToken].is(tok::hashhash)) { if (PasteTokens(Tok)) { @@ -328,7 +328,7 @@ void TokenLexer::Lex(Token &Tok) { } else { TokenIsFromPaste = true; } - } + } // The token's current location indicate where the token was lexed from. We // need this information to compute the spelling of the token, but any @@ -337,26 +337,26 @@ void TokenLexer::Lex(Token &Tok) { // that captures all of this. if (InstantiateLocStart.isValid()) { // Don't do this for token streams. SourceManager &SM = PP.getSourceManager(); - Tok.setLocation(SM.createInstantiationLoc(Tok.getLocation(), + Tok.setLocation(SM.createInstantiationLoc(Tok.getLocation(), InstantiateLocStart, InstantiateLocEnd, Tok.getLength())); } - + // If this is the first token, set the lexical properties of the token to // match the lexical properties of the macro identifier. if (isFirstToken) { Tok.setFlagValue(Token::StartOfLine , AtStartOfLine); Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace); } - + // Handle recursive expansion! if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != 0) { // Change the kind of this identifier to the appropriate token kind, e.g. // turning "for" into a keyword. IdentifierInfo *II = Tok.getIdentifierInfo(); Tok.setKind(II->getTokenID()); - + // If this identifier was poisoned and from a paste, emit an error. This // won't be handled by Preprocessor::HandleIdentifier because this is coming // from a macro expansion. @@ -367,7 +367,7 @@ void TokenLexer::Lex(Token &Tok) { else PP.Diag(Tok, diag::err_pp_used_poisoned_id); } - + if (!DisableMacroExpansion && II->isHandleIdentifierCase()) PP.HandleIdentifier(Tok); } @@ -387,33 +387,33 @@ bool TokenLexer::PasteTokens(Token &Tok) { SourceLocation PasteOpLoc = Tokens[CurToken].getLocation(); ++CurToken; assert(!isAtEnd() && "No token on the RHS of a paste operator!"); - + // Get the RHS token. const Token &RHS = Tokens[CurToken]; - + // Allocate space for the result token. This is guaranteed to be enough for // the two tokens. Buffer.resize(Tok.getLength() + RHS.getLength()); - + // Get the spelling of the LHS token in Buffer. const char *BufPtr = &Buffer[0]; unsigned LHSLen = PP.getSpelling(Tok, BufPtr); if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer! memcpy(&Buffer[0], BufPtr, LHSLen); - + BufPtr = &Buffer[LHSLen]; unsigned RHSLen = PP.getSpelling(RHS, BufPtr); if (BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer! memcpy(&Buffer[LHSLen], BufPtr, RHSLen); - + // Trim excess space. Buffer.resize(LHSLen+RHSLen); - + // Plop the pasted result (including the trailing newline and null) into a // scratch buffer where we can lex it. Token ResultTokTmp; ResultTokTmp.startToken(); - + // Claim that the tmp token is a string_literal so that we can get the // character pointer back from CreateString. ResultTokTmp.setKind(tok::string_literal); @@ -423,7 +423,7 @@ bool TokenLexer::PasteTokens(Token &Tok) { // Lex the resultant pasted token into Result. Token Result; - + if (Tok.is(tok::identifier) && RHS.is(tok::identifier)) { // Common paste case: identifier+identifier = identifier. Avoid creating // a lexer and other overhead. @@ -434,42 +434,42 @@ bool TokenLexer::PasteTokens(Token &Tok) { Result.setLength(LHSLen+RHSLen); } else { PP.IncrementPasteCounter(false); - + assert(ResultTokLoc.isFileID() && "Should be a raw location into scratch buffer"); SourceManager &SourceMgr = PP.getSourceManager(); FileID LocFileID = SourceMgr.getFileID(ResultTokLoc); - + const char *ScratchBufStart = SourceMgr.getBufferData(LocFileID).first; - + // Make a lexer to lex this string from. Lex just this one token. // Make a lexer object so that we lex and expand the paste result. Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID), PP.getLangOptions(), ScratchBufStart, ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen); - + // Lex a token in raw mode. This way it won't look up identifiers // automatically, lexing off the end will return an eof token, and // warnings are disabled. This returns true if the result token is the // entire buffer. bool isInvalid = !TL.LexFromRawLexer(Result); - + // If we got an EOF token, we didn't form even ONE token. For example, we // did "/ ## /" to get "//". isInvalid |= Result.is(tok::eof); - + // If pasting the two tokens didn't form a full new token, this is an // error. This occurs with "x ## +" and other stuff. Return with Tok // unmodified and with RHS as the next token to lex. if (isInvalid) { // Test for the Microsoft extension of /##/ turning into // here on the // error path. - if (PP.getLangOptions().Microsoft && Tok.is(tok::slash) && + if (PP.getLangOptions().Microsoft && Tok.is(tok::slash) && RHS.is(tok::slash)) { HandleMicrosoftCommentPaste(Tok); return true; } - + // Do not emit the warning when preprocessing assembler code. if (!PP.getLangOptions().AsmPreprocessor) { // Explicitly convert the token location to have proper instantiation @@ -481,26 +481,26 @@ bool TokenLexer::PasteTokens(Token &Tok) { PP.Diag(Loc, diag::err_pp_bad_paste) << std::string(Buffer.begin(), Buffer.end()); } - + // Do not consume the RHS. --CurToken; } - + // Turn ## into 'unknown' to avoid # ## # from looking like a paste // operator. if (Result.is(tok::hashhash)) Result.setKind(tok::unknown); } - + // Transfer properties of the LHS over the the Result. Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine()); Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace()); - + // Finally, replace LHS with the result, consume the RHS, and iterate. ++CurToken; Tok = Result; } while (!isAtEnd() && Tokens[CurToken].is(tok::hashhash)); - + // Now that we got the result token, it will be subject to expansion. Since // token pasting re-lexes the result token in raw mode, identifier information // isn't looked up. As such, if the result is an identifier, look up id info. @@ -532,11 +532,11 @@ unsigned TokenLexer::isNextTokenLParen() const { void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok) { // We 'comment out' the rest of this macro by just ignoring the rest of the // tokens that have not been lexed yet, if any. - + // Since this must be a macro, mark the macro enabled now that it is no longer // being expanded. assert(Macro && "Token streams can't paste comments"); Macro->EnableMacro(); - + PP.HandleMicrosoftCommentPaste(Tok); } diff --git a/clang/lib/Parse/AttributeList.cpp b/clang/lib/Parse/AttributeList.cpp index 32ffba36dd6002c8a4375bcb904ee07a17e6d548..2ee41bc3eb8d8f05cffb4661e1d84d4867942bb7 100644 --- a/clang/lib/Parse/AttributeList.cpp +++ b/clang/lib/Parse/AttributeList.cpp @@ -21,7 +21,7 @@ AttributeList::AttributeList(IdentifierInfo *aName, SourceLocation aLoc, AttributeList *n, bool declspec) : AttrName(aName), AttrLoc(aLoc), ParmName(pName), ParmLoc(pLoc), NumArgs(numArgs), Next(n), DeclspecAttribute(declspec) { - + if (numArgs == 0) Args = 0; else { @@ -32,12 +32,12 @@ AttributeList::AttributeList(IdentifierInfo *aName, SourceLocation aLoc, AttributeList::~AttributeList() { if (Args) { - // FIXME: before we delete the vector, we need to make sure the Expr's + // FIXME: before we delete the vector, we need to make sure the Expr's // have been deleted. Since ActionBase::ExprTy is "void", we are dependent // on the actions module for actually freeing the memory. The specific - // hooks are ActOnDeclarator, ActOnTypeName, ActOnParamDeclaratorType, - // ParseField, ParseTag. Once these routines have freed the expression, - // they should zero out the Args slot (to indicate the memory has been + // hooks are ActOnDeclarator, ActOnTypeName, ActOnParamDeclaratorType, + // ParseField, ParseTag. Once these routines have freed the expression, + // they should zero out the Args slot (to indicate the memory has been // freed). If any element of the vector is non-null, we should assert. delete [] Args; } @@ -54,7 +54,7 @@ AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name) { Str += 2; Len -= 4; } - + // FIXME: Hand generating this is neither smart nor efficient. switch (Len) { case 4: @@ -103,7 +103,7 @@ AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name) { if (!memcmp(Str, "deprecated", 10)) return AT_deprecated; if (!memcmp(Str, "visibility", 10)) return AT_visibility; if (!memcmp(Str, "destructor", 10)) return AT_destructor; - if (!memcmp(Str, "format_arg", 10)) return AT_format_arg; + if (!memcmp(Str, "format_arg", 10)) return AT_format_arg; if (!memcmp(Str, "gnu_inline", 10)) return AT_gnu_inline; break; case 11: @@ -136,13 +136,13 @@ AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name) { case 19: if (!memcmp(Str, "ns_returns_retained", 19)) return AT_ns_returns_retained; if (!memcmp(Str, "cf_returns_retained", 19)) return AT_cf_returns_retained; - break; + break; case 20: if (!memcmp(Str, "reqd_work_group_size", 20)) return AT_reqd_wg_size; case 22: if (!memcmp(Str, "no_instrument_function", 22)) return AT_no_instrument_function; break; - } + } return UnknownAttribute; } diff --git a/clang/lib/Parse/DeclSpec.cpp b/clang/lib/Parse/DeclSpec.cpp index ceb19a3b3b1a23c01b795b93afe4eeb5f0514534..0342e393635a744c6a47f418bac665c06f5ef665 100644 --- a/clang/lib/Parse/DeclSpec.cpp +++ b/clang/lib/Parse/DeclSpec.cpp @@ -65,7 +65,7 @@ DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto, bool isVariadic, // parameter list there (in an effort to avoid new/delete traffic). If it // is already used (consider a function returning a function pointer) or too // small (function taking too many arguments), go to the heap. - if (!TheDeclarator.InlineParamsUsed && + if (!TheDeclarator.InlineParamsUsed && NumArgs <= llvm::array_lengthof(TheDeclarator.InlineParams)) { I.Fun.ArgInfo = TheDeclarator.InlineParams; I.Fun.DeleteArgInfo = false; @@ -98,10 +98,10 @@ unsigned DeclSpec::getParsedSpecifiers() const { if (TypeQualifiers != TQ_unspecified) Res |= PQ_TypeQualifier; - + if (hasTypeSpecifier()) Res |= PQ_TypeSpecifier; - + if (FS_inline_specified || FS_virtual_specified || FS_explicit_specified) Res |= PQ_FunctionSpecifier; return Res; @@ -114,7 +114,7 @@ template static bool BadSpecifier(T TNew, T TPrev, DiagID = (TNew == TPrev ? diag::ext_duplicate_declspec : diag::err_invalid_decl_spec_combination); return true; -} +} const char *DeclSpec::getSpecifierName(DeclSpec::SCS S) { switch (S) { @@ -209,7 +209,7 @@ bool DeclSpec::SetStorageClassSpec(SCS S, SourceLocation Loc, return false; } -bool DeclSpec::SetStorageClassSpecThread(SourceLocation Loc, +bool DeclSpec::SetStorageClassSpecThread(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID) { if (SCS_thread_specified) { @@ -238,7 +238,7 @@ bool DeclSpec::SetTypeSpecWidth(TSW W, SourceLocation Loc, return false; } -bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc, +bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID) { if (TypeSpecComplex != TSC_unspecified) @@ -248,7 +248,7 @@ bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc, return false; } -bool DeclSpec::SetTypeSpecSign(TSS S, SourceLocation Loc, +bool DeclSpec::SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID) { if (TypeSpecSign != TSS_unspecified) @@ -287,7 +287,7 @@ bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec, if ((TypeQualifiers & T) && !Lang.C99) return BadSpecifier(T, T, PrevSpec, DiagID); TypeQualifiers |= T; - + switch (T) { default: assert(0 && "Unknown type qualifier!"); case TQ_const: TQ_constLoc = Loc; break; @@ -380,7 +380,7 @@ void DeclSpec::Finish(Diagnostic &D, Preprocessor &PP) { } break; } - + // TODO: if the implementation does not implement _Complex or _Imaginary, // disallow their use. Need information about the backend. if (TypeSpecComplex != TSC_unspecified) { @@ -419,9 +419,9 @@ void DeclSpec::Finish(Diagnostic &D, Preprocessor &PP) { // Okay, now we can infer the real type. - + // TODO: return "auto function" and other bad things based on the real type. - + // 'data definition has no type or storage class'? } diff --git a/clang/lib/Parse/ExtensionRAIIObject.h b/clang/lib/Parse/ExtensionRAIIObject.h index 2b2bd3b21648e66285fb8ceb3ff186915df712db..cc7c8e21705c14adeefc3a8f29ad386c18b53f79 100644 --- a/clang/lib/Parse/ExtensionRAIIObject.h +++ b/clang/lib/Parse/ExtensionRAIIObject.h @@ -30,7 +30,7 @@ namespace clang { ExtensionRAIIObject(Diagnostic &diags) : Diags(diags) { Diags.IncrementAllExtensionsSilenced(); } - + ~ExtensionRAIIObject() { Diags.DecrementAllExtensionsSilenced(); } diff --git a/clang/lib/Parse/MinimalAction.cpp b/clang/lib/Parse/MinimalAction.cpp index d89cc8c3ea2940c57752f667b150fe3cbf754719..71b22cad6f6226ffd4f5d3b6d3813a3a75f62423 100644 --- a/clang/lib/Parse/MinimalAction.cpp +++ b/clang/lib/Parse/MinimalAction.cpp @@ -34,7 +34,7 @@ Action::DeclPtrTy Action::ActOnUsingDirective(Scope *CurScope, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *AttrList) { - + // FIXME: Parser seems to assume that Action::ActOn* takes ownership over // passed AttributeList, however other actions don't free it, is it // temporary state or bug? @@ -52,7 +52,7 @@ Action::DeclPtrTy Action::ActOnUsingDeclaration(Scope *CurScope, OverloadedOperatorKind Op, AttributeList *AttrList, bool IsTypeName) { - + // FIXME: Parser seems to assume that Action::ActOn* takes ownership over // passed AttributeList, however other actions don't free it, is it // temporary state or bug? @@ -67,11 +67,11 @@ void PrettyStackTraceActionsDecl::print(llvm::raw_ostream &OS) const { OS << ": "; } OS << Message; - + std::string Name = Actions.getDeclName(TheDecl); if (!Name.empty()) OS << " '" << Name << '\''; - + OS << '\n'; } @@ -81,7 +81,7 @@ namespace { struct TypeNameInfo { TypeNameInfo *Prev; bool isTypeName; - + TypeNameInfo(bool istypename, TypeNameInfo *prev) { isTypeName = istypename; Prev = prev; @@ -90,13 +90,13 @@ namespace { struct TypeNameInfoTable { llvm::RecyclingAllocator Allocator; - + void AddEntry(bool isTypename, IdentifierInfo *II) { TypeNameInfo *TI = Allocator.Allocate(); new (TI) TypeNameInfo(isTypename, II->getFETokenInfo()); II->setFETokenInfo(TI); } - + void DeleteEntry(TypeNameInfo *Entry) { Entry->~TypeNameInfo(); Allocator.Deallocate(Entry); @@ -108,7 +108,7 @@ static TypeNameInfoTable *getTable(void *TP) { return static_cast(TP); } -MinimalAction::MinimalAction(Preprocessor &pp) +MinimalAction::MinimalAction(Preprocessor &pp) : Idents(pp.getIdentifierTable()), PP(pp) { TypeNameInfoTablePtr = new TypeNameInfoTable(); } @@ -127,9 +127,9 @@ void MinimalAction::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { TNIT.AddEntry(true, &Idents.get("__int128_t")); TNIT.AddEntry(true, &Idents.get("__uint128_t")); } - + if (PP.getLangOptions().ObjC1) { - // Recognize the ObjC built-in type identifiers as types. + // Recognize the ObjC built-in type identifiers as types. TNIT.AddEntry(true, &Idents.get("id")); TNIT.AddEntry(true, &Idents.get("SEL")); TNIT.AddEntry(true, &Idents.get("Class")); @@ -159,12 +159,12 @@ bool MinimalAction::isCurrentClassName(const IdentifierInfo &, Scope *, return false; } -TemplateNameKind +TemplateNameKind MinimalAction::isTemplateName(Scope *S, const IdentifierInfo &II, SourceLocation IdLoc, const CXXScopeSpec *SS, - TypeTy *ObjectType, + TypeTy *ObjectType, bool EnteringScope, TemplateTy &TemplateDecl) { return TNK_Non_template; @@ -176,10 +176,10 @@ MinimalAction::isTemplateName(Scope *S, Action::DeclPtrTy MinimalAction::ActOnDeclarator(Scope *S, Declarator &D) { IdentifierInfo *II = D.getIdentifier(); - + // If there is no identifier associated with this declarator, bail out. if (II == 0) return DeclPtrTy(); - + TypeNameInfo *weCurrentlyHaveTypeInfo = II->getFETokenInfo(); bool isTypeName = D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef; @@ -190,10 +190,10 @@ MinimalAction::ActOnDeclarator(Scope *S, Declarator &D) { if (weCurrentlyHaveTypeInfo || isTypeName) { // Allocate and add the 'TypeNameInfo' "decl". getTable(TypeNameInfoTablePtr)->AddEntry(isTypeName, II); - + // Remember that this needs to be removed when the scope is popped. S->AddDecl(DeclPtrTy::make(II)); - } + } return DeclPtrTy(); } @@ -212,15 +212,15 @@ MinimalAction::ActOnStartClassInterface(SourceLocation AtInterfaceLoc, return DeclPtrTy(); } -/// ActOnForwardClassDeclaration - -/// Scope will always be top level file scope. +/// ActOnForwardClassDeclaration - +/// Scope will always be top level file scope. Action::DeclPtrTy MinimalAction::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts) { for (unsigned i = 0; i != NumElts; ++i) { // Allocate and add the 'TypeNameInfo' "decl". getTable(TypeNameInfoTablePtr)->AddEntry(true, IdentList[i]); - + // Remember that this needs to be removed when the scope is popped. TUScope->AddDecl(DeclPtrTy::make(IdentList[i])); } @@ -231,17 +231,17 @@ MinimalAction::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, /// out-of-scope, they are removed from the IdentifierInfo::FETokenInfo field. void MinimalAction::ActOnPopScope(SourceLocation Loc, Scope *S) { TypeNameInfoTable &Table = *getTable(TypeNameInfoTablePtr); - + for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); I != E; ++I) { IdentifierInfo &II = *(*I).getAs(); TypeNameInfo *TI = II.getFETokenInfo(); assert(TI && "This decl didn't get pushed??"); - + if (TI) { TypeNameInfo *Next = TI->Prev; Table.DeleteEntry(TI); - + II.setFETokenInfo(Next); } } diff --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp b/clang/lib/Parse/ParseCXXInlineMethods.cpp index bfdbde6ddff48c9d234aaa857a632b5aa7d76606..82b7da9f68e5ef5ae546ebf6f848a9fb8292c95d 100644 --- a/clang/lib/Parse/ParseCXXInlineMethods.cpp +++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp @@ -36,7 +36,7 @@ Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D, // FIXME: Friend templates FnD = Actions.ActOnFriendDecl(CurScope, &D, /*IsDefinition*/ true); else // FIXME: pass template information through - FnD = Actions.ActOnCXXMemberDeclarator(CurScope, AS, D, + FnD = Actions.ActOnCXXMemberDeclarator(CurScope, AS, D, move(TemplateParams), 0, 0); HandleMemberFunctionDefaultArgs(D, FnD); @@ -44,7 +44,7 @@ Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D, // Consume the tokens and store them for later parsing. getCurrentClass().MethodDefs.push_back(LexedMethod(FnD)); - getCurrentClass().MethodDefs.back().TemplateScope + getCurrentClass().MethodDefs.back().TemplateScope = CurScope->isTemplateParamScope(); CachedTokens &Toks = getCurrentClass().MethodDefs.back().Toks; @@ -54,7 +54,7 @@ Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D, // Consume everything up to (and including) the left brace. if (!ConsumeAndStoreUntil(tok::l_brace, tok::unknown, Toks, tok::semi)) { // We didn't find the left-brace we expected after the - // constructor initializer. + // constructor initializer. if (Tok.is(tok::semi)) { // We found a semicolon; complain, consume the semicolon, and // don't try to parse this method later. @@ -66,7 +66,7 @@ Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D, } } else { - // Begin by storing the '{' token. + // Begin by storing the '{' token. Toks.push_back(Tok); ConsumeBrace(); } @@ -100,18 +100,18 @@ void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) { for (; !Class.MethodDecls.empty(); Class.MethodDecls.pop_front()) { LateParsedMethodDeclaration &LM = Class.MethodDecls.front(); - + // If this is a member template, introduce the template parameter scope. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); if (LM.TemplateScope) Actions.ActOnReenterTemplateScope(CurScope, LM.Method); - + // Start the delayed C++ method declaration Actions.ActOnStartDelayedCXXMethodDeclaration(CurScope, LM.Method); // Introduce the parameters into scope and parse their default // arguments. - ParseScope PrototypeScope(this, + ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope); for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) { // Introduce the parameter into scope. @@ -169,7 +169,7 @@ void Parser::ParseLexedMethodDefs(ParsingClass &Class) { ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); if (LM.TemplateScope) Actions.ActOnReenterTemplateScope(CurScope, LM.D); - + assert(!LM.Toks.empty() && "Empty body!"); // Append the current token at the end of the new token stream so that it // doesn't get lost. @@ -205,7 +205,7 @@ void Parser::ParseLexedMethodDefs(ParsingClass &Class) { /// ConsumeAndStoreUntil - Consume and store the token at the passed token /// container until the token 'T' is reached (which gets -/// consumed/stored too, if ConsumeFinalToken). +/// consumed/stored too, if ConsumeFinalToken). /// If EarlyAbortIf is specified, then we will stop early if we find that /// token at the top level. /// Returns true if token 'T1' or 'T2' was found. diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 25ff53ca9f3c73f6cb2edaa703a4f8b0e7afa13b..5d62c0c67ea1642fed95294923c2db1b06a3aeb7 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -69,10 +69,10 @@ Action::TypeResult Parser::ParseTypeName(SourceRange *Range) { /// typespec /// typequal /// storageclass -/// +/// /// FIXME: The GCC grammar/code for this construct implies we need two -/// token lookahead. Comment from gcc: "If they start with an identifier -/// which is followed by a comma or close parenthesis, then the arguments +/// token lookahead. Comment from gcc: "If they start with an identifier +/// which is followed by a comma or close parenthesis, then the arguments /// start with that identifier; otherwise they are an expression list." /// /// At the moment, I am not doing 2 token lookahead. I am also unaware of @@ -82,9 +82,9 @@ Action::TypeResult Parser::ParseTypeName(SourceRange *Range) { AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { assert(Tok.is(tok::kw___attribute) && "Not an attribute list!"); - + AttributeList *CurrAttr = 0; - + while (Tok.is(tok::kw___attribute)) { ConsumeToken(); if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, @@ -99,8 +99,8 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) while (Tok.is(tok::identifier) || isDeclarationSpecifier() || Tok.is(tok::comma)) { - - if (Tok.is(tok::comma)) { + + if (Tok.is(tok::comma)) { // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) ConsumeToken(); continue; @@ -108,26 +108,26 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { // we have an identifier or declaration specifier (const, int, etc.) IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = ConsumeToken(); - + // check if we have a "paramterized" attribute if (Tok.is(tok::l_paren)) { ConsumeParen(); // ignore the left paren loc for now - + if (Tok.is(tok::identifier)) { IdentifierInfo *ParmName = Tok.getIdentifierInfo(); SourceLocation ParmLoc = ConsumeToken(); - - if (Tok.is(tok::r_paren)) { + + if (Tok.is(tok::r_paren)) { // __attribute__(( mode(byte) )) ConsumeParen(); // ignore the right paren loc for now - CurrAttr = new AttributeList(AttrName, AttrNameLoc, + CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName, ParmLoc, 0, 0, CurrAttr); } else if (Tok.is(tok::comma)) { ConsumeToken(); // __attribute__(( format(printf, 1, 2) )) ExprVector ArgExprs(Actions); bool ArgExprsOk = true; - + // now parse the non-empty comma separated list of expressions while (1) { OwningExprResult ArgExpr(ParseAssignmentExpression()); @@ -144,7 +144,7 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { } if (ArgExprsOk && Tok.is(tok::r_paren)) { ConsumeParen(); // ignore the right paren loc for now - CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName, + CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr); } } @@ -154,7 +154,7 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { // parse a possibly empty comma separated list of expressions // __attribute__(( nonnull() )) ConsumeParen(); // ignore the right paren loc for now - CurrAttr = new AttributeList(AttrName, AttrNameLoc, + CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, SourceLocation(), 0, 0, CurrAttr); break; case tok::kw_char: @@ -174,7 +174,7 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { // If it's a builtin type name, eat it and expect a rparen // __attribute__(( vec_type_hint(char) )) ConsumeToken(); - CurrAttr = new AttributeList(AttrName, AttrNameLoc, + CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, SourceLocation(), 0, 0, CurrAttr); if (Tok.is(tok::r_paren)) ConsumeParen(); @@ -183,7 +183,7 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { // __attribute__(( aligned(16) )) ExprVector ArgExprs(Actions); bool ArgExprsOk = true; - + // now parse the list of expressions while (1) { OwningExprResult ArgExpr(ParseAssignmentExpression()); @@ -209,7 +209,7 @@ AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { } } } else { - CurrAttr = new AttributeList(AttrName, AttrNameLoc, + CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, SourceLocation(), 0, 0, CurrAttr); } } @@ -322,7 +322,7 @@ Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context, default: return ParseSimpleDeclaration(Context, DeclEnd); } - + // This routine returns a DeclGroup, if the thing we parsed only contains a // single decl, convert it now. return Actions.ConvertDeclToDeclGroup(SingleDecl); @@ -341,7 +341,7 @@ Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context, // Parse the common declaration-specifiers piece. DeclSpec DS; ParseDeclarationSpecifiers(DS); - + // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" // declaration-specifiers init-declarator-list[opt] ';' if (Tok.is(tok::semi)) { @@ -349,24 +349,24 @@ Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context, DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS); return Actions.ConvertDeclToDeclGroup(TheDecl); } - + Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context); ParseDeclarator(DeclaratorInfo); - + DeclGroupPtrTy DG = ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo); DeclEnd = Tok.getLocation(); - + // If the client wants to check what comes after the declaration, just return // immediately without checking anything! if (!RequireSemi) return DG; - + if (Tok.is(tok::semi)) { ConsumeToken(); return DG; } - + Diag(Tok, diag::err_expected_semi_declaration); // Skip to end of block or statement SkipUntil(tok::r_brace, true, true); @@ -406,27 +406,27 @@ Parser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D, SkipUntil(tok::semi, true, true); return DeclPtrTy(); } - + D.setAsmLabel(AsmLabel.release()); D.SetRangeEnd(Loc); } - + // If attributes are present, parse them. if (Tok.is(tok::kw___attribute)) { SourceLocation Loc; AttributeList *AttrList = ParseAttributes(&Loc); D.AddAttributes(AttrList, Loc); } - + // Inform the current actions module that we just parsed this declarator. - DeclPtrTy ThisDecl = TemplateInfo.TemplateParams? + DeclPtrTy ThisDecl = TemplateInfo.TemplateParams? Actions.ActOnTemplateDeclarator(CurScope, Action::MultiTemplateParamsArg(Actions, TemplateInfo.TemplateParams->data(), TemplateInfo.TemplateParams->size()), D) : Actions.ActOnDeclarator(CurScope, D); - + // Parse declarator '=' initializer. if (Tok.is(tok::equal)) { ConsumeToken(); @@ -467,7 +467,7 @@ Parser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D, CommaLocs.data(), RParenLoc); } } else { - bool TypeContainsUndeducedAuto = + bool TypeContainsUndeducedAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsUndeducedAuto); } @@ -492,25 +492,25 @@ ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) { // Declarators may be grouped together ("int X, *Y, Z();"). Remember the decls // that we parse together here. llvm::SmallVector DeclsInGroup; - + // At this point, we know that it is not a function definition. Parse the // rest of the init-declarator-list. while (1) { DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(D); if (ThisDecl.get()) DeclsInGroup.push_back(ThisDecl); - + // If we don't have a comma, it is either the end of the list (a ';') or an // error, bail out. if (Tok.isNot(tok::comma)) break; - + // Consume the comma. ConsumeToken(); - + // Parse the next declarator. D.clear(); - + // Accept attributes in an init-declarator. In the first declarator in a // declaration, these would be part of the declspec. In subsequent // declarators, they become part of the declarator itself, so that they @@ -523,10 +523,10 @@ ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) { AttributeList *AttrList = ParseAttributes(&Loc); D.AddAttributes(AttrList, Loc); } - + ParseDeclarator(D); } - + return Actions.FinalizeDeclaratorGroup(CurScope, D.getDeclSpec(), DeclsInGroup.data(), DeclsInGroup.size()); @@ -542,13 +542,13 @@ void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { /// specifier-qualifier-list is a subset of declaration-specifiers. Just /// parse declaration-specifiers and complain about extra stuff. ParseDeclarationSpecifiers(DS); - + // Validate declspec for type-name. unsigned Specs = DS.getParsedSpecifiers(); if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && !DS.getAttributes()) Diag(Tok, diag::err_typename_requires_specqual); - + // Issue diagnostic and remove storage class if present. if (Specs & DeclSpec::PQ_StorageClassSpecifier) { if (DS.getStorageClassSpecLoc().isValid()) @@ -557,7 +557,7 @@ void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); DS.ClearStorageClassSpecs(); } - + // Issue diagnostic and remove function specfier if present. if (Specs & DeclSpec::PQ_FunctionSpecifier) { if (DS.isInlineSpecified()) @@ -608,7 +608,7 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS) { assert(Tok.is(tok::identifier) && "should have identifier"); - + SourceLocation Loc = Tok.getLocation(); // If we see an identifier that is not a type name, we normally would // parse it as the identifer being declared. However, when a typename @@ -623,7 +623,7 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, // next token is obviously invalid for a type. Parse these as a case // with an invalid type specifier. assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); - + // Since we know that this either implicit int (which is rare) or an // error, we'd do lookahead to try to do better recovery. if (isValidAfterIdentifierInDeclarator(NextToken())) { @@ -632,7 +632,7 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, // identifier in the declarator. return false; } - + // Otherwise, if we don't consume this token, we are going to emit an // error anyway. Try to recover from various common problems. Check // to see if this was a reference to a tag name without a tag specified. @@ -642,7 +642,7 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, if (SS == 0) { const char *TagName = 0; tok::TokenKind TagKind = tok::unknown; - + switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) { default: break; case DeclSpec::TST_enum: TagName="enum" ;TagKind=tok::kw_enum ;break; @@ -650,12 +650,12 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break; case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break; } - + if (TagName) { Diag(Loc, diag::err_use_of_tag_name_without_tag) << Tok.getIdentifierInfo() << TagName << CodeModificationHint::CreateInsertion(Tok.getLocation(),TagName); - + // Parse this as a tag as if the missing tag were present. if (TagKind == tok::kw_enum) ParseEnumSpecifier(Loc, DS, AS); @@ -664,20 +664,20 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, return true; } } - + // Since this is almost certainly an invalid type name, emit a // diagnostic that says it, eat the token, and mark the declspec as // invalid. SourceRange R; if (SS) R = SS->getRange(); - + Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; const char *PrevSpec; unsigned DiagID; DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID); DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); - + // TODO: Could inject an invalid typedef decl in an enclosing scope to // avoid rippling error messages on subsequent uses of the same type, // could be useful if #include was forgotten. @@ -719,13 +719,13 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, SourceLocation Loc = Tok.getLocation(); switch (Tok.getKind()) { - default: + default: DoneWithDeclSpec: // If this is not a declaration specifier token, we're done reading decl // specifiers. First verify that DeclSpec's are consistent. DS.Finish(Diags, PP); return; - + case tok::coloncolon: // ::foo::bar // Annotate C++ scope specifiers. If we get one, loop. if (TryAnnotateCXXScopeToken(true)) @@ -738,13 +738,13 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, // We are looking for a qualified typename. Token Next = NextToken(); - if (Next.is(tok::annot_template_id) && + if (Next.is(tok::annot_template_id) && static_cast(Next.getAnnotationValue()) ->Kind == TNK_Type_template) { // We have a qualified template-id, e.g., N::A CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true); - assert(Tok.is(tok::annot_template_id) && + assert(Tok.is(tok::annot_template_id) && "ParseOptionalCXXScopeSpecifier not working"); AnnotateTemplateIdTokenAsType(&SS); continue; @@ -771,26 +771,26 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, // If the referenced identifier is not a type, then this declspec is // erroneous: We already checked about that it has no type specifier, and // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the - // typename. + // typename. if (TypeRep == 0) { ConsumeToken(); // Eat the scope spec so the identifier is current. if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; goto DoneWithDeclSpec; } - + ConsumeToken(); // The C++ scope. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, TypeRep); if (isInvalid) break; - + DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); // The typename. continue; } - + case tok::annot_typename: { if (Tok.getAnnotationValue()) isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, @@ -799,38 +799,38 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, DS.SetTypeSpecError(); DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeToken(); // The typename - + // Objective-C supports syntax of the form 'id' where 'id' // is a specific typedef and 'itf' where 'itf' is an // Objective-C interface. If we don't have Objective-C or a '<', this is // just a normal reference to a typedef name. if (!Tok.is(tok::less) || !getLang().ObjC1) continue; - + SourceLocation EndProtoLoc; llvm::SmallVector ProtocolDecl; ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size()); - + DS.SetRangeEnd(EndProtoLoc); continue; } - + // typedef-name case tok::identifier: { // In C++, check to see if this is a scope specifier like foo::bar::, if // so handle it as such. This is important for ctor parsing. if (getLang().CPlusPlus && TryAnnotateCXXScopeToken(true)) continue; - + // This identifier can only be a typedef name if we haven't already seen // a type-specifier. Without this check we misparse: // typedef int X; struct Y { short X; }; as 'short int'. if (DS.hasTypeSpecifier()) goto DoneWithDeclSpec; - + // It has to be available as a typedef too! - TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), + TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), CurScope); // If this is not a typedef name, don't parse it as part of the declspec, @@ -844,11 +844,11 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, // being defined and the next token is a '(', then this is a // constructor declaration. We're done with the decl-specifiers // and will treat this token as an identifier. - if (getLang().CPlusPlus && - (CurScope->isClassScope() || - (CurScope->isTemplateParamScope() && + if (getLang().CPlusPlus && + (CurScope->isClassScope() || + (CurScope->isTemplateParamScope() && CurScope->getParent()->isClassScope())) && - Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) && + Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) && NextToken().getKind() == tok::l_paren) goto DoneWithDeclSpec; @@ -856,7 +856,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, DiagID, TypeRep); if (isInvalid) break; - + DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); // The identifier @@ -866,12 +866,12 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, // just a normal reference to a typedef name. if (!Tok.is(tok::less) || !getLang().ObjC1) continue; - + SourceLocation EndProtoLoc; llvm::SmallVector ProtocolDecl; ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size()); - + DS.SetRangeEnd(EndProtoLoc); // Need to support trailing type qualifiers (e.g. "id

const"). @@ -881,7 +881,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, // type-name case tok::annot_template_id: { - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); if (TemplateId->Kind != TNK_Type_template) { // This template-id does not refer to a type name, so we're @@ -904,7 +904,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, case tok::kw___declspec: DS.AddAttributes(ParseMicrosoftDeclSpec()); continue; - + // Microsoft single token adornments. case tok::kw___forceinline: // FIXME: Add handling here! @@ -958,7 +958,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, case tok::kw___thread: isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); break; - + // function-specifier case tok::kw_inline: isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); @@ -980,7 +980,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, isInvalid = true; } break; - + // type-specifier case tok::kw_short: isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, @@ -1111,7 +1111,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, // but we support it. if (DS.hasTypeSpecifier() || !getLang().ObjC1) goto DoneWithDeclSpec; - + { SourceLocation EndProtoLoc; llvm::SmallVector ProtocolDecl; @@ -1201,7 +1201,7 @@ bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, if (NextToken().is(tok::kw_new) || // ::new NextToken().is(tok::kw_delete)) // ::delete return false; - + // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) @@ -1209,7 +1209,7 @@ bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, TemplateInfo); // Otherwise, not a type specifier. return false; - + // simple-type-specifier: case tok::annot_typename: { if (Tok.getAnnotationValue()) @@ -1219,19 +1219,19 @@ bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, DS.SetTypeSpecError(); DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeToken(); // The typename - + // Objective-C supports syntax of the form 'id' where 'id' // is a specific typedef and 'itf' where 'itf' is an // Objective-C interface. If we don't have Objective-C or a '<', this is // just a normal reference to a typedef name. if (!Tok.is(tok::less) || !getLang().ObjC1) return true; - + SourceLocation EndProtoLoc; llvm::SmallVector ProtocolDecl; ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size()); - + DS.SetRangeEnd(EndProtoLoc); return true; } @@ -1342,7 +1342,7 @@ bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, case tok::kw_decltype: ParseDecltypeSpecifier(DS); return true; - + // C++0x auto support. case tok::kw_auto: if (!getLang().CPlusPlus0x) @@ -1400,11 +1400,11 @@ ParseStructDeclaration(DeclSpec &DS, ConsumeToken(); return ParseStructDeclaration(DS, Fields); } - + // Parse the common specifier-qualifiers-list piece. SourceLocation DSStart = Tok.getLocation(); ParseSpecifierQualifierList(DS); - + // If there are no declarators, this is a free-standing declaration // specifier. Let the actions module cope with it. if (Tok.is(tok::semi)) { @@ -1416,12 +1416,12 @@ ParseStructDeclaration(DeclSpec &DS, Fields.push_back(FieldDeclarator(DS)); while (1) { FieldDeclarator &DeclaratorInfo = Fields.back(); - + /// struct-declarator: declarator /// struct-declarator: declarator[opt] ':' constant-expression if (Tok.isNot(tok::colon)) ParseDeclarator(DeclaratorInfo.D); - + if (Tok.is(tok::colon)) { ConsumeToken(); OwningExprResult Res(ParseConstantExpression()); @@ -1473,9 +1473,9 @@ void Parser::ParseStructUnionBody(SourceLocation RecordLoc, PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, PP.getSourceManager(), "parsing struct/union body"); - + SourceLocation LBraceLoc = ConsumeBrace(); - + ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); Actions.ActOnTagStartDefinition(CurScope, TagDecl); @@ -1491,7 +1491,7 @@ void Parser::ParseStructUnionBody(SourceLocation RecordLoc, // While we still have something to read, read the declarations in the struct. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { // Each iteration of this loop reads one struct-declaration. - + // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { Diag(Tok, diag::ext_extra_struct_semi) @@ -1505,7 +1505,7 @@ void Parser::ParseStructUnionBody(SourceLocation RecordLoc, FieldDeclarators.clear(); if (!Tok.is(tok::at)) { ParseStructDeclaration(DS, FieldDeclarators); - + // Convert them all to fields. for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) { FieldDeclarator &FD = FieldDeclarators[i]; @@ -1539,12 +1539,12 @@ void Parser::ParseStructUnionBody(SourceLocation RecordLoc, continue; } llvm::SmallVector Fields; - Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(), + Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(), Tok.getIdentifierInfo(), Fields); FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); ConsumeToken(); ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); - } + } if (Tok.is(tok::semi)) { ConsumeToken(); @@ -1557,9 +1557,9 @@ void Parser::ParseStructUnionBody(SourceLocation RecordLoc, SkipUntil(tok::r_brace, true, true); } } - + SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); - + AttributeList *AttrList = 0; // If attributes exist after struct contents, parse them. if (Tok.is(tok::kw___attribute)) @@ -1607,16 +1607,16 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, } } } - + // Must have either 'enum name' or 'enum {...}'. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) { Diag(Tok, diag::err_expected_ident_lbrace); - + // Skip the rest of this declarator, up until the comma or semicolon. SkipUntil(tok::comma, true); return; } - + // If an identifier is present, consume and remember it. IdentifierInfo *Name = 0; SourceLocation NameLoc; @@ -1624,7 +1624,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, Name = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); } - + // There are three options here. If we have 'enum foo;', then this is a // forward declaration. If we have 'enum foo {...' then this is a // definition. Otherwise we have something like 'enum foo xyz', a reference. @@ -1645,10 +1645,10 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, StartLoc, SS, Name, NameLoc, Attr, AS, Action::MultiTemplateParamsArg(Actions), Owned); - + if (Tok.is(tok::l_brace)) ParseEnumBody(StartLoc, TagDecl); - + // TODO: semantic analysis on the declspec for enums. const char *PrevSpec = 0; unsigned DiagID; @@ -1673,20 +1673,20 @@ void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { Actions.ActOnTagStartDefinition(CurScope, EnumDecl); SourceLocation LBraceLoc = ConsumeBrace(); - + // C does not allow an empty enumerator-list, C++ does [dcl.enum]. if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) Diag(Tok, diag::ext_empty_struct_union_enum) << "enum"; - + llvm::SmallVector EnumConstantDecls; DeclPtrTy LastEnumConstDecl; - + // Parse the enumerator-list. while (Tok.is(tok::identifier)) { IdentifierInfo *Ident = Tok.getIdentifierInfo(); SourceLocation IdentLoc = ConsumeToken(); - + SourceLocation EqualLoc; OwningExprResult AssignedVal(Actions); if (Tok.is(tok::equal)) { @@ -1695,7 +1695,7 @@ void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { if (AssignedVal.isInvalid()) SkipUntil(tok::comma, tok::r_brace, true, true); } - + // Install the enumerator constant into EnumDecl. DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl, LastEnumConstDecl, @@ -1704,18 +1704,18 @@ void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { AssignedVal.release()); EnumConstantDecls.push_back(EnumConstDecl); LastEnumConstDecl = EnumConstDecl; - + if (Tok.isNot(tok::comma)) break; SourceLocation CommaLoc = ConsumeToken(); - - if (Tok.isNot(tok::identifier) && + + if (Tok.isNot(tok::identifier) && !(getLang().C99 || getLang().CPlusPlus0x)) Diag(CommaLoc, diag::ext_enumerator_list_comma) << getLang().CPlusPlus << CodeModificationHint::CreateRemoval((SourceRange(CommaLoc))); } - + // Eat the }. SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); @@ -1727,7 +1727,7 @@ void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl, EnumConstantDecls.data(), EnumConstantDecls.size(), CurScope, Attr); - + EnumScope.Exit(); Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc); } @@ -1750,7 +1750,7 @@ bool Parser::isTypeQualifier() const { bool Parser::isTypeSpecifierQualifier() { switch (Tok.getKind()) { default: return false; - + case tok::identifier: // foo::bar case tok::kw_typename: // typename T::type // Annotate typenames and C++ scope specifiers. If we get one, just @@ -1771,12 +1771,12 @@ bool Parser::isTypeSpecifierQualifier() { return isTypeSpecifierQualifier(); // Otherwise, not a type specifier. return false; - + // GNU attributes support. case tok::kw___attribute: // GNU typeof support. case tok::kw_typeof: - + // type-specifiers case tok::kw_short: case tok::kw_long: @@ -1797,14 +1797,14 @@ bool Parser::isTypeSpecifierQualifier() { case tok::kw__Decimal32: case tok::kw__Decimal64: case tok::kw__Decimal128: - + // struct-or-union-specifier (C99) or class-specifier (C++) case tok::kw_class: case tok::kw_struct: case tok::kw_union: // enum-specifier case tok::kw_enum: - + // type-qualifier case tok::kw_const: case tok::kw_volatile: @@ -1813,11 +1813,11 @@ bool Parser::isTypeSpecifierQualifier() { // typedef-name case tok::annot_typename: return true; - + // GNU ObjC bizarre protocol extension: with implicit 'id'. case tok::less: return getLang().ObjC1; - + case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: @@ -1832,7 +1832,7 @@ bool Parser::isTypeSpecifierQualifier() { bool Parser::isDeclarationSpecifier() { switch (Tok.getKind()) { default: return false; - + case tok::identifier: // foo::bar // Unfortunate hack to support "Class.factoryMethod" notation. if (getLang().ObjC1 && NextToken().is(tok::period)) @@ -1850,14 +1850,14 @@ bool Parser::isDeclarationSpecifier() { if (NextToken().is(tok::kw_new) || // ::new NextToken().is(tok::kw_delete)) // ::delete return false; - + // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return isDeclarationSpecifier(); // Otherwise, not a declaration specifier. return false; - + // storage-class-specifier case tok::kw_typedef: case tok::kw_extern: @@ -1866,7 +1866,7 @@ bool Parser::isDeclarationSpecifier() { case tok::kw_auto: case tok::kw_register: case tok::kw___thread: - + // type-specifiers case tok::kw_short: case tok::kw_long: @@ -1888,14 +1888,14 @@ bool Parser::isDeclarationSpecifier() { case tok::kw__Decimal32: case tok::kw__Decimal64: case tok::kw__Decimal128: - + // struct-or-union-specifier (C99) or class-specifier (C++) case tok::kw_class: case tok::kw_struct: case tok::kw_union: // enum-specifier case tok::kw_enum: - + // type-qualifier case tok::kw_const: case tok::kw_volatile: @@ -1911,15 +1911,15 @@ bool Parser::isDeclarationSpecifier() { // GNU typeof support. case tok::kw_typeof: - + // GNU attributes. case tok::kw___attribute: return true; - + // GNU ObjC bizarre protocol extension: with implicit 'id'. case tok::less: return getLang().ObjC1; - + case tok::kw___declspec: case tok::kw___cdecl: case tok::kw___stdcall: @@ -2035,7 +2035,7 @@ void Parser::ParseDeclaratorInternal(Declarator &D, Tok.is(tok::annot_cxxscope))) { CXXScopeSpec SS; if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) { - if(Tok.isNot(tok::star)) { + if (Tok.isNot(tok::star)) { // The scope spec really belongs to the direct-declarator. D.getCXXScopeSpec() = SS; if (DirectDeclParser) @@ -2093,7 +2093,7 @@ void Parser::ParseDeclaratorInternal(Declarator &D, SourceLocation()); else // Remember that we parsed a Block type, and remember the type-quals. - D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), + D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc, DS.TakeAttributes()), SourceLocation()); } else { @@ -2178,10 +2178,10 @@ void Parser::ParseDeclaratorInternal(Declarator &D, /// qualified-id [TODO] /// /// unqualified-id: [C++ 5.1] -/// identifier +/// identifier /// operator-function-id /// conversion-function-id [TODO] -/// '~' class-name +/// '~' class-name /// template-id /// void Parser::ParseDirectDeclarator(Declarator &D) { @@ -2191,7 +2191,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { if (D.mayHaveIdentifier()) { // ParseDeclaratorInternal might already have parsed the scope. bool afterCXXScope = D.getCXXScopeSpec().isSet() || - ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0, + ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0, true); if (afterCXXScope) { // Change the declaration context for name lookup, until this function @@ -2203,7 +2203,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { assert(Tok.getIdentifierInfo() && "Not an identifier?"); // If this identifier is the name of the current class, it's a - // constructor name. + // constructor name. if (!D.getDeclSpec().hasTypeSpecifier() && Actions.isCurrentClassName(*Tok.getIdentifierInfo(),CurScope)) { CXXScopeSpec *SS = afterCXXScope? &D.getCXXScopeSpec() : 0; @@ -2216,7 +2216,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { ConsumeToken(); goto PastIdentifier; } else if (Tok.is(tok::annot_template_id)) { - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); // FIXME: Could this template-id name a constructor? @@ -2305,11 +2305,11 @@ void Parser::ParseDirectDeclarator(Declarator &D) { D.SetIdentifier(0, Tok.getLocation()); D.setInvalidType(true); } - + PastIdentifier: assert(D.isPastIdentifier() && "Haven't past the location of the identifier yet?"); - + while (1) { if (Tok.is(tok::l_paren)) { // The paren may be part of a C++ direct initializer, eg. "int x(1);". @@ -2333,7 +2333,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is /// only called before the identifier, so these are most likely just grouping -/// parens for precedence. If we find that these are actually function +/// parens for precedence. If we find that these are actually function /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. /// /// direct-declarator: @@ -2347,7 +2347,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { void Parser::ParseParenDeclarator(Declarator &D) { SourceLocation StartLoc = ConsumeParen(); assert(!D.isPastIdentifier() && "Should be called before passing identifier"); - + // Eat any attributes before we look at whether this is a grouping or function // declarator paren. If this is a grouping paren, the attribute applies to // the type being built up, for example: @@ -2362,7 +2362,7 @@ void Parser::ParseParenDeclarator(Declarator &D) { bool RequiresArg = false; if (Tok.is(tok::kw___attribute)) { AttrList = ParseAttributes(); - + // We require that the argument list (if this is a non-grouping paren) be // present even if the attribute list was empty. RequiresArg = true; @@ -2373,13 +2373,13 @@ void Parser::ParseParenDeclarator(Declarator &D) { Tok.is(tok::kw___ptr64)) { AttrList = ParseMicrosoftTypeAttributes(AttrList); } - + // If we haven't past the identifier yet (or where the identifier would be // stored, if this is an abstract declarator), then this is probably just // grouping parens. However, if this could be an abstract-declarator, then // this could also be the start of function arguments (consider 'void()'). bool isGrouping; - + if (!D.mayOmitIdentifier()) { // If this can't be an abstract-declarator, this *must* be a grouping // paren, because we haven't seen the identifier yet. @@ -2394,7 +2394,7 @@ void Parser::ParseParenDeclarator(Declarator &D) { // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. isGrouping = true; } - + // If this is a grouping paren, handle: // direct-declarator: '(' declarator ')' // direct-declarator: '(' attributes declarator ')' @@ -2412,7 +2412,7 @@ void Parser::ParseParenDeclarator(Declarator &D) { D.SetRangeEnd(Loc); return; } - + // Okay, if this wasn't a grouping paren, it must be the start of a function // argument list. Recognize that this declarator will never have an // identifier (and remember where it would have been), then call into @@ -2458,7 +2458,7 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, bool RequiresArg) { // lparen is already consumed! assert(D.isPastIdentifier() && "Should not call before identifier!"); - + // This parameter list may be empty. if (Tok.is(tok::r_paren)) { if (RequiresArg) { @@ -2524,9 +2524,9 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, return ParseFunctionDeclaratorIdentifierList(LParenLoc, D); } } - + // Finally, a normal, non-empty parameter type list. - + // Build up an array of information about the parsed arguments. llvm::SmallVector ParamInfo; @@ -2534,7 +2534,7 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, // function prototype scope, including parameter declarators. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope); - + bool IsVariadic = false; SourceLocation EllipsisLoc; while (1) { @@ -2543,9 +2543,9 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, EllipsisLoc = ConsumeToken(); // Consume the ellipsis. break; } - + SourceLocation DSStart = Tok.getLocation(); - + // Parse the declaration-specifiers. DeclSpec DS; @@ -2555,7 +2555,7 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, AttrList = 0; // Only apply the attributes to the first parameter. } ParseDeclarationSpecifiers(DS); - + // Parse the declarator. This is "PrototypeContext", because we must // accept either 'declarator' or 'abstract-declarator' here. Declarator ParmDecl(DS, Declarator::PrototypeContext); @@ -2567,10 +2567,10 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, AttributeList *AttrList = ParseAttributes(&Loc); ParmDecl.AddAttributes(AttrList, Loc); } - + // Remember this parsed parameter in ParamInfo. IdentifierInfo *ParmII = ParmDecl.getIdentifier(); - + // DefArgToks is used when the parsing of default arguments needs // to be delayed. CachedTokens *DefArgToks = 0; @@ -2584,7 +2584,7 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, } else { // Otherwise, we have something. Add it and let semantic analysis try // to grok it and add the result to the ParamInfo we are building. - + // Inform the actions module about the parameter declarator, so it gets // added to the current scope. DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl); @@ -2605,18 +2605,18 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, // FIXME: Can we use a smart pointer for Toks? DefArgToks = new CachedTokens; - if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, + if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, tok::semi, false)) { delete DefArgToks; DefArgToks = 0; Actions.ActOnParamDefaultArgumentError(Param); } else - Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, + Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, (*DefArgToks)[1].getLocation()); } else { // Consume the '='. ConsumeToken(); - + OwningExprResult DefArgResult(ParseAssignmentExpression()); if (DefArgResult.isInvalid()) { Actions.ActOnParamDefaultArgumentError(Param); @@ -2628,22 +2628,22 @@ void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, } } } - - ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, - ParmDecl.getIdentifierLoc(), Param, + + ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, + ParmDecl.getIdentifierLoc(), Param, DefArgToks)); } // If the next token is a comma, consume it and keep reading arguments. if (Tok.isNot(tok::comma)) break; - + // Consume the comma. ConsumeToken(); } - + // Leave prototype scope. PrototypeScope.Exit(); - + // If we have the closing ')', eat it. SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); SourceLocation EndLoc = RParenLoc; @@ -2698,7 +2698,7 @@ void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, // Build up an array of information about the parsed arguments. llvm::SmallVector ParamInfo; llvm::SmallSet ParamsSoFar; - + // If there was no identifier specified for the declarator, either we are in // an abstract-declarator, or we are in a parameter declarator which was found // to be abstract. In abstract-declarators, identifier lists are not valid: @@ -2712,13 +2712,13 @@ void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(), Tok.getLocation(), DeclPtrTy())); - + ConsumeToken(); // eat the first identifier. - + while (Tok.is(tok::comma)) { // Eat the comma. ConsumeToken(); - + // If this isn't an identifier, report the error and skip until ')'. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); @@ -2731,7 +2731,7 @@ void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, // Reject 'typedef int y; int test(x, y)', but continue parsing. if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope)) Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; - + // Verify that the argument identifier has not already been mentioned. if (!ParamsSoFar.insert(ParmII)) { Diag(Tok, diag::err_param_redefinition) << ParmII; @@ -2741,7 +2741,7 @@ void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, Tok.getLocation(), DeclPtrTy())); } - + // Eat the identifier. ConsumeToken(); } @@ -2769,7 +2769,7 @@ void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' void Parser::ParseBracketDeclarator(Declarator &D) { SourceLocation StartLoc = ConsumeBracket(); - + // C array syntax has many features, but by-far the most common is [] and [4]. // This code does a fast path to handle some of the most obvious cases. if (Tok.getKind() == tok::r_square) { @@ -2791,33 +2791,33 @@ void Parser::ParseBracketDeclarator(Declarator &D) { // If there was an error parsing the assignment-expression, recover. if (ExprRes.isInvalid()) ExprRes.release(); // Deallocate expr, just use []. - + // Remember that we parsed a array type, and remember its features. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(), StartLoc, EndLoc), EndLoc); return; } - + // If valid, this location is the position where we read the 'static' keyword. SourceLocation StaticLoc; if (Tok.is(tok::kw_static)) StaticLoc = ConsumeToken(); - + // If there is a type-qualifier-list, read it now. // Type qualifiers in an array subscript are a C99 feature. DeclSpec DS; ParseTypeQualifierListOpt(DS, false /*no attributes*/); - + // If we haven't already read 'static', check to see if there is one after the // type-qualifier-list. if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) StaticLoc = ConsumeToken(); - + // Handle "direct-declarator [ type-qual-list[opt] * ]". bool isStar = false; OwningExprResult NumElements(Actions); - + // Handle the case where we have '[*]' as the array size. However, a leading // star could be the start of an expression, for example 'X[*p + 4]'. Verify // the the token after the star is a ']'. Since stars in arrays are @@ -2835,7 +2835,7 @@ void Parser::ParseBracketDeclarator(Declarator &D) { // of assignment-expr. The only difference is that assignment-expr allows // things like '=' and '*='. Sema rejects these in C89 mode because they // are not i-c-e's, so we don't need to distinguish between the two here. - + // Parse the constant-expression or assignment-expression now (depending // on dialect). if (getLang().CPlusPlus) @@ -2843,7 +2843,7 @@ void Parser::ParseBracketDeclarator(Declarator &D) { else NumElements = ParseAssignmentExpression(); } - + // If there was an error parsing the assignment-expression, recover. if (NumElements.isInvalid()) { D.setInvalidType(true); @@ -2885,7 +2885,7 @@ void Parser::ParseTypeofSpecifier(DeclSpec &DS) { DS.SetRangeEnd(Tok.getLocation()); else DS.SetRangeEnd(CastRange.getEnd()); - + if (isCastExpr) { if (!CastTy) { DS.SetTypeSpecError(); diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp index 55c7c85fa685012a486ed75d649004d4f6ba163a..fc3e6ae17f0ec2afeb1764d8f04d380b58dd8035 100644 --- a/clang/lib/Parse/ParseDeclCXX.cpp +++ b/clang/lib/Parse/ParseDeclCXX.cpp @@ -38,7 +38,7 @@ using namespace clang; /// /// extension-namespace-definition: /// 'namespace' original-namespace-name '{' namespace-body '}' -/// +/// /// namespace-alias-definition: [C++ 7.3.2: namespace.alias] /// 'namespace' identifier '=' qualified-namespace-specifier ';' /// @@ -46,17 +46,17 @@ Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context, SourceLocation &DeclEnd) { assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. - + SourceLocation IdentLoc; IdentifierInfo *Ident = 0; Token attrTok; - + if (Tok.is(tok::identifier)) { Ident = Tok.getIdentifierInfo(); IdentLoc = ConsumeToken(); // eat the identifier. } - + // Read label attributes, if present. Action::AttrTy *AttrList = 0; if (Tok.is(tok::kw___attribute)) { @@ -65,20 +65,20 @@ Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context, // FIXME: save these somewhere. AttrList = ParseAttributes(); } - + if (Tok.is(tok::equal)) { if (AttrList) Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); } - + if (Tok.isNot(tok::l_brace)) { - Diag(Tok, Ident ? diag::err_expected_lbrace : + Diag(Tok, Ident ? diag::err_expected_lbrace : diag::err_expected_ident_lbrace); return DeclPtrTy(); } - + SourceLocation LBrace = ConsumeBrace(); // Enter a scope for the namespace. @@ -90,10 +90,10 @@ Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context, PrettyStackTraceActionsDecl CrashInfo(NamespcDecl, NamespaceLoc, Actions, PP.getSourceManager(), "parsing namespace"); - + while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) ParseExternalDeclaration(); - + // Leave the namespace scope. NamespaceScope.Exit(); @@ -108,13 +108,13 @@ Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context, /// alias definition. /// Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, - SourceLocation AliasLoc, + SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd) { assert(Tok.is(tok::equal) && "Not equal token"); - + ConsumeToken(); // eat the '='. - + CXXScopeSpec SS; // Parse (optional) nested-name-specifier. ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false); @@ -129,13 +129,13 @@ Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, // Parse identifier. IdentifierInfo *Ident = Tok.getIdentifierInfo(); SourceLocation IdentLoc = ConsumeToken(); - + // Eat the ';'. DeclEnd = Tok.getLocation(); ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, "", tok::semi); - - return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias, + + return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias, SS, IdentLoc, Ident); } @@ -157,18 +157,18 @@ Parser::DeclPtrTy Parser::ParseLinkage(unsigned Context) { SourceLocation Loc = ConsumeStringToken(); ParseScope LinkageScope(this, Scope::DeclScope); - DeclPtrTy LinkageSpec - = Actions.ActOnStartLinkageSpecification(CurScope, + DeclPtrTy LinkageSpec + = Actions.ActOnStartLinkageSpecification(CurScope, /*FIXME: */SourceLocation(), Loc, LangBufPtr, StrSize, - Tok.is(tok::l_brace)? Tok.getLocation() + Tok.is(tok::l_brace)? Tok.getLocation() : SourceLocation()); if (Tok.isNot(tok::l_brace)) { ParseDeclarationOrFunctionDefinition(); - return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, + return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, SourceLocation()); - } + } SourceLocation LBrace = ConsumeBrace(); while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { @@ -230,15 +230,15 @@ Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context, // FIXME: Are there cases, when we would like to call ActOnUsingDirective? return DeclPtrTy(); } - + // Parse identifier. NamespcName = Tok.getIdentifierInfo(); IdentLoc = ConsumeToken(); - + // Parse (optional) attributes (most likely GNU strong-using extension). if (Tok.is(tok::kw___attribute)) AttrList = ParseAttributes(); - + // Eat ';'. DeclEnd = Tok.getLocation(); ExpectAndConsume(tok::semi, @@ -284,16 +284,16 @@ Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context, } if (Tok.is(tok::annot_template_id)) { // C++0x N2914 [namespace.udecl]p5: - // A using-declaration shall not name a template-id. + // A using-declaration shall not name a template-id. Diag(Tok, diag::err_using_decl_can_not_refer_to_template_spec); SkipUntil(tok::semi); return DeclPtrTy(); } - + IdentifierInfo *TargetName = 0; OverloadedOperatorKind Op = OO_None; SourceLocation IdentLoc; - + if (Tok.is(tok::kw_operator)) { IdentLoc = Tok.getLocation(); @@ -315,11 +315,11 @@ Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context, SkipUntil(tok::semi); return DeclPtrTy(); } - + // Parse (optional) attributes (most likely GNU strong-using extension). if (Tok.is(tok::kw___attribute)) AttrList = ParseAttributes(); - + // Eat ';'. DeclEnd = Tok.getLocation(); ExpectAndConsume(tok::semi, diag::err_expected_semi_after, @@ -338,12 +338,12 @@ Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context, Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration"); SourceLocation StaticAssertLoc = ConsumeToken(); - + if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen); return DeclPtrTy(); } - + SourceLocation LParenLoc = ConsumeParen(); OwningExprResult AssertExpr(ParseConstantExpression()); @@ -351,7 +351,7 @@ Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ SkipUntil(tok::semi); return DeclPtrTy(); } - + if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) return DeclPtrTy(); @@ -360,17 +360,17 @@ Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ SkipUntil(tok::semi); return DeclPtrTy(); } - + OwningExprResult AssertMessage(ParseStringLiteralExpression()); - if (AssertMessage.isInvalid()) + if (AssertMessage.isInvalid()) return DeclPtrTy(); MatchRHSPunctuation(tok::r_paren, LParenLoc); - + DeclEnd = Tok.getLocation(); ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert); - return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr), + return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr), move(AssertMessage)); } @@ -383,15 +383,15 @@ void Parser::ParseDecltypeSpecifier(DeclSpec &DS) { SourceLocation StartLoc = ConsumeToken(); SourceLocation LParenLoc = Tok.getLocation(); - - if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, + + if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "decltype")) { SkipUntil(tok::r_paren); return; } - + // Parse the expression - + // C++0x [dcl.type.simple]p4: // The operand of the decltype specifier is an unevaluated operand. EnterExpressionEvaluationContext Unevaluated(Actions, @@ -401,21 +401,21 @@ void Parser::ParseDecltypeSpecifier(DeclSpec &DS) { SkipUntil(tok::r_paren); return; } - + // Match the ')' SourceLocation RParenLoc; if (Tok.is(tok::r_paren)) RParenLoc = ConsumeParen(); else MatchRHSPunctuation(tok::r_paren, LParenLoc); - + if (RParenLoc.isInvalid()) return; const char *PrevSpec = 0; unsigned DiagID; // Check for duplicate type specifiers (e.g. "int decltype(a)"). - if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, + if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, DiagID, Result.release())) Diag(StartLoc, DiagID) << PrevSpec; } @@ -429,13 +429,13 @@ void Parser::ParseDecltypeSpecifier(DeclSpec &DS) { /// class-name: [C++ 9.1] /// identifier /// simple-template-id -/// +/// Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, const CXXScopeSpec *SS, bool DestrExpected) { // Check whether we have a template-id that names a type. if (Tok.is(tok::annot_template_id)) { - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); if (TemplateId->Kind == TNK_Type_template) { AnnotateTemplateIdTokenAsType(SS); @@ -459,11 +459,11 @@ Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, } // We have an identifier; check whether it is actually a type. - TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(), + TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), CurScope, SS, true); if (!Type) { - Diag(Tok, DestrExpected ? diag::err_destructor_class_name + Diag(Tok, DestrExpected ? diag::err_destructor_class_name : diag::err_expected_class_name); return true; } @@ -487,9 +487,9 @@ Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, /// class-key nested-name-specifier[opt] simple-template-id /// base-clause[opt] /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] -/// [GNU] class-key attributes[opt] nested-name-specifier +/// [GNU] class-key attributes[opt] nested-name-specifier /// identifier base-clause[opt] -/// [GNU] class-key attributes[opt] nested-name-specifier[opt] +/// [GNU] class-key attributes[opt] nested-name-specifier[opt] /// simple-template-id base-clause[opt] /// class-key: /// 'class' @@ -497,9 +497,9 @@ Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, /// 'union' /// /// elaborated-type-specifier: [C++ dcl.type.elab] -/// class-key ::[opt] nested-name-specifier[opt] identifier -/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] -/// simple-template-id +/// class-key ::[opt] nested-name-specifier[opt] identifier +/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] +/// simple-template-id /// /// Note that the C++ class-specifier and elaborated-type-specifier, /// together, subsume the C99 struct-or-union-specifier: @@ -535,11 +535,11 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, // If declspecs exist after tag, parse them. if (Tok.is(tok::kw___declspec)) Attr = ParseMicrosoftDeclSpec(Attr); - + if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) { // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the - // token sequence "struct __is_pod", make __is_pod into a normal + // token sequence "struct __is_pod", make __is_pod into a normal // identifier rather than a keyword, to allow libstdc++ 4.2 to work // properly. Tok.getIdentifierInfo()->setTokenID(tok::identifier); @@ -549,16 +549,16 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) { // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the - // token sequence "struct __is_empty", make __is_empty into a normal + // token sequence "struct __is_empty", make __is_empty into a normal // identifier rather than a keyword, to allow libstdc++ 4.2 to work // properly. Tok.getIdentifierInfo()->setTokenID(tok::identifier); Tok.setKind(tok::identifier); } - + // Parse the (optional) nested-name-specifier. CXXScopeSpec SS; - if (getLang().CPlusPlus && + if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) Diag(Tok, diag::err_expected_ident); @@ -584,7 +584,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) << Name << static_cast(TemplateId->Kind) << Range; - + DS.SetTypeSpecError(); SkipUntil(tok::semi, false, true); TemplateId->Destroy(); @@ -629,7 +629,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, if (TemplateId) { // Explicit specialization, class template partial specialization, // or explicit instantiation. - ASTTemplateArgsPtr TemplateArgsPtr(Actions, + ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateId->getTemplateArgs(), TemplateId->getTemplateArgIsType(), TemplateId->NumArgs); @@ -637,18 +637,18 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, TUK == Action::TUK_Declaration) { // This is an explicit instantiation of a class template. TagOrTempResult - = Actions.ActOnExplicitInstantiation(CurScope, + = Actions.ActOnExplicitInstantiation(CurScope, TemplateInfo.ExternLoc, - TemplateInfo.TemplateLoc, + TemplateInfo.TemplateLoc, TagType, - StartLoc, + StartLoc, SS, - TemplateTy::make(TemplateId->Template), - TemplateId->TemplateNameLoc, - TemplateId->LAngleLoc, + TemplateTy::make(TemplateId->Template), + TemplateId->TemplateNameLoc, + TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->getTemplateArgLocations(), - TemplateId->RAngleLoc, + TemplateId->RAngleLoc, Attr); } else if (TUK == Action::TUK_Reference || TUK == Action::TUK_Friend) { Action::TypeResult Type @@ -675,7 +675,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, Diag(StartLoc, DiagID) << PrevSpec; return; - + } else { // This is an explicit specialization or a class template // partial specialization. @@ -692,9 +692,9 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, // the '<>' after 'template'. assert(TUK == Action::TUK_Definition && "Expected a definition here"); - SourceLocation LAngleLoc + SourceLocation LAngleLoc = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); - Diag(TemplateId->TemplateNameLoc, + Diag(TemplateId->TemplateNameLoc, diag::err_explicit_instantiation_with_definition) << SourceRange(TemplateInfo.TemplateLoc) << CodeModificationHint::CreateInsertion(LAngleLoc, "<>"); @@ -703,10 +703,10 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, // "template<>", so that we treat this construct as a class // template specialization. FakedParamLists.push_back( - Actions.ActOnTemplateParameterList(0, SourceLocation(), + Actions.ActOnTemplateParameterList(0, SourceLocation(), TemplateInfo.TemplateLoc, - LAngleLoc, - 0, 0, + LAngleLoc, + 0, 0, LAngleLoc)); TemplateParams = &FakedParamLists; } @@ -715,14 +715,14 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, TagOrTempResult = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK, StartLoc, SS, - TemplateTy::make(TemplateId->Template), - TemplateId->TemplateNameLoc, - TemplateId->LAngleLoc, + TemplateTy::make(TemplateId->Template), + TemplateId->TemplateNameLoc, + TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->getTemplateArgLocations(), - TemplateId->RAngleLoc, + TemplateId->RAngleLoc, Attr, - Action::MultiTemplateParamsArg(Actions, + Action::MultiTemplateParamsArg(Actions, TemplateParams? &(*TemplateParams)[0] : 0, TemplateParams? TemplateParams->size() : 0)); } @@ -735,10 +735,10 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, // template struct Outer::Inner; // TagOrTempResult - = Actions.ActOnExplicitInstantiation(CurScope, + = Actions.ActOnExplicitInstantiation(CurScope, TemplateInfo.ExternLoc, - TemplateInfo.TemplateLoc, - TagType, StartLoc, SS, Name, + TemplateInfo.TemplateLoc, + TagType, StartLoc, SS, Name, NameLoc, Attr); } else { if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && @@ -747,9 +747,9 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, } // Declaration or definition of a class type - TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS, + TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS, Name, NameLoc, Attr, AS, - Action::MultiTemplateParamsArg(Actions, + Action::MultiTemplateParamsArg(Actions, TemplateParams? &(*TemplateParams)[0] : 0, TemplateParams? TemplateParams->size() : 0), Owned); @@ -775,7 +775,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, DS.SetTypeSpecError(); return; } - + const char *PrevSpec = 0; unsigned DiagID; if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, DiagID, @@ -783,7 +783,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, Diag(StartLoc, DiagID) << PrevSpec; } -/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. +/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. /// /// base-clause : [C++ class.derived] /// ':' base-specifier-list @@ -812,7 +812,7 @@ void Parser::ParseBaseClause(DeclPtrTy ClassDecl) { // If the next token is a comma, consume it and keep reading // base-specifiers. if (Tok.isNot(tok::comma)) break; - + // Consume the comma. ConsumeToken(); } @@ -846,7 +846,7 @@ Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) { AccessSpecifier Access = getAccessSpecifierIfPresent(); if (Access) ConsumeToken(); - + // Parse the 'virtual' keyword (again!), in case it came after the // access specifier. if (Tok.is(tok::kw_virtual)) { @@ -872,10 +872,10 @@ Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) { TypeResult BaseType = ParseClassName(EndLocation, &SS); if (BaseType.isInvalid()) return true; - - // Find the complete source range for the base-specifier. + + // Find the complete source range for the base-specifier. SourceRange Range(StartLoc, EndLocation); - + // Notify semantic analysis that we have parsed a complete // base-specifier. return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, @@ -889,8 +889,7 @@ Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) { /// 'private' /// 'protected' /// 'public' -AccessSpecifier Parser::getAccessSpecifierIfPresent() const -{ +AccessSpecifier Parser::getAccessSpecifierIfPresent() const { switch (Tok.getKind()) { default: return AS_none; case tok::kw_private: return AS_private; @@ -904,7 +903,7 @@ void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo, // We just declared a member function. If this member function // has any default arguments, we'll need to parse them later. LateParsedMethodDeclaration *LateMethod = 0; - DeclaratorChunk::FunctionTypeInfo &FTI + DeclaratorChunk::FunctionTypeInfo &FTI = DeclaratorInfo.getTypeObject(0).Fun; for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { @@ -968,12 +967,12 @@ void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, ParseStaticAssertDeclaration(DeclEnd); return; } - + if (Tok.is(tok::kw_template)) { - assert(!TemplateInfo.TemplateParams && + assert(!TemplateInfo.TemplateParams && "Nested template improperly parsed?"); SourceLocation DeclEnd; - ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, + ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, AS); return; } @@ -988,7 +987,7 @@ void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, if (Tok.is(tok::kw_using)) { // FIXME: Check for template aliases - + // Eat 'using'. SourceLocation UsingLoc = ConsumeToken(); @@ -1084,7 +1083,7 @@ void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, if (BitfieldSize.isInvalid()) SkipUntil(tok::comma, true, true); } - + // pure-specifier: // '= 0' // @@ -1138,7 +1137,7 @@ void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, DeclsInGroup.push_back(ThisDecl); if (DeclaratorInfo.isFunctionDeclarator() && - DeclaratorInfo.getDeclSpec().getStorageClassSpec() + DeclaratorInfo.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) { HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl); } @@ -1147,16 +1146,16 @@ void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, // or an error, bail out. if (Tok.isNot(tok::comma)) break; - + // Consume the comma. ConsumeToken(); - + // Parse the next declarator. DeclaratorInfo.clear(); BitfieldSize = 0; Init = 0; Deleted = false; - + // Attributes are only allowed on the second declarator. if (Tok.is(tok::kw___attribute)) { SourceLocation Loc; @@ -1198,11 +1197,11 @@ void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, PP.getSourceManager(), "parsing struct/union/class body"); - + SourceLocation LBraceLoc = ConsumeBrace(); // Determine whether this is a top-level (non-nested) class. - bool TopLevelClass = ClassStack.empty() || + bool TopLevelClass = ClassStack.empty() || CurScope->isInCXXInlineMethodScope(); // Enter a scope for the class. @@ -1230,7 +1229,7 @@ void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, // While we still have something to read, read the member-declarations. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { // Each iteration of this loop reads one member-declaration. - + // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { Diag(Tok, diag::ext_extra_struct_semi); @@ -1248,13 +1247,13 @@ void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, } // FIXME: Make sure we don't have a template here. - + // Parse all the comma separated declarators. ParseCXXClassMemberDeclaration(CurAS); } - + SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); - + AttributeList *AttrList = 0; // If attributes exist after class contents, parse them. if (Tok.is(tok::kw___attribute)) @@ -1300,19 +1299,19 @@ void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, /// }; /// @endcode /// -/// [C++] ctor-initializer: -/// ':' mem-initializer-list +/// [C++] ctor-initializer: +/// ':' mem-initializer-list /// -/// [C++] mem-initializer-list: -/// mem-initializer -/// mem-initializer , mem-initializer-list +/// [C++] mem-initializer-list: +/// mem-initializer +/// mem-initializer , mem-initializer-list void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) { assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); SourceLocation ColonLoc = ConsumeToken(); - + llvm::SmallVector MemInitializers; - + do { MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); if (!MemInit.isInvalid()) @@ -1330,7 +1329,7 @@ void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) { } } while (true); - Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, + Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers.data(), MemInitializers.size()); } @@ -1341,7 +1340,7 @@ void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) { /// /// [C++] mem-initializer: /// mem-initializer-id '(' expression-list[opt] ')' -/// +/// /// [C++] mem-initializer-id: /// '::'[opt] nested-name-specifier[opt] class-name /// identifier @@ -1364,7 +1363,7 @@ Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) { Diag(Tok, diag::err_expected_member_or_base_name); return true; } - + // Get the identifier. This may be a member name or a class name, // but we'll let the semantic analysis determine which it is. IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; @@ -1400,7 +1399,7 @@ Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) { /// exception-specification: /// 'throw' '(' type-id-list [opt] ')' /// [MS] 'throw' '(' '...' ')' -/// +/// /// type-id-list: /// type-id /// type-id-list ',' type-id @@ -1412,9 +1411,9 @@ bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, &Ranges, bool &hasAnyExceptionSpec) { assert(Tok.is(tok::kw_throw) && "expected throw"); - + SourceLocation ThrowLoc = ConsumeToken(); - + if (!Tok.is(tok::l_paren)) { return Diag(Tok, diag::err_expected_lparen_after) << "throw"; } @@ -1453,7 +1452,7 @@ bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, /// so push that class onto our stack of classes that is currently /// being parsed. void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) { - assert((TopLevelClass || !ClassStack.empty()) && + assert((TopLevelClass || !ClassStack.empty()) && "Nested class without outer class"); ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass)); } @@ -1477,7 +1476,7 @@ void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { /// false otherwise. void Parser::PopParsingClass() { assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); - + ParsingClass *Victim = ClassStack.top(); ClassStack.pop(); if (Victim->TopLevelClass) { @@ -1485,7 +1484,7 @@ void Parser::PopParsingClass() { // recursively: we don't need to keep any of this information. DeallocateParsedClasses(Victim); return; - } + } assert(!ClassStack.empty() && "Missing top-level class?"); if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() && diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp index 39496626febc2b7089ae9fd31ee621a70b4219ec..60c81929658b25ea37c28669d36f86de5db6924f 100644 --- a/clang/lib/Parse/ParseExpr.cpp +++ b/clang/lib/Parse/ParseExpr.cpp @@ -55,7 +55,7 @@ namespace prec { /// getBinOpPrecedence - Return the precedence of the specified binary operator /// token. This returns: /// -static prec::Level getBinOpPrecedence(tok::TokenKind Kind, +static prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus0x) { switch (Kind) { @@ -67,7 +67,7 @@ static prec::Level getBinOpPrecedence(tok::TokenKind Kind, if (GreaterThanIsOperator) return prec::Relational; return prec::Unknown; - + case tok::greatergreater: // C++0x [temp.names]p3: // @@ -206,7 +206,7 @@ Parser::OwningExprResult Parser::ParseExpression() { return ParseRHSOfBinaryExpression(move(LHS), prec::Comma); } -/// This routine is called when the '@' is seen and consumed. +/// This routine is called when the '@' is seen and consumed. /// Current token is an Identifier and is not a 'try'. This /// routine is necessary to disambiguate @try-statement from, /// for example, @encode-expression. @@ -277,11 +277,11 @@ Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, Parser::OwningExprResult Parser::ParseConstantExpression() { // C++ [basic.def.odr]p2: - // An expression is potentially evaluated unless it appears where an + // An expression is potentially evaluated unless it appears where an // integral constant expression is required (see 5.19) [...]. EnterExpressionEvaluationContext Unevaluated(Actions, Action::Unevaluated); - + OwningExprResult LHS(ParseCastExpression(false)); if (LHS.isInvalid()) return move(LHS); @@ -292,7 +292,7 @@ Parser::OwningExprResult Parser::ParseConstantExpression() { /// LHS and has a precedence of at least MinPrec. Parser::OwningExprResult Parser::ParseRHSOfBinaryExpression(OwningExprResult LHS, unsigned MinPrec) { - unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind(), + unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, getLang().CPlusPlus0x); SourceLocation ColonLoc; @@ -465,10 +465,10 @@ Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, /// assign-expr ')' /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' /// [GNU] '__null' -/// [OBJC] '[' objc-message-expr ']' +/// [OBJC] '[' objc-message-expr ']' /// [OBJC] '@selector' '(' objc-selector-arg ')' -/// [OBJC] '@protocol' '(' identifier ')' -/// [OBJC] '@encode' '(' type-name ')' +/// [OBJC] '@protocol' '(' identifier ')' +/// [OBJC] '@encode' '(' type-name ')' /// [OBJC] objc-string-literal /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] /// [C++] typename-specifier '(' expression-list[opt] ')' [TODO] @@ -537,7 +537,7 @@ Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, OwningExprResult Res(Actions); tok::TokenKind SavedKind = Tok.getKind(); NotCastExpr = false; - + // This handles all of cast-expression, unary-expression, postfix-expression, // and primary-expression. We handle them together like this for efficiency // and to simplify handling of an expression starting with a '(' token: which @@ -560,7 +560,7 @@ Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, parseParenAsExprList, CastTy, RParenLoc); if (Res.isInvalid()) return move(Res); - + switch (ParenExprType) { case SimpleExpr: break; // Nothing else to do. case CompoundStmt: break; // Nothing else to do. @@ -608,23 +608,23 @@ Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, } // Support 'Class.property' notation. - // We don't use isTokObjCMessageIdentifierReceiver(), since it allows + // We don't use isTokObjCMessageIdentifierReceiver(), since it allows // 'super' (which is inappropriate here). - if (getLang().ObjC1 && - Actions.getTypeName(*Tok.getIdentifierInfo(), + if (getLang().ObjC1 && + Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), CurScope) && NextToken().is(tok::period)) { IdentifierInfo &ReceiverName = *Tok.getIdentifierInfo(); SourceLocation IdentLoc = ConsumeToken(); SourceLocation DotLoc = ConsumeToken(); - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); return ExprError(); } IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); SourceLocation PropertyLoc = ConsumeToken(); - + Res = Actions.ActOnClassPropertyRefExpr(ReceiverName, PropertyName, IdentLoc, PropertyLoc); // These can be followed by postfix-expr pieces. @@ -799,7 +799,7 @@ Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, return ParseCXXNewExpression(true, CCLoc); if (Tok.is(tok::kw_delete)) return ParseCXXDeleteExpression(true, CCLoc); - + // This is not a type name or scope specifier, it is an invalid expression. Diag(CCLoc, diag::err_expected_expression); return ExprError(); @@ -834,7 +834,7 @@ Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, // These can be followed by postfix-expr pieces. if (getLang().ObjC1) return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); - // FALL THROUGH. + // FALL THROUGH. default: NotCastExpr = true; return ExprError(); @@ -906,7 +906,7 @@ Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { MatchRHSPunctuation(tok::r_paren, Loc); return ExprError(); } - + if (!LHS.isInvalid()) { assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); @@ -914,7 +914,7 @@ Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { move_arg(ArgExprs), CommaLocs.data(), Tok.getLocation()); } - + ConsumeParen(); break; } @@ -944,19 +944,19 @@ Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { ConsumeToken(); } else if (getLang().CPlusPlus && Tok.is(tok::tilde)) { // We have a C++ pseudo-destructor or a destructor call, e.g., t.~T() - + // Consume the tilde. ConsumeToken(); - + if (!Tok.is(tok::identifier)) { Diag(Tok, diag::err_expected_ident); return ExprError(); } - + if (!LHS.isInvalid()) - LHS = Actions.ActOnDestructorReferenceExpr(CurScope, move(LHS), + LHS = Actions.ActOnDestructorReferenceExpr(CurScope, move(LHS), OpLoc, OpKind, - Tok.getLocation(), + Tok.getLocation(), Tok.getIdentifierInfo(), SS, NextToken().is(tok::l_paren)); @@ -987,14 +987,14 @@ Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { } else if (getLang().CPlusPlus && Tok.is(tok::annot_template_id)) { // We have a reference to a member template along with explicitly- // specified template arguments, e.g., t.f. - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); if (!LHS.isInvalid()) { - ASTTemplateArgsPtr TemplateArgsPtr(Actions, + ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateId->getTemplateArgs(), TemplateId->getTemplateArgIsType(), TemplateId->NumArgs); - + LHS = Actions.ActOnMemberTemplateIdReferenceExpr(CurScope, move(LHS), OpLoc, OpKind, SS, TemplateTy::make(TemplateId->Template), @@ -1014,7 +1014,7 @@ Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { case tok::plusplus: // postfix-expression: postfix-expression '++' case tok::minusminus: // postfix-expression: postfix-expression '--' if (!LHS.isInvalid()) { - LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(), + LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(), Tok.getKind(), move(LHS)); } ConsumeToken(); @@ -1045,13 +1045,13 @@ Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, bool &isCastExpr, TypeTy *&CastTy, SourceRange &CastRange) { - - assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || + + assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) && "Not a typeof/sizeof/alignof expression!"); OwningExprResult Operand(Actions); - + // If the operand doesn't start with an '(', it must be an expression. if (Tok.isNot(tok::l_paren)) { isCastExpr = false; @@ -1059,9 +1059,9 @@ Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); return ExprError(); } - + // C++0x [expr.sizeof]p1: - // [...] The operand is either an expression, which is an unevaluated + // [...] The operand is either an expression, which is an unevaluated // operand (Clause 5) [...] // // The GNU typeof and alignof extensions also behave as unevaluated @@ -1076,9 +1076,9 @@ Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, // expression. ParenParseOption ExprType = CastExpr; SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; - + // C++0x [expr.sizeof]p1: - // [...] The operand is either an expression, which is an unevaluated + // [...] The operand is either an expression, which is an unevaluated // operand (Clause 5) [...] // // The GNU typeof and alignof extensions also behave as unevaluated @@ -1096,7 +1096,7 @@ Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, return ExprEmpty(); } - // If this is a parenthesized expression, it is the start of a + // If this is a parenthesized expression, it is the start of a // unary-expression, but doesn't include any postfix pieces. Parse these // now if present. Operand = ParsePostfixExpressionSuffix(move(Operand)); @@ -1121,7 +1121,7 @@ Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() { "Not a sizeof/alignof expression!"); Token OpTok = Tok; ConsumeToken(); - + bool isCastExpr; TypeTy *CastTy; SourceRange CastRange; @@ -1153,7 +1153,7 @@ Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() { /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' /// assign-expr ')' /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' -/// +/// /// [GNU] offsetof-member-designator: /// [GNU] identifier /// [GNU] offsetof-member-designator '.' identifier @@ -1205,7 +1205,7 @@ Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() { SkipUntil(tok::r_paren); return ExprError(); } - + if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) return ExprError(); @@ -1261,8 +1261,8 @@ Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() { } else if (Ty.isInvalid()) { Res = ExprError(); } else { - Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc, - Ty.get(), &Comps[0], + Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc, + Ty.get(), &Comps[0], Comps.size(), ConsumeParen()); } break; @@ -1342,7 +1342,7 @@ Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() { /// Parser::OwningExprResult Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, - bool parseAsExprList, TypeTy *&CastTy, + bool parseAsExprList, TypeTy *&CastTy, SourceLocation &RParenLoc) { assert(Tok.is(tok::l_paren) && "Not a paren expr!"); GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); @@ -1362,9 +1362,9 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, } else if (ExprType >= CompoundLiteral && isTypeIdInParens(isAmbiguousTypeId)) { - + // Otherwise, this is a compound literal expression or cast expression. - + // In C++, if the type-id is ambiguous we disambiguate based on context. // If stopIfCastExpr is true the context is a typeof/sizeof/alignof // in which case we should treat it as type-id. @@ -1373,7 +1373,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, if (isAmbiguousTypeId && !stopIfCastExpr) return ParseCXXAmbiguousParenExpression(ExprType, CastTy, OpenLoc, RParenLoc); - + TypeResult Ty = ParseTypeName(); // Match the ')'. @@ -1419,7 +1419,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, if (!ParseExpressionList(ArgExprs, CommaLocs)) { ExprType = SimpleExpr; - Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), + Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), move_arg(ArgExprs)); } } else { @@ -1434,7 +1434,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, SkipUntil(tok::r_paren); return ExprError(); } - + if (Tok.is(tok::r_paren)) RParenLoc = ConsumeParen(); else @@ -1554,7 +1554,7 @@ Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, "block literal parsing"); - // Enter a scope to hold everything within the block. This includes the + // Enter a scope to hold everything within the block. This includes the // argument decls, decls within the compound expression, etc. This also // allows determining whether a variable reference inside the block is // within or outside of the block. @@ -1564,7 +1564,7 @@ Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { // Inform sema that we are starting a block. Actions.ActOnBlockStart(CaretLoc, CurScope); - + // Parse the return type if present. DeclSpec DS; Declarator ParamInfo(DS, Declarator::BlockLiteralContext); @@ -1602,7 +1602,7 @@ Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { ParseBlockId(); } else { // Otherwise, pretend we saw (void). - ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, + ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, SourceLocation(), 0, 0, 0, false, SourceLocation(), @@ -1629,7 +1629,7 @@ Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { Actions.ActOnBlockError(CaretLoc, CurScope); return ExprError(); } - + OwningStmtResult Stmt(ParseCompoundStatementBody()); if (!Stmt.isInvalid()) Result = Actions.ActOnBlockStmtExpr(CaretLoc, move(Stmt), CurScope); diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp index a248a5dbeef1ef16ab4fb83f61ad19877949896c..a68ed6a8037026ac4393d2cdaf13784fa6a5c8aa 100644 --- a/clang/lib/Parse/ParseExprCXX.cpp +++ b/clang/lib/Parse/ParseExprCXX.cpp @@ -16,10 +16,10 @@ #include "clang/Parse/DeclSpec.h" using namespace clang; -/// \brief Parse global scope or nested-name-specifier if present. +/// \brief Parse global scope or nested-name-specifier if present. /// /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which -/// may be preceded by '::'). Note that this routine will not parse ::new or +/// may be preceded by '::'). Note that this routine will not parse ::new or /// ::delete; it will just leave them in the token stream. /// /// '::'[opt] nested-name-specifier @@ -32,10 +32,10 @@ using namespace clang; /// nested-name-specifier 'template'[opt] simple-template-id '::' /// /// -/// \param SS the scope specifier that will be set to the parsed +/// \param SS the scope specifier that will be set to the parsed /// nested-name-specifier (or empty) /// -/// \param ObjectType if this nested-name-specifier is being parsed following +/// \param ObjectType if this nested-name-specifier is being parsed following /// the "." or "->" of a member access expression, this parameter provides the /// type of the object whose members are being accessed. /// @@ -48,7 +48,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, bool EnteringContext) { assert(getLang().CPlusPlus && "Call sites of this function should be guarded by checking for C++"); - + if (Tok.is(tok::annot_cxxscope)) { SS.setScopeRep(Tok.getAnnotationValue()); SS.setRange(Tok.getAnnotationRange()); @@ -63,7 +63,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, tok::TokenKind NextKind = NextToken().getKind(); if (NextKind == tok::kw_new || NextKind == tok::kw_delete) return false; - + // '::' - Global scope qualifier. SourceLocation CCLoc = ConsumeToken(); SS.setBeginLoc(CCLoc); @@ -86,7 +86,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, // seen a leading '::' or part of a nested-name-specifier. ObjectType = 0; } - + // nested-name-specifier: // nested-name-specifier 'template'[opt] simple-template-id '::' @@ -100,14 +100,14 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, break; SourceLocation TemplateKWLoc = ConsumeToken(); - + if (Tok.isNot(tok::identifier)) { - Diag(Tok.getLocation(), + Diag(Tok.getLocation(), diag::err_id_after_template_in_nested_name_spec) << SourceRange(TemplateKWLoc); break; } - + if (NextToken().isNot(tok::less)) { Diag(NextToken().getLocation(), diag::err_less_after_template_name_in_nested_name_spec) @@ -115,8 +115,8 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, << SourceRange(TemplateKWLoc, Tok.getLocation()); break; } - - TemplateTy Template + + TemplateTy Template = Actions.ActOnDependentTemplateName(TemplateKWLoc, *Tok.getIdentifierInfo(), Tok.getLocation(), SS, @@ -126,40 +126,40 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, if (AnnotateTemplateIdToken(Template, TNK_Dependent_template_name, &SS, TemplateKWLoc, false)) break; - + continue; } - + if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { - // We have + // We have // // simple-template-id '::' // // So we need to check whether the simple-template-id is of the // right kind (it should name a type or be dependent), and then // convert it into a type within the nested-name-specifier. - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); - if (TemplateId->Kind == TNK_Type_template || + if (TemplateId->Kind == TNK_Type_template || TemplateId->Kind == TNK_Dependent_template_name) { AnnotateTemplateIdTokenAsType(&SS); - assert(Tok.is(tok::annot_typename) && + assert(Tok.is(tok::annot_typename) && "AnnotateTemplateIdTokenAsType isn't working"); Token TypeToken = Tok; ConsumeToken(); assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); SourceLocation CCLoc = ConsumeToken(); - + if (!HasScopeSpecifier) { SS.setBeginLoc(TypeToken.getLocation()); HasScopeSpecifier = true; } - + if (TypeToken.getAnnotationValue()) SS.setScopeRep( - Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, + Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, TypeToken.getAnnotationValue(), TypeToken.getAnnotationRange(), CCLoc)); @@ -168,7 +168,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, SS.setEndLoc(CCLoc); continue; } - + assert(false && "FIXME: Only type template names supported here"); } @@ -191,22 +191,22 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, SourceLocation IdLoc = ConsumeToken(); assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); SourceLocation CCLoc = ConsumeToken(); - + if (!HasScopeSpecifier) { SS.setBeginLoc(IdLoc); HasScopeSpecifier = true; } - + if (SS.isInvalid()) continue; - + SS.setScopeRep( Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, IdLoc, CCLoc, II, ObjectType, EnteringContext)); SS.setEndLoc(CCLoc); continue; } - + // nested-name-specifier: // type-name '<' if (Next.is(tok::less)) { @@ -234,7 +234,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, // nested-name-specifier, so we're done. break; } - + return HasScopeSpecifier; } @@ -337,17 +337,17 @@ Parser::OwningExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { } case tok::annot_template_id: { - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); assert((TemplateId->Kind == TNK_Function_template || TemplateId->Kind == TNK_Dependent_template_name) && "A template type name is not an ID expression"); - ASTTemplateArgsPtr TemplateArgsPtr(Actions, + ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateId->getTemplateArgs(), TemplateId->getTemplateArgIsType(), TemplateId->NumArgs); - + OwningExprResult Result = Actions.ActOnTemplateIdExpr(TemplateTy::make(TemplateId->Template), TemplateId->TemplateNameLoc, @@ -403,11 +403,11 @@ Parser::OwningExprResult Parser::ParseCXXCasts() { return ExprError(); OwningExprResult Result = ParseExpression(); - + // Match the ')'. if (Result.isInvalid()) SkipUntil(tok::r_paren); - + if (Tok.is(tok::r_paren)) RParenLoc = ConsumeParen(); else @@ -455,11 +455,11 @@ Parser::OwningExprResult Parser::ParseCXXTypeid() { Ty.get(), RParenLoc); } else { // C++0x [expr.typeid]p3: - // When typeid is applied to an expression other than an lvalue of a - // polymorphic class type [...] The expression is an unevaluated + // When typeid is applied to an expression other than an lvalue of a + // polymorphic class type [...] The expression is an unevaluated // operand (Clause 5). // - // Note that we can't tell whether the expression is an lvalue of a + // Note that we can't tell whether the expression is an lvalue of a // polymorphic class type until after we've parsed the expression, so // we the expression is potentially potentially evaluated. EnterExpressionEvaluationContext Unevaluated(Actions, @@ -654,12 +654,12 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { const char *PrevSpec; unsigned DiagID; SourceLocation Loc = Tok.getLocation(); - + switch (Tok.getKind()) { case tok::identifier: // foo::bar case tok::coloncolon: // ::foo::bar assert(0 && "Annotation token should already be formed!"); - default: + default: assert(0 && "Not a simple-type-specifier token!"); abort(); @@ -669,7 +669,7 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { Tok.getAnnotationValue()); break; } - + // builtin types case tok::kw_short: DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); @@ -710,7 +710,7 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { case tok::kw_bool: DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); break; - + // GNU typeof support. case tok::kw_typeof: ParseTypeofSpecifier(DS); @@ -747,7 +747,7 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { Diag(Tok, diag::err_operator_missing_type_specifier); return true; } - + while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID)) ; return false; @@ -878,7 +878,7 @@ Parser::TypeTy *Parser::ParseConversionFunctionId(SourceLocation *EndLoc) { /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate /// memory in a typesafe manner and call constructors. -/// +/// /// This method is called to parse the new expression after the optional :: has /// been already parsed. If the :: was present, "UseGlobal" is true and "Start" /// is its location. Otherwise, "Start" is the location of the 'new' token. @@ -1087,8 +1087,7 @@ Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, move(Operand)); } -static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) -{ +static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) { switch(kind) { default: assert(false && "Not a known unary type trait."); case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign; @@ -1116,8 +1115,7 @@ static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) /// primary-expression: /// [GNU] unary-type-trait '(' type-id ')' /// -Parser::OwningExprResult Parser::ParseUnaryTypeTrait() -{ +Parser::OwningExprResult Parser::ParseUnaryTypeTrait() { UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind()); SourceLocation Loc = ConsumeToken(); @@ -1172,7 +1170,7 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, // parsing a cast-expression), and then we re-introduce the cached tokens // into the token stream and parse them appropriately. - ParenParseOption ParseAs; + ParenParseOption ParseAs; CachedTokens Toks; // Store the tokens of the parentheses. We will parse them after we determine @@ -1204,7 +1202,7 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, ParseAs = NotCastExpr ? SimpleExpr : CastExpr; } - // The current token should go after the cached tokens. + // The current token should go after the cached tokens. Toks.push_back(Tok); // Re-enter the stored parenthesized tokens into the token stream, so we may // parse them now. @@ -1227,7 +1225,7 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, ExprType = CompoundLiteral; return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc); } - + // We parsed '(' type-id ')' and the thing after it wasn't a '{'. assert(ParseAs == CastExpr); @@ -1238,11 +1236,11 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, // Result is what ParseCastExpression returned earlier. if (!Result.isInvalid()) - Result = Actions.ActOnCastExpr(CurScope, LParenLoc, CastTy, RParenLoc, + Result = Actions.ActOnCastExpr(CurScope, LParenLoc, CastTy, RParenLoc, move(Result)); return move(Result); } - + // Not a compound literal, and not followed by a cast-expression. assert(ParseAs == SimpleExpr); @@ -1256,7 +1254,7 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, SkipUntil(tok::r_paren); return ExprError(); } - + if (Tok.is(tok::r_paren)) RParenLoc = ConsumeParen(); else diff --git a/clang/lib/Parse/ParseInit.cpp b/clang/lib/Parse/ParseInit.cpp index bbc2124e598630cd48f10ecc3b5282762f697994..6ab23fd42ddc54c311cd768fa0f372ca383bb4ad 100644 --- a/clang/lib/Parse/ParseInit.cpp +++ b/clang/lib/Parse/ParseInit.cpp @@ -20,7 +20,7 @@ using namespace clang; /// MayBeDesignationStart - Return true if this token might be the start of a /// designator. If we can tell it is impossible that it is a designator, return -/// false. +/// false. static bool MayBeDesignationStart(tok::TokenKind K, Preprocessor &PP) { switch (K) { default: return false; @@ -70,46 +70,46 @@ Parser::OwningExprResult Parser::ParseInitializerWithPotentialDesignator() { NewSyntax += " = "; SourceLocation NameLoc = ConsumeToken(); // Eat the identifier. - + assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!"); SourceLocation ColonLoc = ConsumeToken(); Diag(Tok, diag::ext_gnu_old_style_field_designator) - << CodeModificationHint::CreateReplacement(SourceRange(NameLoc, + << CodeModificationHint::CreateReplacement(SourceRange(NameLoc, ColonLoc), NewSyntax); Designation D; D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc)); - return Actions.ActOnDesignatedInitializer(D, ColonLoc, true, + return Actions.ActOnDesignatedInitializer(D, ColonLoc, true, ParseInitializer()); } - + // Desig - This is initialized when we see our first designator. We may have // an objc message send with no designator, so we don't want to create this // eagerly. Designation Desig; - + // Parse each designator in the designator list until we find an initializer. while (Tok.is(tok::period) || Tok.is(tok::l_square)) { if (Tok.is(tok::period)) { // designator: '.' identifier SourceLocation DotLoc = ConsumeToken(); - + if (Tok.isNot(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected_field_designator); return ExprError(); } - + Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc, Tok.getLocation())); ConsumeToken(); // Eat the identifier. continue; } - + // We must have either an array designator now or an objc message send. assert(Tok.is(tok::l_square) && "Unexpected token!"); - + // Handle the two forms of array designator: // array-designator: '[' constant-expression ']' // array-designator: '[' constant-expression '...' constant-expression ']' @@ -123,14 +123,14 @@ Parser::OwningExprResult Parser::ParseInitializerWithPotentialDesignator() { // [4][foo bar] -> obsolete GNU designation with objc message send. // SourceLocation StartLoc = ConsumeBracket(); - + // If Objective-C is enabled and this is a typename or other identifier // receiver, parse this as a message send expression. if (getLang().ObjC1 && isTokObjCMessageIdentifierReceiver()) { // If we have exactly one array designator, this used the GNU // 'designation: array-designator' extension, otherwise there should be no // designators at all! - if (Desig.getNumDesignators() == 1 && + if (Desig.getNumDesignators() == 1 && (Desig.getDesignator(0).isArrayDesignator() || Desig.getDesignator(0).isArrayRangeDesignator())) Diag(StartLoc, diag::ext_gnu_missing_equal_designator); @@ -151,18 +151,18 @@ Parser::OwningExprResult Parser::ParseInitializerWithPotentialDesignator() { SkipUntil(tok::r_square); return move(Idx); } - + // Given an expression, we could either have a designator (if the next // tokens are '...' or ']' or an objc message send. If this is an objc - // message send, handle it now. An objc-message send is the start of + // message send, handle it now. An objc-message send is the start of // an assignment-expression production. - if (getLang().ObjC1 && Tok.isNot(tok::ellipsis) && + if (getLang().ObjC1 && Tok.isNot(tok::ellipsis) && Tok.isNot(tok::r_square)) { - + // If we have exactly one array designator, this used the GNU // 'designation: array-designator' extension, otherwise there should be no // designators at all! - if (Desig.getNumDesignators() == 1 && + if (Desig.getNumDesignators() == 1 && (Desig.getDesignator(0).isArrayDesignator() || Desig.getDesignator(0).isArrayRangeDesignator())) Diag(StartLoc, diag::ext_gnu_missing_equal_designator); @@ -213,7 +213,7 @@ Parser::OwningExprResult Parser::ParseInitializerWithPotentialDesignator() { // an initializer. If we have exactly one array designator, this // is the GNU 'designation: array-designator' extension. Otherwise, it is a // parse error. - if (Desig.getNumDesignators() == 1 && + if (Desig.getNumDesignators() == 1 && (Desig.getDesignator(0).isArrayDesignator() || Desig.getDesignator(0).isArrayRangeDesignator())) { Diag(Tok, diag::ext_gnu_missing_equal_designator) @@ -267,13 +267,13 @@ Parser::OwningExprResult Parser::ParseBraceInitializer() { SubElt = ParseInitializerWithPotentialDesignator(); else SubElt = ParseInitializer(); - + // If we couldn't parse the subelement, bail out. if (!SubElt.isInvalid()) { InitExprs.push_back(SubElt.release()); } else { InitExprsOk = false; - + // We have two ways to try to recover from this error: if the code looks // gramatically ok (i.e. we have a comma coming up) try to continue // parsing the rest of the initializer. This allows us to emit diff --git a/clang/lib/Parse/ParseObjc.cpp b/clang/lib/Parse/ParseObjc.cpp index 013e26b891e1ba5d083d41bec7080639a000ba3d..fdd031c66de1d0974e48b975720cbee50f12898a 100644 --- a/clang/lib/Parse/ParseObjc.cpp +++ b/clang/lib/Parse/ParseObjc.cpp @@ -29,7 +29,7 @@ using namespace clang; /// [OBJC] '@' 'end' Parser::DeclPtrTy Parser::ParseObjCAtDirectives() { SourceLocation AtLoc = ConsumeToken(); // the "@" - + switch (Tok.getObjCKeywordID()) { case tok::objc_class: return ParseObjCAtClassDeclaration(AtLoc); @@ -55,13 +55,13 @@ Parser::DeclPtrTy Parser::ParseObjCAtDirectives() { } /// -/// objc-class-declaration: +/// objc-class-declaration: /// '@' 'class' identifier-list ';' -/// +/// Parser::DeclPtrTy Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { ConsumeToken(); // the identifier "class" llvm::SmallVector ClassNames; - + while (1) { if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); @@ -70,17 +70,17 @@ Parser::DeclPtrTy Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { } ClassNames.push_back(Tok.getIdentifierInfo()); ConsumeToken(); - + if (Tok.isNot(tok::comma)) break; - + ConsumeToken(); } - + // Consume the ';'. if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class")) return DeclPtrTy(); - + return Actions.ActOnForwardClassDeclaration(atLoc, &ClassNames[0], ClassNames.size()); } @@ -91,14 +91,14 @@ Parser::DeclPtrTy Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { /// objc-category-interface /// /// objc-class-interface: -/// '@' 'interface' identifier objc-superclass[opt] +/// '@' 'interface' identifier objc-superclass[opt] /// objc-protocol-refs[opt] -/// objc-class-instance-variables[opt] +/// objc-class-instance-variables[opt] /// objc-interface-decl-list /// @end /// /// objc-category-interface: -/// '@' 'interface' identifier '(' identifier[opt] ')' +/// '@' 'interface' identifier '(' identifier[opt] ')' /// objc-protocol-refs[opt] /// objc-interface-decl-list /// @end @@ -118,7 +118,7 @@ Parser::DeclPtrTy Parser::ParseObjCAtInterfaceDeclaration( assert(Tok.isObjCAtKeyword(tok::objc_interface) && "ParseObjCAtInterfaceDeclaration(): Expected @interface"); ConsumeToken(); // the "interface" identifier - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); // missing class or category name. return DeclPtrTy(); @@ -126,12 +126,12 @@ Parser::DeclPtrTy Parser::ParseObjCAtInterfaceDeclaration( // We have a class or category name - consume it. IdentifierInfo *nameId = Tok.getIdentifierInfo(); SourceLocation nameLoc = ConsumeToken(); - + if (Tok.is(tok::l_paren)) { // we have a category. SourceLocation lparenLoc = ConsumeParen(); SourceLocation categoryLoc, rparenLoc; IdentifierInfo *categoryId = 0; - + // For ObjC2, the category name is optional (not an error). if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); @@ -146,25 +146,25 @@ Parser::DeclPtrTy Parser::ParseObjCAtInterfaceDeclaration( return DeclPtrTy(); } rparenLoc = ConsumeParen(); - + // Next, we need to check for any protocol references. SourceLocation EndProtoLoc; llvm::SmallVector ProtocolRefs; if (Tok.is(tok::less) && ParseObjCProtocolReferences(ProtocolRefs, true, EndProtoLoc)) return DeclPtrTy(); - + if (attrList) // categories don't support attributes. Diag(Tok, diag::err_objc_no_attributes_on_category); - + DeclPtrTy CategoryType = - Actions.ActOnStartCategoryInterface(atLoc, + Actions.ActOnStartCategoryInterface(atLoc, nameId, nameLoc, categoryId, categoryLoc, ProtocolRefs.data(), ProtocolRefs.size(), EndProtoLoc); - + ParseObjCInterfaceDeclList(CategoryType, tok::objc_not_keyword); return CategoryType; } @@ -187,13 +187,13 @@ Parser::DeclPtrTy Parser::ParseObjCAtInterfaceDeclaration( if (Tok.is(tok::less) && ParseObjCProtocolReferences(ProtocolRefs, true, EndProtoLoc)) return DeclPtrTy(); - - DeclPtrTy ClsType = - Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc, + + DeclPtrTy ClsType = + Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc, superClassId, superClassLoc, ProtocolRefs.data(), ProtocolRefs.size(), EndProtoLoc, attrList); - + if (Tok.is(tok::l_brace)) ParseObjCClassInstanceVariables(ClsType, atLoc); @@ -219,13 +219,13 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, llvm::SmallVector allProperties; llvm::SmallVector allTUVariables; tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; - + SourceLocation AtEndLoc; while (1) { // If this is a method prototype, parse it. if (Tok.is(tok::minus) || Tok.is(tok::plus)) { - DeclPtrTy methodPrototype = + DeclPtrTy methodPrototype = ParseObjCMethodPrototype(interfaceDecl, MethodImplKind); allMethods.push_back(methodPrototype); // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for @@ -234,17 +234,17 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, "", tok::semi); continue; } - + // Ignore excess semicolons. if (Tok.is(tok::semi)) { ConsumeToken(); continue; } - + // If we got to the end of the file, exit the loop. if (Tok.is(tok::eof)) break; - + // 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 @@ -252,22 +252,22 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, // erroneous r_brace would cause an infinite loop if not handled here. if (Tok.is(tok::r_brace)) break; - + // FIXME: as the name implies, this rule allows function definitions. // We could pass a flag or check for functions during semantic analysis. allTUVariables.push_back(ParseDeclarationOrFunctionDefinition()); continue; } - + // Otherwise, we have an @ directive, eat the @. SourceLocation AtLoc = ConsumeToken(); // the "@" tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID(); - + if (DirectiveKind == tok::objc_end) { // @end -> terminate list AtEndLoc = AtLoc; break; } - + // Eat the identifier. ConsumeToken(); @@ -281,7 +281,7 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, // Skip until we see an '@' or '}' or ';'. SkipUntil(tok::r_brace, tok::at); break; - + case tok::objc_required: case tok::objc_optional: // This is only valid on protocols. @@ -291,24 +291,24 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, else MethodImplKind = DirectiveKind; break; - + case tok::objc_property: if (!getLang().ObjC2) Diag(AtLoc, diag::err_objc_propertoes_require_objc2); ObjCDeclSpec OCDS; - // Parse property attribute list, if any. + // Parse property attribute list, if any. if (Tok.is(tok::l_paren)) ParseObjCPropertyAttribute(OCDS); - + // Parse all the comma separated declarators. DeclSpec DS; llvm::SmallVector FieldDeclarators; ParseStructDeclaration(DS, FieldDeclarators); - + ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list, "", tok::at); - + // Convert them all to property declarations. for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) { FieldDeclarator &FD = FieldDeclarators[i]; @@ -322,12 +322,12 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, << FD.D.getSourceRange(); continue; } - + // Install the property declarator into interfaceDecl. IdentifierInfo *SelName = OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); - - Selector GetterSel = + + Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName); IdentifierInfo *SetterName = OCDS.getSetterName(); Selector SetterSel; @@ -340,7 +340,7 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, bool isOverridingProperty = false; DeclPtrTy Property = Actions.ActOnProperty(CurScope, AtLoc, FD, OCDS, GetterSel, SetterSel, - interfaceDecl, + interfaceDecl, &isOverridingProperty, MethodImplKind); if (!isOverridingProperty) @@ -356,11 +356,11 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, ConsumeToken(); // the "end" identifier else Diag(Tok, diag::err_objc_missing_end); - + // Insert collected methods declarations into the @interface object. // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit. Actions.ActOnAtEnd(AtEndLoc, interfaceDecl, - allMethods.data(), allMethods.size(), + allMethods.data(), allMethods.size(), allProperties.data(), allProperties.size(), allTUVariables.data(), allTUVariables.size()); } @@ -384,18 +384,18 @@ void Parser::ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { assert(Tok.getKind() == tok::l_paren); SourceLocation LHSLoc = ConsumeParen(); // consume '(' - + while (1) { const IdentifierInfo *II = Tok.getIdentifierInfo(); - + // If this is not an identifier at all, bail out early. if (II == 0) { MatchRHSPunctuation(tok::r_paren, LHSLoc); return; } - + SourceLocation AttrName = ConsumeToken(); // consume last attribute name - + if (II->isStr("readonly")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly); else if (II->isStr("assign")) @@ -413,18 +413,18 @@ void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { if (ExpectAndConsume(tok::equal, diag::err_objc_expected_equal, "", tok::r_paren)) return; - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); SkipUntil(tok::r_paren); return; } - + if (II->getName()[0] == 's') { DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter); DS.setSetterName(Tok.getIdentifierInfo()); ConsumeToken(); // consume method name - + if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "", tok::r_paren)) return; @@ -438,18 +438,18 @@ void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { SkipUntil(tok::r_paren); return; } - + if (Tok.isNot(tok::comma)) break; - + ConsumeToken(); } - + MatchRHSPunctuation(tok::r_paren, LHSLoc); } /// objc-method-proto: -/// objc-instance-method objc-method-decl objc-method-attributes[opt] +/// objc-instance-method objc-method-decl objc-method-attributes[opt] /// objc-class-method objc-method-decl objc-method-attributes[opt] /// /// objc-instance-method: '-' @@ -458,13 +458,13 @@ void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { /// objc-method-attributes: [OBJC2] /// __attribute__((deprecated)) /// -Parser::DeclPtrTy Parser::ParseObjCMethodPrototype(DeclPtrTy IDecl, +Parser::DeclPtrTy Parser::ParseObjCMethodPrototype(DeclPtrTy IDecl, tok::ObjCKeywordKind MethodImplKind) { assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-"); - tok::TokenKind methodType = Tok.getKind(); + tok::TokenKind methodType = Tok.getKind(); SourceLocation mLoc = ConsumeToken(); - + DeclPtrTy MDecl = ParseObjCMethodDecl(mLoc, methodType, IDecl,MethodImplKind); // Since this rule is used for both method declarations and definitions, // the caller is (optionally) responsible for consuming the ';'. @@ -564,7 +564,7 @@ bool Parser::isTokIdentifier_in() const { // FIXME: May have to do additional look-ahead to only allow for // valid tokens following an 'in'; such as an identifier, unary operators, // '[' etc. - return (getLang().ObjC2 && Tok.is(tok::identifier) && + return (getLang().ObjC2 && Tok.is(tok::identifier) && Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]); } @@ -580,12 +580,12 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS) { while (1) { if (Tok.isNot(tok::identifier)) return; - + const IdentifierInfo *II = Tok.getIdentifierInfo(); for (unsigned i = 0; i != objc_NumQuals; ++i) { if (II != ObjCTypeQuals[i]) continue; - + ObjCDeclSpec::ObjCDeclQualifier Qual; switch (i) { default: assert(0 && "Unknown decl qualifier"); @@ -601,7 +601,7 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS) { II = 0; break; } - + // If this wasn't a recognized qualifier, bail out. if (II) return; } @@ -613,10 +613,10 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS) { /// Parser::TypeTy *Parser::ParseObjCTypeName(ObjCDeclSpec &DS) { assert(Tok.is(tok::l_paren) && "expected ("); - + SourceLocation LParenLoc = ConsumeParen(); SourceLocation TypeStartLoc = Tok.getLocation(); - + // Parse type qualifiers, in, inout, etc. ParseObjCTypeQualifierList(DS); @@ -626,7 +626,7 @@ Parser::TypeTy *Parser::ParseObjCTypeName(ObjCDeclSpec &DS) { if (!TypeSpec.isInvalid()) Ty = TypeSpec.get(); } - + if (Tok.is(tok::r_paren)) ConsumeParen(); else if (Tok.getLocation() == TypeStartLoc) { @@ -648,7 +648,7 @@ Parser::TypeTy *Parser::ParseObjCTypeName(ObjCDeclSpec &DS) { /// objc-type-name objc-keyword-selector objc-parmlist[opt] /// /// objc-keyword-selector: -/// objc-keyword-decl +/// objc-keyword-decl /// objc-keyword-selector objc-keyword-decl /// /// objc-keyword-decl: @@ -678,7 +678,7 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDecl(SourceLocation mLoc, ObjCDeclSpec DSRet; if (Tok.is(tok::l_paren)) ReturnType = ParseObjCTypeName(DSRet); - + SourceLocation selLoc; IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc); @@ -690,14 +690,14 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDecl(SourceLocation mLoc, SkipUntil(tok::r_brace); return DeclPtrTy(); } - + llvm::SmallVector CargNames; if (Tok.isNot(tok::colon)) { // If attributes exist after the method, parse them. AttributeList *MethodAttrs = 0; - if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) + if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) MethodAttrs = ParseAttributes(); - + Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent); return Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(), mType, IDecl, DSRet, ReturnType, Sel, @@ -707,17 +707,17 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDecl(SourceLocation mLoc, llvm::SmallVector KeyIdents; llvm::SmallVector ArgInfos; - + while (1) { Action::ObjCArgInfo ArgInfo; - + // Each iteration parses a single keyword argument. if (Tok.isNot(tok::colon)) { Diag(Tok, diag::err_expected_colon); break; } ConsumeToken(); // Eat the ':'. - + ArgInfo.Type = 0; if (Tok.is(tok::l_paren)) // Parse the argument type if present. ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec); @@ -731,11 +731,11 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDecl(SourceLocation mLoc, Diag(Tok, diag::err_expected_ident); // missing argument name. break; } - + ArgInfo.Name = Tok.getIdentifierInfo(); ArgInfo.NameLoc = Tok.getLocation(); ConsumeToken(); // Eat the identifier. - + ArgInfos.push_back(ArgInfo); KeyIdents.push_back(SelIdent); @@ -746,9 +746,9 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDecl(SourceLocation mLoc, break; // We have a selector or a colon, continue parsing. } - + bool isVariadic = false; - + // Parse the (optional) parameter list. while (Tok.is(tok::comma)) { ConsumeToken(); @@ -759,18 +759,18 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDecl(SourceLocation mLoc, } DeclSpec DS; ParseDeclarationSpecifiers(DS); - // Parse the declarator. + // Parse the declarator. Declarator ParmDecl(DS, Declarator::PrototypeContext); ParseDeclarator(ParmDecl); CargNames.push_back(ParmDecl); } - + // FIXME: Add support for optional parmameter list... // If attributes exist after the method, parse them. AttributeList *MethodAttrs = 0; - if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) + if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) MethodAttrs = ParseAttributes(); - + if (KeyIdents.size() == 0) return DeclPtrTy(); Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), @@ -788,11 +788,11 @@ bool Parser:: ParseObjCProtocolReferences(llvm::SmallVectorImpl &Protocols, bool WarnOnDeclarations, SourceLocation &EndLoc) { assert(Tok.is(tok::less) && "expected <"); - + ConsumeToken(); // the "<" - + llvm::SmallVector ProtocolIdents; - + while (1) { if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); @@ -802,20 +802,20 @@ ParseObjCProtocolReferences(llvm::SmallVectorImpl &Protocols, ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); ConsumeToken(); - + if (Tok.isNot(tok::comma)) break; ConsumeToken(); } - + // Consume the '>'. if (Tok.isNot(tok::greater)) { Diag(Tok, diag::err_expected_greater); return true; } - + EndLoc = ConsumeAnyToken(); - + // Convert the list of protocols identifiers into a list of protocol decls. Actions.FindProtocolDeclaration(WarnOnDeclarations, &ProtocolIdents[0], ProtocolIdents.size(), @@ -841,7 +841,7 @@ ParseObjCProtocolReferences(llvm::SmallVectorImpl &Protocols, /// @package [OBJC2] /// /// objc-instance-variable-decl: -/// struct-declaration +/// struct-declaration /// void Parser::ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, SourceLocation atLoc) { @@ -852,19 +852,19 @@ void Parser::ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); SourceLocation LBraceLoc = ConsumeBrace(); // the "{" - + tok::ObjCKeywordKind visibility = tok::objc_protected; // While we still have something to read, read the instance variables. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { // Each iteration of this loop reads one objc-instance-variable-decl. - + // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { Diag(Tok, diag::ext_extra_struct_semi); ConsumeToken(); continue; } - + // Set the default visibility to private. if (Tok.is(tok::at)) { // parse objc-visibility-spec ConsumeToken(); // eat the @ sign @@ -875,18 +875,18 @@ void Parser::ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, case tok::objc_package: visibility = Tok.getObjCKeywordID(); ConsumeToken(); - continue; + continue; default: Diag(Tok, diag::err_objc_illegal_visibility_spec); continue; } } - + // Parse all the comma separated declarators. DeclSpec DS; FieldDeclarators.clear(); ParseStructDeclaration(DS, FieldDeclarators); - + // Convert them all to fields. for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) { FieldDeclarator &FD = FieldDeclarators[i]; @@ -897,7 +897,7 @@ void Parser::ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, FD.D, FD.BitfieldSize, visibility); AllIvarDecls.push_back(Field); } - + if (Tok.is(tok::semi)) { ConsumeToken(); } else { @@ -920,9 +920,9 @@ void Parser::ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, /// objc-protocol-forward-reference /// /// objc-protocol-definition: -/// @protocol identifier -/// objc-protocol-refs[opt] -/// objc-interface-decl-list +/// @protocol identifier +/// objc-protocol-refs[opt] +/// objc-interface-decl-list /// @end /// /// objc-protocol-forward-reference: @@ -936,7 +936,7 @@ Parser::DeclPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, assert(Tok.isObjCAtKeyword(tok::objc_protocol) && "ParseObjCAtProtocolDeclaration(): Expected @protocol"); ConsumeToken(); // the "protocol" identifier - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); // missing protocol name. return DeclPtrTy(); @@ -944,14 +944,14 @@ Parser::DeclPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, // Save the protocol name, then consume it. IdentifierInfo *protocolName = Tok.getIdentifierInfo(); SourceLocation nameLoc = ConsumeToken(); - + if (Tok.is(tok::semi)) { // forward declaration of one protocol. IdentifierLocPair ProtoInfo(protocolName, nameLoc); ConsumeToken(); - return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, + return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, attrList); } - + if (Tok.is(tok::comma)) { // list of forward declarations. llvm::SmallVector ProtocolRefs; ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); @@ -967,20 +967,20 @@ Parser::DeclPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), Tok.getLocation())); ConsumeToken(); // the identifier - + if (Tok.isNot(tok::comma)) break; } // Consume the ';'. if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol")) return DeclPtrTy(); - + return Actions.ActOnForwardProtocolDeclaration(AtLoc, - &ProtocolRefs[0], + &ProtocolRefs[0], ProtocolRefs.size(), attrList); } - + // Last, and definitely not least, parse a protocol declaration. SourceLocation EndProtoLoc; @@ -988,7 +988,7 @@ Parser::DeclPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, if (Tok.is(tok::less) && ParseObjCProtocolReferences(ProtocolRefs, false, EndProtoLoc)) return DeclPtrTy(); - + DeclPtrTy ProtoType = Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, ProtocolRefs.data(), @@ -1013,7 +1013,7 @@ Parser::DeclPtrTy Parser::ParseObjCAtImplementationDeclaration( assert(Tok.isObjCAtKeyword(tok::objc_implementation) && "ParseObjCAtImplementationDeclaration(): Expected @implementation"); ConsumeToken(); // the "implementation" identifier - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); // missing class or category name. return DeclPtrTy(); @@ -1021,20 +1021,20 @@ Parser::DeclPtrTy Parser::ParseObjCAtImplementationDeclaration( // We have a class or category name - consume it. IdentifierInfo *nameId = Tok.getIdentifierInfo(); SourceLocation nameLoc = ConsumeToken(); // consume class or category name - - if (Tok.is(tok::l_paren)) { + + if (Tok.is(tok::l_paren)) { // we have a category implementation. SourceLocation lparenLoc = ConsumeParen(); SourceLocation categoryLoc, rparenLoc; IdentifierInfo *categoryId = 0; - + if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); categoryLoc = ConsumeToken(); } else { Diag(Tok, diag::err_expected_ident); // missing category name. return DeclPtrTy(); - } + } if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected_rparen); SkipUntil(tok::r_paren, false); // don't stop at ';' @@ -1042,7 +1042,7 @@ Parser::DeclPtrTy Parser::ParseObjCAtImplementationDeclaration( } rparenLoc = ConsumeParen(); DeclPtrTy ImplCatType = Actions.ActOnStartCategoryImplementation( - atLoc, nameId, nameLoc, categoryId, + atLoc, nameId, nameLoc, categoryId, categoryLoc); ObjCImpDecl = ImplCatType; return DeclPtrTy(); @@ -1063,11 +1063,11 @@ Parser::DeclPtrTy Parser::ParseObjCAtImplementationDeclaration( DeclPtrTy ImplClsType = Actions.ActOnStartClassImplementation( atLoc, nameId, nameLoc, superClassId, superClassLoc); - + if (Tok.is(tok::l_brace)) // we have ivars ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/, atLoc); ObjCImpDecl = ImplClsType; - + return DeclPtrTy(); } @@ -1131,7 +1131,7 @@ Parser::DeclPtrTy Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { Diag(Tok, diag::err_expected_ident); return DeclPtrTy(); } - + while (Tok.is(tok::identifier)) { IdentifierInfo *propertyIvar = 0; IdentifierInfo *propertyId = Tok.getIdentifierInfo(); @@ -1186,7 +1186,7 @@ Parser::DeclPtrTy Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { Diag(Tok, diag::err_expected_semi_after) << "@dynamic"; return DeclPtrTy(); } - + /// objc-throw-statement: /// throw expression[opt]; /// @@ -1288,7 +1288,7 @@ Parser::OwningStmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { DeclSpec DS; ParseDeclarationSpecifiers(DS); // For some odd reason, the name of the exception variable is - // optional. As a result, we need to use "PrototypeContext", because + // optional. As a result, we need to use "PrototypeContext", because // we must accept either 'declarator' or 'abstract-declarator' here. Declarator ParmDecl(DS, Declarator::PrototypeContext); ParseDeclarator(ParmDecl); @@ -1298,9 +1298,9 @@ Parser::OwningStmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { FirstPart = Actions.ActOnParamDeclarator(CurScope, ParmDecl); } else ConsumeToken(); // consume '...' - + SourceLocation RParenLoc; - + if (Tok.is(tok::r_paren)) RParenLoc = ConsumeParen(); else // Skip over garbage, until we get to ')'. Eat the ')'. @@ -1352,11 +1352,11 @@ Parser::OwningStmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { /// Parser::DeclPtrTy Parser::ParseObjCMethodDefinition() { DeclPtrTy MDecl = ParseObjCMethodPrototype(ObjCImpDecl); - + PrettyStackTraceActionsDecl CrashInfo(MDecl, Tok.getLocation(), Actions, PP.getSourceManager(), "parsing Objective-C method"); - + // parse optional ';' if (Tok.is(tok::semi)) ConsumeToken(); @@ -1364,19 +1364,19 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDefinition() { // We should have an opening brace now. if (Tok.isNot(tok::l_brace)) { Diag(Tok, diag::err_expected_method_body); - + // Skip over garbage, until we get to '{'. Don't eat the '{'. SkipUntil(tok::l_brace, true, true); - + // If we didn't find the '{', bail out. if (Tok.isNot(tok::l_brace)) return DeclPtrTy(); } SourceLocation BraceLoc = Tok.getLocation(); - + // Enter a scope for the method body. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); - + // Tell the actions module that we have entered a method definition with the // specified Declarator for the method. Actions.ActOnStartOfObjCMethodDef(CurScope, MDecl); @@ -1390,7 +1390,7 @@ Parser::DeclPtrTy Parser::ParseObjCMethodDefinition() { // TODO: Pass argument information. Actions.ActOnFinishFunctionBody(MDecl, move(FnBody)); - + // Leave the function body scope. BodyScope.Exit(); @@ -1439,7 +1439,7 @@ Parser::OwningExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { } } -/// objc-message-expr: +/// objc-message-expr: /// '[' objc-receiver objc-message-args ']' /// /// objc-receiver: @@ -1472,7 +1472,7 @@ Parser::OwningExprResult Parser::ParseObjCMessageExpression() { /// ParseObjCMessageExpressionBody - Having parsed "'[' objc-receiver", parse /// the rest of a message expression. -/// +/// /// objc-message-args: /// objc-selector /// objc-keywordarg-list @@ -1481,7 +1481,7 @@ Parser::OwningExprResult Parser::ParseObjCMessageExpression() { /// objc-keywordarg /// objc-keywordarg-list objc-keywordarg /// -/// objc-keywordarg: +/// objc-keywordarg: /// selector-name[opt] ':' objc-keywordexpr /// /// objc-keywordexpr: @@ -1501,7 +1501,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); SourceLocation SelectorLoc = Loc; - + llvm::SmallVector KeyIdents; ExprVector KeyExprs(Actions); @@ -1520,7 +1520,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, } ConsumeToken(); // Eat the ':'. - /// Parse the expression after ':' + /// Parse the expression after ':' OwningExprResult Res(ParseAssignmentExpression()); if (Res.isInvalid()) { // We must manually skip to a ']', otherwise the expression skipper will @@ -1542,7 +1542,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, // Parse the, optional, argument list, comma separated. while (Tok.is(tok::comma)) { ConsumeToken(); // Eat the ','. - /// Parse the expression after ',' + /// Parse the expression after ',' OwningExprResult Res(ParseAssignmentExpression()); if (Res.isInvalid()) { // We must manually skip to a ']', otherwise the expression skipper will @@ -1584,7 +1584,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, // We've just parsed a keyword message. if (ReceiverName) return Owned(Actions.ActOnClassMessage(CurScope, ReceiverName, Sel, - LBracLoc, NameLoc, SelectorLoc, + LBracLoc, NameLoc, SelectorLoc, RBracLoc, KeyExprs.take(), KeyExprs.size())); return Owned(Actions.ActOnInstanceMessage(ReceiverExpr.release(), Sel, @@ -1642,7 +1642,7 @@ Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { if (Ty.isInvalid()) return ExprError(); - return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc, + return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc, Ty.get(), RParenLoc)); } diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp index 68b10934b15b527cf3f1c03e8f50683967a98d87..812d8e2af901d631391545f4dbd9ee5178d0c35b 100644 --- a/clang/lib/Parse/ParsePragma.cpp +++ b/clang/lib/Parse/ParsePragma.cpp @@ -37,7 +37,7 @@ void PragmaPackHandler::HandlePragma(Preprocessor &PP, Token &PackTok) { IdentifierInfo *Name = 0; Action::OwningExprResult Alignment(Actions); SourceLocation LParenLoc = Tok.getLocation(); - PP.Lex(Tok); + PP.Lex(Tok); if (Tok.is(tok::numeric_constant)) { Alignment = Actions.ActOnNumericConstant(Tok); if (Alignment.isInvalid()) @@ -57,12 +57,12 @@ void PragmaPackHandler::HandlePragma(Preprocessor &PP, Token &PackTok) { } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_invalid_action); return; - } + } PP.Lex(Tok); - + if (Tok.is(tok::comma)) { PP.Lex(Tok); - + if (Tok.is(tok::numeric_constant)) { Alignment = Actions.ActOnNumericConstant(Tok); if (Alignment.isInvalid()) @@ -72,15 +72,15 @@ void PragmaPackHandler::HandlePragma(Preprocessor &PP, Token &PackTok) { } else if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); PP.Lex(Tok); - + if (Tok.is(tok::comma)) { PP.Lex(Tok); - + if (Tok.isNot(tok::numeric_constant)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed); return; } - + Alignment = Actions.ActOnNumericConstant(Tok); if (Alignment.isInvalid()) return; @@ -115,7 +115,7 @@ void PragmaPackHandler::HandlePragma(Preprocessor &PP, Token &PackTok) { void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, Token &UnusedTok) { // FIXME: Should we be expanding macros here? My guess is no. SourceLocation UnusedLoc = UnusedTok.getLocation(); - + // Lex the left '('. Token Tok; PP.Lex(Tok); @@ -124,17 +124,17 @@ void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, Token &UnusedTok) { return; } SourceLocation LParenLoc = Tok.getLocation(); - + // Lex the declaration reference(s). llvm::SmallVector Identifiers; SourceLocation RParenLoc; bool LexID = true; - + while (true) { PP.Lex(Tok); - + if (LexID) { - if (Tok.is(tok::identifier)) { + if (Tok.is(tok::identifier)) { Identifiers.push_back(Tok); LexID = false; continue; @@ -144,18 +144,18 @@ void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, Token &UnusedTok) { PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var); return; } - + // We are execting a ')' or a ','. if (Tok.is(tok::comma)) { LexID = true; continue; } - + if (Tok.is(tok::r_paren)) { RParenLoc = Tok.getLocation(); break; } - + // Illegal token! PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_punc); return; @@ -172,7 +172,7 @@ void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, Token &UnusedTok) { assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'"); assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments"); - // Perform the action to handle the pragma. + // Perform the action to handle the pragma. Actions.ActOnPragmaUnused(Identifiers.data(), Identifiers.size(), parser.CurScope, UnusedLoc, LParenLoc, RParenLoc); } @@ -197,7 +197,7 @@ void PragmaWeakHandler::HandlePragma(Preprocessor &PP, Token &WeakTok) { if (Tok.is(tok::equal)) { PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { - PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) + PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak"; return; } diff --git a/clang/lib/Parse/ParsePragma.h b/clang/lib/Parse/ParsePragma.h index 39c86eea43b03b022a440fe30de165d3ee8a67cd..db385c6371e390029a13e1bd89ad38c04c51fbfe 100644 --- a/clang/lib/Parse/ParsePragma.h +++ b/clang/lib/Parse/ParsePragma.h @@ -23,29 +23,29 @@ namespace clang { class PragmaPackHandler : public PragmaHandler { Action &Actions; public: - PragmaPackHandler(const IdentifierInfo *N, Action &A) : PragmaHandler(N), + PragmaPackHandler(const IdentifierInfo *N, Action &A) : PragmaHandler(N), Actions(A) {} - - virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); + + virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); }; - + class PragmaUnusedHandler : public PragmaHandler { Action &Actions; Parser &parser; public: PragmaUnusedHandler(const IdentifierInfo *N, Action &A, Parser& p) : PragmaHandler(N), Actions(A), parser(p) {} - - virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); -}; + + virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); +}; class PragmaWeakHandler : public PragmaHandler { Action &Actions; public: PragmaWeakHandler(const IdentifierInfo *N, Action &A) : PragmaHandler(N), Actions(A) {} - - virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); + + virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); }; } // end namespace clang diff --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp index 4a7bd57d786a347b2d03a8c224f44e7e9d8c4ded..edb0018d20d207ecd9d676f8e27575abf9c18744 100644 --- a/clang/lib/Parse/ParseStmt.cpp +++ b/clang/lib/Parse/ParseStmt.cpp @@ -71,8 +71,8 @@ using namespace clang; /// /// [OBC] objc-throw-statement: /// [OBC] '@' 'throw' expression ';' -/// [OBC] '@' 'throw' ';' -/// +/// [OBC] '@' 'throw' ';' +/// Parser::OwningStmtResult Parser::ParseStatementOrDeclaration(bool OnlyStatement) { const char *SemiError = 0; @@ -108,7 +108,7 @@ Parser::ParseStatementOrDeclaration(bool OnlyStatement) { Diag(Tok, diag::err_expected_statement); return StmtError(); } - + // expression[opt] ';' OwningExprResult Expr(ParseExpression()); if (Expr.isInvalid()) { @@ -187,7 +187,7 @@ Parser::ParseStatementOrDeclaration(bool OnlyStatement) { // Skip until we see a } or ;, but don't eat it. SkipUntil(tok::r_brace, true, true); } - + return move(Res); } @@ -233,7 +233,7 @@ Parser::OwningStmtResult Parser::ParseLabeledStatement() { /// Parser::OwningStmtResult Parser::ParseCaseStatement() { assert(Tok.is(tok::kw_case) && "Not a case stmt!"); - + // It is very very common for code to contain many case statements recursively // nested, as in (but usually without indentation): // case 1: @@ -247,20 +247,20 @@ Parser::OwningStmtResult Parser::ParseCaseStatement() { // flatten this recursion into an iterative loop. This is complex and gross, // but all the grossness is constrained to ParseCaseStatement (and some // wierdness in the actions), so this is just local grossness :). - + // TopLevelCase - This is the highest level we have parsed. 'case 1' in the // example above. OwningStmtResult TopLevelCase(Actions, true); - + // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which // gets updated each time a new case is parsed, and whose body is unset so // far. When parsing 'case 4', this is the 'case 3' node. StmtTy *DeepestParsedCaseStmt = 0; - + // While we have case statements, eat and stack them. do { SourceLocation CaseLoc = ConsumeToken(); // eat the 'case'. - + OwningExprResult LHS(ParseConstantExpression()); if (LHS.isInvalid()) { SkipUntil(tok::colon); @@ -288,11 +288,11 @@ Parser::OwningStmtResult Parser::ParseCaseStatement() { } SourceLocation ColonLoc = ConsumeToken(); - + OwningStmtResult Case = Actions.ActOnCaseStmt(CaseLoc, move(LHS), DotDotDotLoc, move(RHS), ColonLoc); - + // If we had a sema error parsing this case, then just ignore it and // continue parsing the sub-stmt. if (Case.isInvalid()) { @@ -309,15 +309,15 @@ Parser::OwningStmtResult Parser::ParseCaseStatement() { Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, move(Case)); DeepestParsedCaseStmt = NextDeepest; } - + // Handle all case statements. } while (Tok.is(tok::kw_case)); - + assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!"); - + // If we found a non-case statement, start by parsing it. OwningStmtResult SubStmt(Actions); - + if (Tok.isNot(tok::r_brace)) { SubStmt = ParseStatement(); } else { @@ -327,11 +327,11 @@ Parser::OwningStmtResult Parser::ParseCaseStatement() { Diag(Tok, diag::err_label_end_of_compound_statement); SubStmt = true; } - + // Broken sub-stmt shouldn't prevent forming the case statement properly. if (SubStmt.isInvalid()) SubStmt = Actions.ActOnNullStmt(SourceLocation()); - + // Install the body into the most deeply-nested case. Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, move(SubStmt)); @@ -415,10 +415,10 @@ Parser::OwningStmtResult Parser::ParseCompoundStatement(bool isStmtExpr) { /// consume the '}' at the end of the block. It does not manipulate the scope /// stack. Parser::OwningStmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) { - PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), + PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), Tok.getLocation(), "in compound statement ('{}')"); - + SourceLocation LBraceLoc = ConsumeBrace(); // eat the '{'. // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are @@ -496,12 +496,12 @@ bool Parser::ParseParenExprOrCondition(OwningExprResult &CondExp, SourceLocation *RParenLocPtr) { SourceLocation LParenLoc = ConsumeParen(); if (LParenLocPtr) *LParenLocPtr = LParenLoc; - + if (getLang().CPlusPlus) CondExp = ParseCXXCondition(); else CondExp = ParseExpression(); - + // If the parser was confused by the condition and we don't have a ')', try to // recover by skipping ahead to a semi and bailing out. If condexp is // semantically invalid but we have well formed code, keep going. @@ -512,7 +512,7 @@ bool Parser::ParseParenExprOrCondition(OwningExprResult &CondExp, if (Tok.isNot(tok::r_paren)) return true; } - + // Otherwise the condition is valid or the rparen is present. SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); if (RParenLocPtr) *RParenLocPtr = RPLoc; @@ -559,7 +559,7 @@ Parser::OwningStmtResult Parser::ParseIfStatement() { return StmtError(); FullExprArg FullCondExp(Actions.FullExpr(CondExp)); - + // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. @@ -578,7 +578,7 @@ Parser::OwningStmtResult Parser::ParseIfStatement() { // would have to notify ParseStatement not to create a new scope. It's // simpler to let it create a new scope. // - ParseScope InnerScope(this, Scope::DeclScope, + ParseScope InnerScope(this, Scope::DeclScope, C99orCXX && Tok.isNot(tok::l_brace)); // Read the 'then' stmt. @@ -619,14 +619,14 @@ Parser::OwningStmtResult Parser::ParseIfStatement() { } IfScope.Exit(); - + // If the condition was invalid, discard the if statement. We could recover // better by replacing it with a valid expr, but don't do that yet. if (CondExp.isInvalid()) return StmtError(); // If the then or else stmt is invalid and the other is valid (and present), - // make turn the invalid one into a null stmt to avoid dropping the other + // make turn the invalid one into a null stmt to avoid dropping the other // part. If both are invalid, return error. if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) || (ThenStmt.isInvalid() && ElseStmt.get() == 0) || @@ -641,7 +641,7 @@ Parser::OwningStmtResult Parser::ParseIfStatement() { if (ElseStmt.isInvalid()) ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc); - return Actions.ActOnIfStmt(IfLoc, FullCondExp, move(ThenStmt), + return Actions.ActOnIfStmt(IfLoc, FullCondExp, move(ThenStmt), ElseLoc, move(ElseStmt)); } @@ -698,7 +698,7 @@ Parser::OwningStmtResult Parser::ParseSwitchStatement() { // See comments in ParseIfStatement for why we create a scope for the // condition and a new scope for substatement in C++. // - ParseScope InnerScope(this, Scope::DeclScope, + ParseScope InnerScope(this, Scope::DeclScope, C99orCXX && Tok.isNot(tok::l_brace)); // Read the body statement. @@ -763,7 +763,7 @@ Parser::OwningStmtResult Parser::ParseWhileStatement() { return StmtError(); FullExprArg FullCond(Actions.FullExpr(Cond)); - + // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. @@ -775,7 +775,7 @@ Parser::OwningStmtResult Parser::ParseWhileStatement() { // See comments in ParseIfStatement for why we create a scope for the // condition and a new scope for substatement in C++. // - ParseScope InnerScope(this, Scope::DeclScope, + ParseScope InnerScope(this, Scope::DeclScope, C99orCXX && Tok.isNot(tok::l_brace)); // Read the body statement. @@ -818,7 +818,7 @@ Parser::OwningStmtResult Parser::ParseDoStatement() { // which is entered and exited each time through the loop. // ParseScope InnerScope(this, Scope::DeclScope, - (getLang().C99 || getLang().CPlusPlus) && + (getLang().C99 || getLang().CPlusPlus) && Tok.isNot(tok::l_brace)); // Read the body statement. @@ -847,7 +847,7 @@ Parser::OwningStmtResult Parser::ParseDoStatement() { OwningExprResult Cond(Actions); SourceLocation LPLoc, RPLoc; ParseParenExprOrCondition(Cond, true, &LPLoc, &RPLoc); - + DoScope.Exit(); if (Cond.isInvalid() || Body.isInvalid()) @@ -926,11 +926,11 @@ Parser::OwningStmtResult Parser::ParseForStatement() { DeclGroupPtrTy DG = ParseSimpleDeclaration(Declarator::ForContext, DeclEnd, false); FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); - + if (Tok.is(tok::semi)) { // for (int x = 4; ConsumeToken(); } else if ((ForEach = isTokIdentifier_in())) { - // ObjC: for (id x in expr) + // ObjC: for (id x in expr) ConsumeToken(); // consume 'in' SecondPart = ParseExpression(); } else { @@ -988,7 +988,7 @@ Parser::OwningStmtResult Parser::ParseForStatement() { // See comments in ParseIfStatement for why we create a scope for // for-init-statement/condition and a new scope for substatement in C++. // - ParseScope InnerScope(this, Scope::DeclScope, + ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC && Tok.isNot(tok::l_brace)); // Read the body statement. @@ -1007,7 +1007,7 @@ Parser::OwningStmtResult Parser::ParseForStatement() { return Actions.ActOnForStmt(ForLoc, LParenLoc, move(FirstPart), move(SecondPart), move(ThirdPart), RParenLoc, move(Body)); - + return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, move(FirstPart), move(SecondPart), @@ -1096,7 +1096,7 @@ Parser::OwningStmtResult Parser::FuzzyParseMicrosoftAsmStatement() { do { ConsumeAnyToken(); } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof)); - } else { + } else { // From the MS website: If used without braces, the __asm keyword means // that the rest of the line is an assembly-language statement. SourceManager &SrcMgr = PP.getSourceManager(); @@ -1105,8 +1105,8 @@ Parser::OwningStmtResult Parser::FuzzyParseMicrosoftAsmStatement() { do { ConsumeAnyToken(); TokLoc = Tok.getLocation(); - } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) && - Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) && + } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) && + Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) && Tok.isNot(tok::eof)); } return Actions.ActOnNullStmt(Tok.getLocation()); @@ -1196,7 +1196,7 @@ Parser::OwningStmtResult Parser::ParseAsmStatement(bool &msAsm) { return StmtError(); assert(Names.size() == Constraints.size() && - Constraints.size() == Exprs.size() + Constraints.size() == Exprs.size() && "Input operand size mismatch!"); NumInputs = Names.size() - NumOutputs; @@ -1247,22 +1247,22 @@ bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl &Names, // Only do anything if this operand is present. if (Tok.isNot(tok::colon)) return false; ConsumeToken(); - + // 'asm-operands' isn't present? if (!isTokenStringLiteral() && Tok.isNot(tok::l_square)) return false; - - while (1) { + + while (1) { // Read the [id] if present. if (Tok.is(tok::l_square)) { SourceLocation Loc = ConsumeBracket(); - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_ident); SkipUntil(tok::r_paren); return true; } - + IdentifierInfo *II = Tok.getIdentifierInfo(); ConsumeToken(); @@ -1308,7 +1308,7 @@ Parser::DeclPtrTy Parser::ParseFunctionStatementBody(DeclPtrTy Decl) { PrettyStackTraceActionsDecl CrashInfo(Decl, LBraceLoc, Actions, PP.getSourceManager(), "parsing function body"); - + // Do not enter a scope for the brace, as the arguments are in the same scope // (the function body) as the body itself. Instead, just read the statement // list and put it into a CompoundStmt for safe keeping. @@ -1316,7 +1316,7 @@ Parser::DeclPtrTy Parser::ParseFunctionStatementBody(DeclPtrTy Decl) { // If the function body could not be parsed, make a bogus compoundstmt. if (FnBody.isInvalid()) - FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, + FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, MultiStmtArg(Actions), false); return Actions.ActOnFinishFunctionBody(Decl, move(FnBody)); diff --git a/clang/lib/Parse/ParseTemplate.cpp b/clang/lib/Parse/ParseTemplate.cpp index 40de81a883f2741209509f2355f325215309d7a7..8e63fb89db3177fc909ae3ed091df832af69f156 100644 --- a/clang/lib/Parse/ParseTemplate.cpp +++ b/clang/lib/Parse/ParseTemplate.cpp @@ -25,7 +25,7 @@ Parser::ParseDeclarationStartingWithTemplate(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS) { if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) - return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(), + return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(), DeclEnd); return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS); @@ -38,18 +38,18 @@ namespace { unsigned AddedLevels; public: - explicit TemplateParameterDepthCounter(unsigned &Depth) + explicit TemplateParameterDepthCounter(unsigned &Depth) : Depth(Depth), AddedLevels(0) { } - + ~TemplateParameterDepthCounter() { Depth -= AddedLevels; } - - void operator++() { + + void operator++() { ++Depth; ++AddedLevels; } - + operator unsigned() const { return Depth; } }; } @@ -73,9 +73,9 @@ Parser::DeclPtrTy Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS) { - assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) && - "Token does not start a template declaration."); - + assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) && + "Token does not start a template declaration."); + // Enter template-parameter scope. ParseScope TemplateParmScope(this, Scope::TemplateParamScope); @@ -118,33 +118,33 @@ Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, Diag(Tok.getLocation(), diag::err_expected_template); return DeclPtrTy(); } - + // Parse the '<' template-parameter-list '>' SourceLocation LAngleLoc, RAngleLoc; TemplateParameterList TemplateParams; - if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc, + if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc, RAngleLoc)) { // Skip until the semi-colon or a }. SkipUntil(tok::r_brace, true, true); if (Tok.is(tok::semi)) ConsumeToken(); - return DeclPtrTy(); + return DeclPtrTy(); } ParamLists.push_back( - Actions.ActOnTemplateParameterList(Depth, ExportLoc, - TemplateLoc, LAngleLoc, + Actions.ActOnTemplateParameterList(Depth, ExportLoc, + TemplateLoc, LAngleLoc, TemplateParams.data(), TemplateParams.size(), RAngleLoc)); if (!TemplateParams.empty()) { isSpecialization = false; ++Depth; - } + } } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template)); // Parse the actual template declaration. - return ParseSingleDeclarationAfterTemplate(Context, + return ParseSingleDeclarationAfterTemplate(Context, ParsedTemplateInfo(&ParamLists, isSpecialization), DeclEnd, AS); @@ -170,7 +170,7 @@ Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, /// declaration. Will be AS_none for namespace-scope declarations. /// /// \returns the new declaration. -Parser::DeclPtrTy +Parser::DeclPtrTy Parser::ParseSingleDeclarationAfterTemplate( unsigned Context, const ParsedTemplateInfo &TemplateInfo, @@ -184,7 +184,7 @@ Parser::ParseSingleDeclarationAfterTemplate( ParseCXXClassMemberDeclaration(AS, TemplateInfo); return DeclPtrTy::make((void*)0); } - + // Parse the declaration specifiers. DeclSpec DS; ParseDeclarationSpecifiers(DS, TemplateInfo, AS); @@ -205,7 +205,7 @@ Parser::ParseSingleDeclarationAfterTemplate( ConsumeToken(); return DeclPtrTy(); } - + // If we have a declaration or declarator list, handle it. if (isDeclarationAfterDeclarator()) { // Parse this declaration. @@ -256,7 +256,7 @@ Parser::ParseSingleDeclarationAfterTemplate( /// is the number of template headers directly enclosing this template header. /// TemplateParams is the current list of template parameters we're building. /// The template parameter we parse will be added to this list. LAngleLoc and -/// RAngleLoc will receive the positions of the '<' and '>', respectively, +/// RAngleLoc will receive the positions of the '<' and '>', respectively, /// that enclose this template parameter list. /// /// \returns true if an error occurred, false otherwise. @@ -265,17 +265,17 @@ bool Parser::ParseTemplateParameters(unsigned Depth, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) { // Get the template parameter list. - if(!Tok.is(tok::less)) { + if (!Tok.is(tok::less)) { Diag(Tok.getLocation(), diag::err_expected_less_after) << "template"; return true; } LAngleLoc = ConsumeToken(); - + // Try to parse the template parameter list. if (Tok.is(tok::greater)) RAngleLoc = ConsumeToken(); - else if(ParseTemplateParameterList(Depth, TemplateParams)) { - if(!Tok.is(tok::greater)) { + else if (ParseTemplateParameterList(Depth, TemplateParams)) { + if (!Tok.is(tok::greater)) { Diag(Tok.getLocation(), diag::err_expected_greater); return true; } @@ -287,15 +287,15 @@ bool Parser::ParseTemplateParameters(unsigned Depth, /// ParseTemplateParameterList - Parse a template parameter list. If /// the parsing fails badly (i.e., closing bracket was left out), this /// will try to put the token stream in a reasonable position (closing -/// a statement, etc.) and return false. +/// a statement, etc.) and return false. /// /// template-parameter-list: [C++ temp] /// template-parameter /// template-parameter-list ',' template-parameter -bool +bool Parser::ParseTemplateParameterList(unsigned Depth, TemplateParameterList &TemplateParams) { - while(1) { + while (1) { if (DeclPtrTy TmpParam = ParseTemplateParameter(Depth, TemplateParams.size())) { TemplateParams.push_back(TmpParam); @@ -304,11 +304,11 @@ Parser::ParseTemplateParameterList(unsigned Depth, // a comma or closing brace. SkipUntil(tok::comma, tok::greater, true, true); } - + // Did we find a comma or the end of the template parmeter list? - if(Tok.is(tok::comma)) { + if (Tok.is(tok::comma)) { ConsumeToken(); - } else if(Tok.is(tok::greater)) { + } else if (Tok.is(tok::greater)) { // Don't consume this... that's done by template parser. break; } else { @@ -338,16 +338,16 @@ Parser::ParseTemplateParameterList(unsigned Depth, /// 'typename' identifier[opt] '=' type-id /// 'template' ...[opt][C++0x] '<' template-parameter-list '>' 'class' identifier[opt] /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression -Parser::DeclPtrTy +Parser::DeclPtrTy Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { - if(Tok.is(tok::kw_class) || - (Tok.is(tok::kw_typename) && - // FIXME: Next token has not been annotated! - NextToken().isNot(tok::annot_typename))) { + if (Tok.is(tok::kw_class) || + (Tok.is(tok::kw_typename) && + // FIXME: Next token has not been annotated! + NextToken().isNot(tok::annot_typename))) { return ParseTypeParameter(Depth, Position); } - - if(Tok.is(tok::kw_template)) + + if (Tok.is(tok::kw_template)) return ParseTemplateTemplateParameter(Depth, Position); // If it's none of the above, then it must be a parameter declaration. @@ -367,7 +367,7 @@ Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { /// 'typename' identifier[opt] '=' type-id Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){ assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) && - "A type-parameter starts with 'class' or 'typename'"); + "A type-parameter starts with 'class' or 'typename'"); // Consume the 'class' or 'typename' keyword. bool TypenameKeyword = Tok.is(tok::kw_typename); @@ -379,33 +379,33 @@ Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){ if (Tok.is(tok::ellipsis)) { Ellipsis = true; EllipsisLoc = ConsumeToken(); - - if (!getLang().CPlusPlus0x) + + if (!getLang().CPlusPlus0x) Diag(EllipsisLoc, diag::err_variadic_templates); } - + // Grab the template parameter name (if given) SourceLocation NameLoc; IdentifierInfo* ParamName = 0; - if(Tok.is(tok::identifier)) { + if (Tok.is(tok::identifier)) { ParamName = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); - } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || - Tok.is(tok::greater)) { + } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || + Tok.is(tok::greater)) { // Unnamed template parameter. Don't have to do anything here, just // don't consume this token. } else { Diag(Tok.getLocation(), diag::err_expected_ident); return DeclPtrTy(); } - + DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword, Ellipsis, EllipsisLoc, KeyLoc, ParamName, NameLoc, Depth, Position); // Grab a default type id (if given). - if(Tok.is(tok::equal)) { + if (Tok.is(tok::equal)) { SourceLocation EqualLoc = ConsumeToken(); SourceLocation DefaultLoc = Tok.getLocation(); TypeResult DefaultType = ParseTypeName(); @@ -413,12 +413,12 @@ Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){ Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc, DefaultType.get()); } - + return TypeParam; } /// ParseTemplateTemplateParameter - Handle the parsing of template -/// template parameters. +/// template parameters. /// /// type-parameter: [C++ temp.param] /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] @@ -429,11 +429,11 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { // Handle the template <...> part. SourceLocation TemplateLoc = ConsumeToken(); - TemplateParameterList TemplateParams; + TemplateParameterList TemplateParams; SourceLocation LAngleLoc, RAngleLoc; { ParseScope TemplateParmScope(this, Scope::TemplateParamScope); - if(ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc, + if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc, RAngleLoc)) { return DeclPtrTy(); } @@ -441,8 +441,8 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { // Generate a meaningful error if the user forgot to put class before the // identifier, comma, or greater. - if(!Tok.is(tok::kw_class)) { - Diag(Tok.getLocation(), diag::err_expected_class_before) + if (!Tok.is(tok::kw_class)) { + Diag(Tok.getLocation(), diag::err_expected_class_before) << PP.getSpelling(Tok); return DeclPtrTy(); } @@ -451,10 +451,10 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { // Get the identifier, if given. SourceLocation NameLoc; IdentifierInfo* ParamName = 0; - if(Tok.is(tok::identifier)) { + if (Tok.is(tok::identifier)) { ParamName = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); - } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) { + } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) { // Unnamed template parameter. Don't have to do anything here, just // don't consume this token. } else { @@ -462,10 +462,10 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { return DeclPtrTy(); } - TemplateParamsTy *ParamList = + TemplateParamsTy *ParamList = Actions.ActOnTemplateParameterList(Depth, SourceLocation(), TemplateLoc, LAngleLoc, - &TemplateParams[0], + &TemplateParams[0], TemplateParams.size(), RAngleLoc); @@ -489,7 +489,7 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { } /// ParseNonTypeTemplateParameter - Handle the parsing of non-type -/// template parameters (e.g., in "template class array;"). +/// template parameters (e.g., in "template class array;"). /// /// template-parameter: /// ... @@ -501,7 +501,7 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { /// parameters. /// FIXME: We need to make a ParseParameterDeclaration that works for /// non-type template parameters and normal function parameters. -Parser::DeclPtrTy +Parser::DeclPtrTy Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { SourceLocation StartLoc = Tok.getLocation(); @@ -524,7 +524,7 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { return DeclPtrTy(); } - // Create the parameter. + // Create the parameter. DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl, Depth, Position); @@ -537,16 +537,16 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { // template-parameter, the first non-nested > is taken as the // end of the template-parameter-list rather than a greater-than // operator. - GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); + GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); OwningExprResult DefaultArg = ParseAssignmentExpression(); if (DefaultArg.isInvalid()) SkipUntil(tok::comma, tok::greater, true, true); else if (Param) - Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc, + Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc, move(DefaultArg)); } - + return Param; } @@ -568,9 +568,9 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { /// token that forms the template-id. Otherwise, we will leave the /// last token in the stream (e.g., so that it can be replaced with an /// annotation token). -bool +bool Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, - SourceLocation TemplateNameLoc, + SourceLocation TemplateNameLoc, const CXXScopeSpec *SS, bool ConsumeLastToken, SourceLocation &LAngleLoc, @@ -628,7 +628,7 @@ Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, return false; } - + /// \brief Replace the tokens that form a simple-template-id with an /// annotation token containing the complete template-id. /// @@ -667,7 +667,7 @@ Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, /// formed, this function returns true. /// bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, - const CXXScopeSpec *SS, + const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, bool AllowTypeAnnotation) { assert(getLang().CPlusPlus && "Can only annotate template-ids in C++"); @@ -684,12 +684,12 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, TemplateArgIsTypeList TemplateArgIsType; TemplateArgLocationList TemplateArgLocations; bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc, - SS, false, LAngleLoc, - TemplateArgs, + SS, false, LAngleLoc, + TemplateArgs, TemplateArgIsType, TemplateArgLocations, RAngleLoc); - + if (Invalid) { // If we failed to parse the template ID but skipped ahead to a >, we're not // going to be able to form a token annotation. Eat the '>' if present. @@ -704,7 +704,7 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, // Build the annotation token. if (TNK == TNK_Type_template && AllowTypeAnnotation) { - Action::TypeResult Type + Action::TypeResult Type = Actions.ActOnTemplateIdType(Template, TemplateNameLoc, LAngleLoc, TemplateArgsPtr, &TemplateArgLocations[0], @@ -723,13 +723,13 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, Tok.setLocation(SS->getBeginLoc()); else if (TemplateKWLoc.isValid()) Tok.setLocation(TemplateKWLoc); - else + else Tok.setLocation(TemplateNameLoc); } else { // Build a template-id annotation token that can be processed // later. Tok.setKind(tok::annot_template_id); - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Allocate(TemplateArgs.size()); TemplateId->TemplateNameLoc = TemplateNameLoc; TemplateId->Name = Name; @@ -772,21 +772,21 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) { assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens"); - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); assert((TemplateId->Kind == TNK_Type_template || TemplateId->Kind == TNK_Dependent_template_name) && "Only works for type and dependent templates"); - - ASTTemplateArgsPtr TemplateArgsPtr(Actions, + + ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateId->getTemplateArgs(), TemplateId->getTemplateArgIsType(), TemplateId->NumArgs); - Action::TypeResult Type + Action::TypeResult Type = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), TemplateId->TemplateNameLoc, - TemplateId->LAngleLoc, + TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->getTemplateArgLocations(), TemplateId->RAngleLoc); @@ -839,7 +839,7 @@ void *Parser::ParseTemplateArgument(bool &ArgIsType) { /// template-argument-list: [C++ 14.2] /// template-argument /// template-argument-list ',' template-argument -bool +bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs, TemplateArgIsTypeList &TemplateArgIsType, TemplateArgLocationList &TemplateArgLocations) { @@ -867,18 +867,18 @@ Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs, return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater); } -/// \brief Parse a C++ explicit template instantiation +/// \brief Parse a C++ explicit template instantiation /// (C++ [temp.explicit]). /// /// explicit-instantiation: /// 'extern' [opt] 'template' declaration /// /// Note that the 'extern' is a GNU extension and C++0x feature. -Parser::DeclPtrTy +Parser::DeclPtrTy Parser::ParseExplicitInstantiation(SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd) { - return ParseSingleDeclarationAfterTemplate(Declarator::FileContext, + return ParseSingleDeclarationAfterTemplate(Declarator::FileContext, ParsedTemplateInfo(ExternLoc, TemplateLoc), DeclEnd, AS_none); diff --git a/clang/lib/Parse/ParseTentative.cpp b/clang/lib/Parse/ParseTentative.cpp index 89c3db74152f3848b20c4c8185026066261892bc..eb6e93540566ef7b0449d6b81d4a5a6db422812b 100644 --- a/clang/lib/Parse/ParseTentative.cpp +++ b/clang/lib/Parse/ParseTentative.cpp @@ -270,7 +270,7 @@ bool Parser::isCXXConditionDeclaration() { return TPR == TPResult::True(); } - /// \brief Determine whether the next set of tokens contains a type-id. + /// \brief Determine whether the next set of tokens contains a type-id. /// /// The context parameter states what context we're parsing right /// now, which affects how this routine copes with the token @@ -288,7 +288,7 @@ bool Parser::isCXXConditionDeclaration() { /// type-specifier-seq abstract-declarator[opt] /// bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) { - + isAmbiguous = false; // C++ 8.2p2: @@ -601,14 +601,14 @@ Parser::TPResult Parser::isCXXDeclarationSpecifier() { if (NextToken().is(tok::kw_new) || // ::new NextToken().is(tok::kw_delete)) // ::delete return TPResult::False(); - + // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return isCXXDeclarationSpecifier(); // Otherwise, not a typename. return TPResult::False(); - + // decl-specifier: // storage-class-specifier // type-specifier @@ -654,7 +654,7 @@ Parser::TPResult Parser::isCXXDeclarationSpecifier() { case tok::kw__Complex: case tok::kw___attribute: return TPResult::True(); - + // Microsoft case tok::kw___declspec: case tok::kw___cdecl: @@ -758,7 +758,7 @@ Parser::TPResult Parser::TryParseDeclarationSpecifier() { TryParseTypeofSpecifier(); else ConsumeToken(); - + assert(Tok.is(tok::l_paren) && "Expected '('!"); return TPResult::Ambiguous(); } @@ -880,7 +880,7 @@ Parser::TPResult Parser::TryParseParameterDeclarationClause() { /// If TryParseFunctionDeclarator fully parsed the function declarator, it will /// return TPResult::Ambiguous(), otherwise it will return either False() or /// Error(). -/// +/// /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] /// exception-specification[opt] /// diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp index 8572d3268667cf29cbd9bb2a4ef2af327116c523..177290b4381dc66439a938847d7a3cfc88eb740d 100644 --- a/clang/lib/Parse/Parser.cpp +++ b/clang/lib/Parse/Parser.cpp @@ -24,17 +24,17 @@ using namespace clang; /// to the parser action. class ActionCommentHandler : public CommentHandler { Action &Actions; - + public: explicit ActionCommentHandler(Action &Actions) : Actions(Actions) { } - + virtual void HandleComment(Preprocessor &PP, SourceRange Comment) { Actions.ActOnComment(Comment); } }; Parser::Parser(Preprocessor &pp, Action &actions) - : CrashInfo(*this), PP(pp), Actions(actions), Diags(PP.getDiagnostics()), + : CrashInfo(*this), PP(pp), Actions(actions), Diags(PP.getDiagnostics()), GreaterThanIsOperator(true), TemplateParameterDepth(0) { Tok.setKind(tok::eof); CurScope = 0; @@ -47,7 +47,7 @@ Parser::Parser(Preprocessor &pp, Action &actions) PackHandler.reset(new PragmaPackHandler(&PP.getIdentifierTable().get("pack"), actions)); PP.AddPragmaHandler(0, PackHandler.get()); - + UnusedHandler.reset(new PragmaUnusedHandler(&PP.getIdentifierTable().get("unused"), actions, *this)); @@ -56,9 +56,9 @@ Parser::Parser(Preprocessor &pp, Action &actions) WeakHandler.reset(new PragmaWeakHandler(&PP.getIdentifierTable().get("weak"), actions)); PP.AddPragmaHandler(0, WeakHandler.get()); - + CommentHandler.reset(new ActionCommentHandler(actions)); - PP.AddCommentHandler(CommentHandler.get()); + PP.AddCommentHandler(CommentHandler.get()); } /// If a crash happens while the parser is active, print out a line indicating @@ -69,12 +69,12 @@ void PrettyStackTraceParserEntry::print(llvm::raw_ostream &OS) const { OS << " parser at end of file\n"; return; } - + if (Tok.getLocation().isInvalid()) { OS << " parser at unknown location\n"; return; } - + const Preprocessor &PP = P.getPreprocessor(); Tok.getLocation().print(OS, PP.getSourceManager()); OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n"; @@ -104,8 +104,8 @@ void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK, Diag(Loc, DK); return; } - - Diag(Loc, DK) + + Diag(Loc, DK) << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(") << CodeModificationHint::CreateInsertion(EndLoc, ")"); } @@ -152,10 +152,10 @@ bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID, const char *Spelling = 0; SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); - if (EndLoc.isValid() && + if (EndLoc.isValid() && (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) { // Show what code to insert to fix this problem. - Diag(EndLoc, DiagID) + Diag(EndLoc, DiagID) << Msg << CodeModificationHint::CreateInsertion(EndLoc, Spelling); } else @@ -365,7 +365,7 @@ void Parser::ParseTranslationUnit() { DeclGroupPtrTy Res; while (!ParseTopLevelDecl(Res)) /*parse them all*/; - + ExitScope(); assert(CurScope == 0 && "Scope imbalance!"); } @@ -399,7 +399,7 @@ Parser::DeclGroupPtrTy Parser::ParseExternalDeclaration() { if (!getLang().CPlusPlus0x) Diag(Tok, diag::ext_top_level_semi) << CodeModificationHint::CreateRemoval(SourceRange(Tok.getLocation())); - + ConsumeToken(); // TODO: Invoke action for top-level semicolon. return DeclGroupPtrTy(); @@ -462,16 +462,16 @@ Parser::DeclGroupPtrTy Parser::ParseExternalDeclaration() { return Actions.ConvertDeclToDeclGroup( ParseExplicitInstantiation(ExternLoc, TemplateLoc, DeclEnd)); } - + // FIXME: Detect C++ linkage specifications here? - + // Fall through to handle other declarations or function definitions. - + default: // We can't tell whether this is a function-definition or declaration yet. return ParseDeclarationOrFunctionDefinition(); } - + // This routine returns a DeclGroup, if the thing we parsed only contains a // single decl, convert it now. return Actions.ConvertDeclToDeclGroup(SingleDecl); @@ -493,7 +493,7 @@ bool Parser::isDeclarationAfterDeclarator() { /// declarator, indicates the start of a function definition. bool Parser::isStartOfFunctionDefinition() { return Tok.is(tok::l_brace) || // int X() {} - (!getLang().CPlusPlus && + (!getLang().CPlusPlus && isDeclarationSpecifier()) || // int X(f) int f; {} (getLang().CPlusPlus && (Tok.is(tok::colon) || // X() : Base() {} (used for ctors) @@ -504,7 +504,7 @@ bool Parser::isStartOfFunctionDefinition() { /// a declaration. We can't tell which we have until we read up to the /// compound-statement in function-definition. TemplateParams, if /// non-NULL, provides the template parameters when we're parsing a -/// C++ template-declaration. +/// C++ template-declaration. /// /// function-definition: [C99 6.9.1] /// decl-specs declarator declaration-list[opt] compound-statement @@ -535,7 +535,7 @@ Parser::ParseDeclarationOrFunctionDefinition(AccessSpecifier AS) { // attributes here, no types, etc. if (getLang().ObjC2 && Tok.is(tok::at)) { SourceLocation AtLoc = ConsumeToken(); // the "@" - if (!Tok.isObjCAtKeyword(tok::objc_interface) && + if (!Tok.isObjCAtKeyword(tok::objc_interface) && !Tok.isObjCAtKeyword(tok::objc_protocol)) { Diag(Tok, diag::err_objc_unexpected_attr); SkipUntil(tok::semi); // FIXME: better skip? @@ -545,7 +545,7 @@ Parser::ParseDeclarationOrFunctionDefinition(AccessSpecifier AS) { unsigned DiagID; if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID)) Diag(AtLoc, DiagID) << PrevSpec; - + DeclPtrTy TheDecl; if (Tok.isObjCAtKeyword(tok::objc_protocol)) TheDecl = ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); @@ -585,7 +585,7 @@ Parser::ParseDeclarationOrFunctionDefinition(AccessSpecifier AS) { ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration); return DG; } - + if (DeclaratorInfo.isFunctionDeclarator() && isStartOfFunctionDefinition()) { if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { @@ -605,7 +605,7 @@ Parser::ParseDeclarationOrFunctionDefinition(AccessSpecifier AS) { DeclPtrTy TheDecl = ParseFunctionDefinition(DeclaratorInfo); return Actions.ConvertDeclToDeclGroup(TheDecl); } - + if (DeclaratorInfo.isFunctionDeclarator()) Diag(Tok, diag::err_expected_fn_body); else @@ -672,7 +672,7 @@ Parser::DeclPtrTy Parser::ParseFunctionDefinition(Declarator &D, // Tell the actions module that we have entered a function definition with the // specified Declarator for the function. - DeclPtrTy Res = TemplateInfo.TemplateParams? + DeclPtrTy Res = TemplateInfo.TemplateParams? Actions.ActOnStartOfFunctionTemplateDef(CurScope, Action::MultiTemplateParamsArg(Actions, TemplateInfo.TemplateParams->data(), @@ -882,24 +882,24 @@ Parser::OwningExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) { /// /// This returns true if the token was annotated or an unrecoverable error /// occurs. -/// +/// /// Note that this routine emits an error if you call it with ::new or ::delete /// as the current tokens, so only call it in contexts where these are invalid. bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { - assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) + assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || Tok.is(tok::kw_typename)) && "Cannot be a type or scope token!"); - + if (Tok.is(tok::kw_typename)) { // Parse a C++ typename-specifier, e.g., "typename T::type". // // typename-specifier: // 'typename' '::' [opt] nested-name-specifier identifier - // 'typename' '::' [opt] nested-name-specifier template [opt] + // 'typename' '::' [opt] nested-name-specifier template [opt] // simple-template-id SourceLocation TypenameLoc = ConsumeToken(); CXXScopeSpec SS; - bool HadNestedNameSpecifier + bool HadNestedNameSpecifier = ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false); if (!HadNestedNameSpecifier) { Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); @@ -909,10 +909,10 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { TypeResult Ty; if (Tok.is(tok::identifier)) { // FIXME: check whether the next token is '<', first! - Ty = Actions.ActOnTypenameType(TypenameLoc, SS, *Tok.getIdentifierInfo(), + Ty = Actions.ActOnTypenameType(TypenameLoc, SS, *Tok.getIdentifierInfo(), Tok.getLocation()); } else if (Tok.is(tok::annot_template_id)) { - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); if (TemplateId->Kind == TNK_Function_template) { Diag(Tok, diag::err_typename_refers_to_non_type_template) @@ -921,7 +921,7 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { } AnnotateTemplateIdTokenAsType(0); - assert(Tok.is(tok::annot_typename) && + assert(Tok.is(tok::annot_typename) && "AnnotateTemplateIdTokenAsType isn't working properly"); if (Tok.getAnnotationValue()) Ty = Actions.ActOnTypenameType(TypenameLoc, SS, SourceLocation(), @@ -948,7 +948,7 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { if (Tok.is(tok::identifier)) { // Determine whether the identifier is a type name. - if (TypeTy *Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), + if (TypeTy *Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), CurScope, &SS)) { // This is a typename. Replace the current token in-place with an // annotation type token. @@ -957,27 +957,27 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { Tok.setAnnotationEndLoc(Tok.getLocation()); if (SS.isNotEmpty()) // it was a C++ qualified type name. Tok.setLocation(SS.getBeginLoc()); - + // In case the tokens were cached, have Preprocessor replace // them with the annotation token. PP.AnnotateCachedTokens(Tok); return true; - } + } if (!getLang().CPlusPlus) { // If we're in C, we can't have :: tokens at all (the lexer won't return // them). If the identifier is not a type, then it can't be scope either, - // just early exit. + // just early exit. return false; } - + // If this is a template-id, annotate with a template-id or type token. if (NextToken().is(tok::less)) { TemplateTy Template; - if (TemplateNameKind TNK - = Actions.isTemplateName(CurScope, *Tok.getIdentifierInfo(), - Tok.getLocation(), &SS, - /*ObjectType=*/0, EnteringContext, + if (TemplateNameKind TNK + = Actions.isTemplateName(CurScope, *Tok.getIdentifierInfo(), + Tok.getLocation(), &SS, + /*ObjectType=*/0, EnteringContext, Template)) if (AnnotateTemplateIdToken(Template, TNK, &SS)) { // If an unrecoverable error occurred, we need to return true here, @@ -991,10 +991,10 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { // template-id, is not part of the annotation. Fall through to // push that token back into the stream and complete the C++ scope // specifier annotation. - } + } if (Tok.is(tok::annot_template_id)) { - TemplateIdAnnotation *TemplateId + TemplateIdAnnotation *TemplateId = static_cast(Tok.getAnnotationValue()); if (TemplateId->Kind == TNK_Type_template) { // A template-id that refers to a type was parsed into a @@ -1008,7 +1008,7 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { if (SS.isEmpty()) return Tok.isNot(tok::identifier) && Tok.isNot(tok::coloncolon); - + // A C++ scope specifier that isn't followed by a typename. // Push the current token back into the token stream (or revert it if it is // cached) and use an annotation scope token for current token. @@ -1030,7 +1030,7 @@ bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) { /// annotates C++ scope specifiers and template-ids. This returns /// true if the token was annotated or there was an error that could not be /// recovered from. -/// +/// /// Note that this routine emits an error if you call it with ::new or ::delete /// as the current tokens, so only call it in contexts where these are invalid. bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { diff --git a/clang/lib/Rewrite/DeltaTree.cpp b/clang/lib/Rewrite/DeltaTree.cpp index 5d51ddae08965a7d2fca721b6fe36b1612c02512..a94444b50c778d81da7d8b98904c86e704dca4b8 100644 --- a/clang/lib/Rewrite/DeltaTree.cpp +++ b/clang/lib/Rewrite/DeltaTree.cpp @@ -39,7 +39,7 @@ namespace { /// former and adds children pointers. Each node knows the full delta of all /// entries (recursively) contained inside of it, which allows us to get the /// full delta implied by a whole subtree in constant time. - + namespace { /// SourceDelta - As code in the original input buffer is added and deleted, /// SourceDelta records are used to keep track of how the input SourceLocation @@ -47,7 +47,7 @@ namespace { struct SourceDelta { unsigned FileLoc; int Delta; - + static SourceDelta get(unsigned Loc, int D) { SourceDelta Delta; Delta.FileLoc = Loc; @@ -71,36 +71,36 @@ namespace { /// class DeltaTreeNode { friend class DeltaTreeInteriorNode; - + /// WidthFactor - This controls the number of K/V slots held in the BTree: /// how wide it is. Each level of the BTree is guaranteed to have at least /// WidthFactor-1 K/V pairs (except the root) and may have at most /// 2*WidthFactor-1 K/V pairs. enum { WidthFactor = 8 }; - + /// Values - This tracks the SourceDelta's currently in this node. /// SourceDelta Values[2*WidthFactor-1]; - + /// NumValuesUsed - This tracks the number of values this node currently /// holds. unsigned char NumValuesUsed; - + /// IsLeaf - This is true if this is a leaf of the btree. If false, this is /// an interior node, and is actually an instance of DeltaTreeInteriorNode. bool IsLeaf; - + /// FullDelta - This is the full delta of all the values in this node and /// all children nodes. int FullDelta; public: DeltaTreeNode(bool isLeaf = true) : NumValuesUsed(0), IsLeaf(isLeaf), FullDelta(0) {} - + bool isLeaf() const { return IsLeaf; } int getFullDelta() const { return FullDelta; } bool isFull() const { return NumValuesUsed == 2*WidthFactor-1; } - + unsigned getNumValuesUsed() const { return NumValuesUsed; } const SourceDelta &getValue(unsigned i) const { assert(i < NumValuesUsed && "Invalid value #"); @@ -110,7 +110,7 @@ namespace { assert(i < NumValuesUsed && "Invalid value #"); return Values[i]; } - + /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into /// this node. If insertion is easy, do it and return false. Otherwise, /// split the node, populate InsertRes with info about the split, and return @@ -118,14 +118,14 @@ namespace { bool DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes); void DoSplit(InsertResult &InsertRes); - - + + /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a /// local walk over our contained deltas. void RecomputeFullDeltaLocally(); - + void Destroy(); - + static inline bool classof(const DeltaTreeNode *) { return true; } }; } // end anonymous namespace @@ -142,14 +142,14 @@ namespace { friend class DeltaTreeNode; public: DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {} - + DeltaTreeInteriorNode(DeltaTreeNode *FirstChild) : DeltaTreeNode(false /*nonleaf*/) { FullDelta = FirstChild->FullDelta; Children[0] = FirstChild; } - - DeltaTreeInteriorNode(const InsertResult &IR) + + DeltaTreeInteriorNode(const InsertResult &IR) : DeltaTreeNode(false /*nonleaf*/) { Children[0] = IR.LHS; Children[1] = IR.RHS; @@ -157,7 +157,7 @@ namespace { FullDelta = IR.LHS->getFullDelta()+IR.RHS->getFullDelta()+IR.Split.Delta; NumValuesUsed = 1; } - + const DeltaTreeNode *getChild(unsigned i) const { assert(i < getNumValuesUsed()+1 && "Invalid child"); return Children[i]; @@ -166,7 +166,7 @@ namespace { assert(i < getNumValuesUsed()+1 && "Invalid child"); return Children[i]; } - + static inline bool classof(const DeltaTreeInteriorNode *) { return true; } static inline bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); } }; @@ -197,16 +197,16 @@ void DeltaTreeNode::RecomputeFullDeltaLocally() { /// this node. If insertion is easy, do it and return false. Otherwise, /// split the node, populate InsertRes with info about the split, and return /// true. -bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, +bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes) { // Maintain full delta for this node. FullDelta += Delta; - + // Find the insertion point, the first delta whose index is >= FileIndex. unsigned i = 0, e = getNumValuesUsed(); while (i != e && FileIndex > getValue(i).FileLoc) ++i; - + // If we found an a record for exactly this file index, just merge this // value into the pre-existing record and finish early. if (i != e && getValue(i).FileLoc == FileIndex) { @@ -230,19 +230,19 @@ bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, ++NumValuesUsed; return false; } - + // Otherwise, if this is leaf is full, split the node at its median, insert // the value into one of the children, and return the result. assert(InsertRes && "No result location specified"); DoSplit(*InsertRes); - + if (InsertRes->Split.FileLoc > FileIndex) InsertRes->LHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/); else InsertRes->RHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/); return true; } - + // Otherwise, this is an interior node. Send the request down the tree. DeltaTreeInteriorNode *IN = cast(this); if (!IN->Children[i]->DoInsertion(FileIndex, Delta, InsertRes)) @@ -259,21 +259,21 @@ bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, (e-i)*sizeof(IN->Children[0])); IN->Children[i] = InsertRes->LHS; IN->Children[i+1] = InsertRes->RHS; - + if (e != i) memmove(&Values[i+1], &Values[i], (e-i)*sizeof(Values[0])); Values[i] = InsertRes->Split; ++NumValuesUsed; return false; } - + // Finally, if this interior node was full and a node is percolated up, split // ourself and return that up the chain. Start by saving all our info to // avoid having the split clobber it. IN->Children[i] = InsertRes->LHS; DeltaTreeNode *SubRHS = InsertRes->RHS; SourceDelta SubSplit = InsertRes->Split; - + // Do the split. DoSplit(*InsertRes); @@ -283,22 +283,22 @@ bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, InsertSide = cast(InsertRes->LHS); else InsertSide = cast(InsertRes->RHS); - - // We now have a non-empty interior node 'InsertSide' to insert + + // We now have a non-empty interior node 'InsertSide' to insert // SubRHS/SubSplit into. Find out where to insert SubSplit. - + // Find the insertion point, the first delta whose index is >SubSplit.FileLoc. i = 0; e = InsertSide->getNumValuesUsed(); while (i != e && SubSplit.FileLoc > InsertSide->getValue(i).FileLoc) ++i; - + // Now we know that i is the place to insert the split value into. Insert it // and the child right after it. if (i != e) memmove(&InsertSide->Children[i+2], &InsertSide->Children[i+1], (e-i)*sizeof(IN->Children[0])); InsertSide->Children[i+1] = SubRHS; - + if (e != i) memmove(&InsertSide->Values[i+1], &InsertSide->Values[i], (e-i)*sizeof(Values[0])); @@ -313,12 +313,12 @@ bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, /// Return the pieces in InsertRes. void DeltaTreeNode::DoSplit(InsertResult &InsertRes) { assert(isFull() && "Why split a non-full node?"); - + // Since this node is full, it contains 2*WidthFactor-1 values. We move // the first 'WidthFactor-1' values to the LHS child (which we leave in this // node), propagate one value up, and move the last 'WidthFactor-1' values // into the RHS child. - + // Create the new child node. DeltaTreeNode *NewNode; if (DeltaTreeInteriorNode *IN = dyn_cast(this)) { @@ -332,18 +332,18 @@ void DeltaTreeNode::DoSplit(InsertResult &InsertRes) { // Just create the new leaf node. NewNode = new DeltaTreeNode(); } - + // Move over the last 'WidthFactor-1' values from here to NewNode. memcpy(&NewNode->Values[0], &Values[WidthFactor], (WidthFactor-1)*sizeof(Values[0])); - + // Decrease the number of values in the two nodes. NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1; - + // Recompute the two nodes' full delta. NewNode->RecomputeFullDeltaLocally(); RecomputeFullDeltaLocally(); - + InsertRes.LHS = this; InsertRes.RHS = NewNode; InsertRes.Split = Values[WidthFactor-1]; @@ -374,7 +374,7 @@ static void VerifyTree(const DeltaTreeNode *N) { assert(FullDelta == N->getFullDelta()); return; } - + // Verify interior nodes: Ensure that FullDelta matches up and the // elements are in proper order and the children are in proper order. int FullDelta = 0; @@ -385,18 +385,18 @@ static void VerifyTree(const DeltaTreeNode *N) { assert(IN->getValue(i-1).FileLoc < IVal.FileLoc); FullDelta += IVal.Delta; FullDelta += IChild->getFullDelta(); - + // The largest value in child #i should be smaller than FileLoc. assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc < IVal.FileLoc); - + // The smallest value in child #i+1 should be larger than FileLoc. assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc); VerifyTree(IChild); } - + FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta(); - + assert(FullDelta == N->getFullDelta()); } #endif // VERIFY_TREE @@ -424,9 +424,9 @@ DeltaTree::~DeltaTree() { /// specified file index. int DeltaTree::getDeltaAt(unsigned FileIndex) const { const DeltaTreeNode *Node = getRoot(Root); - + int Result = 0; - + // Walk down the tree. while (1) { // For all nodes, include any local deltas before the specified file @@ -436,29 +436,29 @@ int DeltaTree::getDeltaAt(unsigned FileIndex) const { for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e; ++NumValsGreater) { const SourceDelta &Val = Node->getValue(NumValsGreater); - + if (Val.FileLoc >= FileIndex) break; Result += Val.Delta; } - + // If we have an interior node, include information about children and // recurse. Otherwise, if we have a leaf, we're done. const DeltaTreeInteriorNode *IN = dyn_cast(Node); if (!IN) return Result; - + // Include any children to the left of the values we skipped, all of // their deltas should be included as well. for (unsigned i = 0; i != NumValsGreater; ++i) Result += IN->getChild(i)->getFullDelta(); - + // If we found exactly the value we were looking for, break off the // search early. There is no need to search the RHS of the value for // partial results. if (NumValsGreater != Node->getNumValuesUsed() && Node->getValue(NumValsGreater).FileLoc == FileIndex) return Result+IN->getChild(NumValsGreater)->getFullDelta(); - + // Otherwise, traverse down the tree. The selected subtree may be // partially included in the range. Node = IN->getChild(NumValsGreater); @@ -472,12 +472,12 @@ int DeltaTree::getDeltaAt(unsigned FileIndex) const { void DeltaTree::AddDelta(unsigned FileIndex, int Delta) { assert(Delta && "Adding a noop?"); DeltaTreeNode *MyRoot = getRoot(Root); - + InsertResult InsertRes; if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) { Root = MyRoot = new DeltaTreeInteriorNode(InsertRes); } - + #ifdef VERIFY_TREE VerifyTree(MyRoot); #endif diff --git a/clang/lib/Rewrite/HTMLRewrite.cpp b/clang/lib/Rewrite/HTMLRewrite.cpp index 925fa5531283e513935eda28fbeccc7a92e394e1..7326890ded76725576759621daf94cfdd7774f69 100644 --- a/clang/lib/Rewrite/HTMLRewrite.cpp +++ b/clang/lib/Rewrite/HTMLRewrite.cpp @@ -39,10 +39,10 @@ void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E, unsigned BOffset = SM.getFileOffset(B); unsigned EOffset = SM.getFileOffset(E); - + // Include the whole end token in the range. EOffset += Lexer::MeasureTokenLength(E, R.getSourceMgr(), R.getLangOpts()); - + HighlightRange(R.getEditBuffer(FID), BOffset, EOffset, SM.getBufferData(FID).first, StartTag, EndTag); } @@ -55,11 +55,11 @@ void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E, // Insert the tag at the absolute start/end of the range. RB.InsertTextAfter(B, StartTag); RB.InsertTextBefore(E, EndTag); - + // Scan the range to see if there is a \r or \n. If so, and if the line is // not blank, insert tags on that line as well. bool HadOpenTag = true; - + unsigned LastNonWhiteSpace = B; for (unsigned i = B; i != E; ++i) { switch (BufferStart[i]) { @@ -69,7 +69,7 @@ void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E, // to insert a close tag at the first non-whitespace before the newline. if (HadOpenTag) RB.InsertTextBefore(LastNonWhiteSpace+1, EndTag); - + // Instead of inserting an open tag immediately after the newline, we // wait until we see a non-whitespace character. This prevents us from // inserting tags around blank lines, and also allows the open tag to @@ -83,14 +83,14 @@ void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E, case '\v': // Ignore whitespace. break; - + default: // If there is no tag open, do it now. if (!HadOpenTag) { RB.InsertTextAfter(i, StartTag); HadOpenTag = true; } - + // Remember this character. LastNonWhiteSpace = i; break; @@ -100,13 +100,13 @@ void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E, void html::EscapeText(Rewriter &R, FileID FID, bool EscapeSpaces, bool ReplaceTabs) { - + const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID); const char* C = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); - + assert (C <= FileEnd); - + RewriteBuffer &RB = R.getEditBuffer(FID); unsigned ColNo = 0; @@ -117,7 +117,7 @@ void html::EscapeText(Rewriter &R, FileID FID, case '\r': ColNo = 0; break; - + case ' ': if (EscapeSpaces) RB.ReplaceText(FilePos, 1, " "); @@ -127,7 +127,7 @@ void html::EscapeText(Rewriter &R, FileID FID, RB.ReplaceText(FilePos, 1, "


"); ColNo = 0; break; - + case '\t': { if (!ReplaceTabs) break; @@ -145,12 +145,12 @@ void html::EscapeText(Rewriter &R, FileID FID, RB.ReplaceText(FilePos, 1, "<"); ++ColNo; break; - + case '>': RB.ReplaceText(FilePos, 1, ">"); ++ColNo; break; - + case '&': RB.ReplaceText(FilePos, 1, "&"); ++ColNo; @@ -161,23 +161,23 @@ void html::EscapeText(Rewriter &R, FileID FID, std::string html::EscapeText(const std::string& s, bool EscapeSpaces, bool ReplaceTabs) { - + unsigned len = s.size(); std::string Str; llvm::raw_string_ostream os(Str); - + for (unsigned i = 0 ; i < len; ++i) { - + char c = s[i]; switch (c) { default: os << c; break; - + case ' ': if (EscapeSpaces) os << " "; else os << ' '; break; - + case '\t': if (ReplaceTabs) { if (EscapeSpaces) @@ -187,17 +187,17 @@ std::string html::EscapeText(const std::string& s, bool EscapeSpaces, for (unsigned i = 0; i < 4; ++i) os << " "; } - else + else os << c; - + break; - + case '<': os << "<"; break; case '>': os << ">"; break; case '&': os << "&"; break; } } - + return os.str(); } @@ -209,7 +209,7 @@ static void AddLineNumber(RewriteBuffer &RB, unsigned LineNo, OS << "" << LineNo << ""; - + if (B == E) { // Handle empty lines. OS << " "; RB.InsertTextBefore(B, OS.str()); @@ -226,44 +226,44 @@ void html::AddLineNumbers(Rewriter& R, FileID FID) { const char* FileEnd = Buf->getBufferEnd(); const char* C = FileBeg; RewriteBuffer &RB = R.getEditBuffer(FID); - + assert (C <= FileEnd); - + unsigned LineNo = 0; unsigned FilePos = 0; - - while (C != FileEnd) { - + + while (C != FileEnd) { + ++LineNo; unsigned LineStartPos = FilePos; unsigned LineEndPos = FileEnd - FileBeg; - + assert (FilePos <= LineEndPos); assert (C < FileEnd); - + // Scan until the newline (or end-of-file). - + while (C != FileEnd) { char c = *C; ++C; - + if (c == '\n') { LineEndPos = FilePos++; break; } - + ++FilePos; } - + AddLineNumber(RB, LineNo, LineStartPos, LineEndPos); } - + // Add one big table tag that surrounds all of the code. RB.InsertTextBefore(0, "\n"); RB.InsertTextAfter(FileEnd - FileBeg, "
"); } -void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, FileID FID, +void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, FileID FID, const char *title) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID); @@ -277,10 +277,10 @@ void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, FileID FID, llvm::raw_string_ostream os(s); os << "\n" // Use HTML 5 doctype "\n\n"; - + if (title) os << "" << html::EscapeText(title) << "\n"; - + os << "