22#include "clang/Config/config.h"
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#if CLANG_ENABLE_OBJC_REWRITER
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_IS_GC = (1 << 27),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
61 static const int OBJC_ABI_VERSION = 7;
70 const char *MainFileStart, *MainFileEnd;
73 std::string InFileName;
74 std::unique_ptr<raw_ostream> OutFile;
79 unsigned RewriteFailedDiag;
81 unsigned NumObjCStringLiterals;
82 VarDecl *ConstantStringClassReference;
88 unsigned TryFinallyContainsReturnDiag;
114 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
134 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
138 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
147 bool SilenceRewriteMacroWarning;
148 bool objc_impl_method;
150 bool DisableReplaceStmt;
151 class DisableReplaceStmtScope {
156 DisableReplaceStmtScope(RewriteObjC &R)
157 : R(R), SavedValue(R.DisableReplaceStmt) {
158 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);
191 void HandleTopLevelSingleDecl(
Decl *D);
192 void HandleDeclInMainFile(
Decl *D);
193 RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
195 bool silenceMacroWarn);
197 ~RewriteObjC()
override {}
199 void HandleTranslationUnit(
ASTContext &C)
override;
201 void ReplaceStmt(
Stmt *Old,
Stmt *New) {
206 assert(Old !=
nullptr && New !=
nullptr &&
"Expected non-null Stmt's");
208 Stmt *ReplacingStmt = ReplacedNodes[Old];
212 if (DisableReplaceStmt)
224 llvm::raw_string_ostream S(SStr);
226 const std::string &Str = S.str();
230 ReplacedNodes[Old] = New;
233 if (SilenceRewriteMacroWarning)
240 bool InsertAfter =
true) {
242 if (!
Rewrite.InsertText(Loc, Str, InsertAfter) ||
243 SilenceRewriteMacroWarning)
246 Diags.
Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 if (!
Rewrite.ReplaceText(Start, OrigLength, Str) ||
253 SilenceRewriteMacroWarning)
256 Diags.
Report(Context->getFullLoc(Start), RewriteFailedDiag);
261 void RewriteInclude();
265 const std::string &typedefString);
266 void RewriteImplementations();
271 void RewriteImplementationDecl(
Decl *Dcl);
274 void RewriteTypeIntoString(
QualType T, std::string &ResultStr,
276 void RewriteByRefString(std::string &ResultStr,
const std::string &Name,
285 void RewriteBlockPointerType(std::string& Str,
QualType Type);
286 void RewriteBlockPointerTypeVariable(std::string& Str,
ValueDecl *VD);
288 void RewriteObjCQualifiedInterfaceTypes(
Decl *Dcl);
289 void RewriteTypeOfDecl(
VarDecl *VD);
290 void RewriteObjCQualifiedInterfaceTypes(
Expr *E);
293 Stmt *RewriteFunctionBodyOrGlobalInitializer(
Stmt *S);
301 void RewriteTryReturnStmts(
Stmt *S);
302 void RewriteSyncReturnStmts(
Stmt *S, std::string buf);
316 void RewriteBlockPointerDecl(
NamedDecl *VD);
317 void RewriteByRefVar(
VarDecl *VD);
323 std::string &Result);
325 void Initialize(
ASTContext &context)
override = 0;
328 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
332 std::string &Result) = 0;
334 std::string &Result) = 0;
338 std::string &Result) = 0;
340 std::string &Result) = 0;
344 virtual void RewriteIvarOffsetComputation(
ObjCIvarDecl *ivar,
345 std::string &Result) = 0;
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperConstructorFunctionDecl();
375 std::string SynthesizeByrefCopyDestroyHelper(
VarDecl *VD,
int flag);
376 std::string SynthesizeBlockHelperFuncs(
BlockExpr *CE,
int i,
377 StringRef funcName, std::string Tag);
378 std::string SynthesizeBlockFunc(
BlockExpr *CE,
int i,
379 StringRef funcName, std::string Tag);
380 std::string SynthesizeBlockImpl(
BlockExpr *CE,
381 std::string Tag, std::string Desc);
382 std::string SynthesizeBlockDescriptor(std::string DescTag,
384 int i, StringRef funcName,
389 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
395 void WarnAboutReturnGotoStmts(
Stmt *S);
396 void HasReturnStmts(
Stmt *S,
bool &hasReturns);
398 void InsertBlockLiteralsWithinFunction(
FunctionDecl *FD);
401 bool IsDeclStmtInForeachHeader(
DeclStmt *DS);
402 void CollectBlockDeclRefInfo(
BlockExpr *Exp);
403 void GetBlockDeclRefExprs(
Stmt *S);
404 void GetInnerBlockDeclRefExprs(
Stmt *S,
406 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
410 bool isTopLevelBlockPointerType(
QualType T) {
411 return isa<BlockPointerType>(T);
417 bool convertBlockPointerToFunctionPointer(
QualType &T) {
418 if (isTopLevelBlockPointerType(T)) {
420 T = Context->getPointerType(BPT->getPointeeType());
426 bool needToScanForQualifiers(
QualType T);
428 QualType getConstantStringStructType();
430 bool BufferContainsPPDirectives(
const char *startBuf,
const char *endBuf);
432 void convertToUnqualifiedObjCType(
QualType &T) {
434 T = Context->getObjCIdType();
436 T = Context->getObjCClassType();
443 T = Context->getPointerType(T);
453 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
455 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456 OCT == Context->getCanonicalType(Context->getObjCClassType()))
460 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
461 PT->getPointeeType()->isObjCQualifiedIdType())
466 bool PointerTypeTakesAnyBlockArguments(
QualType QT);
467 bool PointerTypeTakesAnyObjCQualifiedType(
QualType QT);
468 void GetExtentOfArgList(
const char *Name,
const char *&LParen,
469 const char *&RParen);
471 void QuoteDoublequotes(std::string &From, std::string &To) {
472 for (
unsigned i = 0; i < From.length(); i++) {
482 bool variadic =
false) {
483 if (result == Context->getObjCInstanceType())
484 result = Context->getObjCIdType();
487 return Context->getFunctionType(result, args, fpi);
494 return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E,
nullptr,
500 QualType StrType = Context->getConstantArrayType(
501 Context->CharTy, llvm::APInt(32, Str.size() + 1),
nullptr,
502 ArraySizeModifier::Normal, 0);
503 return StringLiteral::Create(*Context, Str, StringLiteralKind::Ordinary,
510 RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
512 bool silenceMacroWarn)
513 :
RewriteObjC(inFile,
std::move(OS), D, LOpts, silenceMacroWarn) {}
515 ~RewriteObjCFragileABI()
override {}
516 void Initialize(
ASTContext &context)
override;
519 template<
typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
525 std::string &Result);
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;
545void 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))
564static bool IsHeaderFile(
const std::string &
Filename) {
565 std::string::size_type DotPos =
Filename.rfind(
'.');
567 if (DotPos == std::string::npos) {
572 std::string Ext =
Filename.substr(DotPos + 1);
575 return Ext ==
"h" || Ext ==
"hh" || Ext ==
"H";
578RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
580 bool silenceMacroWarn)
581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(
std::move(OS)),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
583 IsHeader = IsHeaderFile(inFile);
585 "rewriting sub-expression within a macro (may not be correct)");
587 DiagnosticsEngine::Warning,
588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
592std::unique_ptr<ASTConsumer>
594 std::unique_ptr<raw_ostream> OS,
596 bool SilenceRewriteMacroWarning) {
597 return std::make_unique<RewriteObjCFragileABI>(
598 InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
601void RewriteObjC::InitializeCommon(
ASTContext &context) {
603 SM = &Context->getSourceManager();
604 TUDecl = Context->getTranslationUnitDecl();
605 MsgSendFunctionDecl =
nullptr;
606 MsgSendSuperFunctionDecl =
nullptr;
607 MsgSendStretFunctionDecl =
nullptr;
608 MsgSendSuperStretFunctionDecl =
nullptr;
609 MsgSendFpretFunctionDecl =
nullptr;
610 GetClassFunctionDecl =
nullptr;
611 GetMetaClassFunctionDecl =
nullptr;
612 GetSuperClassFunctionDecl =
nullptr;
613 SelGetUidFunctionDecl =
nullptr;
614 CFStringFunctionDecl =
nullptr;
615 ConstantStringClassReference =
nullptr;
616 NSStringRecord =
nullptr;
617 CurMethodDef =
nullptr;
618 CurFunctionDef =
nullptr;
619 CurFunctionDeclToDeclareForBlock =
nullptr;
620 GlobalVarDecl =
nullptr;
621 SuperStructDecl =
nullptr;
622 ProtocolTypeDecl =
nullptr;
623 ConstantStringDecl =
nullptr;
625 SuperConstructorFunctionDecl =
nullptr;
626 NumObjCStringLiterals = 0;
627 PropParentMap =
nullptr;
628 CurrentBody =
nullptr;
629 DisableReplaceStmt =
false;
630 objc_impl_method =
false;
633 MainFileID =
SM->getMainFileID();
634 llvm::MemoryBufferRef MainBuf =
SM->getBufferOrFake(MainFileID);
635 MainFileStart = MainBuf.getBufferStart();
636 MainFileEnd = MainBuf.getBufferEnd();
638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
645void RewriteObjC::HandleTopLevelSingleDecl(
Decl *D) {
653 Loc =
SM->getExpansionLoc(Loc);
660 RewriteFunctionDecl(FD);
661 }
else if (
VarDecl *FVD = dyn_cast<VarDecl>(D)) {
663 if (FVD->getName() ==
"_NSConstantStringClassReference") {
664 ConstantStringClassReference = FVD;
668 if (
ID->isThisDeclarationADefinition())
669 RewriteInterfaceDecl(
ID);
671 RewriteCategoryDecl(CD);
673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
678 DIEnd = LSD->decls_end();
681 if (!IFace->isThisDeclarationADefinition()) {
685 if (isa<ObjCInterfaceDecl>(*DI) &&
686 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687 StartLoc == (*DI)->getBeginLoc())
693 }
while (DI != DIEnd);
694 RewriteForwardClassDecl(DG);
700 if (!Proto->isThisDeclarationADefinition()) {
704 if (isa<ObjCProtocolDecl>(*DI) &&
705 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706 StartLoc == (*DI)->getBeginLoc())
712 }
while (DI != DIEnd);
713 RewriteForwardProtocolDecl(DG);
718 HandleTopLevelSingleDecl(*DI);
723 if (
SM->isWrittenInMainFile(Loc))
724 return HandleDeclInMainFile(D);
731void RewriteObjC::RewriteInclude() {
733 StringRef MainBuf =
SM->getBufferData(MainFileID);
734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
736 size_t ImportLen = strlen(
"import");
739 for (
const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr ==
'#') {
741 if (++BufPtr == MainBufEnd)
743 while (*BufPtr ==
' ' || *BufPtr ==
'\t')
744 if (++BufPtr == MainBufEnd)
746 if (!strncmp(BufPtr,
"import", ImportLen)) {
750 ReplaceText(ImportLoc, ImportLen,
"include");
757static std::string getIvarAccessString(
ObjCIvarDecl *OID) {
762 S +=
"_IMPL *)self)->";
770 static bool objcGetPropertyDefined =
false;
771 static bool objcSetPropertyDefined =
false;
773 InsertText(startLoc,
"// ");
774 const char *startBuf =
SM->getCharacterData(startLoc);
775 assert((*startBuf ==
'@') &&
"bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf,
';');
777 assert((*semiBuf ==
';') &&
"@synthesize: can't find ';'");
793 bool GenGetProperty =
794 !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
795 (Attributes & (ObjCPropertyAttribute::kind_retain |
796 ObjCPropertyAttribute::kind_copy));
798 if (GenGetProperty && !objcGetPropertyDefined) {
799 objcGetPropertyDefined =
true;
801 Getr =
"\nextern \"C\" __declspec(dllimport) "
802 "id objc_getProperty(id, SEL, long, bool);\n";
809 if (GenGetProperty) {
822 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
824 std::string ParamStr =
825 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
828 if (FT->isVariadic()) {
829 if (FT->getNumParams())
838 Getr +=
"return (_TYPE)";
839 Getr +=
"objc_getProperty(self, _cmd, ";
840 RewriteIvarOffsetComputation(OID, Getr);
844 Getr +=
"return " + getIvarAccessString(OID);
846 InsertText(onePastSemiLoc, Getr);
855 bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
856 ObjCPropertyAttribute::kind_copy);
857 if (GenSetProperty && !objcSetPropertyDefined) {
858 objcSetPropertyDefined =
true;
860 Setr =
"\nextern \"C\" __declspec(dllimport) "
861 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
869 if (GenSetProperty) {
870 Setr +=
"objc_setProperty (self, _cmd, ";
871 RewriteIvarOffsetComputation(OID, Setr);
875 if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
879 if (Attributes & ObjCPropertyAttribute::kind_copy)
885 Setr += getIvarAccessString(OID) +
" = ";
889 InsertText(onePastSemiLoc, Setr);
893 std::string &typedefString) {
894 typedefString +=
"#ifndef _REWRITER_typedef_";
896 typedefString +=
"\n";
897 typedefString +=
"#define _REWRITER_typedef_";
899 typedefString +=
"\n";
900 typedefString +=
"typedef struct objc_object ";
902 typedefString +=
";\n#endif\n";
906 const std::string &typedefString) {
908 const char *startBuf =
SM->getCharacterData(startLoc);
909 const char *semiPtr = strchr(startBuf,
';');
911 ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
914void RewriteObjC::RewriteForwardClassDecl(
DeclGroupRef D) {
915 std::string typedefString;
918 if (I == D.
begin()) {
922 typedefString +=
"// @class ";
924 typedefString +=
";\n";
926 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
929 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
933 std::string typedefString;
934 for (
unsigned i = 0; i < D.size(); i++) {
937 typedefString +=
"// @class ";
939 typedefString +=
";\n";
941 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
943 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
946void RewriteObjC::RewriteMethodDeclaration(
ObjCMethodDecl *Method) {
954 if (
SM->getExpansionLineNumber(LocEnd) >
955 SM->getExpansionLineNumber(LocStart)) {
956 InsertText(LocStart,
"#if 0\n");
957 ReplaceText(LocEnd, 1,
";\n#endif\n");
959 InsertText(LocStart,
"// ");
966 ReplaceText(Loc, 0,
"// ");
974 ReplaceText(LocStart, 0,
"// ");
979 RewriteMethodDeclaration(I);
981 RewriteMethodDeclaration(I);
985 strlen(
"@end"),
"/* @end */");
993 ReplaceText(LocStart, 0,
"// ");
996 RewriteMethodDeclaration(I);
998 RewriteMethodDeclaration(I);
1004 ReplaceText(LocEnd, strlen(
"@end"),
"/* @end */");
1007 const char *startBuf =
SM->getCharacterData(LocStart);
1008 const char *endBuf =
SM->getCharacterData(LocEnd);
1009 for (
const char *p = startBuf; p < endBuf; p++) {
1010 if (*p ==
'@' && !strncmp(p+1,
"optional", strlen(
"optional"))) {
1012 ReplaceText(OptionalLoc, strlen(
"@optional"),
"/* @optional */");
1015 else if (*p ==
'@' && !strncmp(p+1,
"required", strlen(
"required"))) {
1017 ReplaceText(OptionalLoc, strlen(
"@required"),
"/* @required */");
1023void RewriteObjC::RewriteForwardProtocolDecl(
DeclGroupRef D) {
1026 llvm_unreachable(
"Invalid SourceLocation");
1028 ReplaceText(LocStart, 0,
"// ");
1035 llvm_unreachable(
"Invalid SourceLocation");
1037 ReplaceText(LocStart, 0,
"// ");
1040void RewriteObjC::RewriteTypeIntoString(
QualType T, std::string &ResultStr,
1060 ResultStr +=
T.getAsString(Context->getPrintingPolicy());
1065 std::string &ResultStr) {
1068 ResultStr +=
"\nstatic ";
1069 RewriteTypeIntoString(OMD->
getReturnType(), ResultStr, FPRetType);
1073 std::string NameStr;
1091 int len = selString.size();
1092 for (
int i = 0; i < len; i++)
1093 if (selString[i] ==
':')
1095 NameStr += selString;
1098 MethodInternalNames[OMD] = NameStr;
1099 ResultStr += NameStr;
1106 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1107 selfTy = Context->getPointerType(selfTy);
1108 if (!LangOpts.MicrosoftExt) {
1110 ResultStr +=
"struct ";
1117 ResultStr += Context->getObjCClassType().getAsString(
1118 Context->getPrintingPolicy());
1120 ResultStr +=
" self, ";
1121 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1122 ResultStr +=
" _cmd";
1125 for (
const auto *PDecl : OMD->
parameters()) {
1127 if (PDecl->getType()->isObjCQualifiedIdType()) {
1134 (void)convertBlockPointerToFunctionPointer(QT);
1140 ResultStr +=
", ...";
1149 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1150 if (i) ResultStr +=
", ";
1151 std::string ParamStr =
1152 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1153 ResultStr += ParamStr;
1155 if (FT->isVariadic()) {
1156 if (FT->getNumParams())
1167void RewriteObjC::RewriteImplementationDecl(
Decl *OID) {
1170 assert((IMD || CID) &&
"Unknown ImplementationDecl");
1177 std::string ResultStr;
1182 const char *startBuf =
SM->getCharacterData(LocStart);
1183 const char *endBuf =
SM->getCharacterData(LocEnd);
1184 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1190 std::string ResultStr;
1195 const char *startBuf =
SM->getCharacterData(LocStart);
1196 const char *endBuf =
SM->getCharacterData(LocEnd);
1197 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1200 RewritePropertyImplDecl(I, IMD, CID);
1206 std::string ResultStr;
1209 ResultStr =
"#ifndef _REWRITER_typedef_";
1212 ResultStr +=
"#define _REWRITER_typedef_";
1215 ResultStr +=
"typedef struct objc_object ";
1217 ResultStr +=
";\n#endif\n";
1221 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1226 RewriteMethodDeclaration(I);
1228 RewriteMethodDeclaration(I);
1248 DisableReplaceStmtScope S(*
this);
1254 Base = cast<OpaqueValueExpr>(
Base)->getSourceExpr();
1255 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(
Base));
1260 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1261 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1270 case ObjCMessageExpr::Class:
1271 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->
getType(),
1283 case ObjCMessageExpr::Instance:
1284 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->
getType(),
1296 case ObjCMessageExpr::SuperClass:
1297 case ObjCMessageExpr::SuperInstance:
1298 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->
getType(),
1313 Stmt *Replacement = SynthMessageExpr(NewMsg);
1314 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1330 DisableReplaceStmtScope S(*
this);
1335 Base = cast<OpaqueValueExpr>(
Base)->getSourceExpr();
1336 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(
Base));
1346 case ObjCMessageExpr::Class:
1347 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->
getType(),
1359 case ObjCMessageExpr::Instance:
1360 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->
getType(),
1372 case ObjCMessageExpr::SuperClass:
1373 case ObjCMessageExpr::SuperInstance:
1374 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->
getType(),
1389 Stmt *Replacement = SynthMessageExpr(NewMsg);
1390 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1403void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1404 buf +=
"((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1405 "id *, unsigned int))(void *)objc_msgSend)";
1407 buf +=
"((id)l_collection,\n\t\t";
1408 buf +=
"sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1410 buf +=
"&enumState, "
1411 "(id *)__rw_items, (unsigned int)16)";
1418 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1424 buf =
"goto __break_label_";
1425 buf += utostr(ObjCBcLabelNo.back());
1426 ReplaceText(startLoc, strlen(
"break"), buf);
1435 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1441 buf =
"goto __continue_label_";
1442 buf += utostr(ObjCBcLabelNo.back());
1443 ReplaceText(startLoc, strlen(
"continue"), buf);
1482 assert(!Stmts.empty() &&
"ObjCForCollectionStmt - Statement stack empty");
1483 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1484 "ObjCForCollectionStmt Statement stack mismatch");
1485 assert(!ObjCBcLabelNo.empty() &&
1486 "ObjCForCollectionStmt - Label No stack empty");
1489 const char *startBuf =
SM->getCharacterData(startLoc);
1490 StringRef elementName;
1491 std::string elementTypeAsString;
1494 if (
DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1496 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1497 QualType ElementType = cast<ValueDecl>(D)->getType();
1501 elementTypeAsString =
"id";
1503 elementTypeAsString = ElementType.
getAsString(Context->getPrintingPolicy());
1504 buf += elementTypeAsString;
1511 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1517 elementTypeAsString =
"id";
1523 buf +=
"struct __objcFastEnumerationState enumState = { 0 };\n\t";
1525 buf +=
"id __rw_items[16];\n\t";
1527 buf +=
"id l_collection = (id)";
1529 const char *startCollectionBuf = startBuf;
1530 startCollectionBuf += 3;
1531 startCollectionBuf = strchr(startCollectionBuf,
'(');
1532 startCollectionBuf++;
1534 while (*startCollectionBuf !=
' ' ||
1535 *(startCollectionBuf+1) !=
'i' || *(startCollectionBuf+2) !=
'n' ||
1536 (*(startCollectionBuf+3) !=
' ' &&
1537 *(startCollectionBuf+3) !=
'[' && *(startCollectionBuf+3) !=
'('))
1538 startCollectionBuf++;
1539 startCollectionBuf += 3;
1542 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1545 const char *rparenBuf =
SM->getCharacterData(rightParenLoc);
1560 buf +=
"unsigned long limit =\n\t\t";
1561 SynthCountByEnumWithState(buf);
1571 buf +=
"if (limit) {\n\t";
1572 buf +=
"unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1573 buf +=
"do {\n\t\t";
1574 buf +=
"unsigned long counter = 0;\n\t\t";
1575 buf +=
"do {\n\t\t\t";
1576 buf +=
"if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1577 buf +=
"objc_enumerationMutation(l_collection);\n\t\t\t";
1580 buf += elementTypeAsString;
1581 buf +=
")enumState.itemsPtr[counter++];";
1583 ReplaceText(lparenLoc, 1, buf);
1597 buf +=
"__continue_label_";
1598 buf += utostr(ObjCBcLabelNo.back());
1601 buf +=
"} while (counter < limit);\n\t";
1602 buf +=
"} while (limit = ";
1603 SynthCountByEnumWithState(buf);
1607 buf += elementTypeAsString;
1609 buf +=
"__break_label_";
1610 buf += utostr(ObjCBcLabelNo.back());
1613 buf +=
"else\n\t\t";
1616 buf += elementTypeAsString;
1622 if (isa<CompoundStmt>(S->getBody())) {
1624 InsertText(endBodyLoc, buf);
1633 const char *stmtBuf =
SM->getCharacterData(OrigEnd);
1634 const char *semiBuf = strchr(stmtBuf,
';');
1635 assert(semiBuf &&
"Can't find ';'");
1637 InsertText(endBodyLoc, buf);
1640 ObjCBcLabelNo.pop_back();
1653 const char *startBuf =
SM->getCharacterData(startLoc);
1655 assert((*startBuf ==
'@') &&
"bogus @synchronized location");
1658 buf =
"objc_sync_enter((id)";
1659 const char *lparenBuf = startBuf;
1660 while (*lparenBuf !=
'(') lparenBuf++;
1661 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1666 const char *endBuf =
SM->getCharacterData(endLoc);
1667 while (*endBuf !=
')') endBuf--;
1671 buf +=
"/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1672 buf +=
"int buf[18/*32-bit i386*/];\n";
1673 buf +=
"char *pointers[4];} _stack;\n";
1674 buf +=
"id volatile _rethrow = 0;\n";
1675 buf +=
"objc_exception_try_enter(&_stack);\n";
1676 buf +=
"if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1677 ReplaceText(rparenLoc, 1, buf);
1678 startLoc = S->getSynchBody()->getEndLoc();
1679 startBuf =
SM->getCharacterData(startLoc);
1681 assert((*startBuf ==
'}') &&
"bogus @synchronized block");
1683 buf =
"}\nelse {\n";
1684 buf +=
" _rethrow = objc_exception_extract(&_stack);\n";
1686 buf +=
"{ /* implicit finally clause */\n";
1687 buf +=
" if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1689 std::string syncBuf;
1690 syncBuf +=
" objc_sync_exit(";
1692 Expr *syncExpr = S->getSynchExpr();
1696 ? CK_BlockPointerToObjCPointerCast
1697 : CK_CPointerToObjCPointerCast;
1698 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1700 std::string syncExprBufS;
1701 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1702 assert(syncExpr !=
nullptr &&
"Expected non-null Expr");
1704 syncBuf += syncExprBuf.str();
1708 buf +=
"\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1712 ReplaceText(lastCurlyLoc, 1, buf);
1714 bool hasReturns =
false;
1715 HasReturnStmts(S->getSynchBody(), hasReturns);
1717 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1722void RewriteObjC::WarnAboutReturnGotoStmts(
Stmt *S)
1725 for (
Stmt *SubStmt : S->children())
1727 WarnAboutReturnGotoStmts(SubStmt);
1729 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1730 Diags.
Report(Context->getFullLoc(S->getBeginLoc()),
1731 TryFinallyContainsReturnDiag);
1735void RewriteObjC::HasReturnStmts(
Stmt *S,
bool &hasReturns)
1738 for (
Stmt *SubStmt : S->children())
1740 HasReturnStmts(SubStmt, hasReturns);
1742 if (isa<ReturnStmt>(S))
1746void RewriteObjC::RewriteTryReturnStmts(
Stmt *S) {
1748 for (
Stmt *SubStmt : S->children())
1750 RewriteTryReturnStmts(SubStmt);
1752 if (isa<ReturnStmt>(S)) {
1754 const char *startBuf =
SM->getCharacterData(startLoc);
1755 const char *semiBuf = strchr(startBuf,
';');
1756 assert((*semiBuf ==
';') &&
"RewriteTryReturnStmts: can't find ';'");
1760 buf =
"{ objc_exception_try_exit(&_stack); return";
1762 ReplaceText(startLoc, 6, buf);
1763 InsertText(onePastSemiLoc,
"}");
1767void RewriteObjC::RewriteSyncReturnStmts(
Stmt *S, std::string syncExitBuf) {
1769 for (
Stmt *SubStmt : S->children())
1771 RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1773 if (isa<ReturnStmt>(S)) {
1775 const char *startBuf =
SM->getCharacterData(startLoc);
1777 const char *semiBuf = strchr(startBuf,
';');
1778 assert((*semiBuf ==
';') &&
"RewriteSyncReturnStmts: can't find ';'");
1782 buf =
"{ objc_exception_try_exit(&_stack);";
1786 ReplaceText(startLoc, 6, buf);
1787 InsertText(onePastSemiLoc,
"}");
1794 const char *startBuf =
SM->getCharacterData(startLoc);
1796 assert((*startBuf ==
'@') &&
"bogus @try location");
1800 buf =
"/* @try scope begin */ { struct _objc_exception_data {\n";
1801 buf +=
"int buf[18/*32-bit i386*/];\n";
1802 buf +=
"char *pointers[4];} _stack;\n";
1803 buf +=
"id volatile _rethrow = 0;\n";
1804 buf +=
"objc_exception_try_enter(&_stack);\n";
1805 buf +=
"if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1807 ReplaceText(startLoc, 4, buf);
1809 startLoc = S->getTryBody()->getEndLoc();
1810 startBuf =
SM->getCharacterData(startLoc);
1812 assert((*startBuf ==
'}') &&
"bogus @try block");
1815 if (S->getNumCatchStmts()) {
1817 buf =
" /* @catch begin */ else {\n";
1818 buf +=
" id _caught = objc_exception_extract(&_stack);\n";
1819 buf +=
" objc_exception_try_enter (&_stack);\n";
1820 buf +=
" if (_setjmp(_stack.buf))\n";
1821 buf +=
" _rethrow = objc_exception_extract(&_stack);\n";
1822 buf +=
" else { /* @catch continue */";
1824 InsertText(startLoc, buf);
1826 buf =
"}\nelse {\n";
1827 buf +=
" _rethrow = objc_exception_extract(&_stack);\n";
1829 ReplaceText(lastCurlyLoc, 1, buf);
1831 Stmt *lastCatchBody =
nullptr;
1832 for (
unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1841 startBuf =
SM->getCharacterData(startLoc);
1843 assert((*startBuf ==
'@') &&
"bogus @catch location");
1845 const char *lParenLoc = strchr(startBuf,
'(');
1851 const char *bodyBuf =
SM->getCharacterData(bodyLoc);
1853 "bogus @catch paren location");
1854 assert((*bodyBuf ==
'{') &&
"bogus @catch body location");
1856 buf +=
"1) { id _tmp = _caught;";
1857 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1858 }
else if (catchDecl) {
1860 if (t == Context->getObjCIdType()) {
1862 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1868 buf +=
"objc_exception_match((struct objc_class *)objc_getClass(\"";
1870 buf +=
"\"), (struct objc_object *)_caught)) { ";
1871 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1878 const char *bodyBuf =
SM->getCharacterData(bodyLoc);
1879 const char *rParenBuf =
SM->getCharacterData(rParenLoc);
1880 assert((*rParenBuf ==
')') &&
"bogus @catch paren location");
1881 assert((*bodyBuf ==
'{') &&
"bogus @catch body location");
1885 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
" = _caught;");
1887 llvm_unreachable(
"@catch rewrite bug");
1891 if (lastCatchBody) {
1893 assert(*
SM->getCharacterData(bodyLoc) ==
'}' &&
1894 "bogus @catch body location");
1898 buf =
"} /* last catch end */\n";
1900 buf +=
" _rethrow = _caught;\n";
1901 buf +=
" objc_exception_try_exit(&_stack);\n";
1902 buf +=
"} } /* @catch end */\n";
1903 if (!S->getFinallyStmt())
1905 InsertText(bodyLoc, buf);
1908 lastCurlyLoc = lastCatchBody->
getEndLoc();
1911 startLoc = finalStmt->getBeginLoc();
1912 startBuf =
SM->getCharacterData(startLoc);
1913 assert((*startBuf ==
'@') &&
"bogus @finally start");
1915 ReplaceText(startLoc, 8,
"/* @finally */");
1917 Stmt *body = finalStmt->getFinallyBody();
1920 assert(*
SM->getCharacterData(startLoc) ==
'{' &&
1921 "bogus @finally body location");
1922 assert(*
SM->getCharacterData(endLoc) ==
'}' &&
1923 "bogus @finally body location");
1926 InsertText(startLoc,
" if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1928 InsertText(endLoc,
" if (_rethrow) objc_exception_throw(_rethrow);\n");
1934 WarnAboutReturnGotoStmts(S->getTryBody());
1936 buf =
"{ /* implicit finally clause */\n";
1937 buf +=
" if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1938 buf +=
" if (_rethrow) objc_exception_throw(_rethrow);\n";
1940 ReplaceText(lastCurlyLoc, 1, buf);
1945 bool hasReturns =
false;
1946 HasReturnStmts(S->getTryBody(), hasReturns);
1948 RewriteTryReturnStmts(S->getTryBody());
1952 InsertText(lastCurlyLoc,
" } /* @try scope end */\n");
1962 const char *startBuf =
SM->getCharacterData(startLoc);
1964 assert((*startBuf ==
'@') &&
"bogus @throw location");
1968 if (S->getThrowExpr())
1969 buf =
"objc_exception_throw(";
1971 buf =
"objc_exception_throw(_caught";
1974 const char *wBuf = strchr(startBuf,
'w');
1975 assert((*wBuf ==
'w') &&
"@throw: can't find 'w'");
1976 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1978 const char *semiBuf = strchr(startBuf,
';');
1979 assert((*semiBuf ==
';') &&
"@throw: can't find ';'");
1981 ReplaceText(semiLoc, 1,
");");
1987 std::string StrEncoding;
1988 Context->getObjCEncodingForType(Exp->
getEncodedType(), StrEncoding);
1989 Expr *Replacement = getStringLiteral(StrEncoding);
1990 ReplaceStmt(Exp, Replacement);
1998 if (!SelGetUidFunctionDecl)
1999 SynthSelGetUidFunctionDecl();
2000 assert(SelGetUidFunctionDecl &&
"Can't find sel_registerName() decl");
2004 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2006 ReplaceStmt(Exp, SelExp);
2012RewriteObjC::SynthesizeCallToFunctionDecl(
FunctionDecl *FD,
2024 QualType pToFunc = Context->getPointerType(msgSendType);
2026 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2032 CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2037static bool scanForProtocolRefs(
const char *startBuf,
const char *endBuf,
2038 const char *&startRef,
const char *&endRef) {
2039 while (startBuf < endBuf) {
2040 if (*startBuf ==
'<')
2041 startRef = startBuf;
2042 if (*startBuf ==
'>') {
2043 if (startRef && *startRef ==
'<') {
2054static void scanToNextArgument(
const char *&argRef) {
2056 while (*argRef !=
')' && (*argRef !=
',' || angle > 0)) {
2059 else if (*argRef ==
'>')
2063 assert(angle == 0 &&
"scanToNextArgument - bad protocol type syntax");
2066bool RewriteObjC::needToScanForQualifiers(
QualType T) {
2078 QualType ElemTy = Context->getBaseElementType(T);
2079 return needToScanForQualifiers(ElemTy);
2084void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(
Expr *E) {
2086 if (needToScanForQualifiers(
Type)) {
2090 Loc = ECE->getLParenLoc();
2091 EndLoc = ECE->getRParenLoc();
2100 const char *startBuf =
SM->getCharacterData(Loc);
2101 const char *endBuf =
SM->getCharacterData(EndLoc);
2102 const char *startRef =
nullptr, *endRef =
nullptr;
2103 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2108 InsertText(LessLoc,
"/*");
2109 InsertText(GreaterLoc,
"*/");
2114void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(
Decl *Dcl) {
2118 if (
VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2122 else if (
FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2127 assert(funcType &&
"missing function type");
2128 proto = dyn_cast<FunctionProtoType>(funcType);
2133 else if (
FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2140 if (needToScanForQualifiers(
Type)) {
2143 const char *endBuf =
SM->getCharacterData(Loc);
2144 const char *startBuf = endBuf;
2145 while (*startBuf !=
';' && *startBuf !=
'<' && startBuf != MainFileStart)
2147 const char *startRef =
nullptr, *endRef =
nullptr;
2148 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2153 InsertText(LessLoc,
"/*");
2154 InsertText(GreaterLoc,
"*/");
2160 const char *startBuf =
SM->getCharacterData(Loc);
2161 const char *startFuncBuf = startBuf;
2166 const char *endBuf = startBuf;
2168 scanToNextArgument(endBuf);
2169 const char *startRef =
nullptr, *endRef =
nullptr;
2170 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2177 InsertText(LessLoc,
"/*");
2178 InsertText(GreaterLoc,
"*/");
2180 startBuf = ++endBuf;
2185 while (*startBuf && *startBuf !=
')' && *startBuf !=
',')
2192void RewriteObjC::RewriteTypeOfDecl(
VarDecl *ND) {
2195 if (!isa<TypeOfExprType>(TypePtr))
2197 while (isa<TypeOfExprType>(TypePtr)) {
2198 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2204 std::string TypeAsString(QT.
getAsString(Context->getPrintingPolicy()));
2206 const char *startBuf =
SM->getCharacterData(DeclLoc);
2209 TypeAsString +=
" " + Name +
" = ";
2213 startLoc = ECE->getLParenLoc();
2216 startLoc =
SM->getExpansionLoc(startLoc);
2217 const char *endBuf =
SM->getCharacterData(startLoc);
2218 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2222 X =
SM->getExpansionLoc(
X);
2223 const char *endBuf =
SM->getCharacterData(
X);
2224 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2229void RewriteObjC::SynthSelGetUidFunctionDecl() {
2230 IdentifierInfo *SelGetUidIdent = &Context->Idents.get(
"sel_registerName");
2232 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2234 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2235 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2238 SelGetUidIdent, getFuncType,
2239 nullptr, SC_Extern);
2242void RewriteObjC::RewriteFunctionDecl(
FunctionDecl *FD) {
2245 FD->
getName() ==
"sel_registerName") {
2246 SelGetUidFunctionDecl = FD;
2249 RewriteObjCQualifiedInterfaceTypes(FD);
2252void RewriteObjC::RewriteBlockPointerType(std::string& Str,
QualType Type) {
2253 std::string TypeString(
Type.getAsString(Context->getPrintingPolicy()));
2254 const char *argPtr = TypeString.c_str();
2255 if (!strchr(argPtr,
'^')) {
2260 Str += (*argPtr ==
'^' ?
'*' : *argPtr);
2266void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2269 std::string TypeString(
Type.getAsString(Context->getPrintingPolicy()));
2270 const char *argPtr = TypeString.c_str();
2295void RewriteObjC::RewriteBlockLiteralFunctionDecl(
FunctionDecl *FD) {
2302 std::string FdStr =
Type.getAsString(Context->getPrintingPolicy());
2306 unsigned numArgs = proto->getNumParams();
2307 for (
unsigned i = 0; i < numArgs; i++) {
2308 QualType ArgType = proto->getParamType(i);
2309 RewriteBlockPointerType(FdStr, ArgType);
2314 InsertText(FunLocStart, FdStr);
2315 CurFunctionDeclToDeclareForBlock =
nullptr;
2319void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2320 if (SuperConstructorFunctionDecl)
2322 IdentifierInfo *msgSendIdent = &Context->Idents.get(
"__rw_objc_super");
2324 QualType argT = Context->getObjCIdType();
2325 assert(!argT.
isNull() &&
"Can't find 'id' type");
2326 ArgTys.push_back(argT);
2327 ArgTys.push_back(argT);
2328 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2330 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2333 msgSendIdent, msgSendType,
2334 nullptr, SC_Extern);
2338void RewriteObjC::SynthMsgSendFunctionDecl() {
2339 IdentifierInfo *msgSendIdent = &Context->Idents.get(
"objc_msgSend");
2341 QualType argT = Context->getObjCIdType();
2342 assert(!argT.
isNull() &&
"Can't find 'id' type");
2343 ArgTys.push_back(argT);
2344 argT = Context->getObjCSelType();
2345 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2346 ArgTys.push_back(argT);
2347 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2349 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2352 msgSendIdent, msgSendType,
2353 nullptr, SC_Extern);
2357void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2358 IdentifierInfo *msgSendIdent = &Context->Idents.get(
"objc_msgSendSuper");
2360 RecordDecl *RD = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
2362 &Context->Idents.get(
"objc_super"));
2363 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2364 assert(!argT.
isNull() &&
"Can't build 'struct objc_super *' type");
2365 ArgTys.push_back(argT);
2366 argT = Context->getObjCSelType();
2367 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2368 ArgTys.push_back(argT);
2369 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2371 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2374 msgSendIdent, msgSendType,
2375 nullptr, SC_Extern);
2379void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2380 IdentifierInfo *msgSendIdent = &Context->Idents.get(
"objc_msgSend_stret");
2382 QualType argT = Context->getObjCIdType();
2383 assert(!argT.
isNull() &&
"Can't find 'id' type");
2384 ArgTys.push_back(argT);
2385 argT = Context->getObjCSelType();
2386 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2387 ArgTys.push_back(argT);
2388 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2390 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2393 msgSendIdent, msgSendType,
2394 nullptr, SC_Extern);
2399void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2401 &Context->Idents.get(
"objc_msgSendSuper_stret");
2403 RecordDecl *RD = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
2405 &Context->Idents.get(
"objc_super"));
2406 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2407 assert(!argT.
isNull() &&
"Can't build 'struct objc_super *' type");
2408 ArgTys.push_back(argT);
2409 argT = Context->getObjCSelType();
2410 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2411 ArgTys.push_back(argT);
2412 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2414 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2418 msgSendType,
nullptr,
2423void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2424 IdentifierInfo *msgSendIdent = &Context->Idents.get(
"objc_msgSend_fpret");
2426 QualType argT = Context->getObjCIdType();
2427 assert(!argT.
isNull() &&
"Can't find 'id' type");
2428 ArgTys.push_back(argT);
2429 argT = Context->getObjCSelType();
2430 assert(!argT.
isNull() &&
"Can't find 'SEL' type");
2431 ArgTys.push_back(argT);
2432 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2434 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2437 msgSendIdent, msgSendType,
2438 nullptr, SC_Extern);
2442void RewriteObjC::SynthGetClassFunctionDecl() {
2443 IdentifierInfo *getClassIdent = &Context->Idents.get(
"objc_getClass");
2445 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2446 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2448 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2451 getClassIdent, getClassType,
2452 nullptr, SC_Extern);
2456void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2458 &Context->Idents.get(
"class_getSuperclass");
2460 ArgTys.push_back(Context->getObjCClassType());
2461 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2463 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2467 getClassType,
nullptr,
2472void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2473 IdentifierInfo *getClassIdent = &Context->Idents.get(
"objc_getMetaClass");
2475 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2476 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2478 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2481 getClassIdent, getClassType,
2482 nullptr, SC_Extern);
2486 assert(Exp !=
nullptr &&
"Expected non-null ObjCStringLiteral");
2487 QualType strType = getConstantStringStructType();
2489 std::string S =
"__NSConstantStringImpl_";
2491 std::string tmpName = InFileName;
2493 for (i=0; i < tmpName.length(); i++) {
2494 char c = tmpName.at(i);
2501 S += utostr(NumObjCStringLiterals++);
2503 Preamble +=
"static __NSConstantStringImpl " + S;
2504 Preamble +=
" __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2507 std::string prettyBufS;
2508 llvm::raw_string_ostream prettyBuf(prettyBufS);
2516 strType,
nullptr, SC_Static);
2519 Expr *Unop = UnaryOperator::Create(
2520 const_cast<ASTContext &
>(*Context), DRE, UO_AddrOf,
2521 Context->getPointerType(DRE->
getType()), VK_PRValue, OK_Ordinary,
2525 CK_CPointerToObjCPointerCast, Unop);
2526 ReplaceStmt(Exp, cast);
2532QualType RewriteObjC::getSuperStructType() {
2533 if (!SuperStructDecl) {
2534 SuperStructDecl = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
2536 &Context->Idents.get(
"objc_super"));
2540 FieldTypes[0] = Context->getObjCIdType();
2542 FieldTypes[1] = Context->getObjCClassType();
2545 for (
unsigned i = 0; i < 2; ++i) {
2546 SuperStructDecl->
addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2549 FieldTypes[i],
nullptr,
2557 return Context->getTagDeclType(SuperStructDecl);
2560QualType RewriteObjC::getConstantStringStructType() {
2561 if (!ConstantStringDecl) {
2562 ConstantStringDecl = RecordDecl::Create(
2564 SourceLocation(), &Context->Idents.get(
"__NSConstantStringImpl"));
2568 FieldTypes[0] = Context->getObjCIdType();
2570 FieldTypes[1] = Context->IntTy;
2572 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2574 FieldTypes[3] = Context->LongTy;
2577 for (
unsigned i = 0; i < 4; ++i) {
2578 ConstantStringDecl->
addDecl(FieldDecl::Create(*Context,
2582 FieldTypes[i],
nullptr,
2590 return Context->getTagDeclType(ConstantStringDecl);
2601 new (Context)
DeclRefExpr(*Context, MsgSendStretFlavor,
false,
2605 Context->getPointerType(Context->VoidTy),
2608 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2611 castType = Context->getPointerType(castType);
2612 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2620 CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue,
2628 if (!SelGetUidFunctionDecl)
2629 SynthSelGetUidFunctionDecl();
2630 if (!MsgSendFunctionDecl)
2631 SynthMsgSendFunctionDecl();
2632 if (!MsgSendSuperFunctionDecl)
2633 SynthMsgSendSuperFunctionDecl();
2634 if (!MsgSendStretFunctionDecl)
2635 SynthMsgSendStretFunctionDecl();
2636 if (!MsgSendSuperStretFunctionDecl)
2637 SynthMsgSendSuperStretFunctionDecl();
2638 if (!MsgSendFpretFunctionDecl)
2639 SynthMsgSendFpretFunctionDecl();
2640 if (!GetClassFunctionDecl)
2641 SynthGetClassFunctionDecl();
2642 if (!GetSuperClassFunctionDecl)
2643 SynthGetSuperClassFunctionDecl();
2644 if (!GetMetaClassFunctionDecl)
2645 SynthGetMetaClassFunctionDecl();
2652 QualType resultType = mDecl->getReturnType();
2654 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2656 MsgSendFlavor = MsgSendFpretFunctionDecl;
2662 case ObjCMessageExpr::SuperClass: {
2663 MsgSendFlavor = MsgSendSuperFunctionDecl;
2664 if (MsgSendStretFlavor)
2665 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2666 assert(MsgSendFlavor &&
"MsgSendFlavor is NULL!");
2673 InitExprs.push_back(NoTypeInfoCStyleCastExpr(
2674 Context, Context->getObjCIdType(), CK_BitCast,
2676 Context->getObjCIdType(), VK_PRValue,
2682 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2683 ClsExprs, StartLoc, EndLoc);
2685 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2686 Context->getObjCClassType(),
2689 ClsExprs.push_back(ArgExpr);
2690 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2694 InitExprs.push_back(
2695 NoTypeInfoCStyleCastExpr(Context,
2696 Context->getObjCIdType(),
2699 QualType superType = getSuperStructType();
2702 if (LangOpts.MicrosoftExt) {
2703 SynthSuperConstructorFunctionDecl();
2706 DeclRefExpr(*Context, SuperConstructorFunctionDecl,
false, superType,
2709 CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
2717 SuperRep = UnaryOperator::Create(
2718 const_cast<ASTContext &
>(*Context), SuperRep, UO_AddrOf,
2719 Context->getPointerType(SuperRep->
getType()), VK_PRValue, OK_Ordinary,
2721 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2722 Context->getPointerType(superType),
2723 CK_BitCast, SuperRep);
2730 = Context->getTrivialTypeSourceInfo(superType);
2735 SuperRep = UnaryOperator::Create(
2736 const_cast<ASTContext &
>(*Context), SuperRep, UO_AddrOf,
2737 Context->getPointerType(SuperRep->
getType()), VK_PRValue, OK_Ordinary,
2740 MsgExprs.push_back(SuperRep);
2744 case ObjCMessageExpr::Class: {
2749 ClsExprs.push_back(getStringLiteral(clsName->
getName()));
2750 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2752 MsgExprs.push_back(Cls);
2756 case ObjCMessageExpr::SuperInstance:{
2757 MsgSendFlavor = MsgSendSuperFunctionDecl;
2758 if (MsgSendStretFlavor)
2759 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2760 assert(MsgSendFlavor &&
"MsgSendFlavor is NULL!");
2764 InitExprs.push_back(NoTypeInfoCStyleCastExpr(
2765 Context, Context->getObjCIdType(), CK_BitCast,
2767 Context->getObjCIdType(), VK_PRValue,
2773 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2776 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2777 Context->getObjCClassType(),
2780 ClsExprs.push_back(ArgExpr);
2781 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2786 InitExprs.push_back(
2788 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2791 QualType superType = getSuperStructType();
2794 if (LangOpts.MicrosoftExt) {
2795 SynthSuperConstructorFunctionDecl();
2798 DeclRefExpr(*Context, SuperConstructorFunctionDecl,
false, superType,
2801 CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
2809 SuperRep = UnaryOperator::Create(
2810 const_cast<ASTContext &
>(*Context), SuperRep, UO_AddrOf,
2811 Context->getPointerType(SuperRep->
getType()), VK_PRValue, OK_Ordinary,
2813 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2814 Context->getPointerType(superType),
2815 CK_BitCast, SuperRep);
2822 = Context->getTrivialTypeSourceInfo(superType);
2826 MsgExprs.push_back(SuperRep);
2830 case ObjCMessageExpr::Instance: {
2835 recExpr = CE->getSubExpr();
2838 ? CK_BlockPointerToObjCPointerCast
2839 : CK_CPointerToObjCPointerCast;
2841 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2843 MsgExprs.push_back(recExpr);
2851 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2852 SelExprs, StartLoc, EndLoc);
2853 MsgExprs.push_back(SelExp);
2856 for (
unsigned i = 0; i < Exp->
getNumArgs(); i++) {
2862 if (needToScanForQualifiers(type))
2863 type = Context->getObjCIdType();
2865 (void)convertBlockPointerToFunctionPointer(type);
2869 type->isBooleanType()) {
2870 CK = CK_IntegralToBoolean;
2871 }
else if (
type->isObjCObjectPointerType()) {
2873 CK = CK_BlockPointerToObjCPointerCast;
2875 CK = CK_CPointerToObjCPointerCast;
2883 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2886 else if (
CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2887 if (CE->getType()->isObjCQualifiedIdType()) {
2888 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2889 userExpr = CE->getSubExpr();
2892 CK = CK_IntegralToPointer;
2894 CK = CK_BlockPointerToObjCPointerCast;
2896 CK = CK_CPointerToObjCPointerCast;
2900 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2904 MsgExprs.push_back(userExpr);
2916 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2917 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2919 ArgTypes.push_back(Context->getObjCIdType());
2920 ArgTypes.push_back(Context->getObjCSelType());
2925 ? Context->getObjCIdType()
2928 (void)convertBlockPointerToFunctionPointer(t);
2929 ArgTypes.push_back(t);
2932 convertToUnqualifiedObjCType(returnType);
2933 (void)convertBlockPointerToFunctionPointer(returnType);
2935 returnType = Context->getObjCIdType();
2942 *Context, MsgSendFlavor,
false, msgSendType, VK_LValue,
SourceLocation());
2948 cast = NoTypeInfoCStyleCastExpr(Context,
2949 Context->getPointerType(Context->VoidTy),
2956 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->
isVariadic() :
true);
2957 castType = Context->getPointerType(castType);
2958 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2965 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2967 Stmt *ReplacingStmt = CE;
2968 if (MsgSendStretFlavor) {
2974 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2975 msgSendType, returnType,
2982 Context->getTrivialTypeSourceInfo(returnType),
2990 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2992 llvm::APInt(IntSize, 8),
2996 *Context, sizeofExpr, limit, BO_LE, Context->IntTy, VK_PRValue,
3006 return ReplacingStmt;
3010 Stmt *ReplacingStmt =
3014 ReplaceStmt(Exp, ReplacingStmt);
3017 return ReplacingStmt;
3021QualType RewriteObjC::getProtocolType() {
3022 if (!ProtocolTypeDecl) {
3024 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3025 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3027 &Context->Idents.get(
"Protocol"),
3030 return Context->getTypeDeclType(ProtocolTypeDecl);
3042 nullptr, SC_Extern);
3045 Expr *DerefExpr = UnaryOperator::Create(
3046 const_cast<ASTContext &
>(*Context), DRE, UO_AddrOf,
3047 Context->getPointerType(DRE->
getType()), VK_PRValue, OK_Ordinary,
3052 ReplaceStmt(Exp, castExpr);
3058bool RewriteObjC::BufferContainsPPDirectives(
const char *startBuf,
3059 const char *endBuf) {
3060 while (startBuf < endBuf) {
3061 if (*startBuf ==
'#') {
3063 for (++startBuf; startBuf[0] ==
' ' || startBuf[0] ==
'\t'; ++startBuf)
3065 if (!strncmp(startBuf,
"if", strlen(
"if")) ||
3066 !strncmp(startBuf,
"ifdef", strlen(
"ifdef")) ||
3067 !strncmp(startBuf,
"ifndef", strlen(
"ifndef")) ||
3068 !strncmp(startBuf,
"define", strlen(
"define")) ||
3069 !strncmp(startBuf,
"undef", strlen(
"undef")) ||
3070 !strncmp(startBuf,
"else", strlen(
"else")) ||
3071 !strncmp(startBuf,
"elif", strlen(
"elif")) ||
3072 !strncmp(startBuf,
"endif", strlen(
"endif")) ||
3073 !strncmp(startBuf,
"pragma", strlen(
"pragma")) ||
3074 !strncmp(startBuf,
"include", strlen(
"include")) ||
3075 !strncmp(startBuf,
"import", strlen(
"import")) ||
3076 !strncmp(startBuf,
"include_next", strlen(
"include_next")))
3087 std::string &Result) {
3088 assert(CDecl &&
"Class missing in SynthesizeObjCInternalStruct");
3089 assert(CDecl->
getName() !=
"" &&
3090 "Name missing in SynthesizeObjCInternalStruct");
3092 if (ObjCSynthesizedStructs.count(CDecl))
3099 const char *startBuf =
SM->getCharacterData(LocStart);
3100 const char *endBuf =
SM->getCharacterData(LocEnd);
3105 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3106 endBuf += Lexer::MeasureTokenLength(LocEnd, *
SM, LangOpts);
3107 ReplaceText(LocStart, endBuf-startBuf, Result);
3113 Result +=
"\nstruct ";
3115 if (LangOpts.MicrosoftExt)
3119 const char *cursor = strchr(startBuf,
'{');
3120 assert((cursor && endBuf)
3121 &&
"SynthesizeObjCInternalStruct - malformed @interface");
3137 if (BufferContainsPPDirectives(startBuf, cursor)) {
3140 const char *endHeader =
SM->getCharacterData(L);
3141 endHeader += Lexer::MeasureTokenLength(L, *
SM, LangOpts);
3145 while (endHeader < cursor && *endHeader !=
'>') endHeader++;
3149 ReplaceText(LocStart, endHeader-startBuf, Result);
3152 ReplaceText(LocStart, cursor-startBuf, Result);
3154 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3155 Result =
"\n struct ";
3159 Result +=
"_IVARS;\n";
3164 InsertText(OnePastCurly, Result);
3169 while (cursor < endBuf) {
3170 if (*cursor ==
'@') {
3173 for (++cursor; cursor[0] ==
' ' || cursor[0] ==
'\t'; ++cursor)
3178 if (!strncmp(cursor,
"public", strlen(
"public")) ||
3179 !strncmp(cursor,
"private", strlen(
"private")) ||
3180 !strncmp(cursor,
"package", strlen(
"package")) ||
3181 !strncmp(cursor,
"protected", strlen(
"protected")))
3182 InsertText(atLoc,
"// ");
3187 else if (*cursor ==
'<') {
3189 InsertText(atLoc,
"/* ");
3190 cursor = strchr(cursor,
'>');
3193 InsertText(atLoc,
" */");
3194 }
else if (*cursor ==
'^') {
3196 ReplaceText(caretLoc, 1,
"*");
3203 endBuf += Lexer::MeasureTokenLength(LocEnd, *
SM, LangOpts);
3204 Result +=
" {\n struct ";
3208 Result +=
"_IVARS;\n};\n";
3209 ReplaceText(LocStart, endBuf-startBuf, Result);
3212 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3213 llvm_unreachable(
"struct already synthesize- SynthesizeObjCInternalStruct");
3223void RewriteObjC::RewriteImplementations() {
3224 int ClsDefCount = ClassImplementation.size();
3225 int CatDefCount = CategoryImplementation.size();
3228 for (
int i = 0; i < ClsDefCount; i++)
3229 RewriteImplementationDecl(ClassImplementation[i]);
3231 for (
int i = 0; i < CatDefCount; i++)
3232 RewriteImplementationDecl(CategoryImplementation[i]);
3235void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3236 const std::string &Name,
3238 assert(BlockByRefDeclNo.count(VD) &&
3239 "RewriteByRefString: ByRef decl missing");
3241 ResultStr +=
"struct ";
3242 ResultStr +=
"__Block_byref_" + Name +
3243 "_" + utostr(BlockByRefDeclNo[VD]) ;
3246static bool HasLocalVariableExternalStorage(
ValueDecl *VD) {
3247 if (
VarDecl *Var = dyn_cast<VarDecl>(VD))
3248 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3252std::string RewriteObjC::SynthesizeBlockFunc(
BlockExpr *CE,
int i,
3257 std::string StructRef =
"struct " + Tag;
3258 std::string S =
"static " + RT.
getAsString(Context->getPrintingPolicy()) +
" __" +
3259 funcName.str() +
"_" +
"block_func_" + utostr(i);
3263 if (isa<FunctionNoProtoType>(AFT)) {
3266 S +=
"(" + StructRef +
" *__cself)";
3268 S +=
"(" + StructRef +
" *__cself)";
3271 assert(FT &&
"SynthesizeBlockFunc: No function proto");
3274 S += StructRef +
" *__cself, ";
3275 std::string ParamStr;
3279 ParamStr = (*AI)->getNameAsString();
3281 (void)convertBlockPointerToFunctionPointer(QT);
3296 E = BlockByRefDecls.end(); I != E; ++I) {
3298 std::string Name = (*I)->getNameAsString();
3299 std::string TypeString;
3300 RewriteByRefString(TypeString, Name, (*I));
3302 Name = TypeString + Name;
3303 S += Name +
" = __cself->" + (*I)->getNameAsString() +
"; // bound by ref\n";
3307 E = BlockByCopyDecls.end(); I != E; ++I) {
3319 if (isTopLevelBlockPointerType((*I)->getType())) {
3320 RewriteBlockPointerTypeVariable(S, (*I));
3322 RewriteBlockPointerType(S, (*I)->getType());
3324 S +=
"__cself->" + (*I)->getNameAsString() +
"; // bound by copy\n";
3327 std::string Name = (*I)->getNameAsString();
3329 if (HasLocalVariableExternalStorage(*I))
3330 QT = Context->getPointerType(QT);
3332 S += Name +
" = __cself->" +
3333 (*I)->getNameAsString() +
"; // bound by copy\n";
3336 std::string RewrittenStr = RewrittenBlockExprs[CE];
3337 const char *cstr = RewrittenStr.c_str();
3338 while (*cstr++ !=
'{') ;
3344std::string RewriteObjC::SynthesizeBlockHelperFuncs(
BlockExpr *CE,
int i,
3347 std::string StructRef =
"struct " + Tag;
3348 std::string S =
"static void __";
3351 S +=
"_block_copy_" + utostr(i);
3352 S +=
"(" + StructRef;
3353 S +=
"*dst, " + StructRef;
3355 for (
ValueDecl *VD : ImportedBlockDecls) {
3356 S +=
"_Block_object_assign((void*)&dst->";
3358 S +=
", (void*)src->";
3360 if (BlockByRefDeclsPtrSet.count(VD))
3361 S +=
", " + utostr(BLOCK_FIELD_IS_BYREF) +
"/*BLOCK_FIELD_IS_BYREF*/);";
3363 S +=
", " + utostr(BLOCK_FIELD_IS_BLOCK) +
"/*BLOCK_FIELD_IS_BLOCK*/);";
3365 S +=
", " + utostr(BLOCK_FIELD_IS_OBJECT) +
"/*BLOCK_FIELD_IS_OBJECT*/);";
3369 S +=
"\nstatic void __";
3371 S +=
"_block_dispose_" + utostr(i);
3372 S +=
"(" + StructRef;
3374 for (
ValueDecl *VD : ImportedBlockDecls) {
3375 S +=
"_Block_object_dispose((void*)src->";
3377 if (BlockByRefDeclsPtrSet.count(VD))
3378 S +=
", " + utostr(BLOCK_FIELD_IS_BYREF) +
"/*BLOCK_FIELD_IS_BYREF*/);";
3380 S +=
", " + utostr(BLOCK_FIELD_IS_BLOCK) +
"/*BLOCK_FIELD_IS_BLOCK*/);";
3382 S +=
", " + utostr(BLOCK_FIELD_IS_OBJECT) +
"/*BLOCK_FIELD_IS_OBJECT*/);";
3388std::string RewriteObjC::SynthesizeBlockImpl(
BlockExpr *CE, std::string Tag,
3390 std::string S =
"\nstruct " + Tag;
3393 S +=
" {\n struct __block_impl impl;\n";
3394 S +=
" struct " + Desc;
3401 if (BlockDeclRefs.size()) {
3404 E = BlockByCopyDecls.end(); I != E; ++I) {
3406 std::string FieldName = (*I)->getNameAsString();
3407 std::string ArgName =
"_" + FieldName;
3418 if (isTopLevelBlockPointerType((*I)->getType())) {
3419 S +=
"struct __block_impl *";
3423 if (HasLocalVariableExternalStorage(*I))
3424 QT = Context->getPointerType(QT);
3429 S += FieldName +
";\n";
3433 E = BlockByRefDecls.end(); I != E; ++I) {
3435 std::string FieldName = (*I)->getNameAsString();
3436 std::string ArgName =
"_" + FieldName;
3438 std::string TypeString;
3439 RewriteByRefString(TypeString, FieldName, (*I));
3441 FieldName = TypeString + FieldName;
3442 ArgName = TypeString + ArgName;
3445 S += FieldName +
"; // by ref\n";
3450 bool firsTime =
true;
3452 E = BlockByCopyDecls.end(); I != E; ++I) {
3453 std::string Name = (*I)->getNameAsString();
3460 if (isTopLevelBlockPointerType((*I)->getType()))
3461 Constructor += Name +
"((struct __block_impl *)_" + Name +
")";
3467 E = BlockByRefDecls.end(); I != E; ++I) {
3468 std::string Name = (*I)->getNameAsString();
3475 Constructor += Name +
"(_" + Name +
"->__forwarding)";
3480 Constructor +=
" impl.isa = &_NSConcreteGlobalBlock;\n";
3482 Constructor +=
" impl.isa = &_NSConcreteStackBlock;\n";
3483 Constructor +=
" impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3490 Constructor +=
" impl.isa = &_NSConcreteGlobalBlock;\n";
3492 Constructor +=
" impl.isa = &_NSConcreteStackBlock;\n";
3493 Constructor +=
" impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3503std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3504 std::string ImplTag,
int i,
3507 std::string S =
"\nstatic struct " + DescTag;
3509 S +=
" {\n unsigned long reserved;\n";
3510 S +=
" unsigned long Block_size;\n";
3512 S +=
" void (*copy)(struct ";
3513 S += ImplTag; S +=
"*, struct ";
3514 S += ImplTag; S +=
"*);\n";
3516 S +=
" void (*dispose)(struct ";
3517 S += ImplTag; S +=
"*);\n";
3521 S += DescTag +
"_DATA = { 0, sizeof(struct ";
3524 S +=
", __" + FunName.str() +
"_block_copy_" + utostr(i);
3525 S +=
", __" + FunName.str() +
"_block_dispose_" + utostr(i);
3531void RewriteObjC::SynthesizeBlockLiterals(
SourceLocation FunLocStart,
3532 StringRef FunName) {
3534 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3535 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3536 bool RewriteSC = (GlobalVarDecl &&
3541 std::string SC(
" void __");
3544 InsertText(FunLocStart, SC);
3548 for (
unsigned i = 0, count=0; i < Blocks.size(); i++) {
3549 CollectBlockDeclRefInfo(Blocks[i]);
3552 for (
int j = 0; j < InnerDeclRefsCount[i]; j++) {
3555 BlockDeclRefs.push_back(Exp);
3556 if (!VD->
hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3557 BlockByCopyDeclsPtrSet.insert(VD);
3558 BlockByCopyDecls.push_back(VD);
3560 if (VD->
hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3561 BlockByRefDeclsPtrSet.insert(VD);
3562 BlockByRefDecls.push_back(VD);
3566 if (VD->
hasAttr<BlocksAttr>() ||
3569 ImportedBlockDecls.insert(VD);
3572 std::string ImplTag =
"__" + FunName.str() +
"_block_impl_" + utostr(i);
3573 std::string DescTag =
"__" + FunName.str() +
"_block_desc_" + utostr(i);
3575 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3577 InsertText(FunLocStart, CI);
3579 std::string
CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3581 InsertText(FunLocStart, CF);
3583 if (ImportedBlockDecls.size()) {
3584 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3585 InsertText(FunLocStart, HF);
3587 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3588 ImportedBlockDecls.size() > 0);
3589 InsertText(FunLocStart, BD);
3591 BlockDeclRefs.clear();
3592 BlockByRefDecls.clear();
3593 BlockByRefDeclsPtrSet.clear();
3594 BlockByCopyDecls.clear();
3595 BlockByCopyDeclsPtrSet.clear();
3596 ImportedBlockDecls.clear();
3610 InsertText(FunLocStart, SC);
3614 InnerDeclRefsCount.clear();
3615 InnerDeclRefs.clear();
3616 RewrittenBlockExprs.clear();
3619void RewriteObjC::InsertBlockLiteralsWithinFunction(
FunctionDecl *FD) {
3621 StringRef FuncName = FD->
getName();
3623 SynthesizeBlockLiterals(FunLocStart, FuncName);
3626static void BuildUniqueMethodName(std::string &Name,
3629 Name = std::string(IFace->
getName());
3632 std::string::size_type loc = 0;
3633 while ((loc = Name.find(
':', loc)) != std::string::npos)
3634 Name.replace(loc, 1,
"_");
3637void RewriteObjC::InsertBlockLiteralsWithinMethod(
ObjCMethodDecl *MD) {
3641 std::string FuncName;
3642 BuildUniqueMethodName(FuncName, MD);
3643 SynthesizeBlockLiterals(FunLocStart, FuncName);
3646void RewriteObjC::GetBlockDeclRefExprs(
Stmt *S) {
3647 for (
Stmt *SubStmt : S->children())
3649 if (
BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3650 GetBlockDeclRefExprs(CBE->getBody());
3652 GetBlockDeclRefExprs(SubStmt);
3657 HasLocalVariableExternalStorage(DRE->
getDecl()))
3659 BlockDeclRefs.push_back(DRE);
3662void RewriteObjC::GetInnerBlockDeclRefExprs(
Stmt *S,
3664 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3665 for (
Stmt *SubStmt : S->children())
3667 if (
BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3668 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3669 GetInnerBlockDeclRefExprs(CBE->getBody(),
3674 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3677 if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3679 HasLocalVariableExternalStorage(DRE->
getDecl())) {
3681 InnerBlockDeclRefs.push_back(DRE);
3683 if (Var->isFunctionOrMethodVarDecl())
3684 ImportedLocalExternalDecls.insert(Var);
3699 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3705 if (convertBlockPointerToFunctionPointer(t))
3706 HasBlockType =
true;
3707 ArgTypes.push_back(t);
3714 FuncType = getSimpleFunctionType(Res, ArgTypes);
3719Stmt *RewriteObjC::SynthesizeBlockCall(
CallExpr *Exp,
const Expr *BlockExp) {
3723 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3725 }
else if (
const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3728 else if (
const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3729 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3731 else if (
const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3734 dyn_cast<ConditionalOperator>(BlockExp)) {
3735 Expr *LHSExp = CEXPR->getLHS();
3736 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3737 Expr *RHSExp = CEXPR->getRHS();
3738 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3739 Expr *CONDExp = CEXPR->getCond();
3744 }
else if (
const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3747 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3750 assert(
false &&
"RewriteBlockClass: Bad type");
3752 assert(CPT &&
"RewriteBlockClass: Bad type");
3754 assert(FT &&
"RewriteBlockClass: Bad type");
3758 RecordDecl *RD = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
3760 &Context->Idents.get(
"__block_impl"));
3761 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3767 ArgTypes.push_back(PtrBlock);
3772 if (!convertBlockPointerToFunctionPointer(t))
3773 convertToUnqualifiedObjCType(t);
3774 ArgTypes.push_back(t);
3778 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->
getType(), ArgTypes);
3780 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3782 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3784 const_cast<Expr*
>(BlockExp));
3792 &Context->Idents.get(
"FuncPtr"),
3793 Context->VoidPtrTy,
nullptr,
3797 *Context, PE,
true, FD, FD->
getType(), VK_LValue, OK_Ordinary);
3799 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3805 BlkExprs.push_back(BlkCast);
3808 E = Exp->
arg_end(); I != E; ++I) {
3809 BlkExprs.push_back(*I);
3812 CallExpr::Create(*Context, PE, BlkExprs, Exp->
getType(), VK_PRValue,
3835 HasLocalVariableExternalStorage(DeclRefExp->
getDecl());
3839 &Context->Idents.get(
"__forwarding"),
3840 Context->VoidPtrTy,
nullptr,
3844 MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
3845 FD->
getType(), VK_LValue, OK_Ordinary);
3847 StringRef Name = VD->
getName();
3849 &Context->Idents.get(Name),
3850 Context->VoidPtrTy,
nullptr,
3853 ME = MemberExpr::CreateImplicit(*Context, ME,
true, FD, DeclRefExp->
getType(),
3854 VK_LValue, OK_Ordinary);
3860 ReplaceStmt(DeclRefExp, PE);
3867Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(
DeclRefExpr *DRE) {
3869 if (
VarDecl *Var = dyn_cast<VarDecl>(VD))
3870 if (!ImportedLocalExternalDecls.count(Var))
3872 Expr *Exp = UnaryOperator::Create(
3878 ReplaceStmt(DRE, PE);
3890 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3893 const char *startBuf =
SM->getCharacterData(LocStart);
3894 const char *endBuf =
SM->getCharacterData(LocEnd);
3897 if (isa<TypeOfExprType>(TypePtr)) {
3898 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3900 std::string TypeAsString =
"(";
3901 RewriteBlockPointerType(TypeAsString, QT);
3902 TypeAsString +=
")";
3903 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3907 const char *argPtr = startBuf;
3909 while (*argPtr++ && (argPtr < endBuf)) {
3914 ReplaceText(LocStart, 1,
"*");
3920void RewriteObjC::RewriteBlockPointerFunctionArgs(
FunctionDecl *FD) {
3922 unsigned parenCount = 0;
3925 const char *startBuf =
SM->getCharacterData(DeclLoc);
3926 const char *startArgList = strchr(startBuf,
'(');
3928 assert((*startArgList ==
'(') &&
"Rewriter fuzzy parser confused");
3933 assert((DeclLoc.
isValid()) &&
"Invalid DeclLoc");
3935 const char *argPtr = startArgList;
3937 while (*argPtr++ && parenCount) {
3942 ReplaceText(DeclLoc, 1,
"*");
3954bool RewriteObjC::PointerTypeTakesAnyBlockArguments(
QualType QT) {
3961 assert(BPT &&
"BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3966 if (isTopLevelBlockPointerType(I))
3972bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(
QualType QT) {
3979 assert(BPT &&
"BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3984 if (I->isObjCQualifiedIdType())
3986 if (I->isObjCObjectPointerType() &&
3987 I->getPointeeType()->isObjCQualifiedInterfaceType())
3995void RewriteObjC::GetExtentOfArgList(
const char *Name,
const char *&LParen,
3996 const char *&RParen) {
3997 const char *argPtr = strchr(Name,
'(');
3998 assert((*argPtr ==
'(') &&
"Rewriter fuzzy parser confused");
4002 unsigned parenCount = 1;
4004 while (*argPtr && parenCount) {
4006 case '(': parenCount++;
break;
4007 case ')': parenCount--;
break;
4010 if (parenCount) argPtr++;
4012 assert((*argPtr ==
')') &&
"Rewriter fuzzy parser confused");
4016void RewriteObjC::RewriteBlockPointerDecl(
NamedDecl *ND) {
4018 RewriteBlockPointerFunctionArgs(FD);
4024 if (
VarDecl *VD = dyn_cast<VarDecl>(ND))
4027 DeclT = TDD->getUnderlyingType();
4028 else if (
FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4031 llvm_unreachable(
"RewriteBlockPointerDecl(): Decl type not yet handled");
4033 const char *startBuf =
SM->getCharacterData(DeclLoc);
4034 const char *endBuf = startBuf;
4036 while (*startBuf !=
'^' && *startBuf !=
';' && startBuf != MainFileStart)
4040 unsigned OrigLength=0;
4043 if (*startBuf ==
'^') {
4049 while (*startBuf !=
')') {
4057 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4058 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4062 startBuf =
SM->getCharacterData(DeclLoc);
4063 const char *argListBegin, *argListEnd;
4064 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4065 while (argListBegin < argListEnd) {
4066 if (*argListBegin ==
'^')
4068 else if (*argListBegin ==
'<') {
4070 buf += *argListBegin++;
4072 while (*argListBegin !=
'>') {
4073 buf += *argListBegin++;
4076 buf += *argListBegin;
4080 buf += *argListBegin;
4087 ReplaceText(Start, OrigLength, buf);
4110std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(
VarDecl *VD,
4113 if (CopyDestroyCache.count(flag))
4115 CopyDestroyCache.insert(flag);
4116 S =
"static void __Block_byref_id_object_copy_";
4118 S +=
"(void *dst, void *src) {\n";
4123 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4124 unsigned VoidPtrSize =
4125 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4127 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4128 S +=
" _Block_object_assign((char*)dst + ";
4129 S += utostr(offset);
4130 S +=
", *(void * *) ((char*)src + ";
4131 S += utostr(offset);
4136 S +=
"static void __Block_byref_id_object_dispose_";
4138 S +=
"(void *src) {\n";
4139 S +=
" _Block_object_dispose(*(void * *) ((char*)src + ";
4140 S += utostr(offset);
4165void RewriteObjC::RewriteByRefVar(
VarDecl *ND) {
4168 if (CurFunctionDeclToDeclareForBlock)
4169 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4177 const char *startBuf =
SM->getCharacterData(DeclLoc);
4179 X =
SM->getExpansionLoc(
X);
4180 const char *endBuf =
SM->getCharacterData(
X);
4182 std::string ByrefType;
4183 RewriteByRefString(ByrefType, Name, ND,
true);
4184 ByrefType +=
" {\n";
4185 ByrefType +=
" void *__isa;\n";
4186 RewriteByRefString(ByrefType, Name, ND);
4187 ByrefType +=
" *__forwarding;\n";
4188 ByrefType +=
" int __flags;\n";
4189 ByrefType +=
" int __size;\n";
4193 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4194 if (HasCopyAndDispose) {
4195 ByrefType +=
" void (*__Block_byref_id_object_copy)(void*, void*);\n";
4196 ByrefType +=
" void (*__Block_byref_id_object_dispose)(void*);\n";
4200 (void)convertBlockPointerToFunctionPointer(T);
4201 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4203 ByrefType +=
" " + Name +
";\n";
4204 ByrefType +=
"};\n";
4210 assert(CurMethodDef &&
"RewriteByRefVar - CurMethodDef is null");
4213 InsertText(FunLocStart, ByrefType);
4219 if (HasCopyAndDispose) {
4227 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4229 InsertText(FunLocStart, HF);
4235 bool hasInit = (ND->
getInit() !=
nullptr);
4237 if (HasCopyAndDispose)
4241 RewriteByRefString(ByrefType, Name, ND);
4242 std::string ForwardingCastType(
"(");
4243 ForwardingCastType += ByrefType +
" *)";
4245 ByrefType +=
" " + Name +
" = {(void*)";
4246 ByrefType += utostr(isa);
4247 ByrefType +=
"," + ForwardingCastType +
"&" + Name +
", ";
4248 ByrefType += utostr(flags);
4250 ByrefType +=
"sizeof(";
4251 RewriteByRefString(ByrefType, Name, ND);
4253 if (HasCopyAndDispose) {
4254 ByrefType +=
", __Block_byref_id_object_copy_";
4255 ByrefType += utostr(flag);
4256 ByrefType +=
", __Block_byref_id_object_dispose_";
4257 ByrefType += utostr(flag);
4259 ByrefType +=
"};\n";
4260 unsigned nameSize = Name.size();
4265 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4271 startLoc = ECE->getLParenLoc();
4274 startLoc =
SM->getExpansionLoc(startLoc);
4275 endBuf =
SM->getCharacterData(startLoc);
4276 ByrefType +=
" " + Name;
4277 ByrefType +=
" = {(void*)";
4278 ByrefType += utostr(isa);
4279 ByrefType +=
"," + ForwardingCastType +
"&" + Name +
", ";
4280 ByrefType += utostr(flags);
4282 ByrefType +=
"sizeof(";
4283 RewriteByRefString(ByrefType, Name, ND);
4285 if (HasCopyAndDispose) {
4286 ByrefType +=
"__Block_byref_id_object_copy_";
4287 ByrefType += utostr(flag);
4288 ByrefType +=
", __Block_byref_id_object_dispose_";
4289 ByrefType += utostr(flag);
4292 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4302 const char *startInitializerBuf =
SM->getCharacterData(startLoc);
4303 const char *semiBuf = strchr(startInitializerBuf,
';');
4304 assert((*semiBuf ==
';') &&
"RewriteByRefVar: can't find ';'");
4308 InsertText(semiLoc,
"}");
4312void RewriteObjC::CollectBlockDeclRefInfo(
BlockExpr *Exp) {
4314 GetBlockDeclRefExprs(Exp->
getBody());
4315 if (BlockDeclRefs.size()) {
4317 for (
unsigned i = 0; i < BlockDeclRefs.size(); i++)
4318 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4319 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4320 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4321 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4325 for (
unsigned i = 0; i < BlockDeclRefs.size(); i++)
4326 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4327 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4328 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4329 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4333 for (
unsigned i = 0; i < BlockDeclRefs.size(); i++)
4334 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4335 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4336 BlockDeclRefs[i]->getType()->isBlockPointerType())
4337 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4341FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4343 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4352 Blocks.push_back(Exp);
4354 CollectBlockDeclRefInfo(Exp);
4357 int countOfInnerDecls = 0;
4358 if (!InnerBlockDeclRefs.empty()) {
4359 for (
unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4362 if (!VD->
hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4366 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4367 BlockDeclRefs.push_back(Exp);
4368 BlockByCopyDeclsPtrSet.insert(VD);
4369 BlockByCopyDecls.push_back(VD);
4371 if (VD->
hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4372 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4373 BlockDeclRefs.push_back(Exp);
4374 BlockByRefDeclsPtrSet.insert(VD);
4375 BlockByRefDecls.push_back(VD);
4379 for (
unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4380 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4381 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4382 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4383 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4385 InnerDeclRefsCount.push_back(countOfInnerDecls);
4387 std::string FuncName;
4391 else if (CurMethodDef)
4392 BuildUniqueMethodName(FuncName, CurMethodDef);
4393 else if (GlobalVarDecl)
4396 std::string BlockNumber = utostr(Blocks.size()-1);
4398 std::string Tag =
"__" + FuncName +
"_block_impl_" + BlockNumber;
4399 std::string
Func =
"__" + FuncName +
"_block_func_" + BlockNumber;
4402 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4403 QualType FType = Context->getPointerType(BFT);
4409 FD = SynthBlockInitFunctionDecl(Tag);
4416 FD = SynthBlockInitFunctionDecl(Func);
4420 NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
4421 InitExprs.push_back(castExpr);
4424 std::string DescData =
"__" + FuncName +
"_block_desc_" + BlockNumber +
"_DATA";
4426 VarDecl *NewVD = VarDecl::Create(
4428 &Context->Idents.get(DescData), Context->VoidPtrTy,
nullptr, SC_Static);
4431 new (Context)
DeclRefExpr(*Context, NewVD,
false, Context->VoidPtrTy,
4433 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue,
4435 InitExprs.push_back(DescRefExpr);
4438 if (BlockDeclRefs.size()) {
4442 E = BlockByCopyDecls.end(); I != E; ++I) {
4443 if (isObjCType((*I)->getType())) {
4445 FD = SynthBlockInitFunctionDecl((*I)->getName());
4448 if (HasLocalVariableExternalStorage(*I)) {
4450 QT = Context->getPointerType(QT);
4451 Exp = UnaryOperator::Create(
const_cast<ASTContext &
>(*Context), Exp,
4452 UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
4456 }
else if (isTopLevelBlockPointerType((*I)->getType())) {
4457 FD = SynthBlockInitFunctionDecl((*I)->getName());
4460 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
4463 FD = SynthBlockInitFunctionDecl((*I)->getName());
4466 if (HasLocalVariableExternalStorage(*I)) {
4468 QT = Context->getPointerType(QT);
4469 Exp = UnaryOperator::Create(
const_cast<ASTContext &
>(*Context), Exp,
4470 UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
4475 InitExprs.push_back(Exp);
4479 E = BlockByRefDecls.end(); I != E; ++I) {
4482 std::string RecName;
4483 RewriteByRefString(RecName, Name, ND,
true);
4485 +
sizeof(
"struct"));
4487 RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
4489 assert(RD &&
"SynthBlockInitExpr(): Can't find RecordDecl");
4490 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4492 FD = SynthBlockInitFunctionDecl((*I)->getName());
4495 bool isNestedCapturedVar =
false;
4497 for (
const auto &CI : block->
captures()) {
4498 const VarDecl *variable = CI.getVariable();
4499 if (variable == ND && CI.isNested()) {
4500 assert (CI.isByRef() &&
4501 "SynthBlockInitExpr - captured block variable is not byref");
4502 isNestedCapturedVar =
true;
4508 if (!isNestedCapturedVar)
4509 Exp = UnaryOperator::Create(
4510 const_cast<ASTContext &
>(*Context), Exp, UO_AddrOf,
4511 Context->getPointerType(Exp->
getType()), VK_PRValue, OK_Ordinary,
4513 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4514 InitExprs.push_back(Exp);
4517 if (ImportedBlockDecls.size()) {
4521 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4522 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4524 InitExprs.push_back(FlagExp);
4526 NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
4528 NewRep = UnaryOperator::Create(
4529 const_cast<ASTContext &
>(*Context), NewRep, UO_AddrOf,
4530 Context->getPointerType(NewRep->
getType()), VK_PRValue, OK_Ordinary,
4532 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4534 BlockDeclRefs.clear();
4535 BlockByRefDecls.clear();
4536 BlockByRefDeclsPtrSet.clear();
4537 BlockByCopyDecls.clear();
4538 BlockByCopyDeclsPtrSet.clear();
4539 ImportedBlockDecls.clear();
4543bool RewriteObjC::IsDeclStmtInForeachHeader(
DeclStmt *DS) {
4545 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4546 return CS->getElement() == DS;
4554Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(
Stmt *S) {
4555 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4556 isa<DoStmt>(S) || isa<ForStmt>(S))
4558 else if (isa<ObjCForCollectionStmt>(S)) {
4560 ObjCBcLabelNo.push_back(++BcLabelCount);
4567 return RewritePropertyOrImplicitSetter(PseudoOp);
4569 return RewritePropertyOrImplicitGetter(PseudoOp);
4571 }
else if (
ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4572 return RewriteObjCIvarRefExpr(IvarRefExpr);
4578 for (
Stmt *&childStmt : S->children())
4580 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4582 childStmt = newStmt;
4586 if (
BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4589 InnerContexts.insert(BE->getBlockDecl());
4590 ImportedLocalExternalDecls.clear();
4591 GetInnerBlockDeclRefExprs(BE->getBody(),
4592 InnerBlockDeclRefs, InnerContexts);
4594 Stmt *SaveCurrentBody = CurrentBody;
4595 CurrentBody = BE->getBody();
4596 PropParentMap =
nullptr;
4602 bool saveDisableReplaceStmt = DisableReplaceStmt;
4603 DisableReplaceStmt =
false;
4604 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4605 DisableReplaceStmt = saveDisableReplaceStmt;
4606 CurrentBody = SaveCurrentBody;
4607 PropParentMap =
nullptr;
4608 ImportedLocalExternalDecls.clear();
4610 std::string Str =
Rewrite.getRewrittenText(BE->getSourceRange());
4611 RewrittenBlockExprs[BE] = Str;
4613 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4616 ReplaceStmt(S, blockTranscribed);
4617 return blockTranscribed;
4621 return RewriteAtEncode(AtEncode);
4624 return RewriteAtSelector(AtSelector);
4627 return RewriteObjCStringLiteral(AtString);
4635 const char *startBuf =
SM->getCharacterData(startLoc);
4636 const char *endBuf =
SM->getCharacterData(endLoc);
4638 std::string messString;
4639 messString +=
"// ";
4640 messString.append(startBuf, endBuf-startBuf+1);
4649 return RewriteMessageExpr(MessExpr);
4653 return RewriteObjCTryStmt(StmtTry);
4656 return RewriteObjCSynchronizedStmt(StmtTry);
4659 return RewriteObjCThrowStmt(StmtThrow);
4662 return RewriteObjCProtocolExpr(ProtocolExp);
4665 dyn_cast<ObjCForCollectionStmt>(S))
4666 return RewriteObjCForCollectionStmt(StmtForCollection,
4669 dyn_cast<BreakStmt>(S))
4670 return RewriteBreakStmt(StmtBreakStmt);
4672 dyn_cast<ContinueStmt>(S))
4673 return RewriteContinueStmt(StmtContinueStmt);
4677 if (
DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4687 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4688 RewriteObjCQualifiedInterfaceTypes(*DS->
decl_begin());
4691 for (
auto *SD : DS->
decls()) {
4692 if (
ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4693 if (isTopLevelBlockPointerType(ND->
getType()))
4694 RewriteBlockPointerDecl(ND);
4696 CheckFunctionPointerDecl(ND->
getType(), ND);
4697 if (
VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4698 if (VD->
hasAttr<BlocksAttr>()) {
4699 static unsigned uniqueByrefDeclCount = 0;
4700 assert(!BlockByRefDeclNo.count(ND) &&
4701 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4702 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4703 RewriteByRefVar(VD);
4706 RewriteTypeOfDecl(VD);
4710 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4711 RewriteBlockPointerDecl(TD);
4712 else if (TD->getUnderlyingType()->isFunctionPointerType())
4713 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4719 RewriteObjCQualifiedInterfaceTypes(CE);
4721 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4722 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4723 assert(!Stmts.empty() &&
"Statement stack is empty");
4724 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4725 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4726 &&
"Statement stack mismatch");
4730 if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4732 if (VD->
hasAttr<BlocksAttr>())
4733 return RewriteBlockDeclRefExpr(DRE);
4734 if (HasLocalVariableExternalStorage(VD))
4735 return RewriteLocalVariableExternalStorage(DRE);
4738 if (
CallExpr *CE = dyn_cast<CallExpr>(S)) {
4740 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4741 ReplaceStmt(S, BlockCall);
4746 RewriteCastExpr(CE);
4755 llvm::raw_string_ostream Buf(SStr);
4756 Replacement->printPretty(Buf);
4757 const std::string &Str = Buf.str();
4759 printf(
"CAST = %s\n", &Str[0]);
4769void RewriteObjC::RewriteRecordBody(
RecordDecl *RD) {
4770 for (
auto *FD : RD->
fields()) {
4771 if (isTopLevelBlockPointerType(FD->
getType()))
4772 RewriteBlockPointerDecl(FD);
4775 RewriteObjCQualifiedInterfaceTypes(FD);
4781void RewriteObjC::HandleDeclInMainFile(
Decl *D) {
4783 case Decl::Function: {
4791 RewriteBlocksInFunctionProtoType(FD->
getType(), FD);
4798 CurFunctionDef = FD;
4799 CurFunctionDeclToDeclareForBlock = FD;
4802 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4804 CurrentBody =
nullptr;
4805 if (PropParentMap) {
4806 delete PropParentMap;
4807 PropParentMap =
nullptr;
4811 InsertBlockLiteralsWithinFunction(FD);
4812 CurFunctionDef =
nullptr;
4813 CurFunctionDeclToDeclareForBlock =
nullptr;
4817 case Decl::ObjCMethod: {
4823 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4825 CurrentBody =
nullptr;
4826 if (PropParentMap) {
4827 delete PropParentMap;
4828 PropParentMap =
nullptr;
4830 InsertBlockLiteralsWithinMethod(MD);
4831 CurMethodDef =
nullptr;
4835 case Decl::ObjCImplementation: {
4837 ClassImplementation.push_back(CI);
4840 case Decl::ObjCCategoryImpl: {
4842 CategoryImplementation.push_back(CI);
4846 VarDecl *VD = cast<VarDecl>(D);
4847 RewriteObjCQualifiedInterfaceTypes(VD);
4848 if (isTopLevelBlockPointerType(VD->
getType()))
4849 RewriteBlockPointerDecl(VD);
4851 CheckFunctionPointerDecl(VD->
getType(), VD);
4854 RewriteCastExpr(CE);
4860 RewriteRecordBody(RD);
4865 RewriteFunctionBodyOrGlobalInitializer(VD->
getInit());
4866 CurrentBody =
nullptr;
4867 if (PropParentMap) {
4868 delete PropParentMap;
4869 PropParentMap =
nullptr;
4872 GlobalVarDecl =
nullptr;
4876 RewriteCastExpr(CE);
4881 case Decl::TypeAlias:
4882 case Decl::Typedef: {
4884 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4885 RewriteBlockPointerDecl(TD);
4886 else if (TD->getUnderlyingType()->isFunctionPointerType())
4887 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4891 case Decl::CXXRecord:
4892 case Decl::Record: {
4895 RewriteRecordBody(RD);
4904void RewriteObjC::HandleTranslationUnit(
ASTContext &C) {
4913 RewriteObjCProtocolMetaData(ProtDecl,
"",
"", Preamble);
4915 InsertText(
SM->getLocForStartOfFile(MainFileID), Preamble,
false);
4916 if (ClassImplementation.size() || CategoryImplementation.size())
4917 RewriteImplementations();
4922 Rewrite.getRewriteBufferFor(MainFileID)) {
4924 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4926 llvm::errs() <<
"No changes\n";
4929 if (ClassImplementation.size() || CategoryImplementation.size() ||
4930 ProtocolExprDecls.size()) {
4932 std::string ResultStr;
4933 RewriteMetaDataIntoBuffer(ResultStr);
4935 *OutFile << ResultStr;
4940void RewriteObjCFragileABI::Initialize(
ASTContext &context) {
4941 InitializeCommon(context);
4947 Preamble +=
"struct objc_selector; struct objc_class;\n";
4948 Preamble +=
"struct __rw_objc_super { struct objc_object *object; ";
4949 Preamble +=
"struct objc_object *superClass; ";
4950 if (LangOpts.MicrosoftExt) {
4952 Preamble +=
"__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4954 Preamble +=
"object(o), superClass(s) {} ";
4957 Preamble +=
"#ifndef _REWRITER_typedef_Protocol\n";
4958 Preamble +=
"typedef struct objc_object Protocol;\n";
4959 Preamble +=
"#define _REWRITER_typedef_Protocol\n";
4961 if (LangOpts.MicrosoftExt) {
4962 Preamble +=
"#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4963 Preamble +=
"#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4965 Preamble +=
"#define __OBJC_RW_DLLIMPORT extern\n";
4966 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4967 Preamble +=
"(struct objc_object *, struct objc_selector *, ...);\n";
4968 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4969 Preamble +=
"(struct objc_super *, struct objc_selector *, ...);\n";
4970 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4971 Preamble +=
"(struct objc_object *, struct objc_selector *, ...);\n";
4972 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4973 Preamble +=
"(struct objc_super *, struct objc_selector *, ...);\n";
4974 Preamble +=
"__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4975 Preamble +=
"(struct objc_object *, struct objc_selector *, ...);\n";
4976 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4978 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4979 Preamble +=
"(struct objc_class *);\n";
4980 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4982 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4983 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4984 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4985 Preamble +=
"__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4986 Preamble +=
"__OBJC_RW_DLLIMPORT int objc_exception_match";
4987 Preamble +=
"(struct objc_class *, struct objc_object *);\n";
4989 Preamble +=
"__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4990 Preamble +=
"__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4991 Preamble +=
"__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4992 Preamble +=
"#ifndef __FASTENUMERATIONSTATE\n";
4993 Preamble +=
"struct __objcFastEnumerationState {\n\t";
4994 Preamble +=
"unsigned long state;\n\t";
4995 Preamble +=
"void **itemsPtr;\n\t";
4996 Preamble +=
"unsigned long *mutationsPtr;\n\t";
4997 Preamble +=
"unsigned long extra[5];\n};\n";
4998 Preamble +=
"__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
4999 Preamble +=
"#define __FASTENUMERATIONSTATE\n";
5001 Preamble +=
"#ifndef __NSCONSTANTSTRINGIMPL\n";
5002 Preamble +=
"struct __NSConstantStringImpl {\n";
5008 Preamble +=
"#ifdef CF_EXPORT_CONSTANT_STRING\n";
5009 Preamble +=
"extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5011 Preamble +=
"__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5013 Preamble +=
"#define __NSCONSTANTSTRINGIMPL\n";
5016 Preamble +=
"#ifndef BLOCK_IMPL\n";
5017 Preamble +=
"#define BLOCK_IMPL\n";
5018 Preamble +=
"struct __block_impl {\n";
5024 Preamble +=
"// Runtime copy/destroy helper functions (from Block_private.h)\n";
5025 Preamble +=
"#ifdef __OBJC_EXPORT_BLOCKS\n";
5026 Preamble +=
"extern \"C\" __declspec(dllexport) "
5027 "void _Block_object_assign(void *, const void *, const int);\n";
5028 Preamble +=
"extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5029 Preamble +=
"extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5030 Preamble +=
"extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5032 Preamble +=
"__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5033 Preamble +=
"__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5034 Preamble +=
"__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5035 Preamble +=
"__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5038 if (LangOpts.MicrosoftExt) {
5039 Preamble +=
"#undef __OBJC_RW_DLLIMPORT\n";
5040 Preamble +=
"#undef __OBJC_RW_STATICIMPORT\n";
5041 Preamble +=
"#ifndef KEEP_ATTRIBUTES\n";
5042 Preamble +=
"#define __attribute__(X)\n";
5052 Preamble +=
"\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5057void RewriteObjCFragileABI::RewriteIvarOffsetComputation(
ObjCIvarDecl *ivar,
5058 std::string &Result) {
5064 Result +=
"__OFFSETOFIVAR__(struct ";
5066 if (LangOpts.MicrosoftExt)
5075void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5077 StringRef ClassName, std::string &Result) {
5078 static bool objc_protocol_methods =
false;
5087 Result +=
"\nstruct _protocol_methods {\n";
5088 Result +=
"\tstruct objc_selector *_cmd;\n";
5089 Result +=
"\tchar *method_types;\n";
5092 objc_protocol_methods =
true;
5109 Result +=
"\nstatic struct {\n";
5110 Result +=
"\tint protocol_method_count;\n";
5111 Result +=
"\tstruct _protocol_methods protocol_methods[";
5112 Result += utostr(NumMethods);
5113 Result +=
"];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5115 Result +=
" __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5116 "{\n\t" + utostr(NumMethods) +
"\n";
5123 Result +=
"\t ,{{(struct objc_selector *)\"";
5125 Result +=
"\t ,{(struct objc_selector *)\"";
5126 Result += (*I)->getSelector().getAsString();
5127 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5129 Result += MethodTypeString;
5132 Result +=
"\t }\n};\n";
5138 if (NumMethods > 0) {
5144 Result +=
"\nstatic struct {\n";
5145 Result +=
"\tint protocol_method_count;\n";
5146 Result +=
"\tstruct _protocol_methods protocol_methods[";
5147 Result += utostr(NumMethods);
5148 Result +=
"];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5150 Result +=
" __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5152 Result += utostr(NumMethods);
5160 Result +=
"\t ,{{(struct objc_selector *)\"";
5162 Result +=
"\t ,{(struct objc_selector *)\"";
5163 Result += (*I)->getSelector().getAsString();
5164 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5166 Result += MethodTypeString;
5169 Result +=
"\t }\n};\n";
5182 static bool objc_protocol =
false;
5183 if (!objc_protocol) {
5184 Result +=
"\nstruct _objc_protocol {\n";
5185 Result +=
"\tstruct _objc_protocol_extension *isa;\n";
5186 Result +=
"\tchar *protocol_name;\n";
5187 Result +=
"\tstruct _objc_protocol **protocol_list;\n";
5188 Result +=
"\tstruct _objc_protocol_method_list *instance_methods;\n";
5189 Result +=
"\tstruct _objc_protocol_method_list *class_methods;\n";
5192 objc_protocol =
true;
5195 Result +=
"\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5197 Result +=
" __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5200 Result +=
"\", 0, ";
5202 Result +=
"(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5209 Result +=
"(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5219 llvm_unreachable(
"protocol already synthesized");
5222void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5224 StringRef prefix, StringRef ClassName,
5225 std::string &Result) {
5226 if (Protocols.
empty())
return;
5228 for (
unsigned i = 0; i != Protocols.
size(); i++)
5229 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5238 Result +=
"\nstatic struct {\n";
5239 Result +=
"\tstruct _objc_protocol_list *next;\n";
5240 Result +=
"\tint protocol_count;\n";
5241 Result +=
"\tstruct _objc_protocol *class_protocols[";
5242 Result += utostr(Protocols.
size());
5243 Result +=
"];\n} _OBJC_";
5245 Result +=
"_PROTOCOLS_";
5246 Result += ClassName;
5247 Result +=
" __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5249 Result += utostr(Protocols.
size());
5252 Result +=
"\t,{&_OBJC_PROTOCOL_";
5253 Result += Protocols[0]->getNameAsString();
5256 for (
unsigned i = 1; i != Protocols.
size(); i++) {
5257 Result +=
"\t ,&_OBJC_PROTOCOL_";
5258 Result += Protocols[i]->getNameAsString();
5261 Result +=
"\t }\n};\n";
5265 std::string &Result) {
5272 RewriteObjCInternalStruct(CDecl, Result);
5279 static bool objc_ivar =
false;
5287 Result +=
"\nstruct _objc_ivar {\n";
5288 Result +=
"\tchar *ivar_name;\n";
5289 Result +=
"\tchar *ivar_type;\n";
5290 Result +=
"\tint ivar_offset;\n";
5301 Result +=
"\nstatic struct {\n";
5302 Result +=
"\tint ivar_count;\n";
5303 Result +=
"\tstruct _objc_ivar ivar_list[";
5304 Result += utostr(NumIvars);
5305 Result +=
"];\n} _OBJC_INSTANCE_VARIABLES_";
5307 Result +=
" __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5309 Result += utostr(NumIvars);
5315 for (
auto *IV : IDecl->
ivars())
5316 IVars.push_back(IV);
5323 Result +=
"\t,{{\"";
5324 Result += IVI->getNameAsString();
5326 std::string TmpString, StrEncoding;
5327 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5328 QuoteDoublequotes(TmpString, StrEncoding);
5329 Result += StrEncoding;
5331 RewriteIvarOffsetComputation(*IVI, Result);
5333 for (++IVI; IVI != IVE; ++IVI) {
5334 Result +=
"\t ,{\"";
5335 Result += IVI->getNameAsString();
5337 std::string TmpString, StrEncoding;
5338 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5339 QuoteDoublequotes(TmpString, StrEncoding);
5340 Result += StrEncoding;
5342 RewriteIvarOffsetComputation(*IVI, Result);
5346 Result +=
"\t }\n};\n";
5355 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5357 if (!Prop->getPropertyIvarDecl())
5363 if (!Getter->isDefined())
5364 InstanceMethods.push_back(Getter);
5368 if (!Setter->isDefined())
5369 InstanceMethods.push_back(Setter);
5371 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5372 true,
"", IDecl->
getName(), Result);
5376 false,
"", IDecl->
getName(), Result);
5380 "CLASS", CDecl->
getName(), Result);
5398 static bool objc_class =
false;
5400 Result +=
"\nstruct _objc_class {\n";
5401 Result +=
"\tstruct _objc_class *isa;\n";
5402 Result +=
"\tconst char *super_class_name;\n";
5403 Result +=
"\tchar *name;\n";
5404 Result +=
"\tlong version;\n";
5405 Result +=
"\tlong info;\n";
5406 Result +=
"\tlong instance_size;\n";
5407 Result +=
"\tstruct _objc_ivar_list *ivars;\n";
5408 Result +=
"\tstruct _objc_method_list *methods;\n";
5409 Result +=
"\tstruct objc_cache *cache;\n";
5410 Result +=
"\tstruct _objc_protocol_list *protocols;\n";
5411 Result +=
"\tconst char *ivar_layout;\n";
5412 Result +=
"\tstruct _objc_class_ext *ext;\n";
5420 while (SuperClass) {
5421 RootClass = SuperClass;
5426 Result +=
"\nstatic struct _objc_class _OBJC_METACLASS_";
5428 Result +=
" __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5429 "{\n\t(struct _objc_class *)\"";
5441 Result +=
", 0, \"";
5447 Result +=
", 0,2, sizeof(struct _objc_class), 0";
5449 Result +=
"\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5456 Result +=
"\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5461 Result +=
"\t,0,0,0,0\n";
5465 Result +=
"\nstatic struct _objc_class _OBJC_CLASS_";
5467 Result +=
" __attribute__ ((used, section (\"__OBJC, __class\")))= "
5468 "{\n\t&_OBJC_METACLASS_";
5478 Result +=
", 0, \"";
5484 if (!ObjCSynthesizedStructs.count(CDecl))
5488 Result +=
",sizeof(struct ";
5490 if (LangOpts.MicrosoftExt)
5495 Result +=
", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5502 Result +=
", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5504 Result +=
", 0\n\t";
5509 Result +=
", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5511 Result +=
", 0,0\n";
5514 Result +=
",0,0,0\n";
5518void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5519 int ClsDefCount = ClassImplementation.size();
5520 int CatDefCount = CategoryImplementation.size();
5523 for (
int i = 0; i < ClsDefCount; i++)
5524 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5527 for (
int i = 0; i < CatDefCount; i++)
5528 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5542 Result +=
"\nstruct _objc_symtab {\n";
5543 Result +=
"\tlong sel_ref_cnt;\n";
5544 Result +=
"\tSEL *refs;\n";
5545 Result +=
"\tshort cls_def_cnt;\n";
5546 Result +=
"\tshort cat_def_cnt;\n";
5547 Result +=
"\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+
"];\n";
5550 Result +=
"static struct _objc_symtab "
5551 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5552 Result +=
"\t0, 0, " + utostr(ClsDefCount)
5553 +
", " + utostr(CatDefCount) +
"\n";
5554 for (
int i = 0; i < ClsDefCount; i++) {
5555 Result +=
"\t,&_OBJC_CLASS_";
5556 Result += ClassImplementation[i]->getNameAsString();
5560 for (
int i = 0; i < CatDefCount; i++) {
5561 Result +=
"\t,&_OBJC_CATEGORY_";
5562 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5564 Result += CategoryImplementation[i]->getNameAsString();
5581 Result +=
"\nstruct _objc_module {\n";
5582 Result +=
"\tlong version;\n";
5583 Result +=
"\tlong size;\n";
5584 Result +=
"\tconst char *name;\n";
5585 Result +=
"\tstruct _objc_symtab *symtab;\n";
5587 Result +=
"static struct _objc_module "
5588 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5589 Result +=
"\t" + utostr(OBJC_ABI_VERSION) +
5590 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5593 if (LangOpts.MicrosoftExt) {
5594 if (ProtocolExprDecls.size()) {
5595 Result +=
"#pragma section(\".objc_protocol$B\",long,read,write)\n";
5596 Result +=
"#pragma data_seg(push, \".objc_protocol$B\")\n";
5598 Result +=
"static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5599 Result += ProtDecl->getNameAsString();
5600 Result +=
" = &_OBJC_PROTOCOL_";
5601 Result += ProtDecl->getNameAsString();
5604 Result +=
"#pragma data_seg(pop)\n\n";
5606 Result +=
"#pragma section(\".objc_module_info$B\",long,read,write)\n";
5607 Result +=
"#pragma data_seg(push, \".objc_module_info$B\")\n";
5608 Result +=
"static struct _objc_module *_POINTER_OBJC_MODULES = ";
5609 Result +=
"&_OBJC_MODULES;\n";
5610 Result +=
"#pragma data_seg(pop)\n\n";
5617 std::string &Result) {
5624 FullCategoryName +=
'_';
5633 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5635 if (!Prop->getPropertyIvarDecl())
5641 InstanceMethods.push_back(Getter);
5645 InstanceMethods.push_back(Setter);
5647 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5648 true,
"CATEGORY_", FullCategoryName, Result);
5652 false,
"CATEGORY_", FullCategoryName, Result);
5658 FullCategoryName, Result);
5672 static bool objc_category =
false;
5673 if (!objc_category) {
5674 Result +=
"\nstruct _objc_category {\n";
5675 Result +=
"\tchar *category_name;\n";
5676 Result +=
"\tchar *class_name;\n";
5677 Result +=
"\tstruct _objc_method_list *instance_methods;\n";
5678 Result +=
"\tstruct _objc_method_list *class_methods;\n";
5679 Result +=
"\tstruct _objc_protocol_list *protocols;\n";
5680 Result +=
"\tunsigned int size;\n";
5681 Result +=
"\tstruct _objc_property_list *instance_properties;\n";
5683 objc_category =
true;
5685 Result +=
"\nstatic struct _objc_category _OBJC_CATEGORY_";
5686 Result += FullCategoryName;
5687 Result +=
" __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5689 Result +=
"\"\n\t, \"";
5694 Result +=
"\t, (struct _objc_method_list *)"
5695 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5696 Result += FullCategoryName;
5700 Result +=
"\t, 0\n";
5702 Result +=
"\t, (struct _objc_method_list *)"
5703 "&_OBJC_CATEGORY_CLASS_METHODS_";
5704 Result += FullCategoryName;
5708 Result +=
"\t, 0\n";
5711 Result +=
"\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5712 Result += FullCategoryName;
5716 Result +=
"\t, 0\n";
5717 Result +=
"\t, sizeof(struct _objc_category), 0\n};\n";
5722template<
typename MethodIterator>
5723void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5724 MethodIterator MethodEnd,
5725 bool IsInstanceMethod,
5727 StringRef ClassName,
5728 std::string &Result) {
5729 if (MethodBegin == MethodEnd)
return;
5731 if (!objc_impl_method) {
5738 Result +=
"\nstruct _objc_method {\n";
5739 Result +=
"\tSEL _cmd;\n";
5740 Result +=
"\tchar *method_types;\n";
5741 Result +=
"\tvoid *_imp;\n";
5744 objc_impl_method =
true;
5755 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5756 Result +=
"\nstatic struct {\n";
5757 Result +=
"\tstruct _objc_method_list *next_method;\n";
5758 Result +=
"\tint method_count;\n";
5759 Result +=
"\tstruct _objc_method method_list[";
5760 Result += utostr(NumMethods);
5761 Result +=
"];\n} _OBJC_";
5764 Result +=
"_METHODS_";
5765 Result += ClassName;
5766 Result +=
" __attribute__ ((used, section (\"__OBJC, __";
5768 Result +=
"_meth\")))= ";
5769 Result +=
"{\n\t0, " + utostr(NumMethods) +
"\n";
5771 Result +=
"\t,{{(SEL)\"";
5772 Result += (*MethodBegin)->getSelector().getAsString();
5773 std::string MethodTypeString =
5774 Context->getObjCEncodingForMethodDecl(*MethodBegin);
5776 Result += MethodTypeString;
5777 Result +=
"\", (void *)";
5778 Result += MethodInternalNames[*MethodBegin];
5780 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5781 Result +=
"\t ,{(SEL)\"";
5782 Result += (*MethodBegin)->getSelector().getAsString();
5783 std::string MethodTypeString =
5784 Context->getObjCEncodingForMethodDecl(*MethodBegin);
5786 Result += MethodTypeString;
5787 Result +=
"\", (void *)";
5788 Result += MethodInternalNames[*MethodBegin];
5791 Result +=
"\t }\n};\n";
5800 DisableReplaceStmtScope S(*
this);
5801 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5807 Expr *Replacement = IV;
5812 assert(iFaceDecl &&
"RewriteObjCIvarRefExpr - iFaceDecl is null");
5817 assert(clsDeclared &&
"RewriteObjCIvarRefExpr(): Can't find class");
5820 std::string RecName =
5825 RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
5827 assert(RD &&
"RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5828 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5840 *Context, PE,
true, D, D->
getType(), VK_LValue, OK_Ordinary);
5847 assert(!IV->
isFreeIvar() &&
"Cannot have a free standing ivar outside a method");
5858 assert(clsDeclared &&
"RewriteObjCIvarRefExpr(): Can't find class");
5861 std::string RecName =
5866 RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
5868 assert(RD &&
"RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5869 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5883 ReplaceStmtWithRange(IV, Replacement, OldRange);
Defines the Diagnostic-related interfaces.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines the SourceManager interface.
__device__ __2f16 float c
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
A builtin binary operation expression such as "x + y" or "x <= y".
Represents a block literal declaration, which is like an unnamed FunctionDecl.
param_iterator param_end()
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
param_iterator param_begin()
ArrayRef< Capture > captures() const
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
const Stmt * getBody() const
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
const BlockDecl * getBlockDecl() const
QualType getPointeeType() const
BreakStmt - This represents a break.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
SourceLocation getRParenLoc() const
SourceLocation getLParenLoc() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
CompoundLiteralExpr - [C99 6.5.2.5].
CompoundStmt - This represents a group of statements like { stmt stmt }.
SourceLocation getBeginLoc() const
ConditionalOperator - The ?: ternary operator.
ContinueStmt - This represents a continue.
decl_iterator - Iterates through the declarations stored within this context.
Iterates over a filtered subrange of declarations stored in a DeclContext.
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
void addDecl(Decl *D)
Add the declaration D into this context.
A reference to a declared variable, function, enum, etc.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
SourceLocation getLocation() const
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
decl_iterator decl_begin()
Decl - This represents one declaration (or definition), e.g.
SourceLocation getEndLoc() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
SourceLocation getLocation() const
DeclContext * getDeclContext()
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getTypeSpecStartLoc() const
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
bool hasErrorOccurred() const
This represents one expression.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
bool isBitField() const
Determines whether this field is a bitfield.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Represents a prototype with parameter type info, e.g.
unsigned getNumParams() const
QualType getParamType(unsigned i) const
bool isVariadic() const
Whether this function prototype is variadic.
ArrayRef< QualType > param_types() const
FunctionType - C99 6.7.5.3 - Function Declarators.
QualType getReturnType() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Describes an C or C++ initializer list.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a linkage specification.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Represents Objective-C's @catch statement.
const VarDecl * getCatchParamDecl() const
const Stmt * getCatchBody() const
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getRParenLoc() const
Represents Objective-C's @finally statement.
Represents Objective-C's @synchronized statement.
Represents Objective-C's @throw statement.
Represents Objective-C's @try ... @catch ... @finally statement.
ObjCCategoryDecl - Represents a category declaration.
protocol_iterator protocol_end() const
protocol_iterator protocol_begin() const
const ObjCProtocolList & getReferencedProtocols() const
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
classmeth_iterator classmeth_end() const
SourceRange getAtEndRange() const
classmeth_iterator classmeth_begin() const
instmeth_range instance_methods() const
instmeth_iterator instmeth_end() const
SourceLocation getAtStartLoc() const
instprop_range instance_properties() const
instmeth_iterator instmeth_begin() const
classmeth_range class_methods() const
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
Represents Objective-C's collection statement.
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
std::string getNameAsString() const
Get the name of the class associated with this interface.
ivar_iterator ivar_begin() const
StringRef getName() const
getName - Get the name of identifier for the class interface associated with this implementation as a...
ivar_iterator ivar_end() const
unsigned ivar_size() const
Represents an ObjC class declaration.
ivar_iterator ivar_end() const
unsigned ivar_size() const
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
bool isImplicitInterfaceDecl() const
isImplicitInterfaceDecl - check that this is an implicitly declared ObjCInterfaceDecl node.
ObjCCategoryDecl * FindCategoryDeclaration(const IdentifierInfo *CategoryId) const
FindCategoryDeclaration - Finds category declaration in the list of categories for this class and ret...
ivar_iterator ivar_begin() const
protocol_iterator protocol_end() const
SourceLocation getSuperClassLoc() const
Retrieve the starting location of the superclass.
bool isThisDeclarationADefinition() const
Determine whether this particular declaration of this class is actually also a definition.
const ObjCProtocolList & getReferencedProtocols() const
SourceLocation getEndOfDefinitionLoc() const
protocol_iterator protocol_begin() const
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
ObjCInterfaceDecl * getSuperClass() const
Interfaces are the core concept in Objective-C for object oriented design.
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
ObjCIvarRefExpr - A reference to an ObjC instance variable.
const Expr * getBase() const
ObjCList - This is a simple template class used to hold various lists of decls etc,...
An expression that sends a message to the given Objective-C object or class.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
void getSelectorLocs(SmallVectorImpl< SourceLocation > &SelLocs) const
bool isImplicit() const
Indicates whether the message send was implicitly generated by the implementation.
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getLeftLoc() const
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super',...
Selector getSelector() const
TypeSourceInfo * getClassReceiverTypeInfo() const
Returns a type-source information of a class message send, or nullptr if the message is not a class m...
QualType getClassReceiver() const
Returns the type of a class message send, or NULL if the message is not a class message.
QualType getSuperType() const
Retrieve the type referred to by 'super'.
const ObjCMethodDecl * getMethodDecl() const
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
SourceLocation getEndLoc() const LLVM_READONLY
SourceLocation getRightLoc() const
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver.
ObjCMethodDecl - Represents an instance or class method declaration.
ImplicitParamDecl * getSelfDecl() const
ArrayRef< ParmVarDecl * > parameters() const
CompoundStmt * getCompoundBody()
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
SourceLocation getEndLoc() const LLVM_READONLY
SourceLocation getBeginLoc() const LLVM_READONLY
Selector getSelector() const
bool isInstanceMethod() const
QualType getReturnType() const
ObjCInterfaceDecl * getClassInterface()
Represents a pointer to an Objective C object.
Represents a class type in Objective C.
Represents one property declaration in an Objective-C interface.
SourceLocation getAtLoc() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
ObjCPropertyAttribute::Kind getPropertyAttributes() const
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
ObjCIvarDecl * getPropertyIvarDecl() const
Kind getPropertyImplementation() const
ObjCPropertyDecl * getPropertyDecl() const
ObjCMethodDecl * getSetterMethodDecl() const
SourceLocation getBeginLoc() const LLVM_READONLY
ObjCMethodDecl * getGetterMethodDecl() const
Represents an Objective-C protocol declaration.
bool hasDefinition() const
Determine whether this protocol has a definition.
bool isThisDeclarationADefinition() const
Determine whether this particular declaration is also the definition.
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
ObjCProtocolDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C protocol.
ObjCProtocolExpr used for protocol expression in Objective-C.
ObjCProtocolDecl * getProtocol() const
ObjCSelectorExpr used for @selector in Objective-C.
Selector getSelector() const
ObjCStringLiteral, used for Objective-C string literals i.e.
StringLiteral * getString()
ParenExpr - This represents a parethesized expression, e.g.
PointerType - C99 6.7.5.1 - Pointer Declarators.
QualType getPointeeType() const
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
unsigned getNumSemanticExprs() const
Expr * getSemanticExpr(unsigned index)
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
QualType IgnoreParens() const
Returns the specified type after dropping any outer-level parentheses.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isObjCGCWeak() const
true when Type is objc's weak.
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
virtual void completeDefinition()
Note that the definition of this type is now complete.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
RewriteBuffer - As code is rewritten, SourceBuffer's from the original input with modifications get a...
Rewriter - This is the main interface to the rewrite buffers.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
SourceLocation getEndLoc() const LLVM_READONLY
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
unsigned getByteLength() const
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
The top declaration context.
Represents a declaration of a type.
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Expr * getUnderlyingExpr() const
A container of type source information.
The base class of the type hierarchy.
bool isBlockPointerType() const
bool isFunctionPointerType() const
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
bool isObjCQualifiedIdType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isObjCQualifiedInterfaceType() const
bool isObjCObjectPointerType() const
bool isObjCQualifiedClassType() const
bool isRealFloatingType() const
Floating point categories.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
Base class for declarations which introduce a typedef-name.
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
const Expr * getInit() const
StorageClass getStorageClass() const
Returns the storage class as written in the source.
@ BLOCK_BYREF_CURRENT_MAX
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
@ CF
Indicates that the tracked object is a CF object.
@ RewriteObjC
ObjC->C Rewriter.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ OK_Ordinary
An ordinary object is located at an address in memory.
std::unique_ptr< ASTConsumer > CreateObjCRewriter(const std::string &InFile, std::unique_ptr< raw_ostream > OS, DiagnosticsEngine &Diags, const LangOptions &LOpts, bool SilenceRewriteMacroWarning)
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
CastKind
CastKind - The kind of operation required for a conversion.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
U cast(CodeGen::Address addr)
@ Class
The "class" keyword introduces the elaborated-type-specifier.
int printf(__constant const char *st,...) __attribute__((format(printf
Extra information about a function prototype.
Describes how types, statements, expressions, and declarations should be printed.
Iterator for iterating over Stmt * arrays that contain only T *.