25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
32 #ifdef CLANG_ENABLE_OBJC_REWRITER
34 using namespace clang;
55 BLOCK_NEEDS_FREE = (1 << 24),
58 BLOCK_IS_GC = (1 << 27),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 static const int OBJC_ABI_VERSION = 7;
71 const char *MainFileStart, *MainFileEnd;
74 std::string InFileName;
80 unsigned RewriteFailedDiag;
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
89 unsigned TryFinallyContainsReturnDiag;
110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
151 bool DisableReplaceStmt;
152 class DisableReplaceStmtScope {
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt =
true;
161 ~DisableReplaceStmtScope() {
162 R.DisableReplaceStmt = SavedValue;
173 if (!Class->isThisDeclarationADefinition()) {
174 RewriteForwardClassDecl(D);
180 if (!Proto->isThisDeclarationADefinition()) {
181 RewriteForwardProtocolDecl(D);
186 HandleTopLevelSingleDecl(*
I);
190 void HandleTopLevelSingleDecl(
Decl *D);
191 void HandleDeclInMainFile(
Decl *D);
194 bool silenceMacroWarn);
198 void HandleTranslationUnit(
ASTContext &
C)
override;
200 void ReplaceStmt(
Stmt *Old,
Stmt *New) {
201 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
205 assert(Old !=
nullptr && New !=
nullptr &&
"Expected non-null Stmt's");
207 Stmt *ReplacingStmt = ReplacedNodes[Old];
211 if (DisableReplaceStmt)
215 int Size = Rewrite.getRangeSize(SrcRange);
218 << Old->getSourceRange();
223 llvm::raw_string_ostream
S(SStr);
225 const std::string &Str =
S.str();
228 if (!Rewrite.ReplaceText(SrcRange.
getBegin(), Size, Str)) {
229 ReplacedNodes[Old] = New;
232 if (SilenceRewriteMacroWarning)
235 << Old->getSourceRange();
239 bool InsertAfter =
true) {
241 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
242 SilenceRewriteMacroWarning)
251 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
252 SilenceRewriteMacroWarning)
260 void RewriteInclude();
262 void RewriteForwardClassDecl(
const SmallVectorImpl<Decl *> &DG);
264 const std::string &typedefString);
265 void RewriteImplementations();
270 void RewriteImplementationDecl(
Decl *Dcl);
273 void RewriteTypeIntoString(
QualType T, std::string &ResultStr,
275 void RewriteByRefString(std::string &ResultStr,
const std::string &
Name,
280 void RewriteForwardProtocolDecl(
const SmallVectorImpl<Decl *> &DG);
284 void RewriteBlockPointerType(std::string& Str,
QualType Type);
285 void RewriteBlockPointerTypeVariable(std::string& Str,
ValueDecl *VD);
287 void RewriteObjCQualifiedInterfaceTypes(
Decl *Dcl);
288 void RewriteTypeOfDecl(
VarDecl *VD);
289 void RewriteObjCQualifiedInterfaceTypes(
Expr *
E);
292 Stmt *RewriteFunctionBodyOrGlobalInitializer(
Stmt *
S);
300 void RewriteTryReturnStmts(
Stmt *
S);
301 void RewriteSyncReturnStmts(
Stmt *
S, std::string buf);
315 void RewriteBlockPointerDecl(
NamedDecl *VD);
316 void RewriteByRefVar(
VarDecl *VD);
324 void Initialize(
ASTContext &context)
override = 0;
327 virtual void RewriteMetaDataIntoBuffer(std::string &
Result) = 0;
343 virtual void RewriteIvarOffsetComputation(
ObjCIvarDecl *ivar,
349 ArrayRef<Expr *> Args,
355 SmallVectorImpl<QualType> &ArgTypes,
356 SmallVectorImpl<Expr*> &MsgExprs,
362 void SynthCountByEnumWithState(std::string &buf);
363 void SynthMsgSendFunctionDecl();
364 void SynthMsgSendSuperFunctionDecl();
365 void SynthMsgSendStretFunctionDecl();
366 void SynthMsgSendFpretFunctionDecl();
367 void SynthMsgSendSuperStretFunctionDecl();
368 void SynthGetClassFunctionDecl();
369 void SynthGetMetaClassFunctionDecl();
370 void SynthGetSuperClassFunctionDecl();
371 void SynthSelGetUidFunctionDecl();
372 void SynthSuperConstructorFunctionDecl();
374 std::string SynthesizeByrefCopyDestroyHelper(
VarDecl *VD,
int flag);
375 std::string SynthesizeBlockHelperFuncs(
BlockExpr *CE,
int i,
376 StringRef funcName, std::string Tag);
377 std::string SynthesizeBlockFunc(
BlockExpr *CE,
int i,
378 StringRef funcName, std::string Tag);
379 std::string SynthesizeBlockImpl(
BlockExpr *CE,
380 std::string Tag, std::string Desc);
381 std::string SynthesizeBlockDescriptor(std::string DescTag,
383 int i, StringRef funcName,
388 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
394 void WarnAboutReturnGotoStmts(
Stmt *
S);
395 void HasReturnStmts(
Stmt *
S,
bool &hasReturns);
397 void InsertBlockLiteralsWithinFunction(
FunctionDecl *FD);
400 bool IsDeclStmtInForeachHeader(
DeclStmt *DS);
401 void CollectBlockDeclRefInfo(
BlockExpr *Exp);
402 void GetBlockDeclRefExprs(
Stmt *
S);
403 void GetInnerBlockDeclRefExprs(
Stmt *
S,
404 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
405 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
409 bool isTopLevelBlockPointerType(
QualType T) {
410 return isa<BlockPointerType>(T);
416 bool convertBlockPointerToFunctionPointer(
QualType &T) {
417 if (isTopLevelBlockPointerType(T)) {
425 bool needToScanForQualifiers(
QualType T);
427 QualType getConstantStringStructType();
429 bool BufferContainsPPDirectives(
const char *startBuf,
const char *endBuf);
431 void convertToUnqualifiedObjCType(
QualType &T) {
449 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
459 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
460 PT->getPointeeType()->isObjCQualifiedIdType())
465 bool PointerTypeTakesAnyBlockArguments(
QualType QT);
466 bool PointerTypeTakesAnyObjCQualifiedType(
QualType QT);
467 void GetExtentOfArgList(
const char *
Name,
const char *&LParen,
468 const char *&RParen);
470 void QuoteDoublequotes(std::string &From, std::string &To) {
471 for (
unsigned i = 0; i < From.length(); i++) {
480 ArrayRef<QualType> args,
481 bool variadic =
false) {
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
515 ~RewriteObjCFragileABI()
override {}
516 void Initialize(
ASTContext &context)
override;
519 template<
typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
527 StringRef prefix, StringRef ClassName,
528 std::string &
Result)
override;
529 void RewriteObjCProtocolListMetaData(
531 StringRef prefix, StringRef ClassName, std::string &
Result)
override;
533 std::string &
Result)
override;
534 void RewriteMetaDataIntoBuffer(std::string &
Result)
override;
536 std::string &
Result)
override;
540 std::string &
Result)
override;
545 void RewriteObjC::RewriteBlocksInFunctionProtoType(
QualType funcType,
548 = dyn_cast<FunctionProtoType>(funcType.
IgnoreParens())) {
549 for (
const auto &
I : fproto->param_types())
550 if (isTopLevelBlockPointerType(
I)) {
552 RewriteBlockPointerDecl(D);
560 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
564 static bool IsHeaderFile(
const std::string &
Filename) {
565 std::string::size_type DotPos = Filename.rfind(
'.');
567 if (DotPos == std::string::npos) {
572 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 return Ext ==
"h" || Ext ==
"hh" || Ext ==
"H";
580 bool silenceMacroWarn)
581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
583 IsHeader = IsHeaderFile(inFile);
585 "rewriting sub-expression within a macro (may not be correct)");
586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
592 std::unique_ptr<ASTConsumer>
595 bool SilenceRewriteMacroWarning) {
596 return llvm::make_unique<RewriteObjCFragileABI>(InFile, OS, Diags, LOpts,
597 SilenceRewriteMacroWarning);
600 void RewriteObjC::InitializeCommon(
ASTContext &context) {
604 MsgSendFunctionDecl =
nullptr;
605 MsgSendSuperFunctionDecl =
nullptr;
606 MsgSendStretFunctionDecl =
nullptr;
607 MsgSendSuperStretFunctionDecl =
nullptr;
608 MsgSendFpretFunctionDecl =
nullptr;
609 GetClassFunctionDecl =
nullptr;
610 GetMetaClassFunctionDecl =
nullptr;
611 GetSuperClassFunctionDecl =
nullptr;
612 SelGetUidFunctionDecl =
nullptr;
613 CFStringFunctionDecl =
nullptr;
614 ConstantStringClassReference =
nullptr;
615 NSStringRecord =
nullptr;
616 CurMethodDef =
nullptr;
617 CurFunctionDef =
nullptr;
618 CurFunctionDeclToDeclareForBlock =
nullptr;
619 GlobalVarDecl =
nullptr;
620 SuperStructDecl =
nullptr;
621 ProtocolTypeDecl =
nullptr;
622 ConstantStringDecl =
nullptr;
624 SuperConstructorFunctionDecl =
nullptr;
625 NumObjCStringLiterals = 0;
626 PropParentMap =
nullptr;
627 CurrentBody =
nullptr;
628 DisableReplaceStmt =
false;
629 objc_impl_method =
false;
633 const llvm::MemoryBuffer *MainBuf =
SM->
getBuffer(MainFileID);
634 MainFileStart = MainBuf->getBufferStart();
635 MainFileEnd = MainBuf->getBufferEnd();
644 void RewriteObjC::HandleTopLevelSingleDecl(
Decl *D) {
645 if (Diags.hasErrorOccurred())
659 RewriteFunctionDecl(FD);
660 }
else if (
VarDecl *FVD = dyn_cast<VarDecl>(D)) {
662 if (FVD->getName() ==
"_NSConstantStringClassReference") {
663 ConstantStringClassReference = FVD;
667 if (
ID->isThisDeclarationADefinition())
668 RewriteInterfaceDecl(
ID);
670 RewriteCategoryDecl(CD);
672 if (PD->isThisDeclarationADefinition())
673 RewriteProtocolDecl(PD);
677 DIEnd = LSD->decls_end();
680 if (!IFace->isThisDeclarationADefinition()) {
681 SmallVector<Decl *, 8> DG;
684 if (isa<ObjCInterfaceDecl>(*DI) &&
685 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686 StartLoc == (*DI)->getLocStart())
692 }
while (DI != DIEnd);
693 RewriteForwardClassDecl(DG);
699 if (!Proto->isThisDeclarationADefinition()) {
700 SmallVector<Decl *, 8> DG;
703 if (isa<ObjCProtocolDecl>(*DI) &&
704 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705 StartLoc == (*DI)->getLocStart())
711 }
while (DI != DIEnd);
712 RewriteForwardProtocolDecl(DG);
717 HandleTopLevelSingleDecl(*DI);
723 return HandleDeclInMainFile(D);
730 void RewriteObjC::RewriteInclude() {
733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
735 size_t ImportLen = strlen(
"import");
738 for (
const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739 if (*BufPtr ==
'#') {
740 if (++BufPtr == MainBufEnd)
742 while (*BufPtr ==
' ' || *BufPtr ==
'\t')
743 if (++BufPtr == MainBufEnd)
745 if (!strncmp(BufPtr,
"import", ImportLen)) {
749 ReplaceText(ImportLoc, ImportLen,
"include");
756 static std::string getIvarAccessString(
ObjCIvarDecl *OID) {
761 S +=
"_IMPL *)self)->";
769 static bool objcGetPropertyDefined =
false;
770 static bool objcSetPropertyDefined =
false;
772 InsertText(startLoc,
"// ");
774 assert((*startBuf ==
'@') &&
"bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf,
';');
776 assert((*semiBuf ==
';') &&
"@synthesize: can't find ';'");
791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793 ObjCPropertyDecl::OBJC_PR_copy));
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined =
true;
798 Getr =
"\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
806 if (GenGetProperty) {
819 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
821 std::string ParamStr =
825 if (FT->isVariadic()) {
826 if (FT->getNumParams())
835 Getr +=
"return (_TYPE)";
836 Getr +=
"objc_getProperty(self, _cmd, ";
837 RewriteIvarOffsetComputation(OID, Getr);
841 Getr +=
"return " + getIvarAccessString(OID);
843 InsertText(onePastSemiLoc, Getr);
851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined =
true;
856 Setr =
"\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
865 if (GenSetProperty) {
866 Setr +=
"objc_setProperty (self, _cmd, ";
867 RewriteIvarOffsetComputation(OID, Setr);
871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
881 Setr += getIvarAccessString(OID) +
" = ";
885 InsertText(onePastSemiLoc, Setr);
889 std::string &typedefString) {
890 typedefString +=
"#ifndef _REWRITER_typedef_";
892 typedefString +=
"\n";
893 typedefString +=
"#define _REWRITER_typedef_";
895 typedefString +=
"\n";
896 typedefString +=
"typedef struct objc_object ";
898 typedefString +=
";\n#endif\n";
902 const std::string &typedefString) {
905 const char *semiPtr = strchr(startBuf,
';');
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
910 void RewriteObjC::RewriteForwardClassDecl(
DeclGroupRef D) {
911 std::string typedefString;
914 if (I == D.
begin()) {
918 typedefString +=
"// @class ";
920 typedefString +=
";\n";
922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
928 void RewriteObjC::RewriteForwardClassDecl(
const SmallVectorImpl<Decl *> &D) {
929 std::string typedefString;
930 for (
unsigned i = 0; i < D.size(); i++) {
933 typedefString +=
"// @class ";
935 typedefString +=
";\n";
937 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
942 void RewriteObjC::RewriteMethodDeclaration(
ObjCMethodDecl *Method) {
952 InsertText(LocStart,
"#if 0\n");
953 ReplaceText(LocEnd, 1,
";\n#endif\n");
955 InsertText(LocStart,
"// ");
962 ReplaceText(Loc, 0,
"// ");
970 ReplaceText(LocStart, 0,
"// ");
975 RewriteMethodDeclaration(I);
977 RewriteMethodDeclaration(I);
981 strlen(
"@end"),
"/* @end */");
989 ReplaceText(LocStart, 0,
"// ");
992 RewriteMethodDeclaration(I);
994 RewriteMethodDeclaration(I);
1000 ReplaceText(LocEnd, strlen(
"@end"),
"/* @end */");
1005 for (
const char *
p = startBuf;
p < endBuf;
p++) {
1006 if (*
p ==
'@' && !strncmp(
p+1,
"optional", strlen(
"optional"))) {
1008 ReplaceText(OptionalLoc, strlen(
"@optional"),
"/* @optional */");
1011 else if (*
p ==
'@' && !strncmp(
p+1,
"required", strlen(
"required"))) {
1013 ReplaceText(OptionalLoc, strlen(
"@required"),
"/* @required */");
1019 void RewriteObjC::RewriteForwardProtocolDecl(
DeclGroupRef D) {
1022 llvm_unreachable(
"Invalid SourceLocation");
1024 ReplaceText(LocStart, 0,
"// ");
1028 RewriteObjC::RewriteForwardProtocolDecl(
const SmallVectorImpl<Decl *> &DG) {
1031 llvm_unreachable(
"Invalid SourceLocation");
1033 ReplaceText(LocStart, 0,
"// ");
1036 void RewriteObjC::RewriteTypeIntoString(
QualType T, std::string &ResultStr,
1061 std::string &ResultStr) {
1064 ResultStr +=
"\nstatic ";
1065 RewriteTypeIntoString(OMD->
getReturnType(), ResultStr, FPRetType);
1069 std::string NameStr;
1087 int len = selString.size();
1088 for (
int i = 0; i < len; i++)
1089 if (selString[i] ==
':')
1091 NameStr += selString;
1094 MethodInternalNames[OMD] = NameStr;
1095 ResultStr += NameStr;
1104 if (!LangOpts.MicrosoftExt) {
1105 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1106 ResultStr +=
"struct ";
1116 ResultStr +=
" self, ";
1118 ResultStr +=
" _cmd";
1121 for (
const auto *PDecl : OMD->
params()) {
1123 if (PDecl->getType()->isObjCQualifiedIdType()) {
1130 (void)convertBlockPointerToFunctionPointer(QT);
1136 ResultStr +=
", ...";
1145 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1146 if (i) ResultStr +=
", ";
1147 std::string ParamStr =
1149 ResultStr += ParamStr;
1151 if (FT->isVariadic()) {
1152 if (FT->getNumParams())
1162 void RewriteObjC::RewriteImplementationDecl(
Decl *OID) {
1166 InsertText(IMD ? IMD->
getLocStart() : CID->getLocStart(),
"// ");
1168 for (
auto *OMD : IMD ? IMD->
instance_methods() : CID->instance_methods()) {
1169 std::string ResultStr;
1176 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1179 for (
auto *OMD : IMD ? IMD->
class_methods() : CID->class_methods()) {
1180 std::string ResultStr;
1187 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1189 for (
auto *I : IMD ? IMD->
property_impls() : CID->property_impls())
1190 RewritePropertyImplDecl(I, IMD, CID);
1192 InsertText(IMD ? IMD->
getLocEnd() : CID->getLocEnd(),
"// ");
1196 std::string ResultStr;
1199 ResultStr =
"#ifndef _REWRITER_typedef_";
1202 ResultStr +=
"#define _REWRITER_typedef_";
1205 ResultStr +=
"typedef struct objc_object ";
1207 ResultStr +=
";\n#endif\n";
1211 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1216 RewriteMethodDeclaration(I);
1218 RewriteMethodDeclaration(I);
1226 SourceRange OldRange = PseudoOp->getSourceRange();
1238 DisableReplaceStmtScope
S(*
this);
1244 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1245 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1250 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1251 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1255 SmallVector<SourceLocation, 1> SelLocs;
1260 case ObjCMessageExpr::Class:
1273 case ObjCMessageExpr::Instance:
1286 case ObjCMessageExpr::SuperClass:
1287 case ObjCMessageExpr::SuperInstance:
1303 Stmt *Replacement = SynthMessageExpr(NewMsg);
1304 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1309 SourceRange OldRange = PseudoOp->getSourceRange();
1318 Expr *Base =
nullptr;
1320 DisableReplaceStmtScope
S(*
this);
1325 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1326 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1331 SmallVector<SourceLocation, 1> SelLocs;
1332 SmallVector<Expr*, 1> Args;
1336 case ObjCMessageExpr::Class:
1349 case ObjCMessageExpr::Instance:
1362 case ObjCMessageExpr::SuperClass:
1363 case ObjCMessageExpr::SuperInstance:
1379 Stmt *Replacement = SynthMessageExpr(NewMsg);
1380 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1393 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1394 buf +=
"((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1395 "id *, unsigned int))(void *)objc_msgSend)";
1397 buf +=
"((id)l_collection,\n\t\t";
1398 buf +=
"sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1400 buf +=
"&enumState, "
1401 "(id *)__rw_items, (unsigned int)16)";
1408 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1414 buf =
"goto __break_label_";
1415 buf += utostr(ObjCBcLabelNo.back());
1416 ReplaceText(startLoc, strlen(
"break"), buf);
1425 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1431 buf =
"goto __continue_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
1433 ReplaceText(startLoc, strlen(
"continue"), buf);
1472 assert(!Stmts.empty() &&
"ObjCForCollectionStmt - Statement stack empty");
1473 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1474 "ObjCForCollectionStmt Statement stack mismatch");
1475 assert(!ObjCBcLabelNo.empty() &&
1476 "ObjCForCollectionStmt - Label No stack empty");
1480 StringRef elementName;
1481 std::string elementTypeAsString;
1486 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1487 QualType ElementType = cast<ValueDecl>(D)->getType();
1488 if (ElementType->isObjCQualifiedIdType() ||
1489 ElementType->isObjCQualifiedInterfaceType())
1491 elementTypeAsString =
"id";
1494 buf += elementTypeAsString;
1507 elementTypeAsString =
"id";
1513 buf +=
"struct __objcFastEnumerationState enumState = { 0 };\n\t";
1515 buf +=
"id __rw_items[16];\n\t";
1517 buf +=
"id l_collection = (id)";
1519 const char *startCollectionBuf = startBuf;
1520 startCollectionBuf += 3;
1521 startCollectionBuf = strchr(startCollectionBuf,
'(');
1522 startCollectionBuf++;
1524 while (*startCollectionBuf !=
' ' ||
1525 *(startCollectionBuf+1) !=
'i' || *(startCollectionBuf+2) !=
'n' ||
1526 (*(startCollectionBuf+3) !=
' ' &&
1527 *(startCollectionBuf+3) !=
'[' && *(startCollectionBuf+3) !=
'('))
1528 startCollectionBuf++;
1529 startCollectionBuf += 3;
1532 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1550 buf +=
"unsigned long limit =\n\t\t";
1551 SynthCountByEnumWithState(buf);
1561 buf +=
"if (limit) {\n\t";
1562 buf +=
"unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1563 buf +=
"do {\n\t\t";
1564 buf +=
"unsigned long counter = 0;\n\t\t";
1565 buf +=
"do {\n\t\t\t";
1566 buf +=
"if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1567 buf +=
"objc_enumerationMutation(l_collection);\n\t\t\t";
1570 buf += elementTypeAsString;
1571 buf +=
")enumState.itemsPtr[counter++];";
1573 ReplaceText(lparenLoc, 1, buf);
1587 buf +=
"__continue_label_";
1588 buf += utostr(ObjCBcLabelNo.back());
1591 buf +=
"} while (counter < limit);\n\t";
1592 buf +=
"} while (limit = ";
1593 SynthCountByEnumWithState(buf);
1597 buf += elementTypeAsString;
1599 buf +=
"__break_label_";
1600 buf += utostr(ObjCBcLabelNo.back());
1603 buf +=
"else\n\t\t";
1606 buf += elementTypeAsString;
1612 if (isa<CompoundStmt>(S->
getBody())) {
1614 InsertText(endBodyLoc, buf);
1624 const char *semiBuf = strchr(stmtBuf,
';');
1625 assert(semiBuf &&
"Can't find ';'");
1627 InsertText(endBodyLoc, buf);
1630 ObjCBcLabelNo.pop_back();
1645 assert((*startBuf ==
'@') &&
"bogus @synchronized location");
1648 buf =
"objc_sync_enter((id)";
1649 const char *lparenBuf = startBuf;
1650 while (*lparenBuf !=
'(') lparenBuf++;
1651 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1657 while (*endBuf !=
')') endBuf--;
1661 buf +=
"/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1662 buf +=
"int buf[18/*32-bit i386*/];\n";
1663 buf +=
"char *pointers[4];} _stack;\n";
1664 buf +=
"id volatile _rethrow = 0;\n";
1665 buf +=
"objc_exception_try_enter(&_stack);\n";
1666 buf +=
"if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1667 ReplaceText(rparenLoc, 1, buf);
1671 assert((*startBuf ==
'}') &&
"bogus @synchronized block");
1673 buf =
"}\nelse {\n";
1674 buf +=
" _rethrow = objc_exception_extract(&_stack);\n";
1676 buf +=
"{ /* implicit finally clause */\n";
1677 buf +=
" if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1679 std::string syncBuf;
1680 syncBuf +=
" objc_sync_exit(";
1690 std::string syncExprBufS;
1691 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1692 assert(syncExpr !=
nullptr &&
"Expected non-null Expr");
1693 syncExpr->printPretty(syncExprBuf,
nullptr,
PrintingPolicy(LangOpts));
1694 syncBuf += syncExprBuf.str();
1698 buf +=
"\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1702 ReplaceText(lastCurlyLoc, 1, buf);
1704 bool hasReturns =
false;
1712 void RewriteObjC::WarnAboutReturnGotoStmts(
Stmt *S)
1715 for (
Stmt *SubStmt : S->children())
1717 WarnAboutReturnGotoStmts(SubStmt);
1719 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1721 TryFinallyContainsReturnDiag);
1726 void RewriteObjC::HasReturnStmts(
Stmt *S,
bool &hasReturns)
1729 for (
Stmt *SubStmt : S->children())
1731 HasReturnStmts(SubStmt, hasReturns);
1733 if (isa<ReturnStmt>(S))
1738 void RewriteObjC::RewriteTryReturnStmts(
Stmt *S) {
1740 for (
Stmt *SubStmt : S->children())
1742 RewriteTryReturnStmts(SubStmt);
1744 if (isa<ReturnStmt>(S)) {
1748 const char *semiBuf = strchr(startBuf,
';');
1749 assert((*semiBuf ==
';') &&
"RewriteTryReturnStmts: can't find ';'");
1753 buf =
"{ objc_exception_try_exit(&_stack); return";
1755 ReplaceText(startLoc, 6, buf);
1756 InsertText(onePastSemiLoc,
"}");
1761 void RewriteObjC::RewriteSyncReturnStmts(
Stmt *S, std::string syncExitBuf) {
1763 for (
Stmt *SubStmt : S->children())
1765 RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1767 if (isa<ReturnStmt>(S)) {
1771 const char *semiBuf = strchr(startBuf,
';');
1772 assert((*semiBuf ==
';') &&
"RewriteSyncReturnStmts: can't find ';'");
1776 buf =
"{ objc_exception_try_exit(&_stack);";
1780 ReplaceText(startLoc, 6, buf);
1781 InsertText(onePastSemiLoc,
"}");
1791 assert((*startBuf ==
'@') &&
"bogus @try location");
1795 buf =
"/* @try scope begin */ { struct _objc_exception_data {\n";
1796 buf +=
"int buf[18/*32-bit i386*/];\n";
1797 buf +=
"char *pointers[4];} _stack;\n";
1798 buf +=
"id volatile _rethrow = 0;\n";
1799 buf +=
"objc_exception_try_enter(&_stack);\n";
1800 buf +=
"if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1802 ReplaceText(startLoc, 4, buf);
1807 assert((*startBuf ==
'}') &&
"bogus @try block");
1812 buf =
" /* @catch begin */ else {\n";
1813 buf +=
" id _caught = objc_exception_extract(&_stack);\n";
1814 buf +=
" objc_exception_try_enter (&_stack);\n";
1815 buf +=
" if (_setjmp(_stack.buf))\n";
1816 buf +=
" _rethrow = objc_exception_extract(&_stack);\n";
1817 buf +=
" else { /* @catch continue */";
1819 InsertText(startLoc, buf);
1821 buf =
"}\nelse {\n";
1822 buf +=
" _rethrow = objc_exception_extract(&_stack);\n";
1824 ReplaceText(lastCurlyLoc, 1, buf);
1826 Stmt *lastCatchBody =
nullptr;
1838 assert((*startBuf ==
'@') &&
"bogus @catch location");
1840 const char *lParenLoc = strchr(startBuf,
'(');
1848 "bogus @catch paren location");
1849 assert((*bodyBuf ==
'{') &&
"bogus @catch body location");
1851 buf +=
"1) { id _tmp = _caught;";
1852 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1853 }
else if (catchDecl) {
1857 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1863 buf +=
"objc_exception_match((struct objc_class *)objc_getClass(\"";
1865 buf +=
"\"), (struct objc_object *)_caught)) { ";
1866 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1875 assert((*rParenBuf ==
')') &&
"bogus @catch paren location");
1876 assert((*bodyBuf ==
'{') &&
"bogus @catch body location");
1880 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
" = _caught;");
1882 llvm_unreachable(
"@catch rewrite bug");
1886 if (lastCatchBody) {
1889 "bogus @catch body location");
1893 buf =
"} /* last catch end */\n";
1895 buf +=
" _rethrow = _caught;\n";
1896 buf +=
" objc_exception_try_exit(&_stack);\n";
1897 buf +=
"} } /* @catch end */\n";
1900 InsertText(bodyLoc, buf);
1903 lastCurlyLoc = lastCatchBody->getLocEnd();
1906 startLoc = finalStmt->getLocStart();
1908 assert((*startBuf ==
'@') &&
"bogus @finally start");
1910 ReplaceText(startLoc, 8,
"/* @finally */");
1912 Stmt *body = finalStmt->getFinallyBody();
1916 "bogus @finally body location");
1918 "bogus @finally body location");
1921 InsertText(startLoc,
" if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1923 InsertText(endLoc,
" if (_rethrow) objc_exception_throw(_rethrow);\n");
1926 lastCurlyLoc = body->getLocEnd();
1931 buf =
"{ /* implicit finally clause */\n";
1932 buf +=
" if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1933 buf +=
" if (_rethrow) objc_exception_throw(_rethrow);\n";
1935 ReplaceText(lastCurlyLoc, 1, buf);
1940 bool hasReturns =
false;
1947 InsertText(lastCurlyLoc,
" } /* @try scope end */\n");
1959 assert((*startBuf ==
'@') &&
"bogus @throw location");
1964 buf =
"objc_exception_throw(";
1966 buf =
"objc_exception_throw(_caught";
1969 const char *wBuf = strchr(startBuf,
'w');
1970 assert((*wBuf ==
'w') &&
"@throw: can't find 'w'");
1971 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1973 const char *semiBuf = strchr(startBuf,
';');
1974 assert((*semiBuf ==
';') &&
"@throw: can't find ';'");
1976 ReplaceText(semiLoc, 1,
");");
1982 std::string StrEncoding;
1984 Expr *Replacement = getStringLiteral(StrEncoding);
1985 ReplaceStmt(Exp, Replacement);
1993 if (!SelGetUidFunctionDecl)
1994 SynthSelGetUidFunctionDecl();
1995 assert(SelGetUidFunctionDecl &&
"Can't find sel_registerName() decl");
1997 SmallVector<Expr*, 8> SelExprs;
1999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2001 ReplaceStmt(Exp, SelExp);
2007 RewriteObjC::SynthesizeCallToFunctionDecl(
FunctionDecl *FD,
2008 ArrayRef<Expr *> Args,
2032 static bool scanForProtocolRefs(
const char *startBuf,
const char *endBuf,
2033 const char *&startRef,
const char *&endRef) {
2034 while (startBuf < endBuf) {
2035 if (*startBuf ==
'<')
2036 startRef = startBuf;
2037 if (*startBuf ==
'>') {
2038 if (startRef && *startRef ==
'<') {
2049 static void scanToNextArgument(
const char *&argRef) {
2051 while (*argRef !=
')' && (*argRef !=
',' || angle > 0)) {
2054 else if (*argRef ==
'>')
2058 assert(angle == 0 &&
"scanToNextArgument - bad protocol type syntax");
2061 bool RewriteObjC::needToScanForQualifiers(
QualType T) {
2074 return needToScanForQualifiers(ElemTy);
2079 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(
Expr *E) {
2081 if (needToScanForQualifiers(Type)) {
2085 Loc = ECE->getLParenLoc();
2086 EndLoc = ECE->getRParenLoc();
2088 Loc = E->getLocStart();
2089 EndLoc = E->getLocEnd();
2097 const char *startRef =
nullptr, *endRef =
nullptr;
2098 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2103 InsertText(LessLoc,
"/*");
2104 InsertText(GreaterLoc,
"*/");
2109 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(
Decl *Dcl) {
2113 if (
VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2117 else if (
FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2122 assert(funcType &&
"missing function type");
2128 else if (
FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2135 if (needToScanForQualifiers(Type)) {
2139 const char *startBuf = endBuf;
2140 while (*startBuf !=
';' && *startBuf !=
'<' && startBuf != MainFileStart)
2142 const char *startRef =
nullptr, *endRef =
nullptr;
2143 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2148 InsertText(LessLoc,
"/*");
2149 InsertText(GreaterLoc,
"*/");
2156 const char *startFuncBuf = startBuf;
2161 const char *endBuf = startBuf;
2163 scanToNextArgument(endBuf);
2164 const char *startRef =
nullptr, *endRef =
nullptr;
2165 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2172 InsertText(LessLoc,
"/*");
2173 InsertText(GreaterLoc,
"*/");
2175 startBuf = ++endBuf;
2180 while (*startBuf && *startBuf !=
')' && *startBuf !=
',')
2187 void RewriteObjC::RewriteTypeOfDecl(
VarDecl *ND) {
2189 const Type* TypePtr = QT->
getAs<Type>();
2190 if (!isa<TypeOfExprType>(TypePtr))
2192 while (isa<TypeOfExprType>(TypePtr)) {
2193 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2195 TypePtr = QT->
getAs<Type>();
2204 TypeAsString +=
" " + Name +
" = ";
2208 startLoc = ECE->getLParenLoc();
2210 startLoc = E->getLocStart();
2213 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2219 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2224 void RewriteObjC::SynthSelGetUidFunctionDecl() {
2226 SmallVector<QualType, 16> ArgTys;
2233 SelGetUidIdent, getFuncType,
2237 void RewriteObjC::RewriteFunctionDecl(
FunctionDecl *FD) {
2240 FD->
getName() ==
"sel_registerName") {
2241 SelGetUidFunctionDecl = FD;
2244 RewriteObjCQualifiedInterfaceTypes(FD);
2247 void RewriteObjC::RewriteBlockPointerType(std::string& Str,
QualType Type) {
2249 const char *argPtr = TypeString.c_str();
2250 if (!strchr(argPtr,
'^')) {
2255 Str += (*argPtr ==
'^' ?
'*' : *argPtr);
2261 void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2265 const char *argPtr = TypeString.c_str();
2291 void RewriteObjC::RewriteBlockLiteralFunctionDecl(
FunctionDecl *FD) {
2297 QualType Type = proto->getReturnType();
2302 unsigned numArgs = proto->getNumParams();
2303 for (
unsigned i = 0; i < numArgs; i++) {
2304 QualType ArgType = proto->getParamType(i);
2305 RewriteBlockPointerType(FdStr, ArgType);
2310 InsertText(FunLocStart, FdStr);
2311 CurFunctionDeclToDeclareForBlock =
nullptr;
2315 void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2316 if (SuperConstructorFunctionDecl)
2319 SmallVector<QualType, 16> ArgTys;
2321 assert(!argT.
isNull() &&
"Can't find 'id' type");
2322 ArgTys.push_back(argT);
2323 ArgTys.push_back(argT);
2329 msgSendIdent, msgSendType,
2334 void RewriteObjC::SynthMsgSendFunctionDecl() {
2336 SmallVector<QualType, 16> ArgTys;
2338 assert(!argT.
isNull() &&
"Can't find 'id' type");
2339 ArgTys.push_back(argT);
2341 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2342 ArgTys.push_back(argT);
2348 msgSendIdent, msgSendType,
2353 void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2355 SmallVector<QualType, 16> ArgTys;
2360 assert(!argT.isNull() &&
"Can't build 'struct objc_super *' type");
2361 ArgTys.push_back(argT);
2363 assert(!argT.isNull() &&
"Can't find 'SEL' type");
2364 ArgTys.push_back(argT);
2370 msgSendIdent, msgSendType,
2375 void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2377 SmallVector<QualType, 16> ArgTys;
2379 assert(!argT.
isNull() &&
"Can't find 'id' type");
2380 ArgTys.push_back(argT);
2382 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2383 ArgTys.push_back(argT);
2389 msgSendIdent, msgSendType,
2395 void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2398 SmallVector<QualType, 16> ArgTys;
2403 assert(!argT.isNull() &&
"Can't build 'struct objc_super *' type");
2404 ArgTys.push_back(argT);
2406 assert(!argT.isNull() &&
"Can't find 'SEL' type");
2407 ArgTys.push_back(argT);
2414 msgSendType,
nullptr,
2419 void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2421 SmallVector<QualType, 16> ArgTys;
2423 assert(!argT.
isNull() &&
"Can't find 'id' type");
2424 ArgTys.push_back(argT);
2426 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2427 ArgTys.push_back(argT);
2433 msgSendIdent, msgSendType,
2438 void RewriteObjC::SynthGetClassFunctionDecl() {
2440 SmallVector<QualType, 16> ArgTys;
2447 getClassIdent, getClassType,
2452 void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2455 SmallVector<QualType, 16> ArgTys;
2463 getClassType,
nullptr,
2468 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2470 SmallVector<QualType, 16> ArgTys;
2477 getClassIdent, getClassType,
2482 assert(Exp !=
nullptr &&
"Expected non-null ObjCStringLiteral");
2483 QualType strType = getConstantStringStructType();
2485 std::string S =
"__NSConstantStringImpl_";
2487 std::string tmpName = InFileName;
2489 for (i=0; i < tmpName.length(); i++) {
2490 char c = tmpName.at(i);
2497 S += utostr(NumObjCStringLiterals++);
2499 Preamble +=
"static __NSConstantStringImpl " +
S;
2500 Preamble +=
" __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2501 Preamble +=
"0x000007c8,";
2503 std::string prettyBufS;
2504 llvm::raw_string_ostream prettyBuf(prettyBufS);
2506 Preamble += prettyBuf.str();
2522 ReplaceStmt(Exp, cast);
2528 QualType RewriteObjC::getSuperStructType() {
2529 if (!SuperStructDecl) {
2541 for (
unsigned i = 0; i < 2; ++i) {
2545 FieldTypes[i],
nullptr,
2551 SuperStructDecl->completeDefinition();
2556 QualType RewriteObjC::getConstantStringStructType() {
2557 if (!ConstantStringDecl) {
2573 for (
unsigned i = 0; i < 4; ++i) {
2578 FieldTypes[i],
nullptr,
2584 ConstantStringDecl->completeDefinition();
2592 SmallVectorImpl<QualType> &ArgTypes,
2593 SmallVectorImpl<Expr*> &MsgExprs,
2604 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2625 if (!SelGetUidFunctionDecl)
2626 SynthSelGetUidFunctionDecl();
2627 if (!MsgSendFunctionDecl)
2628 SynthMsgSendFunctionDecl();
2629 if (!MsgSendSuperFunctionDecl)
2630 SynthMsgSendSuperFunctionDecl();
2631 if (!MsgSendStretFunctionDecl)
2632 SynthMsgSendStretFunctionDecl();
2633 if (!MsgSendSuperStretFunctionDecl)
2634 SynthMsgSendSuperStretFunctionDecl();
2635 if (!MsgSendFpretFunctionDecl)
2636 SynthMsgSendFpretFunctionDecl();
2637 if (!GetClassFunctionDecl)
2638 SynthGetClassFunctionDecl();
2639 if (!GetSuperClassFunctionDecl)
2640 SynthGetSuperClassFunctionDecl();
2641 if (!GetMetaClassFunctionDecl)
2642 SynthGetMetaClassFunctionDecl();
2649 QualType resultType = mDecl->getReturnType();
2651 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2653 MsgSendFlavor = MsgSendFpretFunctionDecl;
2657 SmallVector<Expr*, 8> MsgExprs;
2659 case ObjCMessageExpr::SuperClass: {
2660 MsgSendFlavor = MsgSendSuperFunctionDecl;
2661 if (MsgSendStretFlavor)
2662 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2663 assert(MsgSendFlavor &&
"MsgSendFlavor is NULL!");
2667 SmallVector<Expr*, 4> InitExprs;
2670 InitExprs.push_back(
2681 SmallVector<Expr*, 8> ClsExprs;
2683 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2684 ClsExprs, StartLoc, EndLoc);
2690 ClsExprs.push_back(ArgExpr);
2691 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2695 InitExprs.push_back(
2696 NoTypeInfoCStyleCastExpr(
Context,
2700 QualType superType = getSuperStructType();
2703 if (LangOpts.MicrosoftExt) {
2704 SynthSuperConstructorFunctionDecl();
2722 SuperRep = NoTypeInfoCStyleCastExpr(
Context,
2741 MsgExprs.push_back(SuperRep);
2745 case ObjCMessageExpr::Class: {
2746 SmallVector<Expr*, 8> ClsExprs;
2750 ClsExprs.push_back(getStringLiteral(clsName->
getName()));
2751 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2753 MsgExprs.push_back(Cls);
2757 case ObjCMessageExpr::SuperInstance:{
2758 MsgSendFlavor = MsgSendSuperFunctionDecl;
2759 if (MsgSendStretFlavor)
2760 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2761 assert(MsgSendFlavor &&
"MsgSendFlavor is NULL!");
2763 SmallVector<Expr*, 4> InitExprs;
2765 InitExprs.push_back(
2775 SmallVector<Expr*, 8> ClsExprs;
2777 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2784 ClsExprs.push_back(ArgExpr);
2785 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2790 InitExprs.push_back(
2795 QualType superType = getSuperStructType();
2798 if (LangOpts.MicrosoftExt) {
2799 SynthSuperConstructorFunctionDecl();
2802 false, superType, VK_LValue,
2816 SuperRep = NoTypeInfoCStyleCastExpr(
Context,
2830 MsgExprs.push_back(SuperRep);
2834 case ObjCMessageExpr::Instance: {
2839 recExpr = CE->getSubExpr();
2847 MsgExprs.push_back(recExpr);
2853 SmallVector<Expr*, 8> SelExprs;
2855 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2856 SelExprs, StartLoc, EndLoc);
2857 MsgExprs.push_back(SelExp);
2860 for (
unsigned i = 0; i < Exp->
getNumArgs(); i++) {
2866 if (needToScanForQualifiers(type))
2869 (void)convertBlockPointerToFunctionPointer(type);
2887 userExpr = NoTypeInfoCStyleCastExpr(
Context, type, CK, userExpr);
2890 else if (
CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2891 if (CE->getType()->isObjCQualifiedIdType()) {
2892 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2893 userExpr = CE->getSubExpr();
2908 MsgExprs.push_back(userExpr);
2916 SmallVector<QualType, 8> ArgTypes;
2920 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2927 for (
const auto *PI : OMD->
params()) {
2932 (void)convertBlockPointerToFunctionPointer(t);
2933 ArgTypes.push_back(t);
2936 convertToUnqualifiedObjCType(returnType);
2937 (void)convertBlockPointerToFunctionPointer(returnType);
2952 cast = NoTypeInfoCStyleCastExpr(
Context,
2960 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() :
true);
2971 Stmt *ReplacingStmt = CE;
2972 if (MsgSendStretFlavor) {
2978 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2979 msgSendType, returnType,
2996 llvm::APInt(IntSize, 8),
3013 return ReplacingStmt;
3021 ReplaceStmt(Exp, ReplacingStmt);
3024 return ReplacingStmt;
3028 QualType RewriteObjC::getProtocolType() {
3029 if (!ProtocolTypeDecl) {
3058 ReplaceStmt(Exp, castExpr);
3065 bool RewriteObjC::BufferContainsPPDirectives(
const char *startBuf,
3066 const char *endBuf) {
3067 while (startBuf < endBuf) {
3068 if (*startBuf ==
'#') {
3070 for (++startBuf; startBuf[0] ==
' ' || startBuf[0] ==
'\t'; ++startBuf)
3072 if (!strncmp(startBuf,
"if", strlen(
"if")) ||
3073 !strncmp(startBuf,
"ifdef", strlen(
"ifdef")) ||
3074 !strncmp(startBuf,
"ifndef", strlen(
"ifndef")) ||
3075 !strncmp(startBuf,
"define", strlen(
"define")) ||
3076 !strncmp(startBuf,
"undef", strlen(
"undef")) ||
3077 !strncmp(startBuf,
"else", strlen(
"else")) ||
3078 !strncmp(startBuf,
"elif", strlen(
"elif")) ||
3079 !strncmp(startBuf,
"endif", strlen(
"endif")) ||
3080 !strncmp(startBuf,
"pragma", strlen(
"pragma")) ||
3081 !strncmp(startBuf,
"include", strlen(
"include")) ||
3082 !strncmp(startBuf,
"import", strlen(
"import")) ||
3083 !strncmp(startBuf,
"include_next", strlen(
"include_next")))
3094 std::string &Result) {
3095 assert(CDecl &&
"Class missing in SynthesizeObjCInternalStruct");
3096 assert(CDecl->
getName() !=
"" &&
3097 "Name missing in SynthesizeObjCInternalStruct");
3099 if (ObjCSynthesizedStructs.count(CDecl))
3112 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3113 endBuf += Lexer::MeasureTokenLength(LocEnd, *
SM, LangOpts);
3114 ReplaceText(LocStart, endBuf-startBuf, Result);
3120 Result +=
"\nstruct ";
3122 if (LangOpts.MicrosoftExt)
3126 const char *cursor = strchr(startBuf,
'{');
3127 assert((cursor && endBuf)
3128 &&
"SynthesizeObjCInternalStruct - malformed @interface");
3144 if (BufferContainsPPDirectives(startBuf, cursor)) {
3148 endHeader += Lexer::MeasureTokenLength(L, *
SM, LangOpts);
3152 while (endHeader < cursor && *endHeader != '>
') endHeader++;
3155 // rewrite the original header
3156 ReplaceText(LocStart, endHeader-startBuf, Result);
3158 // rewrite the original header *without* disturbing the '{
'
3159 ReplaceText(LocStart, cursor-startBuf, Result);
3161 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3162 Result = "\n struct ";
3163 Result += RCDecl->getNameAsString();
3165 Result += RCDecl->getNameAsString();
3166 Result += "_IVARS;\n";
3168 // insert the super class structure definition.
3169 SourceLocation OnePastCurly =
3170 LocStart.getLocWithOffset(cursor-startBuf+1);
3171 InsertText(OnePastCurly, Result);
3173 cursor++; // past '{
'
3175 // Now comment out any visibility specifiers.
3176 while (cursor < endBuf) {
3177 if (*cursor == '@
') {
3178 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3180 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t
'; ++cursor)
3183 // FIXME: presence of @public, etc. inside comment results in
3184 // this transformation as well, which is still correct c-code.
3185 if (!strncmp(cursor, "public", strlen("public")) ||
3186 !strncmp(cursor, "private", strlen("private")) ||
3187 !strncmp(cursor, "package", strlen("package")) ||
3188 !strncmp(cursor, "protected", strlen("protected")))
3189 InsertText(atLoc, "// ");
3191 // FIXME: If there are cases where '<
' is used in ivar declaration part
3192 // of user code, then scan the ivar list and use needToScanForQualifiers
3193 // for type checking.
3194 else if (*cursor == '<
') {
3195 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3196 InsertText(atLoc, "/* ");
3197 cursor = strchr(cursor, '>
');
3199 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3200 InsertText(atLoc, " */");
3201 } else if (*cursor == '^
') { // rewrite block specifier.
3202 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3203 ReplaceText(caretLoc, 1, "*");
3207 // Don't forget to add a
';'!!
3210 endBuf += Lexer::MeasureTokenLength(LocEnd, *
SM, LangOpts);
3211 Result +=
" {\n struct ";
3215 Result +=
"_IVARS;\n};\n";
3216 ReplaceText(LocStart, endBuf-startBuf, Result);
3219 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3220 llvm_unreachable(
"struct already synthesize- SynthesizeObjCInternalStruct");
3231 void RewriteObjC::RewriteImplementations() {
3232 int ClsDefCount = ClassImplementation.size();
3233 int CatDefCount = CategoryImplementation.size();
3236 for (
int i = 0; i < ClsDefCount; i++)
3237 RewriteImplementationDecl(ClassImplementation[i]);
3239 for (
int i = 0; i < CatDefCount; i++)
3240 RewriteImplementationDecl(CategoryImplementation[i]);
3243 void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3244 const std::string &Name,
3246 assert(BlockByRefDeclNo.count(VD) &&
3247 "RewriteByRefString: ByRef decl missing");
3249 ResultStr +=
"struct ";
3250 ResultStr +=
"__Block_byref_" + Name +
3251 "_" + utostr(BlockByRefDeclNo[VD]) ;
3254 static bool HasLocalVariableExternalStorage(
ValueDecl *VD) {
3255 if (
VarDecl *Var = dyn_cast<VarDecl>(VD))
3256 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3260 std::string RewriteObjC::SynthesizeBlockFunc(
BlockExpr *CE,
int i,
3265 std::string StructRef =
"struct " + Tag;
3267 funcName.str() +
"_" +
"block_func_" + utostr(i);
3271 if (isa<FunctionNoProtoType>(AFT)) {
3274 S +=
"(" + StructRef +
" *__cself)";
3276 S +=
"(" + StructRef +
" *__cself)";
3279 assert(FT &&
"SynthesizeBlockFunc: No function proto");
3282 S += StructRef +
" *__cself, ";
3283 std::string ParamStr;
3287 ParamStr = (*AI)->getNameAsString();
3289 (void)convertBlockPointerToFunctionPointer(QT);
3304 E = BlockByRefDecls.end(); I !=
E; ++
I) {
3306 std::string Name = (*I)->getNameAsString();
3307 std::string TypeString;
3308 RewriteByRefString(TypeString, Name, (*I));
3310 Name = TypeString +
Name;
3311 S += Name +
" = __cself->" + (*I)->getNameAsString() +
"; // bound by ref\n";
3315 E = BlockByCopyDecls.end(); I !=
E; ++
I) {
3327 if (isTopLevelBlockPointerType((*I)->getType())) {
3328 RewriteBlockPointerTypeVariable(S, (*I));
3330 RewriteBlockPointerType(S, (*I)->getType());
3332 S +=
"__cself->" + (*I)->getNameAsString() +
"; // bound by copy\n";
3335 std::string Name = (*I)->getNameAsString();
3337 if (HasLocalVariableExternalStorage(*I))
3340 S += Name +
" = __cself->" +
3341 (*I)->getNameAsString() +
"; // bound by copy\n";
3344 std::string RewrittenStr = RewrittenBlockExprs[CE];
3345 const char *cstr = RewrittenStr.c_str();
3346 while (*cstr++ !=
'{') ;
3352 std::string RewriteObjC::SynthesizeBlockHelperFuncs(
BlockExpr *CE,
int i,
3355 std::string StructRef =
"struct " + Tag;
3356 std::string S =
"static void __";
3359 S +=
"_block_copy_" + utostr(i);
3360 S +=
"(" + StructRef;
3361 S +=
"*dst, " + StructRef;
3363 for (
ValueDecl *VD : ImportedBlockDecls) {
3364 S +=
"_Block_object_assign((void*)&dst->";
3366 S +=
", (void*)src->";
3368 if (BlockByRefDeclsPtrSet.count(VD))
3377 S +=
"\nstatic void __";
3379 S +=
"_block_dispose_" + utostr(i);
3380 S +=
"(" + StructRef;
3382 for (
ValueDecl *VD : ImportedBlockDecls) {
3383 S +=
"_Block_object_dispose((void*)src->";
3385 if (BlockByRefDeclsPtrSet.count(VD))
3396 std::string RewriteObjC::SynthesizeBlockImpl(
BlockExpr *CE, std::string Tag,
3398 std::string S =
"\nstruct " + Tag;
3399 std::string Constructor =
" " + Tag;
3401 S +=
" {\n struct __block_impl impl;\n";
3402 S +=
" struct " + Desc;
3405 Constructor +=
"(void *fp, ";
3406 Constructor +=
"struct " + Desc;
3407 Constructor +=
" *desc";
3409 if (BlockDeclRefs.size()) {
3412 E = BlockByCopyDecls.end(); I !=
E; ++
I) {
3414 std::string FieldName = (*I)->getNameAsString();
3415 std::string ArgName =
"_" + FieldName;
3426 if (isTopLevelBlockPointerType((*I)->getType())) {
3427 S +=
"struct __block_impl *";
3428 Constructor +=
", void *" + ArgName;
3431 if (HasLocalVariableExternalStorage(*I))
3435 Constructor +=
", " + ArgName;
3437 S += FieldName +
";\n";
3441 E = BlockByRefDecls.end(); I !=
E; ++
I) {
3443 std::string FieldName = (*I)->getNameAsString();
3444 std::string ArgName =
"_" + FieldName;
3446 std::string TypeString;
3447 RewriteByRefString(TypeString, FieldName, (*I));
3449 FieldName = TypeString + FieldName;
3450 ArgName = TypeString + ArgName;
3451 Constructor +=
", " + ArgName;
3453 S += FieldName +
"; // by ref\n";
3456 Constructor +=
", int flags=0)";
3458 bool firsTime =
true;
3460 E = BlockByCopyDecls.end(); I !=
E; ++
I) {
3461 std::string Name = (*I)->getNameAsString();
3463 Constructor +=
" : ";
3467 Constructor +=
", ";
3468 if (isTopLevelBlockPointerType((*I)->getType()))
3469 Constructor += Name +
"((struct __block_impl *)_" + Name +
")";
3471 Constructor += Name +
"(_" + Name +
")";
3475 E = BlockByRefDecls.end(); I !=
E; ++
I) {
3476 std::string Name = (*I)->getNameAsString();
3478 Constructor +=
" : ";
3482 Constructor +=
", ";
3483 Constructor += Name +
"(_" + Name +
"->__forwarding)";
3486 Constructor +=
" {\n";
3488 Constructor +=
" impl.isa = &_NSConcreteGlobalBlock;\n";
3490 Constructor +=
" impl.isa = &_NSConcreteStackBlock;\n";
3491 Constructor +=
" impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3493 Constructor +=
" Desc = desc;\n";
3496 Constructor +=
", int flags=0) {\n";
3498 Constructor +=
" impl.isa = &_NSConcreteGlobalBlock;\n";
3500 Constructor +=
" impl.isa = &_NSConcreteStackBlock;\n";
3501 Constructor +=
" impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3502 Constructor +=
" Desc = desc;\n";
3505 Constructor +=
"}\n";
3511 std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3512 std::string ImplTag,
int i,
3515 std::string S =
"\nstatic struct " + DescTag;
3517 S +=
" {\n unsigned long reserved;\n";
3518 S +=
" unsigned long Block_size;\n";
3520 S +=
" void (*copy)(struct ";
3521 S += ImplTag; S +=
"*, struct ";
3522 S += ImplTag; S +=
"*);\n";
3524 S +=
" void (*dispose)(struct ";
3525 S += ImplTag; S +=
"*);\n";
3529 S += DescTag +
"_DATA = { 0, sizeof(struct ";
3532 S +=
", __" + FunName.str() +
"_block_copy_" + utostr(i);
3533 S +=
", __" + FunName.str() +
"_block_dispose_" + utostr(i);
3539 void RewriteObjC::SynthesizeBlockLiterals(
SourceLocation FunLocStart,
3540 StringRef FunName) {
3542 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3543 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3544 bool RewriteSC = (GlobalVarDecl &&
3546 GlobalVarDecl->getStorageClass() ==
SC_Static &&
3547 GlobalVarDecl->getType().getCVRQualifiers());
3549 std::string SC(
" void __");
3550 SC += GlobalVarDecl->getNameAsString();
3552 InsertText(FunLocStart, SC);
3556 for (
unsigned i = 0, count=0; i < Blocks.size(); i++) {
3557 CollectBlockDeclRefInfo(Blocks[i]);
3560 for (
int j = 0; j < InnerDeclRefsCount[i]; j++) {
3563 BlockDeclRefs.push_back(Exp);
3564 if (!VD->
hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3565 BlockByCopyDeclsPtrSet.insert(VD);
3566 BlockByCopyDecls.push_back(VD);
3568 if (VD->
hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3569 BlockByRefDeclsPtrSet.insert(VD);
3570 BlockByRefDecls.push_back(VD);
3574 if (VD->
hasAttr<BlocksAttr>() ||
3577 ImportedBlockDecls.insert(VD);
3580 std::string ImplTag =
"__" + FunName.str() +
"_block_impl_" + utostr(i);
3581 std::string DescTag =
"__" + FunName.str() +
"_block_desc_" + utostr(i);
3583 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3585 InsertText(FunLocStart, CI);
3587 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3589 InsertText(FunLocStart, CF);
3591 if (ImportedBlockDecls.size()) {
3592 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3593 InsertText(FunLocStart, HF);
3595 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3596 ImportedBlockDecls.size() > 0);
3597 InsertText(FunLocStart, BD);
3599 BlockDeclRefs.clear();
3600 BlockByRefDecls.clear();
3601 BlockByRefDeclsPtrSet.clear();
3602 BlockByCopyDecls.clear();
3603 BlockByCopyDeclsPtrSet.clear();
3604 ImportedBlockDecls.clear();
3610 if (GlobalVarDecl->getStorageClass() ==
SC_Static)
3612 if (GlobalVarDecl->getType().isConstQualified())
3614 if (GlobalVarDecl->getType().isVolatileQualified())
3616 if (GlobalVarDecl->getType().isRestrictQualified())
3618 InsertText(FunLocStart, SC);
3622 InnerDeclRefsCount.clear();
3623 InnerDeclRefs.clear();
3624 RewrittenBlockExprs.clear();
3627 void RewriteObjC::InsertBlockLiteralsWithinFunction(
FunctionDecl *FD) {
3629 StringRef FuncName = FD->
getName();
3631 SynthesizeBlockLiterals(FunLocStart, FuncName);
3634 static void BuildUniqueMethodName(std::string &Name,
3640 std::string::size_type loc = 0;
3641 while ((loc = Name.find(
":", loc)) != std::string::npos)
3642 Name.replace(loc, 1,
"_");
3645 void RewriteObjC::InsertBlockLiteralsWithinMethod(
ObjCMethodDecl *MD) {
3649 std::string FuncName;
3650 BuildUniqueMethodName(FuncName, MD);
3651 SynthesizeBlockLiterals(FunLocStart, FuncName);
3654 void RewriteObjC::GetBlockDeclRefExprs(
Stmt *S) {
3655 for (
Stmt *SubStmt : S->children())
3657 if (
BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3658 GetBlockDeclRefExprs(CBE->getBody());
3660 GetBlockDeclRefExprs(SubStmt);
3665 HasLocalVariableExternalStorage(DRE->
getDecl()))
3667 BlockDeclRefs.push_back(DRE);
3672 void RewriteObjC::GetInnerBlockDeclRefExprs(
Stmt *S,
3673 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3674 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3675 for (
Stmt *SubStmt : S->children())
3677 if (
BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3678 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3679 GetInnerBlockDeclRefExprs(CBE->getBody(),
3684 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3687 if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3689 HasLocalVariableExternalStorage(DRE->
getDecl())) {
3691 InnerBlockDeclRefs.push_back(DRE);
3693 if (Var->isFunctionOrMethodVarDecl())
3694 ImportedLocalExternalDecls.insert(Var);
3709 SmallVector<QualType, 8> ArgTypes;
3711 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3717 if (convertBlockPointerToFunctionPointer(t))
3718 HasBlockType =
true;
3719 ArgTypes.push_back(t);
3726 FuncType = getSimpleFunctionType(Res, ArgTypes);
3731 Stmt *RewriteObjC::SynthesizeBlockCall(
CallExpr *Exp,
const Expr *BlockExp) {
3735 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3737 }
else if (
const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3740 else if (
const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3741 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3743 else if (
const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3746 dyn_cast<ConditionalOperator>(BlockExp)) {
3747 Expr *LHSExp = CEXPR->getLHS();
3748 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3749 Expr *RHSExp = CEXPR->getRHS();
3750 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3751 Expr *CONDExp = CEXPR->getCond();
3758 }
else if (
const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3761 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3764 assert(1 &&
"RewriteBlockClass: Bad type");
3766 assert(CPT &&
"RewriteBlockClass: Bad type");
3768 assert(FT &&
"RewriteBlockClass: Bad type");
3778 SmallVector<QualType, 8> ArgTypes;
3781 ArgTypes.push_back(PtrBlock);
3786 if (!convertBlockPointerToFunctionPointer(t))
3787 convertToUnqualifiedObjCType(t);
3788 ArgTypes.push_back(t);
3792 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->
getType(), ArgTypes);
3798 const_cast<Expr*>(BlockExp));
3814 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(
Context, PtrToFuncCastType,
3818 SmallVector<Expr*, 8> BlkExprs;
3820 BlkExprs.push_back(BlkCast);
3824 BlkExprs.push_back(*I);
3850 HasLocalVariableExternalStorage(DeclRefExp->
getDecl());
3862 StringRef Name = VD->
getName();
3876 ReplaceStmt(DeclRefExp, PE);
3883 Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(
DeclRefExpr *DRE) {
3885 if (
VarDecl *Var = dyn_cast<VarDecl>(VD))
3886 if (!ImportedLocalExternalDecls.count(Var))
3894 ReplaceStmt(DRE, PE);
3906 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3912 const Type* TypePtr = QT->
getAs<Type>();
3913 if (isa<TypeOfExprType>(TypePtr)) {
3914 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3916 std::string TypeAsString =
"(";
3917 RewriteBlockPointerType(TypeAsString, QT);
3918 TypeAsString +=
")";
3919 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3923 const char *argPtr = startBuf;
3925 while (*argPtr++ && (argPtr < endBuf)) {
3930 ReplaceText(LocStart, 1,
"*");
3937 void RewriteObjC::RewriteBlockPointerFunctionArgs(
FunctionDecl *FD) {
3939 unsigned parenCount = 0;
3943 const char *startArgList = strchr(startBuf,
'(');
3945 assert((*startArgList ==
'(') &&
"Rewriter fuzzy parser confused");
3950 assert((DeclLoc.
isValid()) &&
"Invalid DeclLoc");
3952 const char *argPtr = startArgList;
3954 while (*argPtr++ && parenCount) {
3959 ReplaceText(DeclLoc, 1,
"*");
3972 bool RewriteObjC::PointerTypeTakesAnyBlockArguments(
QualType QT) {
3979 assert(BPT &&
"BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3984 if (isTopLevelBlockPointerType(I))
3990 bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(
QualType QT) {
3997 assert(BPT &&
"BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4002 if (I->isObjCQualifiedIdType())
4004 if (I->isObjCObjectPointerType() &&
4005 I->getPointeeType()->isObjCQualifiedInterfaceType())
4013 void RewriteObjC::GetExtentOfArgList(
const char *Name,
const char *&LParen,
4014 const char *&RParen) {
4015 const char *argPtr = strchr(Name,
'(');
4016 assert((*argPtr ==
'(') &&
"Rewriter fuzzy parser confused");
4020 unsigned parenCount = 1;
4022 while (*argPtr && parenCount) {
4024 case '(': parenCount++;
break;
4025 case ')': parenCount--;
break;
4028 if (parenCount) argPtr++;
4030 assert((*argPtr ==
')') &&
"Rewriter fuzzy parser confused");
4034 void RewriteObjC::RewriteBlockPointerDecl(
NamedDecl *ND) {
4036 RewriteBlockPointerFunctionArgs(FD);
4042 if (
VarDecl *VD = dyn_cast<VarDecl>(ND))
4045 DeclT = TDD->getUnderlyingType();
4046 else if (
FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4049 llvm_unreachable(
"RewriteBlockPointerDecl(): Decl type not yet handled");
4052 const char *endBuf = startBuf;
4054 while (*startBuf !=
'^' && *startBuf !=
';' && startBuf != MainFileStart)
4058 unsigned OrigLength=0;
4061 if (*startBuf ==
'^') {
4067 while (*startBuf !=
')') {
4075 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4076 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4081 const char *argListBegin, *argListEnd;
4082 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4083 while (argListBegin < argListEnd) {
4084 if (*argListBegin ==
'^')
4086 else if (*argListBegin ==
'<') {
4088 buf += *argListBegin++;
4090 while (*argListBegin !=
'>') {
4091 buf += *argListBegin++;
4094 buf += *argListBegin;
4098 buf += *argListBegin;
4105 ReplaceText(Start, OrigLength, buf);
4131 std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(
VarDecl *VD,
4134 if (CopyDestroyCache.count(flag))
4136 CopyDestroyCache.insert(flag);
4137 S =
"static void __Block_byref_id_object_copy_";
4139 S +=
"(void *dst, void *src) {\n";
4145 unsigned VoidPtrSize =
4149 S +=
" _Block_object_assign((char*)dst + ";
4150 S += utostr(offset);
4151 S +=
", *(void * *) ((char*)src + ";
4152 S += utostr(offset);
4157 S +=
"static void __Block_byref_id_object_dispose_";
4159 S +=
"(void *src) {\n";
4160 S +=
" _Block_object_dispose(*(void * *) ((char*)src + ";
4161 S += utostr(offset);
4186 void RewriteObjC::RewriteByRefVar(
VarDecl *ND) {
4189 if (CurFunctionDeclToDeclareForBlock)
4190 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4203 std::string ByrefType;
4204 RewriteByRefString(ByrefType, Name, ND,
true);
4205 ByrefType +=
" {\n";
4206 ByrefType +=
" void *__isa;\n";
4207 RewriteByRefString(ByrefType, Name, ND);
4208 ByrefType +=
" *__forwarding;\n";
4209 ByrefType +=
" int __flags;\n";
4210 ByrefType +=
" int __size;\n";
4215 if (HasCopyAndDispose) {
4216 ByrefType +=
" void (*__Block_byref_id_object_copy)(void*, void*);\n";
4217 ByrefType +=
" void (*__Block_byref_id_object_dispose)(void*);\n";
4221 (void)convertBlockPointerToFunctionPointer(T);
4224 ByrefType +=
" " + Name +
";\n";
4225 ByrefType +=
"};\n";
4229 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4231 assert(CurMethodDef &&
"RewriteByRefVar - CurMethodDef is null");
4232 FunLocStart = CurMethodDef->getLocStart();
4234 InsertText(FunLocStart, ByrefType);
4240 if (HasCopyAndDispose) {
4248 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4250 InsertText(FunLocStart, HF);
4256 bool hasInit = (ND->
getInit() !=
nullptr);
4258 if (HasCopyAndDispose)
4262 RewriteByRefString(ByrefType, Name, ND);
4263 std::string ForwardingCastType(
"(");
4264 ForwardingCastType += ByrefType +
" *)";
4266 ByrefType +=
" " + Name +
" = {(void*)";
4267 ByrefType += utostr(isa);
4268 ByrefType +=
"," + ForwardingCastType +
"&" + Name +
", ";
4269 ByrefType += utostr(flags);
4271 ByrefType +=
"sizeof(";
4272 RewriteByRefString(ByrefType, Name, ND);
4274 if (HasCopyAndDispose) {
4275 ByrefType +=
", __Block_byref_id_object_copy_";
4276 ByrefType += utostr(flag);
4277 ByrefType +=
", __Block_byref_id_object_dispose_";
4278 ByrefType += utostr(flag);
4280 ByrefType +=
"};\n";
4281 unsigned nameSize = Name.size();
4286 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4292 startLoc = ECE->getLParenLoc();
4294 startLoc = E->getLocStart();
4297 ByrefType +=
" " +
Name;
4298 ByrefType +=
" = {(void*)";
4299 ByrefType += utostr(isa);
4300 ByrefType +=
"," + ForwardingCastType +
"&" + Name +
", ";
4301 ByrefType += utostr(flags);
4303 ByrefType +=
"sizeof(";
4304 RewriteByRefString(ByrefType, Name, ND);
4306 if (HasCopyAndDispose) {
4307 ByrefType +=
"__Block_byref_id_object_copy_";
4308 ByrefType += utostr(flag);
4309 ByrefType +=
", __Block_byref_id_object_dispose_";
4310 ByrefType += utostr(flag);
4313 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4324 const char *semiBuf = strchr(startInitializerBuf,
';');
4325 assert((*semiBuf ==
';') &&
"RewriteByRefVar: can't find ';'");
4329 InsertText(semiLoc,
"}");
4334 void RewriteObjC::CollectBlockDeclRefInfo(
BlockExpr *Exp) {
4336 GetBlockDeclRefExprs(Exp->
getBody());
4337 if (BlockDeclRefs.size()) {
4339 for (
unsigned i = 0; i < BlockDeclRefs.size(); i++)
4340 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4341 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4342 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4343 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4347 for (
unsigned i = 0; i < BlockDeclRefs.size(); i++)
4348 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4349 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4350 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4351 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4355 for (
unsigned i = 0; i < BlockDeclRefs.size(); i++)
4356 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4357 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4358 BlockDeclRefs[i]->getType()->isBlockPointerType())
4359 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4363 FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4372 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4374 Blocks.push_back(Exp);
4376 CollectBlockDeclRefInfo(Exp);
4379 int countOfInnerDecls = 0;
4380 if (!InnerBlockDeclRefs.empty()) {
4381 for (
unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4384 if (!VD->
hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4388 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4389 BlockDeclRefs.push_back(Exp);
4390 BlockByCopyDeclsPtrSet.insert(VD);
4391 BlockByCopyDecls.push_back(VD);
4393 if (VD->
hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4394 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4395 BlockDeclRefs.push_back(Exp);
4396 BlockByRefDeclsPtrSet.insert(VD);
4397 BlockByRefDecls.push_back(VD);
4401 for (
unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4402 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4403 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4404 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4405 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4407 InnerDeclRefsCount.push_back(countOfInnerDecls);
4409 std::string FuncName;
4413 else if (CurMethodDef)
4414 BuildUniqueMethodName(FuncName, CurMethodDef);
4415 else if (GlobalVarDecl)
4416 FuncName = std::string(GlobalVarDecl->getNameAsString());
4418 std::string BlockNumber = utostr(Blocks.size()-1);
4420 std::string Tag =
"__" + FuncName +
"_block_impl_" + BlockNumber;
4421 std::string Func =
"__" + FuncName +
"_block_func_" + BlockNumber;
4424 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4431 FD = SynthBlockInitFunctionDecl(Tag);
4435 SmallVector<Expr*, 4> InitExprs;
4438 FD = SynthBlockInitFunctionDecl(Func);
4443 InitExprs.push_back(castExpr);
4446 std::string DescData =
"__" + FuncName +
"_block_desc_" + BlockNumber +
"_DATA";
4462 InitExprs.push_back(DescRefExpr);
4465 if (BlockDeclRefs.size()) {
4469 E = BlockByCopyDecls.end(); I !=
E; ++
I) {
4470 if (isObjCType((*I)->getType())) {
4472 FD = SynthBlockInitFunctionDecl((*I)->getName());
4475 if (HasLocalVariableExternalStorage(*I)) {
4481 }
else if (isTopLevelBlockPointerType((*I)->getType())) {
4482 FD = SynthBlockInitFunctionDecl((*I)->getName());
4488 FD = SynthBlockInitFunctionDecl((*I)->getName());
4491 if (HasLocalVariableExternalStorage(*I)) {
4499 InitExprs.push_back(Exp);
4503 E = BlockByRefDecls.end(); I !=
E; ++
I) {
4506 std::string RecName;
4507 RewriteByRefString(RecName, Name, ND,
true);
4509 +
sizeof(
"struct"));
4513 assert(RD &&
"SynthBlockInitExpr(): Can't find RecordDecl");
4516 FD = SynthBlockInitFunctionDecl((*I)->getName());
4519 bool isNestedCapturedVar =
false;
4521 for (
const auto &CI : block->
captures()) {
4522 const VarDecl *variable = CI.getVariable();
4523 if (variable == ND && CI.isNested()) {
4524 assert (CI.isByRef() &&
4525 "SynthBlockInitExpr - captured block variable is not byref");
4526 isNestedCapturedVar =
true;
4532 if (!isNestedCapturedVar)
4537 InitExprs.push_back(Exp);
4540 if (ImportedBlockDecls.size()) {
4547 InitExprs.push_back(FlagExp);
4556 BlockDeclRefs.clear();
4557 BlockByRefDecls.clear();
4558 BlockByRefDeclsPtrSet.clear();
4559 BlockByCopyDecls.clear();
4560 BlockByCopyDeclsPtrSet.clear();
4561 ImportedBlockDecls.clear();
4565 bool RewriteObjC::IsDeclStmtInForeachHeader(
DeclStmt *DS) {
4567 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4568 return CS->getElement() == DS;
4576 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(
Stmt *S) {
4577 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4578 isa<DoStmt>(S) || isa<ForStmt>(S))
4580 else if (isa<ObjCForCollectionStmt>(S)) {
4582 ObjCBcLabelNo.push_back(++BcLabelCount);
4589 return RewritePropertyOrImplicitSetter(PseudoOp);
4591 return RewritePropertyOrImplicitGetter(PseudoOp);
4593 }
else if (
ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4594 return RewriteObjCIvarRefExpr(IvarRefExpr);
4600 for (
Stmt *&childStmt : S->children())
4602 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4604 childStmt = newStmt;
4608 if (
BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4609 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4610 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4611 InnerContexts.insert(BE->getBlockDecl());
4612 ImportedLocalExternalDecls.clear();
4613 GetInnerBlockDeclRefExprs(BE->getBody(),
4614 InnerBlockDeclRefs, InnerContexts);
4616 Stmt *SaveCurrentBody = CurrentBody;
4617 CurrentBody = BE->getBody();
4618 PropParentMap =
nullptr;
4624 bool saveDisableReplaceStmt = DisableReplaceStmt;
4625 DisableReplaceStmt =
false;
4626 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4627 DisableReplaceStmt = saveDisableReplaceStmt;
4628 CurrentBody = SaveCurrentBody;
4629 PropParentMap =
nullptr;
4630 ImportedLocalExternalDecls.clear();
4632 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4633 RewrittenBlockExprs[BE] = Str;
4635 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4638 ReplaceStmt(S, blockTranscribed);
4639 return blockTranscribed;
4643 return RewriteAtEncode(AtEncode);
4646 return RewriteAtSelector(AtSelector);
4649 return RewriteObjCStringLiteral(AtString);
4660 std::string messString;
4661 messString +=
"// ";
4662 messString.append(startBuf, endBuf-startBuf+1);
4671 return RewriteMessageExpr(MessExpr);
4675 return RewriteObjCTryStmt(StmtTry);
4678 return RewriteObjCSynchronizedStmt(StmtTry);
4681 return RewriteObjCThrowStmt(StmtThrow);
4684 return RewriteObjCProtocolExpr(ProtocolExp);
4687 dyn_cast<ObjCForCollectionStmt>(S))
4688 return RewriteObjCForCollectionStmt(StmtForCollection,
4691 dyn_cast<BreakStmt>(S))
4692 return RewriteBreakStmt(StmtBreakStmt);
4694 dyn_cast<ContinueStmt>(S))
4695 return RewriteContinueStmt(StmtContinueStmt);
4699 if (
DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4709 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4710 RewriteObjCQualifiedInterfaceTypes(*DS->
decl_begin());
4713 for (
auto *SD : DS->
decls()) {
4714 if (
ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4715 if (isTopLevelBlockPointerType(ND->
getType()))
4716 RewriteBlockPointerDecl(ND);
4718 CheckFunctionPointerDecl(ND->
getType(), ND);
4719 if (
VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4720 if (VD->
hasAttr<BlocksAttr>()) {
4721 static unsigned uniqueByrefDeclCount = 0;
4722 assert(!BlockByRefDeclNo.count(ND) &&
4723 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4724 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4725 RewriteByRefVar(VD);
4728 RewriteTypeOfDecl(VD);
4732 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4733 RewriteBlockPointerDecl(TD);
4734 else if (TD->getUnderlyingType()->isFunctionPointerType())
4735 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4741 RewriteObjCQualifiedInterfaceTypes(CE);
4743 if (isa<SwitchStmt>(S) || isa<WhileStmt>(
S) ||
4744 isa<DoStmt>(S) || isa<ForStmt>(
S)) {
4745 assert(!Stmts.empty() &&
"Statement stack is empty");
4746 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4747 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4748 &&
"Statement stack mismatch");
4752 if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4754 if (VD->
hasAttr<BlocksAttr>())
4755 return RewriteBlockDeclRefExpr(DRE);
4756 if (HasLocalVariableExternalStorage(VD))
4757 return RewriteLocalVariableExternalStorage(DRE);
4760 if (
CallExpr *CE = dyn_cast<CallExpr>(S)) {
4763 ReplaceStmt(S, BlockCall);
4768 RewriteCastExpr(CE);
4777 llvm::raw_string_ostream Buf(SStr);
4778 Replacement->printPretty(Buf);
4779 const std::string &Str = Buf.str();
4781 printf(
"CAST = %s\n", &Str[0]);
4782 InsertText(ICE->
getSubExpr()->getLocStart(), Str);
4791 void RewriteObjC::RewriteRecordBody(
RecordDecl *RD) {
4792 for (
auto *FD : RD->
fields()) {
4793 if (isTopLevelBlockPointerType(FD->
getType()))
4794 RewriteBlockPointerDecl(FD);
4797 RewriteObjCQualifiedInterfaceTypes(FD);
4803 void RewriteObjC::HandleDeclInMainFile(
Decl *D) {
4805 case Decl::Function: {
4813 RewriteBlocksInFunctionProtoType(FD->
getType(), FD);
4820 CurFunctionDef = FD;
4821 CurFunctionDeclToDeclareForBlock = FD;
4824 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4826 CurrentBody =
nullptr;
4827 if (PropParentMap) {
4828 delete PropParentMap;
4829 PropParentMap =
nullptr;
4833 InsertBlockLiteralsWithinFunction(FD);
4834 CurFunctionDef =
nullptr;
4835 CurFunctionDeclToDeclareForBlock =
nullptr;
4839 case Decl::ObjCMethod: {
4845 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4847 CurrentBody =
nullptr;
4848 if (PropParentMap) {
4849 delete PropParentMap;
4850 PropParentMap =
nullptr;
4852 InsertBlockLiteralsWithinMethod(MD);
4853 CurMethodDef =
nullptr;
4857 case Decl::ObjCImplementation: {
4859 ClassImplementation.push_back(CI);
4862 case Decl::ObjCCategoryImpl: {
4864 CategoryImplementation.push_back(CI);
4868 VarDecl *VD = cast<VarDecl>(D);
4869 RewriteObjCQualifiedInterfaceTypes(VD);
4870 if (isTopLevelBlockPointerType(VD->
getType()))
4871 RewriteBlockPointerDecl(VD);
4873 CheckFunctionPointerDecl(VD->
getType(), VD);
4876 RewriteCastExpr(CE);
4882 RewriteRecordBody(RD);
4887 RewriteFunctionBodyOrGlobalInitializer(VD->
getInit());
4888 CurrentBody =
nullptr;
4889 if (PropParentMap) {
4890 delete PropParentMap;
4891 PropParentMap =
nullptr;
4894 GlobalVarDecl =
nullptr;
4898 RewriteCastExpr(CE);
4904 case Decl::Typedef: {
4906 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4907 RewriteBlockPointerDecl(TD);
4908 else if (TD->getUnderlyingType()->isFunctionPointerType())
4909 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4913 case Decl::CXXRecord:
4914 case Decl::Record: {
4917 RewriteRecordBody(RD);
4926 void RewriteObjC::HandleTranslationUnit(
ASTContext &
C) {
4927 if (Diags.hasErrorOccurred())
4935 RewriteObjCProtocolMetaData(ProtDecl,
"",
"", Preamble);
4938 if (ClassImplementation.size() || CategoryImplementation.size())
4939 RewriteImplementations();
4944 Rewrite.getRewriteBufferFor(MainFileID)) {
4946 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4948 llvm::errs() <<
"No changes\n";
4951 if (ClassImplementation.size() || CategoryImplementation.size() ||
4952 ProtocolExprDecls.size()) {
4954 std::string ResultStr;
4955 RewriteMetaDataIntoBuffer(ResultStr);
4957 *OutFile << ResultStr;
4962 void RewriteObjCFragileABI::Initialize(
ASTContext &context) {
4963 InitializeCommon(context);
4968 Preamble =
"#pragma once\n";
4969 Preamble +=
"struct objc_selector; struct objc_class;\n";
4970 Preamble +=
"struct __rw_objc_super { struct objc_object *object; ";
4971 Preamble +=
"struct objc_object *superClass; ";
4972 if (LangOpts.MicrosoftExt) {
4974 Preamble +=
"__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4976 Preamble +=
"object(o), superClass(s) {} ";
4979 Preamble +=
"#ifndef _REWRITER_typedef_Protocol\n";
4980 Preamble +=
"typedef struct objc_object Protocol;\n";
4981 Preamble +=
"#define _REWRITER_typedef_Protocol\n";
4982 Preamble +=
"#endif\n";
4983 if (LangOpts.MicrosoftExt) {
4984 Preamble +=
"#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4985 Preamble +=
"#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4987 Preamble +=
"#define __OBJC_RW_DLLIMPORT extern\n";
4988 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4989 Preamble +=
"(struct objc_object *, struct objc_selector *, ...);\n";
4990 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4991 Preamble +=
"(struct objc_super *, struct objc_selector *, ...);\n";
4992 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4993 Preamble +=
"(struct objc_object *, struct objc_selector *, ...);\n";
4994 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4995 Preamble +=
"(struct objc_super *, struct objc_selector *, ...);\n";
4996 Preamble +=
"__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4997 Preamble +=
"(struct objc_object *, struct objc_selector *, ...);\n";
4998 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4999 Preamble +=
"(const char *);\n";
5000 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5001 Preamble +=
"(struct objc_class *);\n";
5002 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5003 Preamble +=
"(const char *);\n";
5004 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5005 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5006 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5007 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5008 Preamble +=
"__OBJC_RW_DLLIMPORT int objc_exception_match";
5009 Preamble +=
"(struct objc_class *, struct objc_object *);\n";
5011 Preamble +=
"__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5012 Preamble +=
"__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
5013 Preamble +=
"__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5014 Preamble +=
"#ifndef __FASTENUMERATIONSTATE\n";
5015 Preamble +=
"struct __objcFastEnumerationState {\n\t";
5016 Preamble +=
"unsigned long state;\n\t";
5017 Preamble +=
"void **itemsPtr;\n\t";
5018 Preamble +=
"unsigned long *mutationsPtr;\n\t";
5019 Preamble +=
"unsigned long extra[5];\n};\n";
5020 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5021 Preamble +=
"#define __FASTENUMERATIONSTATE\n";
5022 Preamble +=
"#endif\n";
5023 Preamble +=
"#ifndef __NSCONSTANTSTRINGIMPL\n";
5024 Preamble +=
"struct __NSConstantStringImpl {\n";
5025 Preamble +=
" int *isa;\n";
5026 Preamble +=
" int flags;\n";
5027 Preamble +=
" char *str;\n";
5028 Preamble +=
" long length;\n";
5030 Preamble +=
"#ifdef CF_EXPORT_CONSTANT_STRING\n";
5031 Preamble +=
"extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5032 Preamble +=
"#else\n";
5033 Preamble +=
"__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5034 Preamble +=
"#endif\n";
5035 Preamble +=
"#define __NSCONSTANTSTRINGIMPL\n";
5036 Preamble +=
"#endif\n";
5038 Preamble +=
"#ifndef BLOCK_IMPL\n";
5039 Preamble +=
"#define BLOCK_IMPL\n";
5040 Preamble +=
"struct __block_impl {\n";
5041 Preamble +=
" void *isa;\n";
5042 Preamble +=
" int Flags;\n";
5043 Preamble +=
" int Reserved;\n";
5044 Preamble +=
" void *FuncPtr;\n";
5046 Preamble +=
"// Runtime copy/destroy helper functions (from Block_private.h)\n";
5047 Preamble +=
"#ifdef __OBJC_EXPORT_BLOCKS\n";
5048 Preamble +=
"extern \"C\" __declspec(dllexport) "
5049 "void _Block_object_assign(void *, const void *, const int);\n";
5050 Preamble +=
"extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5051 Preamble +=
"extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5052 Preamble +=
"extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5053 Preamble +=
"#else\n";
5054 Preamble +=
"__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5055 Preamble +=
"__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5056 Preamble +=
"__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5057 Preamble +=
"__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5058 Preamble +=
"#endif\n";
5059 Preamble +=
"#endif\n";
5060 if (LangOpts.MicrosoftExt) {
5061 Preamble +=
"#undef __OBJC_RW_DLLIMPORT\n";
5062 Preamble +=
"#undef __OBJC_RW_STATICIMPORT\n";
5063 Preamble +=
"#ifndef KEEP_ATTRIBUTES\n";
5064 Preamble +=
"#define __attribute__(X)\n";
5065 Preamble +=
"#endif\n";
5066 Preamble +=
"#define __weak\n";
5069 Preamble +=
"#define __block\n";
5070 Preamble +=
"#define __weak\n";
5074 Preamble +=
"\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5079 void RewriteObjCFragileABI::RewriteIvarOffsetComputation(
ObjCIvarDecl *ivar,
5080 std::string &Result) {
5086 Result +=
"__OFFSETOFIVAR__(struct ";
5088 if (LangOpts.MicrosoftExt)
5097 void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5099 StringRef ClassName, std::string &Result) {
5100 static bool objc_protocol_methods =
false;
5109 Result +=
"\nstruct _protocol_methods {\n";
5110 Result +=
"\tstruct objc_selector *_cmd;\n";
5111 Result +=
"\tchar *method_types;\n";
5114 objc_protocol_methods =
true;
5131 Result +=
"\nstatic struct {\n";
5132 Result +=
"\tint protocol_method_count;\n";
5133 Result +=
"\tstruct _protocol_methods protocol_methods[";
5134 Result += utostr(NumMethods);
5135 Result +=
"];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5137 Result +=
" __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5138 "{\n\t" + utostr(NumMethods) +
"\n";
5141 for (ObjCProtocolDecl::instmeth_iterator
5145 Result +=
"\t ,{{(struct objc_selector *)\"";
5147 Result +=
"\t ,{(struct objc_selector *)\"";
5148 Result += (*I)->getSelector().getAsString();
5149 std::string MethodTypeString;
5152 Result += MethodTypeString;
5155 Result +=
"\t }\n};\n";
5161 if (NumMethods > 0) {
5167 Result +=
"\nstatic struct {\n";
5168 Result +=
"\tint protocol_method_count;\n";
5169 Result +=
"\tstruct _protocol_methods protocol_methods[";
5170 Result += utostr(NumMethods);
5171 Result +=
"];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5173 Result +=
" __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5175 Result += utostr(NumMethods);
5179 for (ObjCProtocolDecl::classmeth_iterator
5183 Result +=
"\t ,{{(struct objc_selector *)\"";
5185 Result +=
"\t ,{(struct objc_selector *)\"";
5186 Result += (*I)->getSelector().getAsString();
5187 std::string MethodTypeString;
5190 Result += MethodTypeString;
5193 Result +=
"\t }\n};\n";
5206 static bool objc_protocol =
false;
5207 if (!objc_protocol) {
5208 Result +=
"\nstruct _objc_protocol {\n";
5209 Result +=
"\tstruct _objc_protocol_extension *isa;\n";
5210 Result +=
"\tchar *protocol_name;\n";
5211 Result +=
"\tstruct _objc_protocol **protocol_list;\n";
5212 Result +=
"\tstruct _objc_protocol_method_list *instance_methods;\n";
5213 Result +=
"\tstruct _objc_protocol_method_list *class_methods;\n";
5216 objc_protocol =
true;
5219 Result +=
"\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5221 Result +=
" __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5224 Result +=
"\", 0, ";
5226 Result +=
"(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5233 Result +=
"(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5243 llvm_unreachable(
"protocol already synthesized");
5247 void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5249 StringRef prefix, StringRef ClassName,
5250 std::string &Result) {
5251 if (Protocols.
empty())
return;
5253 for (
unsigned i = 0; i != Protocols.
size(); i++)
5254 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5263 Result +=
"\nstatic struct {\n";
5264 Result +=
"\tstruct _objc_protocol_list *next;\n";
5265 Result +=
"\tint protocol_count;\n";
5266 Result +=
"\tstruct _objc_protocol *class_protocols[";
5267 Result += utostr(Protocols.
size());
5268 Result +=
"];\n} _OBJC_";
5270 Result +=
"_PROTOCOLS_";
5271 Result += ClassName;
5272 Result +=
" __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5274 Result += utostr(Protocols.
size());
5277 Result +=
"\t,{&_OBJC_PROTOCOL_";
5278 Result += Protocols[0]->getNameAsString();
5281 for (
unsigned i = 1; i != Protocols.
size(); i++) {
5282 Result +=
"\t ,&_OBJC_PROTOCOL_";
5283 Result += Protocols[i]->getNameAsString();
5286 Result +=
"\t }\n};\n";
5290 std::string &Result) {
5297 RewriteObjCInternalStruct(CDecl, Result);
5305 static bool objc_ivar =
false;
5313 Result +=
"\nstruct _objc_ivar {\n";
5314 Result +=
"\tchar *ivar_name;\n";
5315 Result +=
"\tchar *ivar_type;\n";
5316 Result +=
"\tint ivar_offset;\n";
5327 Result +=
"\nstatic struct {\n";
5328 Result +=
"\tint ivar_count;\n";
5329 Result +=
"\tstruct _objc_ivar ivar_list[";
5330 Result += utostr(NumIvars);
5331 Result +=
"];\n} _OBJC_INSTANCE_VARIABLES_";
5333 Result +=
" __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5335 Result += utostr(NumIvars);
5339 SmallVector<ObjCIvarDecl *, 8> IVars;
5341 for (
auto *IV : IDecl->
ivars())
5342 IVars.push_back(IV);
5349 Result +=
"\t,{{\"";
5350 Result += IVI->getNameAsString();
5352 std::string TmpString, StrEncoding;
5354 QuoteDoublequotes(TmpString, StrEncoding);
5355 Result += StrEncoding;
5357 RewriteIvarOffsetComputation(*IVI, Result);
5359 for (++IVI; IVI != IVE; ++IVI) {
5360 Result +=
"\t ,{\"";
5361 Result += IVI->getNameAsString();
5363 std::string TmpString, StrEncoding;
5365 QuoteDoublequotes(TmpString, StrEncoding);
5366 Result += StrEncoding;
5368 RewriteIvarOffsetComputation(*IVI, Result);
5372 Result +=
"\t }\n};\n";
5376 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->
instance_methods());
5381 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5383 if (!Prop->getPropertyIvarDecl())
5389 if (!Getter->isDefined())
5390 InstanceMethods.push_back(Getter);
5394 if (!Setter->isDefined())
5395 InstanceMethods.push_back(Setter);
5397 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5398 true,
"", IDecl->
getName(), Result);
5402 false,
"", IDecl->
getName(), Result);
5406 "CLASS", CDecl->
getName(), Result);
5424 static bool objc_class =
false;
5426 Result +=
"\nstruct _objc_class {\n";
5427 Result +=
"\tstruct _objc_class *isa;\n";
5428 Result +=
"\tconst char *super_class_name;\n";
5429 Result +=
"\tchar *name;\n";
5430 Result +=
"\tlong version;\n";
5431 Result +=
"\tlong info;\n";
5432 Result +=
"\tlong instance_size;\n";
5433 Result +=
"\tstruct _objc_ivar_list *ivars;\n";
5434 Result +=
"\tstruct _objc_method_list *methods;\n";
5435 Result +=
"\tstruct objc_cache *cache;\n";
5436 Result +=
"\tstruct _objc_protocol_list *protocols;\n";
5437 Result +=
"\tconst char *ivar_layout;\n";
5438 Result +=
"\tstruct _objc_class_ext *ext;\n";
5446 while (SuperClass) {
5447 RootClass = SuperClass;
5452 Result +=
"\nstatic struct _objc_class _OBJC_METACLASS_";
5454 Result +=
" __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5455 "{\n\t(struct _objc_class *)\"";
5467 Result +=
", 0, \"";
5473 Result +=
", 0,2, sizeof(struct _objc_class), 0";
5475 Result +=
"\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5482 Result +=
"\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5487 Result +=
"\t,0,0,0,0\n";
5491 Result +=
"\nstatic struct _objc_class _OBJC_CLASS_";
5493 Result +=
" __attribute__ ((used, section (\"__OBJC, __class\")))= "
5494 "{\n\t&_OBJC_METACLASS_";
5504 Result +=
", 0, \"";
5510 if (!ObjCSynthesizedStructs.count(CDecl))
5514 Result +=
",sizeof(struct ";
5516 if (LangOpts.MicrosoftExt)
5521 Result +=
", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5528 Result +=
", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5530 Result +=
", 0\n\t";
5535 Result +=
", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5537 Result +=
", 0,0\n";
5540 Result +=
",0,0,0\n";
5544 void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5545 int ClsDefCount = ClassImplementation.size();
5546 int CatDefCount = CategoryImplementation.size();
5549 for (
int i = 0; i < ClsDefCount; i++)
5550 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5553 for (
int i = 0; i < CatDefCount; i++)
5554 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5568 Result +=
"\nstruct _objc_symtab {\n";
5569 Result +=
"\tlong sel_ref_cnt;\n";
5570 Result +=
"\tSEL *refs;\n";
5571 Result +=
"\tshort cls_def_cnt;\n";
5572 Result +=
"\tshort cat_def_cnt;\n";
5573 Result +=
"\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+
"];\n";
5576 Result +=
"static struct _objc_symtab "
5577 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5578 Result +=
"\t0, 0, " + utostr(ClsDefCount)
5579 +
", " + utostr(CatDefCount) +
"\n";
5580 for (
int i = 0; i < ClsDefCount; i++) {
5581 Result +=
"\t,&_OBJC_CLASS_";
5582 Result += ClassImplementation[i]->getNameAsString();
5586 for (
int i = 0; i < CatDefCount; i++) {
5587 Result +=
"\t,&_OBJC_CATEGORY_";
5588 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5590 Result += CategoryImplementation[i]->getNameAsString();
5607 Result +=
"\nstruct _objc_module {\n";
5608 Result +=
"\tlong version;\n";
5609 Result +=
"\tlong size;\n";
5610 Result +=
"\tconst char *name;\n";
5611 Result +=
"\tstruct _objc_symtab *symtab;\n";
5613 Result +=
"static struct _objc_module "
5614 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5615 Result +=
"\t" + utostr(OBJC_ABI_VERSION) +
5616 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5619 if (LangOpts.MicrosoftExt) {
5620 if (ProtocolExprDecls.size()) {
5621 Result +=
"#pragma section(\".objc_protocol$B\",long,read,write)\n";
5622 Result +=
"#pragma data_seg(push, \".objc_protocol$B\")\n";
5624 Result +=
"static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5625 Result += ProtDecl->getNameAsString();
5626 Result +=
" = &_OBJC_PROTOCOL_";
5627 Result += ProtDecl->getNameAsString();
5630 Result +=
"#pragma data_seg(pop)\n\n";
5632 Result +=
"#pragma section(\".objc_module_info$B\",long,read,write)\n";
5633 Result +=
"#pragma data_seg(push, \".objc_module_info$B\")\n";
5634 Result +=
"static struct _objc_module *_POINTER_OBJC_MODULES = ";
5635 Result +=
"&_OBJC_MODULES;\n";
5636 Result +=
"#pragma data_seg(pop)\n\n";
5643 std::string &Result) {
5650 FullCategoryName +=
'_';
5654 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->
instance_methods());
5659 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5661 if (!Prop->getPropertyIvarDecl())
5667 InstanceMethods.push_back(Getter);
5671 InstanceMethods.push_back(Setter);
5673 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5674 true,
"CATEGORY_", FullCategoryName.c_str(),
5679 false,
"CATEGORY_", FullCategoryName.c_str(),
5686 FullCategoryName, Result);
5700 static bool objc_category =
false;
5701 if (!objc_category) {
5702 Result +=
"\nstruct _objc_category {\n";
5703 Result +=
"\tchar *category_name;\n";
5704 Result +=
"\tchar *class_name;\n";
5705 Result +=
"\tstruct _objc_method_list *instance_methods;\n";
5706 Result +=
"\tstruct _objc_method_list *class_methods;\n";
5707 Result +=
"\tstruct _objc_protocol_list *protocols;\n";
5708 Result +=
"\tunsigned int size;\n";
5709 Result +=
"\tstruct _objc_property_list *instance_properties;\n";
5711 objc_category =
true;
5713 Result +=
"\nstatic struct _objc_category _OBJC_CATEGORY_";
5714 Result += FullCategoryName;
5715 Result +=
" __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5717 Result +=
"\"\n\t, \"";
5722 Result +=
"\t, (struct _objc_method_list *)"
5723 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5724 Result += FullCategoryName;
5728 Result +=
"\t, 0\n";
5730 Result +=
"\t, (struct _objc_method_list *)"
5731 "&_OBJC_CATEGORY_CLASS_METHODS_";
5732 Result += FullCategoryName;
5736 Result +=
"\t, 0\n";
5739 Result +=
"\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5740 Result += FullCategoryName;
5744 Result +=
"\t, 0\n";
5745 Result +=
"\t, sizeof(struct _objc_category), 0\n};\n";
5750 template<
typename MethodIterator>
5751 void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5752 MethodIterator MethodEnd,
5753 bool IsInstanceMethod,
5755 StringRef ClassName,
5756 std::string &Result) {
5757 if (MethodBegin == MethodEnd)
return;
5759 if (!objc_impl_method) {
5766 Result +=
"\nstruct _objc_method {\n";
5767 Result +=
"\tSEL _cmd;\n";
5768 Result +=
"\tchar *method_types;\n";
5769 Result +=
"\tvoid *_imp;\n";
5772 objc_impl_method =
true;
5783 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5784 Result +=
"\nstatic struct {\n";
5785 Result +=
"\tstruct _objc_method_list *next_method;\n";
5786 Result +=
"\tint method_count;\n";
5787 Result +=
"\tstruct _objc_method method_list[";
5788 Result += utostr(NumMethods);
5789 Result +=
"];\n} _OBJC_";
5791 Result += IsInstanceMethod ?
"INSTANCE" :
"CLASS";
5792 Result +=
"_METHODS_";
5793 Result += ClassName;
5794 Result +=
" __attribute__ ((used, section (\"__OBJC, __";
5795 Result += IsInstanceMethod ?
"inst" :
"cls";
5796 Result +=
"_meth\")))= ";
5797 Result +=
"{\n\t0, " + utostr(NumMethods) +
"\n";
5799 Result +=
"\t,{{(SEL)\"";
5800 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5801 std::string MethodTypeString;
5804 Result += MethodTypeString;
5805 Result +=
"\", (void *)";
5806 Result += MethodInternalNames[*MethodBegin];
5808 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5809 Result +=
"\t ,{(SEL)\"";
5810 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5811 std::string MethodTypeString;
5814 Result += MethodTypeString;
5815 Result +=
"\", (void *)";
5816 Result += MethodInternalNames[*MethodBegin];
5819 Result +=
"\t }\n};\n";
5828 DisableReplaceStmtScope
S(*
this);
5829 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5835 Expr *Replacement = IV;
5840 assert(iFaceDecl &&
"RewriteObjCIvarRefExpr - iFaceDecl is null");
5845 assert(clsDeclared &&
"RewriteObjCIvarRefExpr(): Can't find class");
5854 assert(RD &&
"RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5874 assert(!IV->
isFreeIvar() &&
"Cannot have a free standing ivar outside a method");
5885 assert(clsDeclared &&
"RewriteObjCIvarRefExpr(): Can't find class");
5888 std::string RecName = clsDeclared->getIdentifier()->getName();
5894 assert(RD &&
"RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5909 ReplaceStmtWithRange(IV, Replacement, OldRange);
SourceLocation getEnd() const
const Expr * getBase() const
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
classmeth_iterator classmeth_end() const
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
SourceLocation getLocStart() const LLVM_READONLY
PointerType - C99 6.7.5.1 - Pointer Declarators.
const ObjCAtFinallyStmt * getFinallyStmt() const
Retrieve the @finally statement, if any.
A (possibly-)qualified type.
ObjCInterfaceDecl * getClassInterface()
bool isBitField() const
Determines whether this field is a bitfield.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
SourceLocation getLocation() const
QualType getClassReceiver() const
Returns the type of a class message send, or NULL if the message is not a class message.
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
FunctionType - C99 6.7.5.3 - Function Declarators.
bool isThisDeclarationADefinition() const
Determine whether this particular declaration of this class is actually also a definition.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Defines the SourceManager interface.
bool isRecordType() const
Decl - This represents one declaration (or definition), e.g.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
param_iterator param_end()
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
ParenExpr - This represents a parethesized expression, e.g.
void getSelectorLocs(SmallVectorImpl< SourceLocation > &SelLocs) const
std::string getAsString() const
FullSourceLoc getFullLoc(SourceLocation Loc) const
The base class of the type hierarchy.
bool isObjCQualifiedClassType() const
Represents Objective-C's @throw statement.
SourceLocation getLocStart() const LLVM_READONLY
instmeth_iterator instmeth_begin() const
const Expr * getInit() const
bool isBooleanType() const
A container of type source information.
bool isBlockPointerType() const
static StringLiteral * Create(const ASTContext &C, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumStrs)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
SourceLocation getLocStart() const LLVM_READONLY
SourceLocation getLocEnd() const LLVM_READONLY
VarDecl - An instance of this class is created to represent a variable declaration or definition...
CompoundLiteralExpr - [C99 6.5.2.5].
Extra information about a function prototype.
SourceLocation getLocStart() const LLVM_READONLY
QualType getObjCClassType() const
Represents the Objective-C Class type.
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
ObjCMethodDecl - Represents an instance or class method declaration.
RewriteBuffer - As code is rewritten, SourceBuffer's from the original input with modifications get a...
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Describes how types, statements, expressions, and declarations should be printed. ...
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
ParmVarDecl - Represents a parameter to a function.
SourceLocation getLocation() const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names the category interface associated with this implementat...
SourceLocation getLocStart() const LLVM_READONLY
QualType withConst() const
Retrieves a version of this type with const applied.
unsigned getNumParams() const
Kind getPropertyImplementation() const
unsigned ivar_size() const
RecordDecl - Represents a struct/union/class.
ObjCProtocolDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C protocol.
One of these records is kept for each identifier that is lexed.
ObjCProtocolDecl * getProtocol() const
const ObjCInterfaceDecl * getContainingInterface() const
Return the class interface that this ivar is logically contained in; this is either the interface whe...
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Represents a class type in Objective C.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
unsigned getNumSemanticExprs() const
protocol_iterator protocol_begin() const
std::string getNameAsString() const
Get the name of the class associated with this interface.
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
StringLiteral * getString()
const Stmt * getBody() const
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
CK_IntegralToPointer - Integral to pointer.
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super', otherwise an invalid source location.
const VarDecl * getCatchParamDecl() const
Represents Objective-C's @catch statement.
const CompoundStmt * getSynchBody() const
Describes an C or C++ initializer list.
CK_IntegralToBoolean - Integral to boolean.
QualType getCallResultType(ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
param_type_range param_types() const
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
const LangOptions & getLangOpts() const
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
SourceLocation getSuperClassLoc() const
Retrieve the starting location of the superclass.
protocol_iterator protocol_end() const
QualType getReturnType() const
QualType getSuperType() const
Retrieve the type referred to by 'super'.
field_range fields() const
Concrete class used by the front-end to report problems and issues.
Represents a typeof (or typeof) expression (a GCC extension).
TypeDecl - Represents a declaration of a type.
A builtin binary operation expression such as "x + y" or "x <= y".
Selector getSelector() const
bool isOverloadedOperator() const
isOverloadedOperator - Whether this function declaration represents an C++ overloaded operator...
std::string getNameAsString() const
getNameAsString - Get a human-readable name for the declaration, even if it is one of the special kin...
ObjCStringLiteral, used for Objective-C string literals i.e.
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
const Stmt * getCatchBody() const
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
CompoundStmt * getCompoundBody()
Represents an Objective-C protocol declaration.
const ObjCAtCatchStmt * getCatchStmt(unsigned I) const
Retrieve a @catch statement.
SourceLocation getLocEnd() const LLVM_READONLY
An ordinary object is located at an address in memory.
Represents an ObjC class declaration.
SourceLocation getLocEnd() const LLVM_READONLY
propimpl_range property_impls() const
Represents a linkage specification.
detail::InMemoryDirectory::const_iterator I
PropertyAttributeKind getPropertyAttributes() const
SourceLocation getAtStartLoc() const
SourceLocation getAtLoc() const
SourceRange getAtEndRange() const
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
bool isThisDeclarationADefinition() const
Determine whether this particular declaration is also the definition.
ConditionalOperator - The ?: ternary operator.
SourceLocation getLocStart() const LLVM_READONLY
SourceLocation getLocEnd() const LLVM_READONLY
CompoundStmt - This represents a group of statements like { stmt stmt }.
QualType getParamType(unsigned i) const
Represents a prototype with parameter type info, e.g.
CastKind
CastKind - The kind of operation required for a conversion.
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
SourceLocation getTypeSpecStartLoc() const
ID
Defines the set of possible language-specific address spaces.
CK_FunctionToPointerDecay - Function to pointer decay.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
bool isFunctionPointerType() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
bool isRealFloatingType() const
Floating point categories.
const ObjCMethodDecl * getMethodDecl() const
SourceLocation getLocStart() const LLVM_READONLY
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
QualType getPointeeType() const
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - This represents one expression.
StringRef getName() const
Return the actual identifier string.
CK_BitCast - A conversion which causes a bit pattern of one type to be reinterpreted as a bit pattern...
ObjCIvarDecl * getPropertyIvarDecl() const
protocol_iterator protocol_begin() const
SourceLocation getRParenLoc() const
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
TranslationUnitDecl * getTranslationUnitDecl() const
bool isObjCGCWeak() const
true when Type is objc's weak.
Expr * getUnderlyingExpr() const
DeclContext * getDeclContext()
Represents Objective-C's @synchronized statement.
ObjCSelectorExpr used for @selector in Objective-C.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
classmeth_iterator classmeth_begin() const
Selector getSelector() const
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
bool isInstanceMethod() const
bool isa(CodeGen::Address addr)
QualType getObjCIdType() const
Represents the Objective-CC id type.
An expression that sends a message to the given Objective-C object or class.
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep)
Creates clause with a list of variables VL and a linear step Step.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
instmeth_iterator instmeth_end() const
unsigned ivar_size() const
The result type of a method or function.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
const clang::PrintingPolicy & getPrintingPolicy() const
SourceLocation getRightLoc() const
ivar_iterator ivar_begin() const
ivar_iterator ivar_begin() const
param_iterator param_begin()
CK_CPointerToObjCPointerCast - Casting a C pointer kind to an Objective-C pointer.
Stmt * getBody(const FunctionDecl *&Definition) const
getBody - Retrieve the body (definition) of the function.
SourceLocation getLocStart() const LLVM_READONLY
ivar_iterator ivar_end() const
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
const TemplateArgument * iterator
StringRef getName() const
getName - Get the name of identifier for the class interface associated with this implementation as a...
static LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Interfaces are the core concept in Objective-C for object oriented design.
ivar_iterator ivar_end() const
bool isValid() const
Return true if this is a valid SourceLocation object.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
TypeSourceInfo * getClassReceiverTypeInfo() const
Returns a type-source information of a class message send, or NULL if the message is not a class mess...
SourceLocation getLocStart() const LLVM_READONLY
ObjCCategoryDecl - Represents a category declaration.
const ObjCInterfaceDecl * getClassInterface() const
decl_iterator decl_begin()
ObjCProtocolExpr used for protocol expression in Objective-C.
std::string getAsString() const
Derive the full selector name (e.g.
Represents one property declaration in an Objective-C interface.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
QualType getReturnType() const
SourceLocation getBegin() const
const T * castAs() const
Member-template castAs<specific type>.
FileID getMainFileID() const
Returns the FileID of the main source file.
const BlockDecl * getBlockDecl() const
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;...
QualType getPointeeType() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
decl_iterator - Iterates through the declarations stored within this context.
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Base class for declarations which introduce a typedef-name.
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
instmeth_range instance_methods() const
ObjCCategoryDecl * FindCategoryDeclaration(IdentifierInfo *CategoryId) const
FindCategoryDeclaration - Finds category declaration in the list of categories for this class and ret...
SourceLocation getLParenLoc() const
unsigned getByteLength() const
prop_range properties() const
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
SourceLocation getLocStart() const LLVM_READONLY
std::string getNameAsString() const
Get the name of the class associated with this interface.
static __inline__ uint32_t volatile uint32_t * p
QualType IgnoreParens() const
Returns the specified type after dropping any outer-level parentheses.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
std::unique_ptr< ASTConsumer > CreateObjCRewriter(const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags, const LangOptions &LOpts, bool SilenceRewriteMacroWarning)
const Expr * getSynchExpr() const
bool hasDefinition() const
Determine whether this protocol has a definition.
U cast(CodeGen::Address addr)
bool isThisDeclarationADefinition() const
isThisDeclarationADefinition - Returns whether this specific declaration of the function is also a de...
Selector getSelector() const
CK_BlockPointerToObjCPointerCast - Casting a block pointer to an ObjC pointer.
detail::InMemoryDirectory::const_iterator E
SourceLocation getEndOfDefinitionLoc() const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Defines the Diagnostic-related interfaces.
Represents a pointer to an Objective C object.
SourceLocation getRParenLoc() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
ObjCMethodDecl * getGetterMethodDecl() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
SourceLocation getLeftLoc() const
bool TypeAlias
Whether this template specialization type is a substituted type alias.
const T * getAs() const
Member-template getAs<specific type>'.
Represents Objective-C's collection statement.
ObjCMethodDecl * getSetterMethodDecl() const
ObjCEncodeExpr, used for @encode in Objective-C.
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
bool isObjCQualifiedIdType() const
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Represents Objective-C's @finally statement.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
const ObjCProtocolList & getReferencedProtocols() const
ExprIterator arg_iterator
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
protocol_iterator protocol_end() const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
unsigned getNumCatchStmts() const
Retrieve the number of @catch statements in this try-catch-finally block.
SourceLocation getRParenLoc() const
ObjCIvarRefExpr - A reference to an ObjC instance variable.
SourceManager & getSourceManager()
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
ObjCPropertyDecl * getPropertyDecl() const
classmeth_range class_methods() const
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
Rewriter - This is the main interface to the rewrite buffers.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
bool isImplicitInterfaceDecl() const
isImplicitInterfaceDecl - check that this is an implicitly declared ObjCInterfaceDecl node...
ContinueStmt - This represents a continue.
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
bool isObjCObjectPointerType() const
QualType getEncodedType() const
ObjCIvarDecl - Represents an ObjC instance variable.
bool isImplicit() const
Indicates whether the message send was implicitly generated by the implementation.
Represents Objective-C's @try ... @catch ... @finally statement.
const Expr * getThrowExpr() const
StringLiteral - This represents a string literal expression, e.g.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
ObjCInterfaceDecl * getSuperClass() const
const Stmt * getTryBody() const
Retrieve the @try body.
TranslationUnitDecl - The top declaration context.
A reference to a declared variable, function, enum, etc.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
BreakStmt - This represents a break.
Expr * getSemanticExpr(unsigned index)
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
An l-value expression is a reference to an object with independent storage.
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
NamedDecl - This represents a decl with a name.
SourceLocation getLocStart() const LLVM_READONLY
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
SourceLocation getLocStart() const LLVM_READONLY
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
bool isIntegralType(ASTContext &Ctx) const
Determine whether this type is an integral type.
This class handles loading and caching of source files into memory.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isObjCQualifiedInterfaceType() const
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
const ObjCProtocolList & getReferencedProtocols() const
bool isPointerType() const