1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Hacks and fun related to the code rewriter.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/ASTConsumers.h"
15 #include "clang/Rewrite/Rewriter.h"
16 #include "clang/AST/AST.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Lex/Lexer.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/DenseSet.h"
30 using namespace clang;
34 class RewriteObjC : public ASTConsumer {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
45 BLOCK_BYREF_CURRENT_MAX = 256
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 const LangOptions &LangOpts;
60 unsigned RewriteFailedDiag;
61 unsigned TryFinallyContainsReturnDiag;
65 TranslationUnitDecl *TUDecl;
67 const char *MainFileStart, *MainFileEnd;
68 SourceLocation LastIncLoc;
70 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
73 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
74 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
76 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
78 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
83 unsigned NumObjCStringLiterals;
85 FunctionDecl *MsgSendFunctionDecl;
86 FunctionDecl *MsgSendSuperFunctionDecl;
87 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
89 FunctionDecl *MsgSendFpretFunctionDecl;
90 FunctionDecl *GetClassFunctionDecl;
91 FunctionDecl *GetMetaClassFunctionDecl;
92 FunctionDecl *GetSuperClassFunctionDecl;
93 FunctionDecl *SelGetUidFunctionDecl;
94 FunctionDecl *CFStringFunctionDecl;
95 FunctionDecl *SuperContructorFunctionDecl;
97 // ObjC string constant support.
98 VarDecl *ConstantStringClassReference;
99 RecordDecl *NSStringRecord;
101 // ObjC foreach break/continue generation support.
105 ObjCMethodDecl *CurMethodDef;
106 RecordDecl *SuperStructDecl;
107 RecordDecl *ConstantStringDecl;
109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
112 // Needed for header files being rewritten
115 std::string InFileName;
116 llvm::raw_ostream* OutFile;
118 bool SilenceRewriteMacroWarning;
119 bool objc_impl_method;
121 std::string Preamble;
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
130 // Block related declarations.
131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
145 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152 FunctionDecl *CurFunctionDef;
153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
154 VarDecl *GlobalVarDecl;
156 bool DisableReplaceStmt;
158 static const int OBJC_ABI_VERSION =7 ;
160 virtual void Initialize(ASTContext &context);
162 // Top Level Driver code.
163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
167 void HandleTopLevelSingleDecl(Decl *D);
168 void HandleDeclInMainFile(Decl *D);
169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
175 virtual void HandleTranslationUnit(ASTContext &C);
177 void ReplaceStmt(Stmt *Old, Stmt *New) {
178 Stmt *ReplacingStmt = ReplacedNodes[Old];
181 return; // We can't rewrite the same node twice.
183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
186 // If replacement succeeded or warning disabled return with no warning.
187 if (!Rewrite.ReplaceStmt(Old, New)) {
188 ReplacedNodes[Old] = New;
191 if (SilenceRewriteMacroWarning)
193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
207 llvm::raw_string_ostream S(SStr);
208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
209 const std::string &Str = S.str();
211 // If replacement succeeded or warning disabled return with no warning.
212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
213 ReplacedNodes[Old] = New;
216 if (SilenceRewriteMacroWarning)
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
223 bool InsertAfter = true) {
224 // If insertion succeeded or warning disabled return with no warning.
225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
226 SilenceRewriteMacroWarning)
229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
233 llvm::StringRef Str) {
234 // If removal succeeded or warning disabled return with no warning.
235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
236 SilenceRewriteMacroWarning)
239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
242 // Syntactic Rewriting.
243 void RewriteInclude();
244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
249 void RewriteImplementationDecl(Decl *Dcl);
250 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
251 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
252 const FunctionType *&FPRetType);
253 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
255 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
256 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
257 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
258 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
259 void RewriteProperty(ObjCPropertyDecl *prop);
260 void RewriteFunctionDecl(FunctionDecl *FD);
261 void RewriteBlockPointerType(std::string& Str, QualType Type);
262 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
263 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
264 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
265 void RewriteTypeOfDecl(VarDecl *VD);
266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
267 bool needToScanForQualifiers(QualType T);
268 QualType getSuperStructType();
269 QualType getConstantStringStructType();
270 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
273 // Expression Rewriting.
274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
275 void CollectPropertySetters(Stmt *S);
278 ParentMap *PropParentMap; // created lazily.
280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
284 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
285 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
286 SourceRange SrcRange);
287 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
288 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
289 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
290 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
291 void WarnAboutReturnGotoStmts(Stmt *S);
292 void HasReturnStmts(Stmt *S, bool &hasReturns);
293 void RewriteTryReturnStmts(Stmt *S);
294 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
295 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
296 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
301 Expr **args, unsigned nargs,
302 SourceLocation StartLoc=SourceLocation(),
303 SourceLocation EndLoc=SourceLocation());
304 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
305 SourceLocation StartLoc=SourceLocation(),
306 SourceLocation EndLoc=SourceLocation());
307 Stmt *RewriteBreakStmt(BreakStmt *S);
308 Stmt *RewriteContinueStmt(ContinueStmt *S);
309 void SynthCountByEnumWithState(std::string &buf);
311 void SynthMsgSendFunctionDecl();
312 void SynthMsgSendSuperFunctionDecl();
313 void SynthMsgSendStretFunctionDecl();
314 void SynthMsgSendFpretFunctionDecl();
315 void SynthMsgSendSuperStretFunctionDecl();
316 void SynthGetClassFunctionDecl();
317 void SynthGetMetaClassFunctionDecl();
318 void SynthGetSuperClassFunctionDecl();
319 void SynthSelGetUidFunctionDecl();
320 void SynthSuperContructorFunctionDecl();
322 // Metadata emission.
323 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
324 std::string &Result);
326 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
327 std::string &Result);
329 template<typename MethodIterator>
330 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
331 MethodIterator MethodEnd,
332 bool IsInstanceMethod,
333 llvm::StringRef prefix,
334 llvm::StringRef ClassName,
335 std::string &Result);
337 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
338 llvm::StringRef prefix,
339 llvm::StringRef ClassName,
340 std::string &Result);
341 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
342 llvm::StringRef prefix,
343 llvm::StringRef ClassName,
344 std::string &Result);
345 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
349 std::string &Result);
350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
360 // Block specific rewrite rules.
361 void RewriteBlockPointerDecl(NamedDecl *VD);
362 void RewriteByRefVar(VarDecl *VD);
363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
369 llvm::StringRef funcName, std::string Tag);
370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
371 llvm::StringRef funcName, std::string Tag);
372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
376 int i, llvm::StringRef funcName,
378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
380 llvm::StringRef FunName);
381 void RewriteRecordBody(RecordDecl *RD);
383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
384 void GetBlockDeclRefExprs(Stmt *S);
385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
407 // FIXME: This predicate seems like it would be useful to add to ASTContext.
408 bool isObjCType(QualType T) {
409 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
412 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
414 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
415 OCT == Context->getCanonicalType(Context->getObjCClassType()))
418 if (const PointerType *PT = OCT->getAs<PointerType>()) {
419 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
420 PT->getPointeeType()->isObjCQualifiedIdType())
425 bool PointerTypeTakesAnyBlockArguments(QualType QT);
426 void GetExtentOfArgList(const char *Name, const char *&LParen,
427 const char *&RParen);
428 void RewriteCastExpr(CStyleCastExpr *CE);
430 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
432 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
434 void QuoteDoublequotes(std::string &From, std::string &To) {
435 for (unsigned i = 0; i < From.length(); i++) {
444 // Helper function: create a CStyleCastExpr with trivial type source info.
445 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
446 CastKind Kind, Expr *E) {
447 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
448 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
449 SourceLocation(), SourceLocation());
453 void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
455 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
456 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
457 E = fproto->arg_type_end(); I && (I != E); ++I)
458 if (isTopLevelBlockPointerType(*I)) {
459 // All the args are checked/rewritten. Don't call twice!
460 RewriteBlockPointerDecl(D);
466 void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
467 const PointerType *PT = funcType->getAs<PointerType>();
468 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
469 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
472 static bool IsHeaderFile(const std::string &Filename) {
473 std::string::size_type DotPos = Filename.rfind('.');
475 if (DotPos == std::string::npos) {
480 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
482 // C++ header: .hh or .H;
483 return Ext == "h" || Ext == "hh" || Ext == "H";
486 RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
487 Diagnostic &D, const LangOptions &LOpts,
488 bool silenceMacroWarn)
489 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
490 SilenceRewriteMacroWarning(silenceMacroWarn) {
491 IsHeader = IsHeaderFile(inFile);
492 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
493 "rewriting sub-expression within a macro (may not be correct)");
494 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
495 "rewriter doesn't support user-specified control flow semantics "
496 "for @try/@finally (code may not execute properly)");
499 ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
500 llvm::raw_ostream* OS,
502 const LangOptions &LOpts,
503 bool SilenceRewriteMacroWarning) {
504 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
507 void RewriteObjC::Initialize(ASTContext &context) {
509 SM = &Context->getSourceManager();
510 TUDecl = Context->getTranslationUnitDecl();
511 MsgSendFunctionDecl = 0;
512 MsgSendSuperFunctionDecl = 0;
513 MsgSendStretFunctionDecl = 0;
514 MsgSendSuperStretFunctionDecl = 0;
515 MsgSendFpretFunctionDecl = 0;
516 GetClassFunctionDecl = 0;
517 GetMetaClassFunctionDecl = 0;
518 GetSuperClassFunctionDecl = 0;
519 SelGetUidFunctionDecl = 0;
520 CFStringFunctionDecl = 0;
521 ConstantStringClassReference = 0;
525 CurFunctionDeclToDeclareForBlock = 0;
528 ProtocolTypeDecl = 0;
529 ConstantStringDecl = 0;
531 SuperContructorFunctionDecl = 0;
532 NumObjCStringLiterals = 0;
535 DisableReplaceStmt = false;
536 objc_impl_method = false;
538 // Get the ID and start/end of the main file.
539 MainFileID = SM->getMainFileID();
540 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
541 MainFileStart = MainBuf->getBufferStart();
542 MainFileEnd = MainBuf->getBufferEnd();
544 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
546 // declaring objc_selector outside the parameter list removes a silly
547 // scope related warning...
549 Preamble = "#pragma once\n";
550 Preamble += "struct objc_selector; struct objc_class;\n";
551 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
552 Preamble += "struct objc_object *superClass; ";
553 if (LangOpts.Microsoft) {
554 // Add a constructor for creating temporary objects.
555 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
557 Preamble += "object(o), superClass(s) {} ";
560 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
561 Preamble += "typedef struct objc_object Protocol;\n";
562 Preamble += "#define _REWRITER_typedef_Protocol\n";
563 Preamble += "#endif\n";
564 if (LangOpts.Microsoft) {
565 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
566 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
568 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
569 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
570 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
572 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
574 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
575 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
576 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
577 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
578 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
580 Preamble += "(const char *);\n";
581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
582 Preamble += "(struct objc_class *);\n";
583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
584 Preamble += "(const char *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
589 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
590 Preamble += "(struct objc_class *, struct objc_object *);\n";
591 // @synchronized hooks.
592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
594 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
595 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
596 Preamble += "struct __objcFastEnumerationState {\n\t";
597 Preamble += "unsigned long state;\n\t";
598 Preamble += "void **itemsPtr;\n\t";
599 Preamble += "unsigned long *mutationsPtr;\n\t";
600 Preamble += "unsigned long extra[5];\n};\n";
601 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
602 Preamble += "#define __FASTENUMERATIONSTATE\n";
603 Preamble += "#endif\n";
604 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
605 Preamble += "struct __NSConstantStringImpl {\n";
606 Preamble += " int *isa;\n";
607 Preamble += " int flags;\n";
608 Preamble += " char *str;\n";
609 Preamble += " long length;\n";
611 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
612 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
613 Preamble += "#else\n";
614 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
615 Preamble += "#endif\n";
616 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
617 Preamble += "#endif\n";
619 Preamble += "#ifndef BLOCK_IMPL\n";
620 Preamble += "#define BLOCK_IMPL\n";
621 Preamble += "struct __block_impl {\n";
622 Preamble += " void *isa;\n";
623 Preamble += " int Flags;\n";
624 Preamble += " int Reserved;\n";
625 Preamble += " void *FuncPtr;\n";
627 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
628 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
629 Preamble += "extern \"C\" __declspec(dllexport) "
630 "void _Block_object_assign(void *, const void *, const int);\n";
631 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
633 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
634 Preamble += "#else\n";
635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
638 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
639 Preamble += "#endif\n";
640 Preamble += "#endif\n";
641 if (LangOpts.Microsoft) {
642 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
643 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
644 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
645 Preamble += "#define __attribute__(X)\n";
646 Preamble += "#endif\n";
647 Preamble += "#define __weak\n";
650 Preamble += "#define __block\n";
651 Preamble += "#define __weak\n";
653 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
654 // as this avoids warning in any 64bit/32bit compilation model.
655 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
659 //===----------------------------------------------------------------------===//
660 // Top Level Driver Code
661 //===----------------------------------------------------------------------===//
663 void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
664 if (Diags.hasErrorOccurred())
667 // Two cases: either the decl could be in the main file, or it could be in a
668 // #included file. If the former, rewrite it now. If the later, check to see
669 // if we rewrote the #include/#import.
670 SourceLocation Loc = D->getLocation();
671 Loc = SM->getInstantiationLoc(Loc);
673 // If this is for a builtin, ignore it.
674 if (Loc.isInvalid()) return;
676 // Look for built-in declarations that we need to refer during the rewrite.
677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
678 RewriteFunctionDecl(FD);
679 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
680 // declared in <Foundation/NSString.h>
681 if (FVD->getName() == "_NSConstantStringClassReference") {
682 ConstantStringClassReference = FVD;
685 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
686 RewriteInterfaceDecl(MD);
687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
688 RewriteCategoryDecl(CD);
689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
690 RewriteProtocolDecl(PD);
691 } else if (ObjCForwardProtocolDecl *FP =
692 dyn_cast<ObjCForwardProtocolDecl>(D)){
693 RewriteForwardProtocolDecl(FP);
694 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
695 // Recurse into linkage specifications
696 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
697 DIEnd = LSD->decls_end();
699 HandleTopLevelSingleDecl(*DI);
701 // If we have a decl in the main file, see if we should rewrite it.
702 if (SM->isFromMainFile(Loc))
703 return HandleDeclInMainFile(D);
706 //===----------------------------------------------------------------------===//
707 // Syntactic (non-AST) Rewriting Code
708 //===----------------------------------------------------------------------===//
710 void RewriteObjC::RewriteInclude() {
711 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
712 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
713 const char *MainBufStart = MainBuf.begin();
714 const char *MainBufEnd = MainBuf.end();
715 size_t ImportLen = strlen("import");
717 // Loop over the whole file, looking for includes.
718 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
719 if (*BufPtr == '#') {
720 if (++BufPtr == MainBufEnd)
722 while (*BufPtr == ' ' || *BufPtr == '\t')
723 if (++BufPtr == MainBufEnd)
725 if (!strncmp(BufPtr, "import", ImportLen)) {
726 // replace import with include
727 SourceLocation ImportLoc =
728 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
729 ReplaceText(ImportLoc, ImportLen, "include");
736 static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
740 S += ClassDecl->getIdentifier()->getName();
741 S += "_IMPL *)self)->";
746 void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
747 ObjCImplementationDecl *IMD,
748 ObjCCategoryImplDecl *CID) {
749 static bool objcGetPropertyDefined = false;
750 static bool objcSetPropertyDefined = false;
751 SourceLocation startLoc = PID->getLocStart();
752 InsertText(startLoc, "// ");
753 const char *startBuf = SM->getCharacterData(startLoc);
754 assert((*startBuf == '@') && "bogus @synthesize location");
755 const char *semiBuf = strchr(startBuf, ';');
756 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
757 SourceLocation onePastSemiLoc =
758 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
760 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
761 return; // FIXME: is this correct?
763 // Generate the 'getter' function.
764 ObjCPropertyDecl *PD = PID->getPropertyDecl();
765 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
766 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
770 unsigned Attributes = PD->getPropertyAttributes();
771 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
772 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
773 ObjCPropertyDecl::OBJC_PR_copy));
775 if (GenGetProperty && !objcGetPropertyDefined) {
776 objcGetPropertyDefined = true;
777 // FIXME. Is this attribute correct in all cases?
778 Getr = "\nextern \"C\" __declspec(dllimport) "
779 "id objc_getProperty(id, SEL, long, bool);\n";
781 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
783 // Synthesize an explicit cast to gain access to the ivar.
784 // See objc-act.c:objc_synthesize_new_getter() for details.
785 if (GenGetProperty) {
786 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
788 const FunctionType *FPRetType = 0;
789 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
793 Getr += ")"; // close the precedence "scope" for "*".
795 // Now, emit the argument types (if any).
796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
798 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
800 std::string ParamStr = FT->getArgType(i).getAsString(
801 Context->PrintingPolicy);
804 if (FT->isVariadic()) {
805 if (FT->getNumArgs()) Getr += ", ";
813 Getr += "return (_TYPE)";
814 Getr += "objc_getProperty(self, _cmd, ";
815 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
819 Getr += "return " + getIvarAccessString(ClassDecl, OID);
821 InsertText(onePastSemiLoc, Getr);
822 if (PD->isReadOnly())
825 // Generate the 'setter' function.
827 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
828 ObjCPropertyDecl::OBJC_PR_copy);
829 if (GenSetProperty && !objcSetPropertyDefined) {
830 objcSetPropertyDefined = true;
831 // FIXME. Is this attribute correct in all cases?
832 Setr = "\nextern \"C\" __declspec(dllimport) "
833 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
836 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
838 // Synthesize an explicit cast to initialize the ivar.
839 // See objc-act.c:objc_synthesize_new_setter() for details.
840 if (GenSetProperty) {
841 Setr += "objc_setProperty (self, _cmd, ";
842 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
844 Setr += PD->getName();
846 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
850 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
856 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
857 Setr += PD->getName();
860 InsertText(onePastSemiLoc, Setr);
863 void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
864 // Get the start location and compute the semi location.
865 SourceLocation startLoc = ClassDecl->getLocation();
866 const char *startBuf = SM->getCharacterData(startLoc);
867 const char *semiPtr = strchr(startBuf, ';');
869 // Translate to typedef's that forward reference structs with the same name
870 // as the class. As a convenience, we include the original declaration
872 std::string typedefString;
873 typedefString += "// @class ";
874 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
876 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
877 typedefString += ForwardDecl->getNameAsString();
879 typedefString += ", ";
881 typedefString += ";\n";
884 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
886 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
887 typedefString += "#ifndef _REWRITER_typedef_";
888 typedefString += ForwardDecl->getNameAsString();
889 typedefString += "\n";
890 typedefString += "#define _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "typedef struct objc_object ";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += ";\n#endif\n";
898 // Replace the @class with typedefs corresponding to the classes.
899 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
902 void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
903 // When method is a synthesized one, such as a getter/setter there is
904 // nothing to rewrite.
905 if (Method->isSynthesized())
907 SourceLocation LocStart = Method->getLocStart();
908 SourceLocation LocEnd = Method->getLocEnd();
910 if (SM->getInstantiationLineNumber(LocEnd) >
911 SM->getInstantiationLineNumber(LocStart)) {
912 InsertText(LocStart, "#if 0\n");
913 ReplaceText(LocEnd, 1, ";\n#endif\n");
915 InsertText(LocStart, "// ");
919 void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
920 SourceLocation Loc = prop->getAtLoc();
922 ReplaceText(Loc, 0, "// ");
923 // FIXME: handle properties that are declared across multiple lines.
926 void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
927 SourceLocation LocStart = CatDecl->getLocStart();
929 // FIXME: handle category headers that are declared across multiple lines.
930 ReplaceText(LocStart, 0, "// ");
932 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
933 E = CatDecl->prop_end(); I != E; ++I)
936 for (ObjCCategoryDecl::instmeth_iterator
937 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
939 RewriteMethodDeclaration(*I);
940 for (ObjCCategoryDecl::classmeth_iterator
941 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
943 RewriteMethodDeclaration(*I);
945 // Lastly, comment out the @end.
946 ReplaceText(CatDecl->getAtEndRange().getBegin(),
947 strlen("@end"), "/* @end */");
950 void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
951 SourceLocation LocStart = PDecl->getLocStart();
953 // FIXME: handle protocol headers that are declared across multiple lines.
954 ReplaceText(LocStart, 0, "// ");
956 for (ObjCProtocolDecl::instmeth_iterator
957 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
959 RewriteMethodDeclaration(*I);
960 for (ObjCProtocolDecl::classmeth_iterator
961 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
963 RewriteMethodDeclaration(*I);
965 // Lastly, comment out the @end.
966 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
967 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
969 // Must comment out @optional/@required
970 const char *startBuf = SM->getCharacterData(LocStart);
971 const char *endBuf = SM->getCharacterData(LocEnd);
972 for (const char *p = startBuf; p < endBuf; p++) {
973 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
974 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
975 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
978 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
979 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
980 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
986 void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
987 SourceLocation LocStart = PDecl->getLocation();
988 if (LocStart.isInvalid())
989 assert(false && "Invalid SourceLocation");
990 // FIXME: handle forward protocol that are declared across multiple lines.
991 ReplaceText(LocStart, 0, "// ");
994 void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
995 const FunctionType *&FPRetType) {
996 if (T->isObjCQualifiedIdType())
998 else if (T->isFunctionPointerType() ||
999 T->isBlockPointerType()) {
1000 // needs special handling, since pointer-to-functions have special
1001 // syntax (where a decaration models use).
1002 QualType retType = T;
1004 if (const PointerType* PT = retType->getAs<PointerType>())
1005 PointeeTy = PT->getPointeeType();
1006 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1007 PointeeTy = BPT->getPointeeType();
1008 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1009 ResultStr += FPRetType->getResultType().getAsString(
1010 Context->PrintingPolicy);
1014 ResultStr += T.getAsString(Context->PrintingPolicy);
1017 void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1018 std::string &ResultStr) {
1019 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1020 const FunctionType *FPRetType = 0;
1021 ResultStr += "\nstatic ";
1022 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1025 // Unique method name
1026 std::string NameStr;
1028 if (OMD->isInstanceMethod())
1033 NameStr += OMD->getClassInterface()->getNameAsString();
1036 if (ObjCCategoryImplDecl *CID =
1037 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1038 NameStr += CID->getNameAsString();
1041 // Append selector names, replacing ':' with '_'
1043 std::string selString = OMD->getSelector().getAsString();
1044 int len = selString.size();
1045 for (int i = 0; i < len; i++)
1046 if (selString[i] == ':')
1048 NameStr += selString;
1050 // Remember this name for metadata emission
1051 MethodInternalNames[OMD] = NameStr;
1052 ResultStr += NameStr;
1054 // Rewrite arguments
1057 // invisible arguments
1058 if (OMD->isInstanceMethod()) {
1059 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
1060 selfTy = Context->getPointerType(selfTy);
1061 if (!LangOpts.Microsoft) {
1062 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1063 ResultStr += "struct ";
1065 // When rewriting for Microsoft, explicitly omit the structure name.
1066 ResultStr += OMD->getClassInterface()->getNameAsString();
1070 ResultStr += Context->getObjCClassType().getAsString(
1071 Context->PrintingPolicy);
1073 ResultStr += " self, ";
1074 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
1075 ResultStr += " _cmd";
1077 // Method arguments.
1078 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1079 E = OMD->param_end(); PI != E; ++PI) {
1080 ParmVarDecl *PDecl = *PI;
1082 if (PDecl->getType()->isObjCQualifiedIdType()) {
1084 ResultStr += PDecl->getNameAsString();
1086 std::string Name = PDecl->getNameAsString();
1087 QualType QT = PDecl->getType();
1088 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1089 if (convertBlockPointerToFunctionPointer(QT))
1090 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1092 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
1096 if (OMD->isVariadic())
1097 ResultStr += ", ...";
1101 ResultStr += ")"; // close the precedence "scope" for "*".
1103 // Now, emit the argument types (if any).
1104 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1106 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1107 if (i) ResultStr += ", ";
1108 std::string ParamStr = FT->getArgType(i).getAsString(
1109 Context->PrintingPolicy);
1110 ResultStr += ParamStr;
1112 if (FT->isVariadic()) {
1113 if (FT->getNumArgs()) ResultStr += ", ";
1122 void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1123 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1124 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1126 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1128 for (ObjCCategoryImplDecl::instmeth_iterator
1129 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1130 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1132 std::string ResultStr;
1133 ObjCMethodDecl *OMD = *I;
1134 RewriteObjCMethodDecl(OMD, ResultStr);
1135 SourceLocation LocStart = OMD->getLocStart();
1136 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1138 const char *startBuf = SM->getCharacterData(LocStart);
1139 const char *endBuf = SM->getCharacterData(LocEnd);
1140 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1143 for (ObjCCategoryImplDecl::classmeth_iterator
1144 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1145 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1147 std::string ResultStr;
1148 ObjCMethodDecl *OMD = *I;
1149 RewriteObjCMethodDecl(OMD, ResultStr);
1150 SourceLocation LocStart = OMD->getLocStart();
1151 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1153 const char *startBuf = SM->getCharacterData(LocStart);
1154 const char *endBuf = SM->getCharacterData(LocEnd);
1155 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1157 for (ObjCCategoryImplDecl::propimpl_iterator
1158 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1159 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1161 RewritePropertyImplDecl(*I, IMD, CID);
1164 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1167 void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1168 std::string ResultStr;
1169 if (!ObjCForwardDecls.count(ClassDecl)) {
1170 // we haven't seen a forward decl - generate a typedef.
1171 ResultStr = "#ifndef _REWRITER_typedef_";
1172 ResultStr += ClassDecl->getNameAsString();
1174 ResultStr += "#define _REWRITER_typedef_";
1175 ResultStr += ClassDecl->getNameAsString();
1177 ResultStr += "typedef struct objc_object ";
1178 ResultStr += ClassDecl->getNameAsString();
1179 ResultStr += ";\n#endif\n";
1180 // Mark this typedef as having been generated.
1181 ObjCForwardDecls.insert(ClassDecl);
1183 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
1185 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1186 E = ClassDecl->prop_end(); I != E; ++I)
1187 RewriteProperty(*I);
1188 for (ObjCInterfaceDecl::instmeth_iterator
1189 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1191 RewriteMethodDeclaration(*I);
1192 for (ObjCInterfaceDecl::classmeth_iterator
1193 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1195 RewriteMethodDeclaration(*I);
1197 // Lastly, comment out the @end.
1198 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1202 Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1203 SourceRange SrcRange) {
1204 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1205 // This allows us to reuse all the fun and games in SynthMessageExpr().
1206 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1207 ObjCMessageExpr *MsgExpr;
1208 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1209 llvm::SmallVector<Expr *, 1> ExprVec;
1210 ExprVec.push_back(newStmt);
1212 Stmt *Receiver = PropRefExpr->getBase();
1213 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1214 if (PRE && PropGetters[PRE]) {
1215 // This allows us to handle chain/nested property getters.
1216 Receiver = PropGetters[PRE];
1218 if (isa<ObjCSuperExpr>(Receiver))
1219 MsgExpr = ObjCMessageExpr::Create(*Context,
1220 PDecl->getType().getNonReferenceType(),
1221 /*FIXME?*/SourceLocation(),
1222 Receiver->getLocStart(),
1223 /*IsInstanceSuper=*/true,
1224 cast<Expr>(Receiver)->getType(),
1225 PDecl->getSetterName(),
1226 PDecl->getSetterMethodDecl(),
1228 /*FIXME:*/SourceLocation());
1230 MsgExpr = ObjCMessageExpr::Create(*Context,
1231 PDecl->getType().getNonReferenceType(),
1232 /*FIXME: */SourceLocation(),
1233 cast<Expr>(Receiver),
1234 PDecl->getSetterName(),
1235 PDecl->getSetterMethodDecl(),
1237 /*FIXME:*/SourceLocation());
1238 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1240 // Now do the actual rewrite.
1241 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
1243 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1244 // to things that stay around.
1245 Context->Deallocate(MsgExpr);
1246 return ReplacingStmt;
1249 Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
1250 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1251 // This allows us to reuse all the fun and games in SynthMessageExpr().
1252 ObjCMessageExpr *MsgExpr;
1253 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1255 Stmt *Receiver = PropRefExpr->getBase();
1257 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1258 if (PRE && PropGetters[PRE]) {
1259 // This allows us to handle chain/nested property getters.
1260 Receiver = PropGetters[PRE];
1263 if (isa<ObjCSuperExpr>(Receiver))
1264 MsgExpr = ObjCMessageExpr::Create(*Context,
1265 PDecl->getType().getNonReferenceType(),
1266 /*FIXME:*/SourceLocation(),
1267 Receiver->getLocStart(),
1268 /*IsInstanceSuper=*/true,
1269 cast<Expr>(Receiver)->getType(),
1270 PDecl->getGetterName(),
1271 PDecl->getGetterMethodDecl(),
1273 /*FIXME:*/SourceLocation());
1275 MsgExpr = ObjCMessageExpr::Create(*Context,
1276 PDecl->getType().getNonReferenceType(),
1277 /*FIXME:*/SourceLocation(),
1278 cast<Expr>(Receiver),
1279 PDecl->getGetterName(),
1280 PDecl->getGetterMethodDecl(),
1282 /*FIXME:*/SourceLocation());
1284 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1287 PropParentMap = new ParentMap(CurrentBody);
1289 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1290 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1291 // We stash away the ReplacingStmt since actually doing the
1292 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1293 PropGetters[PropRefExpr] = ReplacingStmt;
1294 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1295 // to things that stay around.
1296 Context->Deallocate(MsgExpr);
1297 return PropRefExpr; // return the original...
1299 ReplaceStmt(PropRefExpr, ReplacingStmt);
1300 // delete PropRefExpr; elsewhere...
1301 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1302 // to things that stay around.
1303 Context->Deallocate(MsgExpr);
1304 return ReplacingStmt;
1308 Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1309 SourceLocation OrigStart,
1311 ObjCIvarDecl *D = IV->getDecl();
1312 const Expr *BaseExpr = IV->getBase();
1314 if (BaseExpr->getType()->isObjCObjectPointerType()) {
1315 ObjCInterfaceType *iFaceDecl =
1316 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
1317 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
1318 // lookup which class implements the instance variable.
1319 ObjCInterfaceDecl *clsDeclared = 0;
1320 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
1322 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1324 // Synthesize an explicit cast to gain access to the ivar.
1325 std::string RecName = clsDeclared->getIdentifier()->getName();
1327 IdentifierInfo *II = &Context->Idents.get(RecName);
1328 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
1329 SourceLocation(), II);
1330 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1331 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
1332 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1335 // Don't forget the parens to enforce the proper binding.
1336 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1337 IV->getBase()->getLocEnd(),
1340 if (IV->isFreeIvar() &&
1341 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
1342 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1345 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
1349 // Cannot delete IV->getBase(), since PE points to it.
1350 // Replace the old base with the cast. This is important when doing
1351 // embedded rewrites. For example, [newInv->_container addObject:0].
1355 } else { // we are outside a method.
1356 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1358 // Explicit ivar refs need to have a cast inserted.
1359 // FIXME: consider sharing some of this code with the code above.
1360 if (BaseExpr->getType()->isObjCObjectPointerType()) {
1361 ObjCInterfaceType *iFaceDecl =
1362 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
1363 // lookup which class implements the instance variable.
1364 ObjCInterfaceDecl *clsDeclared = 0;
1365 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
1367 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1369 // Synthesize an explicit cast to gain access to the ivar.
1370 std::string RecName = clsDeclared->getIdentifier()->getName();
1372 IdentifierInfo *II = &Context->Idents.get(RecName);
1373 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
1374 SourceLocation(), II);
1375 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1376 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
1377 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1380 // Don't forget the parens to enforce the proper binding.
1381 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1382 IV->getBase()->getLocEnd(), castExpr);
1384 // Cannot delete IV->getBase(), since PE points to it.
1385 // Replace the old base with the cast. This is important when doing
1386 // embedded rewrites. For example, [newInv->_container addObject:0].
1394 Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1395 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1398 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1403 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1404 SourceRange OrigStmtRange = S->getSourceRange();
1405 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1409 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1410 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1416 /// SynthCountByEnumWithState - To print:
1417 /// ((unsigned int (*)
1418 /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1419 /// (void *)objc_msgSend)((id)l_collection,
1420 /// sel_registerName(
1421 /// "countByEnumeratingWithState:objects:count:"),
1423 /// (id *)items, (unsigned int)16)
1425 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1426 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1427 "id *, unsigned int))(void *)objc_msgSend)";
1429 buf += "((id)l_collection,\n\t\t";
1430 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1432 buf += "&enumState, "
1433 "(id *)items, (unsigned int)16)";
1436 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1437 /// statement to exit to its outer synthesized loop.
1439 Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1440 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1442 // replace break with goto __break_label
1445 SourceLocation startLoc = S->getLocStart();
1446 buf = "goto __break_label_";
1447 buf += utostr(ObjCBcLabelNo.back());
1448 ReplaceText(startLoc, strlen("break"), buf);
1453 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1454 /// statement to continue with its inner synthesized loop.
1456 Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1457 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1459 // replace continue with goto __continue_label
1462 SourceLocation startLoc = S->getLocStart();
1463 buf = "goto __continue_label_";
1464 buf += utostr(ObjCBcLabelNo.back());
1465 ReplaceText(startLoc, strlen("continue"), buf);
1470 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1472 /// for ( type elem in collection) { stmts; }
1477 /// struct __objcFastEnumerationState enumState = { 0 };
1479 /// id l_collection = (id)collection;
1480 /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1481 /// objects:items count:16];
1483 /// unsigned long startMutations = *enumState.mutationsPtr;
1485 /// unsigned long counter = 0;
1487 /// if (startMutations != *enumState.mutationsPtr)
1488 /// objc_enumerationMutation(l_collection);
1489 /// elem = (type)enumState.itemsPtr[counter++];
1491 /// __continue_label: ;
1492 /// } while (counter < limit);
1493 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1494 /// objects:items count:16]);
1496 /// __break_label: ;
1502 Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1503 SourceLocation OrigEnd) {
1504 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1505 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1506 "ObjCForCollectionStmt Statement stack mismatch");
1507 assert(!ObjCBcLabelNo.empty() &&
1508 "ObjCForCollectionStmt - Label No stack empty");
1510 SourceLocation startLoc = S->getLocStart();
1511 const char *startBuf = SM->getCharacterData(startLoc);
1512 llvm::StringRef elementName;
1513 std::string elementTypeAsString;
1516 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1518 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1519 QualType ElementType = cast<ValueDecl>(D)->getType();
1520 if (ElementType->isObjCQualifiedIdType() ||
1521 ElementType->isObjCQualifiedInterfaceType())
1522 // Simply use 'id' for all qualified types.
1523 elementTypeAsString = "id";
1525 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
1526 buf += elementTypeAsString;
1528 elementName = D->getName();
1533 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1534 elementName = DR->getDecl()->getName();
1535 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1536 if (VD->getType()->isObjCQualifiedIdType() ||
1537 VD->getType()->isObjCQualifiedInterfaceType())
1538 // Simply use 'id' for all qualified types.
1539 elementTypeAsString = "id";
1541 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
1544 // struct __objcFastEnumerationState enumState = { 0 };
1545 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1547 buf += "id items[16];\n\t";
1548 // id l_collection = (id)
1549 buf += "id l_collection = (id)";
1550 // Find start location of 'collection' the hard way!
1551 const char *startCollectionBuf = startBuf;
1552 startCollectionBuf += 3; // skip 'for'
1553 startCollectionBuf = strchr(startCollectionBuf, '(');
1554 startCollectionBuf++; // skip '('
1555 // find 'in' and skip it.
1556 while (*startCollectionBuf != ' ' ||
1557 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1558 (*(startCollectionBuf+3) != ' ' &&
1559 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1560 startCollectionBuf++;
1561 startCollectionBuf += 3;
1563 // Replace: "for (type element in" with string constructed thus far.
1564 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1565 // Replace ')' in for '(' type elem in collection ')' with ';'
1566 SourceLocation rightParenLoc = S->getRParenLoc();
1567 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1568 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1571 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1572 // objects:items count:16];
1573 // which is synthesized into:
1574 // unsigned int limit =
1575 // ((unsigned int (*)
1576 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1577 // (void *)objc_msgSend)((id)l_collection,
1578 // sel_registerName(
1579 // "countByEnumeratingWithState:objects:count:"),
1580 // (struct __objcFastEnumerationState *)&state,
1581 // (id *)items, (unsigned int)16);
1582 buf += "unsigned long limit =\n\t\t";
1583 SynthCountByEnumWithState(buf);
1586 /// unsigned long startMutations = *enumState.mutationsPtr;
1588 /// unsigned long counter = 0;
1590 /// if (startMutations != *enumState.mutationsPtr)
1591 /// objc_enumerationMutation(l_collection);
1592 /// elem = (type)enumState.itemsPtr[counter++];
1593 buf += "if (limit) {\n\t";
1594 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1595 buf += "do {\n\t\t";
1596 buf += "unsigned long counter = 0;\n\t\t";
1597 buf += "do {\n\t\t\t";
1598 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1599 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1602 buf += elementTypeAsString;
1603 buf += ")enumState.itemsPtr[counter++];";
1604 // Replace ')' in for '(' type elem in collection ')' with all of these.
1605 ReplaceText(lparenLoc, 1, buf);
1607 /// __continue_label: ;
1608 /// } while (counter < limit);
1609 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1610 /// objects:items count:16]);
1612 /// __break_label: ;
1619 buf += "__continue_label_";
1620 buf += utostr(ObjCBcLabelNo.back());
1623 buf += "} while (counter < limit);\n\t";
1624 buf += "} while (limit = ";
1625 SynthCountByEnumWithState(buf);
1629 buf += elementTypeAsString;
1631 buf += "__break_label_";
1632 buf += utostr(ObjCBcLabelNo.back());
1635 buf += "else\n\t\t";
1638 buf += elementTypeAsString;
1642 // Insert all these *after* the statement body.
1643 // FIXME: If this should support Obj-C++, support CXXTryStmt
1644 if (isa<CompoundStmt>(S->getBody())) {
1645 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1646 InsertText(endBodyLoc, buf);
1648 /* Need to treat single statements specially. For example:
1650 * for (A *a in b) if (stuff()) break;
1651 * for (A *a in b) xxxyy;
1653 * The following code simply scans ahead to the semi to find the actual end.
1655 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1656 const char *semiBuf = strchr(stmtBuf, ';');
1657 assert(semiBuf && "Can't find ';'");
1658 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1659 InsertText(endBodyLoc, buf);
1662 ObjCBcLabelNo.pop_back();
1666 /// RewriteObjCSynchronizedStmt -
1667 /// This routine rewrites @synchronized(expr) stmt;
1669 /// objc_sync_enter(expr);
1670 /// @try stmt @finally { objc_sync_exit(expr); }
1672 Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1673 // Get the start location and compute the semi location.
1674 SourceLocation startLoc = S->getLocStart();
1675 const char *startBuf = SM->getCharacterData(startLoc);
1677 assert((*startBuf == '@') && "bogus @synchronized location");
1680 buf = "objc_sync_enter((id)";
1681 const char *lparenBuf = startBuf;
1682 while (*lparenBuf != '(') lparenBuf++;
1683 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1684 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1685 // the sync expression is typically a message expression that's already
1686 // been rewritten! (which implies the SourceLocation's are invalid).
1687 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1688 const char *endBuf = SM->getCharacterData(endLoc);
1689 while (*endBuf != ')') endBuf--;
1690 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
1692 // declare a new scope with two variables, _stack and _rethrow.
1693 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1694 buf += "int buf[18/*32-bit i386*/];\n";
1695 buf += "char *pointers[4];} _stack;\n";
1696 buf += "id volatile _rethrow = 0;\n";
1697 buf += "objc_exception_try_enter(&_stack);\n";
1698 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1699 ReplaceText(rparenLoc, 1, buf);
1700 startLoc = S->getSynchBody()->getLocEnd();
1701 startBuf = SM->getCharacterData(startLoc);
1703 assert((*startBuf == '}') && "bogus @synchronized block");
1704 SourceLocation lastCurlyLoc = startLoc;
1705 buf = "}\nelse {\n";
1706 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1708 buf += "{ /* implicit finally clause */\n";
1709 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1711 std::string syncBuf;
1712 syncBuf += " objc_sync_exit(";
1713 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1716 std::string syncExprBufS;
1717 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1718 syncExpr->printPretty(syncExprBuf, *Context, 0,
1719 PrintingPolicy(LangOpts));
1720 syncBuf += syncExprBuf.str();
1724 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1728 ReplaceText(lastCurlyLoc, 1, buf);
1730 bool hasReturns = false;
1731 HasReturnStmts(S->getSynchBody(), hasReturns);
1733 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1738 void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1740 // Perform a bottom up traversal of all children.
1741 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1744 WarnAboutReturnGotoStmts(*CI);
1746 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1747 Diags.Report(Context->getFullLoc(S->getLocStart()),
1748 TryFinallyContainsReturnDiag);
1753 void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1755 // Perform a bottom up traversal of all children.
1756 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1759 HasReturnStmts(*CI, hasReturns);
1761 if (isa<ReturnStmt>(S))
1766 void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1767 // Perform a bottom up traversal of all children.
1768 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1771 RewriteTryReturnStmts(*CI);
1773 if (isa<ReturnStmt>(S)) {
1774 SourceLocation startLoc = S->getLocStart();
1775 const char *startBuf = SM->getCharacterData(startLoc);
1777 const char *semiBuf = strchr(startBuf, ';');
1778 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1779 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1782 buf = "{ objc_exception_try_exit(&_stack); return";
1784 ReplaceText(startLoc, 6, buf);
1785 InsertText(onePastSemiLoc, "}");
1790 void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1791 // Perform a bottom up traversal of all children.
1792 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1795 RewriteSyncReturnStmts(*CI, syncExitBuf);
1797 if (isa<ReturnStmt>(S)) {
1798 SourceLocation startLoc = S->getLocStart();
1799 const char *startBuf = SM->getCharacterData(startLoc);
1801 const char *semiBuf = strchr(startBuf, ';');
1802 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1803 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1806 buf = "{ objc_exception_try_exit(&_stack);";
1810 ReplaceText(startLoc, 6, buf);
1811 InsertText(onePastSemiLoc, "}");
1816 Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1817 // Get the start location and compute the semi location.
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
1821 assert((*startBuf == '@') && "bogus @try location");
1824 // declare a new scope with two variables, _stack and _rethrow.
1825 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1826 buf += "int buf[18/*32-bit i386*/];\n";
1827 buf += "char *pointers[4];} _stack;\n";
1828 buf += "id volatile _rethrow = 0;\n";
1829 buf += "objc_exception_try_enter(&_stack);\n";
1830 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1832 ReplaceText(startLoc, 4, buf);
1834 startLoc = S->getTryBody()->getLocEnd();
1835 startBuf = SM->getCharacterData(startLoc);
1837 assert((*startBuf == '}') && "bogus @try block");
1839 SourceLocation lastCurlyLoc = startLoc;
1840 if (S->getNumCatchStmts()) {
1841 startLoc = startLoc.getFileLocWithOffset(1);
1842 buf = " /* @catch begin */ else {\n";
1843 buf += " id _caught = objc_exception_extract(&_stack);\n";
1844 buf += " objc_exception_try_enter (&_stack);\n";
1845 buf += " if (_setjmp(_stack.buf))\n";
1846 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1847 buf += " else { /* @catch continue */";
1849 InsertText(startLoc, buf);
1850 } else { /* no catch list */
1851 buf = "}\nelse {\n";
1852 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1854 ReplaceText(lastCurlyLoc, 1, buf);
1856 bool sawIdTypedCatch = false;
1857 Stmt *lastCatchBody = 0;
1858 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1859 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1860 VarDecl *catchDecl = Catch->getCatchParamDecl();
1863 buf = "if ("; // we are generating code for the first catch clause
1866 startLoc = Catch->getLocStart();
1867 startBuf = SM->getCharacterData(startLoc);
1869 assert((*startBuf == '@') && "bogus @catch location");
1871 const char *lParenLoc = strchr(startBuf, '(');
1873 if (Catch->hasEllipsis()) {
1874 // Now rewrite the body...
1875 lastCatchBody = Catch->getCatchBody();
1876 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1877 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1878 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1879 "bogus @catch paren location");
1880 assert((*bodyBuf == '{') && "bogus @catch body location");
1882 buf += "1) { id _tmp = _caught;";
1883 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1884 } else if (catchDecl) {
1885 QualType t = catchDecl->getType();
1886 if (t == Context->getObjCIdType()) {
1888 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1889 sawIdTypedCatch = true;
1890 } else if (const ObjCObjectPointerType *Ptr =
1891 t->getAs<ObjCObjectPointerType>()) {
1892 // Should be a pointer to a class.
1893 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1895 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1896 buf += IDecl->getNameAsString();
1897 buf += "\"), (struct objc_object *)_caught)) { ";
1898 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1901 // Now rewrite the body...
1902 lastCatchBody = Catch->getCatchBody();
1903 SourceLocation rParenLoc = Catch->getRParenLoc();
1904 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1905 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1906 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1907 assert((*rParenBuf == ')') && "bogus @catch paren location");
1908 assert((*bodyBuf == '{') && "bogus @catch body location");
1910 // Here we replace ") {" with "= _caught;" (which initializes and
1911 // declares the @catch parameter).
1912 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1914 assert(false && "@catch rewrite bug");
1917 // Complete the catch list...
1918 if (lastCatchBody) {
1919 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1920 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1921 "bogus @catch body location");
1923 // Insert the last (implicit) else clause *before* the right curly brace.
1924 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1925 buf = "} /* last catch end */\n";
1927 buf += " _rethrow = _caught;\n";
1928 buf += " objc_exception_try_exit(&_stack);\n";
1929 buf += "} } /* @catch end */\n";
1930 if (!S->getFinallyStmt())
1932 InsertText(bodyLoc, buf);
1935 lastCurlyLoc = lastCatchBody->getLocEnd();
1937 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1938 startLoc = finalStmt->getLocStart();
1939 startBuf = SM->getCharacterData(startLoc);
1940 assert((*startBuf == '@') && "bogus @finally start");
1942 ReplaceText(startLoc, 8, "/* @finally */");
1944 Stmt *body = finalStmt->getFinallyBody();
1945 SourceLocation startLoc = body->getLocStart();
1946 SourceLocation endLoc = body->getLocEnd();
1947 assert(*SM->getCharacterData(startLoc) == '{' &&
1948 "bogus @finally body location");
1949 assert(*SM->getCharacterData(endLoc) == '}' &&
1950 "bogus @finally body location");
1952 startLoc = startLoc.getFileLocWithOffset(1);
1953 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1954 endLoc = endLoc.getFileLocWithOffset(-1);
1955 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1958 lastCurlyLoc = body->getLocEnd();
1960 // Now check for any return/continue/go statements within the @try.
1961 WarnAboutReturnGotoStmts(S->getTryBody());
1962 } else { /* no finally clause - make sure we synthesize an implicit one */
1963 buf = "{ /* implicit finally clause */\n";
1964 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1965 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1967 ReplaceText(lastCurlyLoc, 1, buf);
1969 // Now check for any return/continue/go statements within the @try.
1970 // The implicit finally clause won't called if the @try contains any
1972 bool hasReturns = false;
1973 HasReturnStmts(S->getTryBody(), hasReturns);
1975 RewriteTryReturnStmts(S->getTryBody());
1977 // Now emit the final closing curly brace...
1978 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1979 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1983 // This can't be done with ReplaceStmt(S, ThrowExpr), since
1984 // the throw expression is typically a message expression that's already
1985 // been rewritten! (which implies the SourceLocation's are invalid).
1986 Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1987 // Get the start location and compute the semi location.
1988 SourceLocation startLoc = S->getLocStart();
1989 const char *startBuf = SM->getCharacterData(startLoc);
1991 assert((*startBuf == '@') && "bogus @throw location");
1994 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1995 if (S->getThrowExpr())
1996 buf = "objc_exception_throw(";
1997 else // add an implicit argument
1998 buf = "objc_exception_throw(_caught";
2000 // handle "@ throw" correctly.
2001 const char *wBuf = strchr(startBuf, 'w');
2002 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2003 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2005 const char *semiBuf = strchr(startBuf, ';');
2006 assert((*semiBuf == ';') && "@throw: can't find ';'");
2007 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
2008 ReplaceText(semiLoc, 1, ");");
2012 Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2013 // Create a new string expression.
2014 QualType StrType = Context->getPointerType(Context->CharTy);
2015 std::string StrEncoding;
2016 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2017 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2018 StrEncoding.length(), false,StrType,
2020 ReplaceStmt(Exp, Replacement);
2022 // Replace this subexpr in the parent.
2023 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2027 Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2028 if (!SelGetUidFunctionDecl)
2029 SynthSelGetUidFunctionDecl();
2030 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2031 // Create a call to sel_registerName("selName").
2032 llvm::SmallVector<Expr*, 8> SelExprs;
2033 QualType argType = Context->getPointerType(Context->CharTy);
2034 SelExprs.push_back(StringLiteral::Create(*Context,
2035 Exp->getSelector().getAsString().c_str(),
2036 Exp->getSelector().getAsString().size(),
2037 false, argType, SourceLocation()));
2038 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2039 &SelExprs[0], SelExprs.size());
2040 ReplaceStmt(Exp, SelExp);
2041 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2045 CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
2046 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2047 SourceLocation EndLoc) {
2048 // Get the type, we will need to reference it in a couple spots.
2049 QualType msgSendType = FD->getType();
2051 // Create a reference to the objc_msgSend() declaration.
2052 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
2054 // Now, we cast the reference to a pointer to the objc_msgSend type.
2055 QualType pToFunc = Context->getPointerType(msgSendType);
2056 ImplicitCastExpr *ICE =
2057 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
2060 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2063 new (Context) CallExpr(*Context, ICE, args, nargs,
2064 FT->getCallResultType(*Context), EndLoc);
2068 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2069 const char *&startRef, const char *&endRef) {
2070 while (startBuf < endBuf) {
2071 if (*startBuf == '<')
2072 startRef = startBuf; // mark the start.
2073 if (*startBuf == '>') {
2074 if (startRef && *startRef == '<') {
2075 endRef = startBuf; // mark the end.
2085 static void scanToNextArgument(const char *&argRef) {
2087 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2090 else if (*argRef == '>')
2094 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2097 bool RewriteObjC::needToScanForQualifiers(QualType T) {
2098 if (T->isObjCQualifiedIdType())
2100 if (const PointerType *PT = T->getAs<PointerType>()) {
2101 if (PT->getPointeeType()->isObjCQualifiedIdType())
2104 if (T->isObjCObjectPointerType()) {
2105 T = T->getPointeeType();
2106 return T->isObjCQualifiedInterfaceType();
2111 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2112 QualType Type = E->getType();
2113 if (needToScanForQualifiers(Type)) {
2114 SourceLocation Loc, EndLoc;
2116 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2117 Loc = ECE->getLParenLoc();
2118 EndLoc = ECE->getRParenLoc();
2120 Loc = E->getLocStart();
2121 EndLoc = E->getLocEnd();
2123 // This will defend against trying to rewrite synthesized expressions.
2124 if (Loc.isInvalid() || EndLoc.isInvalid())
2127 const char *startBuf = SM->getCharacterData(Loc);
2128 const char *endBuf = SM->getCharacterData(EndLoc);
2129 const char *startRef = 0, *endRef = 0;
2130 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2131 // Get the locations of the startRef, endRef.
2132 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2133 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2134 // Comment out the protocol references.
2135 InsertText(LessLoc, "/*");
2136 InsertText(GreaterLoc, "*/");
2141 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2144 const FunctionProtoType *proto = 0;
2145 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2146 Loc = VD->getLocation();
2147 Type = VD->getType();
2149 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2150 Loc = FD->getLocation();
2151 // Check for ObjC 'id' and class types that have been adorned with protocol
2152 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2153 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2154 assert(funcType && "missing function type");
2155 proto = dyn_cast<FunctionProtoType>(funcType);
2158 Type = proto->getResultType();
2160 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2161 Loc = FD->getLocation();
2162 Type = FD->getType();
2167 if (needToScanForQualifiers(Type)) {
2168 // Since types are unique, we need to scan the buffer.
2170 const char *endBuf = SM->getCharacterData(Loc);
2171 const char *startBuf = endBuf;
2172 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2173 startBuf--; // scan backward (from the decl location) for return type.
2174 const char *startRef = 0, *endRef = 0;
2175 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2176 // Get the locations of the startRef, endRef.
2177 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2178 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2179 // Comment out the protocol references.
2180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
2185 return; // most likely, was a variable
2186 // Now check arguments.
2187 const char *startBuf = SM->getCharacterData(Loc);
2188 const char *startFuncBuf = startBuf;
2189 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2190 if (needToScanForQualifiers(proto->getArgType(i))) {
2191 // Since types are unique, we need to scan the buffer.
2193 const char *endBuf = startBuf;
2194 // scan forward (from the decl location) for argument types.
2195 scanToNextArgument(endBuf);
2196 const char *startRef = 0, *endRef = 0;
2197 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2198 // Get the locations of the startRef, endRef.
2199 SourceLocation LessLoc =
2200 Loc.getFileLocWithOffset(startRef-startFuncBuf);
2201 SourceLocation GreaterLoc =
2202 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
2203 // Comment out the protocol references.
2204 InsertText(LessLoc, "/*");
2205 InsertText(GreaterLoc, "*/");
2207 startBuf = ++endBuf;
2210 // If the function name is derived from a macro expansion, then the
2211 // argument buffer will not follow the name. Need to speak with Chris.
2212 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2213 startBuf++; // scan forward (from the decl location) for argument types.
2219 void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2220 QualType QT = ND->getType();
2221 const Type* TypePtr = QT->getAs<Type>();
2222 if (!isa<TypeOfExprType>(TypePtr))
2224 while (isa<TypeOfExprType>(TypePtr)) {
2225 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2226 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2227 TypePtr = QT->getAs<Type>();
2229 // FIXME. This will not work for multiple declarators; as in:
2230 // __typeof__(a) b,c,d;
2231 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
2232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2233 const char *startBuf = SM->getCharacterData(DeclLoc);
2234 if (ND->getInit()) {
2235 std::string Name(ND->getNameAsString());
2236 TypeAsString += " " + Name + " = ";
2237 Expr *E = ND->getInit();
2238 SourceLocation startLoc;
2239 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2240 startLoc = ECE->getLParenLoc();
2242 startLoc = E->getLocStart();
2243 startLoc = SM->getInstantiationLoc(startLoc);
2244 const char *endBuf = SM->getCharacterData(startLoc);
2245 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2248 SourceLocation X = ND->getLocEnd();
2249 X = SM->getInstantiationLoc(X);
2250 const char *endBuf = SM->getCharacterData(X);
2251 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2255 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2256 void RewriteObjC::SynthSelGetUidFunctionDecl() {
2257 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2258 llvm::SmallVector<QualType, 16> ArgTys;
2259 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2260 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
2261 &ArgTys[0], ArgTys.size(),
2262 false /*isVariadic*/, 0,
2264 FunctionType::ExtInfo());
2265 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2267 SelGetUidIdent, getFuncType, 0,
2272 void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2273 // declared in <objc/objc.h>
2274 if (FD->getIdentifier() &&
2275 FD->getName() == "sel_registerName") {
2276 SelGetUidFunctionDecl = FD;
2279 RewriteObjCQualifiedInterfaceTypes(FD);
2282 void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2283 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
2284 const char *argPtr = TypeString.c_str();
2285 if (!strchr(argPtr, '^')) {
2290 Str += (*argPtr == '^' ? '*' : *argPtr);
2295 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2296 void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2298 QualType Type = VD->getType();
2299 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
2300 const char *argPtr = TypeString.c_str();
2315 Str += VD->getNameAsString();
2326 void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2327 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2328 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2329 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2332 QualType Type = proto->getResultType();
2333 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
2335 FdStr += FD->getName();
2337 unsigned numArgs = proto->getNumArgs();
2338 for (unsigned i = 0; i < numArgs; i++) {
2339 QualType ArgType = proto->getArgType(i);
2340 RewriteBlockPointerType(FdStr, ArgType);
2345 InsertText(FunLocStart, FdStr);
2346 CurFunctionDeclToDeclareForBlock = 0;
2349 // SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2350 void RewriteObjC::SynthSuperContructorFunctionDecl() {
2351 if (SuperContructorFunctionDecl)
2353 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2354 llvm::SmallVector<QualType, 16> ArgTys;
2355 QualType argT = Context->getObjCIdType();
2356 assert(!argT.isNull() && "Can't find 'id' type");
2357 ArgTys.push_back(argT);
2358 ArgTys.push_back(argT);
2359 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2360 &ArgTys[0], ArgTys.size(),
2363 FunctionType::ExtInfo());
2364 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2366 msgSendIdent, msgSendType, 0,
2371 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2372 void RewriteObjC::SynthMsgSendFunctionDecl() {
2373 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2374 llvm::SmallVector<QualType, 16> ArgTys;
2375 QualType argT = Context->getObjCIdType();
2376 assert(!argT.isNull() && "Can't find 'id' type");
2377 ArgTys.push_back(argT);
2378 argT = Context->getObjCSelType();
2379 assert(!argT.isNull() && "Can't find 'SEL' type");
2380 ArgTys.push_back(argT);
2381 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2382 &ArgTys[0], ArgTys.size(),
2383 true /*isVariadic*/, 0,
2385 FunctionType::ExtInfo());
2386 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2388 msgSendIdent, msgSendType, 0,
2393 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2394 void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2395 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2396 llvm::SmallVector<QualType, 16> ArgTys;
2397 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2399 &Context->Idents.get("objc_super"));
2400 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2401 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2402 ArgTys.push_back(argT);
2403 argT = Context->getObjCSelType();
2404 assert(!argT.isNull() && "Can't find 'SEL' type");
2405 ArgTys.push_back(argT);
2406 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2407 &ArgTys[0], ArgTys.size(),
2408 true /*isVariadic*/, 0,
2410 FunctionType::ExtInfo());
2411 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2413 msgSendIdent, msgSendType, 0,
2418 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2419 void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2420 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2421 llvm::SmallVector<QualType, 16> ArgTys;
2422 QualType argT = Context->getObjCIdType();
2423 assert(!argT.isNull() && "Can't find 'id' type");
2424 ArgTys.push_back(argT);
2425 argT = Context->getObjCSelType();
2426 assert(!argT.isNull() && "Can't find 'SEL' type");
2427 ArgTys.push_back(argT);
2428 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2429 &ArgTys[0], ArgTys.size(),
2430 true /*isVariadic*/, 0,
2432 FunctionType::ExtInfo());
2433 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2435 msgSendIdent, msgSendType, 0,
2440 // SynthMsgSendSuperStretFunctionDecl -
2441 // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2442 void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2443 IdentifierInfo *msgSendIdent =
2444 &Context->Idents.get("objc_msgSendSuper_stret");
2445 llvm::SmallVector<QualType, 16> ArgTys;
2446 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2448 &Context->Idents.get("objc_super"));
2449 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2450 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2451 ArgTys.push_back(argT);
2452 argT = Context->getObjCSelType();
2453 assert(!argT.isNull() && "Can't find 'SEL' type");
2454 ArgTys.push_back(argT);
2455 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2456 &ArgTys[0], ArgTys.size(),
2457 true /*isVariadic*/, 0,
2459 FunctionType::ExtInfo());
2460 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2462 msgSendIdent, msgSendType, 0,
2467 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2468 void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2469 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2470 llvm::SmallVector<QualType, 16> ArgTys;
2471 QualType argT = Context->getObjCIdType();
2472 assert(!argT.isNull() && "Can't find 'id' type");
2473 ArgTys.push_back(argT);
2474 argT = Context->getObjCSelType();
2475 assert(!argT.isNull() && "Can't find 'SEL' type");
2476 ArgTys.push_back(argT);
2477 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
2478 &ArgTys[0], ArgTys.size(),
2479 true /*isVariadic*/, 0,
2481 FunctionType::ExtInfo());
2482 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2484 msgSendIdent, msgSendType, 0,
2489 // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2490 void RewriteObjC::SynthGetClassFunctionDecl() {
2491 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2492 llvm::SmallVector<QualType, 16> ArgTys;
2493 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2494 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
2495 &ArgTys[0], ArgTys.size(),
2496 false /*isVariadic*/, 0,
2498 FunctionType::ExtInfo());
2499 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2501 getClassIdent, getClassType, 0,
2506 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2507 void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2508 IdentifierInfo *getSuperClassIdent =
2509 &Context->Idents.get("class_getSuperclass");
2510 llvm::SmallVector<QualType, 16> ArgTys;
2511 ArgTys.push_back(Context->getObjCClassType());
2512 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2513 &ArgTys[0], ArgTys.size(),
2514 false /*isVariadic*/, 0,
2516 FunctionType::ExtInfo());
2517 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2526 // SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
2527 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2528 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2529 llvm::SmallVector<QualType, 16> ArgTys;
2530 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2531 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
2532 &ArgTys[0], ArgTys.size(),
2533 false /*isVariadic*/, 0,
2535 FunctionType::ExtInfo());
2536 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2538 getClassIdent, getClassType, 0,
2543 Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2544 QualType strType = getConstantStringStructType();
2546 std::string S = "__NSConstantStringImpl_";
2548 std::string tmpName = InFileName;
2550 for (i=0; i < tmpName.length(); i++) {
2551 char c = tmpName.at(i);
2552 // replace any non alphanumeric characters with '_'.
2553 if (!isalpha(c) && (c < '0' || c > '9'))
2558 S += utostr(NumObjCStringLiterals++);
2560 Preamble += "static __NSConstantStringImpl " + S;
2561 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2562 Preamble += "0x000007c8,"; // utf8_str
2563 // The pretty printer for StringLiteral handles escape characters properly.
2564 std::string prettyBufS;
2565 llvm::raw_string_ostream prettyBuf(prettyBufS);
2566 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2567 PrintingPolicy(LangOpts));
2568 Preamble += prettyBuf.str();
2570 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2572 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2573 &Context->Idents.get(S), strType, 0,
2574 SC_Static, SC_None);
2575 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2576 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2577 Context->getPointerType(DRE->getType()),
2579 // cast to NSConstantString *
2580 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2582 ReplaceStmt(Exp, cast);
2583 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2587 // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2588 QualType RewriteObjC::getSuperStructType() {
2589 if (!SuperStructDecl) {
2590 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2592 &Context->Idents.get("objc_super"));
2593 QualType FieldTypes[2];
2595 // struct objc_object *receiver;
2596 FieldTypes[0] = Context->getObjCIdType();
2597 // struct objc_class *super;
2598 FieldTypes[1] = Context->getObjCClassType();
2601 for (unsigned i = 0; i < 2; ++i) {
2602 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2603 SourceLocation(), 0,
2606 /*Mutable=*/false));
2609 SuperStructDecl->completeDefinition();
2611 return Context->getTagDeclType(SuperStructDecl);
2614 QualType RewriteObjC::getConstantStringStructType() {
2615 if (!ConstantStringDecl) {
2616 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2618 &Context->Idents.get("__NSConstantStringImpl"));
2619 QualType FieldTypes[4];
2621 // struct objc_object *receiver;
2622 FieldTypes[0] = Context->getObjCIdType();
2624 FieldTypes[1] = Context->IntTy;
2626 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2628 FieldTypes[3] = Context->LongTy;
2631 for (unsigned i = 0; i < 4; ++i) {
2632 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2634 SourceLocation(), 0,
2640 ConstantStringDecl->completeDefinition();
2642 return Context->getTagDeclType(ConstantStringDecl);
2645 Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2646 SourceLocation StartLoc,
2647 SourceLocation EndLoc) {
2648 if (!SelGetUidFunctionDecl)
2649 SynthSelGetUidFunctionDecl();
2650 if (!MsgSendFunctionDecl)
2651 SynthMsgSendFunctionDecl();
2652 if (!MsgSendSuperFunctionDecl)
2653 SynthMsgSendSuperFunctionDecl();
2654 if (!MsgSendStretFunctionDecl)
2655 SynthMsgSendStretFunctionDecl();
2656 if (!MsgSendSuperStretFunctionDecl)
2657 SynthMsgSendSuperStretFunctionDecl();
2658 if (!MsgSendFpretFunctionDecl)
2659 SynthMsgSendFpretFunctionDecl();
2660 if (!GetClassFunctionDecl)
2661 SynthGetClassFunctionDecl();
2662 if (!GetSuperClassFunctionDecl)
2663 SynthGetSuperClassFunctionDecl();
2664 if (!GetMetaClassFunctionDecl)
2665 SynthGetMetaClassFunctionDecl();
2667 // default to objc_msgSend().
2668 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2669 // May need to use objc_msgSend_stret() as well.
2670 FunctionDecl *MsgSendStretFlavor = 0;
2671 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2672 QualType resultType = mDecl->getResultType();
2673 if (resultType->isRecordType())
2674 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2675 else if (resultType->isRealFloatingType())
2676 MsgSendFlavor = MsgSendFpretFunctionDecl;
2679 // Synthesize a call to objc_msgSend().
2680 llvm::SmallVector<Expr*, 8> MsgExprs;
2681 switch (Exp->getReceiverKind()) {
2682 case ObjCMessageExpr::SuperClass: {
2683 MsgSendFlavor = MsgSendSuperFunctionDecl;
2684 if (MsgSendStretFlavor)
2685 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2686 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2688 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2690 llvm::SmallVector<Expr*, 4> InitExprs;
2692 // set the receiver to self, the first argument to all methods.
2693 InitExprs.push_back(
2694 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2696 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2697 Context->getObjCIdType(),
2699 ); // set the 'receiver'.
2701 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2702 llvm::SmallVector<Expr*, 8> ClsExprs;
2703 QualType argType = Context->getPointerType(Context->CharTy);
2704 ClsExprs.push_back(StringLiteral::Create(*Context,
2705 ClassDecl->getIdentifier()->getNameStart(),
2706 ClassDecl->getIdentifier()->getLength(),
2707 false, argType, SourceLocation()));
2708 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2713 // (Class)objc_getClass("CurrentClass")
2714 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2715 Context->getObjCClassType(),
2718 ClsExprs.push_back(ArgExpr);
2719 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2720 &ClsExprs[0], ClsExprs.size(),
2723 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2724 // To turn off a warning, type-cast to 'id'
2725 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2726 NoTypeInfoCStyleCastExpr(Context,
2727 Context->getObjCIdType(),
2729 // struct objc_super
2730 QualType superType = getSuperStructType();
2733 if (LangOpts.Microsoft) {
2734 SynthSuperContructorFunctionDecl();
2735 // Simulate a contructor call...
2736 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2737 superType, SourceLocation());
2738 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2740 superType, SourceLocation());
2741 // The code for super is a little tricky to prevent collision with
2742 // the structure definition in the header. The rewriter has it's own
2743 // internal definition (__rw_objc_super) that is uses. This is why
2744 // we need the cast below. For example:
2745 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2747 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2748 Context->getPointerType(SuperRep->getType()),
2750 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2751 Context->getPointerType(superType),
2752 CK_Unknown, SuperRep);
2754 // (struct objc_super) { <exprs from above> }
2756 new (Context) InitListExpr(*Context, SourceLocation(),
2757 &InitExprs[0], InitExprs.size(),
2759 TypeSourceInfo *superTInfo
2760 = Context->getTrivialTypeSourceInfo(superType);
2761 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2762 superType, ILE, false);
2763 // struct objc_super *
2764 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2765 Context->getPointerType(SuperRep->getType()),
2768 MsgExprs.push_back(SuperRep);
2772 case ObjCMessageExpr::Class: {
2773 llvm::SmallVector<Expr*, 8> ClsExprs;
2774 QualType argType = Context->getPointerType(Context->CharTy);
2775 ObjCInterfaceDecl *Class
2776 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2777 IdentifierInfo *clsName = Class->getIdentifier();
2778 ClsExprs.push_back(StringLiteral::Create(*Context,
2779 clsName->getNameStart(),
2780 clsName->getLength(),
2783 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2787 MsgExprs.push_back(Cls);
2791 case ObjCMessageExpr::SuperInstance:{
2792 MsgSendFlavor = MsgSendSuperFunctionDecl;
2793 if (MsgSendStretFlavor)
2794 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2795 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2796 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2797 llvm::SmallVector<Expr*, 4> InitExprs;
2799 InitExprs.push_back(
2800 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2802 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2803 Context->getObjCIdType(),
2805 ); // set the 'receiver'.
2807 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2808 llvm::SmallVector<Expr*, 8> ClsExprs;
2809 QualType argType = Context->getPointerType(Context->CharTy);
2810 ClsExprs.push_back(StringLiteral::Create(*Context,
2811 ClassDecl->getIdentifier()->getNameStart(),
2812 ClassDecl->getIdentifier()->getLength(),
2813 false, argType, SourceLocation()));
2814 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2818 // (Class)objc_getClass("CurrentClass")
2819 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2820 Context->getObjCClassType(),
2823 ClsExprs.push_back(ArgExpr);
2824 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2825 &ClsExprs[0], ClsExprs.size(),
2828 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2829 // To turn off a warning, type-cast to 'id'
2830 InitExprs.push_back(
2831 // set 'super class', using class_getSuperclass().
2832 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2834 // struct objc_super
2835 QualType superType = getSuperStructType();
2838 if (LangOpts.Microsoft) {
2839 SynthSuperContructorFunctionDecl();
2840 // Simulate a contructor call...
2841 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2842 superType, SourceLocation());
2843 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2845 superType, SourceLocation());
2846 // The code for super is a little tricky to prevent collision with
2847 // the structure definition in the header. The rewriter has it's own
2848 // internal definition (__rw_objc_super) that is uses. This is why
2849 // we need the cast below. For example:
2850 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2852 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2853 Context->getPointerType(SuperRep->getType()),
2855 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2856 Context->getPointerType(superType),
2857 CK_Unknown, SuperRep);
2859 // (struct objc_super) { <exprs from above> }
2861 new (Context) InitListExpr(*Context, SourceLocation(),
2862 &InitExprs[0], InitExprs.size(),
2864 TypeSourceInfo *superTInfo
2865 = Context->getTrivialTypeSourceInfo(superType);
2866 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2867 superType, ILE, false);
2869 MsgExprs.push_back(SuperRep);
2873 case ObjCMessageExpr::Instance: {
2874 // Remove all type-casts because it may contain objc-style types; e.g.
2876 Expr *recExpr = Exp->getInstanceReceiver();
2877 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2878 recExpr = CE->getSubExpr();
2879 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2880 CK_Unknown, recExpr);
2881 MsgExprs.push_back(recExpr);
2886 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2887 llvm::SmallVector<Expr*, 8> SelExprs;
2888 QualType argType = Context->getPointerType(Context->CharTy);
2889 SelExprs.push_back(StringLiteral::Create(*Context,
2890 Exp->getSelector().getAsString().c_str(),
2891 Exp->getSelector().getAsString().size(),
2892 false, argType, SourceLocation()));
2893 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2894 &SelExprs[0], SelExprs.size(),
2897 MsgExprs.push_back(SelExp);
2899 // Now push any user supplied arguments.
2900 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2901 Expr *userExpr = Exp->getArg(i);
2902 // Make all implicit casts explicit...ICE comes in handy:-)
2903 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2904 // Reuse the ICE type, it is exactly what the doctor ordered.
2905 QualType type = ICE->getType()->isObjCQualifiedIdType()
2906 ? Context->getObjCIdType()
2908 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2909 (void)convertBlockPointerToFunctionPointer(type);
2910 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
2913 // Make id<P...> cast into an 'id' cast.
2914 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2915 if (CE->getType()->isObjCQualifiedIdType()) {
2916 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2917 userExpr = CE->getSubExpr();
2918 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2919 CK_Unknown, userExpr);
2922 MsgExprs.push_back(userExpr);
2923 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2924 // out the argument in the original expression (since we aren't deleting
2925 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2926 //Exp->setArg(i, 0);
2928 // Generate the funky cast.
2930 llvm::SmallVector<QualType, 8> ArgTypes;
2931 QualType returnType;
2933 // Push 'id' and 'SEL', the 2 implicit arguments.
2934 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2935 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2937 ArgTypes.push_back(Context->getObjCIdType());
2938 ArgTypes.push_back(Context->getObjCSelType());
2939 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2940 // Push any user argument types.
2941 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2942 E = OMD->param_end(); PI != E; ++PI) {
2943 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2944 ? Context->getObjCIdType()
2946 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2947 (void)convertBlockPointerToFunctionPointer(t);
2948 ArgTypes.push_back(t);
2950 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2951 ? Context->getObjCIdType() : OMD->getResultType();
2952 (void)convertBlockPointerToFunctionPointer(returnType);
2954 returnType = Context->getObjCIdType();
2956 // Get the type, we will need to reference it in a couple spots.
2957 QualType msgSendType = MsgSendFlavor->getType();
2959 // Create a reference to the objc_msgSend() declaration.
2960 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2963 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2964 // If we don't do this cast, we get the following bizarre warning/note:
2965 // xx.m:13: warning: function called through a non-compatible type
2966 // xx.m:13: note: if this code is reached, the program will abort
2967 cast = NoTypeInfoCStyleCastExpr(Context,
2968 Context->getPointerType(Context->VoidTy),
2971 // Now do the "normal" pointer to function cast.
2972 QualType castType = Context->getFunctionType(returnType,
2973 &ArgTypes[0], ArgTypes.size(),
2974 // If we don't have a method decl, force a variadic cast.
2975 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2977 FunctionType::ExtInfo());
2978 castType = Context->getPointerType(castType);
2979 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
2982 // Don't forget the parens to enforce the proper binding.
2983 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2985 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2986 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2988 FT->getResultType(), EndLoc);
2989 Stmt *ReplacingStmt = CE;
2990 if (MsgSendStretFlavor) {
2991 // We have the method which returns a struct/union. Must also generate
2992 // call to objc_msgSend_stret and hang both varieties on a conditional
2993 // expression which dictate which one to envoke depending on size of
2994 // method's return type.
2996 // Create a reference to the objc_msgSend_stret() declaration.
2997 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
2999 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3000 cast = NoTypeInfoCStyleCastExpr(Context,
3001 Context->getPointerType(Context->VoidTy),
3003 // Now do the "normal" pointer to function cast.
3004 castType = Context->getFunctionType(returnType,
3005 &ArgTypes[0], ArgTypes.size(),
3006 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
3008 FunctionType::ExtInfo());
3009 castType = Context->getPointerType(castType);
3010 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
3013 // Don't forget the parens to enforce the proper binding.
3014 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3016 FT = msgSendType->getAs<FunctionType>();
3017 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3019 FT->getResultType(), SourceLocation());
3021 // Build sizeof(returnType)
3022 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
3023 Context->getTrivialTypeSourceInfo(returnType),
3024 Context->getSizeType(),
3025 SourceLocation(), SourceLocation());
3026 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3027 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3028 // For X86 it is more complicated and some kind of target specific routine
3029 // is needed to decide what to do.
3031 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3032 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3033 llvm::APInt(IntSize, 8),
3036 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3040 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3041 ConditionalOperator *CondExpr =
3042 new (Context) ConditionalOperator(lessThanExpr,
3043 SourceLocation(), CE,
3044 SourceLocation(), STCE, (Expr*)0,
3046 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3049 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
3050 return ReplacingStmt;
3053 Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3054 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3057 // Now do the actual rewrite.
3058 ReplaceStmt(Exp, ReplacingStmt);
3060 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
3061 return ReplacingStmt;
3064 // typedef struct objc_object Protocol;
3065 QualType RewriteObjC::getProtocolType() {
3066 if (!ProtocolTypeDecl) {
3067 TypeSourceInfo *TInfo
3068 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3069 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3071 &Context->Idents.get("Protocol"),
3074 return Context->getTypeDeclType(ProtocolTypeDecl);
3077 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3078 /// a synthesized/forward data reference (to the protocol's metadata).
3079 /// The forward references (and metadata) are generated in
3080 /// RewriteObjC::HandleTranslationUnit().
3081 Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3082 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3083 IdentifierInfo *ID = &Context->Idents.get(Name);
3084 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3085 ID, getProtocolType(), 0,
3086 SC_Extern, SC_None);
3087 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3088 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3089 Context->getPointerType(DRE->getType()),
3091 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3094 ReplaceStmt(Exp, castExpr);
3095 ProtocolExprDecls.insert(Exp->getProtocol());
3096 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
3101 bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3102 const char *endBuf) {
3103 while (startBuf < endBuf) {
3104 if (*startBuf == '#') {
3106 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3108 if (!strncmp(startBuf, "if", strlen("if")) ||
3109 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3110 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3111 !strncmp(startBuf, "define", strlen("define")) ||
3112 !strncmp(startBuf, "undef", strlen("undef")) ||
3113 !strncmp(startBuf, "else", strlen("else")) ||
3114 !strncmp(startBuf, "elif", strlen("elif")) ||
3115 !strncmp(startBuf, "endif", strlen("endif")) ||
3116 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3117 !strncmp(startBuf, "include", strlen("include")) ||
3118 !strncmp(startBuf, "import", strlen("import")) ||
3119 !strncmp(startBuf, "include_next", strlen("include_next")))
3127 /// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
3128 /// an objective-c class with ivars.
3129 void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3130 std::string &Result) {
3131 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3132 assert(CDecl->getName() != "" &&
3133 "Name missing in SynthesizeObjCInternalStruct");
3134 // Do not synthesize more than once.
3135 if (ObjCSynthesizedStructs.count(CDecl))
3137 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3138 int NumIvars = CDecl->ivar_size();
3139 SourceLocation LocStart = CDecl->getLocStart();
3140 SourceLocation LocEnd = CDecl->getLocEnd();
3142 const char *startBuf = SM->getCharacterData(LocStart);
3143 const char *endBuf = SM->getCharacterData(LocEnd);
3145 // If no ivars and no root or if its root, directly or indirectly,
3146 // have no ivars (thus not synthesized) then no need to synthesize this class.
3147 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3148 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3149 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3150 ReplaceText(LocStart, endBuf-startBuf, Result);
3154 // FIXME: This has potential of causing problem. If
3155 // SynthesizeObjCInternalStruct is ever called recursively.
3156 Result += "\nstruct ";
3157 Result += CDecl->getNameAsString();
3158 if (LangOpts.Microsoft)
3162 const char *cursor = strchr(startBuf, '{');
3163 assert((cursor && endBuf)
3164 && "SynthesizeObjCInternalStruct - malformed @interface");
3165 // If the buffer contains preprocessor directives, we do more fine-grained
3166 // rewrites. This is intended to fix code that looks like (which occurs in
3167 // NSURL.h, for example):
3170 // @interface Foo : NSObject
3172 // @interface FooBar : NSObject
3179 // This clause is segregated to avoid breaking the common case.
3180 if (BufferContainsPPDirectives(startBuf, cursor)) {
3181 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3182 CDecl->getClassLoc();
3183 const char *endHeader = SM->getCharacterData(L);
3184 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3186 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3187 // advance to the end of the referenced protocols.
3188 while (endHeader < cursor && *endHeader != '>') endHeader++;
3191 // rewrite the original header
3192 ReplaceText(LocStart, endHeader-startBuf, Result);
3194 // rewrite the original header *without* disturbing the '{'
3195 ReplaceText(LocStart, cursor-startBuf, Result);
3197 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3198 Result = "\n struct ";
3199 Result += RCDecl->getNameAsString();
3201 Result += RCDecl->getNameAsString();
3202 Result += "_IVARS;\n";
3204 // insert the super class structure definition.
3205 SourceLocation OnePastCurly =
3206 LocStart.getFileLocWithOffset(cursor-startBuf+1);
3207 InsertText(OnePastCurly, Result);
3209 cursor++; // past '{'
3211 // Now comment out any visibility specifiers.
3212 while (cursor < endBuf) {
3213 if (*cursor == '@') {
3214 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3216 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3219 // FIXME: presence of @public, etc. inside comment results in
3220 // this transformation as well, which is still correct c-code.
3221 if (!strncmp(cursor, "public", strlen("public")) ||
3222 !strncmp(cursor, "private", strlen("private")) ||
3223 !strncmp(cursor, "package", strlen("package")) ||
3224 !strncmp(cursor, "protected", strlen("protected")))
3225 InsertText(atLoc, "// ");
3227 // FIXME: If there are cases where '<' is used in ivar declaration part
3228 // of user code, then scan the ivar list and use needToScanForQualifiers
3229 // for type checking.
3230 else if (*cursor == '<') {
3231 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3232 InsertText(atLoc, "/* ");
3233 cursor = strchr(cursor, '>');
3235 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3236 InsertText(atLoc, " */");
3237 } else if (*cursor == '^') { // rewrite block specifier.
3238 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3239 ReplaceText(caretLoc, 1, "*");
3243 // Don't forget to add a ';'!!
3244 InsertText(LocEnd.getFileLocWithOffset(1), ";");
3245 } else { // we don't have any instance variables - insert super struct.
3246 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3247 Result += " {\n struct ";
3248 Result += RCDecl->getNameAsString();
3250 Result += RCDecl->getNameAsString();
3251 Result += "_IVARS;\n};\n";
3252 ReplaceText(LocStart, endBuf-startBuf, Result);
3254 // Mark this struct as having been generated.
3255 if (!ObjCSynthesizedStructs.insert(CDecl))
3256 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
3259 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
3261 template<typename MethodIterator>
3262 void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3263 MethodIterator MethodEnd,
3264 bool IsInstanceMethod,
3265 llvm::StringRef prefix,
3266 llvm::StringRef ClassName,
3267 std::string &Result) {
3268 if (MethodBegin == MethodEnd) return;
3270 if (!objc_impl_method) {
3271 /* struct _objc_method {
3277 Result += "\nstruct _objc_method {\n";
3278 Result += "\tSEL _cmd;\n";
3279 Result += "\tchar *method_types;\n";
3280 Result += "\tvoid *_imp;\n";
3283 objc_impl_method = true;
3286 // Build _objc_method_list for class's methods if needed
3289 struct _objc_method_list *next_method;
3291 struct _objc_method method_list[];
3294 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
3295 Result += "\nstatic struct {\n";
3296 Result += "\tstruct _objc_method_list *next_method;\n";
3297 Result += "\tint method_count;\n";
3298 Result += "\tstruct _objc_method method_list[";
3299 Result += utostr(NumMethods);
3300 Result += "];\n} _OBJC_";
3302 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3303 Result += "_METHODS_";
3304 Result += ClassName;
3305 Result += " __attribute__ ((used, section (\"__OBJC, __";
3306 Result += IsInstanceMethod ? "inst" : "cls";
3307 Result += "_meth\")))= ";
3308 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
3310 Result += "\t,{{(SEL)\"";
3311 Result += (*MethodBegin)->getSelector().getAsString().c_str();
3312 std::string MethodTypeString;
3313 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
3315 Result += MethodTypeString;
3316 Result += "\", (void *)";
3317 Result += MethodInternalNames[*MethodBegin];
3319 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3320 Result += "\t ,{(SEL)\"";
3321 Result += (*MethodBegin)->getSelector().getAsString().c_str();
3322 std::string MethodTypeString;
3323 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
3325 Result += MethodTypeString;
3326 Result += "\", (void *)";
3327 Result += MethodInternalNames[*MethodBegin];
3330 Result += "\t }\n};\n";
3333 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
3335 RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3336 llvm::StringRef ClassName, std::string &Result) {
3337 static bool objc_protocol_methods = false;
3339 // Output struct protocol_methods holder of method selector and type.
3340 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3341 /* struct protocol_methods {
3346 Result += "\nstruct _protocol_methods {\n";
3347 Result += "\tstruct objc_selector *_cmd;\n";
3348 Result += "\tchar *method_types;\n";
3351 objc_protocol_methods = true;
3353 // Do not synthesize the protocol more than once.
3354 if (ObjCSynthesizedProtocols.count(PDecl))
3357 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3358 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3359 PDecl->instmeth_end());
3360 /* struct _objc_protocol_method_list {
3361 int protocol_method_count;
3362 struct protocol_methods protocols[];
3365 Result += "\nstatic struct {\n";
3366 Result += "\tint protocol_method_count;\n";
3367 Result += "\tstruct _protocol_methods protocol_methods[";
3368 Result += utostr(NumMethods);
3369 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3370 Result += PDecl->getNameAsString();
3371 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3372 "{\n\t" + utostr(NumMethods) + "\n";
3374 // Output instance methods declared in this protocol.
3375 for (ObjCProtocolDecl::instmeth_iterator
3376 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
3378 if (I == PDecl->instmeth_begin())
3379 Result += "\t ,{{(struct objc_selector *)\"";
3381 Result += "\t ,{(struct objc_selector *)\"";
3382 Result += (*I)->getSelector().getAsString();
3383 std::string MethodTypeString;
3384 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3386 Result += MethodTypeString;
3389 Result += "\t }\n};\n";
3392 // Output class methods declared in this protocol.
3393 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3394 PDecl->classmeth_end());
3395 if (NumMethods > 0) {
3396 /* struct _objc_protocol_method_list {
3397 int protocol_method_count;
3398 struct protocol_methods protocols[];
3401 Result += "\nstatic struct {\n";
3402 Result += "\tint protocol_method_count;\n";
3403 Result += "\tstruct _protocol_methods protocol_methods[";
3404 Result += utostr(NumMethods);
3405 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3406 Result += PDecl->getNameAsString();
3407 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3409 Result += utostr(NumMethods);
3412 // Output instance methods declared in this protocol.
3413 for (ObjCProtocolDecl::classmeth_iterator
3414 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
3416 if (I == PDecl->classmeth_begin())
3417 Result += "\t ,{{(struct objc_selector *)\"";
3419 Result += "\t ,{(struct objc_selector *)\"";
3420 Result += (*I)->getSelector().getAsString();
3421 std::string MethodTypeString;
3422 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3424 Result += MethodTypeString;
3427 Result += "\t }\n};\n";
3431 /* struct _objc_protocol {
3432 // Objective-C 1.0 extensions
3433 struct _objc_protocol_extension *isa;
3434 char *protocol_name;
3435 struct _objc_protocol **protocol_list;
3436 struct _objc_protocol_method_list *instance_methods;
3437 struct _objc_protocol_method_list *class_methods;
3440 static bool objc_protocol = false;
3441 if (!objc_protocol) {
3442 Result += "\nstruct _objc_protocol {\n";
3443 Result += "\tstruct _objc_protocol_extension *isa;\n";
3444 Result += "\tchar *protocol_name;\n";
3445 Result += "\tstruct _objc_protocol **protocol_list;\n";
3446 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3447 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
3450 objc_protocol = true;
3453 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3454 Result += PDecl->getNameAsString();
3455 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3457 Result += PDecl->getNameAsString();
3458 Result += "\", 0, ";
3459 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3460 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3461 Result += PDecl->getNameAsString();
3466 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
3467 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3468 Result += PDecl->getNameAsString();
3475 // Mark this protocol as having been generated.
3476 if (!ObjCSynthesizedProtocols.insert(PDecl))
3477 assert(false && "protocol already synthesized");
3482 RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3483 llvm::StringRef prefix, llvm::StringRef ClassName,
3484 std::string &Result) {
3485 if (Protocols.empty()) return;
3487 for (unsigned i = 0; i != Protocols.size(); i++)
3488 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3490 // Output the top lovel protocol meta-data for the class.
3491 /* struct _objc_protocol_list {
3492 struct _objc_protocol_list *next;
3494 struct _objc_protocol *class_protocols[];
3497 Result += "\nstatic struct {\n";
3498 Result += "\tstruct _objc_protocol_list *next;\n";
3499 Result += "\tint protocol_count;\n";
3500 Result += "\tstruct _objc_protocol *class_protocols[";
3501 Result += utostr(Protocols.size());
3502 Result += "];\n} _OBJC_";
3504 Result += "_PROTOCOLS_";
3505 Result += ClassName;
3506 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3508 Result += utostr(Protocols.size());
3511 Result += "\t,{&_OBJC_PROTOCOL_";
3512 Result += Protocols[0]->getNameAsString();
3515 for (unsigned i = 1; i != Protocols.size(); i++) {
3516 Result += "\t ,&_OBJC_PROTOCOL_";
3517 Result += Protocols[i]->getNameAsString();
3520 Result += "\t }\n};\n";
3524 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
3526 void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
3527 std::string &Result) {
3528 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
3529 // Find category declaration for this implementation.
3530 ObjCCategoryDecl *CDecl;
3531 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3532 CDecl = CDecl->getNextClassCategory())
3533 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3536 std::string FullCategoryName = ClassDecl->getNameAsString();
3537 FullCategoryName += '_';
3538 FullCategoryName += IDecl->getNameAsString();
3540 // Build _objc_method_list for class's instance methods if needed
3541 llvm::SmallVector<ObjCMethodDecl *, 32>
3542 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
3544 // If any of our property implementations have associated getters or
3545 // setters, produce metadata for them as well.
3546 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3547 PropEnd = IDecl->propimpl_end();
3548 Prop != PropEnd; ++Prop) {
3549 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3551 if (!(*Prop)->getPropertyIvarDecl())
3553 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3556 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3557 InstanceMethods.push_back(Getter);
3558 if (PD->isReadOnly())
3560 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3561 InstanceMethods.push_back(Setter);
3563 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
3564 true, "CATEGORY_", FullCategoryName.c_str(),
3567 // Build _objc_method_list for class's class methods if needed
3568 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
3569 false, "CATEGORY_", FullCategoryName.c_str(),
3572 // Protocols referenced in class declaration?
3573 // Null CDecl is case of a category implementation with no category interface
3575 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3576 FullCategoryName, Result);
3577 /* struct _objc_category {
3578 char *category_name;
3580 struct _objc_method_list *instance_methods;
3581 struct _objc_method_list *class_methods;
3582 struct _objc_protocol_list *protocols;
3583 // Objective-C 1.0 extensions
3584 uint32_t size; // sizeof (struct _objc_category)
3585 struct _objc_property_list *instance_properties; // category's own
3590 static bool objc_category = false;
3591 if (!objc_category) {
3592 Result += "\nstruct _objc_category {\n";
3593 Result += "\tchar *category_name;\n";
3594 Result += "\tchar *class_name;\n";
3595 Result += "\tstruct _objc_method_list *instance_methods;\n";
3596 Result += "\tstruct _objc_method_list *class_methods;\n";
3597 Result += "\tstruct _objc_protocol_list *protocols;\n";
3598 Result += "\tunsigned int size;\n";
3599 Result += "\tstruct _objc_property_list *instance_properties;\n";
3601 objc_category = true;
3603 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3604 Result += FullCategoryName;
3605 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
3606 Result += IDecl->getNameAsString();
3607 Result += "\"\n\t, \"";
3608 Result += ClassDecl->getNameAsString();
3611 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
3612 Result += "\t, (struct _objc_method_list *)"
3613 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3614 Result += FullCategoryName;
3618 Result += "\t, 0\n";
3619 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
3620 Result += "\t, (struct _objc_method_list *)"
3621 "&_OBJC_CATEGORY_CLASS_METHODS_";
3622 Result += FullCategoryName;
3626 Result += "\t, 0\n";
3628 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
3629 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3630 Result += FullCategoryName;
3634 Result += "\t, 0\n";
3635 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
3638 /// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3640 void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
3642 std::string &Result) {
3643 if (ivar->isBitField()) {
3644 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3645 // place all bitfields at offset 0.
3648 Result += "__OFFSETOFIVAR__(struct ";
3649 Result += IDecl->getNameAsString();
3650 if (LangOpts.Microsoft)
3653 Result += ivar->getNameAsString();
3658 //===----------------------------------------------------------------------===//
3659 // Meta Data Emission
3660 //===----------------------------------------------------------------------===//
3662 void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
3663 std::string &Result) {
3664 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
3666 // Explictly declared @interface's are already synthesized.
3667 if (CDecl->isImplicitInterfaceDecl()) {
3668 // FIXME: Implementation of a class with no @interface (legacy) doese not
3669 // produce correct synthesis as yet.
3670 SynthesizeObjCInternalStruct(CDecl, Result);
3673 // Build _objc_ivar_list metadata for classes ivars if needed
3674 unsigned NumIvars = !IDecl->ivar_empty()
3675 ? IDecl->ivar_size()
3676 : (CDecl ? CDecl->ivar_size() : 0);
3678 static bool objc_ivar = false;
3680 /* struct _objc_ivar {
3686 Result += "\nstruct _objc_ivar {\n";
3687 Result += "\tchar *ivar_name;\n";
3688 Result += "\tchar *ivar_type;\n";
3689 Result += "\tint ivar_offset;\n";
3697 struct _objc_ivar ivar_list[nIvars];
3700 Result += "\nstatic struct {\n";
3701 Result += "\tint ivar_count;\n";
3702 Result += "\tstruct _objc_ivar ivar_list[";
3703 Result += utostr(NumIvars);
3704 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
3705 Result += IDecl->getNameAsString();
3706 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
3708 Result += utostr(NumIvars);
3711 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
3712 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
3713 if (!IDecl->ivar_empty()) {
3714 for (ObjCInterfaceDecl::ivar_iterator
3715 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
3717 IVars.push_back(*IV);
3718 IVI = IDecl->ivar_begin();
3719 IVE = IDecl->ivar_end();
3721 IVI = CDecl->ivar_begin();
3722 IVE = CDecl->ivar_end();
3724 Result += "\t,{{\"";
3725 Result += (*IVI)->getNameAsString();
3727 std::string TmpString, StrEncoding;
3728 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3729 QuoteDoublequotes(TmpString, StrEncoding);
3730 Result += StrEncoding;
3732 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
3734 for (++IVI; IVI != IVE; ++IVI) {
3735 Result += "\t ,{\"";
3736 Result += (*IVI)->getNameAsString();
3738 std::string TmpString, StrEncoding;
3739 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3740 QuoteDoublequotes(TmpString, StrEncoding);
3741 Result += StrEncoding;
3743 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
3747 Result += "\t }\n};\n";
3750 // Build _objc_method_list for class's instance methods if needed
3751 llvm::SmallVector<ObjCMethodDecl *, 32>
3752 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
3754 // If any of our property implementations have associated getters or
3755 // setters, produce metadata for them as well.
3756 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3757 PropEnd = IDecl->propimpl_end();
3758 Prop != PropEnd; ++Prop) {
3759 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3761 if (!(*Prop)->getPropertyIvarDecl())
3763 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3766 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3767 InstanceMethods.push_back(Getter);
3768 if (PD->isReadOnly())
3770 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3771 InstanceMethods.push_back(Setter);
3773 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
3774 true, "", IDecl->getName(), Result);
3776 // Build _objc_method_list for class's class methods if needed
3777 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
3778 false, "", IDecl->getName(), Result);
3780 // Protocols referenced in class declaration?
3781 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3782 "CLASS", CDecl->getName(), Result);
3784 // Declaration of class/meta-class metadata
3785 /* struct _objc_class {
3786 struct _objc_class *isa; // or const char *root_class_name when metadata
3787 const char *super_class_name;
3792 struct _objc_ivar_list *ivars;
3793 struct _objc_method_list *methods;
3794 struct objc_cache *cache;
3795 struct objc_protocol_list *protocols;
3796 const char *ivar_layout;
3797 struct _objc_class_ext *ext;
3800 static bool objc_class = false;
3802 Result += "\nstruct _objc_class {\n";
3803 Result += "\tstruct _objc_class *isa;\n";
3804 Result += "\tconst char *super_class_name;\n";
3805 Result += "\tchar *name;\n";
3806 Result += "\tlong version;\n";
3807 Result += "\tlong info;\n";
3808 Result += "\tlong instance_size;\n";
3809 Result += "\tstruct _objc_ivar_list *ivars;\n";
3810 Result += "\tstruct _objc_method_list *methods;\n";
3811 Result += "\tstruct objc_cache *cache;\n";
3812 Result += "\tstruct _objc_protocol_list *protocols;\n";
3813 Result += "\tconst char *ivar_layout;\n";
3814 Result += "\tstruct _objc_class_ext *ext;\n";
3819 // Meta-class metadata generation.
3820 ObjCInterfaceDecl *RootClass = 0;
3821 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
3822 while (SuperClass) {
3823 RootClass = SuperClass;
3824 SuperClass = SuperClass->getSuperClass();
3826 SuperClass = CDecl->getSuperClass();
3828 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3829 Result += CDecl->getNameAsString();
3830 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
3831 "{\n\t(struct _objc_class *)\"";
3832 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
3837 Result += SuperClass->getNameAsString();
3839 Result += CDecl->getNameAsString();
3843 Result += ", 0, \"";
3844 Result += CDecl->getNameAsString();
3847 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
3848 // 'info' field is initialized to CLS_META(2) for metaclass
3849 Result += ", 0,2, sizeof(struct _objc_class), 0";
3850 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
3851 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
3852 Result += IDecl->getNameAsString();
3857 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3858 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
3859 Result += CDecl->getNameAsString();
3863 Result += "\t,0,0,0,0\n";
3866 // class metadata generation.
3867 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3868 Result += CDecl->getNameAsString();
3869 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
3870 "{\n\t&_OBJC_METACLASS_";
3871 Result += CDecl->getNameAsString();
3874 Result += SuperClass->getNameAsString();
3876 Result += CDecl->getNameAsString();
3880 Result += ", 0, \"";
3881 Result += CDecl->getNameAsString();
3884 // 'info' field is initialized to CLS_CLASS(1) for class
3886 if (!ObjCSynthesizedStructs.count(CDecl))
3889 // class has size. Must synthesize its size.
3890 Result += ",sizeof(struct ";
3891 Result += CDecl->getNameAsString();
3892 if (LangOpts.Microsoft)
3897 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
3898 Result += CDecl->getNameAsString();
3903 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
3904 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
3905 Result += CDecl->getNameAsString();
3906 Result += ", 0\n\t";
3910 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3911 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
3912 Result += CDecl->getNameAsString();
3913 Result += ", 0,0\n";
3916 Result += ",0,0,0\n";
3920 /// RewriteImplementations - This routine rewrites all method implementations
3921 /// and emits meta-data.
3923 void RewriteObjC::RewriteImplementations() {
3924 int ClsDefCount = ClassImplementation.size();
3925 int CatDefCount = CategoryImplementation.size();
3927 // Rewrite implemented methods
3928 for (int i = 0; i < ClsDefCount; i++)
3929 RewriteImplementationDecl(ClassImplementation[i]);
3931 for (int i = 0; i < CatDefCount; i++)
3932 RewriteImplementationDecl(CategoryImplementation[i]);
3935 void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3936 int ClsDefCount = ClassImplementation.size();
3937 int CatDefCount = CategoryImplementation.size();
3939 // For each implemented class, write out all its meta data.
3940 for (int i = 0; i < ClsDefCount; i++)
3941 RewriteObjCClassMetaData(ClassImplementation[i], Result);
3943 // For each implemented category, write out all its meta data.
3944 for (int i = 0; i < CatDefCount; i++)
3945 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
3947 // Write objc_symtab metadata
3955 void *defs[cls_def_cnt + cat_def_cnt];
3959 Result += "\nstruct _objc_symtab {\n";
3960 Result += "\tlong sel_ref_cnt;\n";
3961 Result += "\tSEL *refs;\n";
3962 Result += "\tshort cls_def_cnt;\n";
3963 Result += "\tshort cat_def_cnt;\n";
3964 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3967 Result += "static struct _objc_symtab "
3968 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
3969 Result += "\t0, 0, " + utostr(ClsDefCount)
3970 + ", " + utostr(CatDefCount) + "\n";
3971 for (int i = 0; i < ClsDefCount; i++) {
3972 Result += "\t,&_OBJC_CLASS_";
3973 Result += ClassImplementation[i]->getNameAsString();
3977 for (int i = 0; i < CatDefCount; i++) {
3978 Result += "\t,&_OBJC_CATEGORY_";
3979 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
3981 Result += CategoryImplementation[i]->getNameAsString();
3987 // Write objc_module metadata
3990 struct _objc_module {
3994 struct _objc_symtab *symtab;
3998 Result += "\nstruct _objc_module {\n";
3999 Result += "\tlong version;\n";
4000 Result += "\tlong size;\n";
4001 Result += "\tconst char *name;\n";
4002 Result += "\tstruct _objc_symtab *symtab;\n";
4004 Result += "static struct _objc_module "
4005 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
4006 Result += "\t" + utostr(OBJC_ABI_VERSION) +
4007 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
4010 if (LangOpts.Microsoft) {
4011 if (ProtocolExprDecls.size()) {
4012 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4013 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
4014 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4015 E = ProtocolExprDecls.end(); I != E; ++I) {
4016 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4017 Result += (*I)->getNameAsString();
4018 Result += " = &_OBJC_PROTOCOL_";
4019 Result += (*I)->getNameAsString();
4022 Result += "#pragma data_seg(pop)\n\n";
4024 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
4025 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
4026 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4027 Result += "&_OBJC_MODULES;\n";
4028 Result += "#pragma data_seg(pop)\n\n";
4032 void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4033 const std::string &Name,
4035 assert(BlockByRefDeclNo.count(VD) &&
4036 "RewriteByRefString: ByRef decl missing");
4037 ResultStr += "struct __Block_byref_" + Name +
4038 "_" + utostr(BlockByRefDeclNo[VD]) ;
4041 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4042 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4043 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4047 std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4048 llvm::StringRef funcName,
4050 const FunctionType *AFT = CE->getFunctionType();
4051 QualType RT = AFT->getResultType();
4052 std::string StructRef = "struct " + Tag;
4053 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
4054 funcName.str() + "_" + "block_func_" + utostr(i);
4056 BlockDecl *BD = CE->getBlockDecl();
4058 if (isa<FunctionNoProtoType>(AFT)) {
4059 // No user-supplied arguments. Still need to pass in a pointer to the
4060 // block (to reference imported block decl refs).
4061 S += "(" + StructRef + " *__cself)";
4062 } else if (BD->param_empty()) {
4063 S += "(" + StructRef + " *__cself)";
4065 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4066 assert(FT && "SynthesizeBlockFunc: No function proto");
4068 // first add the implicit argument.
4069 S += StructRef + " *__cself, ";
4070 std::string ParamStr;
4071 for (BlockDecl::param_iterator AI = BD->param_begin(),
4072 E = BD->param_end(); AI != E; ++AI) {
4073 if (AI != BD->param_begin()) S += ", ";
4074 ParamStr = (*AI)->getNameAsString();
4075 QualType QT = (*AI)->getType();
4076 if (convertBlockPointerToFunctionPointer(QT))
4077 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
4079 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
4082 if (FT->isVariadic()) {
4083 if (!BD->param_empty()) S += ", ";
4090 // Create local declarations to avoid rewriting all closure decl ref exprs.
4091 // First, emit a declaration for all "by ref" decls.
4092 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4093 E = BlockByRefDecls.end(); I != E; ++I) {
4095 std::string Name = (*I)->getNameAsString();
4096 std::string TypeString;
4097 RewriteByRefString(TypeString, Name, (*I));
4099 Name = TypeString + Name;
4100 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4102 // Next, emit a declaration for all "by copy" declarations.
4103 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4104 E = BlockByCopyDecls.end(); I != E; ++I) {
4106 // Handle nested closure invocation. For example:
4108 // void (^myImportedClosure)(void);
4109 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4111 // void (^anotherClosure)(void);
4112 // anotherClosure = ^(void) {
4113 // myImportedClosure(); // import and invoke the closure
4116 if (isTopLevelBlockPointerType((*I)->getType())) {
4117 RewriteBlockPointerTypeVariable(S, (*I));
4119 RewriteBlockPointerType(S, (*I)->getType());
4121 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4124 std::string Name = (*I)->getNameAsString();
4125 QualType QT = (*I)->getType();
4126 if (HasLocalVariableExternalStorage(*I))
4127 QT = Context->getPointerType(QT);
4128 QT.getAsStringInternal(Name, Context->PrintingPolicy);
4129 S += Name + " = __cself->" +
4130 (*I)->getNameAsString() + "; // bound by copy\n";
4133 std::string RewrittenStr = RewrittenBlockExprs[CE];
4134 const char *cstr = RewrittenStr.c_str();
4135 while (*cstr++ != '{') ;
4141 std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4142 llvm::StringRef funcName,
4144 std::string StructRef = "struct " + Tag;
4145 std::string S = "static void __";
4148 S += "_block_copy_" + utostr(i);
4149 S += "(" + StructRef;
4150 S += "*dst, " + StructRef;
4152 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4153 E = ImportedBlockDecls.end(); I != E; ++I) {
4154 S += "_Block_object_assign((void*)&dst->";
4155 S += (*I)->getNameAsString();
4156 S += ", (void*)src->";
4157 S += (*I)->getNameAsString();
4158 if (BlockByRefDeclsPtrSet.count((*I)))
4159 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4161 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4165 S += "\nstatic void __";
4167 S += "_block_dispose_" + utostr(i);
4168 S += "(" + StructRef;
4170 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4171 E = ImportedBlockDecls.end(); I != E; ++I) {
4172 S += "_Block_object_dispose((void*)src->";
4173 S += (*I)->getNameAsString();
4174 if (BlockByRefDeclsPtrSet.count((*I)))
4175 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4177 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4183 std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4185 std::string S = "\nstruct " + Tag;
4186 std::string Constructor = " " + Tag;
4188 S += " {\n struct __block_impl impl;\n";
4189 S += " struct " + Desc;
4192 Constructor += "(void *fp, "; // Invoke function pointer.
4193 Constructor += "struct " + Desc; // Descriptor pointer.
4194 Constructor += " *desc";
4196 if (BlockDeclRefs.size()) {
4197 // Output all "by copy" declarations.
4198 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4199 E = BlockByCopyDecls.end(); I != E; ++I) {
4201 std::string FieldName = (*I)->getNameAsString();
4202 std::string ArgName = "_" + FieldName;
4203 // Handle nested closure invocation. For example:
4205 // void (^myImportedBlock)(void);
4206 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4208 // void (^anotherBlock)(void);
4209 // anotherBlock = ^(void) {
4210 // myImportedBlock(); // import and invoke the closure
4213 if (isTopLevelBlockPointerType((*I)->getType())) {
4214 S += "struct __block_impl *";
4215 Constructor += ", void *" + ArgName;
4217 QualType QT = (*I)->getType();
4218 if (HasLocalVariableExternalStorage(*I))
4219 QT = Context->getPointerType(QT);
4220 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4221 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
4222 Constructor += ", " + ArgName;
4224 S += FieldName + ";\n";
4226 // Output all "by ref" declarations.
4227 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4228 E = BlockByRefDecls.end(); I != E; ++I) {
4230 std::string FieldName = (*I)->getNameAsString();
4231 std::string ArgName = "_" + FieldName;
4232 // Handle nested closure invocation. For example:
4234 // void (^myImportedBlock)(void);
4235 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4237 // void (^anotherBlock)(void);
4238 // anotherBlock = ^(void) {
4239 // myImportedBlock(); // import and invoke the closure
4242 if (isTopLevelBlockPointerType((*I)->getType())) {
4243 S += "struct __block_impl *";
4244 Constructor += ", void *" + ArgName;
4246 std::string TypeString;
4247 RewriteByRefString(TypeString, FieldName, (*I));
4249 FieldName = TypeString + FieldName;
4250 ArgName = TypeString + ArgName;
4251 Constructor += ", " + ArgName;
4253 S += FieldName + "; // by ref\n";
4255 // Finish writing the constructor.
4256 Constructor += ", int flags=0)";
4257 // Initialize all "by copy" arguments.
4258 bool firsTime = true;
4259 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4260 E = BlockByCopyDecls.end(); I != E; ++I) {
4261 std::string Name = (*I)->getNameAsString();
4263 Constructor += " : ";
4267 Constructor += ", ";
4268 if (isTopLevelBlockPointerType((*I)->getType()))
4269 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4271 Constructor += Name + "(_" + Name + ")";
4273 // Initialize all "by ref" arguments.
4274 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4275 E = BlockByRefDecls.end(); I != E; ++I) {
4276 std::string Name = (*I)->getNameAsString();
4278 Constructor += " : ";
4282 Constructor += ", ";
4283 if (isTopLevelBlockPointerType((*I)->getType()))
4284 Constructor += Name + "((struct __block_impl *)_"
4285 + Name + "->__forwarding)";
4287 Constructor += Name + "(_" + Name + "->__forwarding)";
4290 Constructor += " {\n";
4292 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4294 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4295 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4297 Constructor += " Desc = desc;\n";
4299 // Finish writing the constructor.
4300 Constructor += ", int flags=0) {\n";
4302 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4304 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4305 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4306 Constructor += " Desc = desc;\n";
4309 Constructor += "}\n";
4315 std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4316 std::string ImplTag, int i,
4317 llvm::StringRef FunName,
4319 std::string S = "\nstatic struct " + DescTag;
4321 S += " {\n unsigned long reserved;\n";
4322 S += " unsigned long Block_size;\n";
4324 S += " void (*copy)(struct ";
4325 S += ImplTag; S += "*, struct ";
4326 S += ImplTag; S += "*);\n";
4328 S += " void (*dispose)(struct ";
4329 S += ImplTag; S += "*);\n";
4333 S += DescTag + "_DATA = { 0, sizeof(struct ";
4336 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4337 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4343 void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4344 llvm::StringRef FunName) {
4345 // Insert declaration for the function in which block literal is used.
4346 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4347 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4348 bool RewriteSC = (GlobalVarDecl &&
4350 GlobalVarDecl->getStorageClass() == SC_Static &&
4351 GlobalVarDecl->getType().getCVRQualifiers());
4353 std::string SC(" void __");
4354 SC += GlobalVarDecl->getNameAsString();
4356 InsertText(FunLocStart, SC);
4359 // Insert closures that were part of the function.
4360 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4361 CollectBlockDeclRefInfo(Blocks[i]);
4362 // Need to copy-in the inner copied-in variables not actually used in this
4364 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4365 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4366 ValueDecl *VD = Exp->getDecl();
4367 BlockDeclRefs.push_back(Exp);
4368 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4369 BlockByCopyDeclsPtrSet.insert(VD);
4370 BlockByCopyDecls.push_back(VD);
4372 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4373 BlockByRefDeclsPtrSet.insert(VD);
4374 BlockByRefDecls.push_back(VD);
4378 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4379 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4381 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4383 InsertText(FunLocStart, CI);
4385 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4387 InsertText(FunLocStart, CF);
4389 if (ImportedBlockDecls.size()) {
4390 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4391 InsertText(FunLocStart, HF);
4393 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4394 ImportedBlockDecls.size() > 0);
4395 InsertText(FunLocStart, BD);
4397 BlockDeclRefs.clear();
4398 BlockByRefDecls.clear();
4399 BlockByRefDeclsPtrSet.clear();
4400 BlockByCopyDecls.clear();
4401 BlockByCopyDeclsPtrSet.clear();
4402 ImportedBlockDecls.clear();
4405 // Must insert any 'const/volatile/static here. Since it has been
4406 // removed as result of rewriting of block literals.
4408 if (GlobalVarDecl->getStorageClass() == SC_Static)
4410 if (GlobalVarDecl->getType().isConstQualified())
4412 if (GlobalVarDecl->getType().isVolatileQualified())
4414 if (GlobalVarDecl->getType().isRestrictQualified())
4416 InsertText(FunLocStart, SC);
4420 InnerDeclRefsCount.clear();
4421 InnerDeclRefs.clear();
4422 RewrittenBlockExprs.clear();
4425 void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4426 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
4427 llvm::StringRef FuncName = FD->getName();
4429 SynthesizeBlockLiterals(FunLocStart, FuncName);
4432 static void BuildUniqueMethodName(std::string &Name,
4433 ObjCMethodDecl *MD) {
4434 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4435 Name = IFace->getName();
4436 Name += "__" + MD->getSelector().getAsString();
4437 // Convert colons to underscores.
4438 std::string::size_type loc = 0;
4439 while ((loc = Name.find(":", loc)) != std::string::npos)
4440 Name.replace(loc, 1, "_");
4443 void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4444 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4445 //SourceLocation FunLocStart = MD->getLocStart();
4446 SourceLocation FunLocStart = MD->getLocStart();
4447 std::string FuncName;
4448 BuildUniqueMethodName(FuncName, MD);
4449 SynthesizeBlockLiterals(FunLocStart, FuncName);
4452 void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4453 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4456 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4457 GetBlockDeclRefExprs(CBE->getBody());
4459 GetBlockDeclRefExprs(*CI);
4461 // Handle specific things.
4462 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4463 // FIXME: Handle enums.
4464 if (!isa<FunctionDecl>(CDRE->getDecl()))
4465 BlockDeclRefs.push_back(CDRE);
4467 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4468 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4469 BlockDeclRefExpr *BDRE =
4470 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4471 DRE->getLocation(), false);
4472 BlockDeclRefs.push_back(BDRE);
4478 void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4479 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
4480 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4481 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4484 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4485 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4486 GetInnerBlockDeclRefExprs(CBE->getBody(),
4491 GetInnerBlockDeclRefExprs(*CI,
4496 // Handle specific things.
4497 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4498 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
4499 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
4500 InnerBlockDeclRefs.push_back(CDRE);
4502 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4503 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4504 if (Var->isFunctionOrMethodVarDecl())
4505 ImportedLocalExternalDecls.insert(Var);
4511 /// convertFunctionTypeOfBlocks - This routine converts a function type
4512 /// whose result type may be a block pointer or whose argument type(s)
4513 /// might be block pointers to an equivalent funtion type replacing
4514 /// all block pointers to function pointers.
4515 QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4516 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4517 // FTP will be null for closures that don't take arguments.
4518 // Generate a funky cast.
4519 llvm::SmallVector<QualType, 8> ArgTypes;
4520 QualType Res = FT->getResultType();
4521 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
4524 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4525 E = FTP->arg_type_end(); I && (I != E); ++I) {
4527 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4528 if (convertBlockPointerToFunctionPointer(t))
4529 HasBlockType = true;
4530 ArgTypes.push_back(t);
4534 // FIXME. Does this work if block takes no argument but has a return type
4535 // which is of block type?
4537 FuncType = Context->getFunctionType(Res,
4538 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4539 false, false, 0, 0, FunctionType::ExtInfo());
4540 else FuncType = QualType(FT, 0);
4544 Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4545 // Navigate to relevant type information.
4546 const BlockPointerType *CPT = 0;
4548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4549 CPT = DRE->getType()->getAs<BlockPointerType>();
4550 } else if (const BlockDeclRefExpr *CDRE =
4551 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
4552 CPT = CDRE->getType()->getAs<BlockPointerType>();
4553 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4554 CPT = MExpr->getType()->getAs<BlockPointerType>();
4556 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4557 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4559 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4560 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4561 else if (const ConditionalOperator *CEXPR =
4562 dyn_cast<ConditionalOperator>(BlockExp)) {
4563 Expr *LHSExp = CEXPR->getLHS();
4564 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4565 Expr *RHSExp = CEXPR->getRHS();
4566 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4567 Expr *CONDExp = CEXPR->getCond();
4568 ConditionalOperator *CondExpr =
4569 new (Context) ConditionalOperator(CONDExp,
4570 SourceLocation(), cast<Expr>(LHSStmt),
4571 SourceLocation(), cast<Expr>(RHSStmt),
4575 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4576 CPT = IRE->getType()->getAs<BlockPointerType>();
4578 assert(1 && "RewriteBlockClass: Bad type");
4580 assert(CPT && "RewriteBlockClass: Bad type");
4581 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4582 assert(FT && "RewriteBlockClass: Bad type");
4583 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4584 // FTP will be null for closures that don't take arguments.
4586 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4588 &Context->Idents.get("__block_impl"));
4589 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4591 // Generate a funky cast.
4592 llvm::SmallVector<QualType, 8> ArgTypes;
4594 // Push the block argument type.
4595 ArgTypes.push_back(PtrBlock);
4597 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4598 E = FTP->arg_type_end(); I && (I != E); ++I) {
4600 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4601 (void)convertBlockPointerToFunctionPointer(t);
4602 ArgTypes.push_back(t);
4605 // Now do the pointer to function cast.
4606 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
4607 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4609 FunctionType::ExtInfo());
4611 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4613 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4615 const_cast<Expr*>(BlockExp));
4616 // Don't forget the parens to enforce the proper binding.
4617 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4621 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4622 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
4623 /*BitWidth=*/0, /*Mutable=*/true);
4624 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4627 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4629 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4631 llvm::SmallVector<Expr*, 8> BlkExprs;
4632 // Add the implicit argument.
4633 BlkExprs.push_back(BlkCast);
4634 // Add the user arguments.
4635 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4636 E = Exp->arg_end(); I != E; ++I) {
4637 BlkExprs.push_back(*I);
4639 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4641 Exp->getType(), SourceLocation());
4645 // We need to return the rewritten expression to handle cases where the
4646 // BlockDeclRefExpr is embedded in another expression being rewritten.
4653 // void (^myblock)() = ^() {
4654 // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4658 Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
4659 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4660 // for each DeclRefExp where BYREFVAR is name of the variable.
4662 bool isArrow = true;
4663 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4664 VD = BDRE->getDecl();
4666 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4670 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4671 &Context->Idents.get("__forwarding"),
4672 Context->VoidPtrTy, 0,
4673 /*BitWidth=*/0, /*Mutable=*/true);
4674 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4675 FD, SourceLocation(),
4678 llvm::StringRef Name = VD->getName();
4679 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4680 &Context->Idents.get(Name),
4681 Context->VoidPtrTy, 0,
4682 /*BitWidth=*/0, /*Mutable=*/true);
4683 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4684 DeclRefExp->getType());
4688 // Need parens to enforce precedence.
4689 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4691 ReplaceStmt(DeclRefExp, PE);
4695 // Rewrites the imported local variable V with external storage
4696 // (static, extern, etc.) as *V
4698 Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4699 ValueDecl *VD = DRE->getDecl();
4700 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4701 if (!ImportedLocalExternalDecls.count(Var))
4703 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
4704 DRE->getType(), DRE->getLocation());
4705 // Need parens to enforce precedence.
4706 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4708 ReplaceStmt(DRE, PE);
4712 void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4713 SourceLocation LocStart = CE->getLParenLoc();
4714 SourceLocation LocEnd = CE->getRParenLoc();
4716 // Need to avoid trying to rewrite synthesized casts.
4717 if (LocStart.isInvalid())
4719 // Need to avoid trying to rewrite casts contained in macros.
4720 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4723 const char *startBuf = SM->getCharacterData(LocStart);
4724 const char *endBuf = SM->getCharacterData(LocEnd);
4725 QualType QT = CE->getType();
4726 const Type* TypePtr = QT->getAs<Type>();
4727 if (isa<TypeOfExprType>(TypePtr)) {
4728 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4729 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4730 std::string TypeAsString = "(";
4731 RewriteBlockPointerType(TypeAsString, QT);
4732 TypeAsString += ")";
4733 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4736 // advance the location to startArgList.
4737 const char *argPtr = startBuf;
4739 while (*argPtr++ && (argPtr < endBuf)) {
4742 // Replace the '^' with '*'.
4743 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4744 ReplaceText(LocStart, 1, "*");
4751 void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4752 SourceLocation DeclLoc = FD->getLocation();
4753 unsigned parenCount = 0;
4755 // We have 1 or more arguments that have closure pointers.
4756 const char *startBuf = SM->getCharacterData(DeclLoc);
4757 const char *startArgList = strchr(startBuf, '(');
4759 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4762 // advance the location to startArgList.
4763 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4764 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4766 const char *argPtr = startArgList;
4768 while (*argPtr++ && parenCount) {
4771 // Replace the '^' with '*'.
4772 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4773 ReplaceText(DeclLoc, 1, "*");
4786 bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4787 const FunctionProtoType *FTP;
4788 const PointerType *PT = QT->getAs<PointerType>();
4790 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4792 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4793 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4794 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4797 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4798 E = FTP->arg_type_end(); I != E; ++I)
4799 if (isTopLevelBlockPointerType(*I))
4805 void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4806 const char *&RParen) {
4807 const char *argPtr = strchr(Name, '(');
4808 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4810 LParen = argPtr; // output the start.
4811 argPtr++; // skip past the left paren.
4812 unsigned parenCount = 1;
4814 while (*argPtr && parenCount) {
4816 case '(': parenCount++; break;
4817 case ')': parenCount--; break;
4820 if (parenCount) argPtr++;
4822 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4823 RParen = argPtr; // output the end
4826 void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4827 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4828 RewriteBlockPointerFunctionArgs(FD);
4831 // Handle Variables and Typedefs.
4832 SourceLocation DeclLoc = ND->getLocation();
4834 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4835 DeclT = VD->getType();
4836 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4837 DeclT = TDD->getUnderlyingType();
4838 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4839 DeclT = FD->getType();
4841 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4843 const char *startBuf = SM->getCharacterData(DeclLoc);
4844 const char *endBuf = startBuf;
4845 // scan backward (from the decl location) for the end of the previous decl.
4846 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4849 // *startBuf != '^' if we are dealing with a pointer to function that
4850 // may take block argument types (which will be handled below).
4851 if (*startBuf == '^') {
4852 // Replace the '^' with '*', computing a negative offset.
4853 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4854 ReplaceText(DeclLoc, 1, "*");
4856 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4857 // Replace the '^' with '*' for arguments.
4858 DeclLoc = ND->getLocation();
4859 startBuf = SM->getCharacterData(DeclLoc);
4860 const char *argListBegin, *argListEnd;
4861 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4862 while (argListBegin < argListEnd) {
4863 if (*argListBegin == '^') {
4864 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4865 ReplaceText(CaretLoc, 1, "*");
4874 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4875 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4876 /// struct Block_byref_id_object *src) {
4877 /// _Block_object_assign (&_dest->object, _src->object,
4878 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4879 /// [|BLOCK_FIELD_IS_WEAK]) // object
4880 /// _Block_object_assign(&_dest->object, _src->object,
4881 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4882 /// [|BLOCK_FIELD_IS_WEAK]) // block
4885 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4886 /// _Block_object_dispose(_src->object,
4887 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4888 /// [|BLOCK_FIELD_IS_WEAK]) // object
4889 /// _Block_object_dispose(_src->object,
4890 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4891 /// [|BLOCK_FIELD_IS_WEAK]) // block
4894 std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4897 if (CopyDestroyCache.count(flag))
4899 CopyDestroyCache.insert(flag);
4900 S = "static void __Block_byref_id_object_copy_";
4902 S += "(void *dst, void *src) {\n";
4904 // offset into the object pointer is computed as:
4905 // void * + void* + int + int + void* + void *
4907 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4908 unsigned VoidPtrSize =
4909 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4911 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4912 S += " _Block_object_assign((char*)dst + ";
4913 S += utostr(offset);
4914 S += ", *(void * *) ((char*)src + ";
4915 S += utostr(offset);
4920 S += "static void __Block_byref_id_object_dispose_";
4922 S += "(void *src) {\n";
4923 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4924 S += utostr(offset);
4931 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4932 /// the declaration into:
4933 /// struct __Block_byref_ND {
4934 /// void *__isa; // NULL for everything except __weak pointers
4935 /// struct __Block_byref_ND *__forwarding;
4936 /// int32_t __flags;
4938 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4939 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4943 /// It then replaces declaration of ND variable with:
4944 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4945 /// __size=sizeof(struct __Block_byref_ND),
4946 /// ND=initializer-if-any};
4949 void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4950 // Insert declaration for the function in which block literal is
4952 if (CurFunctionDeclToDeclareForBlock)
4953 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4956 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4957 if (DeclLoc.isInvalid())
4958 // If type location is missing, it is because of missing type (a warning).
4959 // Use variable's location which is good for this case.
4960 DeclLoc = ND->getLocation();
4961 const char *startBuf = SM->getCharacterData(DeclLoc);
4962 SourceLocation X = ND->getLocEnd();
4963 X = SM->getInstantiationLoc(X);
4964 const char *endBuf = SM->getCharacterData(X);
4965 std::string Name(ND->getNameAsString());
4966 std::string ByrefType;
4967 RewriteByRefString(ByrefType, Name, ND);
4968 ByrefType += " {\n";
4969 ByrefType += " void *__isa;\n";
4970 RewriteByRefString(ByrefType, Name, ND);
4971 ByrefType += " *__forwarding;\n";
4972 ByrefType += " int __flags;\n";
4973 ByrefType += " int __size;\n";
4974 // Add void *__Block_byref_id_object_copy;
4975 // void *__Block_byref_id_object_dispose; if needed.
4976 QualType Ty = ND->getType();
4977 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4978 if (HasCopyAndDispose) {
4979 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4980 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4983 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
4984 ByrefType += " " + Name + ";\n";
4985 ByrefType += "};\n";
4986 // Insert this type in global scope. It is needed by helper function.
4987 SourceLocation FunLocStart;
4989 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4991 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4992 FunLocStart = CurMethodDef->getLocStart();
4994 InsertText(FunLocStart, ByrefType);
4995 if (Ty.isObjCGCWeak()) {
4996 flag |= BLOCK_FIELD_IS_WEAK;
5000 if (HasCopyAndDispose) {
5001 flag = BLOCK_BYREF_CALLER;
5002 QualType Ty = ND->getType();
5003 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5004 if (Ty->isBlockPointerType())
5005 flag |= BLOCK_FIELD_IS_BLOCK;
5007 flag |= BLOCK_FIELD_IS_OBJECT;
5008 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5010 InsertText(FunLocStart, HF);
5013 // struct __Block_byref_ND ND =
5014 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5015 // initializer-if-any};
5016 bool hasInit = (ND->getInit() != 0);
5018 if (HasCopyAndDispose)
5019 flags |= BLOCK_HAS_COPY_DISPOSE;
5020 Name = ND->getNameAsString();
5022 RewriteByRefString(ByrefType, Name, ND);
5023 std::string ForwardingCastType("(");
5024 ForwardingCastType += ByrefType + " *)";
5026 ByrefType += " " + Name + " = {(void*)";
5027 ByrefType += utostr(isa);
5028 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5029 ByrefType += utostr(flags);
5031 ByrefType += "sizeof(";
5032 RewriteByRefString(ByrefType, Name, ND);
5034 if (HasCopyAndDispose) {
5035 ByrefType += ", __Block_byref_id_object_copy_";
5036 ByrefType += utostr(flag);
5037 ByrefType += ", __Block_byref_id_object_dispose_";
5038 ByrefType += utostr(flag);
5040 ByrefType += "};\n";
5041 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
5044 SourceLocation startLoc;
5045 Expr *E = ND->getInit();
5046 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5047 startLoc = ECE->getLParenLoc();
5049 startLoc = E->getLocStart();
5050 startLoc = SM->getInstantiationLoc(startLoc);
5051 endBuf = SM->getCharacterData(startLoc);
5052 ByrefType += " " + Name;
5053 ByrefType += " = {(void*)";
5054 ByrefType += utostr(isa);
5055 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5056 ByrefType += utostr(flags);
5058 ByrefType += "sizeof(";
5059 RewriteByRefString(ByrefType, Name, ND);
5061 if (HasCopyAndDispose) {
5062 ByrefType += "__Block_byref_id_object_copy_";
5063 ByrefType += utostr(flag);
5064 ByrefType += ", __Block_byref_id_object_dispose_";
5065 ByrefType += utostr(flag);
5068 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5070 // Complete the newly synthesized compound expression by inserting a right
5071 // curly brace before the end of the declaration.
5072 // FIXME: This approach avoids rewriting the initializer expression. It
5073 // also assumes there is only one declarator. For example, the following
5074 // isn't currently supported by this routine (in general):
5076 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5078 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5079 const char *semiBuf = strchr(startInitializerBuf, ';');
5080 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5081 SourceLocation semiLoc =
5082 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
5084 InsertText(semiLoc, "}");
5089 void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5090 // Add initializers for any closure decl refs.
5091 GetBlockDeclRefExprs(Exp->getBody());
5092 if (BlockDeclRefs.size()) {
5093 // Unique all "by copy" declarations.
5094 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5095 if (!BlockDeclRefs[i]->isByRef()) {
5096 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5097 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5098 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5101 // Unique all "by ref" declarations.
5102 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5103 if (BlockDeclRefs[i]->isByRef()) {
5104 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5105 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5106 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5109 // Find any imported blocks...they will need special attention.
5110 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5111 if (BlockDeclRefs[i]->isByRef() ||
5112 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5113 BlockDeclRefs[i]->getType()->isBlockPointerType())
5114 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5118 FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
5119 IdentifierInfo *ID = &Context->Idents.get(name);
5120 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5121 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
5122 ID, FType, 0, SC_Extern,
5123 SC_None, false, false);
5126 Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5127 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
5128 Blocks.push_back(Exp);
5130 CollectBlockDeclRefInfo(Exp);
5132 // Add inner imported variables now used in current block.
5133 int countOfInnerDecls = 0;
5134 if (!InnerBlockDeclRefs.empty()) {
5135 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5136 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5137 ValueDecl *VD = Exp->getDecl();
5138 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
5139 // We need to save the copied-in variables in nested
5140 // blocks because it is needed at the end for some of the API generations.
5141 // See SynthesizeBlockLiterals routine.
5142 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5143 BlockDeclRefs.push_back(Exp);
5144 BlockByCopyDeclsPtrSet.insert(VD);
5145 BlockByCopyDecls.push_back(VD);
5147 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5148 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5149 BlockDeclRefs.push_back(Exp);
5150 BlockByRefDeclsPtrSet.insert(VD);
5151 BlockByRefDecls.push_back(VD);
5154 // Find any imported blocks...they will need special attention.
5155 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5156 if (InnerBlockDeclRefs[i]->isByRef() ||
5157 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5158 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5159 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5161 InnerDeclRefsCount.push_back(countOfInnerDecls);
5163 std::string FuncName;
5166 FuncName = CurFunctionDef->getNameAsString();
5167 else if (CurMethodDef)
5168 BuildUniqueMethodName(FuncName, CurMethodDef);
5169 else if (GlobalVarDecl)
5170 FuncName = std::string(GlobalVarDecl->getNameAsString());
5172 std::string BlockNumber = utostr(Blocks.size()-1);
5174 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5175 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5177 // Get a pointer to the function type so we can cast appropriately.
5178 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5179 QualType FType = Context->getPointerType(BFT);
5184 // Simulate a contructor call...
5185 FD = SynthBlockInitFunctionDecl(Tag);
5186 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
5188 llvm::SmallVector<Expr*, 4> InitExprs;
5190 // Initialize the block function.
5191 FD = SynthBlockInitFunctionDecl(Func);
5192 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5194 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5196 InitExprs.push_back(castExpr);
5198 // Initialize the block descriptor.
5199 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5201 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5202 &Context->Idents.get(DescData.c_str()),
5203 Context->VoidPtrTy, 0,
5204 SC_Static, SC_None);
5205 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5206 new (Context) DeclRefExpr(NewVD,
5207 Context->VoidPtrTy, SourceLocation()),
5209 Context->getPointerType(Context->VoidPtrTy),
5211 InitExprs.push_back(DescRefExpr);
5213 // Add initializers for any closure decl refs.
5214 if (BlockDeclRefs.size()) {
5216 // Output all "by copy" declarations.
5217 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5218 E = BlockByCopyDecls.end(); I != E; ++I) {
5219 if (isObjCType((*I)->getType())) {
5220 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5221 FD = SynthBlockInitFunctionDecl((*I)->getName());
5222 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5223 if (HasLocalVariableExternalStorage(*I)) {
5224 QualType QT = (*I)->getType();
5225 QT = Context->getPointerType(QT);
5226 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
5229 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5230 FD = SynthBlockInitFunctionDecl((*I)->getName());
5231 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5232 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5235 FD = SynthBlockInitFunctionDecl((*I)->getName());
5236 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5237 if (HasLocalVariableExternalStorage(*I)) {
5238 QualType QT = (*I)->getType();
5239 QT = Context->getPointerType(QT);
5240 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
5245 InitExprs.push_back(Exp);
5247 // Output all "by ref" declarations.
5248 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5249 E = BlockByRefDecls.end(); I != E; ++I) {
5250 ValueDecl *ND = (*I);
5251 std::string Name(ND->getNameAsString());
5252 std::string RecName;
5253 RewriteByRefString(RecName, Name, ND);
5254 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5255 + sizeof("struct"));
5256 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5257 SourceLocation(), II);
5258 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5259 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5261 FD = SynthBlockInitFunctionDecl((*I)->getName());
5262 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5263 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5264 Context->getPointerType(Exp->getType()),
5266 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
5267 InitExprs.push_back(Exp);
5270 if (ImportedBlockDecls.size()) {
5271 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5272 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5274 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5275 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5276 Context->IntTy, SourceLocation());
5277 InitExprs.push_back(FlagExp);
5279 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5280 FType, SourceLocation());
5281 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5282 Context->getPointerType(NewRep->getType()),
5284 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
5286 BlockDeclRefs.clear();
5287 BlockByRefDecls.clear();
5288 BlockByRefDeclsPtrSet.clear();
5289 BlockByCopyDecls.clear();
5290 BlockByCopyDeclsPtrSet.clear();
5291 ImportedBlockDecls.clear();
5295 //===----------------------------------------------------------------------===//
5296 // Function Body / Expression rewriting
5297 //===----------------------------------------------------------------------===//
5299 // This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5300 // The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5301 // their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5302 // the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5303 // Since the rewriter isn't capable of rewriting rewritten code, it's important
5304 // we get this right.
5305 void RewriteObjC::CollectPropertySetters(Stmt *S) {
5306 // Perform a bottom up traversal of all children.
5307 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5310 CollectPropertySetters(*CI);
5312 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5313 if (BinOp->isAssignmentOp()) {
5314 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5315 PropSetters[PRE] = BinOp;
5320 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5321 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5322 isa<DoStmt>(S) || isa<ForStmt>(S))
5324 else if (isa<ObjCForCollectionStmt>(S)) {
5326 ObjCBcLabelNo.push_back(++BcLabelCount);
5329 SourceRange OrigStmtRange = S->getSourceRange();
5331 // Perform a bottom up rewrite of all children.
5332 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5337 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5338 Expr *OldBase = IvarRefExpr->getBase();
5339 bool replaced = false;
5340 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5342 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5343 ReplaceStmt(OldBase, IRE->getBase());
5345 ReplaceStmt(S, newStmt);
5349 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
5354 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5355 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
5356 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5357 InnerContexts.insert(BE->getBlockDecl());
5358 ImportedLocalExternalDecls.clear();
5359 GetInnerBlockDeclRefExprs(BE->getBody(),
5360 InnerBlockDeclRefs, InnerContexts);
5361 // Rewrite the block body in place.
5362 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5363 ImportedLocalExternalDecls.clear();
5364 // Now we snarf the rewritten text and stash it away for later use.
5365 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5366 RewrittenBlockExprs[BE] = Str;
5368 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5370 //blockTranscribed->dump();
5371 ReplaceStmt(S, blockTranscribed);
5372 return blockTranscribed;
5374 // Handle specific things.
5375 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5376 return RewriteAtEncode(AtEncode);
5378 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5379 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5381 // Because the rewriter doesn't allow us to rewrite rewritten code,
5382 // we need to rewrite the right hand side prior to rewriting the setter.
5383 DisableReplaceStmt = true;
5384 // Save the source range. Even if we disable the replacement, the
5385 // rewritten node will have been inserted into the tree. If the synthesized
5386 // node is at the 'end', the rewriter will fail. Consider this:
5387 // self.errorHandler = handler ? handler :
5388 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5389 SourceRange SrcRange = BinOp->getSourceRange();
5390 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
5391 DisableReplaceStmt = false;
5393 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5394 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5395 // to see the original expression). Consider this example:
5397 // Foo *obj1, *obj2;
5399 // obj1.i = [obj2 rrrr];
5401 // 'BinOp' for the previous expression looks like:
5403 // (BinaryOperator 0x231ccf0 'int' '='
5404 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5405 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5406 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5407 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5409 // 'newStmt' represents the rewritten message expression. For example:
5411 // (CallExpr 0x231d300 'id':'struct objc_object *'
5412 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5413 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5414 // (CStyleCastExpr 0x231d220 'void *'
5415 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5417 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5418 // can be used as the setter argument. ReplaceStmt() will still 'see'
5419 // the original RHS (since we haven't altered BinOp).
5421 // This implies the Rewrite* routines can no longer delete the original
5422 // node. As a result, we now leak the original AST nodes.
5424 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
5426 return RewritePropertyGetter(PropRefExpr);
5429 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5430 return RewriteAtSelector(AtSelector);
5432 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5433 return RewriteObjCStringLiteral(AtString);
5435 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5437 // Before we rewrite it, put the original message expression in a comment.
5438 SourceLocation startLoc = MessExpr->getLocStart();
5439 SourceLocation endLoc = MessExpr->getLocEnd();
5441 const char *startBuf = SM->getCharacterData(startLoc);
5442 const char *endBuf = SM->getCharacterData(endLoc);
5444 std::string messString;
5445 messString += "// ";
5446 messString.append(startBuf, endBuf-startBuf+1);
5449 // FIXME: Missing definition of
5450 // InsertText(clang::SourceLocation, char const*, unsigned int).
5451 // InsertText(startLoc, messString.c_str(), messString.size());
5452 // Tried this, but it didn't work either...
5453 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5455 return RewriteMessageExpr(MessExpr);
5458 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5459 return RewriteObjCTryStmt(StmtTry);
5461 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5462 return RewriteObjCSynchronizedStmt(StmtTry);
5464 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5465 return RewriteObjCThrowStmt(StmtThrow);
5467 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5468 return RewriteObjCProtocolExpr(ProtocolExp);
5470 if (ObjCForCollectionStmt *StmtForCollection =
5471 dyn_cast<ObjCForCollectionStmt>(S))
5472 return RewriteObjCForCollectionStmt(StmtForCollection,
5473 OrigStmtRange.getEnd());
5474 if (BreakStmt *StmtBreakStmt =
5475 dyn_cast<BreakStmt>(S))
5476 return RewriteBreakStmt(StmtBreakStmt);
5477 if (ContinueStmt *StmtContinueStmt =
5478 dyn_cast<ContinueStmt>(S))
5479 return RewriteContinueStmt(StmtContinueStmt);
5481 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5483 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5484 // FIXME: What we're doing here is modifying the type-specifier that
5485 // precedes the first Decl. In the future the DeclGroup should have
5486 // a separate type-specifier that we can rewrite.
5487 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5488 // the context of an ObjCForCollectionStmt. For example:
5489 // NSArray *someArray;
5490 // for (id <FooProtocol> index in someArray) ;
5491 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5492 // and it depends on the original text locations/positions.
5493 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
5494 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5496 // Blocks rewrite rules.
5497 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5500 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5501 if (isTopLevelBlockPointerType(ND->getType()))
5502 RewriteBlockPointerDecl(ND);
5503 else if (ND->getType()->isFunctionPointerType())
5504 CheckFunctionPointerDecl(ND->getType(), ND);
5505 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5506 if (VD->hasAttr<BlocksAttr>()) {
5507 static unsigned uniqueByrefDeclCount = 0;
5508 assert(!BlockByRefDeclNo.count(ND) &&
5509 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5510 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5511 RewriteByRefVar(VD);
5514 RewriteTypeOfDecl(VD);
5517 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
5518 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5519 RewriteBlockPointerDecl(TD);
5520 else if (TD->getUnderlyingType()->isFunctionPointerType())
5521 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5526 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5527 RewriteObjCQualifiedInterfaceTypes(CE);
5529 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5530 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5531 assert(!Stmts.empty() && "Statement stack is empty");
5532 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5533 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5534 && "Statement stack mismatch");
5537 // Handle blocks rewriting.
5538 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5539 if (BDRE->isByRef())
5540 return RewriteBlockDeclRefExpr(BDRE);
5542 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5543 ValueDecl *VD = DRE->getDecl();
5544 if (VD->hasAttr<BlocksAttr>())
5545 return RewriteBlockDeclRefExpr(DRE);
5546 if (HasLocalVariableExternalStorage(VD))
5547 return RewriteLocalVariableExternalStorage(DRE);
5550 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5551 if (CE->getCallee()->getType()->isBlockPointerType()) {
5552 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5553 ReplaceStmt(S, BlockCall);
5557 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5558 RewriteCastExpr(CE);
5561 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5562 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5565 // Get the new text.
5567 llvm::raw_string_ostream Buf(SStr);
5568 Replacement->printPretty(Buf, *Context);
5569 const std::string &Str = Buf.str();
5571 printf("CAST = %s\n", &Str[0]);
5572 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5577 // Return this stmt unmodified.
5581 void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5582 for (RecordDecl::field_iterator i = RD->field_begin(),
5583 e = RD->field_end(); i != e; ++i) {
5585 if (isTopLevelBlockPointerType(FD->getType()))
5586 RewriteBlockPointerDecl(FD);
5587 if (FD->getType()->isObjCQualifiedIdType() ||
5588 FD->getType()->isObjCQualifiedInterfaceType())
5589 RewriteObjCQualifiedInterfaceTypes(FD);
5593 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5594 /// main file of the input.
5595 void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5596 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5597 if (FD->isOverloadedOperator())
5600 // Since function prototypes don't have ParmDecl's, we check the function
5601 // prototype. This enables us to rewrite function declarations and
5602 // definitions using the same code.
5603 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5605 // FIXME: If this should support Obj-C++, support CXXTryStmt
5606 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5607 CurFunctionDef = FD;
5608 CurFunctionDeclToDeclareForBlock = FD;
5609 CollectPropertySetters(Body);
5612 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5615 if (PropParentMap) {
5616 delete PropParentMap;
5619 // This synthesizes and inserts the block "impl" struct, invoke function,
5620 // and any copy/dispose helper functions.
5621 InsertBlockLiteralsWithinFunction(FD);
5623 CurFunctionDeclToDeclareForBlock = 0;
5627 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
5628 if (CompoundStmt *Body = MD->getCompoundBody()) {
5630 CollectPropertySetters(Body);
5633 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5636 if (PropParentMap) {
5637 delete PropParentMap;
5640 InsertBlockLiteralsWithinMethod(MD);
5644 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5645 ClassImplementation.push_back(CI);
5646 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5647 CategoryImplementation.push_back(CI);
5648 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5649 RewriteForwardClassDecl(CD);
5650 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5651 RewriteObjCQualifiedInterfaceTypes(VD);
5652 if (isTopLevelBlockPointerType(VD->getType()))
5653 RewriteBlockPointerDecl(VD);
5654 else if (VD->getType()->isFunctionPointerType()) {
5655 CheckFunctionPointerDecl(VD->getType(), VD);
5656 if (VD->getInit()) {
5657 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5658 RewriteCastExpr(CE);
5661 } else if (VD->getType()->isRecordType()) {
5662 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5663 if (RD->isDefinition())
5664 RewriteRecordBody(RD);
5666 if (VD->getInit()) {
5668 CollectPropertySetters(VD->getInit());
5669 CurrentBody = VD->getInit();
5670 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5672 if (PropParentMap) {
5673 delete PropParentMap;
5676 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
5680 // This is needed for blocks.
5681 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5682 RewriteCastExpr(CE);
5687 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
5688 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5689 RewriteBlockPointerDecl(TD);
5690 else if (TD->getUnderlyingType()->isFunctionPointerType())
5691 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5694 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
5695 if (RD->isDefinition())
5696 RewriteRecordBody(RD);
5702 void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
5703 if (Diags.hasErrorOccurred())
5708 // Here's a great place to add any extra declarations that may be needed.
5709 // Write out meta data for each @protocol(<expr>).
5710 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5711 E = ProtocolExprDecls.end(); I != E; ++I)
5712 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5714 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5715 if (ClassImplementation.size() || CategoryImplementation.size())
5716 RewriteImplementations();
5718 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5720 if (const RewriteBuffer *RewriteBuf =
5721 Rewrite.getRewriteBufferFor(MainFileID)) {
5722 //printf("Changed:\n");
5723 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5725 llvm::errs() << "No changes\n";
5728 if (ClassImplementation.size() || CategoryImplementation.size() ||
5729 ProtocolExprDecls.size()) {
5730 // Rewrite Objective-c meta data*
5731 std::string ResultStr;
5732 SynthesizeMetaDataIntoBuffer(ResultStr);
5734 *OutFile << ResultStr;