(Dcl)) {
Loc = FD->getLocation();
// Check for ObjC 'id' and class types that have been adorned with protocol
// information (id, C
*). The protocol references need to be rewritten!
const FunctionType *funcType = FD->getType()->getAs();
assert(funcType && "missing function type");
proto = dyn_cast(funcType);
if (!proto)
return;
Type = proto->getReturnType();
}
else if (FieldDecl *FD = dyn_cast(Dcl)) {
Loc = FD->getLocation();
Type = FD->getType();
}
else if (TypedefNameDecl *TD = dyn_cast(Dcl)) {
Loc = TD->getLocation();
Type = TD->getUnderlyingType();
}
else
return;
if (needToScanForQualifiers(Type)) {
// Since types are unique, we need to scan the buffer.
const char *endBuf = SM->getCharacterData(Loc);
const char *startBuf = endBuf;
while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
startBuf--; // scan backward (from the decl location) for return type.
const char *startRef = nullptr, *endRef = nullptr;
if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
// Get the locations of the startRef, endRef.
SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
// Comment out the protocol references.
InsertText(LessLoc, "/*");
InsertText(GreaterLoc, "*/");
}
}
if (!proto)
return; // most likely, was a variable
// Now check arguments.
const char *startBuf = SM->getCharacterData(Loc);
const char *startFuncBuf = startBuf;
for (unsigned i = 0; i < proto->getNumParams(); i++) {
if (needToScanForQualifiers(proto->getParamType(i))) {
// Since types are unique, we need to scan the buffer.
const char *endBuf = startBuf;
// scan forward (from the decl location) for argument types.
scanToNextArgument(endBuf);
const char *startRef = nullptr, *endRef = nullptr;
if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
// Get the locations of the startRef, endRef.
SourceLocation LessLoc =
Loc.getLocWithOffset(startRef-startFuncBuf);
SourceLocation GreaterLoc =
Loc.getLocWithOffset(endRef-startFuncBuf+1);
// Comment out the protocol references.
InsertText(LessLoc, "/*");
InsertText(GreaterLoc, "*/");
}
startBuf = ++endBuf;
}
else {
// If the function name is derived from a macro expansion, then the
// argument buffer will not follow the name. Need to speak with Chris.
while (*startBuf && *startBuf != ')' && *startBuf != ',')
startBuf++; // scan forward (from the decl location) for argument types.
startBuf++;
}
}
}
void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
QualType QT = ND->getType();
const Type* TypePtr = QT->getAs();
if (!isa(TypePtr))
return;
while (isa(TypePtr)) {
const TypeOfExprType *TypeOfExprTypePtr = cast(TypePtr);
QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
TypePtr = QT->getAs();
}
// FIXME. This will not work for multiple declarators; as in:
// __typeof__(a) b,c,d;
std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
const char *startBuf = SM->getCharacterData(DeclLoc);
if (ND->getInit()) {
std::string Name(ND->getNameAsString());
TypeAsString += " " + Name + " = ";
Expr *E = ND->getInit();
SourceLocation startLoc;
if (const CStyleCastExpr *ECE = dyn_cast(E))
startLoc = ECE->getLParenLoc();
else
startLoc = E->getLocStart();
startLoc = SM->getExpansionLoc(startLoc);
const char *endBuf = SM->getCharacterData(startLoc);
ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
}
else {
SourceLocation X = ND->getLocEnd();
X = SM->getExpansionLoc(X);
const char *endBuf = SM->getCharacterData(X);
ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
}
}
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
SmallVector ArgTys;
ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
QualType getFuncType =
getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
SelGetUidIdent, getFuncType,
nullptr, SC_Extern);
}
void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
// declared in
if (FD->getIdentifier() &&
FD->getName() == "sel_registerName") {
SelGetUidFunctionDecl = FD;
return;
}
RewriteObjCQualifiedInterfaceTypes(FD);
}
void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
const char *argPtr = TypeString.c_str();
if (!strchr(argPtr, '^')) {
Str += TypeString;
return;
}
while (*argPtr) {
Str += (*argPtr == '^' ? '*' : *argPtr);
argPtr++;
}
}
// FIXME. Consolidate this routine with RewriteBlockPointerType.
void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
ValueDecl *VD) {
QualType Type = VD->getType();
std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
const char *argPtr = TypeString.c_str();
int paren = 0;
while (*argPtr) {
switch (*argPtr) {
case '(':
Str += *argPtr;
paren++;
break;
case ')':
Str += *argPtr;
paren--;
break;
case '^':
Str += '*';
if (paren == 1)
Str += VD->getNameAsString();
break;
default:
Str += *argPtr;
break;
}
argPtr++;
}
}
void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
const FunctionType *funcType = FD->getType()->getAs();
const FunctionProtoType *proto = dyn_cast(funcType);
if (!proto)
return;
QualType Type = proto->getReturnType();
std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
FdStr += " ";
FdStr += FD->getName();
FdStr += "(";
unsigned numArgs = proto->getNumParams();
for (unsigned i = 0; i < numArgs; i++) {
QualType ArgType = proto->getParamType(i);
RewriteBlockPointerType(FdStr, ArgType);
if (i+1 < numArgs)
FdStr += ", ";
}
if (FD->isVariadic()) {
FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
}
else
FdStr += ");\n";
InsertText(FunLocStart, FdStr);
}
// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
if (SuperConstructorFunctionDecl)
return;
IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
ArgTys);
SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType,
nullptr, SC_Extern);
}
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
void RewriteModernObjC::SynthMsgSendFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
ArgTys, /*isVariadic=*/true);
MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, nullptr,
SC_Extern);
}
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
SmallVector ArgTys;
ArgTys.push_back(Context->VoidTy);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
ArgTys, /*isVariadic=*/true);
MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType,
nullptr, SC_Extern);
}
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
ArgTys, /*isVariadic=*/true);
MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType,
nullptr, SC_Extern);
}
// SynthMsgSendSuperStretFunctionDecl -
// id objc_msgSendSuper_stret(void);
void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
IdentifierInfo *msgSendIdent =
&Context->Idents.get("objc_msgSendSuper_stret");
SmallVector ArgTys;
ArgTys.push_back(Context->VoidTy);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
ArgTys, /*isVariadic=*/true);
MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent,
msgSendType, nullptr,
SC_Extern);
}
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
ArgTys, /*isVariadic=*/true);
MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType,
nullptr, SC_Extern);
}
// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
void RewriteModernObjC::SynthGetClassFunctionDecl() {
IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
SmallVector ArgTys;
ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
ArgTys);
GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
getClassIdent, getClassType,
nullptr, SC_Extern);
}
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
IdentifierInfo *getSuperClassIdent =
&Context->Idents.get("class_getSuperclass");
SmallVector ArgTys;
ArgTys.push_back(Context->getObjCClassType());
QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
ArgTys);
GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
getSuperClassIdent,
getClassType, nullptr,
SC_Extern);
}
// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
SmallVector ArgTys;
ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
ArgTys);
GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
getClassIdent, getClassType,
nullptr, SC_Extern);
}
Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
QualType strType = getConstantStringStructType();
std::string S = "__NSConstantStringImpl_";
std::string tmpName = InFileName;
unsigned i;
for (i=0; i < tmpName.length(); i++) {
char c = tmpName.at(i);
// replace any non-alphanumeric characters with '_'.
if (!isAlphanumeric(c))
tmpName[i] = '_';
}
S += tmpName;
S += "_";
S += utostr(NumObjCStringLiterals++);
Preamble += "static __NSConstantStringImpl " + S;
Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
Preamble += "0x000007c8,"; // utf8_str
// The pretty printer for StringLiteral handles escape characters properly.
std::string prettyBufS;
llvm::raw_string_ostream prettyBuf(prettyBufS);
Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Preamble += prettyBuf.str();
Preamble += ",";
Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
SourceLocation(), &Context->Idents.get(S),
strType, nullptr, SC_Static);
DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
SourceLocation());
Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Context->getPointerType(DRE->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
// cast to NSConstantString *
CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
CK_CPointerToObjCPointerCast, Unop);
ReplaceStmt(Exp, cast);
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return cast;
}
Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
unsigned IntSize =
static_cast(Context->getTypeSize(Context->IntTy));
Expr *FlagExp = IntegerLiteral::Create(*Context,
llvm::APInt(IntSize, Exp->getValue()),
Context->IntTy, Exp->getLocation());
CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
CK_BitCast, FlagExp);
ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
cast);
ReplaceStmt(Exp, PE);
return PE;
}
Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
// synthesize declaration of helper functions needed in this routine.
if (!SelGetUidFunctionDecl)
SynthSelGetUidFunctionDecl();
// use objc_msgSend() for all.
if (!MsgSendFunctionDecl)
SynthMsgSendFunctionDecl();
if (!GetClassFunctionDecl)
SynthGetClassFunctionDecl();
FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
SourceLocation StartLoc = Exp->getLocStart();
SourceLocation EndLoc = Exp->getLocEnd();
// Synthesize a call to objc_msgSend().
SmallVector MsgExprs;
SmallVector ClsExprs;
// Create a call to objc_getClass(""). It will be the 1st argument.
ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
IdentifierInfo *clsName = BoxingClass->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(Cls);
// Create a call to sel_registerName(":"), etc.
// it will be the 2nd argument.
SmallVector SelExprs;
SelExprs.push_back(
getStringLiteral(BoxingMethod->getSelector().getAsString()));
CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
&SelExprs[0], SelExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(SelExp);
// User provided sub-expression is the 3rd, and last, argument.
Expr *subExpr = Exp->getSubExpr();
if (ImplicitCastExpr *ICE = dyn_cast(subExpr)) {
QualType type = ICE->getType();
const Expr *SubExpr = ICE->IgnoreParenImpCasts();
CastKind CK = CK_BitCast;
if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
CK = CK_IntegralToBoolean;
subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
}
MsgExprs.push_back(subExpr);
SmallVector ArgTypes;
ArgTypes.push_back(Context->getObjCIdType());
ArgTypes.push_back(Context->getObjCSelType());
for (const auto PI : BoxingMethod->parameters())
ArgTypes.push_back(PI->getType());
QualType returnType = Exp->getType();
// Get the type, we will need to reference it in a couple spots.
QualType msgSendType = MsgSendFlavor->getType();
// Create a reference to the objc_msgSend() declaration.
DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
VK_LValue, SourceLocation());
CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(Context->VoidTy),
CK_BitCast, DRE);
// Now do the "normal" pointer to function cast.
QualType castType =
getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
castType = Context->getPointerType(castType);
cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
cast);
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
const FunctionType *FT = msgSendType->getAs();
CallExpr *CE = new (Context)
CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
ReplaceStmt(Exp, CE);
return CE;
}
Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
// synthesize declaration of helper functions needed in this routine.
if (!SelGetUidFunctionDecl)
SynthSelGetUidFunctionDecl();
// use objc_msgSend() for all.
if (!MsgSendFunctionDecl)
SynthMsgSendFunctionDecl();
if (!GetClassFunctionDecl)
SynthGetClassFunctionDecl();
FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
SourceLocation StartLoc = Exp->getLocStart();
SourceLocation EndLoc = Exp->getLocEnd();
// Build the expression: __NSContainer_literal(int, ...).arr
QualType IntQT = Context->IntTy;
QualType NSArrayFType =
getSimpleFunctionType(Context->VoidTy, IntQT, true);
std::string NSArrayFName("__NSContainer_literal");
FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
DeclRefExpr *NSArrayDRE =
new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
SourceLocation());
SmallVector InitExprs;
unsigned NumElements = Exp->getNumElements();
unsigned UnsignedIntSize =
static_cast(Context->getTypeSize(Context->UnsignedIntTy));
Expr *count = IntegerLiteral::Create(*Context,
llvm::APInt(UnsignedIntSize, NumElements),
Context->UnsignedIntTy, SourceLocation());
InitExprs.push_back(count);
for (unsigned i = 0; i < NumElements; i++)
InitExprs.push_back(Exp->getElement(i));
Expr *NSArrayCallExpr =
new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
NSArrayFType, VK_LValue, SourceLocation());
FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
SourceLocation(),
&Context->Idents.get("arr"),
Context->getPointerType(Context->VoidPtrTy),
nullptr, /*BitWidth=*/nullptr,
/*Mutable=*/true, ICIS_NoInit);
MemberExpr *ArrayLiteralME =
new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
SourceLocation(),
ARRFD->getType(), VK_LValue,
OK_Ordinary);
QualType ConstIdT = Context->getObjCIdType().withConst();
CStyleCastExpr * ArrayLiteralObjects =
NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(ConstIdT),
CK_BitCast,
ArrayLiteralME);
// Synthesize a call to objc_msgSend().
SmallVector MsgExprs;
SmallVector ClsExprs;
QualType expType = Exp->getType();
// Create a call to objc_getClass("NSArray"). It will be th 1st argument.
ObjCInterfaceDecl *Class =
expType->getPointeeType()->getAs()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(Cls);
// Create a call to sel_registerName("arrayWithObjects:count:").
// it will be the 2nd argument.
SmallVector SelExprs;
ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
SelExprs.push_back(
getStringLiteral(ArrayMethod->getSelector().getAsString()));
CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
&SelExprs[0], SelExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(SelExp);
// (const id [])objects
MsgExprs.push_back(ArrayLiteralObjects);
// (NSUInteger)cnt
Expr *cnt = IntegerLiteral::Create(*Context,
llvm::APInt(UnsignedIntSize, NumElements),
Context->UnsignedIntTy, SourceLocation());
MsgExprs.push_back(cnt);
SmallVector ArgTypes;
ArgTypes.push_back(Context->getObjCIdType());
ArgTypes.push_back(Context->getObjCSelType());
for (const auto *PI : ArrayMethod->params())
ArgTypes.push_back(PI->getType());
QualType returnType = Exp->getType();
// Get the type, we will need to reference it in a couple spots.
QualType msgSendType = MsgSendFlavor->getType();
// Create a reference to the objc_msgSend() declaration.
DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
VK_LValue, SourceLocation());
CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(Context->VoidTy),
CK_BitCast, DRE);
// Now do the "normal" pointer to function cast.
QualType castType =
getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
castType = Context->getPointerType(castType);
cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
cast);
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
const FunctionType *FT = msgSendType->getAs();
CallExpr *CE = new (Context)
CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
ReplaceStmt(Exp, CE);
return CE;
}
Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
// synthesize declaration of helper functions needed in this routine.
if (!SelGetUidFunctionDecl)
SynthSelGetUidFunctionDecl();
// use objc_msgSend() for all.
if (!MsgSendFunctionDecl)
SynthMsgSendFunctionDecl();
if (!GetClassFunctionDecl)
SynthGetClassFunctionDecl();
FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
SourceLocation StartLoc = Exp->getLocStart();
SourceLocation EndLoc = Exp->getLocEnd();
// Build the expression: __NSContainer_literal(int, ...).arr
QualType IntQT = Context->IntTy;
QualType NSDictFType =
getSimpleFunctionType(Context->VoidTy, IntQT, true);
std::string NSDictFName("__NSContainer_literal");
FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
DeclRefExpr *NSDictDRE =
new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
SourceLocation());
SmallVector KeyExprs;
SmallVector ValueExprs;
unsigned NumElements = Exp->getNumElements();
unsigned UnsignedIntSize =
static_cast(Context->getTypeSize(Context->UnsignedIntTy));
Expr *count = IntegerLiteral::Create(*Context,
llvm::APInt(UnsignedIntSize, NumElements),
Context->UnsignedIntTy, SourceLocation());
KeyExprs.push_back(count);
ValueExprs.push_back(count);
for (unsigned i = 0; i < NumElements; i++) {
ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
KeyExprs.push_back(Element.Key);
ValueExprs.push_back(Element.Value);
}
// (const id [])objects
Expr *NSValueCallExpr =
new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
NSDictFType, VK_LValue, SourceLocation());
FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
SourceLocation(),
&Context->Idents.get("arr"),
Context->getPointerType(Context->VoidPtrTy),
nullptr, /*BitWidth=*/nullptr,
/*Mutable=*/true, ICIS_NoInit);
MemberExpr *DictLiteralValueME =
new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
SourceLocation(),
ARRFD->getType(), VK_LValue,
OK_Ordinary);
QualType ConstIdT = Context->getObjCIdType().withConst();
CStyleCastExpr * DictValueObjects =
NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(ConstIdT),
CK_BitCast,
DictLiteralValueME);
// (const id [])keys
Expr *NSKeyCallExpr =
new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
NSDictFType, VK_LValue, SourceLocation());
MemberExpr *DictLiteralKeyME =
new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
SourceLocation(),
ARRFD->getType(), VK_LValue,
OK_Ordinary);
CStyleCastExpr * DictKeyObjects =
NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(ConstIdT),
CK_BitCast,
DictLiteralKeyME);
// Synthesize a call to objc_msgSend().
SmallVector MsgExprs;
SmallVector ClsExprs;
QualType expType = Exp->getType();
// Create a call to objc_getClass("NSArray"). It will be th 1st argument.
ObjCInterfaceDecl *Class =
expType->getPointeeType()->getAs()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(Cls);
// Create a call to sel_registerName("arrayWithObjects:count:").
// it will be the 2nd argument.
SmallVector SelExprs;
ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
&SelExprs[0], SelExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(SelExp);
// (const id [])objects
MsgExprs.push_back(DictValueObjects);
// (const id [])keys
MsgExprs.push_back(DictKeyObjects);
// (NSUInteger)cnt
Expr *cnt = IntegerLiteral::Create(*Context,
llvm::APInt(UnsignedIntSize, NumElements),
Context->UnsignedIntTy, SourceLocation());
MsgExprs.push_back(cnt);
SmallVector ArgTypes;
ArgTypes.push_back(Context->getObjCIdType());
ArgTypes.push_back(Context->getObjCSelType());
for (const auto *PI : DictMethod->params()) {
QualType T = PI->getType();
if (const PointerType* PT = T->getAs()) {
QualType PointeeTy = PT->getPointeeType();
convertToUnqualifiedObjCType(PointeeTy);
T = Context->getPointerType(PointeeTy);
}
ArgTypes.push_back(T);
}
QualType returnType = Exp->getType();
// Get the type, we will need to reference it in a couple spots.
QualType msgSendType = MsgSendFlavor->getType();
// Create a reference to the objc_msgSend() declaration.
DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
VK_LValue, SourceLocation());
CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(Context->VoidTy),
CK_BitCast, DRE);
// Now do the "normal" pointer to function cast.
QualType castType =
getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
castType = Context->getPointerType(castType);
cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
cast);
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
const FunctionType *FT = msgSendType->getAs();
CallExpr *CE = new (Context)
CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
ReplaceStmt(Exp, CE);
return CE;
}
// struct __rw_objc_super {
// struct objc_object *object; struct objc_object *superClass;
// };
QualType RewriteModernObjC::getSuperStructType() {
if (!SuperStructDecl) {
SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("__rw_objc_super"));
QualType FieldTypes[2];
// struct objc_object *object;
FieldTypes[0] = Context->getObjCIdType();
// struct objc_object *superClass;
FieldTypes[1] = Context->getObjCIdType();
// Create fields
for (unsigned i = 0; i < 2; ++i) {
SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
SourceLocation(),
SourceLocation(), nullptr,
FieldTypes[i], nullptr,
/*BitWidth=*/nullptr,
/*Mutable=*/false,
ICIS_NoInit));
}
SuperStructDecl->completeDefinition();
}
return Context->getTagDeclType(SuperStructDecl);
}
QualType RewriteModernObjC::getConstantStringStructType() {
if (!ConstantStringDecl) {
ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("__NSConstantStringImpl"));
QualType FieldTypes[4];
// struct objc_object *receiver;
FieldTypes[0] = Context->getObjCIdType();
// int flags;
FieldTypes[1] = Context->IntTy;
// char *str;
FieldTypes[2] = Context->getPointerType(Context->CharTy);
// long length;
FieldTypes[3] = Context->LongTy;
// Create fields
for (unsigned i = 0; i < 4; ++i) {
ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
ConstantStringDecl,
SourceLocation(),
SourceLocation(), nullptr,
FieldTypes[i], nullptr,
/*BitWidth=*/nullptr,
/*Mutable=*/true,
ICIS_NoInit));
}
ConstantStringDecl->completeDefinition();
}
return Context->getTagDeclType(ConstantStringDecl);
}
/// getFunctionSourceLocation - returns start location of a function
/// definition. Complication arises when function has declared as
/// extern "C" or extern "C" {...}
static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
FunctionDecl *FD) {
if (FD->isExternC() && !FD->isMain()) {
const DeclContext *DC = FD->getDeclContext();
if (const LinkageSpecDecl *LSD = dyn_cast(DC))
// if it is extern "C" {...}, return function decl's own location.
if (!LSD->getRBraceLoc().isValid())
return LSD->getExternLoc();
}
if (FD->getStorageClass() != SC_None)
R.RewriteBlockLiteralFunctionDecl(FD);
return FD->getTypeSpecStartLoc();
}
void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
SourceLocation Location = D->getLocation();
if (Location.isFileID() && GenerateLineInfo) {
std::string LineString("\n#line ");
PresumedLoc PLoc = SM->getPresumedLoc(Location);
LineString += utostr(PLoc.getLine());
LineString += " \"";
LineString += Lexer::Stringify(PLoc.getFilename());
if (isa(D))
LineString += "\"";
else LineString += "\"\n";
Location = D->getLocStart();
if (const FunctionDecl *FD = dyn_cast(D)) {
if (FD->isExternC() && !FD->isMain()) {
const DeclContext *DC = FD->getDeclContext();
if (const LinkageSpecDecl *LSD = dyn_cast(DC))
// if it is extern "C" {...}, return function decl's own location.
if (!LSD->getRBraceLoc().isValid())
Location = LSD->getExternLoc();
}
}
InsertText(Location, LineString);
}
}
/// SynthMsgSendStretCallExpr - This routine translates message expression
/// into a call to objc_msgSend_stret() entry point. Tricky part is that
/// nil check on receiver must be performed before calling objc_msgSend_stret.
/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
/// msgSendType - function type of objc_msgSend_stret(...)
/// returnType - Result type of the method being synthesized.
/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
/// starting with receiver.
/// Method - Method being rewritten.
Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
QualType returnType,
SmallVectorImpl &ArgTypes,
SmallVectorImpl &MsgExprs,
ObjCMethodDecl *Method) {
// Now do the "normal" pointer to function cast.
QualType castType = getSimpleFunctionType(returnType, ArgTypes,
Method ? Method->isVariadic()
: false);
castType = Context->getPointerType(castType);
// build type for containing the objc_msgSend_stret object.
static unsigned stretCount=0;
std::string name = "__Stret"; name += utostr(stretCount);
std::string str =
"extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
str += "namespace {\n";
str += "struct "; str += name;
str += " {\n\t";
str += name;
str += "(id receiver, SEL sel";
for (unsigned i = 2; i < ArgTypes.size(); i++) {
std::string ArgName = "arg"; ArgName += utostr(i);
ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
str += ", "; str += ArgName;
}
// could be vararg.
for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
std::string ArgName = "arg"; ArgName += utostr(i);
MsgExprs[i]->getType().getAsStringInternal(ArgName,
Context->getPrintingPolicy());
str += ", "; str += ArgName;
}
str += ") {\n";
str += "\t unsigned size = sizeof(";
str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
str += ")(void *)objc_msgSend)(receiver, sel";
for (unsigned i = 2; i < ArgTypes.size(); i++) {
str += ", arg"; str += utostr(i);
}
// could be vararg.
for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
str += ", arg"; str += utostr(i);
}
str+= ");\n";
str += "\t else if (receiver == 0)\n";
str += "\t memset((void*)&s, 0, sizeof(s));\n";
str += "\t else\n";
str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
str += ")(void *)objc_msgSend_stret)(receiver, sel";
for (unsigned i = 2; i < ArgTypes.size(); i++) {
str += ", arg"; str += utostr(i);
}
// could be vararg.
for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
str += ", arg"; str += utostr(i);
}
str += ");\n";
str += "\t}\n";
str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
str += " s;\n";
str += "};\n};\n\n";
SourceLocation FunLocStart;
if (CurFunctionDef)
FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
else {
assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
FunLocStart = CurMethodDef->getLocStart();
}
InsertText(FunLocStart, str);
++stretCount;
// AST for __Stretn(receiver, args).s;
IdentifierInfo *ID = &Context->Idents.get(name);
FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
SourceLocation(), ID, castType,
nullptr, SC_Extern, false, false);
DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
SourceLocation());
CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
castType, VK_LValue, SourceLocation());
FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
SourceLocation(),
&Context->Idents.get("s"),
returnType, nullptr,
/*BitWidth=*/nullptr,
/*Mutable=*/true, ICIS_NoInit);
MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
FieldD->getType(), VK_LValue,
OK_Ordinary);
return ME;
}
Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
SourceLocation StartLoc,
SourceLocation EndLoc) {
if (!SelGetUidFunctionDecl)
SynthSelGetUidFunctionDecl();
if (!MsgSendFunctionDecl)
SynthMsgSendFunctionDecl();
if (!MsgSendSuperFunctionDecl)
SynthMsgSendSuperFunctionDecl();
if (!MsgSendStretFunctionDecl)
SynthMsgSendStretFunctionDecl();
if (!MsgSendSuperStretFunctionDecl)
SynthMsgSendSuperStretFunctionDecl();
if (!MsgSendFpretFunctionDecl)
SynthMsgSendFpretFunctionDecl();
if (!GetClassFunctionDecl)
SynthGetClassFunctionDecl();
if (!GetSuperClassFunctionDecl)
SynthGetSuperClassFunctionDecl();
if (!GetMetaClassFunctionDecl)
SynthGetMetaClassFunctionDecl();
// default to objc_msgSend().
FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
// May need to use objc_msgSend_stret() as well.
FunctionDecl *MsgSendStretFlavor = nullptr;
if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
QualType resultType = mDecl->getReturnType();
if (resultType->isRecordType())
MsgSendStretFlavor = MsgSendStretFunctionDecl;
else if (resultType->isRealFloatingType())
MsgSendFlavor = MsgSendFpretFunctionDecl;
}
// Synthesize a call to objc_msgSend().
SmallVector MsgExprs;
switch (Exp->getReceiverKind()) {
case ObjCMessageExpr::SuperClass: {
MsgSendFlavor = MsgSendSuperFunctionDecl;
if (MsgSendStretFlavor)
MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
SmallVector InitExprs;
// set the receiver to self, the first argument to all methods.
InitExprs.push_back(
NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK_BitCast,
new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
false,
Context->getObjCIdType(),
VK_RValue,
SourceLocation()))
); // set the 'receiver'.
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
SmallVector ClsExprs;
ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
// (Class)objc_getClass("CurrentClass")
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc,
EndLoc);
ClsExprs.clear();
ClsExprs.push_back(Cls);
Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
&ClsExprs[0], ClsExprs.size(),
StartLoc, EndLoc);
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
// To turn off a warning, type-cast to 'id'
InitExprs.push_back( // set 'super class', using class_getSuperclass().
NoTypeInfoCStyleCastExpr(Context,
Context->getObjCIdType(),
CK_BitCast, Cls));
// struct __rw_objc_super
QualType superType = getSuperStructType();
Expr *SuperRep;
if (LangOpts.MicrosoftExt) {
SynthSuperConstructorFunctionDecl();
// Simulate a constructor call...
DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
false, superType, VK_LValue,
SourceLocation());
SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
superType, VK_LValue,
SourceLocation());
// The code for super is a little tricky to prevent collision with
// the structure definition in the header. The rewriter has it's own
// internal definition (__rw_objc_super) that is uses. This is why
// we need the cast below. For example:
// (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
//
SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Context->getPointerType(SuperRep->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
SuperRep = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(superType),
CK_BitCast, SuperRep);
} else {
// (struct __rw_objc_super) { }
InitListExpr *ILE =
new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
SourceLocation());
TypeSourceInfo *superTInfo
= Context->getTrivialTypeSourceInfo(superType);
SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
superType, VK_LValue,
ILE, false);
// struct __rw_objc_super *
SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Context->getPointerType(SuperRep->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
}
MsgExprs.push_back(SuperRep);
break;
}
case ObjCMessageExpr::Class: {
SmallVector ClsExprs;
ObjCInterfaceDecl *Class
= Exp->getClassReceiver()->getAs()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
Context->getObjCIdType(),
CK_BitCast, Cls);
MsgExprs.push_back(ArgExpr);
break;
}
case ObjCMessageExpr::SuperInstance:{
MsgSendFlavor = MsgSendSuperFunctionDecl;
if (MsgSendStretFlavor)
MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
SmallVector InitExprs;
InitExprs.push_back(
NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK_BitCast,
new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
false,
Context->getObjCIdType(),
VK_RValue, SourceLocation()))
); // set the 'receiver'.
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
SmallVector ClsExprs;
ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
// (Class)objc_getClass("CurrentClass")
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
ClsExprs.clear();
ClsExprs.push_back(Cls);
Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
&ClsExprs[0], ClsExprs.size(),
StartLoc, EndLoc);
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
// To turn off a warning, type-cast to 'id'
InitExprs.push_back(
// set 'super class', using class_getSuperclass().
NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK_BitCast, Cls));
// struct __rw_objc_super
QualType superType = getSuperStructType();
Expr *SuperRep;
if (LangOpts.MicrosoftExt) {
SynthSuperConstructorFunctionDecl();
// Simulate a constructor call...
DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
false, superType, VK_LValue,
SourceLocation());
SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
superType, VK_LValue, SourceLocation());
// The code for super is a little tricky to prevent collision with
// the structure definition in the header. The rewriter has it's own
// internal definition (__rw_objc_super) that is uses. This is why
// we need the cast below. For example:
// (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
//
SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Context->getPointerType(SuperRep->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
SuperRep = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(superType),
CK_BitCast, SuperRep);
} else {
// (struct __rw_objc_super) { }
InitListExpr *ILE =
new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
SourceLocation());
TypeSourceInfo *superTInfo
= Context->getTrivialTypeSourceInfo(superType);
SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
superType, VK_RValue, ILE,
false);
}
MsgExprs.push_back(SuperRep);
break;
}
case ObjCMessageExpr::Instance: {
// Remove all type-casts because it may contain objc-style types; e.g.
// Foo *.
Expr *recExpr = Exp->getInstanceReceiver();
while (CStyleCastExpr *CE = dyn_cast(recExpr))
recExpr = CE->getSubExpr();
CastKind CK = recExpr->getType()->isObjCObjectPointerType()
? CK_BitCast : recExpr->getType()->isBlockPointerType()
? CK_BlockPointerToObjCPointerCast
: CK_CPointerToObjCPointerCast;
recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK, recExpr);
MsgExprs.push_back(recExpr);
break;
}
}
// Create a call to sel_registerName("selName"), it will be the 2nd argument.
SmallVector SelExprs;
SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
&SelExprs[0], SelExprs.size(),
StartLoc,
EndLoc);
MsgExprs.push_back(SelExp);
// Now push any user supplied arguments.
for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Expr *userExpr = Exp->getArg(i);
// Make all implicit casts explicit...ICE comes in handy:-)
if (ImplicitCastExpr *ICE = dyn_cast(userExpr)) {
// Reuse the ICE type, it is exactly what the doctor ordered.
QualType type = ICE->getType();
if (needToScanForQualifiers(type))
type = Context->getObjCIdType();
// Make sure we convert "type (^)(...)" to "type (*)(...)".
(void)convertBlockPointerToFunctionPointer(type);
const Expr *SubExpr = ICE->IgnoreParenImpCasts();
CastKind CK;
if (SubExpr->getType()->isIntegralType(*Context) &&
type->isBooleanType()) {
CK = CK_IntegralToBoolean;
} else if (type->isObjCObjectPointerType()) {
if (SubExpr->getType()->isBlockPointerType()) {
CK = CK_BlockPointerToObjCPointerCast;
} else if (SubExpr->getType()->isPointerType()) {
CK = CK_CPointerToObjCPointerCast;
} else {
CK = CK_BitCast;
}
} else {
CK = CK_BitCast;
}
userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
}
// Make id cast into an 'id' cast.
else if (CStyleCastExpr *CE = dyn_cast(userExpr)) {
if (CE->getType()->isObjCQualifiedIdType()) {
while ((CE = dyn_cast(userExpr)))
userExpr = CE->getSubExpr();
CastKind CK;
if (userExpr->getType()->isIntegralType(*Context)) {
CK = CK_IntegralToPointer;
} else if (userExpr->getType()->isBlockPointerType()) {
CK = CK_BlockPointerToObjCPointerCast;
} else if (userExpr->getType()->isPointerType()) {
CK = CK_CPointerToObjCPointerCast;
} else {
CK = CK_BitCast;
}
userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK, userExpr);
}
}
MsgExprs.push_back(userExpr);
// We've transferred the ownership to MsgExprs. For now, we *don't* null
// out the argument in the original expression (since we aren't deleting
// the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
//Exp->setArg(i, 0);
}
// Generate the funky cast.
CastExpr *cast;
SmallVector ArgTypes;
QualType returnType;
// Push 'id' and 'SEL', the 2 implicit arguments.
if (MsgSendFlavor == MsgSendSuperFunctionDecl)
ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
else
ArgTypes.push_back(Context->getObjCIdType());
ArgTypes.push_back(Context->getObjCSelType());
if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
// Push any user argument types.
for (const auto *PI : OMD->params()) {
QualType t = PI->getType()->isObjCQualifiedIdType()
? Context->getObjCIdType()
: PI->getType();
// Make sure we convert "t (^)(...)" to "t (*)(...)".
(void)convertBlockPointerToFunctionPointer(t);
ArgTypes.push_back(t);
}
returnType = Exp->getType();
convertToUnqualifiedObjCType(returnType);
(void)convertBlockPointerToFunctionPointer(returnType);
} else {
returnType = Context->getObjCIdType();
}
// Get the type, we will need to reference it in a couple spots.
QualType msgSendType = MsgSendFlavor->getType();
// Create a reference to the objc_msgSend() declaration.
DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
VK_LValue, SourceLocation());
// Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
// If we don't do this cast, we get the following bizarre warning/note:
// xx.m:13: warning: function called through a non-compatible type
// xx.m:13: note: if this code is reached, the program will abort
cast = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(Context->VoidTy),
CK_BitCast, DRE);
// Now do the "normal" pointer to function cast.
// If we don't have a method decl, force a variadic cast.
const ObjCMethodDecl *MD = Exp->getMethodDecl();
QualType castType =
getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
castType = Context->getPointerType(castType);
cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
cast);
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
const FunctionType *FT = msgSendType->getAs();
CallExpr *CE = new (Context)
CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Stmt *ReplacingStmt = CE;
if (MsgSendStretFlavor) {
// We have the method which returns a struct/union. Must also generate
// call to objc_msgSend_stret and hang both varieties on a conditional
// expression which dictate which one to envoke depending on size of
// method's return type.
Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
returnType,
ArgTypes, MsgExprs,
Exp->getMethodDecl());
ReplacingStmt = STCE;
}
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return ReplacingStmt;
}
Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
Exp->getLocEnd());
// Now do the actual rewrite.
ReplaceStmt(Exp, ReplacingStmt);
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return ReplacingStmt;
}
// typedef struct objc_object Protocol;
QualType RewriteModernObjC::getProtocolType() {
if (!ProtocolTypeDecl) {
TypeSourceInfo *TInfo
= Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("Protocol"),
TInfo);
}
return Context->getTypeDeclType(ProtocolTypeDecl);
}
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
/// a synthesized/forward data reference (to the protocol's metadata).
/// The forward references (and metadata) are generated in
/// RewriteModernObjC::HandleTranslationUnit().
Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
Exp->getProtocol()->getNameAsString();
IdentifierInfo *ID = &Context->Idents.get(Name);
VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
SourceLocation(), ID, getProtocolType(),
nullptr, SC_Extern);
DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
VK_LValue, SourceLocation());
CastExpr *castExpr =
NoTypeInfoCStyleCastExpr(
Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
ReplaceStmt(Exp, castExpr);
ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return castExpr;
}
bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
const char *endBuf) {
while (startBuf < endBuf) {
if (*startBuf == '#') {
// Skip whitespace.
for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
;
if (!strncmp(startBuf, "if", strlen("if")) ||
!strncmp(startBuf, "ifdef", strlen("ifdef")) ||
!strncmp(startBuf, "ifndef", strlen("ifndef")) ||
!strncmp(startBuf, "define", strlen("define")) ||
!strncmp(startBuf, "undef", strlen("undef")) ||
!strncmp(startBuf, "else", strlen("else")) ||
!strncmp(startBuf, "elif", strlen("elif")) ||
!strncmp(startBuf, "endif", strlen("endif")) ||
!strncmp(startBuf, "pragma", strlen("pragma")) ||
!strncmp(startBuf, "include", strlen("include")) ||
!strncmp(startBuf, "import", strlen("import")) ||
!strncmp(startBuf, "include_next", strlen("include_next")))
return true;
}
startBuf++;
}
return false;
}
/// IsTagDefinedInsideClass - This routine checks that a named tagged type
/// is defined inside an objective-c class. If so, it returns true.
bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
TagDecl *Tag,
bool &IsNamedDefinition) {
if (!IDecl)
return false;
SourceLocation TagLocation;
if (RecordDecl *RD = dyn_cast(Tag)) {
RD = RD->getDefinition();
if (!RD || !RD->getDeclName().getAsIdentifierInfo())
return false;
IsNamedDefinition = true;
TagLocation = RD->getLocation();
return Context->getSourceManager().isBeforeInTranslationUnit(
IDecl->getLocation(), TagLocation);
}
if (EnumDecl *ED = dyn_cast(Tag)) {
if (!ED || !ED->getDeclName().getAsIdentifierInfo())
return false;
IsNamedDefinition = true;
TagLocation = ED->getLocation();
return Context->getSourceManager().isBeforeInTranslationUnit(
IDecl->getLocation(), TagLocation);
}
return false;
}
/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
/// It handles elaborated types, as well as enum types in the process.
bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
std::string &Result) {
if (isa(Type)) {
Result += "\t";
return false;
}
if (Type->isArrayType()) {
QualType ElemTy = Context->getBaseElementType(Type);
return RewriteObjCFieldDeclType(ElemTy, Result);
}
else if (Type->isRecordType()) {
RecordDecl *RD = Type->getAs()->getDecl();
if (RD->isCompleteDefinition()) {
if (RD->isStruct())
Result += "\n\tstruct ";
else if (RD->isUnion())
Result += "\n\tunion ";
else
assert(false && "class not allowed as an ivar type");
Result += RD->getName();
if (GlobalDefinedTags.count(RD)) {
// struct/union is defined globally, use it.
Result += " ";
return true;
}
Result += " {\n";
for (auto *FD : RD->fields())
RewriteObjCFieldDecl(FD, Result);
Result += "\t} ";
return true;
}
}
else if (Type->isEnumeralType()) {
EnumDecl *ED = Type->getAs()->getDecl();
if (ED->isCompleteDefinition()) {
Result += "\n\tenum ";
Result += ED->getName();
if (GlobalDefinedTags.count(ED)) {
// Enum is globall defined, use it.
Result += " ";
return true;
}
Result += " {\n";
for (const auto *EC : ED->enumerators()) {
Result += "\t"; Result += EC->getName(); Result += " = ";
llvm::APSInt Val = EC->getInitVal();
Result += Val.toString(10);
Result += ",\n";
}
Result += "\t} ";
return true;
}
}
Result += "\t";
convertObjCTypeToCStyleType(Type);
return false;
}
/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
/// It handles elaborated types, as well as enum types in the process.
void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
std::string &Result) {
QualType Type = fieldDecl->getType();
std::string Name = fieldDecl->getNameAsString();
bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
if (!EleboratedType)
Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Result += Name;
if (fieldDecl->isBitField()) {
Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
}
else if (EleboratedType && Type->isArrayType()) {
const ArrayType *AT = Context->getAsArrayType(Type);
do {
if (const ConstantArrayType *CAT = dyn_cast(AT)) {
Result += "[";
llvm::APInt Dim = CAT->getSize();
Result += utostr(Dim.getZExtValue());
Result += "]";
}
AT = Context->getAsArrayType(AT->getElementType());
} while (AT);
}
Result += ";\n";
}
/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
/// named aggregate types into the input buffer.
void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
std::string &Result) {
QualType Type = fieldDecl->getType();
if (isa(Type))
return;
if (Type->isArrayType())
Type = Context->getBaseElementType(Type);
ObjCContainerDecl *IDecl =
dyn_cast(fieldDecl->getDeclContext());
TagDecl *TD = nullptr;
if (Type->isRecordType()) {
TD = Type->getAs()->getDecl();
}
else if (Type->isEnumeralType()) {
TD = Type->getAs()->getDecl();
}
if (TD) {
if (GlobalDefinedTags.count(TD))
return;
bool IsNamedDefinition = false;
if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
RewriteObjCFieldDeclType(Type, Result);
Result += ";";
}
if (IsNamedDefinition)
GlobalDefinedTags.insert(TD);
}
}
unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
return IvarGroupNumber[IV];
}
unsigned GroupNo = 0;
SmallVector IVars;
for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
IVD; IVD = IVD->getNextIvar())
IVars.push_back(IVD);
for (unsigned i = 0, e = IVars.size(); i < e; i++)
if (IVars[i]->isBitField()) {
IvarGroupNumber[IVars[i++]] = ++GroupNo;
while (i < e && IVars[i]->isBitField())
IvarGroupNumber[IVars[i++]] = GroupNo;
if (i < e)
--i;
}
ObjCInterefaceHasBitfieldGroups.insert(CDecl);
return IvarGroupNumber[IV];
}
QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
ObjCIvarDecl *IV,
SmallVectorImpl &IVars) {
std::string StructTagName;
ObjCIvarBitfieldGroupType(IV, StructTagName);
RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
Context->getTranslationUnitDecl(),
SourceLocation(), SourceLocation(),
&Context->Idents.get(StructTagName));
for (unsigned i=0, e = IVars.size(); i < e; i++) {
ObjCIvarDecl *Ivar = IVars[i];
RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
&Context->Idents.get(Ivar->getName()),
Ivar->getType(),
nullptr, /*Expr *BW */Ivar->getBitWidth(),
false, ICIS_NoInit));
}
RD->completeDefinition();
return Context->getTagDeclType(RD);
}
QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
std::pair tuple = std::make_pair(CDecl, GroupNo);
if (GroupRecordType.count(tuple))
return GroupRecordType[tuple];
SmallVector IVars;
for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
IVD; IVD = IVD->getNextIvar()) {
if (IVD->isBitField())
IVars.push_back(const_cast(IVD));
else {
if (!IVars.empty()) {
unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
// Generate the struct type for this group of bitfield ivars.
GroupRecordType[std::make_pair(CDecl, GroupNo)] =
SynthesizeBitfieldGroupStructType(IVars[0], IVars);
IVars.clear();
}
}
}
if (!IVars.empty()) {
// Do the last one.
unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
GroupRecordType[std::make_pair(CDecl, GroupNo)] =
SynthesizeBitfieldGroupStructType(IVars[0], IVars);
}
QualType RetQT = GroupRecordType[tuple];
assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
return RetQT;
}
/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
/// Name would be: classname__GRBF_n where n is the group number for this ivar.
void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
std::string &Result) {
const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
Result += CDecl->getName();
Result += "__GRBF_";
unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
Result += utostr(GroupNo);
return;
}
/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
/// Name of the struct would be: classname__T_n where n is the group number for
/// this ivar.
void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
std::string &Result) {
const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
Result += CDecl->getName();
Result += "__T_";
unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
Result += utostr(GroupNo);
return;
}
/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
/// this ivar.
void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
std::string &Result) {
Result += "OBJC_IVAR_$_";
ObjCIvarBitfieldGroupDecl(IV, Result);
}
#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
while ((IX < ENDIX) && VEC[IX]->isBitField()) \
++IX; \
if (IX < ENDIX) \
--IX; \
}
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
/// an objective-c class with ivars.
void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
std::string &Result) {
assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
assert(CDecl->getName() != "" &&
"Name missing in SynthesizeObjCInternalStruct");
ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
SmallVector IVars;
for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
IVD; IVD = IVD->getNextIvar())
IVars.push_back(IVD);
SourceLocation LocStart = CDecl->getLocStart();
SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
const char *startBuf = SM->getCharacterData(LocStart);
const char *endBuf = SM->getCharacterData(LocEnd);
// If no ivars and no root or if its root, directly or indirectly,
// have no ivars (thus not synthesized) then no need to synthesize this class.
if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
(!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
ReplaceText(LocStart, endBuf-startBuf, Result);
return;
}
// Insert named struct/union definitions inside class to
// outer scope. This follows semantics of locally defined
// struct/unions in objective-c classes.
for (unsigned i = 0, e = IVars.size(); i < e; i++)
RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
// Insert named structs which are syntheized to group ivar bitfields
// to outer scope as well.
for (unsigned i = 0, e = IVars.size(); i < e; i++)
if (IVars[i]->isBitField()) {
ObjCIvarDecl *IV = IVars[i];
QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
RewriteObjCFieldDeclType(QT, Result);
Result += ";";
// skip over ivar bitfields in this group.
SKIP_BITFIELDS(i , e, IVars);
}
Result += "\nstruct ";
Result += CDecl->getNameAsString();
Result += "_IMPL {\n";
if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Result += "\tstruct "; Result += RCDecl->getNameAsString();
Result += "_IMPL "; Result += RCDecl->getNameAsString();
Result += "_IVARS;\n";
}
for (unsigned i = 0, e = IVars.size(); i < e; i++) {
if (IVars[i]->isBitField()) {
ObjCIvarDecl *IV = IVars[i];
Result += "\tstruct ";
ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
// skip over ivar bitfields in this group.
SKIP_BITFIELDS(i , e, IVars);
}
else
RewriteObjCFieldDecl(IVars[i], Result);
}
Result += "};\n";
endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
ReplaceText(LocStart, endBuf-startBuf, Result);
// Mark this struct as having been generated.
if (!ObjCSynthesizedStructs.insert(CDecl))
llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
}
/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
/// have been referenced in an ivar access expression.
void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
std::string &Result) {
// write out ivar offset symbols which have been referenced in an ivar
// access expression.
llvm::SmallPtrSet Ivars = ReferencedIvars[CDecl];
if (Ivars.empty())
return;
llvm::DenseSet > GroupSymbolOutput;
for (llvm::SmallPtrSet::iterator i = Ivars.begin(),
e = Ivars.end(); i != e; i++) {
ObjCIvarDecl *IvarDecl = (*i);
const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
unsigned GroupNo = 0;
if (IvarDecl->isBitField()) {
GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
continue;
}
Result += "\n";
if (LangOpts.MicrosoftExt)
Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Result += "extern \"C\" ";
if (LangOpts.MicrosoftExt &&
IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
Result += "__declspec(dllimport) ";
Result += "unsigned long ";
if (IvarDecl->isBitField()) {
ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
}
else
WriteInternalIvarName(CDecl, IvarDecl, Result);
Result += ";";
}
}
//===----------------------------------------------------------------------===//
// Meta Data Emission
//===----------------------------------------------------------------------===//
/// RewriteImplementations - This routine rewrites all method implementations
/// and emits meta-data.
void RewriteModernObjC::RewriteImplementations() {
int ClsDefCount = ClassImplementation.size();
int CatDefCount = CategoryImplementation.size();
// Rewrite implemented methods
for (int i = 0; i < ClsDefCount; i++) {
ObjCImplementationDecl *OIMP = ClassImplementation[i];
ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
if (CDecl->isImplicitInterfaceDecl())
assert(false &&
"Legacy implicit interface rewriting not supported in moder abi");
RewriteImplementationDecl(OIMP);
}
for (int i = 0; i < CatDefCount; i++) {
ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
if (CDecl->isImplicitInterfaceDecl())
assert(false &&
"Legacy implicit interface rewriting not supported in moder abi");
RewriteImplementationDecl(CIMP);
}
}
void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
const std::string &Name,
ValueDecl *VD, bool def) {
assert(BlockByRefDeclNo.count(VD) &&
"RewriteByRefString: ByRef decl missing");
if (def)
ResultStr += "struct ";
ResultStr += "__Block_byref_" + Name +
"_" + utostr(BlockByRefDeclNo[VD]) ;
}
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
if (VarDecl *Var = dyn_cast(VD))
return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
return false;
}
std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
StringRef funcName,
std::string Tag) {
const FunctionType *AFT = CE->getFunctionType();
QualType RT = AFT->getReturnType();
std::string StructRef = "struct " + Tag;
SourceLocation BlockLoc = CE->getExprLoc();
std::string S;
ConvertSourceLocationToLineDirective(BlockLoc, S);
S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
funcName.str() + "_block_func_" + utostr(i);
BlockDecl *BD = CE->getBlockDecl();
if (isa(AFT)) {
// No user-supplied arguments. Still need to pass in a pointer to the
// block (to reference imported block decl refs).
S += "(" + StructRef + " *__cself)";
} else if (BD->param_empty()) {
S += "(" + StructRef + " *__cself)";
} else {
const FunctionProtoType *FT = cast(AFT);
assert(FT && "SynthesizeBlockFunc: No function proto");
S += '(';
// first add the implicit argument.
S += StructRef + " *__cself, ";
std::string ParamStr;
for (BlockDecl::param_iterator AI = BD->param_begin(),
E = BD->param_end(); AI != E; ++AI) {
if (AI != BD->param_begin()) S += ", ";
ParamStr = (*AI)->getNameAsString();
QualType QT = (*AI)->getType();
(void)convertBlockPointerToFunctionPointer(QT);
QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
S += ParamStr;
}
if (FT->isVariadic()) {
if (!BD->param_empty()) S += ", ";
S += "...";
}
S += ')';
}
S += " {\n";
// Create local declarations to avoid rewriting all closure decl ref exprs.
// First, emit a declaration for all "by ref" decls.
for (SmallVectorImpl::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
S += " ";
std::string Name = (*I)->getNameAsString();
std::string TypeString;
RewriteByRefString(TypeString, Name, (*I));
TypeString += " *";
Name = TypeString + Name;
S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
}
// Next, emit a declaration for all "by copy" declarations.
for (SmallVectorImpl::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
S += " ";
// Handle nested closure invocation. For example:
//
// void (^myImportedClosure)(void);
// myImportedClosure = ^(void) { setGlobalInt(x + y); };
//
// void (^anotherClosure)(void);
// anotherClosure = ^(void) {
// myImportedClosure(); // import and invoke the closure
// };
//
if (isTopLevelBlockPointerType((*I)->getType())) {
RewriteBlockPointerTypeVariable(S, (*I));
S += " = (";
RewriteBlockPointerType(S, (*I)->getType());
S += ")";
S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
}
else {
std::string Name = (*I)->getNameAsString();
QualType QT = (*I)->getType();
if (HasLocalVariableExternalStorage(*I))
QT = Context->getPointerType(QT);
QT.getAsStringInternal(Name, Context->getPrintingPolicy());
S += Name + " = __cself->" +
(*I)->getNameAsString() + "; // bound by copy\n";
}
}
std::string RewrittenStr = RewrittenBlockExprs[CE];
const char *cstr = RewrittenStr.c_str();
while (*cstr++ != '{') ;
S += cstr;
S += "\n";
return S;
}
std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
StringRef funcName,
std::string Tag) {
std::string StructRef = "struct " + Tag;
std::string S = "static void __";
S += funcName;
S += "_block_copy_" + utostr(i);
S += "(" + StructRef;
S += "*dst, " + StructRef;
S += "*src) {";
for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(),
E = ImportedBlockDecls.end(); I != E; ++I) {
ValueDecl *VD = (*I);
S += "_Block_object_assign((void*)&dst->";
S += (*I)->getNameAsString();
S += ", (void*)src->";
S += (*I)->getNameAsString();
if (BlockByRefDeclsPtrSet.count((*I)))
S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
else if (VD->getType()->isBlockPointerType())
S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
else
S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
}
S += "}\n";
S += "\nstatic void __";
S += funcName;
S += "_block_dispose_" + utostr(i);
S += "(" + StructRef;
S += "*src) {";
for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(),
E = ImportedBlockDecls.end(); I != E; ++I) {
ValueDecl *VD = (*I);
S += "_Block_object_dispose((void*)src->";
S += (*I)->getNameAsString();
if (BlockByRefDeclsPtrSet.count((*I)))
S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
else if (VD->getType()->isBlockPointerType())
S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
else
S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
}
S += "}\n";
return S;
}
std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
std::string Desc) {
std::string S = "\nstruct " + Tag;
std::string Constructor = " " + Tag;
S += " {\n struct __block_impl impl;\n";
S += " struct " + Desc;
S += "* Desc;\n";
Constructor += "(void *fp, "; // Invoke function pointer.
Constructor += "struct " + Desc; // Descriptor pointer.
Constructor += " *desc";
if (BlockDeclRefs.size()) {
// Output all "by copy" declarations.
for (SmallVectorImpl::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
S += " ";
std::string FieldName = (*I)->getNameAsString();
std::string ArgName = "_" + FieldName;
// Handle nested closure invocation. For example:
//
// void (^myImportedBlock)(void);
// myImportedBlock = ^(void) { setGlobalInt(x + y); };
//
// void (^anotherBlock)(void);
// anotherBlock = ^(void) {
// myImportedBlock(); // import and invoke the closure
// };
//
if (isTopLevelBlockPointerType((*I)->getType())) {
S += "struct __block_impl *";
Constructor += ", void *" + ArgName;
} else {
QualType QT = (*I)->getType();
if (HasLocalVariableExternalStorage(*I))
QT = Context->getPointerType(QT);
QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Constructor += ", " + ArgName;
}
S += FieldName + ";\n";
}
// Output all "by ref" declarations.
for (SmallVectorImpl::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
S += " ";
std::string FieldName = (*I)->getNameAsString();
std::string ArgName = "_" + FieldName;
{
std::string TypeString;
RewriteByRefString(TypeString, FieldName, (*I));
TypeString += " *";
FieldName = TypeString + FieldName;
ArgName = TypeString + ArgName;
Constructor += ", " + ArgName;
}
S += FieldName + "; // by ref\n";
}
// Finish writing the constructor.
Constructor += ", int flags=0)";
// Initialize all "by copy" arguments.
bool firsTime = true;
for (SmallVectorImpl::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
std::string Name = (*I)->getNameAsString();
if (firsTime) {
Constructor += " : ";
firsTime = false;
}
else
Constructor += ", ";
if (isTopLevelBlockPointerType((*I)->getType()))
Constructor += Name + "((struct __block_impl *)_" + Name + ")";
else
Constructor += Name + "(_" + Name + ")";
}
// Initialize all "by ref" arguments.
for (SmallVectorImpl::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
std::string Name = (*I)->getNameAsString();
if (firsTime) {
Constructor += " : ";
firsTime = false;
}
else
Constructor += ", ";
Constructor += Name + "(_" + Name + "->__forwarding)";
}
Constructor += " {\n";
if (GlobalVarDecl)
Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
else
Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Constructor += " Desc = desc;\n";
} else {
// Finish writing the constructor.
Constructor += ", int flags=0) {\n";
if (GlobalVarDecl)
Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
else
Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Constructor += " Desc = desc;\n";
}
Constructor += " ";
Constructor += "}\n";
S += Constructor;
S += "};\n";
return S;
}
std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
std::string ImplTag, int i,
StringRef FunName,
unsigned hasCopy) {
std::string S = "\nstatic struct " + DescTag;
S += " {\n size_t reserved;\n";
S += " size_t Block_size;\n";
if (hasCopy) {
S += " void (*copy)(struct ";
S += ImplTag; S += "*, struct ";
S += ImplTag; S += "*);\n";
S += " void (*dispose)(struct ";
S += ImplTag; S += "*);\n";
}
S += "} ";
S += DescTag + "_DATA = { 0, sizeof(struct ";
S += ImplTag + ")";
if (hasCopy) {
S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
}
S += "};\n";
return S;
}
void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
StringRef FunName) {
bool RewriteSC = (GlobalVarDecl &&
!Blocks.empty() &&
GlobalVarDecl->getStorageClass() == SC_Static &&
GlobalVarDecl->getType().getCVRQualifiers());
if (RewriteSC) {
std::string SC(" void __");
SC += GlobalVarDecl->getNameAsString();
SC += "() {}";
InsertText(FunLocStart, SC);
}
// Insert closures that were part of the function.
for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
CollectBlockDeclRefInfo(Blocks[i]);
// Need to copy-in the inner copied-in variables not actually used in this
// block.
for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
DeclRefExpr *Exp = InnerDeclRefs[count++];
ValueDecl *VD = Exp->getDecl();
BlockDeclRefs.push_back(Exp);
if (!VD->hasAttr()) {
if (!BlockByCopyDeclsPtrSet.count(VD)) {
BlockByCopyDeclsPtrSet.insert(VD);
BlockByCopyDecls.push_back(VD);
}
continue;
}
if (!BlockByRefDeclsPtrSet.count(VD)) {
BlockByRefDeclsPtrSet.insert(VD);
BlockByRefDecls.push_back(VD);
}
// imported objects in the inner blocks not used in the outer
// blocks must be copied/disposed in the outer block as well.
if (VD->getType()->isObjCObjectPointerType() ||
VD->getType()->isBlockPointerType())
ImportedBlockDecls.insert(VD);
}
std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
InsertText(FunLocStart, CI);
std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
InsertText(FunLocStart, CF);
if (ImportedBlockDecls.size()) {
std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
InsertText(FunLocStart, HF);
}
std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
ImportedBlockDecls.size() > 0);
InsertText(FunLocStart, BD);
BlockDeclRefs.clear();
BlockByRefDecls.clear();
BlockByRefDeclsPtrSet.clear();
BlockByCopyDecls.clear();
BlockByCopyDeclsPtrSet.clear();
ImportedBlockDecls.clear();
}
if (RewriteSC) {
// Must insert any 'const/volatile/static here. Since it has been
// removed as result of rewriting of block literals.
std::string SC;
if (GlobalVarDecl->getStorageClass() == SC_Static)
SC = "static ";
if (GlobalVarDecl->getType().isConstQualified())
SC += "const ";
if (GlobalVarDecl->getType().isVolatileQualified())
SC += "volatile ";
if (GlobalVarDecl->getType().isRestrictQualified())
SC += "restrict ";
InsertText(FunLocStart, SC);
}
if (GlobalConstructionExp) {
// extra fancy dance for global literal expression.
// Always the latest block expression on the block stack.
std::string Tag = "__";
Tag += FunName;
Tag += "_block_impl_";
Tag += utostr(Blocks.size()-1);
std::string globalBuf = "static ";
globalBuf += Tag; globalBuf += " ";
std::string SStr;
llvm::raw_string_ostream constructorExprBuf(SStr);
GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
PrintingPolicy(LangOpts));
globalBuf += constructorExprBuf.str();
globalBuf += ";\n";
InsertText(FunLocStart, globalBuf);
GlobalConstructionExp = nullptr;
}
Blocks.clear();
InnerDeclRefsCount.clear();
InnerDeclRefs.clear();
RewrittenBlockExprs.clear();
}
void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
SourceLocation FunLocStart =
(!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
: FD->getTypeSpecStartLoc();
StringRef FuncName = FD->getName();
SynthesizeBlockLiterals(FunLocStart, FuncName);
}
static void BuildUniqueMethodName(std::string &Name,
ObjCMethodDecl *MD) {
ObjCInterfaceDecl *IFace = MD->getClassInterface();
Name = IFace->getName();
Name += "__" + MD->getSelector().getAsString();
// Convert colons to underscores.
std::string::size_type loc = 0;
while ((loc = Name.find(":", loc)) != std::string::npos)
Name.replace(loc, 1, "_");
}
void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
//fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
//SourceLocation FunLocStart = MD->getLocStart();
SourceLocation FunLocStart = MD->getLocStart();
std::string FuncName;
BuildUniqueMethodName(FuncName, MD);
SynthesizeBlockLiterals(FunLocStart, FuncName);
}
void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
for (Stmt::child_range CI = S->children(); CI; ++CI)
if (*CI) {
if (BlockExpr *CBE = dyn_cast(*CI))
GetBlockDeclRefExprs(CBE->getBody());
else
GetBlockDeclRefExprs(*CI);
}
// Handle specific things.
if (DeclRefExpr *DRE = dyn_cast(S)) {
if (DRE->refersToEnclosingLocal()) {
// FIXME: Handle enums.
if (!isa(DRE->getDecl()))
BlockDeclRefs.push_back(DRE);
if (HasLocalVariableExternalStorage(DRE->getDecl()))
BlockDeclRefs.push_back(DRE);
}
}
return;
}
void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
SmallVectorImpl &InnerBlockDeclRefs,
llvm::SmallPtrSet &InnerContexts) {
for (Stmt::child_range CI = S->children(); CI; ++CI)
if (*CI) {
if (BlockExpr *CBE = dyn_cast(*CI)) {
InnerContexts.insert(cast(CBE->getBlockDecl()));
GetInnerBlockDeclRefExprs(CBE->getBody(),
InnerBlockDeclRefs,
InnerContexts);
}
else
GetInnerBlockDeclRefExprs(*CI,
InnerBlockDeclRefs,
InnerContexts);
}
// Handle specific things.
if (DeclRefExpr *DRE = dyn_cast(S)) {
if (DRE->refersToEnclosingLocal()) {
if (!isa(DRE->getDecl()) &&
!InnerContexts.count(DRE->getDecl()->getDeclContext()))
InnerBlockDeclRefs.push_back(DRE);
if (VarDecl *Var = dyn_cast(DRE->getDecl()))
if (Var->isFunctionOrMethodVarDecl())
ImportedLocalExternalDecls.insert(Var);
}
}
return;
}
/// convertObjCTypeToCStyleType - This routine converts such objc types
/// as qualified objects, and blocks to their closest c/c++ types that
/// it can. It returns true if input type was modified.
bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
QualType oldT = T;
convertBlockPointerToFunctionPointer(T);
if (T->isFunctionPointerType()) {
QualType PointeeTy;
if (const PointerType* PT = T->getAs()) {
PointeeTy = PT->getPointeeType();
if (const FunctionType *FT = PointeeTy->getAs()) {
T = convertFunctionTypeOfBlocks(FT);
T = Context->getPointerType(T);
}
}
}
convertToUnqualifiedObjCType(T);
return T != oldT;
}
/// convertFunctionTypeOfBlocks - This routine converts a function type
/// whose result type may be a block pointer or whose argument type(s)
/// might be block pointers to an equivalent function type replacing
/// all block pointers to function pointers.
QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
const FunctionProtoType *FTP = dyn_cast(FT);
// FTP will be null for closures that don't take arguments.
// Generate a funky cast.
SmallVector ArgTypes;
QualType Res = FT->getReturnType();
bool modified = convertObjCTypeToCStyleType(Res);
if (FTP) {
for (auto &I : FTP->param_types()) {
QualType t = I;
// Make sure we convert "t (^)(...)" to "t (*)(...)".
if (convertObjCTypeToCStyleType(t))
modified = true;
ArgTypes.push_back(t);
}
}
QualType FuncType;
if (modified)
FuncType = getSimpleFunctionType(Res, ArgTypes);
else FuncType = QualType(FT, 0);
return FuncType;
}
Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
// Navigate to relevant type information.
const BlockPointerType *CPT = nullptr;
if (const DeclRefExpr *DRE = dyn_cast(BlockExp)) {
CPT = DRE->getType()->getAs();
} else if (const MemberExpr *MExpr = dyn_cast(BlockExp)) {
CPT = MExpr->getType()->getAs();
}
else if (const ParenExpr *PRE = dyn_cast(BlockExp)) {
return SynthesizeBlockCall(Exp, PRE->getSubExpr());
}
else if (const ImplicitCastExpr *IEXPR = dyn_cast(BlockExp))
CPT = IEXPR->getType()->getAs