17330f729Sjoerg //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // Hacks and fun related to the code rewriter.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg #include "clang/Rewrite/Frontend/ASTConsumers.h"
147330f729Sjoerg #include "clang/AST/AST.h"
157330f729Sjoerg #include "clang/AST/ASTConsumer.h"
167330f729Sjoerg #include "clang/AST/Attr.h"
177330f729Sjoerg #include "clang/AST/ParentMap.h"
187330f729Sjoerg #include "clang/Basic/CharInfo.h"
197330f729Sjoerg #include "clang/Basic/Diagnostic.h"
207330f729Sjoerg #include "clang/Basic/IdentifierTable.h"
217330f729Sjoerg #include "clang/Basic/SourceManager.h"
227330f729Sjoerg #include "clang/Config/config.h"
237330f729Sjoerg #include "clang/Lex/Lexer.h"
247330f729Sjoerg #include "clang/Rewrite/Core/Rewriter.h"
257330f729Sjoerg #include "llvm/ADT/DenseSet.h"
267330f729Sjoerg #include "llvm/ADT/SmallPtrSet.h"
277330f729Sjoerg #include "llvm/ADT/StringExtras.h"
287330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
297330f729Sjoerg #include "llvm/Support/raw_ostream.h"
307330f729Sjoerg #include <memory>
317330f729Sjoerg
327330f729Sjoerg #if CLANG_ENABLE_OBJC_REWRITER
337330f729Sjoerg
347330f729Sjoerg using namespace clang;
357330f729Sjoerg using llvm::utostr;
367330f729Sjoerg
377330f729Sjoerg namespace {
387330f729Sjoerg class RewriteObjC : public ASTConsumer {
397330f729Sjoerg protected:
407330f729Sjoerg enum {
417330f729Sjoerg BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
427330f729Sjoerg block, ... */
437330f729Sjoerg BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
447330f729Sjoerg BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
457330f729Sjoerg __block variable */
467330f729Sjoerg BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
477330f729Sjoerg helpers */
487330f729Sjoerg BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
497330f729Sjoerg support routines */
507330f729Sjoerg BLOCK_BYREF_CURRENT_MAX = 256
517330f729Sjoerg };
527330f729Sjoerg
537330f729Sjoerg enum {
547330f729Sjoerg BLOCK_NEEDS_FREE = (1 << 24),
557330f729Sjoerg BLOCK_HAS_COPY_DISPOSE = (1 << 25),
567330f729Sjoerg BLOCK_HAS_CXX_OBJ = (1 << 26),
577330f729Sjoerg BLOCK_IS_GC = (1 << 27),
587330f729Sjoerg BLOCK_IS_GLOBAL = (1 << 28),
597330f729Sjoerg BLOCK_HAS_DESCRIPTOR = (1 << 29)
607330f729Sjoerg };
617330f729Sjoerg static const int OBJC_ABI_VERSION = 7;
627330f729Sjoerg
637330f729Sjoerg Rewriter Rewrite;
647330f729Sjoerg DiagnosticsEngine &Diags;
657330f729Sjoerg const LangOptions &LangOpts;
667330f729Sjoerg ASTContext *Context;
677330f729Sjoerg SourceManager *SM;
687330f729Sjoerg TranslationUnitDecl *TUDecl;
697330f729Sjoerg FileID MainFileID;
707330f729Sjoerg const char *MainFileStart, *MainFileEnd;
717330f729Sjoerg Stmt *CurrentBody;
727330f729Sjoerg ParentMap *PropParentMap; // created lazily.
737330f729Sjoerg std::string InFileName;
747330f729Sjoerg std::unique_ptr<raw_ostream> OutFile;
757330f729Sjoerg std::string Preamble;
767330f729Sjoerg
777330f729Sjoerg TypeDecl *ProtocolTypeDecl;
787330f729Sjoerg VarDecl *GlobalVarDecl;
797330f729Sjoerg unsigned RewriteFailedDiag;
807330f729Sjoerg // ObjC string constant support.
817330f729Sjoerg unsigned NumObjCStringLiterals;
827330f729Sjoerg VarDecl *ConstantStringClassReference;
837330f729Sjoerg RecordDecl *NSStringRecord;
847330f729Sjoerg
857330f729Sjoerg // ObjC foreach break/continue generation support.
867330f729Sjoerg int BcLabelCount;
877330f729Sjoerg
887330f729Sjoerg unsigned TryFinallyContainsReturnDiag;
897330f729Sjoerg // Needed for super.
907330f729Sjoerg ObjCMethodDecl *CurMethodDef;
917330f729Sjoerg RecordDecl *SuperStructDecl;
927330f729Sjoerg RecordDecl *ConstantStringDecl;
937330f729Sjoerg
947330f729Sjoerg FunctionDecl *MsgSendFunctionDecl;
957330f729Sjoerg FunctionDecl *MsgSendSuperFunctionDecl;
967330f729Sjoerg FunctionDecl *MsgSendStretFunctionDecl;
977330f729Sjoerg FunctionDecl *MsgSendSuperStretFunctionDecl;
987330f729Sjoerg FunctionDecl *MsgSendFpretFunctionDecl;
997330f729Sjoerg FunctionDecl *GetClassFunctionDecl;
1007330f729Sjoerg FunctionDecl *GetMetaClassFunctionDecl;
1017330f729Sjoerg FunctionDecl *GetSuperClassFunctionDecl;
1027330f729Sjoerg FunctionDecl *SelGetUidFunctionDecl;
1037330f729Sjoerg FunctionDecl *CFStringFunctionDecl;
1047330f729Sjoerg FunctionDecl *SuperConstructorFunctionDecl;
1057330f729Sjoerg FunctionDecl *CurFunctionDef;
1067330f729Sjoerg FunctionDecl *CurFunctionDeclToDeclareForBlock;
1077330f729Sjoerg
1087330f729Sjoerg /* Misc. containers needed for meta-data rewrite. */
1097330f729Sjoerg SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
1107330f729Sjoerg SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
1117330f729Sjoerg llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
1127330f729Sjoerg llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
1137330f729Sjoerg llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
1147330f729Sjoerg llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
1157330f729Sjoerg SmallVector<Stmt *, 32> Stmts;
1167330f729Sjoerg SmallVector<int, 8> ObjCBcLabelNo;
1177330f729Sjoerg // Remember all the @protocol(<expr>) expressions.
1187330f729Sjoerg llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
1197330f729Sjoerg
1207330f729Sjoerg llvm::DenseSet<uint64_t> CopyDestroyCache;
1217330f729Sjoerg
1227330f729Sjoerg // Block expressions.
1237330f729Sjoerg SmallVector<BlockExpr *, 32> Blocks;
1247330f729Sjoerg SmallVector<int, 32> InnerDeclRefsCount;
1257330f729Sjoerg SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
1267330f729Sjoerg
1277330f729Sjoerg SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
1287330f729Sjoerg
1297330f729Sjoerg // Block related declarations.
1307330f729Sjoerg SmallVector<ValueDecl *, 8> BlockByCopyDecls;
1317330f729Sjoerg llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
1327330f729Sjoerg SmallVector<ValueDecl *, 8> BlockByRefDecls;
1337330f729Sjoerg llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
1347330f729Sjoerg llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
1357330f729Sjoerg llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
1367330f729Sjoerg llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
1377330f729Sjoerg
1387330f729Sjoerg llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
1397330f729Sjoerg
1407330f729Sjoerg // This maps an original source AST to it's rewritten form. This allows
1417330f729Sjoerg // us to avoid rewriting the same node twice (which is very uncommon).
1427330f729Sjoerg // This is needed to support some of the exotic property rewriting.
1437330f729Sjoerg llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
1447330f729Sjoerg
1457330f729Sjoerg // Needed for header files being rewritten
1467330f729Sjoerg bool IsHeader;
1477330f729Sjoerg bool SilenceRewriteMacroWarning;
1487330f729Sjoerg bool objc_impl_method;
1497330f729Sjoerg
1507330f729Sjoerg bool DisableReplaceStmt;
1517330f729Sjoerg class DisableReplaceStmtScope {
1527330f729Sjoerg RewriteObjC &R;
1537330f729Sjoerg bool SavedValue;
1547330f729Sjoerg
1557330f729Sjoerg public:
DisableReplaceStmtScope(RewriteObjC & R)1567330f729Sjoerg DisableReplaceStmtScope(RewriteObjC &R)
1577330f729Sjoerg : R(R), SavedValue(R.DisableReplaceStmt) {
1587330f729Sjoerg R.DisableReplaceStmt = true;
1597330f729Sjoerg }
1607330f729Sjoerg
~DisableReplaceStmtScope()1617330f729Sjoerg ~DisableReplaceStmtScope() {
1627330f729Sjoerg R.DisableReplaceStmt = SavedValue;
1637330f729Sjoerg }
1647330f729Sjoerg };
1657330f729Sjoerg
1667330f729Sjoerg void InitializeCommon(ASTContext &context);
1677330f729Sjoerg
1687330f729Sjoerg public:
1697330f729Sjoerg // Top Level Driver code.
HandleTopLevelDecl(DeclGroupRef D)1707330f729Sjoerg bool HandleTopLevelDecl(DeclGroupRef D) override {
1717330f729Sjoerg for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1727330f729Sjoerg if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
1737330f729Sjoerg if (!Class->isThisDeclarationADefinition()) {
1747330f729Sjoerg RewriteForwardClassDecl(D);
1757330f729Sjoerg break;
1767330f729Sjoerg }
1777330f729Sjoerg }
1787330f729Sjoerg
1797330f729Sjoerg if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
1807330f729Sjoerg if (!Proto->isThisDeclarationADefinition()) {
1817330f729Sjoerg RewriteForwardProtocolDecl(D);
1827330f729Sjoerg break;
1837330f729Sjoerg }
1847330f729Sjoerg }
1857330f729Sjoerg
1867330f729Sjoerg HandleTopLevelSingleDecl(*I);
1877330f729Sjoerg }
1887330f729Sjoerg return true;
1897330f729Sjoerg }
1907330f729Sjoerg
1917330f729Sjoerg void HandleTopLevelSingleDecl(Decl *D);
1927330f729Sjoerg void HandleDeclInMainFile(Decl *D);
1937330f729Sjoerg RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
1947330f729Sjoerg DiagnosticsEngine &D, const LangOptions &LOpts,
1957330f729Sjoerg bool silenceMacroWarn);
1967330f729Sjoerg
~RewriteObjC()1977330f729Sjoerg ~RewriteObjC() override {}
1987330f729Sjoerg
1997330f729Sjoerg void HandleTranslationUnit(ASTContext &C) override;
2007330f729Sjoerg
ReplaceStmt(Stmt * Old,Stmt * New)2017330f729Sjoerg void ReplaceStmt(Stmt *Old, Stmt *New) {
2027330f729Sjoerg ReplaceStmtWithRange(Old, New, Old->getSourceRange());
2037330f729Sjoerg }
2047330f729Sjoerg
ReplaceStmtWithRange(Stmt * Old,Stmt * New,SourceRange SrcRange)2057330f729Sjoerg void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
2067330f729Sjoerg assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
2077330f729Sjoerg
2087330f729Sjoerg Stmt *ReplacingStmt = ReplacedNodes[Old];
2097330f729Sjoerg if (ReplacingStmt)
2107330f729Sjoerg return; // We can't rewrite the same node twice.
2117330f729Sjoerg
2127330f729Sjoerg if (DisableReplaceStmt)
2137330f729Sjoerg return;
2147330f729Sjoerg
2157330f729Sjoerg // Measure the old text.
2167330f729Sjoerg int Size = Rewrite.getRangeSize(SrcRange);
2177330f729Sjoerg if (Size == -1) {
2187330f729Sjoerg Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
2197330f729Sjoerg << Old->getSourceRange();
2207330f729Sjoerg return;
2217330f729Sjoerg }
2227330f729Sjoerg // Get the new text.
2237330f729Sjoerg std::string SStr;
2247330f729Sjoerg llvm::raw_string_ostream S(SStr);
2257330f729Sjoerg New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
2267330f729Sjoerg const std::string &Str = S.str();
2277330f729Sjoerg
2287330f729Sjoerg // If replacement succeeded or warning disabled return with no warning.
2297330f729Sjoerg if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
2307330f729Sjoerg ReplacedNodes[Old] = New;
2317330f729Sjoerg return;
2327330f729Sjoerg }
2337330f729Sjoerg if (SilenceRewriteMacroWarning)
2347330f729Sjoerg return;
2357330f729Sjoerg Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
2367330f729Sjoerg << Old->getSourceRange();
2377330f729Sjoerg }
2387330f729Sjoerg
InsertText(SourceLocation Loc,StringRef Str,bool InsertAfter=true)2397330f729Sjoerg void InsertText(SourceLocation Loc, StringRef Str,
2407330f729Sjoerg bool InsertAfter = true) {
2417330f729Sjoerg // If insertion succeeded or warning disabled return with no warning.
2427330f729Sjoerg if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
2437330f729Sjoerg SilenceRewriteMacroWarning)
2447330f729Sjoerg return;
2457330f729Sjoerg
2467330f729Sjoerg Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
2477330f729Sjoerg }
2487330f729Sjoerg
ReplaceText(SourceLocation Start,unsigned OrigLength,StringRef Str)2497330f729Sjoerg void ReplaceText(SourceLocation Start, unsigned OrigLength,
2507330f729Sjoerg StringRef Str) {
2517330f729Sjoerg // If removal succeeded or warning disabled return with no warning.
2527330f729Sjoerg if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
2537330f729Sjoerg SilenceRewriteMacroWarning)
2547330f729Sjoerg return;
2557330f729Sjoerg
2567330f729Sjoerg Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
2577330f729Sjoerg }
2587330f729Sjoerg
2597330f729Sjoerg // Syntactic Rewriting.
2607330f729Sjoerg void RewriteRecordBody(RecordDecl *RD);
2617330f729Sjoerg void RewriteInclude();
2627330f729Sjoerg void RewriteForwardClassDecl(DeclGroupRef D);
2637330f729Sjoerg void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
2647330f729Sjoerg void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
2657330f729Sjoerg const std::string &typedefString);
2667330f729Sjoerg void RewriteImplementations();
2677330f729Sjoerg void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
2687330f729Sjoerg ObjCImplementationDecl *IMD,
2697330f729Sjoerg ObjCCategoryImplDecl *CID);
2707330f729Sjoerg void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
2717330f729Sjoerg void RewriteImplementationDecl(Decl *Dcl);
2727330f729Sjoerg void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
2737330f729Sjoerg ObjCMethodDecl *MDecl, std::string &ResultStr);
2747330f729Sjoerg void RewriteTypeIntoString(QualType T, std::string &ResultStr,
2757330f729Sjoerg const FunctionType *&FPRetType);
2767330f729Sjoerg void RewriteByRefString(std::string &ResultStr, const std::string &Name,
2777330f729Sjoerg ValueDecl *VD, bool def=false);
2787330f729Sjoerg void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
2797330f729Sjoerg void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
2807330f729Sjoerg void RewriteForwardProtocolDecl(DeclGroupRef D);
2817330f729Sjoerg void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
2827330f729Sjoerg void RewriteMethodDeclaration(ObjCMethodDecl *Method);
2837330f729Sjoerg void RewriteProperty(ObjCPropertyDecl *prop);
2847330f729Sjoerg void RewriteFunctionDecl(FunctionDecl *FD);
2857330f729Sjoerg void RewriteBlockPointerType(std::string& Str, QualType Type);
2867330f729Sjoerg void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
2877330f729Sjoerg void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
2887330f729Sjoerg void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
2897330f729Sjoerg void RewriteTypeOfDecl(VarDecl *VD);
2907330f729Sjoerg void RewriteObjCQualifiedInterfaceTypes(Expr *E);
2917330f729Sjoerg
2927330f729Sjoerg // Expression Rewriting.
2937330f729Sjoerg Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
2947330f729Sjoerg Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
2957330f729Sjoerg Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
2967330f729Sjoerg Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
2977330f729Sjoerg Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
2987330f729Sjoerg Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
2997330f729Sjoerg Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
3007330f729Sjoerg Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
3017330f729Sjoerg void RewriteTryReturnStmts(Stmt *S);
3027330f729Sjoerg void RewriteSyncReturnStmts(Stmt *S, std::string buf);
3037330f729Sjoerg Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
3047330f729Sjoerg Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
3057330f729Sjoerg Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
3067330f729Sjoerg Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
3077330f729Sjoerg SourceLocation OrigEnd);
3087330f729Sjoerg Stmt *RewriteBreakStmt(BreakStmt *S);
3097330f729Sjoerg Stmt *RewriteContinueStmt(ContinueStmt *S);
3107330f729Sjoerg void RewriteCastExpr(CStyleCastExpr *CE);
3117330f729Sjoerg
3127330f729Sjoerg // Block rewriting.
3137330f729Sjoerg void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
3147330f729Sjoerg
3157330f729Sjoerg // Block specific rewrite rules.
3167330f729Sjoerg void RewriteBlockPointerDecl(NamedDecl *VD);
3177330f729Sjoerg void RewriteByRefVar(VarDecl *VD);
3187330f729Sjoerg Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
3197330f729Sjoerg Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
3207330f729Sjoerg void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
3217330f729Sjoerg
3227330f729Sjoerg void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3237330f729Sjoerg std::string &Result);
3247330f729Sjoerg
3257330f729Sjoerg void Initialize(ASTContext &context) override = 0;
3267330f729Sjoerg
3277330f729Sjoerg // Metadata Rewriting.
3287330f729Sjoerg virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
3297330f729Sjoerg virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
3307330f729Sjoerg StringRef prefix,
3317330f729Sjoerg StringRef ClassName,
3327330f729Sjoerg std::string &Result) = 0;
3337330f729Sjoerg virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
3347330f729Sjoerg std::string &Result) = 0;
3357330f729Sjoerg virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
3367330f729Sjoerg StringRef prefix,
3377330f729Sjoerg StringRef ClassName,
3387330f729Sjoerg std::string &Result) = 0;
3397330f729Sjoerg virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
3407330f729Sjoerg std::string &Result) = 0;
3417330f729Sjoerg
3427330f729Sjoerg // Rewriting ivar access
3437330f729Sjoerg virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
3447330f729Sjoerg virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
3457330f729Sjoerg std::string &Result) = 0;
3467330f729Sjoerg
3477330f729Sjoerg // Misc. AST transformation routines. Sometimes they end up calling
3487330f729Sjoerg // rewriting routines on the new ASTs.
3497330f729Sjoerg CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
3507330f729Sjoerg ArrayRef<Expr *> Args,
3517330f729Sjoerg SourceLocation StartLoc=SourceLocation(),
3527330f729Sjoerg SourceLocation EndLoc=SourceLocation());
3537330f729Sjoerg CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3547330f729Sjoerg QualType msgSendType,
3557330f729Sjoerg QualType returnType,
3567330f729Sjoerg SmallVectorImpl<QualType> &ArgTypes,
3577330f729Sjoerg SmallVectorImpl<Expr*> &MsgExprs,
3587330f729Sjoerg ObjCMethodDecl *Method);
3597330f729Sjoerg Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
3607330f729Sjoerg SourceLocation StartLoc=SourceLocation(),
3617330f729Sjoerg SourceLocation EndLoc=SourceLocation());
3627330f729Sjoerg
3637330f729Sjoerg void SynthCountByEnumWithState(std::string &buf);
3647330f729Sjoerg void SynthMsgSendFunctionDecl();
3657330f729Sjoerg void SynthMsgSendSuperFunctionDecl();
3667330f729Sjoerg void SynthMsgSendStretFunctionDecl();
3677330f729Sjoerg void SynthMsgSendFpretFunctionDecl();
3687330f729Sjoerg void SynthMsgSendSuperStretFunctionDecl();
3697330f729Sjoerg void SynthGetClassFunctionDecl();
3707330f729Sjoerg void SynthGetMetaClassFunctionDecl();
3717330f729Sjoerg void SynthGetSuperClassFunctionDecl();
3727330f729Sjoerg void SynthSelGetUidFunctionDecl();
3737330f729Sjoerg void SynthSuperConstructorFunctionDecl();
3747330f729Sjoerg
3757330f729Sjoerg std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
3767330f729Sjoerg std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3777330f729Sjoerg StringRef funcName, std::string Tag);
3787330f729Sjoerg std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
3797330f729Sjoerg StringRef funcName, std::string Tag);
3807330f729Sjoerg std::string SynthesizeBlockImpl(BlockExpr *CE,
3817330f729Sjoerg std::string Tag, std::string Desc);
3827330f729Sjoerg std::string SynthesizeBlockDescriptor(std::string DescTag,
3837330f729Sjoerg std::string ImplTag,
3847330f729Sjoerg int i, StringRef funcName,
3857330f729Sjoerg unsigned hasCopy);
3867330f729Sjoerg Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
3877330f729Sjoerg void SynthesizeBlockLiterals(SourceLocation FunLocStart,
3887330f729Sjoerg StringRef FunName);
3897330f729Sjoerg FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
3907330f729Sjoerg Stmt *SynthBlockInitExpr(BlockExpr *Exp,
3917330f729Sjoerg const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
3927330f729Sjoerg
3937330f729Sjoerg // Misc. helper routines.
3947330f729Sjoerg QualType getProtocolType();
3957330f729Sjoerg void WarnAboutReturnGotoStmts(Stmt *S);
3967330f729Sjoerg void HasReturnStmts(Stmt *S, bool &hasReturns);
3977330f729Sjoerg void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
3987330f729Sjoerg void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
3997330f729Sjoerg void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
4007330f729Sjoerg
4017330f729Sjoerg bool IsDeclStmtInForeachHeader(DeclStmt *DS);
4027330f729Sjoerg void CollectBlockDeclRefInfo(BlockExpr *Exp);
4037330f729Sjoerg void GetBlockDeclRefExprs(Stmt *S);
4047330f729Sjoerg void GetInnerBlockDeclRefExprs(Stmt *S,
4057330f729Sjoerg SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4067330f729Sjoerg llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
4077330f729Sjoerg
4087330f729Sjoerg // We avoid calling Type::isBlockPointerType(), since it operates on the
4097330f729Sjoerg // canonical type. We only care if the top-level type is a closure pointer.
isTopLevelBlockPointerType(QualType T)4107330f729Sjoerg bool isTopLevelBlockPointerType(QualType T) {
4117330f729Sjoerg return isa<BlockPointerType>(T);
4127330f729Sjoerg }
4137330f729Sjoerg
4147330f729Sjoerg /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
4157330f729Sjoerg /// to a function pointer type and upon success, returns true; false
4167330f729Sjoerg /// otherwise.
convertBlockPointerToFunctionPointer(QualType & T)4177330f729Sjoerg bool convertBlockPointerToFunctionPointer(QualType &T) {
4187330f729Sjoerg if (isTopLevelBlockPointerType(T)) {
4197330f729Sjoerg const auto *BPT = T->castAs<BlockPointerType>();
4207330f729Sjoerg T = Context->getPointerType(BPT->getPointeeType());
4217330f729Sjoerg return true;
4227330f729Sjoerg }
4237330f729Sjoerg return false;
4247330f729Sjoerg }
4257330f729Sjoerg
4267330f729Sjoerg bool needToScanForQualifiers(QualType T);
4277330f729Sjoerg QualType getSuperStructType();
4287330f729Sjoerg QualType getConstantStringStructType();
4297330f729Sjoerg QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
4307330f729Sjoerg bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
4317330f729Sjoerg
convertToUnqualifiedObjCType(QualType & T)4327330f729Sjoerg void convertToUnqualifiedObjCType(QualType &T) {
4337330f729Sjoerg if (T->isObjCQualifiedIdType())
4347330f729Sjoerg T = Context->getObjCIdType();
4357330f729Sjoerg else if (T->isObjCQualifiedClassType())
4367330f729Sjoerg T = Context->getObjCClassType();
4377330f729Sjoerg else if (T->isObjCObjectPointerType() &&
4387330f729Sjoerg T->getPointeeType()->isObjCQualifiedInterfaceType()) {
4397330f729Sjoerg if (const ObjCObjectPointerType * OBJPT =
4407330f729Sjoerg T->getAsObjCInterfacePointerType()) {
4417330f729Sjoerg const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
4427330f729Sjoerg T = QualType(IFaceT, 0);
4437330f729Sjoerg T = Context->getPointerType(T);
4447330f729Sjoerg }
4457330f729Sjoerg }
4467330f729Sjoerg }
4477330f729Sjoerg
4487330f729Sjoerg // FIXME: This predicate seems like it would be useful to add to ASTContext.
isObjCType(QualType T)4497330f729Sjoerg bool isObjCType(QualType T) {
4507330f729Sjoerg if (!LangOpts.ObjC)
4517330f729Sjoerg return false;
4527330f729Sjoerg
4537330f729Sjoerg QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
4547330f729Sjoerg
4557330f729Sjoerg if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
4567330f729Sjoerg OCT == Context->getCanonicalType(Context->getObjCClassType()))
4577330f729Sjoerg return true;
4587330f729Sjoerg
4597330f729Sjoerg if (const PointerType *PT = OCT->getAs<PointerType>()) {
4607330f729Sjoerg if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
4617330f729Sjoerg PT->getPointeeType()->isObjCQualifiedIdType())
4627330f729Sjoerg return true;
4637330f729Sjoerg }
4647330f729Sjoerg return false;
4657330f729Sjoerg }
4667330f729Sjoerg bool PointerTypeTakesAnyBlockArguments(QualType QT);
4677330f729Sjoerg bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
4687330f729Sjoerg void GetExtentOfArgList(const char *Name, const char *&LParen,
4697330f729Sjoerg const char *&RParen);
4707330f729Sjoerg
QuoteDoublequotes(std::string & From,std::string & To)4717330f729Sjoerg void QuoteDoublequotes(std::string &From, std::string &To) {
4727330f729Sjoerg for (unsigned i = 0; i < From.length(); i++) {
4737330f729Sjoerg if (From[i] == '"')
4747330f729Sjoerg To += "\\\"";
4757330f729Sjoerg else
4767330f729Sjoerg To += From[i];
4777330f729Sjoerg }
4787330f729Sjoerg }
4797330f729Sjoerg
getSimpleFunctionType(QualType result,ArrayRef<QualType> args,bool variadic=false)4807330f729Sjoerg QualType getSimpleFunctionType(QualType result,
4817330f729Sjoerg ArrayRef<QualType> args,
4827330f729Sjoerg bool variadic = false) {
4837330f729Sjoerg if (result == Context->getObjCInstanceType())
4847330f729Sjoerg result = Context->getObjCIdType();
4857330f729Sjoerg FunctionProtoType::ExtProtoInfo fpi;
4867330f729Sjoerg fpi.Variadic = variadic;
4877330f729Sjoerg return Context->getFunctionType(result, args, fpi);
4887330f729Sjoerg }
4897330f729Sjoerg
4907330f729Sjoerg // Helper function: create a CStyleCastExpr with trivial type source info.
NoTypeInfoCStyleCastExpr(ASTContext * Ctx,QualType Ty,CastKind Kind,Expr * E)4917330f729Sjoerg CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
4927330f729Sjoerg CastKind Kind, Expr *E) {
4937330f729Sjoerg TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
4947330f729Sjoerg return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
495*e038c9c4Sjoerg FPOptionsOverride(), TInfo,
496*e038c9c4Sjoerg SourceLocation(), SourceLocation());
4977330f729Sjoerg }
4987330f729Sjoerg
getStringLiteral(StringRef Str)4997330f729Sjoerg StringLiteral *getStringLiteral(StringRef Str) {
5007330f729Sjoerg QualType StrType = Context->getConstantArrayType(
5017330f729Sjoerg Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
5027330f729Sjoerg ArrayType::Normal, 0);
5037330f729Sjoerg return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
5047330f729Sjoerg /*Pascal=*/false, StrType, SourceLocation());
5057330f729Sjoerg }
5067330f729Sjoerg };
5077330f729Sjoerg
5087330f729Sjoerg class RewriteObjCFragileABI : public RewriteObjC {
5097330f729Sjoerg public:
RewriteObjCFragileABI(std::string inFile,std::unique_ptr<raw_ostream> OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn)5107330f729Sjoerg RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
5117330f729Sjoerg DiagnosticsEngine &D, const LangOptions &LOpts,
5127330f729Sjoerg bool silenceMacroWarn)
5137330f729Sjoerg : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
5147330f729Sjoerg
~RewriteObjCFragileABI()5157330f729Sjoerg ~RewriteObjCFragileABI() override {}
5167330f729Sjoerg void Initialize(ASTContext &context) override;
5177330f729Sjoerg
5187330f729Sjoerg // Rewriting metadata
5197330f729Sjoerg template<typename MethodIterator>
5207330f729Sjoerg void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5217330f729Sjoerg MethodIterator MethodEnd,
5227330f729Sjoerg bool IsInstanceMethod,
5237330f729Sjoerg StringRef prefix,
5247330f729Sjoerg StringRef ClassName,
5257330f729Sjoerg std::string &Result);
5267330f729Sjoerg void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
5277330f729Sjoerg StringRef prefix, StringRef ClassName,
5287330f729Sjoerg std::string &Result) override;
5297330f729Sjoerg void RewriteObjCProtocolListMetaData(
5307330f729Sjoerg const ObjCList<ObjCProtocolDecl> &Prots,
5317330f729Sjoerg StringRef prefix, StringRef ClassName, std::string &Result) override;
5327330f729Sjoerg void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5337330f729Sjoerg std::string &Result) override;
5347330f729Sjoerg void RewriteMetaDataIntoBuffer(std::string &Result) override;
5357330f729Sjoerg void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
5367330f729Sjoerg std::string &Result) override;
5377330f729Sjoerg
5387330f729Sjoerg // Rewriting ivar
5397330f729Sjoerg void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5407330f729Sjoerg std::string &Result) override;
5417330f729Sjoerg Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
5427330f729Sjoerg };
5437330f729Sjoerg } // end anonymous namespace
5447330f729Sjoerg
RewriteBlocksInFunctionProtoType(QualType funcType,NamedDecl * D)5457330f729Sjoerg void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
5467330f729Sjoerg NamedDecl *D) {
5477330f729Sjoerg if (const FunctionProtoType *fproto
5487330f729Sjoerg = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
5497330f729Sjoerg for (const auto &I : fproto->param_types())
5507330f729Sjoerg if (isTopLevelBlockPointerType(I)) {
5517330f729Sjoerg // All the args are checked/rewritten. Don't call twice!
5527330f729Sjoerg RewriteBlockPointerDecl(D);
5537330f729Sjoerg break;
5547330f729Sjoerg }
5557330f729Sjoerg }
5567330f729Sjoerg }
5577330f729Sjoerg
CheckFunctionPointerDecl(QualType funcType,NamedDecl * ND)5587330f729Sjoerg void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
5597330f729Sjoerg const PointerType *PT = funcType->getAs<PointerType>();
5607330f729Sjoerg if (PT && PointerTypeTakesAnyBlockArguments(funcType))
5617330f729Sjoerg RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
5627330f729Sjoerg }
5637330f729Sjoerg
IsHeaderFile(const std::string & Filename)5647330f729Sjoerg static bool IsHeaderFile(const std::string &Filename) {
5657330f729Sjoerg std::string::size_type DotPos = Filename.rfind('.');
5667330f729Sjoerg
5677330f729Sjoerg if (DotPos == std::string::npos) {
5687330f729Sjoerg // no file extension
5697330f729Sjoerg return false;
5707330f729Sjoerg }
5717330f729Sjoerg
5727330f729Sjoerg std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
5737330f729Sjoerg // C header: .h
5747330f729Sjoerg // C++ header: .hh or .H;
5757330f729Sjoerg return Ext == "h" || Ext == "hh" || Ext == "H";
5767330f729Sjoerg }
5777330f729Sjoerg
RewriteObjC(std::string inFile,std::unique_ptr<raw_ostream> OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn)5787330f729Sjoerg RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
5797330f729Sjoerg DiagnosticsEngine &D, const LangOptions &LOpts,
5807330f729Sjoerg bool silenceMacroWarn)
5817330f729Sjoerg : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
5827330f729Sjoerg SilenceRewriteMacroWarning(silenceMacroWarn) {
5837330f729Sjoerg IsHeader = IsHeaderFile(inFile);
5847330f729Sjoerg RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
5857330f729Sjoerg "rewriting sub-expression within a macro (may not be correct)");
5867330f729Sjoerg TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
5877330f729Sjoerg DiagnosticsEngine::Warning,
5887330f729Sjoerg "rewriter doesn't support user-specified control flow semantics "
5897330f729Sjoerg "for @try/@finally (code may not execute properly)");
5907330f729Sjoerg }
5917330f729Sjoerg
5927330f729Sjoerg std::unique_ptr<ASTConsumer>
CreateObjCRewriter(const std::string & InFile,std::unique_ptr<raw_ostream> OS,DiagnosticsEngine & Diags,const LangOptions & LOpts,bool SilenceRewriteMacroWarning)5937330f729Sjoerg clang::CreateObjCRewriter(const std::string &InFile,
5947330f729Sjoerg std::unique_ptr<raw_ostream> OS,
5957330f729Sjoerg DiagnosticsEngine &Diags, const LangOptions &LOpts,
5967330f729Sjoerg bool SilenceRewriteMacroWarning) {
5977330f729Sjoerg return std::make_unique<RewriteObjCFragileABI>(
5987330f729Sjoerg InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
5997330f729Sjoerg }
6007330f729Sjoerg
InitializeCommon(ASTContext & context)6017330f729Sjoerg void RewriteObjC::InitializeCommon(ASTContext &context) {
6027330f729Sjoerg Context = &context;
6037330f729Sjoerg SM = &Context->getSourceManager();
6047330f729Sjoerg TUDecl = Context->getTranslationUnitDecl();
6057330f729Sjoerg MsgSendFunctionDecl = nullptr;
6067330f729Sjoerg MsgSendSuperFunctionDecl = nullptr;
6077330f729Sjoerg MsgSendStretFunctionDecl = nullptr;
6087330f729Sjoerg MsgSendSuperStretFunctionDecl = nullptr;
6097330f729Sjoerg MsgSendFpretFunctionDecl = nullptr;
6107330f729Sjoerg GetClassFunctionDecl = nullptr;
6117330f729Sjoerg GetMetaClassFunctionDecl = nullptr;
6127330f729Sjoerg GetSuperClassFunctionDecl = nullptr;
6137330f729Sjoerg SelGetUidFunctionDecl = nullptr;
6147330f729Sjoerg CFStringFunctionDecl = nullptr;
6157330f729Sjoerg ConstantStringClassReference = nullptr;
6167330f729Sjoerg NSStringRecord = nullptr;
6177330f729Sjoerg CurMethodDef = nullptr;
6187330f729Sjoerg CurFunctionDef = nullptr;
6197330f729Sjoerg CurFunctionDeclToDeclareForBlock = nullptr;
6207330f729Sjoerg GlobalVarDecl = nullptr;
6217330f729Sjoerg SuperStructDecl = nullptr;
6227330f729Sjoerg ProtocolTypeDecl = nullptr;
6237330f729Sjoerg ConstantStringDecl = nullptr;
6247330f729Sjoerg BcLabelCount = 0;
6257330f729Sjoerg SuperConstructorFunctionDecl = nullptr;
6267330f729Sjoerg NumObjCStringLiterals = 0;
6277330f729Sjoerg PropParentMap = nullptr;
6287330f729Sjoerg CurrentBody = nullptr;
6297330f729Sjoerg DisableReplaceStmt = false;
6307330f729Sjoerg objc_impl_method = false;
6317330f729Sjoerg
6327330f729Sjoerg // Get the ID and start/end of the main file.
6337330f729Sjoerg MainFileID = SM->getMainFileID();
634*e038c9c4Sjoerg llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
635*e038c9c4Sjoerg MainFileStart = MainBuf.getBufferStart();
636*e038c9c4Sjoerg MainFileEnd = MainBuf.getBufferEnd();
6377330f729Sjoerg
6387330f729Sjoerg Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
6397330f729Sjoerg }
6407330f729Sjoerg
6417330f729Sjoerg //===----------------------------------------------------------------------===//
6427330f729Sjoerg // Top Level Driver Code
6437330f729Sjoerg //===----------------------------------------------------------------------===//
6447330f729Sjoerg
HandleTopLevelSingleDecl(Decl * D)6457330f729Sjoerg void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
6467330f729Sjoerg if (Diags.hasErrorOccurred())
6477330f729Sjoerg return;
6487330f729Sjoerg
6497330f729Sjoerg // Two cases: either the decl could be in the main file, or it could be in a
6507330f729Sjoerg // #included file. If the former, rewrite it now. If the later, check to see
6517330f729Sjoerg // if we rewrote the #include/#import.
6527330f729Sjoerg SourceLocation Loc = D->getLocation();
6537330f729Sjoerg Loc = SM->getExpansionLoc(Loc);
6547330f729Sjoerg
6557330f729Sjoerg // If this is for a builtin, ignore it.
6567330f729Sjoerg if (Loc.isInvalid()) return;
6577330f729Sjoerg
6587330f729Sjoerg // Look for built-in declarations that we need to refer during the rewrite.
6597330f729Sjoerg if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6607330f729Sjoerg RewriteFunctionDecl(FD);
6617330f729Sjoerg } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
6627330f729Sjoerg // declared in <Foundation/NSString.h>
6637330f729Sjoerg if (FVD->getName() == "_NSConstantStringClassReference") {
6647330f729Sjoerg ConstantStringClassReference = FVD;
6657330f729Sjoerg return;
6667330f729Sjoerg }
6677330f729Sjoerg } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
6687330f729Sjoerg if (ID->isThisDeclarationADefinition())
6697330f729Sjoerg RewriteInterfaceDecl(ID);
6707330f729Sjoerg } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
6717330f729Sjoerg RewriteCategoryDecl(CD);
6727330f729Sjoerg } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
6737330f729Sjoerg if (PD->isThisDeclarationADefinition())
6747330f729Sjoerg RewriteProtocolDecl(PD);
6757330f729Sjoerg } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
6767330f729Sjoerg // Recurse into linkage specifications
6777330f729Sjoerg for (DeclContext::decl_iterator DI = LSD->decls_begin(),
6787330f729Sjoerg DIEnd = LSD->decls_end();
6797330f729Sjoerg DI != DIEnd; ) {
6807330f729Sjoerg if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
6817330f729Sjoerg if (!IFace->isThisDeclarationADefinition()) {
6827330f729Sjoerg SmallVector<Decl *, 8> DG;
6837330f729Sjoerg SourceLocation StartLoc = IFace->getBeginLoc();
6847330f729Sjoerg do {
6857330f729Sjoerg if (isa<ObjCInterfaceDecl>(*DI) &&
6867330f729Sjoerg !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
6877330f729Sjoerg StartLoc == (*DI)->getBeginLoc())
6887330f729Sjoerg DG.push_back(*DI);
6897330f729Sjoerg else
6907330f729Sjoerg break;
6917330f729Sjoerg
6927330f729Sjoerg ++DI;
6937330f729Sjoerg } while (DI != DIEnd);
6947330f729Sjoerg RewriteForwardClassDecl(DG);
6957330f729Sjoerg continue;
6967330f729Sjoerg }
6977330f729Sjoerg }
6987330f729Sjoerg
6997330f729Sjoerg if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
7007330f729Sjoerg if (!Proto->isThisDeclarationADefinition()) {
7017330f729Sjoerg SmallVector<Decl *, 8> DG;
7027330f729Sjoerg SourceLocation StartLoc = Proto->getBeginLoc();
7037330f729Sjoerg do {
7047330f729Sjoerg if (isa<ObjCProtocolDecl>(*DI) &&
7057330f729Sjoerg !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
7067330f729Sjoerg StartLoc == (*DI)->getBeginLoc())
7077330f729Sjoerg DG.push_back(*DI);
7087330f729Sjoerg else
7097330f729Sjoerg break;
7107330f729Sjoerg
7117330f729Sjoerg ++DI;
7127330f729Sjoerg } while (DI != DIEnd);
7137330f729Sjoerg RewriteForwardProtocolDecl(DG);
7147330f729Sjoerg continue;
7157330f729Sjoerg }
7167330f729Sjoerg }
7177330f729Sjoerg
7187330f729Sjoerg HandleTopLevelSingleDecl(*DI);
7197330f729Sjoerg ++DI;
7207330f729Sjoerg }
7217330f729Sjoerg }
7227330f729Sjoerg // If we have a decl in the main file, see if we should rewrite it.
7237330f729Sjoerg if (SM->isWrittenInMainFile(Loc))
7247330f729Sjoerg return HandleDeclInMainFile(D);
7257330f729Sjoerg }
7267330f729Sjoerg
7277330f729Sjoerg //===----------------------------------------------------------------------===//
7287330f729Sjoerg // Syntactic (non-AST) Rewriting Code
7297330f729Sjoerg //===----------------------------------------------------------------------===//
7307330f729Sjoerg
RewriteInclude()7317330f729Sjoerg void RewriteObjC::RewriteInclude() {
7327330f729Sjoerg SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
7337330f729Sjoerg StringRef MainBuf = SM->getBufferData(MainFileID);
7347330f729Sjoerg const char *MainBufStart = MainBuf.begin();
7357330f729Sjoerg const char *MainBufEnd = MainBuf.end();
7367330f729Sjoerg size_t ImportLen = strlen("import");
7377330f729Sjoerg
7387330f729Sjoerg // Loop over the whole file, looking for includes.
7397330f729Sjoerg for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
7407330f729Sjoerg if (*BufPtr == '#') {
7417330f729Sjoerg if (++BufPtr == MainBufEnd)
7427330f729Sjoerg return;
7437330f729Sjoerg while (*BufPtr == ' ' || *BufPtr == '\t')
7447330f729Sjoerg if (++BufPtr == MainBufEnd)
7457330f729Sjoerg return;
7467330f729Sjoerg if (!strncmp(BufPtr, "import", ImportLen)) {
7477330f729Sjoerg // replace import with include
7487330f729Sjoerg SourceLocation ImportLoc =
7497330f729Sjoerg LocStart.getLocWithOffset(BufPtr-MainBufStart);
7507330f729Sjoerg ReplaceText(ImportLoc, ImportLen, "include");
7517330f729Sjoerg BufPtr += ImportLen;
7527330f729Sjoerg }
7537330f729Sjoerg }
7547330f729Sjoerg }
7557330f729Sjoerg }
7567330f729Sjoerg
getIvarAccessString(ObjCIvarDecl * OID)7577330f729Sjoerg static std::string getIvarAccessString(ObjCIvarDecl *OID) {
7587330f729Sjoerg const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
7597330f729Sjoerg std::string S;
7607330f729Sjoerg S = "((struct ";
7617330f729Sjoerg S += ClassDecl->getIdentifier()->getName();
7627330f729Sjoerg S += "_IMPL *)self)->";
7637330f729Sjoerg S += OID->getName();
7647330f729Sjoerg return S;
7657330f729Sjoerg }
7667330f729Sjoerg
RewritePropertyImplDecl(ObjCPropertyImplDecl * PID,ObjCImplementationDecl * IMD,ObjCCategoryImplDecl * CID)7677330f729Sjoerg void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
7687330f729Sjoerg ObjCImplementationDecl *IMD,
7697330f729Sjoerg ObjCCategoryImplDecl *CID) {
7707330f729Sjoerg static bool objcGetPropertyDefined = false;
7717330f729Sjoerg static bool objcSetPropertyDefined = false;
7727330f729Sjoerg SourceLocation startLoc = PID->getBeginLoc();
7737330f729Sjoerg InsertText(startLoc, "// ");
7747330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
7757330f729Sjoerg assert((*startBuf == '@') && "bogus @synthesize location");
7767330f729Sjoerg const char *semiBuf = strchr(startBuf, ';');
7777330f729Sjoerg assert((*semiBuf == ';') && "@synthesize: can't find ';'");
7787330f729Sjoerg SourceLocation onePastSemiLoc =
7797330f729Sjoerg startLoc.getLocWithOffset(semiBuf-startBuf+1);
7807330f729Sjoerg
7817330f729Sjoerg if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7827330f729Sjoerg return; // FIXME: is this correct?
7837330f729Sjoerg
7847330f729Sjoerg // Generate the 'getter' function.
7857330f729Sjoerg ObjCPropertyDecl *PD = PID->getPropertyDecl();
7867330f729Sjoerg ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
7877330f729Sjoerg
7887330f729Sjoerg if (!OID)
7897330f729Sjoerg return;
790*e038c9c4Sjoerg
7917330f729Sjoerg unsigned Attributes = PD->getPropertyAttributes();
792*e038c9c4Sjoerg if (PID->getGetterMethodDecl() && !PID->getGetterMethodDecl()->isDefined()) {
793*e038c9c4Sjoerg bool GenGetProperty =
794*e038c9c4Sjoerg !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
795*e038c9c4Sjoerg (Attributes & (ObjCPropertyAttribute::kind_retain |
796*e038c9c4Sjoerg ObjCPropertyAttribute::kind_copy));
7977330f729Sjoerg std::string Getr;
7987330f729Sjoerg if (GenGetProperty && !objcGetPropertyDefined) {
7997330f729Sjoerg objcGetPropertyDefined = true;
8007330f729Sjoerg // FIXME. Is this attribute correct in all cases?
8017330f729Sjoerg Getr = "\nextern \"C\" __declspec(dllimport) "
8027330f729Sjoerg "id objc_getProperty(id, SEL, long, bool);\n";
8037330f729Sjoerg }
8047330f729Sjoerg RewriteObjCMethodDecl(OID->getContainingInterface(),
805*e038c9c4Sjoerg PID->getGetterMethodDecl(), Getr);
8067330f729Sjoerg Getr += "{ ";
8077330f729Sjoerg // Synthesize an explicit cast to gain access to the ivar.
8087330f729Sjoerg // See objc-act.c:objc_synthesize_new_getter() for details.
8097330f729Sjoerg if (GenGetProperty) {
8107330f729Sjoerg // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
8117330f729Sjoerg Getr += "typedef ";
8127330f729Sjoerg const FunctionType *FPRetType = nullptr;
813*e038c9c4Sjoerg RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
8147330f729Sjoerg FPRetType);
8157330f729Sjoerg Getr += " _TYPE";
8167330f729Sjoerg if (FPRetType) {
8177330f729Sjoerg Getr += ")"; // close the precedence "scope" for "*".
8187330f729Sjoerg
8197330f729Sjoerg // Now, emit the argument types (if any).
8207330f729Sjoerg if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
8217330f729Sjoerg Getr += "(";
8227330f729Sjoerg for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
8237330f729Sjoerg if (i) Getr += ", ";
8247330f729Sjoerg std::string ParamStr =
8257330f729Sjoerg FT->getParamType(i).getAsString(Context->getPrintingPolicy());
8267330f729Sjoerg Getr += ParamStr;
8277330f729Sjoerg }
8287330f729Sjoerg if (FT->isVariadic()) {
8297330f729Sjoerg if (FT->getNumParams())
8307330f729Sjoerg Getr += ", ";
8317330f729Sjoerg Getr += "...";
8327330f729Sjoerg }
8337330f729Sjoerg Getr += ")";
8347330f729Sjoerg } else
8357330f729Sjoerg Getr += "()";
8367330f729Sjoerg }
8377330f729Sjoerg Getr += ";\n";
8387330f729Sjoerg Getr += "return (_TYPE)";
8397330f729Sjoerg Getr += "objc_getProperty(self, _cmd, ";
8407330f729Sjoerg RewriteIvarOffsetComputation(OID, Getr);
8417330f729Sjoerg Getr += ", 1)";
8427330f729Sjoerg }
8437330f729Sjoerg else
8447330f729Sjoerg Getr += "return " + getIvarAccessString(OID);
8457330f729Sjoerg Getr += "; }";
8467330f729Sjoerg InsertText(onePastSemiLoc, Getr);
8477330f729Sjoerg }
8487330f729Sjoerg
849*e038c9c4Sjoerg if (PD->isReadOnly() || !PID->getSetterMethodDecl() ||
850*e038c9c4Sjoerg PID->getSetterMethodDecl()->isDefined())
8517330f729Sjoerg return;
8527330f729Sjoerg
8537330f729Sjoerg // Generate the 'setter' function.
8547330f729Sjoerg std::string Setr;
855*e038c9c4Sjoerg bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
856*e038c9c4Sjoerg ObjCPropertyAttribute::kind_copy);
8577330f729Sjoerg if (GenSetProperty && !objcSetPropertyDefined) {
8587330f729Sjoerg objcSetPropertyDefined = true;
8597330f729Sjoerg // FIXME. Is this attribute correct in all cases?
8607330f729Sjoerg Setr = "\nextern \"C\" __declspec(dllimport) "
8617330f729Sjoerg "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
8627330f729Sjoerg }
8637330f729Sjoerg
8647330f729Sjoerg RewriteObjCMethodDecl(OID->getContainingInterface(),
865*e038c9c4Sjoerg PID->getSetterMethodDecl(), Setr);
8667330f729Sjoerg Setr += "{ ";
8677330f729Sjoerg // Synthesize an explicit cast to initialize the ivar.
8687330f729Sjoerg // See objc-act.c:objc_synthesize_new_setter() for details.
8697330f729Sjoerg if (GenSetProperty) {
8707330f729Sjoerg Setr += "objc_setProperty (self, _cmd, ";
8717330f729Sjoerg RewriteIvarOffsetComputation(OID, Setr);
8727330f729Sjoerg Setr += ", (id)";
8737330f729Sjoerg Setr += PD->getName();
8747330f729Sjoerg Setr += ", ";
875*e038c9c4Sjoerg if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
8767330f729Sjoerg Setr += "0, ";
8777330f729Sjoerg else
8787330f729Sjoerg Setr += "1, ";
879*e038c9c4Sjoerg if (Attributes & ObjCPropertyAttribute::kind_copy)
8807330f729Sjoerg Setr += "1)";
8817330f729Sjoerg else
8827330f729Sjoerg Setr += "0)";
8837330f729Sjoerg }
8847330f729Sjoerg else {
8857330f729Sjoerg Setr += getIvarAccessString(OID) + " = ";
8867330f729Sjoerg Setr += PD->getName();
8877330f729Sjoerg }
8887330f729Sjoerg Setr += "; }";
8897330f729Sjoerg InsertText(onePastSemiLoc, Setr);
8907330f729Sjoerg }
8917330f729Sjoerg
RewriteOneForwardClassDecl(ObjCInterfaceDecl * ForwardDecl,std::string & typedefString)8927330f729Sjoerg static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
8937330f729Sjoerg std::string &typedefString) {
8947330f729Sjoerg typedefString += "#ifndef _REWRITER_typedef_";
8957330f729Sjoerg typedefString += ForwardDecl->getNameAsString();
8967330f729Sjoerg typedefString += "\n";
8977330f729Sjoerg typedefString += "#define _REWRITER_typedef_";
8987330f729Sjoerg typedefString += ForwardDecl->getNameAsString();
8997330f729Sjoerg typedefString += "\n";
9007330f729Sjoerg typedefString += "typedef struct objc_object ";
9017330f729Sjoerg typedefString += ForwardDecl->getNameAsString();
9027330f729Sjoerg typedefString += ";\n#endif\n";
9037330f729Sjoerg }
9047330f729Sjoerg
RewriteForwardClassEpilogue(ObjCInterfaceDecl * ClassDecl,const std::string & typedefString)9057330f729Sjoerg void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
9067330f729Sjoerg const std::string &typedefString) {
9077330f729Sjoerg SourceLocation startLoc = ClassDecl->getBeginLoc();
9087330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
9097330f729Sjoerg const char *semiPtr = strchr(startBuf, ';');
9107330f729Sjoerg // Replace the @class with typedefs corresponding to the classes.
9117330f729Sjoerg ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
9127330f729Sjoerg }
9137330f729Sjoerg
RewriteForwardClassDecl(DeclGroupRef D)9147330f729Sjoerg void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
9157330f729Sjoerg std::string typedefString;
9167330f729Sjoerg for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
9177330f729Sjoerg ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
9187330f729Sjoerg if (I == D.begin()) {
9197330f729Sjoerg // Translate to typedef's that forward reference structs with the same name
9207330f729Sjoerg // as the class. As a convenience, we include the original declaration
9217330f729Sjoerg // as a comment.
9227330f729Sjoerg typedefString += "// @class ";
9237330f729Sjoerg typedefString += ForwardDecl->getNameAsString();
9247330f729Sjoerg typedefString += ";\n";
9257330f729Sjoerg }
9267330f729Sjoerg RewriteOneForwardClassDecl(ForwardDecl, typedefString);
9277330f729Sjoerg }
9287330f729Sjoerg DeclGroupRef::iterator I = D.begin();
9297330f729Sjoerg RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
9307330f729Sjoerg }
9317330f729Sjoerg
RewriteForwardClassDecl(const SmallVectorImpl<Decl * > & D)9327330f729Sjoerg void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
9337330f729Sjoerg std::string typedefString;
9347330f729Sjoerg for (unsigned i = 0; i < D.size(); i++) {
9357330f729Sjoerg ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
9367330f729Sjoerg if (i == 0) {
9377330f729Sjoerg typedefString += "// @class ";
9387330f729Sjoerg typedefString += ForwardDecl->getNameAsString();
9397330f729Sjoerg typedefString += ";\n";
9407330f729Sjoerg }
9417330f729Sjoerg RewriteOneForwardClassDecl(ForwardDecl, typedefString);
9427330f729Sjoerg }
9437330f729Sjoerg RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
9447330f729Sjoerg }
9457330f729Sjoerg
RewriteMethodDeclaration(ObjCMethodDecl * Method)9467330f729Sjoerg void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
9477330f729Sjoerg // When method is a synthesized one, such as a getter/setter there is
9487330f729Sjoerg // nothing to rewrite.
9497330f729Sjoerg if (Method->isImplicit())
9507330f729Sjoerg return;
9517330f729Sjoerg SourceLocation LocStart = Method->getBeginLoc();
9527330f729Sjoerg SourceLocation LocEnd = Method->getEndLoc();
9537330f729Sjoerg
9547330f729Sjoerg if (SM->getExpansionLineNumber(LocEnd) >
9557330f729Sjoerg SM->getExpansionLineNumber(LocStart)) {
9567330f729Sjoerg InsertText(LocStart, "#if 0\n");
9577330f729Sjoerg ReplaceText(LocEnd, 1, ";\n#endif\n");
9587330f729Sjoerg } else {
9597330f729Sjoerg InsertText(LocStart, "// ");
9607330f729Sjoerg }
9617330f729Sjoerg }
9627330f729Sjoerg
RewriteProperty(ObjCPropertyDecl * prop)9637330f729Sjoerg void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
9647330f729Sjoerg SourceLocation Loc = prop->getAtLoc();
9657330f729Sjoerg
9667330f729Sjoerg ReplaceText(Loc, 0, "// ");
9677330f729Sjoerg // FIXME: handle properties that are declared across multiple lines.
9687330f729Sjoerg }
9697330f729Sjoerg
RewriteCategoryDecl(ObjCCategoryDecl * CatDecl)9707330f729Sjoerg void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
9717330f729Sjoerg SourceLocation LocStart = CatDecl->getBeginLoc();
9727330f729Sjoerg
9737330f729Sjoerg // FIXME: handle category headers that are declared across multiple lines.
9747330f729Sjoerg ReplaceText(LocStart, 0, "// ");
9757330f729Sjoerg
9767330f729Sjoerg for (auto *I : CatDecl->instance_properties())
9777330f729Sjoerg RewriteProperty(I);
9787330f729Sjoerg for (auto *I : CatDecl->instance_methods())
9797330f729Sjoerg RewriteMethodDeclaration(I);
9807330f729Sjoerg for (auto *I : CatDecl->class_methods())
9817330f729Sjoerg RewriteMethodDeclaration(I);
9827330f729Sjoerg
9837330f729Sjoerg // Lastly, comment out the @end.
9847330f729Sjoerg ReplaceText(CatDecl->getAtEndRange().getBegin(),
9857330f729Sjoerg strlen("@end"), "/* @end */");
9867330f729Sjoerg }
9877330f729Sjoerg
RewriteProtocolDecl(ObjCProtocolDecl * PDecl)9887330f729Sjoerg void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
9897330f729Sjoerg SourceLocation LocStart = PDecl->getBeginLoc();
9907330f729Sjoerg assert(PDecl->isThisDeclarationADefinition());
9917330f729Sjoerg
9927330f729Sjoerg // FIXME: handle protocol headers that are declared across multiple lines.
9937330f729Sjoerg ReplaceText(LocStart, 0, "// ");
9947330f729Sjoerg
9957330f729Sjoerg for (auto *I : PDecl->instance_methods())
9967330f729Sjoerg RewriteMethodDeclaration(I);
9977330f729Sjoerg for (auto *I : PDecl->class_methods())
9987330f729Sjoerg RewriteMethodDeclaration(I);
9997330f729Sjoerg for (auto *I : PDecl->instance_properties())
10007330f729Sjoerg RewriteProperty(I);
10017330f729Sjoerg
10027330f729Sjoerg // Lastly, comment out the @end.
10037330f729Sjoerg SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
10047330f729Sjoerg ReplaceText(LocEnd, strlen("@end"), "/* @end */");
10057330f729Sjoerg
10067330f729Sjoerg // Must comment out @optional/@required
10077330f729Sjoerg const char *startBuf = SM->getCharacterData(LocStart);
10087330f729Sjoerg const char *endBuf = SM->getCharacterData(LocEnd);
10097330f729Sjoerg for (const char *p = startBuf; p < endBuf; p++) {
10107330f729Sjoerg if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
10117330f729Sjoerg SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
10127330f729Sjoerg ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
10137330f729Sjoerg
10147330f729Sjoerg }
10157330f729Sjoerg else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
10167330f729Sjoerg SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
10177330f729Sjoerg ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
10187330f729Sjoerg
10197330f729Sjoerg }
10207330f729Sjoerg }
10217330f729Sjoerg }
10227330f729Sjoerg
RewriteForwardProtocolDecl(DeclGroupRef D)10237330f729Sjoerg void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
10247330f729Sjoerg SourceLocation LocStart = (*D.begin())->getBeginLoc();
10257330f729Sjoerg if (LocStart.isInvalid())
10267330f729Sjoerg llvm_unreachable("Invalid SourceLocation");
10277330f729Sjoerg // FIXME: handle forward protocol that are declared across multiple lines.
10287330f729Sjoerg ReplaceText(LocStart, 0, "// ");
10297330f729Sjoerg }
10307330f729Sjoerg
10317330f729Sjoerg void
RewriteForwardProtocolDecl(const SmallVectorImpl<Decl * > & DG)10327330f729Sjoerg RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
10337330f729Sjoerg SourceLocation LocStart = DG[0]->getBeginLoc();
10347330f729Sjoerg if (LocStart.isInvalid())
10357330f729Sjoerg llvm_unreachable("Invalid SourceLocation");
10367330f729Sjoerg // FIXME: handle forward protocol that are declared across multiple lines.
10377330f729Sjoerg ReplaceText(LocStart, 0, "// ");
10387330f729Sjoerg }
10397330f729Sjoerg
RewriteTypeIntoString(QualType T,std::string & ResultStr,const FunctionType * & FPRetType)10407330f729Sjoerg void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
10417330f729Sjoerg const FunctionType *&FPRetType) {
10427330f729Sjoerg if (T->isObjCQualifiedIdType())
10437330f729Sjoerg ResultStr += "id";
10447330f729Sjoerg else if (T->isFunctionPointerType() ||
10457330f729Sjoerg T->isBlockPointerType()) {
10467330f729Sjoerg // needs special handling, since pointer-to-functions have special
10477330f729Sjoerg // syntax (where a decaration models use).
10487330f729Sjoerg QualType retType = T;
10497330f729Sjoerg QualType PointeeTy;
10507330f729Sjoerg if (const PointerType* PT = retType->getAs<PointerType>())
10517330f729Sjoerg PointeeTy = PT->getPointeeType();
10527330f729Sjoerg else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
10537330f729Sjoerg PointeeTy = BPT->getPointeeType();
10547330f729Sjoerg if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
10557330f729Sjoerg ResultStr +=
10567330f729Sjoerg FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
10577330f729Sjoerg ResultStr += "(*";
10587330f729Sjoerg }
10597330f729Sjoerg } else
10607330f729Sjoerg ResultStr += T.getAsString(Context->getPrintingPolicy());
10617330f729Sjoerg }
10627330f729Sjoerg
RewriteObjCMethodDecl(const ObjCInterfaceDecl * IDecl,ObjCMethodDecl * OMD,std::string & ResultStr)10637330f729Sjoerg void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
10647330f729Sjoerg ObjCMethodDecl *OMD,
10657330f729Sjoerg std::string &ResultStr) {
10667330f729Sjoerg //fprintf(stderr,"In RewriteObjCMethodDecl\n");
10677330f729Sjoerg const FunctionType *FPRetType = nullptr;
10687330f729Sjoerg ResultStr += "\nstatic ";
10697330f729Sjoerg RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
10707330f729Sjoerg ResultStr += " ";
10717330f729Sjoerg
10727330f729Sjoerg // Unique method name
10737330f729Sjoerg std::string NameStr;
10747330f729Sjoerg
10757330f729Sjoerg if (OMD->isInstanceMethod())
10767330f729Sjoerg NameStr += "_I_";
10777330f729Sjoerg else
10787330f729Sjoerg NameStr += "_C_";
10797330f729Sjoerg
10807330f729Sjoerg NameStr += IDecl->getNameAsString();
10817330f729Sjoerg NameStr += "_";
10827330f729Sjoerg
10837330f729Sjoerg if (ObjCCategoryImplDecl *CID =
10847330f729Sjoerg dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
10857330f729Sjoerg NameStr += CID->getNameAsString();
10867330f729Sjoerg NameStr += "_";
10877330f729Sjoerg }
10887330f729Sjoerg // Append selector names, replacing ':' with '_'
10897330f729Sjoerg {
10907330f729Sjoerg std::string selString = OMD->getSelector().getAsString();
10917330f729Sjoerg int len = selString.size();
10927330f729Sjoerg for (int i = 0; i < len; i++)
10937330f729Sjoerg if (selString[i] == ':')
10947330f729Sjoerg selString[i] = '_';
10957330f729Sjoerg NameStr += selString;
10967330f729Sjoerg }
10977330f729Sjoerg // Remember this name for metadata emission
10987330f729Sjoerg MethodInternalNames[OMD] = NameStr;
10997330f729Sjoerg ResultStr += NameStr;
11007330f729Sjoerg
11017330f729Sjoerg // Rewrite arguments
11027330f729Sjoerg ResultStr += "(";
11037330f729Sjoerg
11047330f729Sjoerg // invisible arguments
11057330f729Sjoerg if (OMD->isInstanceMethod()) {
11067330f729Sjoerg QualType selfTy = Context->getObjCInterfaceType(IDecl);
11077330f729Sjoerg selfTy = Context->getPointerType(selfTy);
11087330f729Sjoerg if (!LangOpts.MicrosoftExt) {
11097330f729Sjoerg if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
11107330f729Sjoerg ResultStr += "struct ";
11117330f729Sjoerg }
11127330f729Sjoerg // When rewriting for Microsoft, explicitly omit the structure name.
11137330f729Sjoerg ResultStr += IDecl->getNameAsString();
11147330f729Sjoerg ResultStr += " *";
11157330f729Sjoerg }
11167330f729Sjoerg else
11177330f729Sjoerg ResultStr += Context->getObjCClassType().getAsString(
11187330f729Sjoerg Context->getPrintingPolicy());
11197330f729Sjoerg
11207330f729Sjoerg ResultStr += " self, ";
11217330f729Sjoerg ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
11227330f729Sjoerg ResultStr += " _cmd";
11237330f729Sjoerg
11247330f729Sjoerg // Method arguments.
11257330f729Sjoerg for (const auto *PDecl : OMD->parameters()) {
11267330f729Sjoerg ResultStr += ", ";
11277330f729Sjoerg if (PDecl->getType()->isObjCQualifiedIdType()) {
11287330f729Sjoerg ResultStr += "id ";
11297330f729Sjoerg ResultStr += PDecl->getNameAsString();
11307330f729Sjoerg } else {
11317330f729Sjoerg std::string Name = PDecl->getNameAsString();
11327330f729Sjoerg QualType QT = PDecl->getType();
11337330f729Sjoerg // Make sure we convert "t (^)(...)" to "t (*)(...)".
11347330f729Sjoerg (void)convertBlockPointerToFunctionPointer(QT);
11357330f729Sjoerg QT.getAsStringInternal(Name, Context->getPrintingPolicy());
11367330f729Sjoerg ResultStr += Name;
11377330f729Sjoerg }
11387330f729Sjoerg }
11397330f729Sjoerg if (OMD->isVariadic())
11407330f729Sjoerg ResultStr += ", ...";
11417330f729Sjoerg ResultStr += ") ";
11427330f729Sjoerg
11437330f729Sjoerg if (FPRetType) {
11447330f729Sjoerg ResultStr += ")"; // close the precedence "scope" for "*".
11457330f729Sjoerg
11467330f729Sjoerg // Now, emit the argument types (if any).
11477330f729Sjoerg if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
11487330f729Sjoerg ResultStr += "(";
11497330f729Sjoerg for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
11507330f729Sjoerg if (i) ResultStr += ", ";
11517330f729Sjoerg std::string ParamStr =
11527330f729Sjoerg FT->getParamType(i).getAsString(Context->getPrintingPolicy());
11537330f729Sjoerg ResultStr += ParamStr;
11547330f729Sjoerg }
11557330f729Sjoerg if (FT->isVariadic()) {
11567330f729Sjoerg if (FT->getNumParams())
11577330f729Sjoerg ResultStr += ", ";
11587330f729Sjoerg ResultStr += "...";
11597330f729Sjoerg }
11607330f729Sjoerg ResultStr += ")";
11617330f729Sjoerg } else {
11627330f729Sjoerg ResultStr += "()";
11637330f729Sjoerg }
11647330f729Sjoerg }
11657330f729Sjoerg }
11667330f729Sjoerg
RewriteImplementationDecl(Decl * OID)11677330f729Sjoerg void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
11687330f729Sjoerg ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
11697330f729Sjoerg ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
11707330f729Sjoerg assert((IMD || CID) && "Unknown ImplementationDecl");
11717330f729Sjoerg
11727330f729Sjoerg InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// ");
11737330f729Sjoerg
11747330f729Sjoerg for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1175*e038c9c4Sjoerg if (!OMD->getBody())
1176*e038c9c4Sjoerg continue;
11777330f729Sjoerg std::string ResultStr;
11787330f729Sjoerg RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
11797330f729Sjoerg SourceLocation LocStart = OMD->getBeginLoc();
11807330f729Sjoerg SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
11817330f729Sjoerg
11827330f729Sjoerg const char *startBuf = SM->getCharacterData(LocStart);
11837330f729Sjoerg const char *endBuf = SM->getCharacterData(LocEnd);
11847330f729Sjoerg ReplaceText(LocStart, endBuf-startBuf, ResultStr);
11857330f729Sjoerg }
11867330f729Sjoerg
11877330f729Sjoerg for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1188*e038c9c4Sjoerg if (!OMD->getBody())
1189*e038c9c4Sjoerg continue;
11907330f729Sjoerg std::string ResultStr;
11917330f729Sjoerg RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
11927330f729Sjoerg SourceLocation LocStart = OMD->getBeginLoc();
11937330f729Sjoerg SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
11947330f729Sjoerg
11957330f729Sjoerg const char *startBuf = SM->getCharacterData(LocStart);
11967330f729Sjoerg const char *endBuf = SM->getCharacterData(LocEnd);
11977330f729Sjoerg ReplaceText(LocStart, endBuf-startBuf, ResultStr);
11987330f729Sjoerg }
11997330f729Sjoerg for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
12007330f729Sjoerg RewritePropertyImplDecl(I, IMD, CID);
12017330f729Sjoerg
12027330f729Sjoerg InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
12037330f729Sjoerg }
12047330f729Sjoerg
RewriteInterfaceDecl(ObjCInterfaceDecl * ClassDecl)12057330f729Sjoerg void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
12067330f729Sjoerg std::string ResultStr;
12077330f729Sjoerg if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
12087330f729Sjoerg // we haven't seen a forward decl - generate a typedef.
12097330f729Sjoerg ResultStr = "#ifndef _REWRITER_typedef_";
12107330f729Sjoerg ResultStr += ClassDecl->getNameAsString();
12117330f729Sjoerg ResultStr += "\n";
12127330f729Sjoerg ResultStr += "#define _REWRITER_typedef_";
12137330f729Sjoerg ResultStr += ClassDecl->getNameAsString();
12147330f729Sjoerg ResultStr += "\n";
12157330f729Sjoerg ResultStr += "typedef struct objc_object ";
12167330f729Sjoerg ResultStr += ClassDecl->getNameAsString();
12177330f729Sjoerg ResultStr += ";\n#endif\n";
12187330f729Sjoerg // Mark this typedef as having been generated.
12197330f729Sjoerg ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
12207330f729Sjoerg }
12217330f729Sjoerg RewriteObjCInternalStruct(ClassDecl, ResultStr);
12227330f729Sjoerg
12237330f729Sjoerg for (auto *I : ClassDecl->instance_properties())
12247330f729Sjoerg RewriteProperty(I);
12257330f729Sjoerg for (auto *I : ClassDecl->instance_methods())
12267330f729Sjoerg RewriteMethodDeclaration(I);
12277330f729Sjoerg for (auto *I : ClassDecl->class_methods())
12287330f729Sjoerg RewriteMethodDeclaration(I);
12297330f729Sjoerg
12307330f729Sjoerg // Lastly, comment out the @end.
12317330f729Sjoerg ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
12327330f729Sjoerg "/* @end */");
12337330f729Sjoerg }
12347330f729Sjoerg
RewritePropertyOrImplicitSetter(PseudoObjectExpr * PseudoOp)12357330f729Sjoerg Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
12367330f729Sjoerg SourceRange OldRange = PseudoOp->getSourceRange();
12377330f729Sjoerg
12387330f729Sjoerg // We just magically know some things about the structure of this
12397330f729Sjoerg // expression.
12407330f729Sjoerg ObjCMessageExpr *OldMsg =
12417330f729Sjoerg cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
12427330f729Sjoerg PseudoOp->getNumSemanticExprs() - 1));
12437330f729Sjoerg
12447330f729Sjoerg // Because the rewriter doesn't allow us to rewrite rewritten code,
12457330f729Sjoerg // we need to suppress rewriting the sub-statements.
12467330f729Sjoerg Expr *Base, *RHS;
12477330f729Sjoerg {
12487330f729Sjoerg DisableReplaceStmtScope S(*this);
12497330f729Sjoerg
12507330f729Sjoerg // Rebuild the base expression if we have one.
12517330f729Sjoerg Base = nullptr;
12527330f729Sjoerg if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
12537330f729Sjoerg Base = OldMsg->getInstanceReceiver();
12547330f729Sjoerg Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
12557330f729Sjoerg Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
12567330f729Sjoerg }
12577330f729Sjoerg
12587330f729Sjoerg // Rebuild the RHS.
12597330f729Sjoerg RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
12607330f729Sjoerg RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
12617330f729Sjoerg RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
12627330f729Sjoerg }
12637330f729Sjoerg
12647330f729Sjoerg // TODO: avoid this copy.
12657330f729Sjoerg SmallVector<SourceLocation, 1> SelLocs;
12667330f729Sjoerg OldMsg->getSelectorLocs(SelLocs);
12677330f729Sjoerg
12687330f729Sjoerg ObjCMessageExpr *NewMsg = nullptr;
12697330f729Sjoerg switch (OldMsg->getReceiverKind()) {
12707330f729Sjoerg case ObjCMessageExpr::Class:
12717330f729Sjoerg NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
12727330f729Sjoerg OldMsg->getValueKind(),
12737330f729Sjoerg OldMsg->getLeftLoc(),
12747330f729Sjoerg OldMsg->getClassReceiverTypeInfo(),
12757330f729Sjoerg OldMsg->getSelector(),
12767330f729Sjoerg SelLocs,
12777330f729Sjoerg OldMsg->getMethodDecl(),
12787330f729Sjoerg RHS,
12797330f729Sjoerg OldMsg->getRightLoc(),
12807330f729Sjoerg OldMsg->isImplicit());
12817330f729Sjoerg break;
12827330f729Sjoerg
12837330f729Sjoerg case ObjCMessageExpr::Instance:
12847330f729Sjoerg NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
12857330f729Sjoerg OldMsg->getValueKind(),
12867330f729Sjoerg OldMsg->getLeftLoc(),
12877330f729Sjoerg Base,
12887330f729Sjoerg OldMsg->getSelector(),
12897330f729Sjoerg SelLocs,
12907330f729Sjoerg OldMsg->getMethodDecl(),
12917330f729Sjoerg RHS,
12927330f729Sjoerg OldMsg->getRightLoc(),
12937330f729Sjoerg OldMsg->isImplicit());
12947330f729Sjoerg break;
12957330f729Sjoerg
12967330f729Sjoerg case ObjCMessageExpr::SuperClass:
12977330f729Sjoerg case ObjCMessageExpr::SuperInstance:
12987330f729Sjoerg NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
12997330f729Sjoerg OldMsg->getValueKind(),
13007330f729Sjoerg OldMsg->getLeftLoc(),
13017330f729Sjoerg OldMsg->getSuperLoc(),
13027330f729Sjoerg OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
13037330f729Sjoerg OldMsg->getSuperType(),
13047330f729Sjoerg OldMsg->getSelector(),
13057330f729Sjoerg SelLocs,
13067330f729Sjoerg OldMsg->getMethodDecl(),
13077330f729Sjoerg RHS,
13087330f729Sjoerg OldMsg->getRightLoc(),
13097330f729Sjoerg OldMsg->isImplicit());
13107330f729Sjoerg break;
13117330f729Sjoerg }
13127330f729Sjoerg
13137330f729Sjoerg Stmt *Replacement = SynthMessageExpr(NewMsg);
13147330f729Sjoerg ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
13157330f729Sjoerg return Replacement;
13167330f729Sjoerg }
13177330f729Sjoerg
RewritePropertyOrImplicitGetter(PseudoObjectExpr * PseudoOp)13187330f729Sjoerg Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
13197330f729Sjoerg SourceRange OldRange = PseudoOp->getSourceRange();
13207330f729Sjoerg
13217330f729Sjoerg // We just magically know some things about the structure of this
13227330f729Sjoerg // expression.
13237330f729Sjoerg ObjCMessageExpr *OldMsg =
13247330f729Sjoerg cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
13257330f729Sjoerg
13267330f729Sjoerg // Because the rewriter doesn't allow us to rewrite rewritten code,
13277330f729Sjoerg // we need to suppress rewriting the sub-statements.
13287330f729Sjoerg Expr *Base = nullptr;
13297330f729Sjoerg {
13307330f729Sjoerg DisableReplaceStmtScope S(*this);
13317330f729Sjoerg
13327330f729Sjoerg // Rebuild the base expression if we have one.
13337330f729Sjoerg if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
13347330f729Sjoerg Base = OldMsg->getInstanceReceiver();
13357330f729Sjoerg Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
13367330f729Sjoerg Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
13377330f729Sjoerg }
13387330f729Sjoerg }
13397330f729Sjoerg
13407330f729Sjoerg // Intentionally empty.
13417330f729Sjoerg SmallVector<SourceLocation, 1> SelLocs;
13427330f729Sjoerg SmallVector<Expr*, 1> Args;
13437330f729Sjoerg
13447330f729Sjoerg ObjCMessageExpr *NewMsg = nullptr;
13457330f729Sjoerg switch (OldMsg->getReceiverKind()) {
13467330f729Sjoerg case ObjCMessageExpr::Class:
13477330f729Sjoerg NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
13487330f729Sjoerg OldMsg->getValueKind(),
13497330f729Sjoerg OldMsg->getLeftLoc(),
13507330f729Sjoerg OldMsg->getClassReceiverTypeInfo(),
13517330f729Sjoerg OldMsg->getSelector(),
13527330f729Sjoerg SelLocs,
13537330f729Sjoerg OldMsg->getMethodDecl(),
13547330f729Sjoerg Args,
13557330f729Sjoerg OldMsg->getRightLoc(),
13567330f729Sjoerg OldMsg->isImplicit());
13577330f729Sjoerg break;
13587330f729Sjoerg
13597330f729Sjoerg case ObjCMessageExpr::Instance:
13607330f729Sjoerg NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
13617330f729Sjoerg OldMsg->getValueKind(),
13627330f729Sjoerg OldMsg->getLeftLoc(),
13637330f729Sjoerg Base,
13647330f729Sjoerg OldMsg->getSelector(),
13657330f729Sjoerg SelLocs,
13667330f729Sjoerg OldMsg->getMethodDecl(),
13677330f729Sjoerg Args,
13687330f729Sjoerg OldMsg->getRightLoc(),
13697330f729Sjoerg OldMsg->isImplicit());
13707330f729Sjoerg break;
13717330f729Sjoerg
13727330f729Sjoerg case ObjCMessageExpr::SuperClass:
13737330f729Sjoerg case ObjCMessageExpr::SuperInstance:
13747330f729Sjoerg NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
13757330f729Sjoerg OldMsg->getValueKind(),
13767330f729Sjoerg OldMsg->getLeftLoc(),
13777330f729Sjoerg OldMsg->getSuperLoc(),
13787330f729Sjoerg OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
13797330f729Sjoerg OldMsg->getSuperType(),
13807330f729Sjoerg OldMsg->getSelector(),
13817330f729Sjoerg SelLocs,
13827330f729Sjoerg OldMsg->getMethodDecl(),
13837330f729Sjoerg Args,
13847330f729Sjoerg OldMsg->getRightLoc(),
13857330f729Sjoerg OldMsg->isImplicit());
13867330f729Sjoerg break;
13877330f729Sjoerg }
13887330f729Sjoerg
13897330f729Sjoerg Stmt *Replacement = SynthMessageExpr(NewMsg);
13907330f729Sjoerg ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
13917330f729Sjoerg return Replacement;
13927330f729Sjoerg }
13937330f729Sjoerg
13947330f729Sjoerg /// SynthCountByEnumWithState - To print:
13957330f729Sjoerg /// ((unsigned int (*)
13967330f729Sjoerg /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
13977330f729Sjoerg /// (void *)objc_msgSend)((id)l_collection,
13987330f729Sjoerg /// sel_registerName(
13997330f729Sjoerg /// "countByEnumeratingWithState:objects:count:"),
14007330f729Sjoerg /// &enumState,
14017330f729Sjoerg /// (id *)__rw_items, (unsigned int)16)
14027330f729Sjoerg ///
SynthCountByEnumWithState(std::string & buf)14037330f729Sjoerg void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
14047330f729Sjoerg buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
14057330f729Sjoerg "id *, unsigned int))(void *)objc_msgSend)";
14067330f729Sjoerg buf += "\n\t\t";
14077330f729Sjoerg buf += "((id)l_collection,\n\t\t";
14087330f729Sjoerg buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
14097330f729Sjoerg buf += "\n\t\t";
14107330f729Sjoerg buf += "&enumState, "
14117330f729Sjoerg "(id *)__rw_items, (unsigned int)16)";
14127330f729Sjoerg }
14137330f729Sjoerg
14147330f729Sjoerg /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
14157330f729Sjoerg /// statement to exit to its outer synthesized loop.
14167330f729Sjoerg ///
RewriteBreakStmt(BreakStmt * S)14177330f729Sjoerg Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
14187330f729Sjoerg if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
14197330f729Sjoerg return S;
14207330f729Sjoerg // replace break with goto __break_label
14217330f729Sjoerg std::string buf;
14227330f729Sjoerg
14237330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
14247330f729Sjoerg buf = "goto __break_label_";
14257330f729Sjoerg buf += utostr(ObjCBcLabelNo.back());
14267330f729Sjoerg ReplaceText(startLoc, strlen("break"), buf);
14277330f729Sjoerg
14287330f729Sjoerg return nullptr;
14297330f729Sjoerg }
14307330f729Sjoerg
14317330f729Sjoerg /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
14327330f729Sjoerg /// statement to continue with its inner synthesized loop.
14337330f729Sjoerg ///
RewriteContinueStmt(ContinueStmt * S)14347330f729Sjoerg Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
14357330f729Sjoerg if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
14367330f729Sjoerg return S;
14377330f729Sjoerg // replace continue with goto __continue_label
14387330f729Sjoerg std::string buf;
14397330f729Sjoerg
14407330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
14417330f729Sjoerg buf = "goto __continue_label_";
14427330f729Sjoerg buf += utostr(ObjCBcLabelNo.back());
14437330f729Sjoerg ReplaceText(startLoc, strlen("continue"), buf);
14447330f729Sjoerg
14457330f729Sjoerg return nullptr;
14467330f729Sjoerg }
14477330f729Sjoerg
14487330f729Sjoerg /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
14497330f729Sjoerg /// It rewrites:
14507330f729Sjoerg /// for ( type elem in collection) { stmts; }
14517330f729Sjoerg
14527330f729Sjoerg /// Into:
14537330f729Sjoerg /// {
14547330f729Sjoerg /// type elem;
14557330f729Sjoerg /// struct __objcFastEnumerationState enumState = { 0 };
14567330f729Sjoerg /// id __rw_items[16];
14577330f729Sjoerg /// id l_collection = (id)collection;
14587330f729Sjoerg /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
14597330f729Sjoerg /// objects:__rw_items count:16];
14607330f729Sjoerg /// if (limit) {
14617330f729Sjoerg /// unsigned long startMutations = *enumState.mutationsPtr;
14627330f729Sjoerg /// do {
14637330f729Sjoerg /// unsigned long counter = 0;
14647330f729Sjoerg /// do {
14657330f729Sjoerg /// if (startMutations != *enumState.mutationsPtr)
14667330f729Sjoerg /// objc_enumerationMutation(l_collection);
14677330f729Sjoerg /// elem = (type)enumState.itemsPtr[counter++];
14687330f729Sjoerg /// stmts;
14697330f729Sjoerg /// __continue_label: ;
14707330f729Sjoerg /// } while (counter < limit);
14717330f729Sjoerg /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
14727330f729Sjoerg /// objects:__rw_items count:16]);
14737330f729Sjoerg /// elem = nil;
14747330f729Sjoerg /// __break_label: ;
14757330f729Sjoerg /// }
14767330f729Sjoerg /// else
14777330f729Sjoerg /// elem = nil;
14787330f729Sjoerg /// }
14797330f729Sjoerg ///
RewriteObjCForCollectionStmt(ObjCForCollectionStmt * S,SourceLocation OrigEnd)14807330f729Sjoerg Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
14817330f729Sjoerg SourceLocation OrigEnd) {
14827330f729Sjoerg assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
14837330f729Sjoerg assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
14847330f729Sjoerg "ObjCForCollectionStmt Statement stack mismatch");
14857330f729Sjoerg assert(!ObjCBcLabelNo.empty() &&
14867330f729Sjoerg "ObjCForCollectionStmt - Label No stack empty");
14877330f729Sjoerg
14887330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
14897330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
14907330f729Sjoerg StringRef elementName;
14917330f729Sjoerg std::string elementTypeAsString;
14927330f729Sjoerg std::string buf;
14937330f729Sjoerg buf = "\n{\n\t";
14947330f729Sjoerg if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
14957330f729Sjoerg // type elem;
14967330f729Sjoerg NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
14977330f729Sjoerg QualType ElementType = cast<ValueDecl>(D)->getType();
14987330f729Sjoerg if (ElementType->isObjCQualifiedIdType() ||
14997330f729Sjoerg ElementType->isObjCQualifiedInterfaceType())
15007330f729Sjoerg // Simply use 'id' for all qualified types.
15017330f729Sjoerg elementTypeAsString = "id";
15027330f729Sjoerg else
15037330f729Sjoerg elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
15047330f729Sjoerg buf += elementTypeAsString;
15057330f729Sjoerg buf += " ";
15067330f729Sjoerg elementName = D->getName();
15077330f729Sjoerg buf += elementName;
15087330f729Sjoerg buf += ";\n\t";
15097330f729Sjoerg }
15107330f729Sjoerg else {
15117330f729Sjoerg DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
15127330f729Sjoerg elementName = DR->getDecl()->getName();
15137330f729Sjoerg ValueDecl *VD = DR->getDecl();
15147330f729Sjoerg if (VD->getType()->isObjCQualifiedIdType() ||
15157330f729Sjoerg VD->getType()->isObjCQualifiedInterfaceType())
15167330f729Sjoerg // Simply use 'id' for all qualified types.
15177330f729Sjoerg elementTypeAsString = "id";
15187330f729Sjoerg else
15197330f729Sjoerg elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
15207330f729Sjoerg }
15217330f729Sjoerg
15227330f729Sjoerg // struct __objcFastEnumerationState enumState = { 0 };
15237330f729Sjoerg buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
15247330f729Sjoerg // id __rw_items[16];
15257330f729Sjoerg buf += "id __rw_items[16];\n\t";
15267330f729Sjoerg // id l_collection = (id)
15277330f729Sjoerg buf += "id l_collection = (id)";
15287330f729Sjoerg // Find start location of 'collection' the hard way!
15297330f729Sjoerg const char *startCollectionBuf = startBuf;
15307330f729Sjoerg startCollectionBuf += 3; // skip 'for'
15317330f729Sjoerg startCollectionBuf = strchr(startCollectionBuf, '(');
15327330f729Sjoerg startCollectionBuf++; // skip '('
15337330f729Sjoerg // find 'in' and skip it.
15347330f729Sjoerg while (*startCollectionBuf != ' ' ||
15357330f729Sjoerg *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
15367330f729Sjoerg (*(startCollectionBuf+3) != ' ' &&
15377330f729Sjoerg *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
15387330f729Sjoerg startCollectionBuf++;
15397330f729Sjoerg startCollectionBuf += 3;
15407330f729Sjoerg
15417330f729Sjoerg // Replace: "for (type element in" with string constructed thus far.
15427330f729Sjoerg ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
15437330f729Sjoerg // Replace ')' in for '(' type elem in collection ')' with ';'
15447330f729Sjoerg SourceLocation rightParenLoc = S->getRParenLoc();
15457330f729Sjoerg const char *rparenBuf = SM->getCharacterData(rightParenLoc);
15467330f729Sjoerg SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
15477330f729Sjoerg buf = ";\n\t";
15487330f729Sjoerg
15497330f729Sjoerg // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
15507330f729Sjoerg // objects:__rw_items count:16];
15517330f729Sjoerg // which is synthesized into:
15527330f729Sjoerg // unsigned int limit =
15537330f729Sjoerg // ((unsigned int (*)
15547330f729Sjoerg // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
15557330f729Sjoerg // (void *)objc_msgSend)((id)l_collection,
15567330f729Sjoerg // sel_registerName(
15577330f729Sjoerg // "countByEnumeratingWithState:objects:count:"),
15587330f729Sjoerg // (struct __objcFastEnumerationState *)&state,
15597330f729Sjoerg // (id *)__rw_items, (unsigned int)16);
15607330f729Sjoerg buf += "unsigned long limit =\n\t\t";
15617330f729Sjoerg SynthCountByEnumWithState(buf);
15627330f729Sjoerg buf += ";\n\t";
15637330f729Sjoerg /// if (limit) {
15647330f729Sjoerg /// unsigned long startMutations = *enumState.mutationsPtr;
15657330f729Sjoerg /// do {
15667330f729Sjoerg /// unsigned long counter = 0;
15677330f729Sjoerg /// do {
15687330f729Sjoerg /// if (startMutations != *enumState.mutationsPtr)
15697330f729Sjoerg /// objc_enumerationMutation(l_collection);
15707330f729Sjoerg /// elem = (type)enumState.itemsPtr[counter++];
15717330f729Sjoerg buf += "if (limit) {\n\t";
15727330f729Sjoerg buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
15737330f729Sjoerg buf += "do {\n\t\t";
15747330f729Sjoerg buf += "unsigned long counter = 0;\n\t\t";
15757330f729Sjoerg buf += "do {\n\t\t\t";
15767330f729Sjoerg buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
15777330f729Sjoerg buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
15787330f729Sjoerg buf += elementName;
15797330f729Sjoerg buf += " = (";
15807330f729Sjoerg buf += elementTypeAsString;
15817330f729Sjoerg buf += ")enumState.itemsPtr[counter++];";
15827330f729Sjoerg // Replace ')' in for '(' type elem in collection ')' with all of these.
15837330f729Sjoerg ReplaceText(lparenLoc, 1, buf);
15847330f729Sjoerg
15857330f729Sjoerg /// __continue_label: ;
15867330f729Sjoerg /// } while (counter < limit);
15877330f729Sjoerg /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
15887330f729Sjoerg /// objects:__rw_items count:16]);
15897330f729Sjoerg /// elem = nil;
15907330f729Sjoerg /// __break_label: ;
15917330f729Sjoerg /// }
15927330f729Sjoerg /// else
15937330f729Sjoerg /// elem = nil;
15947330f729Sjoerg /// }
15957330f729Sjoerg ///
15967330f729Sjoerg buf = ";\n\t";
15977330f729Sjoerg buf += "__continue_label_";
15987330f729Sjoerg buf += utostr(ObjCBcLabelNo.back());
15997330f729Sjoerg buf += ": ;";
16007330f729Sjoerg buf += "\n\t\t";
16017330f729Sjoerg buf += "} while (counter < limit);\n\t";
16027330f729Sjoerg buf += "} while (limit = ";
16037330f729Sjoerg SynthCountByEnumWithState(buf);
16047330f729Sjoerg buf += ");\n\t";
16057330f729Sjoerg buf += elementName;
16067330f729Sjoerg buf += " = ((";
16077330f729Sjoerg buf += elementTypeAsString;
16087330f729Sjoerg buf += ")0);\n\t";
16097330f729Sjoerg buf += "__break_label_";
16107330f729Sjoerg buf += utostr(ObjCBcLabelNo.back());
16117330f729Sjoerg buf += ": ;\n\t";
16127330f729Sjoerg buf += "}\n\t";
16137330f729Sjoerg buf += "else\n\t\t";
16147330f729Sjoerg buf += elementName;
16157330f729Sjoerg buf += " = ((";
16167330f729Sjoerg buf += elementTypeAsString;
16177330f729Sjoerg buf += ")0);\n\t";
16187330f729Sjoerg buf += "}\n";
16197330f729Sjoerg
16207330f729Sjoerg // Insert all these *after* the statement body.
16217330f729Sjoerg // FIXME: If this should support Obj-C++, support CXXTryStmt
16227330f729Sjoerg if (isa<CompoundStmt>(S->getBody())) {
16237330f729Sjoerg SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
16247330f729Sjoerg InsertText(endBodyLoc, buf);
16257330f729Sjoerg } else {
16267330f729Sjoerg /* Need to treat single statements specially. For example:
16277330f729Sjoerg *
16287330f729Sjoerg * for (A *a in b) if (stuff()) break;
16297330f729Sjoerg * for (A *a in b) xxxyy;
16307330f729Sjoerg *
16317330f729Sjoerg * The following code simply scans ahead to the semi to find the actual end.
16327330f729Sjoerg */
16337330f729Sjoerg const char *stmtBuf = SM->getCharacterData(OrigEnd);
16347330f729Sjoerg const char *semiBuf = strchr(stmtBuf, ';');
16357330f729Sjoerg assert(semiBuf && "Can't find ';'");
16367330f729Sjoerg SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
16377330f729Sjoerg InsertText(endBodyLoc, buf);
16387330f729Sjoerg }
16397330f729Sjoerg Stmts.pop_back();
16407330f729Sjoerg ObjCBcLabelNo.pop_back();
16417330f729Sjoerg return nullptr;
16427330f729Sjoerg }
16437330f729Sjoerg
16447330f729Sjoerg /// RewriteObjCSynchronizedStmt -
16457330f729Sjoerg /// This routine rewrites @synchronized(expr) stmt;
16467330f729Sjoerg /// into:
16477330f729Sjoerg /// objc_sync_enter(expr);
16487330f729Sjoerg /// @try stmt @finally { objc_sync_exit(expr); }
16497330f729Sjoerg ///
RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt * S)16507330f729Sjoerg Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
16517330f729Sjoerg // Get the start location and compute the semi location.
16527330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
16537330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
16547330f729Sjoerg
16557330f729Sjoerg assert((*startBuf == '@') && "bogus @synchronized location");
16567330f729Sjoerg
16577330f729Sjoerg std::string buf;
16587330f729Sjoerg buf = "objc_sync_enter((id)";
16597330f729Sjoerg const char *lparenBuf = startBuf;
16607330f729Sjoerg while (*lparenBuf != '(') lparenBuf++;
16617330f729Sjoerg ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
16627330f729Sjoerg // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
16637330f729Sjoerg // the sync expression is typically a message expression that's already
16647330f729Sjoerg // been rewritten! (which implies the SourceLocation's are invalid).
16657330f729Sjoerg SourceLocation endLoc = S->getSynchBody()->getBeginLoc();
16667330f729Sjoerg const char *endBuf = SM->getCharacterData(endLoc);
16677330f729Sjoerg while (*endBuf != ')') endBuf--;
16687330f729Sjoerg SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
16697330f729Sjoerg buf = ");\n";
16707330f729Sjoerg // declare a new scope with two variables, _stack and _rethrow.
16717330f729Sjoerg buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
16727330f729Sjoerg buf += "int buf[18/*32-bit i386*/];\n";
16737330f729Sjoerg buf += "char *pointers[4];} _stack;\n";
16747330f729Sjoerg buf += "id volatile _rethrow = 0;\n";
16757330f729Sjoerg buf += "objc_exception_try_enter(&_stack);\n";
16767330f729Sjoerg buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
16777330f729Sjoerg ReplaceText(rparenLoc, 1, buf);
16787330f729Sjoerg startLoc = S->getSynchBody()->getEndLoc();
16797330f729Sjoerg startBuf = SM->getCharacterData(startLoc);
16807330f729Sjoerg
16817330f729Sjoerg assert((*startBuf == '}') && "bogus @synchronized block");
16827330f729Sjoerg SourceLocation lastCurlyLoc = startLoc;
16837330f729Sjoerg buf = "}\nelse {\n";
16847330f729Sjoerg buf += " _rethrow = objc_exception_extract(&_stack);\n";
16857330f729Sjoerg buf += "}\n";
16867330f729Sjoerg buf += "{ /* implicit finally clause */\n";
16877330f729Sjoerg buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
16887330f729Sjoerg
16897330f729Sjoerg std::string syncBuf;
16907330f729Sjoerg syncBuf += " objc_sync_exit(";
16917330f729Sjoerg
16927330f729Sjoerg Expr *syncExpr = S->getSynchExpr();
16937330f729Sjoerg CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
16947330f729Sjoerg ? CK_BitCast :
16957330f729Sjoerg syncExpr->getType()->isBlockPointerType()
16967330f729Sjoerg ? CK_BlockPointerToObjCPointerCast
16977330f729Sjoerg : CK_CPointerToObjCPointerCast;
16987330f729Sjoerg syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
16997330f729Sjoerg CK, syncExpr);
17007330f729Sjoerg std::string syncExprBufS;
17017330f729Sjoerg llvm::raw_string_ostream syncExprBuf(syncExprBufS);
17027330f729Sjoerg assert(syncExpr != nullptr && "Expected non-null Expr");
17037330f729Sjoerg syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
17047330f729Sjoerg syncBuf += syncExprBuf.str();
17057330f729Sjoerg syncBuf += ");";
17067330f729Sjoerg
17077330f729Sjoerg buf += syncBuf;
17087330f729Sjoerg buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
17097330f729Sjoerg buf += "}\n";
17107330f729Sjoerg buf += "}";
17117330f729Sjoerg
17127330f729Sjoerg ReplaceText(lastCurlyLoc, 1, buf);
17137330f729Sjoerg
17147330f729Sjoerg bool hasReturns = false;
17157330f729Sjoerg HasReturnStmts(S->getSynchBody(), hasReturns);
17167330f729Sjoerg if (hasReturns)
17177330f729Sjoerg RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
17187330f729Sjoerg
17197330f729Sjoerg return nullptr;
17207330f729Sjoerg }
17217330f729Sjoerg
WarnAboutReturnGotoStmts(Stmt * S)17227330f729Sjoerg void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
17237330f729Sjoerg {
17247330f729Sjoerg // Perform a bottom up traversal of all children.
17257330f729Sjoerg for (Stmt *SubStmt : S->children())
17267330f729Sjoerg if (SubStmt)
17277330f729Sjoerg WarnAboutReturnGotoStmts(SubStmt);
17287330f729Sjoerg
17297330f729Sjoerg if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
17307330f729Sjoerg Diags.Report(Context->getFullLoc(S->getBeginLoc()),
17317330f729Sjoerg TryFinallyContainsReturnDiag);
17327330f729Sjoerg }
17337330f729Sjoerg }
17347330f729Sjoerg
HasReturnStmts(Stmt * S,bool & hasReturns)17357330f729Sjoerg void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
17367330f729Sjoerg {
17377330f729Sjoerg // Perform a bottom up traversal of all children.
17387330f729Sjoerg for (Stmt *SubStmt : S->children())
17397330f729Sjoerg if (SubStmt)
17407330f729Sjoerg HasReturnStmts(SubStmt, hasReturns);
17417330f729Sjoerg
17427330f729Sjoerg if (isa<ReturnStmt>(S))
17437330f729Sjoerg hasReturns = true;
17447330f729Sjoerg }
17457330f729Sjoerg
RewriteTryReturnStmts(Stmt * S)17467330f729Sjoerg void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
17477330f729Sjoerg // Perform a bottom up traversal of all children.
17487330f729Sjoerg for (Stmt *SubStmt : S->children())
17497330f729Sjoerg if (SubStmt) {
17507330f729Sjoerg RewriteTryReturnStmts(SubStmt);
17517330f729Sjoerg }
17527330f729Sjoerg if (isa<ReturnStmt>(S)) {
17537330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
17547330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
17557330f729Sjoerg const char *semiBuf = strchr(startBuf, ';');
17567330f729Sjoerg assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
17577330f729Sjoerg SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
17587330f729Sjoerg
17597330f729Sjoerg std::string buf;
17607330f729Sjoerg buf = "{ objc_exception_try_exit(&_stack); return";
17617330f729Sjoerg
17627330f729Sjoerg ReplaceText(startLoc, 6, buf);
17637330f729Sjoerg InsertText(onePastSemiLoc, "}");
17647330f729Sjoerg }
17657330f729Sjoerg }
17667330f729Sjoerg
RewriteSyncReturnStmts(Stmt * S,std::string syncExitBuf)17677330f729Sjoerg void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
17687330f729Sjoerg // Perform a bottom up traversal of all children.
17697330f729Sjoerg for (Stmt *SubStmt : S->children())
17707330f729Sjoerg if (SubStmt) {
17717330f729Sjoerg RewriteSyncReturnStmts(SubStmt, syncExitBuf);
17727330f729Sjoerg }
17737330f729Sjoerg if (isa<ReturnStmt>(S)) {
17747330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
17757330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
17767330f729Sjoerg
17777330f729Sjoerg const char *semiBuf = strchr(startBuf, ';');
17787330f729Sjoerg assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
17797330f729Sjoerg SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
17807330f729Sjoerg
17817330f729Sjoerg std::string buf;
17827330f729Sjoerg buf = "{ objc_exception_try_exit(&_stack);";
17837330f729Sjoerg buf += syncExitBuf;
17847330f729Sjoerg buf += " return";
17857330f729Sjoerg
17867330f729Sjoerg ReplaceText(startLoc, 6, buf);
17877330f729Sjoerg InsertText(onePastSemiLoc, "}");
17887330f729Sjoerg }
17897330f729Sjoerg }
17907330f729Sjoerg
RewriteObjCTryStmt(ObjCAtTryStmt * S)17917330f729Sjoerg Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
17927330f729Sjoerg // Get the start location and compute the semi location.
17937330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
17947330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
17957330f729Sjoerg
17967330f729Sjoerg assert((*startBuf == '@') && "bogus @try location");
17977330f729Sjoerg
17987330f729Sjoerg std::string buf;
17997330f729Sjoerg // declare a new scope with two variables, _stack and _rethrow.
18007330f729Sjoerg buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
18017330f729Sjoerg buf += "int buf[18/*32-bit i386*/];\n";
18027330f729Sjoerg buf += "char *pointers[4];} _stack;\n";
18037330f729Sjoerg buf += "id volatile _rethrow = 0;\n";
18047330f729Sjoerg buf += "objc_exception_try_enter(&_stack);\n";
18057330f729Sjoerg buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
18067330f729Sjoerg
18077330f729Sjoerg ReplaceText(startLoc, 4, buf);
18087330f729Sjoerg
18097330f729Sjoerg startLoc = S->getTryBody()->getEndLoc();
18107330f729Sjoerg startBuf = SM->getCharacterData(startLoc);
18117330f729Sjoerg
18127330f729Sjoerg assert((*startBuf == '}') && "bogus @try block");
18137330f729Sjoerg
18147330f729Sjoerg SourceLocation lastCurlyLoc = startLoc;
18157330f729Sjoerg if (S->getNumCatchStmts()) {
18167330f729Sjoerg startLoc = startLoc.getLocWithOffset(1);
18177330f729Sjoerg buf = " /* @catch begin */ else {\n";
18187330f729Sjoerg buf += " id _caught = objc_exception_extract(&_stack);\n";
18197330f729Sjoerg buf += " objc_exception_try_enter (&_stack);\n";
18207330f729Sjoerg buf += " if (_setjmp(_stack.buf))\n";
18217330f729Sjoerg buf += " _rethrow = objc_exception_extract(&_stack);\n";
18227330f729Sjoerg buf += " else { /* @catch continue */";
18237330f729Sjoerg
18247330f729Sjoerg InsertText(startLoc, buf);
18257330f729Sjoerg } else { /* no catch list */
18267330f729Sjoerg buf = "}\nelse {\n";
18277330f729Sjoerg buf += " _rethrow = objc_exception_extract(&_stack);\n";
18287330f729Sjoerg buf += "}";
18297330f729Sjoerg ReplaceText(lastCurlyLoc, 1, buf);
18307330f729Sjoerg }
18317330f729Sjoerg Stmt *lastCatchBody = nullptr;
18327330f729Sjoerg for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
18337330f729Sjoerg ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
18347330f729Sjoerg VarDecl *catchDecl = Catch->getCatchParamDecl();
18357330f729Sjoerg
18367330f729Sjoerg if (I == 0)
18377330f729Sjoerg buf = "if ("; // we are generating code for the first catch clause
18387330f729Sjoerg else
18397330f729Sjoerg buf = "else if (";
18407330f729Sjoerg startLoc = Catch->getBeginLoc();
18417330f729Sjoerg startBuf = SM->getCharacterData(startLoc);
18427330f729Sjoerg
18437330f729Sjoerg assert((*startBuf == '@') && "bogus @catch location");
18447330f729Sjoerg
18457330f729Sjoerg const char *lParenLoc = strchr(startBuf, '(');
18467330f729Sjoerg
18477330f729Sjoerg if (Catch->hasEllipsis()) {
18487330f729Sjoerg // Now rewrite the body...
18497330f729Sjoerg lastCatchBody = Catch->getCatchBody();
18507330f729Sjoerg SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
18517330f729Sjoerg const char *bodyBuf = SM->getCharacterData(bodyLoc);
18527330f729Sjoerg assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
18537330f729Sjoerg "bogus @catch paren location");
18547330f729Sjoerg assert((*bodyBuf == '{') && "bogus @catch body location");
18557330f729Sjoerg
18567330f729Sjoerg buf += "1) { id _tmp = _caught;";
18577330f729Sjoerg Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
18587330f729Sjoerg } else if (catchDecl) {
18597330f729Sjoerg QualType t = catchDecl->getType();
18607330f729Sjoerg if (t == Context->getObjCIdType()) {
18617330f729Sjoerg buf += "1) { ";
18627330f729Sjoerg ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
18637330f729Sjoerg } else if (const ObjCObjectPointerType *Ptr =
18647330f729Sjoerg t->getAs<ObjCObjectPointerType>()) {
18657330f729Sjoerg // Should be a pointer to a class.
18667330f729Sjoerg ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
18677330f729Sjoerg if (IDecl) {
18687330f729Sjoerg buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
18697330f729Sjoerg buf += IDecl->getNameAsString();
18707330f729Sjoerg buf += "\"), (struct objc_object *)_caught)) { ";
18717330f729Sjoerg ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
18727330f729Sjoerg }
18737330f729Sjoerg }
18747330f729Sjoerg // Now rewrite the body...
18757330f729Sjoerg lastCatchBody = Catch->getCatchBody();
18767330f729Sjoerg SourceLocation rParenLoc = Catch->getRParenLoc();
18777330f729Sjoerg SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
18787330f729Sjoerg const char *bodyBuf = SM->getCharacterData(bodyLoc);
18797330f729Sjoerg const char *rParenBuf = SM->getCharacterData(rParenLoc);
18807330f729Sjoerg assert((*rParenBuf == ')') && "bogus @catch paren location");
18817330f729Sjoerg assert((*bodyBuf == '{') && "bogus @catch body location");
18827330f729Sjoerg
18837330f729Sjoerg // Here we replace ") {" with "= _caught;" (which initializes and
18847330f729Sjoerg // declares the @catch parameter).
18857330f729Sjoerg ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
18867330f729Sjoerg } else {
18877330f729Sjoerg llvm_unreachable("@catch rewrite bug");
18887330f729Sjoerg }
18897330f729Sjoerg }
18907330f729Sjoerg // Complete the catch list...
18917330f729Sjoerg if (lastCatchBody) {
18927330f729Sjoerg SourceLocation bodyLoc = lastCatchBody->getEndLoc();
18937330f729Sjoerg assert(*SM->getCharacterData(bodyLoc) == '}' &&
18947330f729Sjoerg "bogus @catch body location");
18957330f729Sjoerg
18967330f729Sjoerg // Insert the last (implicit) else clause *before* the right curly brace.
18977330f729Sjoerg bodyLoc = bodyLoc.getLocWithOffset(-1);
18987330f729Sjoerg buf = "} /* last catch end */\n";
18997330f729Sjoerg buf += "else {\n";
19007330f729Sjoerg buf += " _rethrow = _caught;\n";
19017330f729Sjoerg buf += " objc_exception_try_exit(&_stack);\n";
19027330f729Sjoerg buf += "} } /* @catch end */\n";
19037330f729Sjoerg if (!S->getFinallyStmt())
19047330f729Sjoerg buf += "}\n";
19057330f729Sjoerg InsertText(bodyLoc, buf);
19067330f729Sjoerg
19077330f729Sjoerg // Set lastCurlyLoc
19087330f729Sjoerg lastCurlyLoc = lastCatchBody->getEndLoc();
19097330f729Sjoerg }
19107330f729Sjoerg if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
19117330f729Sjoerg startLoc = finalStmt->getBeginLoc();
19127330f729Sjoerg startBuf = SM->getCharacterData(startLoc);
19137330f729Sjoerg assert((*startBuf == '@') && "bogus @finally start");
19147330f729Sjoerg
19157330f729Sjoerg ReplaceText(startLoc, 8, "/* @finally */");
19167330f729Sjoerg
19177330f729Sjoerg Stmt *body = finalStmt->getFinallyBody();
19187330f729Sjoerg SourceLocation startLoc = body->getBeginLoc();
19197330f729Sjoerg SourceLocation endLoc = body->getEndLoc();
19207330f729Sjoerg assert(*SM->getCharacterData(startLoc) == '{' &&
19217330f729Sjoerg "bogus @finally body location");
19227330f729Sjoerg assert(*SM->getCharacterData(endLoc) == '}' &&
19237330f729Sjoerg "bogus @finally body location");
19247330f729Sjoerg
19257330f729Sjoerg startLoc = startLoc.getLocWithOffset(1);
19267330f729Sjoerg InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
19277330f729Sjoerg endLoc = endLoc.getLocWithOffset(-1);
19287330f729Sjoerg InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
19297330f729Sjoerg
19307330f729Sjoerg // Set lastCurlyLoc
19317330f729Sjoerg lastCurlyLoc = body->getEndLoc();
19327330f729Sjoerg
19337330f729Sjoerg // Now check for any return/continue/go statements within the @try.
19347330f729Sjoerg WarnAboutReturnGotoStmts(S->getTryBody());
19357330f729Sjoerg } else { /* no finally clause - make sure we synthesize an implicit one */
19367330f729Sjoerg buf = "{ /* implicit finally clause */\n";
19377330f729Sjoerg buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
19387330f729Sjoerg buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
19397330f729Sjoerg buf += "}";
19407330f729Sjoerg ReplaceText(lastCurlyLoc, 1, buf);
19417330f729Sjoerg
19427330f729Sjoerg // Now check for any return/continue/go statements within the @try.
19437330f729Sjoerg // The implicit finally clause won't called if the @try contains any
19447330f729Sjoerg // jump statements.
19457330f729Sjoerg bool hasReturns = false;
19467330f729Sjoerg HasReturnStmts(S->getTryBody(), hasReturns);
19477330f729Sjoerg if (hasReturns)
19487330f729Sjoerg RewriteTryReturnStmts(S->getTryBody());
19497330f729Sjoerg }
19507330f729Sjoerg // Now emit the final closing curly brace...
19517330f729Sjoerg lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
19527330f729Sjoerg InsertText(lastCurlyLoc, " } /* @try scope end */\n");
19537330f729Sjoerg return nullptr;
19547330f729Sjoerg }
19557330f729Sjoerg
19567330f729Sjoerg // This can't be done with ReplaceStmt(S, ThrowExpr), since
19577330f729Sjoerg // the throw expression is typically a message expression that's already
19587330f729Sjoerg // been rewritten! (which implies the SourceLocation's are invalid).
RewriteObjCThrowStmt(ObjCAtThrowStmt * S)19597330f729Sjoerg Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
19607330f729Sjoerg // Get the start location and compute the semi location.
19617330f729Sjoerg SourceLocation startLoc = S->getBeginLoc();
19627330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
19637330f729Sjoerg
19647330f729Sjoerg assert((*startBuf == '@') && "bogus @throw location");
19657330f729Sjoerg
19667330f729Sjoerg std::string buf;
19677330f729Sjoerg /* void objc_exception_throw(id) __attribute__((noreturn)); */
19687330f729Sjoerg if (S->getThrowExpr())
19697330f729Sjoerg buf = "objc_exception_throw(";
19707330f729Sjoerg else // add an implicit argument
19717330f729Sjoerg buf = "objc_exception_throw(_caught";
19727330f729Sjoerg
19737330f729Sjoerg // handle "@ throw" correctly.
19747330f729Sjoerg const char *wBuf = strchr(startBuf, 'w');
19757330f729Sjoerg assert((*wBuf == 'w') && "@throw: can't find 'w'");
19767330f729Sjoerg ReplaceText(startLoc, wBuf-startBuf+1, buf);
19777330f729Sjoerg
19787330f729Sjoerg const char *semiBuf = strchr(startBuf, ';');
19797330f729Sjoerg assert((*semiBuf == ';') && "@throw: can't find ';'");
19807330f729Sjoerg SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
19817330f729Sjoerg ReplaceText(semiLoc, 1, ");");
19827330f729Sjoerg return nullptr;
19837330f729Sjoerg }
19847330f729Sjoerg
RewriteAtEncode(ObjCEncodeExpr * Exp)19857330f729Sjoerg Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
19867330f729Sjoerg // Create a new string expression.
19877330f729Sjoerg std::string StrEncoding;
19887330f729Sjoerg Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
19897330f729Sjoerg Expr *Replacement = getStringLiteral(StrEncoding);
19907330f729Sjoerg ReplaceStmt(Exp, Replacement);
19917330f729Sjoerg
19927330f729Sjoerg // Replace this subexpr in the parent.
19937330f729Sjoerg // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
19947330f729Sjoerg return Replacement;
19957330f729Sjoerg }
19967330f729Sjoerg
RewriteAtSelector(ObjCSelectorExpr * Exp)19977330f729Sjoerg Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
19987330f729Sjoerg if (!SelGetUidFunctionDecl)
19997330f729Sjoerg SynthSelGetUidFunctionDecl();
20007330f729Sjoerg assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
20017330f729Sjoerg // Create a call to sel_registerName("selName").
20027330f729Sjoerg SmallVector<Expr*, 8> SelExprs;
20037330f729Sjoerg SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
20047330f729Sjoerg CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
20057330f729Sjoerg SelExprs);
20067330f729Sjoerg ReplaceStmt(Exp, SelExp);
20077330f729Sjoerg // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
20087330f729Sjoerg return SelExp;
20097330f729Sjoerg }
20107330f729Sjoerg
20117330f729Sjoerg CallExpr *
SynthesizeCallToFunctionDecl(FunctionDecl * FD,ArrayRef<Expr * > Args,SourceLocation StartLoc,SourceLocation EndLoc)20127330f729Sjoerg RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
20137330f729Sjoerg ArrayRef<Expr *> Args,
20147330f729Sjoerg SourceLocation StartLoc,
20157330f729Sjoerg SourceLocation EndLoc) {
20167330f729Sjoerg // Get the type, we will need to reference it in a couple spots.
20177330f729Sjoerg QualType msgSendType = FD->getType();
20187330f729Sjoerg
20197330f729Sjoerg // Create a reference to the objc_msgSend() declaration.
20207330f729Sjoerg DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
20217330f729Sjoerg VK_LValue, SourceLocation());
20227330f729Sjoerg
20237330f729Sjoerg // Now, we cast the reference to a pointer to the objc_msgSend type.
20247330f729Sjoerg QualType pToFunc = Context->getPointerType(msgSendType);
20257330f729Sjoerg ImplicitCastExpr *ICE =
20267330f729Sjoerg ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2027*e038c9c4Sjoerg DRE, nullptr, VK_RValue, FPOptionsOverride());
20287330f729Sjoerg
20297330f729Sjoerg const auto *FT = msgSendType->castAs<FunctionType>();
20307330f729Sjoerg
2031*e038c9c4Sjoerg CallExpr *Exp =
2032*e038c9c4Sjoerg CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2033*e038c9c4Sjoerg VK_RValue, EndLoc, FPOptionsOverride());
20347330f729Sjoerg return Exp;
20357330f729Sjoerg }
20367330f729Sjoerg
scanForProtocolRefs(const char * startBuf,const char * endBuf,const char * & startRef,const char * & endRef)20377330f729Sjoerg static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
20387330f729Sjoerg const char *&startRef, const char *&endRef) {
20397330f729Sjoerg while (startBuf < endBuf) {
20407330f729Sjoerg if (*startBuf == '<')
20417330f729Sjoerg startRef = startBuf; // mark the start.
20427330f729Sjoerg if (*startBuf == '>') {
20437330f729Sjoerg if (startRef && *startRef == '<') {
20447330f729Sjoerg endRef = startBuf; // mark the end.
20457330f729Sjoerg return true;
20467330f729Sjoerg }
20477330f729Sjoerg return false;
20487330f729Sjoerg }
20497330f729Sjoerg startBuf++;
20507330f729Sjoerg }
20517330f729Sjoerg return false;
20527330f729Sjoerg }
20537330f729Sjoerg
scanToNextArgument(const char * & argRef)20547330f729Sjoerg static void scanToNextArgument(const char *&argRef) {
20557330f729Sjoerg int angle = 0;
20567330f729Sjoerg while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
20577330f729Sjoerg if (*argRef == '<')
20587330f729Sjoerg angle++;
20597330f729Sjoerg else if (*argRef == '>')
20607330f729Sjoerg angle--;
20617330f729Sjoerg argRef++;
20627330f729Sjoerg }
20637330f729Sjoerg assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
20647330f729Sjoerg }
20657330f729Sjoerg
needToScanForQualifiers(QualType T)20667330f729Sjoerg bool RewriteObjC::needToScanForQualifiers(QualType T) {
20677330f729Sjoerg if (T->isObjCQualifiedIdType())
20687330f729Sjoerg return true;
20697330f729Sjoerg if (const PointerType *PT = T->getAs<PointerType>()) {
20707330f729Sjoerg if (PT->getPointeeType()->isObjCQualifiedIdType())
20717330f729Sjoerg return true;
20727330f729Sjoerg }
20737330f729Sjoerg if (T->isObjCObjectPointerType()) {
20747330f729Sjoerg T = T->getPointeeType();
20757330f729Sjoerg return T->isObjCQualifiedInterfaceType();
20767330f729Sjoerg }
20777330f729Sjoerg if (T->isArrayType()) {
20787330f729Sjoerg QualType ElemTy = Context->getBaseElementType(T);
20797330f729Sjoerg return needToScanForQualifiers(ElemTy);
20807330f729Sjoerg }
20817330f729Sjoerg return false;
20827330f729Sjoerg }
20837330f729Sjoerg
RewriteObjCQualifiedInterfaceTypes(Expr * E)20847330f729Sjoerg void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
20857330f729Sjoerg QualType Type = E->getType();
20867330f729Sjoerg if (needToScanForQualifiers(Type)) {
20877330f729Sjoerg SourceLocation Loc, EndLoc;
20887330f729Sjoerg
20897330f729Sjoerg if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
20907330f729Sjoerg Loc = ECE->getLParenLoc();
20917330f729Sjoerg EndLoc = ECE->getRParenLoc();
20927330f729Sjoerg } else {
20937330f729Sjoerg Loc = E->getBeginLoc();
20947330f729Sjoerg EndLoc = E->getEndLoc();
20957330f729Sjoerg }
20967330f729Sjoerg // This will defend against trying to rewrite synthesized expressions.
20977330f729Sjoerg if (Loc.isInvalid() || EndLoc.isInvalid())
20987330f729Sjoerg return;
20997330f729Sjoerg
21007330f729Sjoerg const char *startBuf = SM->getCharacterData(Loc);
21017330f729Sjoerg const char *endBuf = SM->getCharacterData(EndLoc);
21027330f729Sjoerg const char *startRef = nullptr, *endRef = nullptr;
21037330f729Sjoerg if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
21047330f729Sjoerg // Get the locations of the startRef, endRef.
21057330f729Sjoerg SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
21067330f729Sjoerg SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
21077330f729Sjoerg // Comment out the protocol references.
21087330f729Sjoerg InsertText(LessLoc, "/*");
21097330f729Sjoerg InsertText(GreaterLoc, "*/");
21107330f729Sjoerg }
21117330f729Sjoerg }
21127330f729Sjoerg }
21137330f729Sjoerg
RewriteObjCQualifiedInterfaceTypes(Decl * Dcl)21147330f729Sjoerg void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
21157330f729Sjoerg SourceLocation Loc;
21167330f729Sjoerg QualType Type;
21177330f729Sjoerg const FunctionProtoType *proto = nullptr;
21187330f729Sjoerg if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
21197330f729Sjoerg Loc = VD->getLocation();
21207330f729Sjoerg Type = VD->getType();
21217330f729Sjoerg }
21227330f729Sjoerg else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
21237330f729Sjoerg Loc = FD->getLocation();
21247330f729Sjoerg // Check for ObjC 'id' and class types that have been adorned with protocol
21257330f729Sjoerg // information (id<p>, C<p>*). The protocol references need to be rewritten!
21267330f729Sjoerg const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
21277330f729Sjoerg assert(funcType && "missing function type");
21287330f729Sjoerg proto = dyn_cast<FunctionProtoType>(funcType);
21297330f729Sjoerg if (!proto)
21307330f729Sjoerg return;
21317330f729Sjoerg Type = proto->getReturnType();
21327330f729Sjoerg }
21337330f729Sjoerg else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
21347330f729Sjoerg Loc = FD->getLocation();
21357330f729Sjoerg Type = FD->getType();
21367330f729Sjoerg }
21377330f729Sjoerg else
21387330f729Sjoerg return;
21397330f729Sjoerg
21407330f729Sjoerg if (needToScanForQualifiers(Type)) {
21417330f729Sjoerg // Since types are unique, we need to scan the buffer.
21427330f729Sjoerg
21437330f729Sjoerg const char *endBuf = SM->getCharacterData(Loc);
21447330f729Sjoerg const char *startBuf = endBuf;
21457330f729Sjoerg while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
21467330f729Sjoerg startBuf--; // scan backward (from the decl location) for return type.
21477330f729Sjoerg const char *startRef = nullptr, *endRef = nullptr;
21487330f729Sjoerg if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
21497330f729Sjoerg // Get the locations of the startRef, endRef.
21507330f729Sjoerg SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
21517330f729Sjoerg SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
21527330f729Sjoerg // Comment out the protocol references.
21537330f729Sjoerg InsertText(LessLoc, "/*");
21547330f729Sjoerg InsertText(GreaterLoc, "*/");
21557330f729Sjoerg }
21567330f729Sjoerg }
21577330f729Sjoerg if (!proto)
21587330f729Sjoerg return; // most likely, was a variable
21597330f729Sjoerg // Now check arguments.
21607330f729Sjoerg const char *startBuf = SM->getCharacterData(Loc);
21617330f729Sjoerg const char *startFuncBuf = startBuf;
21627330f729Sjoerg for (unsigned i = 0; i < proto->getNumParams(); i++) {
21637330f729Sjoerg if (needToScanForQualifiers(proto->getParamType(i))) {
21647330f729Sjoerg // Since types are unique, we need to scan the buffer.
21657330f729Sjoerg
21667330f729Sjoerg const char *endBuf = startBuf;
21677330f729Sjoerg // scan forward (from the decl location) for argument types.
21687330f729Sjoerg scanToNextArgument(endBuf);
21697330f729Sjoerg const char *startRef = nullptr, *endRef = nullptr;
21707330f729Sjoerg if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
21717330f729Sjoerg // Get the locations of the startRef, endRef.
21727330f729Sjoerg SourceLocation LessLoc =
21737330f729Sjoerg Loc.getLocWithOffset(startRef-startFuncBuf);
21747330f729Sjoerg SourceLocation GreaterLoc =
21757330f729Sjoerg Loc.getLocWithOffset(endRef-startFuncBuf+1);
21767330f729Sjoerg // Comment out the protocol references.
21777330f729Sjoerg InsertText(LessLoc, "/*");
21787330f729Sjoerg InsertText(GreaterLoc, "*/");
21797330f729Sjoerg }
21807330f729Sjoerg startBuf = ++endBuf;
21817330f729Sjoerg }
21827330f729Sjoerg else {
21837330f729Sjoerg // If the function name is derived from a macro expansion, then the
21847330f729Sjoerg // argument buffer will not follow the name. Need to speak with Chris.
21857330f729Sjoerg while (*startBuf && *startBuf != ')' && *startBuf != ',')
21867330f729Sjoerg startBuf++; // scan forward (from the decl location) for argument types.
21877330f729Sjoerg startBuf++;
21887330f729Sjoerg }
21897330f729Sjoerg }
21907330f729Sjoerg }
21917330f729Sjoerg
RewriteTypeOfDecl(VarDecl * ND)21927330f729Sjoerg void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
21937330f729Sjoerg QualType QT = ND->getType();
21947330f729Sjoerg const Type* TypePtr = QT->getAs<Type>();
21957330f729Sjoerg if (!isa<TypeOfExprType>(TypePtr))
21967330f729Sjoerg return;
21977330f729Sjoerg while (isa<TypeOfExprType>(TypePtr)) {
21987330f729Sjoerg const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
21997330f729Sjoerg QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
22007330f729Sjoerg TypePtr = QT->getAs<Type>();
22017330f729Sjoerg }
22027330f729Sjoerg // FIXME. This will not work for multiple declarators; as in:
22037330f729Sjoerg // __typeof__(a) b,c,d;
22047330f729Sjoerg std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
22057330f729Sjoerg SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
22067330f729Sjoerg const char *startBuf = SM->getCharacterData(DeclLoc);
22077330f729Sjoerg if (ND->getInit()) {
22087330f729Sjoerg std::string Name(ND->getNameAsString());
22097330f729Sjoerg TypeAsString += " " + Name + " = ";
22107330f729Sjoerg Expr *E = ND->getInit();
22117330f729Sjoerg SourceLocation startLoc;
22127330f729Sjoerg if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
22137330f729Sjoerg startLoc = ECE->getLParenLoc();
22147330f729Sjoerg else
22157330f729Sjoerg startLoc = E->getBeginLoc();
22167330f729Sjoerg startLoc = SM->getExpansionLoc(startLoc);
22177330f729Sjoerg const char *endBuf = SM->getCharacterData(startLoc);
22187330f729Sjoerg ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
22197330f729Sjoerg }
22207330f729Sjoerg else {
22217330f729Sjoerg SourceLocation X = ND->getEndLoc();
22227330f729Sjoerg X = SM->getExpansionLoc(X);
22237330f729Sjoerg const char *endBuf = SM->getCharacterData(X);
22247330f729Sjoerg ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
22257330f729Sjoerg }
22267330f729Sjoerg }
22277330f729Sjoerg
22287330f729Sjoerg // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
SynthSelGetUidFunctionDecl()22297330f729Sjoerg void RewriteObjC::SynthSelGetUidFunctionDecl() {
22307330f729Sjoerg IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
22317330f729Sjoerg SmallVector<QualType, 16> ArgTys;
22327330f729Sjoerg ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
22337330f729Sjoerg QualType getFuncType =
22347330f729Sjoerg getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
22357330f729Sjoerg SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
22367330f729Sjoerg SourceLocation(),
22377330f729Sjoerg SourceLocation(),
22387330f729Sjoerg SelGetUidIdent, getFuncType,
22397330f729Sjoerg nullptr, SC_Extern);
22407330f729Sjoerg }
22417330f729Sjoerg
RewriteFunctionDecl(FunctionDecl * FD)22427330f729Sjoerg void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
22437330f729Sjoerg // declared in <objc/objc.h>
22447330f729Sjoerg if (FD->getIdentifier() &&
22457330f729Sjoerg FD->getName() == "sel_registerName") {
22467330f729Sjoerg SelGetUidFunctionDecl = FD;
22477330f729Sjoerg return;
22487330f729Sjoerg }
22497330f729Sjoerg RewriteObjCQualifiedInterfaceTypes(FD);
22507330f729Sjoerg }
22517330f729Sjoerg
RewriteBlockPointerType(std::string & Str,QualType Type)22527330f729Sjoerg void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
22537330f729Sjoerg std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
22547330f729Sjoerg const char *argPtr = TypeString.c_str();
22557330f729Sjoerg if (!strchr(argPtr, '^')) {
22567330f729Sjoerg Str += TypeString;
22577330f729Sjoerg return;
22587330f729Sjoerg }
22597330f729Sjoerg while (*argPtr) {
22607330f729Sjoerg Str += (*argPtr == '^' ? '*' : *argPtr);
22617330f729Sjoerg argPtr++;
22627330f729Sjoerg }
22637330f729Sjoerg }
22647330f729Sjoerg
22657330f729Sjoerg // FIXME. Consolidate this routine with RewriteBlockPointerType.
RewriteBlockPointerTypeVariable(std::string & Str,ValueDecl * VD)22667330f729Sjoerg void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
22677330f729Sjoerg ValueDecl *VD) {
22687330f729Sjoerg QualType Type = VD->getType();
22697330f729Sjoerg std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
22707330f729Sjoerg const char *argPtr = TypeString.c_str();
22717330f729Sjoerg int paren = 0;
22727330f729Sjoerg while (*argPtr) {
22737330f729Sjoerg switch (*argPtr) {
22747330f729Sjoerg case '(':
22757330f729Sjoerg Str += *argPtr;
22767330f729Sjoerg paren++;
22777330f729Sjoerg break;
22787330f729Sjoerg case ')':
22797330f729Sjoerg Str += *argPtr;
22807330f729Sjoerg paren--;
22817330f729Sjoerg break;
22827330f729Sjoerg case '^':
22837330f729Sjoerg Str += '*';
22847330f729Sjoerg if (paren == 1)
22857330f729Sjoerg Str += VD->getNameAsString();
22867330f729Sjoerg break;
22877330f729Sjoerg default:
22887330f729Sjoerg Str += *argPtr;
22897330f729Sjoerg break;
22907330f729Sjoerg }
22917330f729Sjoerg argPtr++;
22927330f729Sjoerg }
22937330f729Sjoerg }
22947330f729Sjoerg
RewriteBlockLiteralFunctionDecl(FunctionDecl * FD)22957330f729Sjoerg void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
22967330f729Sjoerg SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
22977330f729Sjoerg const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
22987330f729Sjoerg const FunctionProtoType *proto = dyn_cast_or_null<FunctionProtoType>(funcType);
22997330f729Sjoerg if (!proto)
23007330f729Sjoerg return;
23017330f729Sjoerg QualType Type = proto->getReturnType();
23027330f729Sjoerg std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
23037330f729Sjoerg FdStr += " ";
23047330f729Sjoerg FdStr += FD->getName();
23057330f729Sjoerg FdStr += "(";
23067330f729Sjoerg unsigned numArgs = proto->getNumParams();
23077330f729Sjoerg for (unsigned i = 0; i < numArgs; i++) {
23087330f729Sjoerg QualType ArgType = proto->getParamType(i);
23097330f729Sjoerg RewriteBlockPointerType(FdStr, ArgType);
23107330f729Sjoerg if (i+1 < numArgs)
23117330f729Sjoerg FdStr += ", ";
23127330f729Sjoerg }
23137330f729Sjoerg FdStr += ");\n";
23147330f729Sjoerg InsertText(FunLocStart, FdStr);
23157330f729Sjoerg CurFunctionDeclToDeclareForBlock = nullptr;
23167330f729Sjoerg }
23177330f729Sjoerg
23187330f729Sjoerg // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
SynthSuperConstructorFunctionDecl()23197330f729Sjoerg void RewriteObjC::SynthSuperConstructorFunctionDecl() {
23207330f729Sjoerg if (SuperConstructorFunctionDecl)
23217330f729Sjoerg return;
23227330f729Sjoerg IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
23237330f729Sjoerg SmallVector<QualType, 16> ArgTys;
23247330f729Sjoerg QualType argT = Context->getObjCIdType();
23257330f729Sjoerg assert(!argT.isNull() && "Can't find 'id' type");
23267330f729Sjoerg ArgTys.push_back(argT);
23277330f729Sjoerg ArgTys.push_back(argT);
23287330f729Sjoerg QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
23297330f729Sjoerg ArgTys);
23307330f729Sjoerg SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
23317330f729Sjoerg SourceLocation(),
23327330f729Sjoerg SourceLocation(),
23337330f729Sjoerg msgSendIdent, msgSendType,
23347330f729Sjoerg nullptr, SC_Extern);
23357330f729Sjoerg }
23367330f729Sjoerg
23377330f729Sjoerg // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
SynthMsgSendFunctionDecl()23387330f729Sjoerg void RewriteObjC::SynthMsgSendFunctionDecl() {
23397330f729Sjoerg IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
23407330f729Sjoerg SmallVector<QualType, 16> ArgTys;
23417330f729Sjoerg QualType argT = Context->getObjCIdType();
23427330f729Sjoerg assert(!argT.isNull() && "Can't find 'id' type");
23437330f729Sjoerg ArgTys.push_back(argT);
23447330f729Sjoerg argT = Context->getObjCSelType();
23457330f729Sjoerg assert(!argT.isNull() && "Can't find 'SEL' type");
23467330f729Sjoerg ArgTys.push_back(argT);
23477330f729Sjoerg QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
23487330f729Sjoerg ArgTys, /*variadic=*/true);
23497330f729Sjoerg MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
23507330f729Sjoerg SourceLocation(),
23517330f729Sjoerg SourceLocation(),
23527330f729Sjoerg msgSendIdent, msgSendType,
23537330f729Sjoerg nullptr, SC_Extern);
23547330f729Sjoerg }
23557330f729Sjoerg
23567330f729Sjoerg // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
SynthMsgSendSuperFunctionDecl()23577330f729Sjoerg void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
23587330f729Sjoerg IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
23597330f729Sjoerg SmallVector<QualType, 16> ArgTys;
23607330f729Sjoerg RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
23617330f729Sjoerg SourceLocation(), SourceLocation(),
23627330f729Sjoerg &Context->Idents.get("objc_super"));
23637330f729Sjoerg QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
23647330f729Sjoerg assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
23657330f729Sjoerg ArgTys.push_back(argT);
23667330f729Sjoerg argT = Context->getObjCSelType();
23677330f729Sjoerg assert(!argT.isNull() && "Can't find 'SEL' type");
23687330f729Sjoerg ArgTys.push_back(argT);
23697330f729Sjoerg QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
23707330f729Sjoerg ArgTys, /*variadic=*/true);
23717330f729Sjoerg MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
23727330f729Sjoerg SourceLocation(),
23737330f729Sjoerg SourceLocation(),
23747330f729Sjoerg msgSendIdent, msgSendType,
23757330f729Sjoerg nullptr, SC_Extern);
23767330f729Sjoerg }
23777330f729Sjoerg
23787330f729Sjoerg // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
SynthMsgSendStretFunctionDecl()23797330f729Sjoerg void RewriteObjC::SynthMsgSendStretFunctionDecl() {
23807330f729Sjoerg IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
23817330f729Sjoerg SmallVector<QualType, 16> ArgTys;
23827330f729Sjoerg QualType argT = Context->getObjCIdType();
23837330f729Sjoerg assert(!argT.isNull() && "Can't find 'id' type");
23847330f729Sjoerg ArgTys.push_back(argT);
23857330f729Sjoerg argT = Context->getObjCSelType();
23867330f729Sjoerg assert(!argT.isNull() && "Can't find 'SEL' type");
23877330f729Sjoerg ArgTys.push_back(argT);
23887330f729Sjoerg QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
23897330f729Sjoerg ArgTys, /*variadic=*/true);
23907330f729Sjoerg MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
23917330f729Sjoerg SourceLocation(),
23927330f729Sjoerg SourceLocation(),
23937330f729Sjoerg msgSendIdent, msgSendType,
23947330f729Sjoerg nullptr, SC_Extern);
23957330f729Sjoerg }
23967330f729Sjoerg
23977330f729Sjoerg // SynthMsgSendSuperStretFunctionDecl -
23987330f729Sjoerg // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
SynthMsgSendSuperStretFunctionDecl()23997330f729Sjoerg void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
24007330f729Sjoerg IdentifierInfo *msgSendIdent =
24017330f729Sjoerg &Context->Idents.get("objc_msgSendSuper_stret");
24027330f729Sjoerg SmallVector<QualType, 16> ArgTys;
24037330f729Sjoerg RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
24047330f729Sjoerg SourceLocation(), SourceLocation(),
24057330f729Sjoerg &Context->Idents.get("objc_super"));
24067330f729Sjoerg QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
24077330f729Sjoerg assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
24087330f729Sjoerg ArgTys.push_back(argT);
24097330f729Sjoerg argT = Context->getObjCSelType();
24107330f729Sjoerg assert(!argT.isNull() && "Can't find 'SEL' type");
24117330f729Sjoerg ArgTys.push_back(argT);
24127330f729Sjoerg QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
24137330f729Sjoerg ArgTys, /*variadic=*/true);
24147330f729Sjoerg MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24157330f729Sjoerg SourceLocation(),
24167330f729Sjoerg SourceLocation(),
24177330f729Sjoerg msgSendIdent,
24187330f729Sjoerg msgSendType, nullptr,
24197330f729Sjoerg SC_Extern);
24207330f729Sjoerg }
24217330f729Sjoerg
24227330f729Sjoerg // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
SynthMsgSendFpretFunctionDecl()24237330f729Sjoerg void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
24247330f729Sjoerg IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
24257330f729Sjoerg SmallVector<QualType, 16> ArgTys;
24267330f729Sjoerg QualType argT = Context->getObjCIdType();
24277330f729Sjoerg assert(!argT.isNull() && "Can't find 'id' type");
24287330f729Sjoerg ArgTys.push_back(argT);
24297330f729Sjoerg argT = Context->getObjCSelType();
24307330f729Sjoerg assert(!argT.isNull() && "Can't find 'SEL' type");
24317330f729Sjoerg ArgTys.push_back(argT);
24327330f729Sjoerg QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
24337330f729Sjoerg ArgTys, /*variadic=*/true);
24347330f729Sjoerg MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24357330f729Sjoerg SourceLocation(),
24367330f729Sjoerg SourceLocation(),
24377330f729Sjoerg msgSendIdent, msgSendType,
24387330f729Sjoerg nullptr, SC_Extern);
24397330f729Sjoerg }
24407330f729Sjoerg
24417330f729Sjoerg // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
SynthGetClassFunctionDecl()24427330f729Sjoerg void RewriteObjC::SynthGetClassFunctionDecl() {
24437330f729Sjoerg IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
24447330f729Sjoerg SmallVector<QualType, 16> ArgTys;
24457330f729Sjoerg ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
24467330f729Sjoerg QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
24477330f729Sjoerg ArgTys);
24487330f729Sjoerg GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24497330f729Sjoerg SourceLocation(),
24507330f729Sjoerg SourceLocation(),
24517330f729Sjoerg getClassIdent, getClassType,
24527330f729Sjoerg nullptr, SC_Extern);
24537330f729Sjoerg }
24547330f729Sjoerg
24557330f729Sjoerg // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
SynthGetSuperClassFunctionDecl()24567330f729Sjoerg void RewriteObjC::SynthGetSuperClassFunctionDecl() {
24577330f729Sjoerg IdentifierInfo *getSuperClassIdent =
24587330f729Sjoerg &Context->Idents.get("class_getSuperclass");
24597330f729Sjoerg SmallVector<QualType, 16> ArgTys;
24607330f729Sjoerg ArgTys.push_back(Context->getObjCClassType());
24617330f729Sjoerg QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
24627330f729Sjoerg ArgTys);
24637330f729Sjoerg GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24647330f729Sjoerg SourceLocation(),
24657330f729Sjoerg SourceLocation(),
24667330f729Sjoerg getSuperClassIdent,
24677330f729Sjoerg getClassType, nullptr,
24687330f729Sjoerg SC_Extern);
24697330f729Sjoerg }
24707330f729Sjoerg
24717330f729Sjoerg // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
SynthGetMetaClassFunctionDecl()24727330f729Sjoerg void RewriteObjC::SynthGetMetaClassFunctionDecl() {
24737330f729Sjoerg IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
24747330f729Sjoerg SmallVector<QualType, 16> ArgTys;
24757330f729Sjoerg ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
24767330f729Sjoerg QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
24777330f729Sjoerg ArgTys);
24787330f729Sjoerg GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24797330f729Sjoerg SourceLocation(),
24807330f729Sjoerg SourceLocation(),
24817330f729Sjoerg getClassIdent, getClassType,
24827330f729Sjoerg nullptr, SC_Extern);
24837330f729Sjoerg }
24847330f729Sjoerg
RewriteObjCStringLiteral(ObjCStringLiteral * Exp)24857330f729Sjoerg Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
24867330f729Sjoerg assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
24877330f729Sjoerg QualType strType = getConstantStringStructType();
24887330f729Sjoerg
24897330f729Sjoerg std::string S = "__NSConstantStringImpl_";
24907330f729Sjoerg
24917330f729Sjoerg std::string tmpName = InFileName;
24927330f729Sjoerg unsigned i;
24937330f729Sjoerg for (i=0; i < tmpName.length(); i++) {
24947330f729Sjoerg char c = tmpName.at(i);
24957330f729Sjoerg // replace any non-alphanumeric characters with '_'.
24967330f729Sjoerg if (!isAlphanumeric(c))
24977330f729Sjoerg tmpName[i] = '_';
24987330f729Sjoerg }
24997330f729Sjoerg S += tmpName;
25007330f729Sjoerg S += "_";
25017330f729Sjoerg S += utostr(NumObjCStringLiterals++);
25027330f729Sjoerg
25037330f729Sjoerg Preamble += "static __NSConstantStringImpl " + S;
25047330f729Sjoerg Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
25057330f729Sjoerg Preamble += "0x000007c8,"; // utf8_str
25067330f729Sjoerg // The pretty printer for StringLiteral handles escape characters properly.
25077330f729Sjoerg std::string prettyBufS;
25087330f729Sjoerg llvm::raw_string_ostream prettyBuf(prettyBufS);
25097330f729Sjoerg Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
25107330f729Sjoerg Preamble += prettyBuf.str();
25117330f729Sjoerg Preamble += ",";
25127330f729Sjoerg Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
25137330f729Sjoerg
25147330f729Sjoerg VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
25157330f729Sjoerg SourceLocation(), &Context->Idents.get(S),
25167330f729Sjoerg strType, nullptr, SC_Static);
25177330f729Sjoerg DeclRefExpr *DRE = new (Context)
25187330f729Sjoerg DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2519*e038c9c4Sjoerg Expr *Unop = UnaryOperator::Create(
2520*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
2521*e038c9c4Sjoerg Context->getPointerType(DRE->getType()), VK_RValue, OK_Ordinary,
2522*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
25237330f729Sjoerg // cast to NSConstantString *
25247330f729Sjoerg CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
25257330f729Sjoerg CK_CPointerToObjCPointerCast, Unop);
25267330f729Sjoerg ReplaceStmt(Exp, cast);
25277330f729Sjoerg // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
25287330f729Sjoerg return cast;
25297330f729Sjoerg }
25307330f729Sjoerg
25317330f729Sjoerg // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
getSuperStructType()25327330f729Sjoerg QualType RewriteObjC::getSuperStructType() {
25337330f729Sjoerg if (!SuperStructDecl) {
25347330f729Sjoerg SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
25357330f729Sjoerg SourceLocation(), SourceLocation(),
25367330f729Sjoerg &Context->Idents.get("objc_super"));
25377330f729Sjoerg QualType FieldTypes[2];
25387330f729Sjoerg
25397330f729Sjoerg // struct objc_object *receiver;
25407330f729Sjoerg FieldTypes[0] = Context->getObjCIdType();
25417330f729Sjoerg // struct objc_class *super;
25427330f729Sjoerg FieldTypes[1] = Context->getObjCClassType();
25437330f729Sjoerg
25447330f729Sjoerg // Create fields
25457330f729Sjoerg for (unsigned i = 0; i < 2; ++i) {
25467330f729Sjoerg SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
25477330f729Sjoerg SourceLocation(),
25487330f729Sjoerg SourceLocation(), nullptr,
25497330f729Sjoerg FieldTypes[i], nullptr,
25507330f729Sjoerg /*BitWidth=*/nullptr,
25517330f729Sjoerg /*Mutable=*/false,
25527330f729Sjoerg ICIS_NoInit));
25537330f729Sjoerg }
25547330f729Sjoerg
25557330f729Sjoerg SuperStructDecl->completeDefinition();
25567330f729Sjoerg }
25577330f729Sjoerg return Context->getTagDeclType(SuperStructDecl);
25587330f729Sjoerg }
25597330f729Sjoerg
getConstantStringStructType()25607330f729Sjoerg QualType RewriteObjC::getConstantStringStructType() {
25617330f729Sjoerg if (!ConstantStringDecl) {
25627330f729Sjoerg ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
25637330f729Sjoerg SourceLocation(), SourceLocation(),
25647330f729Sjoerg &Context->Idents.get("__NSConstantStringImpl"));
25657330f729Sjoerg QualType FieldTypes[4];
25667330f729Sjoerg
25677330f729Sjoerg // struct objc_object *receiver;
25687330f729Sjoerg FieldTypes[0] = Context->getObjCIdType();
25697330f729Sjoerg // int flags;
25707330f729Sjoerg FieldTypes[1] = Context->IntTy;
25717330f729Sjoerg // char *str;
25727330f729Sjoerg FieldTypes[2] = Context->getPointerType(Context->CharTy);
25737330f729Sjoerg // long length;
25747330f729Sjoerg FieldTypes[3] = Context->LongTy;
25757330f729Sjoerg
25767330f729Sjoerg // Create fields
25777330f729Sjoerg for (unsigned i = 0; i < 4; ++i) {
25787330f729Sjoerg ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
25797330f729Sjoerg ConstantStringDecl,
25807330f729Sjoerg SourceLocation(),
25817330f729Sjoerg SourceLocation(), nullptr,
25827330f729Sjoerg FieldTypes[i], nullptr,
25837330f729Sjoerg /*BitWidth=*/nullptr,
25847330f729Sjoerg /*Mutable=*/true,
25857330f729Sjoerg ICIS_NoInit));
25867330f729Sjoerg }
25877330f729Sjoerg
25887330f729Sjoerg ConstantStringDecl->completeDefinition();
25897330f729Sjoerg }
25907330f729Sjoerg return Context->getTagDeclType(ConstantStringDecl);
25917330f729Sjoerg }
25927330f729Sjoerg
SynthMsgSendStretCallExpr(FunctionDecl * MsgSendStretFlavor,QualType msgSendType,QualType returnType,SmallVectorImpl<QualType> & ArgTypes,SmallVectorImpl<Expr * > & MsgExprs,ObjCMethodDecl * Method)25937330f729Sjoerg CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
25947330f729Sjoerg QualType msgSendType,
25957330f729Sjoerg QualType returnType,
25967330f729Sjoerg SmallVectorImpl<QualType> &ArgTypes,
25977330f729Sjoerg SmallVectorImpl<Expr*> &MsgExprs,
25987330f729Sjoerg ObjCMethodDecl *Method) {
25997330f729Sjoerg // Create a reference to the objc_msgSend_stret() declaration.
26007330f729Sjoerg DeclRefExpr *STDRE =
26017330f729Sjoerg new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false,
26027330f729Sjoerg msgSendType, VK_LValue, SourceLocation());
26037330f729Sjoerg // Need to cast objc_msgSend_stret to "void *" (see above comment).
26047330f729Sjoerg CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
26057330f729Sjoerg Context->getPointerType(Context->VoidTy),
26067330f729Sjoerg CK_BitCast, STDRE);
26077330f729Sjoerg // Now do the "normal" pointer to function cast.
26087330f729Sjoerg QualType castType = getSimpleFunctionType(returnType, ArgTypes,
26097330f729Sjoerg Method ? Method->isVariadic()
26107330f729Sjoerg : false);
26117330f729Sjoerg castType = Context->getPointerType(castType);
26127330f729Sjoerg cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
26137330f729Sjoerg cast);
26147330f729Sjoerg
26157330f729Sjoerg // Don't forget the parens to enforce the proper binding.
26167330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
26177330f729Sjoerg
26187330f729Sjoerg const auto *FT = msgSendType->castAs<FunctionType>();
2619*e038c9c4Sjoerg CallExpr *STCE =
2620*e038c9c4Sjoerg CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue,
2621*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
26227330f729Sjoerg return STCE;
26237330f729Sjoerg }
26247330f729Sjoerg
SynthMessageExpr(ObjCMessageExpr * Exp,SourceLocation StartLoc,SourceLocation EndLoc)26257330f729Sjoerg Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
26267330f729Sjoerg SourceLocation StartLoc,
26277330f729Sjoerg SourceLocation EndLoc) {
26287330f729Sjoerg if (!SelGetUidFunctionDecl)
26297330f729Sjoerg SynthSelGetUidFunctionDecl();
26307330f729Sjoerg if (!MsgSendFunctionDecl)
26317330f729Sjoerg SynthMsgSendFunctionDecl();
26327330f729Sjoerg if (!MsgSendSuperFunctionDecl)
26337330f729Sjoerg SynthMsgSendSuperFunctionDecl();
26347330f729Sjoerg if (!MsgSendStretFunctionDecl)
26357330f729Sjoerg SynthMsgSendStretFunctionDecl();
26367330f729Sjoerg if (!MsgSendSuperStretFunctionDecl)
26377330f729Sjoerg SynthMsgSendSuperStretFunctionDecl();
26387330f729Sjoerg if (!MsgSendFpretFunctionDecl)
26397330f729Sjoerg SynthMsgSendFpretFunctionDecl();
26407330f729Sjoerg if (!GetClassFunctionDecl)
26417330f729Sjoerg SynthGetClassFunctionDecl();
26427330f729Sjoerg if (!GetSuperClassFunctionDecl)
26437330f729Sjoerg SynthGetSuperClassFunctionDecl();
26447330f729Sjoerg if (!GetMetaClassFunctionDecl)
26457330f729Sjoerg SynthGetMetaClassFunctionDecl();
26467330f729Sjoerg
26477330f729Sjoerg // default to objc_msgSend().
26487330f729Sjoerg FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
26497330f729Sjoerg // May need to use objc_msgSend_stret() as well.
26507330f729Sjoerg FunctionDecl *MsgSendStretFlavor = nullptr;
26517330f729Sjoerg if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
26527330f729Sjoerg QualType resultType = mDecl->getReturnType();
26537330f729Sjoerg if (resultType->isRecordType())
26547330f729Sjoerg MsgSendStretFlavor = MsgSendStretFunctionDecl;
26557330f729Sjoerg else if (resultType->isRealFloatingType())
26567330f729Sjoerg MsgSendFlavor = MsgSendFpretFunctionDecl;
26577330f729Sjoerg }
26587330f729Sjoerg
26597330f729Sjoerg // Synthesize a call to objc_msgSend().
26607330f729Sjoerg SmallVector<Expr*, 8> MsgExprs;
26617330f729Sjoerg switch (Exp->getReceiverKind()) {
26627330f729Sjoerg case ObjCMessageExpr::SuperClass: {
26637330f729Sjoerg MsgSendFlavor = MsgSendSuperFunctionDecl;
26647330f729Sjoerg if (MsgSendStretFlavor)
26657330f729Sjoerg MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
26667330f729Sjoerg assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
26677330f729Sjoerg
26687330f729Sjoerg ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
26697330f729Sjoerg
26707330f729Sjoerg SmallVector<Expr*, 4> InitExprs;
26717330f729Sjoerg
26727330f729Sjoerg // set the receiver to self, the first argument to all methods.
26737330f729Sjoerg InitExprs.push_back(
26747330f729Sjoerg NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
26757330f729Sjoerg CK_BitCast,
26767330f729Sjoerg new (Context) DeclRefExpr(*Context,
26777330f729Sjoerg CurMethodDef->getSelfDecl(),
26787330f729Sjoerg false,
26797330f729Sjoerg Context->getObjCIdType(),
26807330f729Sjoerg VK_RValue,
26817330f729Sjoerg SourceLocation()))
26827330f729Sjoerg ); // set the 'receiver'.
26837330f729Sjoerg
26847330f729Sjoerg // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
26857330f729Sjoerg SmallVector<Expr*, 8> ClsExprs;
26867330f729Sjoerg ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
26877330f729Sjoerg CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
26887330f729Sjoerg ClsExprs, StartLoc, EndLoc);
26897330f729Sjoerg // (Class)objc_getClass("CurrentClass")
26907330f729Sjoerg CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
26917330f729Sjoerg Context->getObjCClassType(),
26927330f729Sjoerg CK_BitCast, Cls);
26937330f729Sjoerg ClsExprs.clear();
26947330f729Sjoerg ClsExprs.push_back(ArgExpr);
26957330f729Sjoerg Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
26967330f729Sjoerg StartLoc, EndLoc);
26977330f729Sjoerg // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
26987330f729Sjoerg // To turn off a warning, type-cast to 'id'
26997330f729Sjoerg InitExprs.push_back( // set 'super class', using class_getSuperclass().
27007330f729Sjoerg NoTypeInfoCStyleCastExpr(Context,
27017330f729Sjoerg Context->getObjCIdType(),
27027330f729Sjoerg CK_BitCast, Cls));
27037330f729Sjoerg // struct objc_super
27047330f729Sjoerg QualType superType = getSuperStructType();
27057330f729Sjoerg Expr *SuperRep;
27067330f729Sjoerg
27077330f729Sjoerg if (LangOpts.MicrosoftExt) {
27087330f729Sjoerg SynthSuperConstructorFunctionDecl();
27097330f729Sjoerg // Simulate a constructor call...
27107330f729Sjoerg DeclRefExpr *DRE = new (Context)
27117330f729Sjoerg DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
27127330f729Sjoerg VK_LValue, SourceLocation());
2713*e038c9c4Sjoerg SuperRep =
2714*e038c9c4Sjoerg CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
2715*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
27167330f729Sjoerg // The code for super is a little tricky to prevent collision with
27177330f729Sjoerg // the structure definition in the header. The rewriter has it's own
27187330f729Sjoerg // internal definition (__rw_objc_super) that is uses. This is why
27197330f729Sjoerg // we need the cast below. For example:
27207330f729Sjoerg // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
27217330f729Sjoerg //
2722*e038c9c4Sjoerg SuperRep = UnaryOperator::Create(
2723*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
2724*e038c9c4Sjoerg Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
2725*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
27267330f729Sjoerg SuperRep = NoTypeInfoCStyleCastExpr(Context,
27277330f729Sjoerg Context->getPointerType(superType),
27287330f729Sjoerg CK_BitCast, SuperRep);
27297330f729Sjoerg } else {
27307330f729Sjoerg // (struct objc_super) { <exprs from above> }
27317330f729Sjoerg InitListExpr *ILE =
27327330f729Sjoerg new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
27337330f729Sjoerg SourceLocation());
27347330f729Sjoerg TypeSourceInfo *superTInfo
27357330f729Sjoerg = Context->getTrivialTypeSourceInfo(superType);
27367330f729Sjoerg SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
27377330f729Sjoerg superType, VK_LValue,
27387330f729Sjoerg ILE, false);
27397330f729Sjoerg // struct objc_super *
2740*e038c9c4Sjoerg SuperRep = UnaryOperator::Create(
2741*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
2742*e038c9c4Sjoerg Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
2743*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
27447330f729Sjoerg }
27457330f729Sjoerg MsgExprs.push_back(SuperRep);
27467330f729Sjoerg break;
27477330f729Sjoerg }
27487330f729Sjoerg
27497330f729Sjoerg case ObjCMessageExpr::Class: {
27507330f729Sjoerg SmallVector<Expr*, 8> ClsExprs;
27517330f729Sjoerg auto *Class =
27527330f729Sjoerg Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
27537330f729Sjoerg IdentifierInfo *clsName = Class->getIdentifier();
27547330f729Sjoerg ClsExprs.push_back(getStringLiteral(clsName->getName()));
27557330f729Sjoerg CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
27567330f729Sjoerg StartLoc, EndLoc);
27577330f729Sjoerg MsgExprs.push_back(Cls);
27587330f729Sjoerg break;
27597330f729Sjoerg }
27607330f729Sjoerg
27617330f729Sjoerg case ObjCMessageExpr::SuperInstance:{
27627330f729Sjoerg MsgSendFlavor = MsgSendSuperFunctionDecl;
27637330f729Sjoerg if (MsgSendStretFlavor)
27647330f729Sjoerg MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
27657330f729Sjoerg assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
27667330f729Sjoerg ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
27677330f729Sjoerg SmallVector<Expr*, 4> InitExprs;
27687330f729Sjoerg
27697330f729Sjoerg InitExprs.push_back(
27707330f729Sjoerg NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
27717330f729Sjoerg CK_BitCast,
27727330f729Sjoerg new (Context) DeclRefExpr(*Context,
27737330f729Sjoerg CurMethodDef->getSelfDecl(),
27747330f729Sjoerg false,
27757330f729Sjoerg Context->getObjCIdType(),
27767330f729Sjoerg VK_RValue, SourceLocation()))
27777330f729Sjoerg ); // set the 'receiver'.
27787330f729Sjoerg
27797330f729Sjoerg // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
27807330f729Sjoerg SmallVector<Expr*, 8> ClsExprs;
27817330f729Sjoerg ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
27827330f729Sjoerg CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
27837330f729Sjoerg StartLoc, EndLoc);
27847330f729Sjoerg // (Class)objc_getClass("CurrentClass")
27857330f729Sjoerg CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
27867330f729Sjoerg Context->getObjCClassType(),
27877330f729Sjoerg CK_BitCast, Cls);
27887330f729Sjoerg ClsExprs.clear();
27897330f729Sjoerg ClsExprs.push_back(ArgExpr);
27907330f729Sjoerg Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
27917330f729Sjoerg StartLoc, EndLoc);
27927330f729Sjoerg
27937330f729Sjoerg // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
27947330f729Sjoerg // To turn off a warning, type-cast to 'id'
27957330f729Sjoerg InitExprs.push_back(
27967330f729Sjoerg // set 'super class', using class_getSuperclass().
27977330f729Sjoerg NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
27987330f729Sjoerg CK_BitCast, Cls));
27997330f729Sjoerg // struct objc_super
28007330f729Sjoerg QualType superType = getSuperStructType();
28017330f729Sjoerg Expr *SuperRep;
28027330f729Sjoerg
28037330f729Sjoerg if (LangOpts.MicrosoftExt) {
28047330f729Sjoerg SynthSuperConstructorFunctionDecl();
28057330f729Sjoerg // Simulate a constructor call...
28067330f729Sjoerg DeclRefExpr *DRE = new (Context)
28077330f729Sjoerg DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
28087330f729Sjoerg VK_LValue, SourceLocation());
2809*e038c9c4Sjoerg SuperRep =
2810*e038c9c4Sjoerg CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
2811*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
28127330f729Sjoerg // The code for super is a little tricky to prevent collision with
28137330f729Sjoerg // the structure definition in the header. The rewriter has it's own
28147330f729Sjoerg // internal definition (__rw_objc_super) that is uses. This is why
28157330f729Sjoerg // we need the cast below. For example:
28167330f729Sjoerg // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
28177330f729Sjoerg //
2818*e038c9c4Sjoerg SuperRep = UnaryOperator::Create(
2819*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
2820*e038c9c4Sjoerg Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
2821*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
28227330f729Sjoerg SuperRep = NoTypeInfoCStyleCastExpr(Context,
28237330f729Sjoerg Context->getPointerType(superType),
28247330f729Sjoerg CK_BitCast, SuperRep);
28257330f729Sjoerg } else {
28267330f729Sjoerg // (struct objc_super) { <exprs from above> }
28277330f729Sjoerg InitListExpr *ILE =
28287330f729Sjoerg new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
28297330f729Sjoerg SourceLocation());
28307330f729Sjoerg TypeSourceInfo *superTInfo
28317330f729Sjoerg = Context->getTrivialTypeSourceInfo(superType);
28327330f729Sjoerg SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
28337330f729Sjoerg superType, VK_RValue, ILE,
28347330f729Sjoerg false);
28357330f729Sjoerg }
28367330f729Sjoerg MsgExprs.push_back(SuperRep);
28377330f729Sjoerg break;
28387330f729Sjoerg }
28397330f729Sjoerg
28407330f729Sjoerg case ObjCMessageExpr::Instance: {
28417330f729Sjoerg // Remove all type-casts because it may contain objc-style types; e.g.
28427330f729Sjoerg // Foo<Proto> *.
28437330f729Sjoerg Expr *recExpr = Exp->getInstanceReceiver();
28447330f729Sjoerg while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
28457330f729Sjoerg recExpr = CE->getSubExpr();
28467330f729Sjoerg CastKind CK = recExpr->getType()->isObjCObjectPointerType()
28477330f729Sjoerg ? CK_BitCast : recExpr->getType()->isBlockPointerType()
28487330f729Sjoerg ? CK_BlockPointerToObjCPointerCast
28497330f729Sjoerg : CK_CPointerToObjCPointerCast;
28507330f729Sjoerg
28517330f729Sjoerg recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
28527330f729Sjoerg CK, recExpr);
28537330f729Sjoerg MsgExprs.push_back(recExpr);
28547330f729Sjoerg break;
28557330f729Sjoerg }
28567330f729Sjoerg }
28577330f729Sjoerg
28587330f729Sjoerg // Create a call to sel_registerName("selName"), it will be the 2nd argument.
28597330f729Sjoerg SmallVector<Expr*, 8> SelExprs;
28607330f729Sjoerg SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
28617330f729Sjoerg CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
28627330f729Sjoerg SelExprs, StartLoc, EndLoc);
28637330f729Sjoerg MsgExprs.push_back(SelExp);
28647330f729Sjoerg
28657330f729Sjoerg // Now push any user supplied arguments.
28667330f729Sjoerg for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
28677330f729Sjoerg Expr *userExpr = Exp->getArg(i);
28687330f729Sjoerg // Make all implicit casts explicit...ICE comes in handy:-)
28697330f729Sjoerg if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
28707330f729Sjoerg // Reuse the ICE type, it is exactly what the doctor ordered.
28717330f729Sjoerg QualType type = ICE->getType();
28727330f729Sjoerg if (needToScanForQualifiers(type))
28737330f729Sjoerg type = Context->getObjCIdType();
28747330f729Sjoerg // Make sure we convert "type (^)(...)" to "type (*)(...)".
28757330f729Sjoerg (void)convertBlockPointerToFunctionPointer(type);
28767330f729Sjoerg const Expr *SubExpr = ICE->IgnoreParenImpCasts();
28777330f729Sjoerg CastKind CK;
28787330f729Sjoerg if (SubExpr->getType()->isIntegralType(*Context) &&
28797330f729Sjoerg type->isBooleanType()) {
28807330f729Sjoerg CK = CK_IntegralToBoolean;
28817330f729Sjoerg } else if (type->isObjCObjectPointerType()) {
28827330f729Sjoerg if (SubExpr->getType()->isBlockPointerType()) {
28837330f729Sjoerg CK = CK_BlockPointerToObjCPointerCast;
28847330f729Sjoerg } else if (SubExpr->getType()->isPointerType()) {
28857330f729Sjoerg CK = CK_CPointerToObjCPointerCast;
28867330f729Sjoerg } else {
28877330f729Sjoerg CK = CK_BitCast;
28887330f729Sjoerg }
28897330f729Sjoerg } else {
28907330f729Sjoerg CK = CK_BitCast;
28917330f729Sjoerg }
28927330f729Sjoerg
28937330f729Sjoerg userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
28947330f729Sjoerg }
28957330f729Sjoerg // Make id<P...> cast into an 'id' cast.
28967330f729Sjoerg else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
28977330f729Sjoerg if (CE->getType()->isObjCQualifiedIdType()) {
28987330f729Sjoerg while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
28997330f729Sjoerg userExpr = CE->getSubExpr();
29007330f729Sjoerg CastKind CK;
29017330f729Sjoerg if (userExpr->getType()->isIntegralType(*Context)) {
29027330f729Sjoerg CK = CK_IntegralToPointer;
29037330f729Sjoerg } else if (userExpr->getType()->isBlockPointerType()) {
29047330f729Sjoerg CK = CK_BlockPointerToObjCPointerCast;
29057330f729Sjoerg } else if (userExpr->getType()->isPointerType()) {
29067330f729Sjoerg CK = CK_CPointerToObjCPointerCast;
29077330f729Sjoerg } else {
29087330f729Sjoerg CK = CK_BitCast;
29097330f729Sjoerg }
29107330f729Sjoerg userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
29117330f729Sjoerg CK, userExpr);
29127330f729Sjoerg }
29137330f729Sjoerg }
29147330f729Sjoerg MsgExprs.push_back(userExpr);
29157330f729Sjoerg // We've transferred the ownership to MsgExprs. For now, we *don't* null
29167330f729Sjoerg // out the argument in the original expression (since we aren't deleting
29177330f729Sjoerg // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
29187330f729Sjoerg //Exp->setArg(i, 0);
29197330f729Sjoerg }
29207330f729Sjoerg // Generate the funky cast.
29217330f729Sjoerg CastExpr *cast;
29227330f729Sjoerg SmallVector<QualType, 8> ArgTypes;
29237330f729Sjoerg QualType returnType;
29247330f729Sjoerg
29257330f729Sjoerg // Push 'id' and 'SEL', the 2 implicit arguments.
29267330f729Sjoerg if (MsgSendFlavor == MsgSendSuperFunctionDecl)
29277330f729Sjoerg ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
29287330f729Sjoerg else
29297330f729Sjoerg ArgTypes.push_back(Context->getObjCIdType());
29307330f729Sjoerg ArgTypes.push_back(Context->getObjCSelType());
29317330f729Sjoerg if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
29327330f729Sjoerg // Push any user argument types.
29337330f729Sjoerg for (const auto *PI : OMD->parameters()) {
29347330f729Sjoerg QualType t = PI->getType()->isObjCQualifiedIdType()
29357330f729Sjoerg ? Context->getObjCIdType()
29367330f729Sjoerg : PI->getType();
29377330f729Sjoerg // Make sure we convert "t (^)(...)" to "t (*)(...)".
29387330f729Sjoerg (void)convertBlockPointerToFunctionPointer(t);
29397330f729Sjoerg ArgTypes.push_back(t);
29407330f729Sjoerg }
29417330f729Sjoerg returnType = Exp->getType();
29427330f729Sjoerg convertToUnqualifiedObjCType(returnType);
29437330f729Sjoerg (void)convertBlockPointerToFunctionPointer(returnType);
29447330f729Sjoerg } else {
29457330f729Sjoerg returnType = Context->getObjCIdType();
29467330f729Sjoerg }
29477330f729Sjoerg // Get the type, we will need to reference it in a couple spots.
29487330f729Sjoerg QualType msgSendType = MsgSendFlavor->getType();
29497330f729Sjoerg
29507330f729Sjoerg // Create a reference to the objc_msgSend() declaration.
29517330f729Sjoerg DeclRefExpr *DRE = new (Context) DeclRefExpr(
29527330f729Sjoerg *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
29537330f729Sjoerg
29547330f729Sjoerg // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
29557330f729Sjoerg // If we don't do this cast, we get the following bizarre warning/note:
29567330f729Sjoerg // xx.m:13: warning: function called through a non-compatible type
29577330f729Sjoerg // xx.m:13: note: if this code is reached, the program will abort
29587330f729Sjoerg cast = NoTypeInfoCStyleCastExpr(Context,
29597330f729Sjoerg Context->getPointerType(Context->VoidTy),
29607330f729Sjoerg CK_BitCast, DRE);
29617330f729Sjoerg
29627330f729Sjoerg // Now do the "normal" pointer to function cast.
29637330f729Sjoerg // If we don't have a method decl, force a variadic cast.
29647330f729Sjoerg const ObjCMethodDecl *MD = Exp->getMethodDecl();
29657330f729Sjoerg QualType castType =
29667330f729Sjoerg getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
29677330f729Sjoerg castType = Context->getPointerType(castType);
29687330f729Sjoerg cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
29697330f729Sjoerg cast);
29707330f729Sjoerg
29717330f729Sjoerg // Don't forget the parens to enforce the proper binding.
29727330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
29737330f729Sjoerg
29747330f729Sjoerg const auto *FT = msgSendType->castAs<FunctionType>();
29757330f729Sjoerg CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2976*e038c9c4Sjoerg VK_RValue, EndLoc, FPOptionsOverride());
29777330f729Sjoerg Stmt *ReplacingStmt = CE;
29787330f729Sjoerg if (MsgSendStretFlavor) {
29797330f729Sjoerg // We have the method which returns a struct/union. Must also generate
29807330f729Sjoerg // call to objc_msgSend_stret and hang both varieties on a conditional
29817330f729Sjoerg // expression which dictate which one to envoke depending on size of
29827330f729Sjoerg // method's return type.
29837330f729Sjoerg
29847330f729Sjoerg CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
29857330f729Sjoerg msgSendType, returnType,
29867330f729Sjoerg ArgTypes, MsgExprs,
29877330f729Sjoerg Exp->getMethodDecl());
29887330f729Sjoerg
29897330f729Sjoerg // Build sizeof(returnType)
29907330f729Sjoerg UnaryExprOrTypeTraitExpr *sizeofExpr =
29917330f729Sjoerg new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
29927330f729Sjoerg Context->getTrivialTypeSourceInfo(returnType),
29937330f729Sjoerg Context->getSizeType(), SourceLocation(),
29947330f729Sjoerg SourceLocation());
29957330f729Sjoerg // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
29967330f729Sjoerg // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
29977330f729Sjoerg // For X86 it is more complicated and some kind of target specific routine
29987330f729Sjoerg // is needed to decide what to do.
29997330f729Sjoerg unsigned IntSize =
30007330f729Sjoerg static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
30017330f729Sjoerg IntegerLiteral *limit = IntegerLiteral::Create(*Context,
30027330f729Sjoerg llvm::APInt(IntSize, 8),
30037330f729Sjoerg Context->IntTy,
30047330f729Sjoerg SourceLocation());
3005*e038c9c4Sjoerg BinaryOperator *lessThanExpr = BinaryOperator::Create(
3006*e038c9c4Sjoerg *Context, sizeofExpr, limit, BO_LE, Context->IntTy, VK_RValue,
3007*e038c9c4Sjoerg OK_Ordinary, SourceLocation(), FPOptionsOverride());
30087330f729Sjoerg // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
30097330f729Sjoerg ConditionalOperator *CondExpr =
30107330f729Sjoerg new (Context) ConditionalOperator(lessThanExpr,
30117330f729Sjoerg SourceLocation(), CE,
30127330f729Sjoerg SourceLocation(), STCE,
30137330f729Sjoerg returnType, VK_RValue, OK_Ordinary);
30147330f729Sjoerg ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
30157330f729Sjoerg CondExpr);
30167330f729Sjoerg }
30177330f729Sjoerg // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
30187330f729Sjoerg return ReplacingStmt;
30197330f729Sjoerg }
30207330f729Sjoerg
RewriteMessageExpr(ObjCMessageExpr * Exp)30217330f729Sjoerg Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
30227330f729Sjoerg Stmt *ReplacingStmt =
30237330f729Sjoerg SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
30247330f729Sjoerg
30257330f729Sjoerg // Now do the actual rewrite.
30267330f729Sjoerg ReplaceStmt(Exp, ReplacingStmt);
30277330f729Sjoerg
30287330f729Sjoerg // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
30297330f729Sjoerg return ReplacingStmt;
30307330f729Sjoerg }
30317330f729Sjoerg
30327330f729Sjoerg // typedef struct objc_object Protocol;
getProtocolType()30337330f729Sjoerg QualType RewriteObjC::getProtocolType() {
30347330f729Sjoerg if (!ProtocolTypeDecl) {
30357330f729Sjoerg TypeSourceInfo *TInfo
30367330f729Sjoerg = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
30377330f729Sjoerg ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
30387330f729Sjoerg SourceLocation(), SourceLocation(),
30397330f729Sjoerg &Context->Idents.get("Protocol"),
30407330f729Sjoerg TInfo);
30417330f729Sjoerg }
30427330f729Sjoerg return Context->getTypeDeclType(ProtocolTypeDecl);
30437330f729Sjoerg }
30447330f729Sjoerg
30457330f729Sjoerg /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
30467330f729Sjoerg /// a synthesized/forward data reference (to the protocol's metadata).
30477330f729Sjoerg /// The forward references (and metadata) are generated in
30487330f729Sjoerg /// RewriteObjC::HandleTranslationUnit().
RewriteObjCProtocolExpr(ObjCProtocolExpr * Exp)30497330f729Sjoerg Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
30507330f729Sjoerg std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
30517330f729Sjoerg IdentifierInfo *ID = &Context->Idents.get(Name);
30527330f729Sjoerg VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
30537330f729Sjoerg SourceLocation(), ID, getProtocolType(),
30547330f729Sjoerg nullptr, SC_Extern);
30557330f729Sjoerg DeclRefExpr *DRE = new (Context) DeclRefExpr(
30567330f729Sjoerg *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3057*e038c9c4Sjoerg Expr *DerefExpr = UnaryOperator::Create(
3058*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
3059*e038c9c4Sjoerg Context->getPointerType(DRE->getType()), VK_RValue, OK_Ordinary,
3060*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
30617330f729Sjoerg CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
30627330f729Sjoerg CK_BitCast,
30637330f729Sjoerg DerefExpr);
30647330f729Sjoerg ReplaceStmt(Exp, castExpr);
30657330f729Sjoerg ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
30667330f729Sjoerg // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
30677330f729Sjoerg return castExpr;
30687330f729Sjoerg }
30697330f729Sjoerg
BufferContainsPPDirectives(const char * startBuf,const char * endBuf)30707330f729Sjoerg bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
30717330f729Sjoerg const char *endBuf) {
30727330f729Sjoerg while (startBuf < endBuf) {
30737330f729Sjoerg if (*startBuf == '#') {
30747330f729Sjoerg // Skip whitespace.
30757330f729Sjoerg for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
30767330f729Sjoerg ;
30777330f729Sjoerg if (!strncmp(startBuf, "if", strlen("if")) ||
30787330f729Sjoerg !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
30797330f729Sjoerg !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
30807330f729Sjoerg !strncmp(startBuf, "define", strlen("define")) ||
30817330f729Sjoerg !strncmp(startBuf, "undef", strlen("undef")) ||
30827330f729Sjoerg !strncmp(startBuf, "else", strlen("else")) ||
30837330f729Sjoerg !strncmp(startBuf, "elif", strlen("elif")) ||
30847330f729Sjoerg !strncmp(startBuf, "endif", strlen("endif")) ||
30857330f729Sjoerg !strncmp(startBuf, "pragma", strlen("pragma")) ||
30867330f729Sjoerg !strncmp(startBuf, "include", strlen("include")) ||
30877330f729Sjoerg !strncmp(startBuf, "import", strlen("import")) ||
30887330f729Sjoerg !strncmp(startBuf, "include_next", strlen("include_next")))
30897330f729Sjoerg return true;
30907330f729Sjoerg }
30917330f729Sjoerg startBuf++;
30927330f729Sjoerg }
30937330f729Sjoerg return false;
30947330f729Sjoerg }
30957330f729Sjoerg
30967330f729Sjoerg /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
30977330f729Sjoerg /// an objective-c class with ivars.
RewriteObjCInternalStruct(ObjCInterfaceDecl * CDecl,std::string & Result)30987330f729Sjoerg void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
30997330f729Sjoerg std::string &Result) {
31007330f729Sjoerg assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
31017330f729Sjoerg assert(CDecl->getName() != "" &&
31027330f729Sjoerg "Name missing in SynthesizeObjCInternalStruct");
31037330f729Sjoerg // Do not synthesize more than once.
31047330f729Sjoerg if (ObjCSynthesizedStructs.count(CDecl))
31057330f729Sjoerg return;
31067330f729Sjoerg ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
31077330f729Sjoerg int NumIvars = CDecl->ivar_size();
31087330f729Sjoerg SourceLocation LocStart = CDecl->getBeginLoc();
31097330f729Sjoerg SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
31107330f729Sjoerg
31117330f729Sjoerg const char *startBuf = SM->getCharacterData(LocStart);
31127330f729Sjoerg const char *endBuf = SM->getCharacterData(LocEnd);
31137330f729Sjoerg
31147330f729Sjoerg // If no ivars and no root or if its root, directly or indirectly,
31157330f729Sjoerg // have no ivars (thus not synthesized) then no need to synthesize this class.
31167330f729Sjoerg if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
31177330f729Sjoerg (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
31187330f729Sjoerg endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
31197330f729Sjoerg ReplaceText(LocStart, endBuf-startBuf, Result);
31207330f729Sjoerg return;
31217330f729Sjoerg }
31227330f729Sjoerg
31237330f729Sjoerg // FIXME: This has potential of causing problem. If
31247330f729Sjoerg // SynthesizeObjCInternalStruct is ever called recursively.
31257330f729Sjoerg Result += "\nstruct ";
31267330f729Sjoerg Result += CDecl->getNameAsString();
31277330f729Sjoerg if (LangOpts.MicrosoftExt)
31287330f729Sjoerg Result += "_IMPL";
31297330f729Sjoerg
31307330f729Sjoerg if (NumIvars > 0) {
31317330f729Sjoerg const char *cursor = strchr(startBuf, '{');
31327330f729Sjoerg assert((cursor && endBuf)
31337330f729Sjoerg && "SynthesizeObjCInternalStruct - malformed @interface");
31347330f729Sjoerg // If the buffer contains preprocessor directives, we do more fine-grained
31357330f729Sjoerg // rewrites. This is intended to fix code that looks like (which occurs in
31367330f729Sjoerg // NSURL.h, for example):
31377330f729Sjoerg //
31387330f729Sjoerg // #ifdef XYZ
31397330f729Sjoerg // @interface Foo : NSObject
31407330f729Sjoerg // #else
31417330f729Sjoerg // @interface FooBar : NSObject
31427330f729Sjoerg // #endif
31437330f729Sjoerg // {
31447330f729Sjoerg // int i;
31457330f729Sjoerg // }
31467330f729Sjoerg // @end
31477330f729Sjoerg //
31487330f729Sjoerg // This clause is segregated to avoid breaking the common case.
31497330f729Sjoerg if (BufferContainsPPDirectives(startBuf, cursor)) {
31507330f729Sjoerg SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
31517330f729Sjoerg CDecl->getAtStartLoc();
31527330f729Sjoerg const char *endHeader = SM->getCharacterData(L);
31537330f729Sjoerg endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
31547330f729Sjoerg
31557330f729Sjoerg if (CDecl->protocol_begin() != CDecl->protocol_end()) {
31567330f729Sjoerg // advance to the end of the referenced protocols.
31577330f729Sjoerg while (endHeader < cursor && *endHeader != '>') endHeader++;
31587330f729Sjoerg endHeader++;
31597330f729Sjoerg }
31607330f729Sjoerg // rewrite the original header
31617330f729Sjoerg ReplaceText(LocStart, endHeader-startBuf, Result);
31627330f729Sjoerg } else {
31637330f729Sjoerg // rewrite the original header *without* disturbing the '{'
31647330f729Sjoerg ReplaceText(LocStart, cursor-startBuf, Result);
31657330f729Sjoerg }
31667330f729Sjoerg if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
31677330f729Sjoerg Result = "\n struct ";
31687330f729Sjoerg Result += RCDecl->getNameAsString();
31697330f729Sjoerg Result += "_IMPL ";
31707330f729Sjoerg Result += RCDecl->getNameAsString();
31717330f729Sjoerg Result += "_IVARS;\n";
31727330f729Sjoerg
31737330f729Sjoerg // insert the super class structure definition.
31747330f729Sjoerg SourceLocation OnePastCurly =
31757330f729Sjoerg LocStart.getLocWithOffset(cursor-startBuf+1);
31767330f729Sjoerg InsertText(OnePastCurly, Result);
31777330f729Sjoerg }
31787330f729Sjoerg cursor++; // past '{'
31797330f729Sjoerg
31807330f729Sjoerg // Now comment out any visibility specifiers.
31817330f729Sjoerg while (cursor < endBuf) {
31827330f729Sjoerg if (*cursor == '@') {
31837330f729Sjoerg SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
31847330f729Sjoerg // Skip whitespace.
31857330f729Sjoerg for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
31867330f729Sjoerg /*scan*/;
31877330f729Sjoerg
31887330f729Sjoerg // FIXME: presence of @public, etc. inside comment results in
31897330f729Sjoerg // this transformation as well, which is still correct c-code.
31907330f729Sjoerg if (!strncmp(cursor, "public", strlen("public")) ||
31917330f729Sjoerg !strncmp(cursor, "private", strlen("private")) ||
31927330f729Sjoerg !strncmp(cursor, "package", strlen("package")) ||
31937330f729Sjoerg !strncmp(cursor, "protected", strlen("protected")))
31947330f729Sjoerg InsertText(atLoc, "// ");
31957330f729Sjoerg }
31967330f729Sjoerg // FIXME: If there are cases where '<' is used in ivar declaration part
31977330f729Sjoerg // of user code, then scan the ivar list and use needToScanForQualifiers
31987330f729Sjoerg // for type checking.
31997330f729Sjoerg else if (*cursor == '<') {
32007330f729Sjoerg SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
32017330f729Sjoerg InsertText(atLoc, "/* ");
32027330f729Sjoerg cursor = strchr(cursor, '>');
32037330f729Sjoerg cursor++;
32047330f729Sjoerg atLoc = LocStart.getLocWithOffset(cursor-startBuf);
32057330f729Sjoerg InsertText(atLoc, " */");
32067330f729Sjoerg } else if (*cursor == '^') { // rewrite block specifier.
32077330f729Sjoerg SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
32087330f729Sjoerg ReplaceText(caretLoc, 1, "*");
32097330f729Sjoerg }
32107330f729Sjoerg cursor++;
32117330f729Sjoerg }
32127330f729Sjoerg // Don't forget to add a ';'!!
32137330f729Sjoerg InsertText(LocEnd.getLocWithOffset(1), ";");
32147330f729Sjoerg } else { // we don't have any instance variables - insert super struct.
32157330f729Sjoerg endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
32167330f729Sjoerg Result += " {\n struct ";
32177330f729Sjoerg Result += RCDecl->getNameAsString();
32187330f729Sjoerg Result += "_IMPL ";
32197330f729Sjoerg Result += RCDecl->getNameAsString();
32207330f729Sjoerg Result += "_IVARS;\n};\n";
32217330f729Sjoerg ReplaceText(LocStart, endBuf-startBuf, Result);
32227330f729Sjoerg }
32237330f729Sjoerg // Mark this struct as having been generated.
32247330f729Sjoerg if (!ObjCSynthesizedStructs.insert(CDecl).second)
32257330f729Sjoerg llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
32267330f729Sjoerg }
32277330f729Sjoerg
32287330f729Sjoerg //===----------------------------------------------------------------------===//
32297330f729Sjoerg // Meta Data Emission
32307330f729Sjoerg //===----------------------------------------------------------------------===//
32317330f729Sjoerg
32327330f729Sjoerg /// RewriteImplementations - This routine rewrites all method implementations
32337330f729Sjoerg /// and emits meta-data.
32347330f729Sjoerg
RewriteImplementations()32357330f729Sjoerg void RewriteObjC::RewriteImplementations() {
32367330f729Sjoerg int ClsDefCount = ClassImplementation.size();
32377330f729Sjoerg int CatDefCount = CategoryImplementation.size();
32387330f729Sjoerg
32397330f729Sjoerg // Rewrite implemented methods
32407330f729Sjoerg for (int i = 0; i < ClsDefCount; i++)
32417330f729Sjoerg RewriteImplementationDecl(ClassImplementation[i]);
32427330f729Sjoerg
32437330f729Sjoerg for (int i = 0; i < CatDefCount; i++)
32447330f729Sjoerg RewriteImplementationDecl(CategoryImplementation[i]);
32457330f729Sjoerg }
32467330f729Sjoerg
RewriteByRefString(std::string & ResultStr,const std::string & Name,ValueDecl * VD,bool def)32477330f729Sjoerg void RewriteObjC::RewriteByRefString(std::string &ResultStr,
32487330f729Sjoerg const std::string &Name,
32497330f729Sjoerg ValueDecl *VD, bool def) {
32507330f729Sjoerg assert(BlockByRefDeclNo.count(VD) &&
32517330f729Sjoerg "RewriteByRefString: ByRef decl missing");
32527330f729Sjoerg if (def)
32537330f729Sjoerg ResultStr += "struct ";
32547330f729Sjoerg ResultStr += "__Block_byref_" + Name +
32557330f729Sjoerg "_" + utostr(BlockByRefDeclNo[VD]) ;
32567330f729Sjoerg }
32577330f729Sjoerg
HasLocalVariableExternalStorage(ValueDecl * VD)32587330f729Sjoerg static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
32597330f729Sjoerg if (VarDecl *Var = dyn_cast<VarDecl>(VD))
32607330f729Sjoerg return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
32617330f729Sjoerg return false;
32627330f729Sjoerg }
32637330f729Sjoerg
SynthesizeBlockFunc(BlockExpr * CE,int i,StringRef funcName,std::string Tag)32647330f729Sjoerg std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
32657330f729Sjoerg StringRef funcName,
32667330f729Sjoerg std::string Tag) {
32677330f729Sjoerg const FunctionType *AFT = CE->getFunctionType();
32687330f729Sjoerg QualType RT = AFT->getReturnType();
32697330f729Sjoerg std::string StructRef = "struct " + Tag;
32707330f729Sjoerg std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
32717330f729Sjoerg funcName.str() + "_" + "block_func_" + utostr(i);
32727330f729Sjoerg
32737330f729Sjoerg BlockDecl *BD = CE->getBlockDecl();
32747330f729Sjoerg
32757330f729Sjoerg if (isa<FunctionNoProtoType>(AFT)) {
32767330f729Sjoerg // No user-supplied arguments. Still need to pass in a pointer to the
32777330f729Sjoerg // block (to reference imported block decl refs).
32787330f729Sjoerg S += "(" + StructRef + " *__cself)";
32797330f729Sjoerg } else if (BD->param_empty()) {
32807330f729Sjoerg S += "(" + StructRef + " *__cself)";
32817330f729Sjoerg } else {
32827330f729Sjoerg const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
32837330f729Sjoerg assert(FT && "SynthesizeBlockFunc: No function proto");
32847330f729Sjoerg S += '(';
32857330f729Sjoerg // first add the implicit argument.
32867330f729Sjoerg S += StructRef + " *__cself, ";
32877330f729Sjoerg std::string ParamStr;
32887330f729Sjoerg for (BlockDecl::param_iterator AI = BD->param_begin(),
32897330f729Sjoerg E = BD->param_end(); AI != E; ++AI) {
32907330f729Sjoerg if (AI != BD->param_begin()) S += ", ";
32917330f729Sjoerg ParamStr = (*AI)->getNameAsString();
32927330f729Sjoerg QualType QT = (*AI)->getType();
32937330f729Sjoerg (void)convertBlockPointerToFunctionPointer(QT);
32947330f729Sjoerg QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
32957330f729Sjoerg S += ParamStr;
32967330f729Sjoerg }
32977330f729Sjoerg if (FT->isVariadic()) {
32987330f729Sjoerg if (!BD->param_empty()) S += ", ";
32997330f729Sjoerg S += "...";
33007330f729Sjoerg }
33017330f729Sjoerg S += ')';
33027330f729Sjoerg }
33037330f729Sjoerg S += " {\n";
33047330f729Sjoerg
33057330f729Sjoerg // Create local declarations to avoid rewriting all closure decl ref exprs.
33067330f729Sjoerg // First, emit a declaration for all "by ref" decls.
33077330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
33087330f729Sjoerg E = BlockByRefDecls.end(); I != E; ++I) {
33097330f729Sjoerg S += " ";
33107330f729Sjoerg std::string Name = (*I)->getNameAsString();
33117330f729Sjoerg std::string TypeString;
33127330f729Sjoerg RewriteByRefString(TypeString, Name, (*I));
33137330f729Sjoerg TypeString += " *";
33147330f729Sjoerg Name = TypeString + Name;
33157330f729Sjoerg S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
33167330f729Sjoerg }
33177330f729Sjoerg // Next, emit a declaration for all "by copy" declarations.
33187330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
33197330f729Sjoerg E = BlockByCopyDecls.end(); I != E; ++I) {
33207330f729Sjoerg S += " ";
33217330f729Sjoerg // Handle nested closure invocation. For example:
33227330f729Sjoerg //
33237330f729Sjoerg // void (^myImportedClosure)(void);
33247330f729Sjoerg // myImportedClosure = ^(void) { setGlobalInt(x + y); };
33257330f729Sjoerg //
33267330f729Sjoerg // void (^anotherClosure)(void);
33277330f729Sjoerg // anotherClosure = ^(void) {
33287330f729Sjoerg // myImportedClosure(); // import and invoke the closure
33297330f729Sjoerg // };
33307330f729Sjoerg //
33317330f729Sjoerg if (isTopLevelBlockPointerType((*I)->getType())) {
33327330f729Sjoerg RewriteBlockPointerTypeVariable(S, (*I));
33337330f729Sjoerg S += " = (";
33347330f729Sjoerg RewriteBlockPointerType(S, (*I)->getType());
33357330f729Sjoerg S += ")";
33367330f729Sjoerg S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
33377330f729Sjoerg }
33387330f729Sjoerg else {
33397330f729Sjoerg std::string Name = (*I)->getNameAsString();
33407330f729Sjoerg QualType QT = (*I)->getType();
33417330f729Sjoerg if (HasLocalVariableExternalStorage(*I))
33427330f729Sjoerg QT = Context->getPointerType(QT);
33437330f729Sjoerg QT.getAsStringInternal(Name, Context->getPrintingPolicy());
33447330f729Sjoerg S += Name + " = __cself->" +
33457330f729Sjoerg (*I)->getNameAsString() + "; // bound by copy\n";
33467330f729Sjoerg }
33477330f729Sjoerg }
33487330f729Sjoerg std::string RewrittenStr = RewrittenBlockExprs[CE];
33497330f729Sjoerg const char *cstr = RewrittenStr.c_str();
33507330f729Sjoerg while (*cstr++ != '{') ;
33517330f729Sjoerg S += cstr;
33527330f729Sjoerg S += "\n";
33537330f729Sjoerg return S;
33547330f729Sjoerg }
33557330f729Sjoerg
SynthesizeBlockHelperFuncs(BlockExpr * CE,int i,StringRef funcName,std::string Tag)33567330f729Sjoerg std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
33577330f729Sjoerg StringRef funcName,
33587330f729Sjoerg std::string Tag) {
33597330f729Sjoerg std::string StructRef = "struct " + Tag;
33607330f729Sjoerg std::string S = "static void __";
33617330f729Sjoerg
33627330f729Sjoerg S += funcName;
33637330f729Sjoerg S += "_block_copy_" + utostr(i);
33647330f729Sjoerg S += "(" + StructRef;
33657330f729Sjoerg S += "*dst, " + StructRef;
33667330f729Sjoerg S += "*src) {";
33677330f729Sjoerg for (ValueDecl *VD : ImportedBlockDecls) {
33687330f729Sjoerg S += "_Block_object_assign((void*)&dst->";
33697330f729Sjoerg S += VD->getNameAsString();
33707330f729Sjoerg S += ", (void*)src->";
33717330f729Sjoerg S += VD->getNameAsString();
33727330f729Sjoerg if (BlockByRefDeclsPtrSet.count(VD))
33737330f729Sjoerg S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
33747330f729Sjoerg else if (VD->getType()->isBlockPointerType())
33757330f729Sjoerg S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
33767330f729Sjoerg else
33777330f729Sjoerg S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
33787330f729Sjoerg }
33797330f729Sjoerg S += "}\n";
33807330f729Sjoerg
33817330f729Sjoerg S += "\nstatic void __";
33827330f729Sjoerg S += funcName;
33837330f729Sjoerg S += "_block_dispose_" + utostr(i);
33847330f729Sjoerg S += "(" + StructRef;
33857330f729Sjoerg S += "*src) {";
33867330f729Sjoerg for (ValueDecl *VD : ImportedBlockDecls) {
33877330f729Sjoerg S += "_Block_object_dispose((void*)src->";
33887330f729Sjoerg S += VD->getNameAsString();
33897330f729Sjoerg if (BlockByRefDeclsPtrSet.count(VD))
33907330f729Sjoerg S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
33917330f729Sjoerg else if (VD->getType()->isBlockPointerType())
33927330f729Sjoerg S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
33937330f729Sjoerg else
33947330f729Sjoerg S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
33957330f729Sjoerg }
33967330f729Sjoerg S += "}\n";
33977330f729Sjoerg return S;
33987330f729Sjoerg }
33997330f729Sjoerg
SynthesizeBlockImpl(BlockExpr * CE,std::string Tag,std::string Desc)34007330f729Sjoerg std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
34017330f729Sjoerg std::string Desc) {
34027330f729Sjoerg std::string S = "\nstruct " + Tag;
34037330f729Sjoerg std::string Constructor = " " + Tag;
34047330f729Sjoerg
34057330f729Sjoerg S += " {\n struct __block_impl impl;\n";
34067330f729Sjoerg S += " struct " + Desc;
34077330f729Sjoerg S += "* Desc;\n";
34087330f729Sjoerg
34097330f729Sjoerg Constructor += "(void *fp, "; // Invoke function pointer.
34107330f729Sjoerg Constructor += "struct " + Desc; // Descriptor pointer.
34117330f729Sjoerg Constructor += " *desc";
34127330f729Sjoerg
34137330f729Sjoerg if (BlockDeclRefs.size()) {
34147330f729Sjoerg // Output all "by copy" declarations.
34157330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
34167330f729Sjoerg E = BlockByCopyDecls.end(); I != E; ++I) {
34177330f729Sjoerg S += " ";
34187330f729Sjoerg std::string FieldName = (*I)->getNameAsString();
34197330f729Sjoerg std::string ArgName = "_" + FieldName;
34207330f729Sjoerg // Handle nested closure invocation. For example:
34217330f729Sjoerg //
34227330f729Sjoerg // void (^myImportedBlock)(void);
34237330f729Sjoerg // myImportedBlock = ^(void) { setGlobalInt(x + y); };
34247330f729Sjoerg //
34257330f729Sjoerg // void (^anotherBlock)(void);
34267330f729Sjoerg // anotherBlock = ^(void) {
34277330f729Sjoerg // myImportedBlock(); // import and invoke the closure
34287330f729Sjoerg // };
34297330f729Sjoerg //
34307330f729Sjoerg if (isTopLevelBlockPointerType((*I)->getType())) {
34317330f729Sjoerg S += "struct __block_impl *";
34327330f729Sjoerg Constructor += ", void *" + ArgName;
34337330f729Sjoerg } else {
34347330f729Sjoerg QualType QT = (*I)->getType();
34357330f729Sjoerg if (HasLocalVariableExternalStorage(*I))
34367330f729Sjoerg QT = Context->getPointerType(QT);
34377330f729Sjoerg QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
34387330f729Sjoerg QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
34397330f729Sjoerg Constructor += ", " + ArgName;
34407330f729Sjoerg }
34417330f729Sjoerg S += FieldName + ";\n";
34427330f729Sjoerg }
34437330f729Sjoerg // Output all "by ref" declarations.
34447330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
34457330f729Sjoerg E = BlockByRefDecls.end(); I != E; ++I) {
34467330f729Sjoerg S += " ";
34477330f729Sjoerg std::string FieldName = (*I)->getNameAsString();
34487330f729Sjoerg std::string ArgName = "_" + FieldName;
34497330f729Sjoerg {
34507330f729Sjoerg std::string TypeString;
34517330f729Sjoerg RewriteByRefString(TypeString, FieldName, (*I));
34527330f729Sjoerg TypeString += " *";
34537330f729Sjoerg FieldName = TypeString + FieldName;
34547330f729Sjoerg ArgName = TypeString + ArgName;
34557330f729Sjoerg Constructor += ", " + ArgName;
34567330f729Sjoerg }
34577330f729Sjoerg S += FieldName + "; // by ref\n";
34587330f729Sjoerg }
34597330f729Sjoerg // Finish writing the constructor.
34607330f729Sjoerg Constructor += ", int flags=0)";
34617330f729Sjoerg // Initialize all "by copy" arguments.
34627330f729Sjoerg bool firsTime = true;
34637330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
34647330f729Sjoerg E = BlockByCopyDecls.end(); I != E; ++I) {
34657330f729Sjoerg std::string Name = (*I)->getNameAsString();
34667330f729Sjoerg if (firsTime) {
34677330f729Sjoerg Constructor += " : ";
34687330f729Sjoerg firsTime = false;
34697330f729Sjoerg }
34707330f729Sjoerg else
34717330f729Sjoerg Constructor += ", ";
34727330f729Sjoerg if (isTopLevelBlockPointerType((*I)->getType()))
34737330f729Sjoerg Constructor += Name + "((struct __block_impl *)_" + Name + ")";
34747330f729Sjoerg else
34757330f729Sjoerg Constructor += Name + "(_" + Name + ")";
34767330f729Sjoerg }
34777330f729Sjoerg // Initialize all "by ref" arguments.
34787330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
34797330f729Sjoerg E = BlockByRefDecls.end(); I != E; ++I) {
34807330f729Sjoerg std::string Name = (*I)->getNameAsString();
34817330f729Sjoerg if (firsTime) {
34827330f729Sjoerg Constructor += " : ";
34837330f729Sjoerg firsTime = false;
34847330f729Sjoerg }
34857330f729Sjoerg else
34867330f729Sjoerg Constructor += ", ";
34877330f729Sjoerg Constructor += Name + "(_" + Name + "->__forwarding)";
34887330f729Sjoerg }
34897330f729Sjoerg
34907330f729Sjoerg Constructor += " {\n";
34917330f729Sjoerg if (GlobalVarDecl)
34927330f729Sjoerg Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
34937330f729Sjoerg else
34947330f729Sjoerg Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
34957330f729Sjoerg Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
34967330f729Sjoerg
34977330f729Sjoerg Constructor += " Desc = desc;\n";
34987330f729Sjoerg } else {
34997330f729Sjoerg // Finish writing the constructor.
35007330f729Sjoerg Constructor += ", int flags=0) {\n";
35017330f729Sjoerg if (GlobalVarDecl)
35027330f729Sjoerg Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
35037330f729Sjoerg else
35047330f729Sjoerg Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
35057330f729Sjoerg Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
35067330f729Sjoerg Constructor += " Desc = desc;\n";
35077330f729Sjoerg }
35087330f729Sjoerg Constructor += " ";
35097330f729Sjoerg Constructor += "}\n";
35107330f729Sjoerg S += Constructor;
35117330f729Sjoerg S += "};\n";
35127330f729Sjoerg return S;
35137330f729Sjoerg }
35147330f729Sjoerg
SynthesizeBlockDescriptor(std::string DescTag,std::string ImplTag,int i,StringRef FunName,unsigned hasCopy)35157330f729Sjoerg std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
35167330f729Sjoerg std::string ImplTag, int i,
35177330f729Sjoerg StringRef FunName,
35187330f729Sjoerg unsigned hasCopy) {
35197330f729Sjoerg std::string S = "\nstatic struct " + DescTag;
35207330f729Sjoerg
35217330f729Sjoerg S += " {\n unsigned long reserved;\n";
35227330f729Sjoerg S += " unsigned long Block_size;\n";
35237330f729Sjoerg if (hasCopy) {
35247330f729Sjoerg S += " void (*copy)(struct ";
35257330f729Sjoerg S += ImplTag; S += "*, struct ";
35267330f729Sjoerg S += ImplTag; S += "*);\n";
35277330f729Sjoerg
35287330f729Sjoerg S += " void (*dispose)(struct ";
35297330f729Sjoerg S += ImplTag; S += "*);\n";
35307330f729Sjoerg }
35317330f729Sjoerg S += "} ";
35327330f729Sjoerg
35337330f729Sjoerg S += DescTag + "_DATA = { 0, sizeof(struct ";
35347330f729Sjoerg S += ImplTag + ")";
35357330f729Sjoerg if (hasCopy) {
35367330f729Sjoerg S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
35377330f729Sjoerg S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
35387330f729Sjoerg }
35397330f729Sjoerg S += "};\n";
35407330f729Sjoerg return S;
35417330f729Sjoerg }
35427330f729Sjoerg
SynthesizeBlockLiterals(SourceLocation FunLocStart,StringRef FunName)35437330f729Sjoerg void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
35447330f729Sjoerg StringRef FunName) {
35457330f729Sjoerg // Insert declaration for the function in which block literal is used.
35467330f729Sjoerg if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
35477330f729Sjoerg RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
35487330f729Sjoerg bool RewriteSC = (GlobalVarDecl &&
35497330f729Sjoerg !Blocks.empty() &&
35507330f729Sjoerg GlobalVarDecl->getStorageClass() == SC_Static &&
35517330f729Sjoerg GlobalVarDecl->getType().getCVRQualifiers());
35527330f729Sjoerg if (RewriteSC) {
35537330f729Sjoerg std::string SC(" void __");
35547330f729Sjoerg SC += GlobalVarDecl->getNameAsString();
35557330f729Sjoerg SC += "() {}";
35567330f729Sjoerg InsertText(FunLocStart, SC);
35577330f729Sjoerg }
35587330f729Sjoerg
35597330f729Sjoerg // Insert closures that were part of the function.
35607330f729Sjoerg for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
35617330f729Sjoerg CollectBlockDeclRefInfo(Blocks[i]);
35627330f729Sjoerg // Need to copy-in the inner copied-in variables not actually used in this
35637330f729Sjoerg // block.
35647330f729Sjoerg for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
35657330f729Sjoerg DeclRefExpr *Exp = InnerDeclRefs[count++];
35667330f729Sjoerg ValueDecl *VD = Exp->getDecl();
35677330f729Sjoerg BlockDeclRefs.push_back(Exp);
35687330f729Sjoerg if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
35697330f729Sjoerg BlockByCopyDeclsPtrSet.insert(VD);
35707330f729Sjoerg BlockByCopyDecls.push_back(VD);
35717330f729Sjoerg }
35727330f729Sjoerg if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
35737330f729Sjoerg BlockByRefDeclsPtrSet.insert(VD);
35747330f729Sjoerg BlockByRefDecls.push_back(VD);
35757330f729Sjoerg }
35767330f729Sjoerg // imported objects in the inner blocks not used in the outer
35777330f729Sjoerg // blocks must be copied/disposed in the outer block as well.
35787330f729Sjoerg if (VD->hasAttr<BlocksAttr>() ||
35797330f729Sjoerg VD->getType()->isObjCObjectPointerType() ||
35807330f729Sjoerg VD->getType()->isBlockPointerType())
35817330f729Sjoerg ImportedBlockDecls.insert(VD);
35827330f729Sjoerg }
35837330f729Sjoerg
35847330f729Sjoerg std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
35857330f729Sjoerg std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
35867330f729Sjoerg
35877330f729Sjoerg std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
35887330f729Sjoerg
35897330f729Sjoerg InsertText(FunLocStart, CI);
35907330f729Sjoerg
35917330f729Sjoerg std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
35927330f729Sjoerg
35937330f729Sjoerg InsertText(FunLocStart, CF);
35947330f729Sjoerg
35957330f729Sjoerg if (ImportedBlockDecls.size()) {
35967330f729Sjoerg std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
35977330f729Sjoerg InsertText(FunLocStart, HF);
35987330f729Sjoerg }
35997330f729Sjoerg std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
36007330f729Sjoerg ImportedBlockDecls.size() > 0);
36017330f729Sjoerg InsertText(FunLocStart, BD);
36027330f729Sjoerg
36037330f729Sjoerg BlockDeclRefs.clear();
36047330f729Sjoerg BlockByRefDecls.clear();
36057330f729Sjoerg BlockByRefDeclsPtrSet.clear();
36067330f729Sjoerg BlockByCopyDecls.clear();
36077330f729Sjoerg BlockByCopyDeclsPtrSet.clear();
36087330f729Sjoerg ImportedBlockDecls.clear();
36097330f729Sjoerg }
36107330f729Sjoerg if (RewriteSC) {
36117330f729Sjoerg // Must insert any 'const/volatile/static here. Since it has been
36127330f729Sjoerg // removed as result of rewriting of block literals.
36137330f729Sjoerg std::string SC;
36147330f729Sjoerg if (GlobalVarDecl->getStorageClass() == SC_Static)
36157330f729Sjoerg SC = "static ";
36167330f729Sjoerg if (GlobalVarDecl->getType().isConstQualified())
36177330f729Sjoerg SC += "const ";
36187330f729Sjoerg if (GlobalVarDecl->getType().isVolatileQualified())
36197330f729Sjoerg SC += "volatile ";
36207330f729Sjoerg if (GlobalVarDecl->getType().isRestrictQualified())
36217330f729Sjoerg SC += "restrict ";
36227330f729Sjoerg InsertText(FunLocStart, SC);
36237330f729Sjoerg }
36247330f729Sjoerg
36257330f729Sjoerg Blocks.clear();
36267330f729Sjoerg InnerDeclRefsCount.clear();
36277330f729Sjoerg InnerDeclRefs.clear();
36287330f729Sjoerg RewrittenBlockExprs.clear();
36297330f729Sjoerg }
36307330f729Sjoerg
InsertBlockLiteralsWithinFunction(FunctionDecl * FD)36317330f729Sjoerg void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
36327330f729Sjoerg SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
36337330f729Sjoerg StringRef FuncName = FD->getName();
36347330f729Sjoerg
36357330f729Sjoerg SynthesizeBlockLiterals(FunLocStart, FuncName);
36367330f729Sjoerg }
36377330f729Sjoerg
BuildUniqueMethodName(std::string & Name,ObjCMethodDecl * MD)36387330f729Sjoerg static void BuildUniqueMethodName(std::string &Name,
36397330f729Sjoerg ObjCMethodDecl *MD) {
36407330f729Sjoerg ObjCInterfaceDecl *IFace = MD->getClassInterface();
3641*e038c9c4Sjoerg Name = std::string(IFace->getName());
36427330f729Sjoerg Name += "__" + MD->getSelector().getAsString();
36437330f729Sjoerg // Convert colons to underscores.
36447330f729Sjoerg std::string::size_type loc = 0;
36457330f729Sjoerg while ((loc = Name.find(':', loc)) != std::string::npos)
36467330f729Sjoerg Name.replace(loc, 1, "_");
36477330f729Sjoerg }
36487330f729Sjoerg
InsertBlockLiteralsWithinMethod(ObjCMethodDecl * MD)36497330f729Sjoerg void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
36507330f729Sjoerg // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
36517330f729Sjoerg // SourceLocation FunLocStart = MD->getBeginLoc();
36527330f729Sjoerg SourceLocation FunLocStart = MD->getBeginLoc();
36537330f729Sjoerg std::string FuncName;
36547330f729Sjoerg BuildUniqueMethodName(FuncName, MD);
36557330f729Sjoerg SynthesizeBlockLiterals(FunLocStart, FuncName);
36567330f729Sjoerg }
36577330f729Sjoerg
GetBlockDeclRefExprs(Stmt * S)36587330f729Sjoerg void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
36597330f729Sjoerg for (Stmt *SubStmt : S->children())
36607330f729Sjoerg if (SubStmt) {
36617330f729Sjoerg if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
36627330f729Sjoerg GetBlockDeclRefExprs(CBE->getBody());
36637330f729Sjoerg else
36647330f729Sjoerg GetBlockDeclRefExprs(SubStmt);
36657330f729Sjoerg }
36667330f729Sjoerg // Handle specific things.
36677330f729Sjoerg if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
36687330f729Sjoerg if (DRE->refersToEnclosingVariableOrCapture() ||
36697330f729Sjoerg HasLocalVariableExternalStorage(DRE->getDecl()))
36707330f729Sjoerg // FIXME: Handle enums.
36717330f729Sjoerg BlockDeclRefs.push_back(DRE);
36727330f729Sjoerg }
36737330f729Sjoerg
GetInnerBlockDeclRefExprs(Stmt * S,SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs,llvm::SmallPtrSetImpl<const DeclContext * > & InnerContexts)36747330f729Sjoerg void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
36757330f729Sjoerg SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
36767330f729Sjoerg llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
36777330f729Sjoerg for (Stmt *SubStmt : S->children())
36787330f729Sjoerg if (SubStmt) {
36797330f729Sjoerg if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
36807330f729Sjoerg InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
36817330f729Sjoerg GetInnerBlockDeclRefExprs(CBE->getBody(),
36827330f729Sjoerg InnerBlockDeclRefs,
36837330f729Sjoerg InnerContexts);
36847330f729Sjoerg }
36857330f729Sjoerg else
36867330f729Sjoerg GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
36877330f729Sjoerg }
36887330f729Sjoerg // Handle specific things.
36897330f729Sjoerg if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
36907330f729Sjoerg if (DRE->refersToEnclosingVariableOrCapture() ||
36917330f729Sjoerg HasLocalVariableExternalStorage(DRE->getDecl())) {
36927330f729Sjoerg if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
36937330f729Sjoerg InnerBlockDeclRefs.push_back(DRE);
36947330f729Sjoerg if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
36957330f729Sjoerg if (Var->isFunctionOrMethodVarDecl())
36967330f729Sjoerg ImportedLocalExternalDecls.insert(Var);
36977330f729Sjoerg }
36987330f729Sjoerg }
36997330f729Sjoerg }
37007330f729Sjoerg
37017330f729Sjoerg /// convertFunctionTypeOfBlocks - This routine converts a function type
37027330f729Sjoerg /// whose result type may be a block pointer or whose argument type(s)
37037330f729Sjoerg /// might be block pointers to an equivalent function type replacing
37047330f729Sjoerg /// all block pointers to function pointers.
convertFunctionTypeOfBlocks(const FunctionType * FT)37057330f729Sjoerg QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
37067330f729Sjoerg const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
37077330f729Sjoerg // FTP will be null for closures that don't take arguments.
37087330f729Sjoerg // Generate a funky cast.
37097330f729Sjoerg SmallVector<QualType, 8> ArgTypes;
37107330f729Sjoerg QualType Res = FT->getReturnType();
37117330f729Sjoerg bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
37127330f729Sjoerg
37137330f729Sjoerg if (FTP) {
37147330f729Sjoerg for (auto &I : FTP->param_types()) {
37157330f729Sjoerg QualType t = I;
37167330f729Sjoerg // Make sure we convert "t (^)(...)" to "t (*)(...)".
37177330f729Sjoerg if (convertBlockPointerToFunctionPointer(t))
37187330f729Sjoerg HasBlockType = true;
37197330f729Sjoerg ArgTypes.push_back(t);
37207330f729Sjoerg }
37217330f729Sjoerg }
37227330f729Sjoerg QualType FuncType;
37237330f729Sjoerg // FIXME. Does this work if block takes no argument but has a return type
37247330f729Sjoerg // which is of block type?
37257330f729Sjoerg if (HasBlockType)
37267330f729Sjoerg FuncType = getSimpleFunctionType(Res, ArgTypes);
37277330f729Sjoerg else FuncType = QualType(FT, 0);
37287330f729Sjoerg return FuncType;
37297330f729Sjoerg }
37307330f729Sjoerg
SynthesizeBlockCall(CallExpr * Exp,const Expr * BlockExp)37317330f729Sjoerg Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
37327330f729Sjoerg // Navigate to relevant type information.
37337330f729Sjoerg const BlockPointerType *CPT = nullptr;
37347330f729Sjoerg
37357330f729Sjoerg if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
37367330f729Sjoerg CPT = DRE->getType()->getAs<BlockPointerType>();
37377330f729Sjoerg } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
37387330f729Sjoerg CPT = MExpr->getType()->getAs<BlockPointerType>();
37397330f729Sjoerg }
37407330f729Sjoerg else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
37417330f729Sjoerg return SynthesizeBlockCall(Exp, PRE->getSubExpr());
37427330f729Sjoerg }
37437330f729Sjoerg else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
37447330f729Sjoerg CPT = IEXPR->getType()->getAs<BlockPointerType>();
37457330f729Sjoerg else if (const ConditionalOperator *CEXPR =
37467330f729Sjoerg dyn_cast<ConditionalOperator>(BlockExp)) {
37477330f729Sjoerg Expr *LHSExp = CEXPR->getLHS();
37487330f729Sjoerg Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
37497330f729Sjoerg Expr *RHSExp = CEXPR->getRHS();
37507330f729Sjoerg Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
37517330f729Sjoerg Expr *CONDExp = CEXPR->getCond();
37527330f729Sjoerg ConditionalOperator *CondExpr =
37537330f729Sjoerg new (Context) ConditionalOperator(CONDExp,
37547330f729Sjoerg SourceLocation(), cast<Expr>(LHSStmt),
37557330f729Sjoerg SourceLocation(), cast<Expr>(RHSStmt),
37567330f729Sjoerg Exp->getType(), VK_RValue, OK_Ordinary);
37577330f729Sjoerg return CondExpr;
37587330f729Sjoerg } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
37597330f729Sjoerg CPT = IRE->getType()->getAs<BlockPointerType>();
37607330f729Sjoerg } else if (const PseudoObjectExpr *POE
37617330f729Sjoerg = dyn_cast<PseudoObjectExpr>(BlockExp)) {
37627330f729Sjoerg CPT = POE->getType()->castAs<BlockPointerType>();
37637330f729Sjoerg } else {
37647330f729Sjoerg assert(false && "RewriteBlockClass: Bad type");
37657330f729Sjoerg }
37667330f729Sjoerg assert(CPT && "RewriteBlockClass: Bad type");
37677330f729Sjoerg const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
37687330f729Sjoerg assert(FT && "RewriteBlockClass: Bad type");
37697330f729Sjoerg const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
37707330f729Sjoerg // FTP will be null for closures that don't take arguments.
37717330f729Sjoerg
37727330f729Sjoerg RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
37737330f729Sjoerg SourceLocation(), SourceLocation(),
37747330f729Sjoerg &Context->Idents.get("__block_impl"));
37757330f729Sjoerg QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
37767330f729Sjoerg
37777330f729Sjoerg // Generate a funky cast.
37787330f729Sjoerg SmallVector<QualType, 8> ArgTypes;
37797330f729Sjoerg
37807330f729Sjoerg // Push the block argument type.
37817330f729Sjoerg ArgTypes.push_back(PtrBlock);
37827330f729Sjoerg if (FTP) {
37837330f729Sjoerg for (auto &I : FTP->param_types()) {
37847330f729Sjoerg QualType t = I;
37857330f729Sjoerg // Make sure we convert "t (^)(...)" to "t (*)(...)".
37867330f729Sjoerg if (!convertBlockPointerToFunctionPointer(t))
37877330f729Sjoerg convertToUnqualifiedObjCType(t);
37887330f729Sjoerg ArgTypes.push_back(t);
37897330f729Sjoerg }
37907330f729Sjoerg }
37917330f729Sjoerg // Now do the pointer to function cast.
37927330f729Sjoerg QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
37937330f729Sjoerg
37947330f729Sjoerg PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
37957330f729Sjoerg
37967330f729Sjoerg CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
37977330f729Sjoerg CK_BitCast,
37987330f729Sjoerg const_cast<Expr*>(BlockExp));
37997330f729Sjoerg // Don't forget the parens to enforce the proper binding.
38007330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
38017330f729Sjoerg BlkCast);
38027330f729Sjoerg //PE->dump();
38037330f729Sjoerg
38047330f729Sjoerg FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
38057330f729Sjoerg SourceLocation(),
38067330f729Sjoerg &Context->Idents.get("FuncPtr"),
38077330f729Sjoerg Context->VoidPtrTy, nullptr,
38087330f729Sjoerg /*BitWidth=*/nullptr, /*Mutable=*/true,
38097330f729Sjoerg ICIS_NoInit);
38107330f729Sjoerg MemberExpr *ME = MemberExpr::CreateImplicit(
38117330f729Sjoerg *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
38127330f729Sjoerg
38137330f729Sjoerg CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
38147330f729Sjoerg CK_BitCast, ME);
38157330f729Sjoerg PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
38167330f729Sjoerg
38177330f729Sjoerg SmallVector<Expr*, 8> BlkExprs;
38187330f729Sjoerg // Add the implicit argument.
38197330f729Sjoerg BlkExprs.push_back(BlkCast);
38207330f729Sjoerg // Add the user arguments.
38217330f729Sjoerg for (CallExpr::arg_iterator I = Exp->arg_begin(),
38227330f729Sjoerg E = Exp->arg_end(); I != E; ++I) {
38237330f729Sjoerg BlkExprs.push_back(*I);
38247330f729Sjoerg }
3825*e038c9c4Sjoerg CallExpr *CE =
3826*e038c9c4Sjoerg CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_RValue,
3827*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
38287330f729Sjoerg return CE;
38297330f729Sjoerg }
38307330f729Sjoerg
38317330f729Sjoerg // We need to return the rewritten expression to handle cases where the
38327330f729Sjoerg // BlockDeclRefExpr is embedded in another expression being rewritten.
38337330f729Sjoerg // For example:
38347330f729Sjoerg //
38357330f729Sjoerg // int main() {
38367330f729Sjoerg // __block Foo *f;
38377330f729Sjoerg // __block int i;
38387330f729Sjoerg //
38397330f729Sjoerg // void (^myblock)() = ^() {
38407330f729Sjoerg // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
38417330f729Sjoerg // i = 77;
38427330f729Sjoerg // };
38437330f729Sjoerg //}
RewriteBlockDeclRefExpr(DeclRefExpr * DeclRefExp)38447330f729Sjoerg Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
38457330f729Sjoerg // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
38467330f729Sjoerg // for each DeclRefExp where BYREFVAR is name of the variable.
38477330f729Sjoerg ValueDecl *VD = DeclRefExp->getDecl();
38487330f729Sjoerg bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
38497330f729Sjoerg HasLocalVariableExternalStorage(DeclRefExp->getDecl());
38507330f729Sjoerg
38517330f729Sjoerg FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
38527330f729Sjoerg SourceLocation(),
38537330f729Sjoerg &Context->Idents.get("__forwarding"),
38547330f729Sjoerg Context->VoidPtrTy, nullptr,
38557330f729Sjoerg /*BitWidth=*/nullptr, /*Mutable=*/true,
38567330f729Sjoerg ICIS_NoInit);
38577330f729Sjoerg MemberExpr *ME =
38587330f729Sjoerg MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
38597330f729Sjoerg FD->getType(), VK_LValue, OK_Ordinary);
38607330f729Sjoerg
38617330f729Sjoerg StringRef Name = VD->getName();
38627330f729Sjoerg FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
38637330f729Sjoerg &Context->Idents.get(Name),
38647330f729Sjoerg Context->VoidPtrTy, nullptr,
38657330f729Sjoerg /*BitWidth=*/nullptr, /*Mutable=*/true,
38667330f729Sjoerg ICIS_NoInit);
38677330f729Sjoerg ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
38687330f729Sjoerg VK_LValue, OK_Ordinary);
38697330f729Sjoerg
38707330f729Sjoerg // Need parens to enforce precedence.
38717330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
38727330f729Sjoerg DeclRefExp->getExprLoc(),
38737330f729Sjoerg ME);
38747330f729Sjoerg ReplaceStmt(DeclRefExp, PE);
38757330f729Sjoerg return PE;
38767330f729Sjoerg }
38777330f729Sjoerg
38787330f729Sjoerg // Rewrites the imported local variable V with external storage
38797330f729Sjoerg // (static, extern, etc.) as *V
38807330f729Sjoerg //
RewriteLocalVariableExternalStorage(DeclRefExpr * DRE)38817330f729Sjoerg Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
38827330f729Sjoerg ValueDecl *VD = DRE->getDecl();
38837330f729Sjoerg if (VarDecl *Var = dyn_cast<VarDecl>(VD))
38847330f729Sjoerg if (!ImportedLocalExternalDecls.count(Var))
38857330f729Sjoerg return DRE;
3886*e038c9c4Sjoerg Expr *Exp = UnaryOperator::Create(
3887*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
3888*e038c9c4Sjoerg VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
38897330f729Sjoerg // Need parens to enforce precedence.
38907330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
38917330f729Sjoerg Exp);
38927330f729Sjoerg ReplaceStmt(DRE, PE);
38937330f729Sjoerg return PE;
38947330f729Sjoerg }
38957330f729Sjoerg
RewriteCastExpr(CStyleCastExpr * CE)38967330f729Sjoerg void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
38977330f729Sjoerg SourceLocation LocStart = CE->getLParenLoc();
38987330f729Sjoerg SourceLocation LocEnd = CE->getRParenLoc();
38997330f729Sjoerg
39007330f729Sjoerg // Need to avoid trying to rewrite synthesized casts.
39017330f729Sjoerg if (LocStart.isInvalid())
39027330f729Sjoerg return;
39037330f729Sjoerg // Need to avoid trying to rewrite casts contained in macros.
39047330f729Sjoerg if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
39057330f729Sjoerg return;
39067330f729Sjoerg
39077330f729Sjoerg const char *startBuf = SM->getCharacterData(LocStart);
39087330f729Sjoerg const char *endBuf = SM->getCharacterData(LocEnd);
39097330f729Sjoerg QualType QT = CE->getType();
39107330f729Sjoerg const Type* TypePtr = QT->getAs<Type>();
39117330f729Sjoerg if (isa<TypeOfExprType>(TypePtr)) {
39127330f729Sjoerg const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
39137330f729Sjoerg QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
39147330f729Sjoerg std::string TypeAsString = "(";
39157330f729Sjoerg RewriteBlockPointerType(TypeAsString, QT);
39167330f729Sjoerg TypeAsString += ")";
39177330f729Sjoerg ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
39187330f729Sjoerg return;
39197330f729Sjoerg }
39207330f729Sjoerg // advance the location to startArgList.
39217330f729Sjoerg const char *argPtr = startBuf;
39227330f729Sjoerg
39237330f729Sjoerg while (*argPtr++ && (argPtr < endBuf)) {
39247330f729Sjoerg switch (*argPtr) {
39257330f729Sjoerg case '^':
39267330f729Sjoerg // Replace the '^' with '*'.
39277330f729Sjoerg LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
39287330f729Sjoerg ReplaceText(LocStart, 1, "*");
39297330f729Sjoerg break;
39307330f729Sjoerg }
39317330f729Sjoerg }
39327330f729Sjoerg }
39337330f729Sjoerg
RewriteBlockPointerFunctionArgs(FunctionDecl * FD)39347330f729Sjoerg void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
39357330f729Sjoerg SourceLocation DeclLoc = FD->getLocation();
39367330f729Sjoerg unsigned parenCount = 0;
39377330f729Sjoerg
39387330f729Sjoerg // We have 1 or more arguments that have closure pointers.
39397330f729Sjoerg const char *startBuf = SM->getCharacterData(DeclLoc);
39407330f729Sjoerg const char *startArgList = strchr(startBuf, '(');
39417330f729Sjoerg
39427330f729Sjoerg assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
39437330f729Sjoerg
39447330f729Sjoerg parenCount++;
39457330f729Sjoerg // advance the location to startArgList.
39467330f729Sjoerg DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
39477330f729Sjoerg assert((DeclLoc.isValid()) && "Invalid DeclLoc");
39487330f729Sjoerg
39497330f729Sjoerg const char *argPtr = startArgList;
39507330f729Sjoerg
39517330f729Sjoerg while (*argPtr++ && parenCount) {
39527330f729Sjoerg switch (*argPtr) {
39537330f729Sjoerg case '^':
39547330f729Sjoerg // Replace the '^' with '*'.
39557330f729Sjoerg DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
39567330f729Sjoerg ReplaceText(DeclLoc, 1, "*");
39577330f729Sjoerg break;
39587330f729Sjoerg case '(':
39597330f729Sjoerg parenCount++;
39607330f729Sjoerg break;
39617330f729Sjoerg case ')':
39627330f729Sjoerg parenCount--;
39637330f729Sjoerg break;
39647330f729Sjoerg }
39657330f729Sjoerg }
39667330f729Sjoerg }
39677330f729Sjoerg
PointerTypeTakesAnyBlockArguments(QualType QT)39687330f729Sjoerg bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
39697330f729Sjoerg const FunctionProtoType *FTP;
39707330f729Sjoerg const PointerType *PT = QT->getAs<PointerType>();
39717330f729Sjoerg if (PT) {
39727330f729Sjoerg FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
39737330f729Sjoerg } else {
39747330f729Sjoerg const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
39757330f729Sjoerg assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
39767330f729Sjoerg FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
39777330f729Sjoerg }
39787330f729Sjoerg if (FTP) {
39797330f729Sjoerg for (const auto &I : FTP->param_types())
39807330f729Sjoerg if (isTopLevelBlockPointerType(I))
39817330f729Sjoerg return true;
39827330f729Sjoerg }
39837330f729Sjoerg return false;
39847330f729Sjoerg }
39857330f729Sjoerg
PointerTypeTakesAnyObjCQualifiedType(QualType QT)39867330f729Sjoerg bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
39877330f729Sjoerg const FunctionProtoType *FTP;
39887330f729Sjoerg const PointerType *PT = QT->getAs<PointerType>();
39897330f729Sjoerg if (PT) {
39907330f729Sjoerg FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
39917330f729Sjoerg } else {
39927330f729Sjoerg const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
39937330f729Sjoerg assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
39947330f729Sjoerg FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
39957330f729Sjoerg }
39967330f729Sjoerg if (FTP) {
39977330f729Sjoerg for (const auto &I : FTP->param_types()) {
39987330f729Sjoerg if (I->isObjCQualifiedIdType())
39997330f729Sjoerg return true;
40007330f729Sjoerg if (I->isObjCObjectPointerType() &&
40017330f729Sjoerg I->getPointeeType()->isObjCQualifiedInterfaceType())
40027330f729Sjoerg return true;
40037330f729Sjoerg }
40047330f729Sjoerg
40057330f729Sjoerg }
40067330f729Sjoerg return false;
40077330f729Sjoerg }
40087330f729Sjoerg
GetExtentOfArgList(const char * Name,const char * & LParen,const char * & RParen)40097330f729Sjoerg void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
40107330f729Sjoerg const char *&RParen) {
40117330f729Sjoerg const char *argPtr = strchr(Name, '(');
40127330f729Sjoerg assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
40137330f729Sjoerg
40147330f729Sjoerg LParen = argPtr; // output the start.
40157330f729Sjoerg argPtr++; // skip past the left paren.
40167330f729Sjoerg unsigned parenCount = 1;
40177330f729Sjoerg
40187330f729Sjoerg while (*argPtr && parenCount) {
40197330f729Sjoerg switch (*argPtr) {
40207330f729Sjoerg case '(': parenCount++; break;
40217330f729Sjoerg case ')': parenCount--; break;
40227330f729Sjoerg default: break;
40237330f729Sjoerg }
40247330f729Sjoerg if (parenCount) argPtr++;
40257330f729Sjoerg }
40267330f729Sjoerg assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
40277330f729Sjoerg RParen = argPtr; // output the end
40287330f729Sjoerg }
40297330f729Sjoerg
RewriteBlockPointerDecl(NamedDecl * ND)40307330f729Sjoerg void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
40317330f729Sjoerg if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
40327330f729Sjoerg RewriteBlockPointerFunctionArgs(FD);
40337330f729Sjoerg return;
40347330f729Sjoerg }
40357330f729Sjoerg // Handle Variables and Typedefs.
40367330f729Sjoerg SourceLocation DeclLoc = ND->getLocation();
40377330f729Sjoerg QualType DeclT;
40387330f729Sjoerg if (VarDecl *VD = dyn_cast<VarDecl>(ND))
40397330f729Sjoerg DeclT = VD->getType();
40407330f729Sjoerg else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
40417330f729Sjoerg DeclT = TDD->getUnderlyingType();
40427330f729Sjoerg else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
40437330f729Sjoerg DeclT = FD->getType();
40447330f729Sjoerg else
40457330f729Sjoerg llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
40467330f729Sjoerg
40477330f729Sjoerg const char *startBuf = SM->getCharacterData(DeclLoc);
40487330f729Sjoerg const char *endBuf = startBuf;
40497330f729Sjoerg // scan backward (from the decl location) for the end of the previous decl.
40507330f729Sjoerg while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
40517330f729Sjoerg startBuf--;
40527330f729Sjoerg SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
40537330f729Sjoerg std::string buf;
40547330f729Sjoerg unsigned OrigLength=0;
40557330f729Sjoerg // *startBuf != '^' if we are dealing with a pointer to function that
40567330f729Sjoerg // may take block argument types (which will be handled below).
40577330f729Sjoerg if (*startBuf == '^') {
40587330f729Sjoerg // Replace the '^' with '*', computing a negative offset.
40597330f729Sjoerg buf = '*';
40607330f729Sjoerg startBuf++;
40617330f729Sjoerg OrigLength++;
40627330f729Sjoerg }
40637330f729Sjoerg while (*startBuf != ')') {
40647330f729Sjoerg buf += *startBuf;
40657330f729Sjoerg startBuf++;
40667330f729Sjoerg OrigLength++;
40677330f729Sjoerg }
40687330f729Sjoerg buf += ')';
40697330f729Sjoerg OrigLength++;
40707330f729Sjoerg
40717330f729Sjoerg if (PointerTypeTakesAnyBlockArguments(DeclT) ||
40727330f729Sjoerg PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
40737330f729Sjoerg // Replace the '^' with '*' for arguments.
40747330f729Sjoerg // Replace id<P> with id/*<>*/
40757330f729Sjoerg DeclLoc = ND->getLocation();
40767330f729Sjoerg startBuf = SM->getCharacterData(DeclLoc);
40777330f729Sjoerg const char *argListBegin, *argListEnd;
40787330f729Sjoerg GetExtentOfArgList(startBuf, argListBegin, argListEnd);
40797330f729Sjoerg while (argListBegin < argListEnd) {
40807330f729Sjoerg if (*argListBegin == '^')
40817330f729Sjoerg buf += '*';
40827330f729Sjoerg else if (*argListBegin == '<') {
40837330f729Sjoerg buf += "/*";
40847330f729Sjoerg buf += *argListBegin++;
40857330f729Sjoerg OrigLength++;
40867330f729Sjoerg while (*argListBegin != '>') {
40877330f729Sjoerg buf += *argListBegin++;
40887330f729Sjoerg OrigLength++;
40897330f729Sjoerg }
40907330f729Sjoerg buf += *argListBegin;
40917330f729Sjoerg buf += "*/";
40927330f729Sjoerg }
40937330f729Sjoerg else
40947330f729Sjoerg buf += *argListBegin;
40957330f729Sjoerg argListBegin++;
40967330f729Sjoerg OrigLength++;
40977330f729Sjoerg }
40987330f729Sjoerg buf += ')';
40997330f729Sjoerg OrigLength++;
41007330f729Sjoerg }
41017330f729Sjoerg ReplaceText(Start, OrigLength, buf);
41027330f729Sjoerg }
41037330f729Sjoerg
41047330f729Sjoerg /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
41057330f729Sjoerg /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
41067330f729Sjoerg /// struct Block_byref_id_object *src) {
41077330f729Sjoerg /// _Block_object_assign (&_dest->object, _src->object,
41087330f729Sjoerg /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
41097330f729Sjoerg /// [|BLOCK_FIELD_IS_WEAK]) // object
41107330f729Sjoerg /// _Block_object_assign(&_dest->object, _src->object,
41117330f729Sjoerg /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
41127330f729Sjoerg /// [|BLOCK_FIELD_IS_WEAK]) // block
41137330f729Sjoerg /// }
41147330f729Sjoerg /// And:
41157330f729Sjoerg /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
41167330f729Sjoerg /// _Block_object_dispose(_src->object,
41177330f729Sjoerg /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
41187330f729Sjoerg /// [|BLOCK_FIELD_IS_WEAK]) // object
41197330f729Sjoerg /// _Block_object_dispose(_src->object,
41207330f729Sjoerg /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
41217330f729Sjoerg /// [|BLOCK_FIELD_IS_WEAK]) // block
41227330f729Sjoerg /// }
41237330f729Sjoerg
SynthesizeByrefCopyDestroyHelper(VarDecl * VD,int flag)41247330f729Sjoerg std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
41257330f729Sjoerg int flag) {
41267330f729Sjoerg std::string S;
41277330f729Sjoerg if (CopyDestroyCache.count(flag))
41287330f729Sjoerg return S;
41297330f729Sjoerg CopyDestroyCache.insert(flag);
41307330f729Sjoerg S = "static void __Block_byref_id_object_copy_";
41317330f729Sjoerg S += utostr(flag);
41327330f729Sjoerg S += "(void *dst, void *src) {\n";
41337330f729Sjoerg
41347330f729Sjoerg // offset into the object pointer is computed as:
41357330f729Sjoerg // void * + void* + int + int + void* + void *
41367330f729Sjoerg unsigned IntSize =
41377330f729Sjoerg static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
41387330f729Sjoerg unsigned VoidPtrSize =
41397330f729Sjoerg static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
41407330f729Sjoerg
41417330f729Sjoerg unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
41427330f729Sjoerg S += " _Block_object_assign((char*)dst + ";
41437330f729Sjoerg S += utostr(offset);
41447330f729Sjoerg S += ", *(void * *) ((char*)src + ";
41457330f729Sjoerg S += utostr(offset);
41467330f729Sjoerg S += "), ";
41477330f729Sjoerg S += utostr(flag);
41487330f729Sjoerg S += ");\n}\n";
41497330f729Sjoerg
41507330f729Sjoerg S += "static void __Block_byref_id_object_dispose_";
41517330f729Sjoerg S += utostr(flag);
41527330f729Sjoerg S += "(void *src) {\n";
41537330f729Sjoerg S += " _Block_object_dispose(*(void * *) ((char*)src + ";
41547330f729Sjoerg S += utostr(offset);
41557330f729Sjoerg S += "), ";
41567330f729Sjoerg S += utostr(flag);
41577330f729Sjoerg S += ");\n}\n";
41587330f729Sjoerg return S;
41597330f729Sjoerg }
41607330f729Sjoerg
41617330f729Sjoerg /// RewriteByRefVar - For each __block typex ND variable this routine transforms
41627330f729Sjoerg /// the declaration into:
41637330f729Sjoerg /// struct __Block_byref_ND {
41647330f729Sjoerg /// void *__isa; // NULL for everything except __weak pointers
41657330f729Sjoerg /// struct __Block_byref_ND *__forwarding;
41667330f729Sjoerg /// int32_t __flags;
41677330f729Sjoerg /// int32_t __size;
41687330f729Sjoerg /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
41697330f729Sjoerg /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
41707330f729Sjoerg /// typex ND;
41717330f729Sjoerg /// };
41727330f729Sjoerg ///
41737330f729Sjoerg /// It then replaces declaration of ND variable with:
41747330f729Sjoerg /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
41757330f729Sjoerg /// __size=sizeof(struct __Block_byref_ND),
41767330f729Sjoerg /// ND=initializer-if-any};
41777330f729Sjoerg ///
41787330f729Sjoerg ///
RewriteByRefVar(VarDecl * ND)41797330f729Sjoerg void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
41807330f729Sjoerg // Insert declaration for the function in which block literal is
41817330f729Sjoerg // used.
41827330f729Sjoerg if (CurFunctionDeclToDeclareForBlock)
41837330f729Sjoerg RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
41847330f729Sjoerg int flag = 0;
41857330f729Sjoerg int isa = 0;
41867330f729Sjoerg SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
41877330f729Sjoerg if (DeclLoc.isInvalid())
41887330f729Sjoerg // If type location is missing, it is because of missing type (a warning).
41897330f729Sjoerg // Use variable's location which is good for this case.
41907330f729Sjoerg DeclLoc = ND->getLocation();
41917330f729Sjoerg const char *startBuf = SM->getCharacterData(DeclLoc);
41927330f729Sjoerg SourceLocation X = ND->getEndLoc();
41937330f729Sjoerg X = SM->getExpansionLoc(X);
41947330f729Sjoerg const char *endBuf = SM->getCharacterData(X);
41957330f729Sjoerg std::string Name(ND->getNameAsString());
41967330f729Sjoerg std::string ByrefType;
41977330f729Sjoerg RewriteByRefString(ByrefType, Name, ND, true);
41987330f729Sjoerg ByrefType += " {\n";
41997330f729Sjoerg ByrefType += " void *__isa;\n";
42007330f729Sjoerg RewriteByRefString(ByrefType, Name, ND);
42017330f729Sjoerg ByrefType += " *__forwarding;\n";
42027330f729Sjoerg ByrefType += " int __flags;\n";
42037330f729Sjoerg ByrefType += " int __size;\n";
42047330f729Sjoerg // Add void *__Block_byref_id_object_copy;
42057330f729Sjoerg // void *__Block_byref_id_object_dispose; if needed.
42067330f729Sjoerg QualType Ty = ND->getType();
42077330f729Sjoerg bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
42087330f729Sjoerg if (HasCopyAndDispose) {
42097330f729Sjoerg ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
42107330f729Sjoerg ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
42117330f729Sjoerg }
42127330f729Sjoerg
42137330f729Sjoerg QualType T = Ty;
42147330f729Sjoerg (void)convertBlockPointerToFunctionPointer(T);
42157330f729Sjoerg T.getAsStringInternal(Name, Context->getPrintingPolicy());
42167330f729Sjoerg
42177330f729Sjoerg ByrefType += " " + Name + ";\n";
42187330f729Sjoerg ByrefType += "};\n";
42197330f729Sjoerg // Insert this type in global scope. It is needed by helper function.
42207330f729Sjoerg SourceLocation FunLocStart;
42217330f729Sjoerg if (CurFunctionDef)
42227330f729Sjoerg FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
42237330f729Sjoerg else {
42247330f729Sjoerg assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
42257330f729Sjoerg FunLocStart = CurMethodDef->getBeginLoc();
42267330f729Sjoerg }
42277330f729Sjoerg InsertText(FunLocStart, ByrefType);
42287330f729Sjoerg if (Ty.isObjCGCWeak()) {
42297330f729Sjoerg flag |= BLOCK_FIELD_IS_WEAK;
42307330f729Sjoerg isa = 1;
42317330f729Sjoerg }
42327330f729Sjoerg
42337330f729Sjoerg if (HasCopyAndDispose) {
42347330f729Sjoerg flag = BLOCK_BYREF_CALLER;
42357330f729Sjoerg QualType Ty = ND->getType();
42367330f729Sjoerg // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
42377330f729Sjoerg if (Ty->isBlockPointerType())
42387330f729Sjoerg flag |= BLOCK_FIELD_IS_BLOCK;
42397330f729Sjoerg else
42407330f729Sjoerg flag |= BLOCK_FIELD_IS_OBJECT;
42417330f729Sjoerg std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
42427330f729Sjoerg if (!HF.empty())
42437330f729Sjoerg InsertText(FunLocStart, HF);
42447330f729Sjoerg }
42457330f729Sjoerg
42467330f729Sjoerg // struct __Block_byref_ND ND =
42477330f729Sjoerg // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
42487330f729Sjoerg // initializer-if-any};
42497330f729Sjoerg bool hasInit = (ND->getInit() != nullptr);
42507330f729Sjoerg unsigned flags = 0;
42517330f729Sjoerg if (HasCopyAndDispose)
42527330f729Sjoerg flags |= BLOCK_HAS_COPY_DISPOSE;
42537330f729Sjoerg Name = ND->getNameAsString();
42547330f729Sjoerg ByrefType.clear();
42557330f729Sjoerg RewriteByRefString(ByrefType, Name, ND);
42567330f729Sjoerg std::string ForwardingCastType("(");
42577330f729Sjoerg ForwardingCastType += ByrefType + " *)";
42587330f729Sjoerg if (!hasInit) {
42597330f729Sjoerg ByrefType += " " + Name + " = {(void*)";
42607330f729Sjoerg ByrefType += utostr(isa);
42617330f729Sjoerg ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
42627330f729Sjoerg ByrefType += utostr(flags);
42637330f729Sjoerg ByrefType += ", ";
42647330f729Sjoerg ByrefType += "sizeof(";
42657330f729Sjoerg RewriteByRefString(ByrefType, Name, ND);
42667330f729Sjoerg ByrefType += ")";
42677330f729Sjoerg if (HasCopyAndDispose) {
42687330f729Sjoerg ByrefType += ", __Block_byref_id_object_copy_";
42697330f729Sjoerg ByrefType += utostr(flag);
42707330f729Sjoerg ByrefType += ", __Block_byref_id_object_dispose_";
42717330f729Sjoerg ByrefType += utostr(flag);
42727330f729Sjoerg }
42737330f729Sjoerg ByrefType += "};\n";
42747330f729Sjoerg unsigned nameSize = Name.size();
42757330f729Sjoerg // for block or function pointer declaration. Name is already
42767330f729Sjoerg // part of the declaration.
42777330f729Sjoerg if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
42787330f729Sjoerg nameSize = 1;
42797330f729Sjoerg ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
42807330f729Sjoerg }
42817330f729Sjoerg else {
42827330f729Sjoerg SourceLocation startLoc;
42837330f729Sjoerg Expr *E = ND->getInit();
42847330f729Sjoerg if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
42857330f729Sjoerg startLoc = ECE->getLParenLoc();
42867330f729Sjoerg else
42877330f729Sjoerg startLoc = E->getBeginLoc();
42887330f729Sjoerg startLoc = SM->getExpansionLoc(startLoc);
42897330f729Sjoerg endBuf = SM->getCharacterData(startLoc);
42907330f729Sjoerg ByrefType += " " + Name;
42917330f729Sjoerg ByrefType += " = {(void*)";
42927330f729Sjoerg ByrefType += utostr(isa);
42937330f729Sjoerg ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
42947330f729Sjoerg ByrefType += utostr(flags);
42957330f729Sjoerg ByrefType += ", ";
42967330f729Sjoerg ByrefType += "sizeof(";
42977330f729Sjoerg RewriteByRefString(ByrefType, Name, ND);
42987330f729Sjoerg ByrefType += "), ";
42997330f729Sjoerg if (HasCopyAndDispose) {
43007330f729Sjoerg ByrefType += "__Block_byref_id_object_copy_";
43017330f729Sjoerg ByrefType += utostr(flag);
43027330f729Sjoerg ByrefType += ", __Block_byref_id_object_dispose_";
43037330f729Sjoerg ByrefType += utostr(flag);
43047330f729Sjoerg ByrefType += ", ";
43057330f729Sjoerg }
43067330f729Sjoerg ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
43077330f729Sjoerg
43087330f729Sjoerg // Complete the newly synthesized compound expression by inserting a right
43097330f729Sjoerg // curly brace before the end of the declaration.
43107330f729Sjoerg // FIXME: This approach avoids rewriting the initializer expression. It
43117330f729Sjoerg // also assumes there is only one declarator. For example, the following
43127330f729Sjoerg // isn't currently supported by this routine (in general):
43137330f729Sjoerg //
43147330f729Sjoerg // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
43157330f729Sjoerg //
43167330f729Sjoerg const char *startInitializerBuf = SM->getCharacterData(startLoc);
43177330f729Sjoerg const char *semiBuf = strchr(startInitializerBuf, ';');
43187330f729Sjoerg assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
43197330f729Sjoerg SourceLocation semiLoc =
43207330f729Sjoerg startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
43217330f729Sjoerg
43227330f729Sjoerg InsertText(semiLoc, "}");
43237330f729Sjoerg }
43247330f729Sjoerg }
43257330f729Sjoerg
CollectBlockDeclRefInfo(BlockExpr * Exp)43267330f729Sjoerg void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
43277330f729Sjoerg // Add initializers for any closure decl refs.
43287330f729Sjoerg GetBlockDeclRefExprs(Exp->getBody());
43297330f729Sjoerg if (BlockDeclRefs.size()) {
43307330f729Sjoerg // Unique all "by copy" declarations.
43317330f729Sjoerg for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
43327330f729Sjoerg if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
43337330f729Sjoerg if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
43347330f729Sjoerg BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
43357330f729Sjoerg BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
43367330f729Sjoerg }
43377330f729Sjoerg }
43387330f729Sjoerg // Unique all "by ref" declarations.
43397330f729Sjoerg for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
43407330f729Sjoerg if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
43417330f729Sjoerg if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
43427330f729Sjoerg BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
43437330f729Sjoerg BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
43447330f729Sjoerg }
43457330f729Sjoerg }
43467330f729Sjoerg // Find any imported blocks...they will need special attention.
43477330f729Sjoerg for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
43487330f729Sjoerg if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
43497330f729Sjoerg BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
43507330f729Sjoerg BlockDeclRefs[i]->getType()->isBlockPointerType())
43517330f729Sjoerg ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
43527330f729Sjoerg }
43537330f729Sjoerg }
43547330f729Sjoerg
SynthBlockInitFunctionDecl(StringRef name)43557330f729Sjoerg FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
43567330f729Sjoerg IdentifierInfo *ID = &Context->Idents.get(name);
43577330f729Sjoerg QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
43587330f729Sjoerg return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
43597330f729Sjoerg SourceLocation(), ID, FType, nullptr, SC_Extern,
43607330f729Sjoerg false, false);
43617330f729Sjoerg }
43627330f729Sjoerg
SynthBlockInitExpr(BlockExpr * Exp,const SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs)43637330f729Sjoerg Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
43647330f729Sjoerg const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
43657330f729Sjoerg const BlockDecl *block = Exp->getBlockDecl();
43667330f729Sjoerg Blocks.push_back(Exp);
43677330f729Sjoerg
43687330f729Sjoerg CollectBlockDeclRefInfo(Exp);
43697330f729Sjoerg
43707330f729Sjoerg // Add inner imported variables now used in current block.
43717330f729Sjoerg int countOfInnerDecls = 0;
43727330f729Sjoerg if (!InnerBlockDeclRefs.empty()) {
43737330f729Sjoerg for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
43747330f729Sjoerg DeclRefExpr *Exp = InnerBlockDeclRefs[i];
43757330f729Sjoerg ValueDecl *VD = Exp->getDecl();
43767330f729Sjoerg if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
43777330f729Sjoerg // We need to save the copied-in variables in nested
43787330f729Sjoerg // blocks because it is needed at the end for some of the API generations.
43797330f729Sjoerg // See SynthesizeBlockLiterals routine.
43807330f729Sjoerg InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
43817330f729Sjoerg BlockDeclRefs.push_back(Exp);
43827330f729Sjoerg BlockByCopyDeclsPtrSet.insert(VD);
43837330f729Sjoerg BlockByCopyDecls.push_back(VD);
43847330f729Sjoerg }
43857330f729Sjoerg if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
43867330f729Sjoerg InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
43877330f729Sjoerg BlockDeclRefs.push_back(Exp);
43887330f729Sjoerg BlockByRefDeclsPtrSet.insert(VD);
43897330f729Sjoerg BlockByRefDecls.push_back(VD);
43907330f729Sjoerg }
43917330f729Sjoerg }
43927330f729Sjoerg // Find any imported blocks...they will need special attention.
43937330f729Sjoerg for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
43947330f729Sjoerg if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
43957330f729Sjoerg InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
43967330f729Sjoerg InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
43977330f729Sjoerg ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
43987330f729Sjoerg }
43997330f729Sjoerg InnerDeclRefsCount.push_back(countOfInnerDecls);
44007330f729Sjoerg
44017330f729Sjoerg std::string FuncName;
44027330f729Sjoerg
44037330f729Sjoerg if (CurFunctionDef)
44047330f729Sjoerg FuncName = CurFunctionDef->getNameAsString();
44057330f729Sjoerg else if (CurMethodDef)
44067330f729Sjoerg BuildUniqueMethodName(FuncName, CurMethodDef);
44077330f729Sjoerg else if (GlobalVarDecl)
44087330f729Sjoerg FuncName = std::string(GlobalVarDecl->getNameAsString());
44097330f729Sjoerg
44107330f729Sjoerg std::string BlockNumber = utostr(Blocks.size()-1);
44117330f729Sjoerg
44127330f729Sjoerg std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
44137330f729Sjoerg std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
44147330f729Sjoerg
44157330f729Sjoerg // Get a pointer to the function type so we can cast appropriately.
44167330f729Sjoerg QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
44177330f729Sjoerg QualType FType = Context->getPointerType(BFT);
44187330f729Sjoerg
44197330f729Sjoerg FunctionDecl *FD;
44207330f729Sjoerg Expr *NewRep;
44217330f729Sjoerg
44227330f729Sjoerg // Simulate a constructor call...
44237330f729Sjoerg FD = SynthBlockInitFunctionDecl(Tag);
44247330f729Sjoerg DeclRefExpr *DRE = new (Context)
44257330f729Sjoerg DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
44267330f729Sjoerg
44277330f729Sjoerg SmallVector<Expr*, 4> InitExprs;
44287330f729Sjoerg
44297330f729Sjoerg // Initialize the block function.
44307330f729Sjoerg FD = SynthBlockInitFunctionDecl(Func);
44317330f729Sjoerg DeclRefExpr *Arg = new (Context) DeclRefExpr(
44327330f729Sjoerg *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
44337330f729Sjoerg CastExpr *castExpr =
44347330f729Sjoerg NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
44357330f729Sjoerg InitExprs.push_back(castExpr);
44367330f729Sjoerg
44377330f729Sjoerg // Initialize the block descriptor.
44387330f729Sjoerg std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
44397330f729Sjoerg
44407330f729Sjoerg VarDecl *NewVD = VarDecl::Create(
44417330f729Sjoerg *Context, TUDecl, SourceLocation(), SourceLocation(),
44427330f729Sjoerg &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4443*e038c9c4Sjoerg UnaryOperator *DescRefExpr = UnaryOperator::Create(
4444*e038c9c4Sjoerg const_cast<ASTContext &>(*Context),
44457330f729Sjoerg new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
44467330f729Sjoerg VK_LValue, SourceLocation()),
44477330f729Sjoerg UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
4448*e038c9c4Sjoerg OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
44497330f729Sjoerg InitExprs.push_back(DescRefExpr);
44507330f729Sjoerg
44517330f729Sjoerg // Add initializers for any closure decl refs.
44527330f729Sjoerg if (BlockDeclRefs.size()) {
44537330f729Sjoerg Expr *Exp;
44547330f729Sjoerg // Output all "by copy" declarations.
44557330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
44567330f729Sjoerg E = BlockByCopyDecls.end(); I != E; ++I) {
44577330f729Sjoerg if (isObjCType((*I)->getType())) {
44587330f729Sjoerg // FIXME: Conform to ABI ([[obj retain] autorelease]).
44597330f729Sjoerg FD = SynthBlockInitFunctionDecl((*I)->getName());
44607330f729Sjoerg Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
44617330f729Sjoerg VK_LValue, SourceLocation());
44627330f729Sjoerg if (HasLocalVariableExternalStorage(*I)) {
44637330f729Sjoerg QualType QT = (*I)->getType();
44647330f729Sjoerg QT = Context->getPointerType(QT);
4465*e038c9c4Sjoerg Exp = UnaryOperator::Create(
4466*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_RValue,
4467*e038c9c4Sjoerg OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
44687330f729Sjoerg }
44697330f729Sjoerg } else if (isTopLevelBlockPointerType((*I)->getType())) {
44707330f729Sjoerg FD = SynthBlockInitFunctionDecl((*I)->getName());
44717330f729Sjoerg Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
44727330f729Sjoerg VK_LValue, SourceLocation());
44737330f729Sjoerg Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
44747330f729Sjoerg Arg);
44757330f729Sjoerg } else {
44767330f729Sjoerg FD = SynthBlockInitFunctionDecl((*I)->getName());
44777330f729Sjoerg Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
44787330f729Sjoerg VK_LValue, SourceLocation());
44797330f729Sjoerg if (HasLocalVariableExternalStorage(*I)) {
44807330f729Sjoerg QualType QT = (*I)->getType();
44817330f729Sjoerg QT = Context->getPointerType(QT);
4482*e038c9c4Sjoerg Exp = UnaryOperator::Create(
4483*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_RValue,
4484*e038c9c4Sjoerg OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
44857330f729Sjoerg }
44867330f729Sjoerg }
44877330f729Sjoerg InitExprs.push_back(Exp);
44887330f729Sjoerg }
44897330f729Sjoerg // Output all "by ref" declarations.
44907330f729Sjoerg for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
44917330f729Sjoerg E = BlockByRefDecls.end(); I != E; ++I) {
44927330f729Sjoerg ValueDecl *ND = (*I);
44937330f729Sjoerg std::string Name(ND->getNameAsString());
44947330f729Sjoerg std::string RecName;
44957330f729Sjoerg RewriteByRefString(RecName, Name, ND, true);
44967330f729Sjoerg IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
44977330f729Sjoerg + sizeof("struct"));
44987330f729Sjoerg RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
44997330f729Sjoerg SourceLocation(), SourceLocation(),
45007330f729Sjoerg II);
45017330f729Sjoerg assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
45027330f729Sjoerg QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
45037330f729Sjoerg
45047330f729Sjoerg FD = SynthBlockInitFunctionDecl((*I)->getName());
45057330f729Sjoerg Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
45067330f729Sjoerg VK_LValue, SourceLocation());
45077330f729Sjoerg bool isNestedCapturedVar = false;
45087330f729Sjoerg if (block)
45097330f729Sjoerg for (const auto &CI : block->captures()) {
45107330f729Sjoerg const VarDecl *variable = CI.getVariable();
45117330f729Sjoerg if (variable == ND && CI.isNested()) {
45127330f729Sjoerg assert (CI.isByRef() &&
45137330f729Sjoerg "SynthBlockInitExpr - captured block variable is not byref");
45147330f729Sjoerg isNestedCapturedVar = true;
45157330f729Sjoerg break;
45167330f729Sjoerg }
45177330f729Sjoerg }
45187330f729Sjoerg // captured nested byref variable has its address passed. Do not take
45197330f729Sjoerg // its address again.
45207330f729Sjoerg if (!isNestedCapturedVar)
4521*e038c9c4Sjoerg Exp = UnaryOperator::Create(
4522*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
4523*e038c9c4Sjoerg Context->getPointerType(Exp->getType()), VK_RValue, OK_Ordinary,
4524*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
45257330f729Sjoerg Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
45267330f729Sjoerg InitExprs.push_back(Exp);
45277330f729Sjoerg }
45287330f729Sjoerg }
45297330f729Sjoerg if (ImportedBlockDecls.size()) {
45307330f729Sjoerg // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
45317330f729Sjoerg int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
45327330f729Sjoerg unsigned IntSize =
45337330f729Sjoerg static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
45347330f729Sjoerg Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
45357330f729Sjoerg Context->IntTy, SourceLocation());
45367330f729Sjoerg InitExprs.push_back(FlagExp);
45377330f729Sjoerg }
45387330f729Sjoerg NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
4539*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
4540*e038c9c4Sjoerg NewRep = UnaryOperator::Create(
4541*e038c9c4Sjoerg const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
4542*e038c9c4Sjoerg Context->getPointerType(NewRep->getType()), VK_RValue, OK_Ordinary,
4543*e038c9c4Sjoerg SourceLocation(), false, FPOptionsOverride());
45447330f729Sjoerg NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
45457330f729Sjoerg NewRep);
45467330f729Sjoerg BlockDeclRefs.clear();
45477330f729Sjoerg BlockByRefDecls.clear();
45487330f729Sjoerg BlockByRefDeclsPtrSet.clear();
45497330f729Sjoerg BlockByCopyDecls.clear();
45507330f729Sjoerg BlockByCopyDeclsPtrSet.clear();
45517330f729Sjoerg ImportedBlockDecls.clear();
45527330f729Sjoerg return NewRep;
45537330f729Sjoerg }
45547330f729Sjoerg
IsDeclStmtInForeachHeader(DeclStmt * DS)45557330f729Sjoerg bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
45567330f729Sjoerg if (const ObjCForCollectionStmt * CS =
45577330f729Sjoerg dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
45587330f729Sjoerg return CS->getElement() == DS;
45597330f729Sjoerg return false;
45607330f729Sjoerg }
45617330f729Sjoerg
45627330f729Sjoerg //===----------------------------------------------------------------------===//
45637330f729Sjoerg // Function Body / Expression rewriting
45647330f729Sjoerg //===----------------------------------------------------------------------===//
45657330f729Sjoerg
RewriteFunctionBodyOrGlobalInitializer(Stmt * S)45667330f729Sjoerg Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
45677330f729Sjoerg if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
45687330f729Sjoerg isa<DoStmt>(S) || isa<ForStmt>(S))
45697330f729Sjoerg Stmts.push_back(S);
45707330f729Sjoerg else if (isa<ObjCForCollectionStmt>(S)) {
45717330f729Sjoerg Stmts.push_back(S);
45727330f729Sjoerg ObjCBcLabelNo.push_back(++BcLabelCount);
45737330f729Sjoerg }
45747330f729Sjoerg
45757330f729Sjoerg // Pseudo-object operations and ivar references need special
45767330f729Sjoerg // treatment because we're going to recursively rewrite them.
45777330f729Sjoerg if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
45787330f729Sjoerg if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
45797330f729Sjoerg return RewritePropertyOrImplicitSetter(PseudoOp);
45807330f729Sjoerg } else {
45817330f729Sjoerg return RewritePropertyOrImplicitGetter(PseudoOp);
45827330f729Sjoerg }
45837330f729Sjoerg } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
45847330f729Sjoerg return RewriteObjCIvarRefExpr(IvarRefExpr);
45857330f729Sjoerg }
45867330f729Sjoerg
45877330f729Sjoerg SourceRange OrigStmtRange = S->getSourceRange();
45887330f729Sjoerg
45897330f729Sjoerg // Perform a bottom up rewrite of all children.
45907330f729Sjoerg for (Stmt *&childStmt : S->children())
45917330f729Sjoerg if (childStmt) {
45927330f729Sjoerg Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
45937330f729Sjoerg if (newStmt) {
45947330f729Sjoerg childStmt = newStmt;
45957330f729Sjoerg }
45967330f729Sjoerg }
45977330f729Sjoerg
45987330f729Sjoerg if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
45997330f729Sjoerg SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
46007330f729Sjoerg llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
46017330f729Sjoerg InnerContexts.insert(BE->getBlockDecl());
46027330f729Sjoerg ImportedLocalExternalDecls.clear();
46037330f729Sjoerg GetInnerBlockDeclRefExprs(BE->getBody(),
46047330f729Sjoerg InnerBlockDeclRefs, InnerContexts);
46057330f729Sjoerg // Rewrite the block body in place.
46067330f729Sjoerg Stmt *SaveCurrentBody = CurrentBody;
46077330f729Sjoerg CurrentBody = BE->getBody();
46087330f729Sjoerg PropParentMap = nullptr;
46097330f729Sjoerg // block literal on rhs of a property-dot-sytax assignment
46107330f729Sjoerg // must be replaced by its synthesize ast so getRewrittenText
46117330f729Sjoerg // works as expected. In this case, what actually ends up on RHS
46127330f729Sjoerg // is the blockTranscribed which is the helper function for the
46137330f729Sjoerg // block literal; as in: self.c = ^() {[ace ARR];};
46147330f729Sjoerg bool saveDisableReplaceStmt = DisableReplaceStmt;
46157330f729Sjoerg DisableReplaceStmt = false;
46167330f729Sjoerg RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
46177330f729Sjoerg DisableReplaceStmt = saveDisableReplaceStmt;
46187330f729Sjoerg CurrentBody = SaveCurrentBody;
46197330f729Sjoerg PropParentMap = nullptr;
46207330f729Sjoerg ImportedLocalExternalDecls.clear();
46217330f729Sjoerg // Now we snarf the rewritten text and stash it away for later use.
46227330f729Sjoerg std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
46237330f729Sjoerg RewrittenBlockExprs[BE] = Str;
46247330f729Sjoerg
46257330f729Sjoerg Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
46267330f729Sjoerg
46277330f729Sjoerg //blockTranscribed->dump();
46287330f729Sjoerg ReplaceStmt(S, blockTranscribed);
46297330f729Sjoerg return blockTranscribed;
46307330f729Sjoerg }
46317330f729Sjoerg // Handle specific things.
46327330f729Sjoerg if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
46337330f729Sjoerg return RewriteAtEncode(AtEncode);
46347330f729Sjoerg
46357330f729Sjoerg if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
46367330f729Sjoerg return RewriteAtSelector(AtSelector);
46377330f729Sjoerg
46387330f729Sjoerg if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
46397330f729Sjoerg return RewriteObjCStringLiteral(AtString);
46407330f729Sjoerg
46417330f729Sjoerg if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
46427330f729Sjoerg #if 0
46437330f729Sjoerg // Before we rewrite it, put the original message expression in a comment.
46447330f729Sjoerg SourceLocation startLoc = MessExpr->getBeginLoc();
46457330f729Sjoerg SourceLocation endLoc = MessExpr->getEndLoc();
46467330f729Sjoerg
46477330f729Sjoerg const char *startBuf = SM->getCharacterData(startLoc);
46487330f729Sjoerg const char *endBuf = SM->getCharacterData(endLoc);
46497330f729Sjoerg
46507330f729Sjoerg std::string messString;
46517330f729Sjoerg messString += "// ";
46527330f729Sjoerg messString.append(startBuf, endBuf-startBuf+1);
46537330f729Sjoerg messString += "\n";
46547330f729Sjoerg
46557330f729Sjoerg // FIXME: Missing definition of
46567330f729Sjoerg // InsertText(clang::SourceLocation, char const*, unsigned int).
46577330f729Sjoerg // InsertText(startLoc, messString);
46587330f729Sjoerg // Tried this, but it didn't work either...
46597330f729Sjoerg // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
46607330f729Sjoerg #endif
46617330f729Sjoerg return RewriteMessageExpr(MessExpr);
46627330f729Sjoerg }
46637330f729Sjoerg
46647330f729Sjoerg if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
46657330f729Sjoerg return RewriteObjCTryStmt(StmtTry);
46667330f729Sjoerg
46677330f729Sjoerg if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
46687330f729Sjoerg return RewriteObjCSynchronizedStmt(StmtTry);
46697330f729Sjoerg
46707330f729Sjoerg if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
46717330f729Sjoerg return RewriteObjCThrowStmt(StmtThrow);
46727330f729Sjoerg
46737330f729Sjoerg if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
46747330f729Sjoerg return RewriteObjCProtocolExpr(ProtocolExp);
46757330f729Sjoerg
46767330f729Sjoerg if (ObjCForCollectionStmt *StmtForCollection =
46777330f729Sjoerg dyn_cast<ObjCForCollectionStmt>(S))
46787330f729Sjoerg return RewriteObjCForCollectionStmt(StmtForCollection,
46797330f729Sjoerg OrigStmtRange.getEnd());
46807330f729Sjoerg if (BreakStmt *StmtBreakStmt =
46817330f729Sjoerg dyn_cast<BreakStmt>(S))
46827330f729Sjoerg return RewriteBreakStmt(StmtBreakStmt);
46837330f729Sjoerg if (ContinueStmt *StmtContinueStmt =
46847330f729Sjoerg dyn_cast<ContinueStmt>(S))
46857330f729Sjoerg return RewriteContinueStmt(StmtContinueStmt);
46867330f729Sjoerg
46877330f729Sjoerg // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
46887330f729Sjoerg // and cast exprs.
46897330f729Sjoerg if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
46907330f729Sjoerg // FIXME: What we're doing here is modifying the type-specifier that
46917330f729Sjoerg // precedes the first Decl. In the future the DeclGroup should have
46927330f729Sjoerg // a separate type-specifier that we can rewrite.
46937330f729Sjoerg // NOTE: We need to avoid rewriting the DeclStmt if it is within
46947330f729Sjoerg // the context of an ObjCForCollectionStmt. For example:
46957330f729Sjoerg // NSArray *someArray;
46967330f729Sjoerg // for (id <FooProtocol> index in someArray) ;
46977330f729Sjoerg // This is because RewriteObjCForCollectionStmt() does textual rewriting
46987330f729Sjoerg // and it depends on the original text locations/positions.
46997330f729Sjoerg if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
47007330f729Sjoerg RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
47017330f729Sjoerg
47027330f729Sjoerg // Blocks rewrite rules.
47037330f729Sjoerg for (auto *SD : DS->decls()) {
47047330f729Sjoerg if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
47057330f729Sjoerg if (isTopLevelBlockPointerType(ND->getType()))
47067330f729Sjoerg RewriteBlockPointerDecl(ND);
47077330f729Sjoerg else if (ND->getType()->isFunctionPointerType())
47087330f729Sjoerg CheckFunctionPointerDecl(ND->getType(), ND);
47097330f729Sjoerg if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
47107330f729Sjoerg if (VD->hasAttr<BlocksAttr>()) {
47117330f729Sjoerg static unsigned uniqueByrefDeclCount = 0;
47127330f729Sjoerg assert(!BlockByRefDeclNo.count(ND) &&
47137330f729Sjoerg "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
47147330f729Sjoerg BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
47157330f729Sjoerg RewriteByRefVar(VD);
47167330f729Sjoerg }
47177330f729Sjoerg else
47187330f729Sjoerg RewriteTypeOfDecl(VD);
47197330f729Sjoerg }
47207330f729Sjoerg }
47217330f729Sjoerg if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
47227330f729Sjoerg if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
47237330f729Sjoerg RewriteBlockPointerDecl(TD);
47247330f729Sjoerg else if (TD->getUnderlyingType()->isFunctionPointerType())
47257330f729Sjoerg CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
47267330f729Sjoerg }
47277330f729Sjoerg }
47287330f729Sjoerg }
47297330f729Sjoerg
47307330f729Sjoerg if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
47317330f729Sjoerg RewriteObjCQualifiedInterfaceTypes(CE);
47327330f729Sjoerg
47337330f729Sjoerg if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
47347330f729Sjoerg isa<DoStmt>(S) || isa<ForStmt>(S)) {
47357330f729Sjoerg assert(!Stmts.empty() && "Statement stack is empty");
47367330f729Sjoerg assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
47377330f729Sjoerg isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
47387330f729Sjoerg && "Statement stack mismatch");
47397330f729Sjoerg Stmts.pop_back();
47407330f729Sjoerg }
47417330f729Sjoerg // Handle blocks rewriting.
47427330f729Sjoerg if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
47437330f729Sjoerg ValueDecl *VD = DRE->getDecl();
47447330f729Sjoerg if (VD->hasAttr<BlocksAttr>())
47457330f729Sjoerg return RewriteBlockDeclRefExpr(DRE);
47467330f729Sjoerg if (HasLocalVariableExternalStorage(VD))
47477330f729Sjoerg return RewriteLocalVariableExternalStorage(DRE);
47487330f729Sjoerg }
47497330f729Sjoerg
47507330f729Sjoerg if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
47517330f729Sjoerg if (CE->getCallee()->getType()->isBlockPointerType()) {
47527330f729Sjoerg Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
47537330f729Sjoerg ReplaceStmt(S, BlockCall);
47547330f729Sjoerg return BlockCall;
47557330f729Sjoerg }
47567330f729Sjoerg }
47577330f729Sjoerg if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
47587330f729Sjoerg RewriteCastExpr(CE);
47597330f729Sjoerg }
47607330f729Sjoerg #if 0
47617330f729Sjoerg if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
47627330f729Sjoerg CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
47637330f729Sjoerg ICE->getSubExpr(),
47647330f729Sjoerg SourceLocation());
47657330f729Sjoerg // Get the new text.
47667330f729Sjoerg std::string SStr;
47677330f729Sjoerg llvm::raw_string_ostream Buf(SStr);
47687330f729Sjoerg Replacement->printPretty(Buf);
47697330f729Sjoerg const std::string &Str = Buf.str();
47707330f729Sjoerg
47717330f729Sjoerg printf("CAST = %s\n", &Str[0]);
47727330f729Sjoerg InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
47737330f729Sjoerg delete S;
47747330f729Sjoerg return Replacement;
47757330f729Sjoerg }
47767330f729Sjoerg #endif
47777330f729Sjoerg // Return this stmt unmodified.
47787330f729Sjoerg return S;
47797330f729Sjoerg }
47807330f729Sjoerg
RewriteRecordBody(RecordDecl * RD)47817330f729Sjoerg void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
47827330f729Sjoerg for (auto *FD : RD->fields()) {
47837330f729Sjoerg if (isTopLevelBlockPointerType(FD->getType()))
47847330f729Sjoerg RewriteBlockPointerDecl(FD);
47857330f729Sjoerg if (FD->getType()->isObjCQualifiedIdType() ||
47867330f729Sjoerg FD->getType()->isObjCQualifiedInterfaceType())
47877330f729Sjoerg RewriteObjCQualifiedInterfaceTypes(FD);
47887330f729Sjoerg }
47897330f729Sjoerg }
47907330f729Sjoerg
47917330f729Sjoerg /// HandleDeclInMainFile - This is called for each top-level decl defined in the
47927330f729Sjoerg /// main file of the input.
HandleDeclInMainFile(Decl * D)47937330f729Sjoerg void RewriteObjC::HandleDeclInMainFile(Decl *D) {
47947330f729Sjoerg switch (D->getKind()) {
47957330f729Sjoerg case Decl::Function: {
47967330f729Sjoerg FunctionDecl *FD = cast<FunctionDecl>(D);
47977330f729Sjoerg if (FD->isOverloadedOperator())
47987330f729Sjoerg return;
47997330f729Sjoerg
48007330f729Sjoerg // Since function prototypes don't have ParmDecl's, we check the function
48017330f729Sjoerg // prototype. This enables us to rewrite function declarations and
48027330f729Sjoerg // definitions using the same code.
48037330f729Sjoerg RewriteBlocksInFunctionProtoType(FD->getType(), FD);
48047330f729Sjoerg
48057330f729Sjoerg if (!FD->isThisDeclarationADefinition())
48067330f729Sjoerg break;
48077330f729Sjoerg
48087330f729Sjoerg // FIXME: If this should support Obj-C++, support CXXTryStmt
48097330f729Sjoerg if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
48107330f729Sjoerg CurFunctionDef = FD;
48117330f729Sjoerg CurFunctionDeclToDeclareForBlock = FD;
48127330f729Sjoerg CurrentBody = Body;
48137330f729Sjoerg Body =
48147330f729Sjoerg cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
48157330f729Sjoerg FD->setBody(Body);
48167330f729Sjoerg CurrentBody = nullptr;
48177330f729Sjoerg if (PropParentMap) {
48187330f729Sjoerg delete PropParentMap;
48197330f729Sjoerg PropParentMap = nullptr;
48207330f729Sjoerg }
48217330f729Sjoerg // This synthesizes and inserts the block "impl" struct, invoke function,
48227330f729Sjoerg // and any copy/dispose helper functions.
48237330f729Sjoerg InsertBlockLiteralsWithinFunction(FD);
48247330f729Sjoerg CurFunctionDef = nullptr;
48257330f729Sjoerg CurFunctionDeclToDeclareForBlock = nullptr;
48267330f729Sjoerg }
48277330f729Sjoerg break;
48287330f729Sjoerg }
48297330f729Sjoerg case Decl::ObjCMethod: {
48307330f729Sjoerg ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
48317330f729Sjoerg if (CompoundStmt *Body = MD->getCompoundBody()) {
48327330f729Sjoerg CurMethodDef = MD;
48337330f729Sjoerg CurrentBody = Body;
48347330f729Sjoerg Body =
48357330f729Sjoerg cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
48367330f729Sjoerg MD->setBody(Body);
48377330f729Sjoerg CurrentBody = nullptr;
48387330f729Sjoerg if (PropParentMap) {
48397330f729Sjoerg delete PropParentMap;
48407330f729Sjoerg PropParentMap = nullptr;
48417330f729Sjoerg }
48427330f729Sjoerg InsertBlockLiteralsWithinMethod(MD);
48437330f729Sjoerg CurMethodDef = nullptr;
48447330f729Sjoerg }
48457330f729Sjoerg break;
48467330f729Sjoerg }
48477330f729Sjoerg case Decl::ObjCImplementation: {
48487330f729Sjoerg ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
48497330f729Sjoerg ClassImplementation.push_back(CI);
48507330f729Sjoerg break;
48517330f729Sjoerg }
48527330f729Sjoerg case Decl::ObjCCategoryImpl: {
48537330f729Sjoerg ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
48547330f729Sjoerg CategoryImplementation.push_back(CI);
48557330f729Sjoerg break;
48567330f729Sjoerg }
48577330f729Sjoerg case Decl::Var: {
48587330f729Sjoerg VarDecl *VD = cast<VarDecl>(D);
48597330f729Sjoerg RewriteObjCQualifiedInterfaceTypes(VD);
48607330f729Sjoerg if (isTopLevelBlockPointerType(VD->getType()))
48617330f729Sjoerg RewriteBlockPointerDecl(VD);
48627330f729Sjoerg else if (VD->getType()->isFunctionPointerType()) {
48637330f729Sjoerg CheckFunctionPointerDecl(VD->getType(), VD);
48647330f729Sjoerg if (VD->getInit()) {
48657330f729Sjoerg if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
48667330f729Sjoerg RewriteCastExpr(CE);
48677330f729Sjoerg }
48687330f729Sjoerg }
48697330f729Sjoerg } else if (VD->getType()->isRecordType()) {
48707330f729Sjoerg RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
48717330f729Sjoerg if (RD->isCompleteDefinition())
48727330f729Sjoerg RewriteRecordBody(RD);
48737330f729Sjoerg }
48747330f729Sjoerg if (VD->getInit()) {
48757330f729Sjoerg GlobalVarDecl = VD;
48767330f729Sjoerg CurrentBody = VD->getInit();
48777330f729Sjoerg RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
48787330f729Sjoerg CurrentBody = nullptr;
48797330f729Sjoerg if (PropParentMap) {
48807330f729Sjoerg delete PropParentMap;
48817330f729Sjoerg PropParentMap = nullptr;
48827330f729Sjoerg }
48837330f729Sjoerg SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
48847330f729Sjoerg GlobalVarDecl = nullptr;
48857330f729Sjoerg
48867330f729Sjoerg // This is needed for blocks.
48877330f729Sjoerg if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
48887330f729Sjoerg RewriteCastExpr(CE);
48897330f729Sjoerg }
48907330f729Sjoerg }
48917330f729Sjoerg break;
48927330f729Sjoerg }
48937330f729Sjoerg case Decl::TypeAlias:
48947330f729Sjoerg case Decl::Typedef: {
48957330f729Sjoerg if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
48967330f729Sjoerg if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
48977330f729Sjoerg RewriteBlockPointerDecl(TD);
48987330f729Sjoerg else if (TD->getUnderlyingType()->isFunctionPointerType())
48997330f729Sjoerg CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
49007330f729Sjoerg }
49017330f729Sjoerg break;
49027330f729Sjoerg }
49037330f729Sjoerg case Decl::CXXRecord:
49047330f729Sjoerg case Decl::Record: {
49057330f729Sjoerg RecordDecl *RD = cast<RecordDecl>(D);
49067330f729Sjoerg if (RD->isCompleteDefinition())
49077330f729Sjoerg RewriteRecordBody(RD);
49087330f729Sjoerg break;
49097330f729Sjoerg }
49107330f729Sjoerg default:
49117330f729Sjoerg break;
49127330f729Sjoerg }
49137330f729Sjoerg // Nothing yet.
49147330f729Sjoerg }
49157330f729Sjoerg
HandleTranslationUnit(ASTContext & C)49167330f729Sjoerg void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
49177330f729Sjoerg if (Diags.hasErrorOccurred())
49187330f729Sjoerg return;
49197330f729Sjoerg
49207330f729Sjoerg RewriteInclude();
49217330f729Sjoerg
49227330f729Sjoerg // Here's a great place to add any extra declarations that may be needed.
49237330f729Sjoerg // Write out meta data for each @protocol(<expr>).
49247330f729Sjoerg for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
49257330f729Sjoerg RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
49267330f729Sjoerg
49277330f729Sjoerg InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
49287330f729Sjoerg if (ClassImplementation.size() || CategoryImplementation.size())
49297330f729Sjoerg RewriteImplementations();
49307330f729Sjoerg
49317330f729Sjoerg // Get the buffer corresponding to MainFileID. If we haven't changed it, then
49327330f729Sjoerg // we are done.
49337330f729Sjoerg if (const RewriteBuffer *RewriteBuf =
49347330f729Sjoerg Rewrite.getRewriteBufferFor(MainFileID)) {
49357330f729Sjoerg //printf("Changed:\n");
49367330f729Sjoerg *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
49377330f729Sjoerg } else {
49387330f729Sjoerg llvm::errs() << "No changes\n";
49397330f729Sjoerg }
49407330f729Sjoerg
49417330f729Sjoerg if (ClassImplementation.size() || CategoryImplementation.size() ||
49427330f729Sjoerg ProtocolExprDecls.size()) {
49437330f729Sjoerg // Rewrite Objective-c meta data*
49447330f729Sjoerg std::string ResultStr;
49457330f729Sjoerg RewriteMetaDataIntoBuffer(ResultStr);
49467330f729Sjoerg // Emit metadata.
49477330f729Sjoerg *OutFile << ResultStr;
49487330f729Sjoerg }
49497330f729Sjoerg OutFile->flush();
49507330f729Sjoerg }
49517330f729Sjoerg
Initialize(ASTContext & context)49527330f729Sjoerg void RewriteObjCFragileABI::Initialize(ASTContext &context) {
49537330f729Sjoerg InitializeCommon(context);
49547330f729Sjoerg
49557330f729Sjoerg // declaring objc_selector outside the parameter list removes a silly
49567330f729Sjoerg // scope related warning...
49577330f729Sjoerg if (IsHeader)
49587330f729Sjoerg Preamble = "#pragma once\n";
49597330f729Sjoerg Preamble += "struct objc_selector; struct objc_class;\n";
49607330f729Sjoerg Preamble += "struct __rw_objc_super { struct objc_object *object; ";
49617330f729Sjoerg Preamble += "struct objc_object *superClass; ";
49627330f729Sjoerg if (LangOpts.MicrosoftExt) {
49637330f729Sjoerg // Add a constructor for creating temporary objects.
49647330f729Sjoerg Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
49657330f729Sjoerg ": ";
49667330f729Sjoerg Preamble += "object(o), superClass(s) {} ";
49677330f729Sjoerg }
49687330f729Sjoerg Preamble += "};\n";
49697330f729Sjoerg Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
49707330f729Sjoerg Preamble += "typedef struct objc_object Protocol;\n";
49717330f729Sjoerg Preamble += "#define _REWRITER_typedef_Protocol\n";
49727330f729Sjoerg Preamble += "#endif\n";
49737330f729Sjoerg if (LangOpts.MicrosoftExt) {
49747330f729Sjoerg Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
49757330f729Sjoerg Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
49767330f729Sjoerg } else
49777330f729Sjoerg Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
49787330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
49797330f729Sjoerg Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
49807330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
49817330f729Sjoerg Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
49827330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
49837330f729Sjoerg Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
49847330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
49857330f729Sjoerg Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
49867330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
49877330f729Sjoerg Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
49887330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
49897330f729Sjoerg Preamble += "(const char *);\n";
49907330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
49917330f729Sjoerg Preamble += "(struct objc_class *);\n";
49927330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
49937330f729Sjoerg Preamble += "(const char *);\n";
49947330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
49957330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
49967330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
49977330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
49987330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
49997330f729Sjoerg Preamble += "(struct objc_class *, struct objc_object *);\n";
50007330f729Sjoerg // @synchronized hooks.
50017330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
50027330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
50037330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
50047330f729Sjoerg Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
50057330f729Sjoerg Preamble += "struct __objcFastEnumerationState {\n\t";
50067330f729Sjoerg Preamble += "unsigned long state;\n\t";
50077330f729Sjoerg Preamble += "void **itemsPtr;\n\t";
50087330f729Sjoerg Preamble += "unsigned long *mutationsPtr;\n\t";
50097330f729Sjoerg Preamble += "unsigned long extra[5];\n};\n";
50107330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
50117330f729Sjoerg Preamble += "#define __FASTENUMERATIONSTATE\n";
50127330f729Sjoerg Preamble += "#endif\n";
50137330f729Sjoerg Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
50147330f729Sjoerg Preamble += "struct __NSConstantStringImpl {\n";
50157330f729Sjoerg Preamble += " int *isa;\n";
50167330f729Sjoerg Preamble += " int flags;\n";
50177330f729Sjoerg Preamble += " char *str;\n";
50187330f729Sjoerg Preamble += " long length;\n";
50197330f729Sjoerg Preamble += "};\n";
50207330f729Sjoerg Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
50217330f729Sjoerg Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
50227330f729Sjoerg Preamble += "#else\n";
50237330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
50247330f729Sjoerg Preamble += "#endif\n";
50257330f729Sjoerg Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
50267330f729Sjoerg Preamble += "#endif\n";
50277330f729Sjoerg // Blocks preamble.
50287330f729Sjoerg Preamble += "#ifndef BLOCK_IMPL\n";
50297330f729Sjoerg Preamble += "#define BLOCK_IMPL\n";
50307330f729Sjoerg Preamble += "struct __block_impl {\n";
50317330f729Sjoerg Preamble += " void *isa;\n";
50327330f729Sjoerg Preamble += " int Flags;\n";
50337330f729Sjoerg Preamble += " int Reserved;\n";
50347330f729Sjoerg Preamble += " void *FuncPtr;\n";
50357330f729Sjoerg Preamble += "};\n";
50367330f729Sjoerg Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
50377330f729Sjoerg Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
50387330f729Sjoerg Preamble += "extern \"C\" __declspec(dllexport) "
50397330f729Sjoerg "void _Block_object_assign(void *, const void *, const int);\n";
50407330f729Sjoerg Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
50417330f729Sjoerg Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
50427330f729Sjoerg Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
50437330f729Sjoerg Preamble += "#else\n";
50447330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
50457330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
50467330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
50477330f729Sjoerg Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
50487330f729Sjoerg Preamble += "#endif\n";
50497330f729Sjoerg Preamble += "#endif\n";
50507330f729Sjoerg if (LangOpts.MicrosoftExt) {
50517330f729Sjoerg Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
50527330f729Sjoerg Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
50537330f729Sjoerg Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
50547330f729Sjoerg Preamble += "#define __attribute__(X)\n";
50557330f729Sjoerg Preamble += "#endif\n";
50567330f729Sjoerg Preamble += "#define __weak\n";
50577330f729Sjoerg }
50587330f729Sjoerg else {
50597330f729Sjoerg Preamble += "#define __block\n";
50607330f729Sjoerg Preamble += "#define __weak\n";
50617330f729Sjoerg }
50627330f729Sjoerg // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
50637330f729Sjoerg // as this avoids warning in any 64bit/32bit compilation model.
50647330f729Sjoerg Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
50657330f729Sjoerg }
50667330f729Sjoerg
50677330f729Sjoerg /// RewriteIvarOffsetComputation - This routine synthesizes computation of
50687330f729Sjoerg /// ivar offset.
RewriteIvarOffsetComputation(ObjCIvarDecl * ivar,std::string & Result)50697330f729Sjoerg void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
50707330f729Sjoerg std::string &Result) {
50717330f729Sjoerg if (ivar->isBitField()) {
50727330f729Sjoerg // FIXME: The hack below doesn't work for bitfields. For now, we simply
50737330f729Sjoerg // place all bitfields at offset 0.
50747330f729Sjoerg Result += "0";
50757330f729Sjoerg } else {
50767330f729Sjoerg Result += "__OFFSETOFIVAR__(struct ";
50777330f729Sjoerg Result += ivar->getContainingInterface()->getNameAsString();
50787330f729Sjoerg if (LangOpts.MicrosoftExt)
50797330f729Sjoerg Result += "_IMPL";
50807330f729Sjoerg Result += ", ";
50817330f729Sjoerg Result += ivar->getNameAsString();
50827330f729Sjoerg Result += ")";
50837330f729Sjoerg }
50847330f729Sjoerg }
50857330f729Sjoerg
50867330f729Sjoerg /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
RewriteObjCProtocolMetaData(ObjCProtocolDecl * PDecl,StringRef prefix,StringRef ClassName,std::string & Result)50877330f729Sjoerg void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
50887330f729Sjoerg ObjCProtocolDecl *PDecl, StringRef prefix,
50897330f729Sjoerg StringRef ClassName, std::string &Result) {
50907330f729Sjoerg static bool objc_protocol_methods = false;
50917330f729Sjoerg
50927330f729Sjoerg // Output struct protocol_methods holder of method selector and type.
50937330f729Sjoerg if (!objc_protocol_methods && PDecl->hasDefinition()) {
50947330f729Sjoerg /* struct protocol_methods {
50957330f729Sjoerg SEL _cmd;
50967330f729Sjoerg char *method_types;
50977330f729Sjoerg }
50987330f729Sjoerg */
50997330f729Sjoerg Result += "\nstruct _protocol_methods {\n";
51007330f729Sjoerg Result += "\tstruct objc_selector *_cmd;\n";
51017330f729Sjoerg Result += "\tchar *method_types;\n";
51027330f729Sjoerg Result += "};\n";
51037330f729Sjoerg
51047330f729Sjoerg objc_protocol_methods = true;
51057330f729Sjoerg }
51067330f729Sjoerg // Do not synthesize the protocol more than once.
51077330f729Sjoerg if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
51087330f729Sjoerg return;
51097330f729Sjoerg
51107330f729Sjoerg if (ObjCProtocolDecl *Def = PDecl->getDefinition())
51117330f729Sjoerg PDecl = Def;
51127330f729Sjoerg
51137330f729Sjoerg if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
51147330f729Sjoerg unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
51157330f729Sjoerg PDecl->instmeth_end());
51167330f729Sjoerg /* struct _objc_protocol_method_list {
51177330f729Sjoerg int protocol_method_count;
51187330f729Sjoerg struct protocol_methods protocols[];
51197330f729Sjoerg }
51207330f729Sjoerg */
51217330f729Sjoerg Result += "\nstatic struct {\n";
51227330f729Sjoerg Result += "\tint protocol_method_count;\n";
51237330f729Sjoerg Result += "\tstruct _protocol_methods protocol_methods[";
51247330f729Sjoerg Result += utostr(NumMethods);
51257330f729Sjoerg Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
51267330f729Sjoerg Result += PDecl->getNameAsString();
51277330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
51287330f729Sjoerg "{\n\t" + utostr(NumMethods) + "\n";
51297330f729Sjoerg
51307330f729Sjoerg // Output instance methods declared in this protocol.
51317330f729Sjoerg for (ObjCProtocolDecl::instmeth_iterator
51327330f729Sjoerg I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
51337330f729Sjoerg I != E; ++I) {
51347330f729Sjoerg if (I == PDecl->instmeth_begin())
51357330f729Sjoerg Result += "\t ,{{(struct objc_selector *)\"";
51367330f729Sjoerg else
51377330f729Sjoerg Result += "\t ,{(struct objc_selector *)\"";
51387330f729Sjoerg Result += (*I)->getSelector().getAsString();
51397330f729Sjoerg std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
51407330f729Sjoerg Result += "\", \"";
51417330f729Sjoerg Result += MethodTypeString;
51427330f729Sjoerg Result += "\"}\n";
51437330f729Sjoerg }
51447330f729Sjoerg Result += "\t }\n};\n";
51457330f729Sjoerg }
51467330f729Sjoerg
51477330f729Sjoerg // Output class methods declared in this protocol.
51487330f729Sjoerg unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
51497330f729Sjoerg PDecl->classmeth_end());
51507330f729Sjoerg if (NumMethods > 0) {
51517330f729Sjoerg /* struct _objc_protocol_method_list {
51527330f729Sjoerg int protocol_method_count;
51537330f729Sjoerg struct protocol_methods protocols[];
51547330f729Sjoerg }
51557330f729Sjoerg */
51567330f729Sjoerg Result += "\nstatic struct {\n";
51577330f729Sjoerg Result += "\tint protocol_method_count;\n";
51587330f729Sjoerg Result += "\tstruct _protocol_methods protocol_methods[";
51597330f729Sjoerg Result += utostr(NumMethods);
51607330f729Sjoerg Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
51617330f729Sjoerg Result += PDecl->getNameAsString();
51627330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
51637330f729Sjoerg "{\n\t";
51647330f729Sjoerg Result += utostr(NumMethods);
51657330f729Sjoerg Result += "\n";
51667330f729Sjoerg
51677330f729Sjoerg // Output instance methods declared in this protocol.
51687330f729Sjoerg for (ObjCProtocolDecl::classmeth_iterator
51697330f729Sjoerg I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
51707330f729Sjoerg I != E; ++I) {
51717330f729Sjoerg if (I == PDecl->classmeth_begin())
51727330f729Sjoerg Result += "\t ,{{(struct objc_selector *)\"";
51737330f729Sjoerg else
51747330f729Sjoerg Result += "\t ,{(struct objc_selector *)\"";
51757330f729Sjoerg Result += (*I)->getSelector().getAsString();
51767330f729Sjoerg std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
51777330f729Sjoerg Result += "\", \"";
51787330f729Sjoerg Result += MethodTypeString;
51797330f729Sjoerg Result += "\"}\n";
51807330f729Sjoerg }
51817330f729Sjoerg Result += "\t }\n};\n";
51827330f729Sjoerg }
51837330f729Sjoerg
51847330f729Sjoerg // Output:
51857330f729Sjoerg /* struct _objc_protocol {
51867330f729Sjoerg // Objective-C 1.0 extensions
51877330f729Sjoerg struct _objc_protocol_extension *isa;
51887330f729Sjoerg char *protocol_name;
51897330f729Sjoerg struct _objc_protocol **protocol_list;
51907330f729Sjoerg struct _objc_protocol_method_list *instance_methods;
51917330f729Sjoerg struct _objc_protocol_method_list *class_methods;
51927330f729Sjoerg };
51937330f729Sjoerg */
51947330f729Sjoerg static bool objc_protocol = false;
51957330f729Sjoerg if (!objc_protocol) {
51967330f729Sjoerg Result += "\nstruct _objc_protocol {\n";
51977330f729Sjoerg Result += "\tstruct _objc_protocol_extension *isa;\n";
51987330f729Sjoerg Result += "\tchar *protocol_name;\n";
51997330f729Sjoerg Result += "\tstruct _objc_protocol **protocol_list;\n";
52007330f729Sjoerg Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
52017330f729Sjoerg Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
52027330f729Sjoerg Result += "};\n";
52037330f729Sjoerg
52047330f729Sjoerg objc_protocol = true;
52057330f729Sjoerg }
52067330f729Sjoerg
52077330f729Sjoerg Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
52087330f729Sjoerg Result += PDecl->getNameAsString();
52097330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
52107330f729Sjoerg "{\n\t0, \"";
52117330f729Sjoerg Result += PDecl->getNameAsString();
52127330f729Sjoerg Result += "\", 0, ";
52137330f729Sjoerg if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
52147330f729Sjoerg Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
52157330f729Sjoerg Result += PDecl->getNameAsString();
52167330f729Sjoerg Result += ", ";
52177330f729Sjoerg }
52187330f729Sjoerg else
52197330f729Sjoerg Result += "0, ";
52207330f729Sjoerg if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
52217330f729Sjoerg Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
52227330f729Sjoerg Result += PDecl->getNameAsString();
52237330f729Sjoerg Result += "\n";
52247330f729Sjoerg }
52257330f729Sjoerg else
52267330f729Sjoerg Result += "0\n";
52277330f729Sjoerg Result += "};\n";
52287330f729Sjoerg
52297330f729Sjoerg // Mark this protocol as having been generated.
52307330f729Sjoerg if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
52317330f729Sjoerg llvm_unreachable("protocol already synthesized");
52327330f729Sjoerg }
52337330f729Sjoerg
RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> & Protocols,StringRef prefix,StringRef ClassName,std::string & Result)52347330f729Sjoerg void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
52357330f729Sjoerg const ObjCList<ObjCProtocolDecl> &Protocols,
52367330f729Sjoerg StringRef prefix, StringRef ClassName,
52377330f729Sjoerg std::string &Result) {
52387330f729Sjoerg if (Protocols.empty()) return;
52397330f729Sjoerg
52407330f729Sjoerg for (unsigned i = 0; i != Protocols.size(); i++)
52417330f729Sjoerg RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
52427330f729Sjoerg
52437330f729Sjoerg // Output the top lovel protocol meta-data for the class.
52447330f729Sjoerg /* struct _objc_protocol_list {
52457330f729Sjoerg struct _objc_protocol_list *next;
52467330f729Sjoerg int protocol_count;
52477330f729Sjoerg struct _objc_protocol *class_protocols[];
52487330f729Sjoerg }
52497330f729Sjoerg */
52507330f729Sjoerg Result += "\nstatic struct {\n";
52517330f729Sjoerg Result += "\tstruct _objc_protocol_list *next;\n";
52527330f729Sjoerg Result += "\tint protocol_count;\n";
52537330f729Sjoerg Result += "\tstruct _objc_protocol *class_protocols[";
52547330f729Sjoerg Result += utostr(Protocols.size());
52557330f729Sjoerg Result += "];\n} _OBJC_";
52567330f729Sjoerg Result += prefix;
52577330f729Sjoerg Result += "_PROTOCOLS_";
52587330f729Sjoerg Result += ClassName;
52597330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
52607330f729Sjoerg "{\n\t0, ";
52617330f729Sjoerg Result += utostr(Protocols.size());
52627330f729Sjoerg Result += "\n";
52637330f729Sjoerg
52647330f729Sjoerg Result += "\t,{&_OBJC_PROTOCOL_";
52657330f729Sjoerg Result += Protocols[0]->getNameAsString();
52667330f729Sjoerg Result += " \n";
52677330f729Sjoerg
52687330f729Sjoerg for (unsigned i = 1; i != Protocols.size(); i++) {
52697330f729Sjoerg Result += "\t ,&_OBJC_PROTOCOL_";
52707330f729Sjoerg Result += Protocols[i]->getNameAsString();
52717330f729Sjoerg Result += "\n";
52727330f729Sjoerg }
52737330f729Sjoerg Result += "\t }\n};\n";
52747330f729Sjoerg }
52757330f729Sjoerg
RewriteObjCClassMetaData(ObjCImplementationDecl * IDecl,std::string & Result)52767330f729Sjoerg void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
52777330f729Sjoerg std::string &Result) {
52787330f729Sjoerg ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
52797330f729Sjoerg
52807330f729Sjoerg // Explicitly declared @interface's are already synthesized.
52817330f729Sjoerg if (CDecl->isImplicitInterfaceDecl()) {
52827330f729Sjoerg // FIXME: Implementation of a class with no @interface (legacy) does not
52837330f729Sjoerg // produce correct synthesis as yet.
52847330f729Sjoerg RewriteObjCInternalStruct(CDecl, Result);
52857330f729Sjoerg }
52867330f729Sjoerg
52877330f729Sjoerg // Build _objc_ivar_list metadata for classes ivars if needed
5288*e038c9c4Sjoerg unsigned NumIvars =
5289*e038c9c4Sjoerg !IDecl->ivar_empty() ? IDecl->ivar_size() : CDecl->ivar_size();
52907330f729Sjoerg if (NumIvars > 0) {
52917330f729Sjoerg static bool objc_ivar = false;
52927330f729Sjoerg if (!objc_ivar) {
52937330f729Sjoerg /* struct _objc_ivar {
52947330f729Sjoerg char *ivar_name;
52957330f729Sjoerg char *ivar_type;
52967330f729Sjoerg int ivar_offset;
52977330f729Sjoerg };
52987330f729Sjoerg */
52997330f729Sjoerg Result += "\nstruct _objc_ivar {\n";
53007330f729Sjoerg Result += "\tchar *ivar_name;\n";
53017330f729Sjoerg Result += "\tchar *ivar_type;\n";
53027330f729Sjoerg Result += "\tint ivar_offset;\n";
53037330f729Sjoerg Result += "};\n";
53047330f729Sjoerg
53057330f729Sjoerg objc_ivar = true;
53067330f729Sjoerg }
53077330f729Sjoerg
53087330f729Sjoerg /* struct {
53097330f729Sjoerg int ivar_count;
53107330f729Sjoerg struct _objc_ivar ivar_list[nIvars];
53117330f729Sjoerg };
53127330f729Sjoerg */
53137330f729Sjoerg Result += "\nstatic struct {\n";
53147330f729Sjoerg Result += "\tint ivar_count;\n";
53157330f729Sjoerg Result += "\tstruct _objc_ivar ivar_list[";
53167330f729Sjoerg Result += utostr(NumIvars);
53177330f729Sjoerg Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
53187330f729Sjoerg Result += IDecl->getNameAsString();
53197330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
53207330f729Sjoerg "{\n\t";
53217330f729Sjoerg Result += utostr(NumIvars);
53227330f729Sjoerg Result += "\n";
53237330f729Sjoerg
53247330f729Sjoerg ObjCInterfaceDecl::ivar_iterator IVI, IVE;
53257330f729Sjoerg SmallVector<ObjCIvarDecl *, 8> IVars;
53267330f729Sjoerg if (!IDecl->ivar_empty()) {
53277330f729Sjoerg for (auto *IV : IDecl->ivars())
53287330f729Sjoerg IVars.push_back(IV);
53297330f729Sjoerg IVI = IDecl->ivar_begin();
53307330f729Sjoerg IVE = IDecl->ivar_end();
53317330f729Sjoerg } else {
53327330f729Sjoerg IVI = CDecl->ivar_begin();
53337330f729Sjoerg IVE = CDecl->ivar_end();
53347330f729Sjoerg }
53357330f729Sjoerg Result += "\t,{{\"";
53367330f729Sjoerg Result += IVI->getNameAsString();
53377330f729Sjoerg Result += "\", \"";
53387330f729Sjoerg std::string TmpString, StrEncoding;
53397330f729Sjoerg Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
53407330f729Sjoerg QuoteDoublequotes(TmpString, StrEncoding);
53417330f729Sjoerg Result += StrEncoding;
53427330f729Sjoerg Result += "\", ";
53437330f729Sjoerg RewriteIvarOffsetComputation(*IVI, Result);
53447330f729Sjoerg Result += "}\n";
53457330f729Sjoerg for (++IVI; IVI != IVE; ++IVI) {
53467330f729Sjoerg Result += "\t ,{\"";
53477330f729Sjoerg Result += IVI->getNameAsString();
53487330f729Sjoerg Result += "\", \"";
53497330f729Sjoerg std::string TmpString, StrEncoding;
53507330f729Sjoerg Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
53517330f729Sjoerg QuoteDoublequotes(TmpString, StrEncoding);
53527330f729Sjoerg Result += StrEncoding;
53537330f729Sjoerg Result += "\", ";
53547330f729Sjoerg RewriteIvarOffsetComputation(*IVI, Result);
53557330f729Sjoerg Result += "}\n";
53567330f729Sjoerg }
53577330f729Sjoerg
53587330f729Sjoerg Result += "\t }\n};\n";
53597330f729Sjoerg }
53607330f729Sjoerg
53617330f729Sjoerg // Build _objc_method_list for class's instance methods if needed
53627330f729Sjoerg SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
53637330f729Sjoerg
53647330f729Sjoerg // If any of our property implementations have associated getters or
53657330f729Sjoerg // setters, produce metadata for them as well.
53667330f729Sjoerg for (const auto *Prop : IDecl->property_impls()) {
53677330f729Sjoerg if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
53687330f729Sjoerg continue;
53697330f729Sjoerg if (!Prop->getPropertyIvarDecl())
53707330f729Sjoerg continue;
53717330f729Sjoerg ObjCPropertyDecl *PD = Prop->getPropertyDecl();
53727330f729Sjoerg if (!PD)
53737330f729Sjoerg continue;
5374*e038c9c4Sjoerg if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
53757330f729Sjoerg if (!Getter->isDefined())
53767330f729Sjoerg InstanceMethods.push_back(Getter);
53777330f729Sjoerg if (PD->isReadOnly())
53787330f729Sjoerg continue;
5379*e038c9c4Sjoerg if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
53807330f729Sjoerg if (!Setter->isDefined())
53817330f729Sjoerg InstanceMethods.push_back(Setter);
53827330f729Sjoerg }
53837330f729Sjoerg RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
53847330f729Sjoerg true, "", IDecl->getName(), Result);
53857330f729Sjoerg
53867330f729Sjoerg // Build _objc_method_list for class's class methods if needed
53877330f729Sjoerg RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
53887330f729Sjoerg false, "", IDecl->getName(), Result);
53897330f729Sjoerg
53907330f729Sjoerg // Protocols referenced in class declaration?
53917330f729Sjoerg RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
53927330f729Sjoerg "CLASS", CDecl->getName(), Result);
53937330f729Sjoerg
53947330f729Sjoerg // Declaration of class/meta-class metadata
53957330f729Sjoerg /* struct _objc_class {
53967330f729Sjoerg struct _objc_class *isa; // or const char *root_class_name when metadata
53977330f729Sjoerg const char *super_class_name;
53987330f729Sjoerg char *name;
53997330f729Sjoerg long version;
54007330f729Sjoerg long info;
54017330f729Sjoerg long instance_size;
54027330f729Sjoerg struct _objc_ivar_list *ivars;
54037330f729Sjoerg struct _objc_method_list *methods;
54047330f729Sjoerg struct objc_cache *cache;
54057330f729Sjoerg struct objc_protocol_list *protocols;
54067330f729Sjoerg const char *ivar_layout;
54077330f729Sjoerg struct _objc_class_ext *ext;
54087330f729Sjoerg };
54097330f729Sjoerg */
54107330f729Sjoerg static bool objc_class = false;
54117330f729Sjoerg if (!objc_class) {
54127330f729Sjoerg Result += "\nstruct _objc_class {\n";
54137330f729Sjoerg Result += "\tstruct _objc_class *isa;\n";
54147330f729Sjoerg Result += "\tconst char *super_class_name;\n";
54157330f729Sjoerg Result += "\tchar *name;\n";
54167330f729Sjoerg Result += "\tlong version;\n";
54177330f729Sjoerg Result += "\tlong info;\n";
54187330f729Sjoerg Result += "\tlong instance_size;\n";
54197330f729Sjoerg Result += "\tstruct _objc_ivar_list *ivars;\n";
54207330f729Sjoerg Result += "\tstruct _objc_method_list *methods;\n";
54217330f729Sjoerg Result += "\tstruct objc_cache *cache;\n";
54227330f729Sjoerg Result += "\tstruct _objc_protocol_list *protocols;\n";
54237330f729Sjoerg Result += "\tconst char *ivar_layout;\n";
54247330f729Sjoerg Result += "\tstruct _objc_class_ext *ext;\n";
54257330f729Sjoerg Result += "};\n";
54267330f729Sjoerg objc_class = true;
54277330f729Sjoerg }
54287330f729Sjoerg
54297330f729Sjoerg // Meta-class metadata generation.
54307330f729Sjoerg ObjCInterfaceDecl *RootClass = nullptr;
54317330f729Sjoerg ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
54327330f729Sjoerg while (SuperClass) {
54337330f729Sjoerg RootClass = SuperClass;
54347330f729Sjoerg SuperClass = SuperClass->getSuperClass();
54357330f729Sjoerg }
54367330f729Sjoerg SuperClass = CDecl->getSuperClass();
54377330f729Sjoerg
54387330f729Sjoerg Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
54397330f729Sjoerg Result += CDecl->getNameAsString();
54407330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
54417330f729Sjoerg "{\n\t(struct _objc_class *)\"";
54427330f729Sjoerg Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
54437330f729Sjoerg Result += "\"";
54447330f729Sjoerg
54457330f729Sjoerg if (SuperClass) {
54467330f729Sjoerg Result += ", \"";
54477330f729Sjoerg Result += SuperClass->getNameAsString();
54487330f729Sjoerg Result += "\", \"";
54497330f729Sjoerg Result += CDecl->getNameAsString();
54507330f729Sjoerg Result += "\"";
54517330f729Sjoerg }
54527330f729Sjoerg else {
54537330f729Sjoerg Result += ", 0, \"";
54547330f729Sjoerg Result += CDecl->getNameAsString();
54557330f729Sjoerg Result += "\"";
54567330f729Sjoerg }
54577330f729Sjoerg // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
54587330f729Sjoerg // 'info' field is initialized to CLS_META(2) for metaclass
54597330f729Sjoerg Result += ", 0,2, sizeof(struct _objc_class), 0";
54607330f729Sjoerg if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
54617330f729Sjoerg Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
54627330f729Sjoerg Result += IDecl->getNameAsString();
54637330f729Sjoerg Result += "\n";
54647330f729Sjoerg }
54657330f729Sjoerg else
54667330f729Sjoerg Result += ", 0\n";
54677330f729Sjoerg if (CDecl->protocol_begin() != CDecl->protocol_end()) {
54687330f729Sjoerg Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
54697330f729Sjoerg Result += CDecl->getNameAsString();
54707330f729Sjoerg Result += ",0,0\n";
54717330f729Sjoerg }
54727330f729Sjoerg else
54737330f729Sjoerg Result += "\t,0,0,0,0\n";
54747330f729Sjoerg Result += "};\n";
54757330f729Sjoerg
54767330f729Sjoerg // class metadata generation.
54777330f729Sjoerg Result += "\nstatic struct _objc_class _OBJC_CLASS_";
54787330f729Sjoerg Result += CDecl->getNameAsString();
54797330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
54807330f729Sjoerg "{\n\t&_OBJC_METACLASS_";
54817330f729Sjoerg Result += CDecl->getNameAsString();
54827330f729Sjoerg if (SuperClass) {
54837330f729Sjoerg Result += ", \"";
54847330f729Sjoerg Result += SuperClass->getNameAsString();
54857330f729Sjoerg Result += "\", \"";
54867330f729Sjoerg Result += CDecl->getNameAsString();
54877330f729Sjoerg Result += "\"";
54887330f729Sjoerg }
54897330f729Sjoerg else {
54907330f729Sjoerg Result += ", 0, \"";
54917330f729Sjoerg Result += CDecl->getNameAsString();
54927330f729Sjoerg Result += "\"";
54937330f729Sjoerg }
54947330f729Sjoerg // 'info' field is initialized to CLS_CLASS(1) for class
54957330f729Sjoerg Result += ", 0,1";
54967330f729Sjoerg if (!ObjCSynthesizedStructs.count(CDecl))
54977330f729Sjoerg Result += ",0";
54987330f729Sjoerg else {
54997330f729Sjoerg // class has size. Must synthesize its size.
55007330f729Sjoerg Result += ",sizeof(struct ";
55017330f729Sjoerg Result += CDecl->getNameAsString();
55027330f729Sjoerg if (LangOpts.MicrosoftExt)
55037330f729Sjoerg Result += "_IMPL";
55047330f729Sjoerg Result += ")";
55057330f729Sjoerg }
55067330f729Sjoerg if (NumIvars > 0) {
55077330f729Sjoerg Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
55087330f729Sjoerg Result += CDecl->getNameAsString();
55097330f729Sjoerg Result += "\n\t";
55107330f729Sjoerg }
55117330f729Sjoerg else
55127330f729Sjoerg Result += ",0";
55137330f729Sjoerg if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
55147330f729Sjoerg Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
55157330f729Sjoerg Result += CDecl->getNameAsString();
55167330f729Sjoerg Result += ", 0\n\t";
55177330f729Sjoerg }
55187330f729Sjoerg else
55197330f729Sjoerg Result += ",0,0";
55207330f729Sjoerg if (CDecl->protocol_begin() != CDecl->protocol_end()) {
55217330f729Sjoerg Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
55227330f729Sjoerg Result += CDecl->getNameAsString();
55237330f729Sjoerg Result += ", 0,0\n";
55247330f729Sjoerg }
55257330f729Sjoerg else
55267330f729Sjoerg Result += ",0,0,0\n";
55277330f729Sjoerg Result += "};\n";
55287330f729Sjoerg }
55297330f729Sjoerg
RewriteMetaDataIntoBuffer(std::string & Result)55307330f729Sjoerg void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
55317330f729Sjoerg int ClsDefCount = ClassImplementation.size();
55327330f729Sjoerg int CatDefCount = CategoryImplementation.size();
55337330f729Sjoerg
55347330f729Sjoerg // For each implemented class, write out all its meta data.
55357330f729Sjoerg for (int i = 0; i < ClsDefCount; i++)
55367330f729Sjoerg RewriteObjCClassMetaData(ClassImplementation[i], Result);
55377330f729Sjoerg
55387330f729Sjoerg // For each implemented category, write out all its meta data.
55397330f729Sjoerg for (int i = 0; i < CatDefCount; i++)
55407330f729Sjoerg RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
55417330f729Sjoerg
55427330f729Sjoerg // Write objc_symtab metadata
55437330f729Sjoerg /*
55447330f729Sjoerg struct _objc_symtab
55457330f729Sjoerg {
55467330f729Sjoerg long sel_ref_cnt;
55477330f729Sjoerg SEL *refs;
55487330f729Sjoerg short cls_def_cnt;
55497330f729Sjoerg short cat_def_cnt;
55507330f729Sjoerg void *defs[cls_def_cnt + cat_def_cnt];
55517330f729Sjoerg };
55527330f729Sjoerg */
55537330f729Sjoerg
55547330f729Sjoerg Result += "\nstruct _objc_symtab {\n";
55557330f729Sjoerg Result += "\tlong sel_ref_cnt;\n";
55567330f729Sjoerg Result += "\tSEL *refs;\n";
55577330f729Sjoerg Result += "\tshort cls_def_cnt;\n";
55587330f729Sjoerg Result += "\tshort cat_def_cnt;\n";
55597330f729Sjoerg Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
55607330f729Sjoerg Result += "};\n\n";
55617330f729Sjoerg
55627330f729Sjoerg Result += "static struct _objc_symtab "
55637330f729Sjoerg "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
55647330f729Sjoerg Result += "\t0, 0, " + utostr(ClsDefCount)
55657330f729Sjoerg + ", " + utostr(CatDefCount) + "\n";
55667330f729Sjoerg for (int i = 0; i < ClsDefCount; i++) {
55677330f729Sjoerg Result += "\t,&_OBJC_CLASS_";
55687330f729Sjoerg Result += ClassImplementation[i]->getNameAsString();
55697330f729Sjoerg Result += "\n";
55707330f729Sjoerg }
55717330f729Sjoerg
55727330f729Sjoerg for (int i = 0; i < CatDefCount; i++) {
55737330f729Sjoerg Result += "\t,&_OBJC_CATEGORY_";
55747330f729Sjoerg Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
55757330f729Sjoerg Result += "_";
55767330f729Sjoerg Result += CategoryImplementation[i]->getNameAsString();
55777330f729Sjoerg Result += "\n";
55787330f729Sjoerg }
55797330f729Sjoerg
55807330f729Sjoerg Result += "};\n\n";
55817330f729Sjoerg
55827330f729Sjoerg // Write objc_module metadata
55837330f729Sjoerg
55847330f729Sjoerg /*
55857330f729Sjoerg struct _objc_module {
55867330f729Sjoerg long version;
55877330f729Sjoerg long size;
55887330f729Sjoerg const char *name;
55897330f729Sjoerg struct _objc_symtab *symtab;
55907330f729Sjoerg }
55917330f729Sjoerg */
55927330f729Sjoerg
55937330f729Sjoerg Result += "\nstruct _objc_module {\n";
55947330f729Sjoerg Result += "\tlong version;\n";
55957330f729Sjoerg Result += "\tlong size;\n";
55967330f729Sjoerg Result += "\tconst char *name;\n";
55977330f729Sjoerg Result += "\tstruct _objc_symtab *symtab;\n";
55987330f729Sjoerg Result += "};\n\n";
55997330f729Sjoerg Result += "static struct _objc_module "
56007330f729Sjoerg "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
56017330f729Sjoerg Result += "\t" + utostr(OBJC_ABI_VERSION) +
56027330f729Sjoerg ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
56037330f729Sjoerg Result += "};\n\n";
56047330f729Sjoerg
56057330f729Sjoerg if (LangOpts.MicrosoftExt) {
56067330f729Sjoerg if (ProtocolExprDecls.size()) {
56077330f729Sjoerg Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
56087330f729Sjoerg Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
56097330f729Sjoerg for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
56107330f729Sjoerg Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
56117330f729Sjoerg Result += ProtDecl->getNameAsString();
56127330f729Sjoerg Result += " = &_OBJC_PROTOCOL_";
56137330f729Sjoerg Result += ProtDecl->getNameAsString();
56147330f729Sjoerg Result += ";\n";
56157330f729Sjoerg }
56167330f729Sjoerg Result += "#pragma data_seg(pop)\n\n";
56177330f729Sjoerg }
56187330f729Sjoerg Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
56197330f729Sjoerg Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
56207330f729Sjoerg Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
56217330f729Sjoerg Result += "&_OBJC_MODULES;\n";
56227330f729Sjoerg Result += "#pragma data_seg(pop)\n\n";
56237330f729Sjoerg }
56247330f729Sjoerg }
56257330f729Sjoerg
56267330f729Sjoerg /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
56277330f729Sjoerg /// implementation.
RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl * IDecl,std::string & Result)56287330f729Sjoerg void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
56297330f729Sjoerg std::string &Result) {
56307330f729Sjoerg ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
56317330f729Sjoerg // Find category declaration for this implementation.
56327330f729Sjoerg ObjCCategoryDecl *CDecl
56337330f729Sjoerg = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
56347330f729Sjoerg
56357330f729Sjoerg std::string FullCategoryName = ClassDecl->getNameAsString();
56367330f729Sjoerg FullCategoryName += '_';
56377330f729Sjoerg FullCategoryName += IDecl->getNameAsString();
56387330f729Sjoerg
56397330f729Sjoerg // Build _objc_method_list for class's instance methods if needed
56407330f729Sjoerg SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
56417330f729Sjoerg
56427330f729Sjoerg // If any of our property implementations have associated getters or
56437330f729Sjoerg // setters, produce metadata for them as well.
56447330f729Sjoerg for (const auto *Prop : IDecl->property_impls()) {
56457330f729Sjoerg if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
56467330f729Sjoerg continue;
56477330f729Sjoerg if (!Prop->getPropertyIvarDecl())
56487330f729Sjoerg continue;
56497330f729Sjoerg ObjCPropertyDecl *PD = Prop->getPropertyDecl();
56507330f729Sjoerg if (!PD)
56517330f729Sjoerg continue;
5652*e038c9c4Sjoerg if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
56537330f729Sjoerg InstanceMethods.push_back(Getter);
56547330f729Sjoerg if (PD->isReadOnly())
56557330f729Sjoerg continue;
5656*e038c9c4Sjoerg if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
56577330f729Sjoerg InstanceMethods.push_back(Setter);
56587330f729Sjoerg }
56597330f729Sjoerg RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
56607330f729Sjoerg true, "CATEGORY_", FullCategoryName, Result);
56617330f729Sjoerg
56627330f729Sjoerg // Build _objc_method_list for class's class methods if needed
56637330f729Sjoerg RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
56647330f729Sjoerg false, "CATEGORY_", FullCategoryName, Result);
56657330f729Sjoerg
56667330f729Sjoerg // Protocols referenced in class declaration?
56677330f729Sjoerg // Null CDecl is case of a category implementation with no category interface
56687330f729Sjoerg if (CDecl)
56697330f729Sjoerg RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
56707330f729Sjoerg FullCategoryName, Result);
56717330f729Sjoerg /* struct _objc_category {
56727330f729Sjoerg char *category_name;
56737330f729Sjoerg char *class_name;
56747330f729Sjoerg struct _objc_method_list *instance_methods;
56757330f729Sjoerg struct _objc_method_list *class_methods;
56767330f729Sjoerg struct _objc_protocol_list *protocols;
56777330f729Sjoerg // Objective-C 1.0 extensions
56787330f729Sjoerg uint32_t size; // sizeof (struct _objc_category)
56797330f729Sjoerg struct _objc_property_list *instance_properties; // category's own
56807330f729Sjoerg // @property decl.
56817330f729Sjoerg };
56827330f729Sjoerg */
56837330f729Sjoerg
56847330f729Sjoerg static bool objc_category = false;
56857330f729Sjoerg if (!objc_category) {
56867330f729Sjoerg Result += "\nstruct _objc_category {\n";
56877330f729Sjoerg Result += "\tchar *category_name;\n";
56887330f729Sjoerg Result += "\tchar *class_name;\n";
56897330f729Sjoerg Result += "\tstruct _objc_method_list *instance_methods;\n";
56907330f729Sjoerg Result += "\tstruct _objc_method_list *class_methods;\n";
56917330f729Sjoerg Result += "\tstruct _objc_protocol_list *protocols;\n";
56927330f729Sjoerg Result += "\tunsigned int size;\n";
56937330f729Sjoerg Result += "\tstruct _objc_property_list *instance_properties;\n";
56947330f729Sjoerg Result += "};\n";
56957330f729Sjoerg objc_category = true;
56967330f729Sjoerg }
56977330f729Sjoerg Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
56987330f729Sjoerg Result += FullCategoryName;
56997330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
57007330f729Sjoerg Result += IDecl->getNameAsString();
57017330f729Sjoerg Result += "\"\n\t, \"";
57027330f729Sjoerg Result += ClassDecl->getNameAsString();
57037330f729Sjoerg Result += "\"\n";
57047330f729Sjoerg
57057330f729Sjoerg if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
57067330f729Sjoerg Result += "\t, (struct _objc_method_list *)"
57077330f729Sjoerg "&_OBJC_CATEGORY_INSTANCE_METHODS_";
57087330f729Sjoerg Result += FullCategoryName;
57097330f729Sjoerg Result += "\n";
57107330f729Sjoerg }
57117330f729Sjoerg else
57127330f729Sjoerg Result += "\t, 0\n";
57137330f729Sjoerg if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
57147330f729Sjoerg Result += "\t, (struct _objc_method_list *)"
57157330f729Sjoerg "&_OBJC_CATEGORY_CLASS_METHODS_";
57167330f729Sjoerg Result += FullCategoryName;
57177330f729Sjoerg Result += "\n";
57187330f729Sjoerg }
57197330f729Sjoerg else
57207330f729Sjoerg Result += "\t, 0\n";
57217330f729Sjoerg
57227330f729Sjoerg if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
57237330f729Sjoerg Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
57247330f729Sjoerg Result += FullCategoryName;
57257330f729Sjoerg Result += "\n";
57267330f729Sjoerg }
57277330f729Sjoerg else
57287330f729Sjoerg Result += "\t, 0\n";
57297330f729Sjoerg Result += "\t, sizeof(struct _objc_category), 0\n};\n";
57307330f729Sjoerg }
57317330f729Sjoerg
57327330f729Sjoerg // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
57337330f729Sjoerg /// class methods.
57347330f729Sjoerg template<typename MethodIterator>
RewriteObjCMethodsMetaData(MethodIterator MethodBegin,MethodIterator MethodEnd,bool IsInstanceMethod,StringRef prefix,StringRef ClassName,std::string & Result)57357330f729Sjoerg void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
57367330f729Sjoerg MethodIterator MethodEnd,
57377330f729Sjoerg bool IsInstanceMethod,
57387330f729Sjoerg StringRef prefix,
57397330f729Sjoerg StringRef ClassName,
57407330f729Sjoerg std::string &Result) {
57417330f729Sjoerg if (MethodBegin == MethodEnd) return;
57427330f729Sjoerg
57437330f729Sjoerg if (!objc_impl_method) {
57447330f729Sjoerg /* struct _objc_method {
57457330f729Sjoerg SEL _cmd;
57467330f729Sjoerg char *method_types;
57477330f729Sjoerg void *_imp;
57487330f729Sjoerg }
57497330f729Sjoerg */
57507330f729Sjoerg Result += "\nstruct _objc_method {\n";
57517330f729Sjoerg Result += "\tSEL _cmd;\n";
57527330f729Sjoerg Result += "\tchar *method_types;\n";
57537330f729Sjoerg Result += "\tvoid *_imp;\n";
57547330f729Sjoerg Result += "};\n";
57557330f729Sjoerg
57567330f729Sjoerg objc_impl_method = true;
57577330f729Sjoerg }
57587330f729Sjoerg
57597330f729Sjoerg // Build _objc_method_list for class's methods if needed
57607330f729Sjoerg
57617330f729Sjoerg /* struct {
57627330f729Sjoerg struct _objc_method_list *next_method;
57637330f729Sjoerg int method_count;
57647330f729Sjoerg struct _objc_method method_list[];
57657330f729Sjoerg }
57667330f729Sjoerg */
57677330f729Sjoerg unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
57687330f729Sjoerg Result += "\nstatic struct {\n";
57697330f729Sjoerg Result += "\tstruct _objc_method_list *next_method;\n";
57707330f729Sjoerg Result += "\tint method_count;\n";
57717330f729Sjoerg Result += "\tstruct _objc_method method_list[";
57727330f729Sjoerg Result += utostr(NumMethods);
57737330f729Sjoerg Result += "];\n} _OBJC_";
57747330f729Sjoerg Result += prefix;
57757330f729Sjoerg Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
57767330f729Sjoerg Result += "_METHODS_";
57777330f729Sjoerg Result += ClassName;
57787330f729Sjoerg Result += " __attribute__ ((used, section (\"__OBJC, __";
57797330f729Sjoerg Result += IsInstanceMethod ? "inst" : "cls";
57807330f729Sjoerg Result += "_meth\")))= ";
57817330f729Sjoerg Result += "{\n\t0, " + utostr(NumMethods) + "\n";
57827330f729Sjoerg
57837330f729Sjoerg Result += "\t,{{(SEL)\"";
57847330f729Sjoerg Result += (*MethodBegin)->getSelector().getAsString();
57857330f729Sjoerg std::string MethodTypeString =
57867330f729Sjoerg Context->getObjCEncodingForMethodDecl(*MethodBegin);
57877330f729Sjoerg Result += "\", \"";
57887330f729Sjoerg Result += MethodTypeString;
57897330f729Sjoerg Result += "\", (void *)";
57907330f729Sjoerg Result += MethodInternalNames[*MethodBegin];
57917330f729Sjoerg Result += "}\n";
57927330f729Sjoerg for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
57937330f729Sjoerg Result += "\t ,{(SEL)\"";
57947330f729Sjoerg Result += (*MethodBegin)->getSelector().getAsString();
57957330f729Sjoerg std::string MethodTypeString =
57967330f729Sjoerg Context->getObjCEncodingForMethodDecl(*MethodBegin);
57977330f729Sjoerg Result += "\", \"";
57987330f729Sjoerg Result += MethodTypeString;
57997330f729Sjoerg Result += "\", (void *)";
58007330f729Sjoerg Result += MethodInternalNames[*MethodBegin];
58017330f729Sjoerg Result += "}\n";
58027330f729Sjoerg }
58037330f729Sjoerg Result += "\t }\n};\n";
58047330f729Sjoerg }
58057330f729Sjoerg
RewriteObjCIvarRefExpr(ObjCIvarRefExpr * IV)58067330f729Sjoerg Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
58077330f729Sjoerg SourceRange OldRange = IV->getSourceRange();
58087330f729Sjoerg Expr *BaseExpr = IV->getBase();
58097330f729Sjoerg
58107330f729Sjoerg // Rewrite the base, but without actually doing replaces.
58117330f729Sjoerg {
58127330f729Sjoerg DisableReplaceStmtScope S(*this);
58137330f729Sjoerg BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
58147330f729Sjoerg IV->setBase(BaseExpr);
58157330f729Sjoerg }
58167330f729Sjoerg
58177330f729Sjoerg ObjCIvarDecl *D = IV->getDecl();
58187330f729Sjoerg
58197330f729Sjoerg Expr *Replacement = IV;
58207330f729Sjoerg if (CurMethodDef) {
58217330f729Sjoerg if (BaseExpr->getType()->isObjCObjectPointerType()) {
58227330f729Sjoerg const ObjCInterfaceType *iFaceDecl =
58237330f729Sjoerg dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
58247330f729Sjoerg assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
58257330f729Sjoerg // lookup which class implements the instance variable.
58267330f729Sjoerg ObjCInterfaceDecl *clsDeclared = nullptr;
58277330f729Sjoerg iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
58287330f729Sjoerg clsDeclared);
58297330f729Sjoerg assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
58307330f729Sjoerg
58317330f729Sjoerg // Synthesize an explicit cast to gain access to the ivar.
5832*e038c9c4Sjoerg std::string RecName =
5833*e038c9c4Sjoerg std::string(clsDeclared->getIdentifier()->getName());
58347330f729Sjoerg RecName += "_IMPL";
58357330f729Sjoerg IdentifierInfo *II = &Context->Idents.get(RecName);
58367330f729Sjoerg RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
58377330f729Sjoerg SourceLocation(), SourceLocation(),
58387330f729Sjoerg II);
58397330f729Sjoerg assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
58407330f729Sjoerg QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
58417330f729Sjoerg CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
58427330f729Sjoerg CK_BitCast,
58437330f729Sjoerg IV->getBase());
58447330f729Sjoerg // Don't forget the parens to enforce the proper binding.
58457330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
58467330f729Sjoerg OldRange.getEnd(),
58477330f729Sjoerg castExpr);
58487330f729Sjoerg if (IV->isFreeIvar() &&
58497330f729Sjoerg declaresSameEntity(CurMethodDef->getClassInterface(),
58507330f729Sjoerg iFaceDecl->getDecl())) {
58517330f729Sjoerg MemberExpr *ME = MemberExpr::CreateImplicit(
58527330f729Sjoerg *Context, PE, true, D, D->getType(), VK_LValue, OK_Ordinary);
58537330f729Sjoerg Replacement = ME;
58547330f729Sjoerg } else {
58557330f729Sjoerg IV->setBase(PE);
58567330f729Sjoerg }
58577330f729Sjoerg }
58587330f729Sjoerg } else { // we are outside a method.
58597330f729Sjoerg assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
58607330f729Sjoerg
58617330f729Sjoerg // Explicit ivar refs need to have a cast inserted.
58627330f729Sjoerg // FIXME: consider sharing some of this code with the code above.
58637330f729Sjoerg if (BaseExpr->getType()->isObjCObjectPointerType()) {
58647330f729Sjoerg const ObjCInterfaceType *iFaceDecl =
58657330f729Sjoerg dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
58667330f729Sjoerg // lookup which class implements the instance variable.
58677330f729Sjoerg ObjCInterfaceDecl *clsDeclared = nullptr;
58687330f729Sjoerg iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
58697330f729Sjoerg clsDeclared);
58707330f729Sjoerg assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
58717330f729Sjoerg
58727330f729Sjoerg // Synthesize an explicit cast to gain access to the ivar.
5873*e038c9c4Sjoerg std::string RecName =
5874*e038c9c4Sjoerg std::string(clsDeclared->getIdentifier()->getName());
58757330f729Sjoerg RecName += "_IMPL";
58767330f729Sjoerg IdentifierInfo *II = &Context->Idents.get(RecName);
58777330f729Sjoerg RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
58787330f729Sjoerg SourceLocation(), SourceLocation(),
58797330f729Sjoerg II);
58807330f729Sjoerg assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
58817330f729Sjoerg QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
58827330f729Sjoerg CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
58837330f729Sjoerg CK_BitCast,
58847330f729Sjoerg IV->getBase());
58857330f729Sjoerg // Don't forget the parens to enforce the proper binding.
58867330f729Sjoerg ParenExpr *PE = new (Context) ParenExpr(
58877330f729Sjoerg IV->getBase()->getBeginLoc(), IV->getBase()->getEndLoc(), castExpr);
58887330f729Sjoerg // Cannot delete IV->getBase(), since PE points to it.
58897330f729Sjoerg // Replace the old base with the cast. This is important when doing
58907330f729Sjoerg // embedded rewrites. For example, [newInv->_container addObject:0].
58917330f729Sjoerg IV->setBase(PE);
58927330f729Sjoerg }
58937330f729Sjoerg }
58947330f729Sjoerg
58957330f729Sjoerg ReplaceStmtWithRange(IV, Replacement, OldRange);
58967330f729Sjoerg return Replacement;
58977330f729Sjoerg }
58987330f729Sjoerg
58997330f729Sjoerg #endif // CLANG_ENABLE_OBJC_REWRITER
5900